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 |
|---|---|---|---|---|---|
Set::Relation Changes --------------------------------------------------------------------------- 2015-01-01 * Set::Relation version 0.13.0 for Perl 5 is released on CPAN as Set-Relation-0.13.0.tar.gz. * The main purpose of this release is making Set::Relation substantially lighter in its external dependencies, so that it can be installed and used with a relative minimum of overhead. This release focuses on the low hanging fruit in that regard, namely the elimination of the Moose and namespace::autoclean dependencies, which are very large trees and didn't really bring much to the table. As of this release, each of the 2 Set::Relation classes require only the Perl core or core modules to run, plus just the 1 CPAN module List::MoreUtils. If you already have List::MoreUtils installed, you can use either V1 or V2 as simply as copying the respective single file into a Perl lib dir. If there is a user desire, the used functionality of List::MoreUtils could be inlined as well, thus making Set::Relation only require core. * This distribution has excised its direct external dependencies on the modules Moose, Moose::Role, Class::MOP and namespace::autoclean. * Updated explicit dependencies on Perl core modules to reduce the required minimum version numbers to be the same as those bundled with Perl 5.8.1, the minimum declared Perl version. If it turns out we actually need newer versions of any of these, they can be increased as needed. Meanwhile, in practice users would have much newer versions anyway when their Perls are newer. So minimum Carp is now 1.01 (previously no explicit dependency), ExtUtils::MakeMaker is now 6.17 (was 6.48), Scalar::Util is now 1.13 (was 1.21), Test::More is now 0.47 (was 0.92). Requiring newer versions than these would require CPAN installation or a newer Perl version. * Updated explicit dependencies on Perl modules that are not bundled with any version of Perl and must be installed from CPAN: The minimum List::MoreUtils was raised to 0.28 as versions before 0.25_02 fail on Perl 5.10.1+. The minimum Carp::Always (used only by the test suite) was reduced to 0.01, its first version; this can be raised later if it needs to be. The minimum Test::Deep (used only by the test suite) was left unchanged at 0.106, as versions below (0.104) fail on Perl 5.10.1+. * (Relation.pm, V2.pm, V1.pm) Demoted the packages Set::Relation and Set::Relation::Mutable from being actual abstract roles to just being placeholder namespaces for the distribution or for documentation purposes. Each of the 2 files V2.pm and V1.pm is now self-contained and no longer has a hard dependency on Relation.pm; the latter now just exists as common documentation, illustrating roles that the classes in the former conceptually must compose, where this is unenforced by code. As such, Relation.pm doesn't actually have to be installed. Related to this, V2 and V1 now each declare their own does() method, which hard-codes that they compose Set::Relation/::Mutable, in case one wants to use it like the one Moose had provided. Calling isa() on V2 or V1 will continue to work as it did before, including that it returns false for Set::Relation/::Mutable. * (Relation.pm, V2.pm, V1.pm) Relation.pm no longer uses Moose::Role and V2.pm plus V1.pm no longer use Moose; the latter 2 now explicitly use Carp::confess() and Scalar::Util::blessed() instead. Now V2 and V1 each have an explicitly defined new() submethod to replace what Moose had provided, and each also now has a complement of explicitly defined attribute private or public accessor methods, for the same reason. Other parts of those modules now test for "can('does')" rather than "isa('Moose::Object')" and besides this no other changes were needed for the code to work as it did in the previous release. * (Relation.pm, README, TODO) Replaced any references in this distro to the obsolete Muldis Rosetta with its replacement Muldis::D::RefEng. Muldis::D::RefEng is still under development and has no CPAN release yet, which will be the case until it has a certain mainimum level of functionality; meanwhile, what has been written can be seen on GitHub. * Note that the changes of this release were partly inspired by Ralf Peine having just released the new module PQL::Cache, which has no non-Perl-core dependencies and can install with a simple file copy. (It was intended all along that my newer Muldis D implementations would similarly eschew non-Perl-core dependencies, particularly Moose et al, but what was new is I was inspired to change Set::Relation likewise.) * Incremented all copyright year range-ends to 2015. 2015-01-01 * Set::Relation version 0.12.8 for Perl 5 is released on CPAN as Set-Relation-0.12.8.tar.gz. * The sole purpose of this release is to publish on CPAN the various minor updates made to Set::Relation up through the middle of 2011, but that any dependency version increases were excluded / reverted. * Note that if you are running Perl 5.10.1+ then your List::MoreUtils must be v0.25_02+ rather than the actual hard dependency of v0.22+. * (Relation.pm) Updated the *.pm file that declares multiple Perl packages, so that now every single package separately declares its (identical) package $VERSION, rather than just the first package in the file declaring said, implicitly applied to the others. * (Relation.pm, V2.pm, V1.pm) Updated all 1 role and 2 classes that compose roles so that they now specify what version numbers of said roles they require. Moose had added support for declaring/enforcing this in its v1.03 (2010-05-06). Note that Set::Relation's hard dependency on Moose has not been increased from v0.92+; it has not been tested if using a version before v1.03 will actually fail or not. * (Relation.pm, README) Updated the list of email forums focusing on Muldis D and its implementations, first to add a 4th list muldis-d-language, and second to update all 4 lists' descriptions. (This change made near 2010-06-20.) * (Relation.pm, README, Makefile.PL) Updated any instances of "" so that they are fully lower-cased, because the mixed case version doesn't work with some web browsers; browsers that don't automatically convert it to lowercase get a "There currently are no publically-advertised mailman lists" message. (This change made near 2010-05-17.) * (Relation.pm) Now spell author personal name "Chris Date (C.J. Date)" rather than "Christopher J. Date". (This change made near 2010-10-08.) * (Relation.pm) Following a Muldis D v0.110.0 spec change, updated the also-known-as notes for 5 functional methods. (This change made near 2010-03-01.) * (Relation.pm) Following one or more Muldis D spec changes between v0.111.0 and v0.148.0 inclusive, updated the also-known-as notes for 11 more functional methods, and possibly the same 5 as for v0.110.0. * There were also a few other minor documentation changes in the files. * Incremented all copyright year range-ends to 2011. 2009-11-03 * Set::Relation version 0.12.7 for Perl 5 is released on CPAN as Set-Relation-0.12.7.tar.gz. * (V1.pm) Fixed two instances of a bug, one in the private method "_group" that manifests in all 4 public methods "[|cmpl_]group", "[|outer_]join_with_group", and one in the "summary" public method. There were no corresponding bugs in V2.pm. Thanks to Todd Hepler for spotting the bug in "_group" and providing a patch. * (Set_Relation_51_Database_in_Depth_Example.t) Added another test block which exercises the "group" method, which previously had no tests; this test exposed the "_group" bug. Thanks to Todd Hepler who authored and contributed the new tests. * Updated all author references to change Darren Duncan's stated email address from "perl@DarrenDuncan.net" to "darren@DarrenDuncan.net". 2009-10-29 * Set::Relation version 0.12.6 for Perl 5 is released on CPAN as Set-Relation-0.12.6.tar.gz. * More small Makefile.PL enhancements. Reverted part of the 0.12.5 change, in that the Makefile.PL now starts with use 5.8 rather than 5.6 but kept the 0.12.5 change in that warnings is still not fatal. This was done since apparently there is no better way, under MakeMaker or otherwise, to be more graceful about required perl version than what results from the plain use-5.8 at the top of Makefile.PL. As the 0.12.5 Makefile.PL was, a Perl 5.6.2 was simply having errors at the "make test" stage due to that requiring 5.8, rather than at the Makefile.PL stage where it should have. Also in Makefile.PL, updated the 'requires' item 'perl' to use X.00Y00Z format rather than X.Y.Z since the upcoming META.yml spec would be stricter about the format. 2009-10-26 * Set::Relation version 0.12.5 for Perl 5 is released on CPAN as Set-Relation-0.12.5.tar.gz. * Updated the distro's Makefile.PL so it will now run under older Perls than the distro's payload modules would, so that users are informed more gracefully about their need to upgrade. Rather than having the same boilerplate use 5.8/utf8/strict/warningsFatal as the modules, the Makefile.PL now has a more liberal 5.6/strict/warnings. Also added explicit 'perl' requires-item to force mentioning of the Perl version in the generated META.yml, since MIN_PERL_VERSION doesn't cause this. 2009-10-26 * Set::Relation version 0.12.4 for Perl 5 is released on CPAN as Set-Relation-0.12.4.tar.gz. * Oops, the previous release 0.12.3 shipped with code all declared as version 0.012002 rather than 0.012003; the metadata was correct though. * Updated the README file to indicate that this distribution now has 2 public Git repositories, one on GitHub.com and one on utsl.gen.nz. * Updated external dependencies: Moose/etc to version 0.92, Class::MOP to version 0.94. * (Relation.pm) Fixed a doc typo; the wrong param was referenced. * (Relation.pm) Following a Muldis D v0.95.0 spec change, updated the also-known-as notes for 2 functional methods. * Updated the README file to mention the new Muldis-D-Manual distro. * (Makefile.PL, V2.pm, V1.pm) Added explicit dependency on Scalar::Util in both the Makefile.PL and in the "DEPENDENCIES" pod, because it is a best practice to name all direct dependencies regardless of whether any of them are normally bundled with Perl. * Major update to the Makefile.PL (and META.yml) to make its format more modern, in particular by distinguishing between dependencies that are needed to use the Set::Relation modules and those needed only for testing them or for configuring the distribution; previously, the dependencies needed only for testing were treated as if necessary to use Set::Relation itself; also added a list of "resources" urls. 2009-09-15 * Set::Relation version 0.12.3 for Perl 5 is released on CPAN as Set-Relation-0.12.3.tar.gz. * Updated external dependencies: namespace::autoclean to version 0.09, Moose/etc to version 0.90, Class::MOP to version 0.93. * (V2.pm, V1.pm) Internals update to remain compatible with the latest Moose/Class::MOP, which has deprecated the ability for one to say "$obj->new(...)", which we had been doing internally rather than "ClassName->new(...)" so that we still work when we're subclassed; so now we use "(blessed $obj)->new(...)" to make new objects instead. * (Relation.pm) In accordance with the Muldis D spec v0.87.0+, updated the descriptions of the 10 functional methods that do rename/projection/wrap/group/etc to update notes about alternate names that each function or its operation are known as. 2009-08-29 * Set::Relation version 0.12.2 for Perl 5 is released on CPAN as Set-Relation-0.12.2.tar.gz. * Updated external dependency on Test::More to version 0.92, which is the version bundled with Perl 5.10.1. * Updated external dependency on Test::Deep to version 0.106, which currently is only used by the 1 test file Set_Relation_51_Database_in_Depth_Example.t, because earlier versions of Test::Deep (0.104) fail their tests under Perl 5.10.1. * Updated external dependencies: Moose/etc to version 0.89, Class::MOP to version 0.92. * (Relation.pm) Other minor docs updates. 2009-08-08 * Set::Relation version 0.12.1 for Perl 5 is released on CPAN as Set-Relation-0.12.1.tar.gz. * This distribution has excised its direct external dependency on the "version" module (bundled with Perl versions 5.10.0+), which was used in all .pm files and a .t file. And so, the modules in this distribution now declare floating point version numbers of format X.00Y00Z in their code (0.012001 for example); however, all module documentation, and the distribution itself, still uses 3-part version numbers of format X.Y.Z (0.12.1 for example) as before. The main reason for this change is to gain simplicity and reduce possible bugs. 2009-08-03 * Set::Relation version 0.12.0 for Perl 5 is released on CPAN as Set-Relation-0.12.0.tar.gz. * Updated external dependencies: Moose/etc to version 0.88, Class::MOP to version 0.91. * This release features a number of functional method updates in accordance with the latest Muldis D spec (v0.82.0). * (Relation.pm, V2.pm, V1.pm) WARNING: INCOMPATIBLE CHANGE: Updated each of the 3 public functional methods "[|cmpl_]wrap", "unwrap" to swap the canonical order of its 2 "outer", "[|cmpl_]inner" parameters so that the one applying to the method's result appears first / on the left. Likewise with each of the 5 public functional methods "[|cmpl_|un|[cardinality|count]_per_]group" and its 2 "[outer|count_attr_name]", "[inner|group_per]" parameters. Also updated the 1 "rename" public functional method's "map" parameter to swap the Hash keys and values so that the Hash keys now represent the "new" names and the Hash values now represent the "old" names. * (Set_Relation_51_Database_in_Depth_Example.t) Updated the tests of the "rename" method to conform to its updated API. * (Relation.pm) Updated the descriptions of 10 functional methods to add notes about alternate names that the function or its operation are known as. The alternate names are symbolic and use combinations of these: '{', '}', '<-', '@'. Used for rename/projection/wrap/group/etc. 2009-07-21 * Set::Relation version 0.11.3 for Perl 5 is released on CPAN as Set-Relation-0.11.3.tar.gz. * Updated external dependency on Test::More to version 0.88, which currently is only used by the 3 test files, same as what used previous versions. While earlier versions of Test::More are bundled with Perl 5, only the impending Perl 5.10.1 will bundle a version not earlier than 0.88, so meanwhile you must update Test::More from CPAN. The test files were updated to no longer declare a planned number of tests at the start, but instead to declare "done_testing()" at the finish. This change should help make further simultaneous development and merging by multiple developers less error prone. 2009-07-08 * Set::Relation version 0.11.2 for Perl 5 is released on CPAN as Set-Relation-0.11.2.tar.gz. * As of this release, Set::Relation for Perl 5 uses the namespace::autoclean pragma instead of the namespace::clean pragma, because it is easier to use and not so contrived in how it works and is a generally recommended upgrade by savvy people. Note that the newer dependency has a larger not-bundled dependency chain, including Class::MOP, but this isn't a problem because Set::Relation for Perl 5 already uses Moose anyway. * This distribution has gained a new direct external dependency on the Carp::Always module, which currently is only used by the 3 test files. * Updated external dependencies: Moose/etc to version 0.87, Class::MOP to version 0.89. * (Relation.pm) Minor docs fix. 2009-06-08 * Set::Relation version 0.11.1 for Perl 5 is released on CPAN as Set-Relation-0.11.1.tar.gz. * Updated external dependencies: Moose/etc to version 0.81, Class::MOP to version 0.85. * (Relation.pm) In accordance with the latest Muldis D spec (v0.77.0), the Muldis D concept or type a Set::Relation object represents is now simply called "relation", which was renamed from "quasi-relation" in the spec. Accordingly, removed the DESCRIPTION paragraph saying that a Set::Relation isn't quite a relational model relation; rather I am now claiming that it is exactly the same, though it is most like the less strict version where it is like every relation attribute may have a declared type of the universal set of values. There are no actual code changes in the Set::Relation distro associated with this update. 2009-06-01 * Set::Relation version 0.11.0 for Perl 5 is released on CPAN as Set-Relation-0.11.0.tar.gz. * Updated external dependencies: Moose/etc to version 0.79, Class::MOP to version 0.84. * This release features a number of functional method updates or additions in accordance with the latest Muldis D spec (v0.75.0). * (Relation.pm, V2.pm, V1.pm) WARNING: INCOMPATIBLE CHANGE: Updated each of the 2 "is[|_proper]_subset" public functional methods so that the canonical sequence of its invocant and parameter is reversed, so the method's name, used infix as normal for OO, would read correctly; also renamed said 2 inputs so that "look_for" is now "topic" and "look_in" is now "other". This change is silently incompatible and old user code will continue to run without changes, but would give the wrong answers; any old code like "$foo->is_subset($bar)" will need to be changed to "$bar->is_subset($foo)" to keep its semantics, or alternately be changed to "$foo->is_superset($bar)" (see next chg itm). * (Relation.pm, V2.pm, V1.pm) Added the 2 public functional methods (in the Set::Relation role) "is[|_proper]_superset", where each is an alias for another function, "is[|_proper]_subset", save that its invocant and argument are transposed. * (Relation.pm, V2.pm, V1.pm) Renamed the public functional method "is_member" to "has_member" so that the methods's name, used infix as normal for OO, reads correctly. * (Relation.pm, V2.pm, V1.pm) Renamed these 8 public functional methods to terser versions of themselves mainly for the purpose of making them easier to type: "cmpl_projection" -> "cmpl_proj", "transitive_closure" -> "tclose", "restriction_and_cmpl" -> "restr_and_cmpl", "cmpl_restriction" -> "cmpl_restr", "static_extension" -> "static_exten", "[|semi]difference" -> "[|semi]diff", "static_substitution" -> "static_subst". * (Relation.pm, V2.pm, V1.pm) Added the 4 public functional methods (in the Set::Relation role) "count", "count_per_group", "symmetric_diff", "antijoin", where each is a simple alias for another functional method, "cardinality", "cardinality_per_group", "exclusion", "semidiff". * (Relation.pm, V2.pm, V1.pm) Minor docs update to reflect that the Muldis D dialect HDMD_Perl5_Tiny was renamed to HDMD_Perl5_STD. * (Relation.pm) Some POD reformatting: Updated every method signature having a param "FooType $bar_param" with a linebreak between the paired type name and param name so that each pair is entirely on one line. * (Relation.pm) Updated the docs for all 14 functional methods that have one or more parameters whose declared Perl 6 type was "Code", so that the more modern Perl 6 type name of "Callable" is used instead. * (Relation.pm) Updated the docs on 3 functional methods to use more correct terminology with respect to symmetric dyadic functions, so that it now calls each a "symmetric function" rather than a "function with 2 mutually commutative main parameters": "is_identical", "is_disjoint", "composition". * (Relation.pm) Annotated the docs on 3 of the functional methods that previously were directly described with "commutative and associative" to now also say "idempotent" when the main inputs were supplied conceptually as a set argument and not a bag: "union", "intersection", "join". Now "product" is also idempotent, but its description just says "like join". The only N-adic functional method that isn't idempotent is "exclusion". * (Relation.pm) Updated the descriptions of 16 functional methods to add or update notes about alternate names that the function or its operation are known as, in particular adding the various math/etc symbols they represent. 2009-04-21 * Set::Relation version 0.10.0 for Perl 5 is released on CPAN as Set-Relation-0.10.0.tar.gz. * Updated external dependencies: namespace::clean to version 0.11, Moose/etc to version 0.75, Class::MOP to version 0.82. * This release features a number of functional method updates or additions in accordance with the latest Muldis D spec (v0.64.0). * (Relation.pm, V2.pm, V1.pm) Added, to the Set::Relation role and its composing classes, 2 new functional methods "[rank|limit]_by_attr_names", which are like "rank|limit" but that rather than taking a closure function to determine relative ordering of each pair of tuples, it takes an array of attribute names to order by; the new methods are more specialized versions of the old ones, and are recommended for use where they are applicable. It is significant to note that these are the first Set::Relation routines that make use of the implementation technique of generating and evaling Perl code to do the actual work, which allows us to unroll what would otherwise be loops iterating over the attributes being ordered by; this should further yield better performance; both V2 and V1 have done this. * (Relation.pm, V2.pm, V1.pm) Changed the "summary" functional method by renaming its "result_attr_names" parameter to "summ_attr_names" and redefining its functionality more in terms of "extension" rather than "map"; the function given to "summ_func" must now just result in a tuple with attributes to add to a result which now already has all the attributes named by "group_per", rather than resulting in all attributes for the result. The new version of "summary" should be much easier to use as presumably users always want to keep the attributes they are grouping per, and they now don't have to spell them out every time. For the rare case where you want the old behaviour, now you have to do it manually with an explicit "cmpl_group" plus "map". * (Relation.pm, V2.pm, V1.pm) Added, to the Set::Relation role and its composing classes, new functional method "cardinality_per_group" which is like "summary" but shorthands the common case where people just want a count of tuples per group and not any other information. 2009-03-24 * Set::Relation version 0.9.0 for Perl 5 is released on CPAN as Set-Relation-0.9.0.tar.gz. * (Relation.pm, V2.pm, V1.pm) Added new functional method "classification" which is sort of a cross between "restriction" and "group"; it uses a Perl subroutine argument to partition a relation's tuples into an arbitrary number of groups. It is named after Perl 6's "classify" operator, and is like List::MoreUtil's "part" function. * (Relation.pm) Updated the Set::Relation role in several closely related ways. Added new named parameter to 'new' named 'keys' which lets one define candidate keys for the new relation which the 'members' argument must satisfy for 'new' to succeed; a variety of format examples were included in the documentation. Also updated the accessor method 'export_for_new' and added the accessor method 'keys' which take care of dumping the list of candidate keys that the relation object is known to satisfy. Also added new functional method 'has_key' which tests whether the invocant relation has a certain candidate key; if it does, this method also has the side effect of remembering the fact for 'keys' to return later. It was also documented in a few places that these 'keys' are not constraints against future object mutations, and so they might be invalidated by 'insert' later for mutable objects. The ::Mutable role inherits all these changes. * (V2.pm) Updated the Set::Relation::V2 class to implement the new features required by the above change item. This is a fairly simple first draft of of the 'keys' feature and isn't very integrated yet, not any more than with V1; it currently doesn't have any positive impact on performance and it currently just provides an extra kind of constraint on new objects or an extra kind of validation on existing ones. * (V1.pm) Updated the Set::Relation::V1 class to implement the new features required by the above change item. The current implementation also is such that while 'insert' is smart enough to clear a candidate key iff it becomes violated, 'delete' will not restore or add any candidate key; you must invoke 'has_key' later to do that. Also, like with indexes, all new relations derived from others such as by 'clone' or 'new' or relational operations will start out with no 'keys' for simplicity; presumably an upcoming V2 will be different. 2009-03-23 * Set::Relation version 0.8.0 for Perl 5 is released on CPAN as Set-Relation-0.8.0.tar.gz. * This release features the addition of a second bundled implementation of the Set::Relation role, called V2, which should have different (and hopefully better) performance characteristics than V1. This release doesn't change the S::R public API in any particularly substantial way. * Updated external dependencies: Moose/etc to version 0.72, Class::MOP to version 0.78. * (Set_Relation_5[0_Synopsis|1_Database_in_Depth_Example].t, Relation.pm) Updated the test suite and the SYNOPSIS docs and the 'new' submethod docs to avoid the repetition of the Set::Relation-implementing class name by creating a one-liner-per-file wrapper function over 'new' named 'relation' which is now used for all methodless S::R object creation. * (Set_Relation_5[0_Synopsis|1_Database_in_Depth_Example].t) Updated the test suite internals to make them more modular; in each test file, refactored all the actual tests into a subroutine, so the set can be defined once and reinvoked for each bundled Set::Relation-doing class, when more than one of those (others besides V1.pm) come to exist. * (Relation.pm) Updated all 10 methods of the Set::Relation role that had a "Array|Str"-typed parameter named "[|\w+_]attrs" and renamed said parameter to "[|\w+_]attr_names"; any similarly named parameters that were of some other type, such as "Hash", kept their old names. This change should make the parameters more self-documenting, since "attrs" names now tend to have both attribute names and values, where as "attr_names" have just names. The changed 10 methods were: "slice", "has_attrs", "[|cmpl_]projection", "extension", "map", "summary", "substitution", "subst_in_[restr|semijoin]". Note that, since all of the methods' parameters are positional (rather than named), the change is completely backwards compatible. * (V1.pm) Updated the Set::Relation::V1 class to rename some of its public method parameters as per the previous change item. * (Relation.pm) Added new performance-enhancing feature to the Set::Relation role, in the form of a new optional boolean parameter "allow_dup_tuples" for each of 17 methods. Each Set::Relation-doing class has the option of honoring a true argument for that parameter by avoiding work involved in eliminating duplicate tuples and thereby having possibly different results or side-effects on said method invocations, due to what are partially multiset semantics being used instead of set semantics. So users can explicitly request, on a case-by-case basis, to get possibly less accurate but "good enough" results in exchange for better performance. Also added new documentation sub-section "Matters of Correctness" under the DESCRIPTION main section, that explains the feature. The changed 17 methods were: "export_for_new", "members", "body", "slice", "attr", "cardinality", "[|cmpl_]restriction", "restriction_and_cmpl", "extension", "map", "summary", "substitution" "[|static_]subst_in_restr", "subst_in_semijoin", "outer_join_with_exten". * (V1.pm) Updated the Set::Relation::V1 class to add some public method parameters as per the previous change item. However, this change is a no-op since the parameters are ignored in every case, with the semantics being the same as if they were never given arguments. * (Relation.pm, V1.pm) Various other small updates and fixes. * Added new file lib/Set/Relation/V2.pm which is now the bundled second implementation of the Set::Relation role, and updated all the other relevant distribution files concerning it. The new V2.pm initially started as a clone of V1.pm following all of the above change items, and then differentiated in 2 main ways: The first is that V2 provides immutable objects (doesn't do ::Mutable). Also V2 just has a short DESCRIPTION pod section to start out, while V1's is longer. 2009-02-13 * Set::Relation version 0.7.0 for Perl 5 is released on CPAN as Set-Relation-0.7.0.tar.gz. * Updated external dependencies: Moose/etc to version 0.69. * Split up Relation.pm into itself and the new file lib/Set/Relation/V1.pm; Relation.pm now declares a role rather than a class, and V1.pm is a class doing that role. Relation.pm now declares the Set::Relation API and keeps nearly all the old module documentation, and V1.pm has nearly all of the old code. Moreover, Relation.pm now declares not one but 2 roles, Set::Relation and Set::Relation::Mutable, where the latter consumes the former and Set::Relation::V1 consumes the latter; the former role promises that its composing class' objects are immutable unless they also compose the latter. The ::Mutable role got the 6 public methods ['clone', 'has_frozen_identity', 'freeze_identity', 'evacuate', 'insert', 'delete'] plus the 'has_frozen_identity' optional parameter of the 'new' constructor, and the parent role got all the other public things. Also updated the test suite, and the SYNOPSIS pod, to account for this split, and they now invoke the ::V1 class directly rather than the shorter package name that is now a role. The new class has exactly the same API as the old class. * Updated the TODO file to outline plans for a near future ::V2 class which represents tuples using Perl Array rather than Perl Hash. 2009-02-09 * Set::Relation version 0.6.0 for Perl 5 is released on CPAN as Set-Relation-0.6.0.tar.gz. * As of this release, Set::Relation for Perl 5 directly uses the List::MoreUtils module to handle some of its detail work; this distribution has now gained a direct external dependency on the Perl 5 module 'List::MoreUtils', which is not bundled with any version of Perl and will need to be installed from CPAN. That said, List::MoreUtils was already a dependency of Set::Relation's existing Moose dependency, so the whole dependency tree has not enlarged. * (Relation.pm) Added these 14 object methods: "wrap", "cmpl_wrap", "unwrap", "group", "cmpl_group", "ungroup", "summary", "join_with_group", "rank", "limit", "outer_join_with_group", "outer_join_with_undefs", "outer_join_with_static_exten", "outer_join_with_exten". As of now, all of the pre-documented and TODO-marked object methods have been implemented. * (Relation.pm) Replaced all instances of "__PACKAGE__->new(...)" with "$self->new(...)" etc, to help avoid potential future problems when someone tries to subclass the module. * (Relation.pm) Various bug fixes and other small changes. * As of this release, Set::Relation is officially in alpha development status (was pre-alpha). All of the initially planned functionality is now implemented, so it is feature complete, which is why it was moved out of pre-alpha status. However most of the functionality has not been tested and so is not proven to actually work without error. Once the module has a thorough test suite which passes, Set::Relation can be moved to beta or released status. 2009-02-09 Record update in the PAUSE modules database: modid: [Set::Relation] statd: [a] was [c] stats: [m] statl: [p] stati: [O] statp: [l] description: [Relation data type for Perl] userid: [DUNCAND] chapterid: [6] mlstatus: [list] 2009-02-06 * Set::Relation version 0.5.0 for Perl 5 is released on CPAN as Set-Relation-0.5.0.tar.gz. * (Relation.pm) Added these 8 object methods (still 14 to go): "restriction_and_cmpl", "semijoin_and_diff", "substitution", "static_substitution", "subst_in_restr", "static_subst_in_restr", "subst_in_semijoin", "static_subst_in_semijoin". * (Relation.pm) Other minor updates and fixes. 2009-02-05 * Set::Relation version 0.4.0 for Perl 5 is released on CPAN as Set-Relation-0.4.0.tar.gz. * Updated external dependencies: Moose/etc to version 0.68. * As of this release, Set::Relation for Perl 5 uses the namespace::clean pragma for good hygiene; this distribution has now gained an external dependency on the Perl 5 module 'namespace::clean', which is not bundled with any version of Perl and will need to be installed from CPAN; namespace::clean also has a few not-bundled dependencies of its own. * (Relation.pm) Added "use namespace::clean" statements inside the package declaration following any other "use" statements, so their exports into our package doesn't also become part of our own public API as a side-effect; the only exception is the "meta" method that Moose adds, which is kept. * (Relation.pm) Added new documentation sub-section under "DESCRIPTION" named "Appropriate Uses For Set::Relation", which should hopefully answer some FAQs, such as why does the module exist, and pointing out some strengths and weaknesses. * (Relation.pm) Corrected a forgetful oversight in the module documentation concerning Set::Relation's "has_frozen_identity" object attribute; this attribute had an auto-generated read-only public accessor method plus is automatically initialized from a same-named constructor method; added "has_frozen_identity" to the accessor method list, and updated the "new" constructor submethod signature. * (Relation.pm, Set_Relation_50_Synopsis.t, Set_Relation_51_Database_in_Depth_Example.t) Updated the "new" constructor submethod so that it now accepts a single positional argument as an invocation option, where before it just accepted named arguments (and it still does); a single positional argument to "new" is treated the same as a single "members" named argument. This change means that the majority of current or anticipated future use cases of Set::Relation are now terser by about 9-11 characters ("members => ") per "new" invocation. (This new feature was implemented mainly by adding a simple BUILDARGS method to Relation.pm.) Updated all the examples and tests to use the new terser format. * (Relation.pm) As a consequence of the previous change, the "new" constructor has also been updated so that the "members" argument is no longer allowed to be a Perl Hash (because a lone Hash positional argument is one of the standard Moose format options to supply named arguments) so any invocations of "new" which gave a Hash argument will have to become 2 characters ("[]") more verbose, wrapping it in an Array. Removed the example using a Hash. * (Relation.pm) Added the Moose concerning recommended practice "__PACKAGE__->meta()->make_immutable();" line to the end of the module, which should help performance regarding Moose-generated stuff; this would've been done before release 0.0.0 but was forgotten at the time. * (Relation.pm) Updated the "LICENSE AND COPYRIGHT" documentation section to change the Copyright declaration from "Darren Duncan" to "Muldis Data Systems, Inc." (which is wholly owned by Darren Duncan). 2009-02-02 * Set::Relation version 0.3.0 for Perl 5 is released on CPAN as Set-Relation-0.3.0.tar.gz. * (Relation.pm) Added these 5 object methods (still 20 to go): "slice", "attr", "has_attrs", "attr_names", "transitive_closure". * (Relation.pm) Other minor updates and fixes. 2009-02-01 * Set::Relation version 0.2.0 for Perl 5 is released on CPAN as Set-Relation-0.2.0.tar.gz. * (Relation.pm) Added full documentation for the remaining 25 object methods that Set::Relation expects to have implemented prior to being moved to alpha development status; each is marked TODO in its title; this change item doesn't have a list of said methods, but when they are implemented in the next 1-3 releases, the change log will mention them simply as being new, same as if they hadn't been pre-documented now (and the TODO marker on their docs will be silently removed). * (Relation.pm) Added placeholder code for said 25 TODO methods, each of which will die with an "unimplemented" message if invoked. * (Relation.pm) Other minor code updates. 2009-01-31 * Set::Relation version 0.1.0 for Perl 5 is released on CPAN as Set-Relation-0.1.0.tar.gz. * This release features a few API changes, some significant feature additions, and bug fixes to existing routines, but no public facing routines have been added or removed. New routines should feature in the next 0.Y.0 release. * (Relation.pm) Updated each of the 5 functional methods ["union", "exclusion", "intersection", "join", "product"] so it is now an N-adic operator rather than a dyadic operator. Each method's "other" parameter was renamed to "others" and now takes either a single Set::Relation object as before or an Array of 0..N Set::Relation objects which is new. With this change, these operators are now at feature parity with the Muldis D functions they are based on, except that they never handle the niladic option; being object methods, there is always at least one operand which is the invocant. * (Relation.pm) Updated each of the 4 functional methods ["[|cmpl_]restriction", "extension", "map"] to remove its optional "assuming" parameter. This parameter was a fossil left over from the original Muldis D versions of these operators that the Perl version was ported from; the parameter was necessary in Muldis D to have reasonable flexibility due to Muldis D lacking certain other features that Perl has, which make this parameter unnecessary in Perl. The removal was to keep the Perl simpler; it also sets the stage for the next change item. * (Relation.pm, Set_Relation_51_Database_in_Depth_Example.t) Updated each of the 4 functional methods ["[|cmpl_]restriction", "extension", "map"] so that the Perl routine supplied as its "func" argument is now assumed to have zero parameters rather than one, and the Perl routine is now supplied its input tuple/Hash in $_, same as how Perl's built-in map/grep operators work, rather than as a first/only argument. Thanks to Todd Hepler for proposing that design change to "restriction" to make it more DWIM. * (Relation.pm, Set_Relation_51_Database_in_Depth_Example.t) Updated each of the 4 functional methods ["[|cmpl_]projection", "extension", "map"] so that the "[|result_]attrs" parameter can also take a Str argument rather than just an Array of Str argument. Thanks to Todd Hepler for proposing that design change to "projection" to make it more DWIM. Also updated the Set::Relation constructor submethod similarly, so its "members" parameter may also take a Str argument; this would produce a relation object with 1 attribute and zero tuples. * (Relation.pm) Fixed an "insert" mutator method bug so it detects and blocks attempts to insert the invocant Set::Relation object into itself as a value-typed component, which would have had the side-effect of freezing the invocant, or would have conceptually been an infinite recursive deep copy operation; also fixed the "delete" mutator with the same detector since it would have had the same freezing problem. * (Relation.pm) Updated all routines that take tuple-representing Hash values from the user, either directly or as tuple-valued attrs, either as a routine argument or a closure return value, so that each Hash is tested for circular references between itself or its value-typed components; this update fixes a general bug where the module could infinitely recurse when processing that input, since tuple-representing input from the user is deep-copied. * (Relation.pm) Some POD reformatting: Took what used to be the 5 level-2 headings under the INTERFACE level-1 heading and changed said 5 into level-1 headings, but did not uppercase their text. Then converted the routine lists from being "=over/=item <routine>/=back" to each routine having its own level-2 heading. For each routine, the new heading is just the short name of the routine, and the full signature of the routine displays just as its own paragraph. All these changes combined should look visually like we are faking 3 levels of headings, with top and middle being upcased and mixed case "=head1" respectively. * (Relation.pm) Minor code and POD updates and fixes. 2009-01-26 * Set::Relation version 0.0.2 for Perl 5 is released on CPAN as Set-Relation-0.0.2.tar.gz. * (Relation.pm) Fixed two instances of a bug in the "rename" method. Thanks to Todd Hepler for spotting the bug and providing a patch. * Added new test file "t/Set_Relation_51_Database_in_Depth_Example.t", which exercises more than a half-dozen Set::Relation methods that previously had no tests; the "rename" bugs were exposed when writing this. Thanks to Todd Hepler who authored and contributed this file. * This distribution has gained a new direct external dependency on the Test::Deep module, which currently is only used by the new test file. * (Relation.pm) Minor code comment fixes and POD updates. 2009-01-21 * Set::Relation version 0.0.1 for Perl 5 is released on CPAN as Set-Relation-0.0.1.tar.gz. * (Relation.pm) Fixed a bug in the "quotient" method, and further updated it with some special-case shortcuts. * (Relation.pm) Other minor updates. * (README, Relation.pm) Previously the FORUMS pod section of Relation.pm and 3 parts of the README file lacked content, and now they have it; added documentation about where the Set::Relation version control and support forums are. 2009-01-19 * Set::Relation version 0.0.0 for Perl 5 is released on CPAN as Set-Relation-0.0.0.tar.gz. * It constitutes a rewrite of Set::Relation for Perl 6 that had been made in 2006 but was never functional; the large body of work going into the Muldis D language and Muldis Rosetta framework during the intervening period also fed into this new Set::Relation module; it is expected that this new Set::Relation for Perl 5 will be ported to Perl 6 in the near future and so upgrade that 2006 version; meanwhile, this Changes entry refers only to the Perl 5 version. * This is the first release of the Perl 5 Set::Relation distribution, and the first release of any distribution to contain a Perl 5 module named Set::Relation. * This is the initial file manifest: Changes INSTALL lib/Set/Relation.pm LICENSE/GPL LICENSE/LGPL Makefile.PL MANIFEST MANIFEST.SKIP README t/Set_Relation_00_Compile.t t/Set_Relation_50_Synopsis.t TODO * As of this release, Set::Relation is officially in pre-alpha development status. * This is the initial complement of routines; besides the "new" constructor submethod, there are these 40 object methods: "clone", "export_for_new", "freeze_identity", "which", "members", "heading", "body", "evacuate", "insert", "delete", "degree", "is_nullary", "cardinality", "is_empty", "is_member", "empty", "insertion", "deletion", "rename", "projection", "cmpl_projection", "restriction", "cmpl_restriction", "extension", "static_extension", "map", "is_identical", "is_subset", "is_proper_subset", "is_disjoint", "union", "exclusion", "intersection", "difference", "semidifference", "semijoin", "join", "product", "quotient", "composition". 2009-01-04 The next version of the Module List will list the following module: modid: Set::Relation DSLIP: cmpOl description: Relation data type for Perl userid: DUNCAND (Darren Duncan) chapterid: 6 (Data_Type_Utilities) enteredby: BDFOY (brian d foy) enteredon: Mon Jan 5 06:12:12 2009 GMT The resulting entry will be: Set:: ::Relation cmpOl Relation data type for Perl DUNCAND 2006-04-14 thru 2006-11-22 * A Perl 6 project named "Relation" is started (complementary to the earlier existing to-be-named Muldis Rosetta project) which was intended to provide native tuple and relation data types for ordinary use in Perl 6 programs like other built-in collection types. The first commit was Pugs SVN rev 9938, on 2006-04-14, and Pugs 6.2.12 (2006-06-26) included it. Hence 2006 is the start of the declared copyright date range for Set::Relation. * On 2006-07-04, renamed this Perl 6 project to "Set-Relation", which it remains to this day. Pugs 6.2.13 and later included this. * The Perl 6 Set-Relation received various small updates thru 2007-02-03 (Pugs SVN rev 15168), but is now stagnant; it will likely get un-stuck after the initially newer Perl 5 version is made to work. 2005-12-05 * Darren Duncan is introduced by David Wheeler to the truly relational model of data, in a posting on the Bricolage development list in the "Re: [6977] New branch for maintenance of Bricolage 1.10.x." thread. * David said that Darren's expressed thought, that compound data types in table fields was a violation of first normal form, was in fact a misconception about the relational model. David then referenced a recent interview with C.J. Date. * This set off a chain of events which was the largest paradigm shift to ever affect what evolved into the Muldis Rosetta project, and also resulted in the genesis of the Set::Relation module. | https://metacpan.org/changes/distribution/Set-Relation | CC-MAIN-2015-22 | refinedweb | 7,489 | 54.63 |
Hi AdiiS,
We need to create our own DataGridView and override the OnScroll method. In the method, we can set the new value equal to the old value to avoid rows/columns moving. This is the code snippet:public class MyDataGridView : DataGridView
{
public MyDataGridView()
{
//Enable both scrollbars.
this.ScrollBars = ScrollBars.Both;
}
protected override void OnScroll(ScrollEventArgs e)
//Set the new value equal to old value to avoid moving.
e.NewValue = e.OldValue;
base.OnScroll(e);
}
Let me know if this helps.Aland Li
Could you please let me know if my reply helps you? If you still have problems, please feel free to tell me.
Regards,Aland Li | http://www.windowsdevelop.com/windows-forms-data-controls-databinding/avoid-scrolling-in-datagriview-21435.shtml | crawl-003 | refinedweb | 108 | 65.83 |
Skip to 0 minutes and 7 secondsWIM: Hello, everyone. In this short video, we're going to look at some more basic elements of Haskell by examples from other languages. So we will look at anonymous functions, higher-order functions, blocks, and conditions. First, anonymous functions. So these are functions that don't have a name and they occur in many languages. For example, in JavaScript. So in JavaScript you can write something like-- so what we have here is a variable f that contains a complete function. In Haskell, these anonymous functions are called lambda functions and they're really very important. They are actually the foundation of the language. So there is a very compact syntax for that. Again, in Haskell the same example would look as follows.
Skip to 1 minute and 5 secondsAnd again, we will talk a lot more about lambda functions in the next class. So another important element in many programming languages is the block structures that you use to define functions. For example, again in JavaScript we could define a function that returns the roots of a quadratic equation. So-- we have a function that takes the coefficients of the quadratic equation and then we can compute the roots in the familiar way. So we have-- so we have a function that defines a block of code where we find a number of variables. So first we have the square of the determinant. Then we take the square root to get to the determinant.
Skip to 2 minutes and 9 secondsThen we compute the root and the first root of the quadratic equation and the second root and we return them both in a list. So, in Haskell, this same code looks very similar. And we will just define it by removing some of this syntax.
Skip to 2 minutes and 39 secondsSo we have a function of a, b, and c. And the function is actually defining a block using a let construct. So it says let and then a number of variables in the expression of this return. Because the whole thing is an expression, you don't need the return statement.
Skip to 3 minutes and 0 secondsAnother very important construct in any programming language is a conditional construct. So an if-then, or if-then-else. For example, in Python we might define a function to compute the maximum of two numbers as follows.
Skip to 3 minutes and 24 secondsSo the function max takes two values, x and y, and we do a comparison. If x is greater than y, we return x. And otherwise, we return y. So nothing special there. Haskell has a very similar if-then statement, but again it's an expression, not a statement. So let's look at what it looks like.
Skip to 3 minutes and 50 secondsAnd again, we need less syntax in Haskell than in Python.
Skip to 3 minutes and 57 secondsSo the last feature of Haskell that I want to illustrate is actually a little bit less basic-- a little bit more advanced-- it's called higher-order functions. These are functions that operate on other functions, or functions that take functions as arguments. And again, we can compare this with other languages. In this case, we compare it with Perl. So, in Perl you could, for instance, compute the double of a list using the following code.
Skip to 4 minutes and 31 secondsSo what happens here is that we have an anonymous function that takes an argument and doubles it, and the map function makes this anonymous function work on the list from 1 to 10. So again, in Haskell, this is very similar.
Skip to 4 minutes and 53 secondsLike that. So we have a map, which takes an anonymous function. So we have map, which takes an anonymous function and works on the list, and it will double every element in the list. So these higher-order functions are a lot more used in a functional language like Haskell than in an imperative language, but, as you can see, they do exist in other languages as well.
More Basic Elements by Example
A few more basic (and not-so-basic) elements of Haskell through comparison with other languages. We will not go into detail on the
Haskell constructs, just show the similarities with constructs from languages you may know.
Blocks
In
JavaScript functions typically are blocks of code:
function roots(a,b,c) { det2 = b*b-4*a*c; det = sqrt(det2); rootp = (-b + det)/a/2; rootm = (-b - det)/a/2; return [rootm,rootp] }
In
Haskell, we would write this function as follows:
roots a b c = let det2 = b*b-4*a*c; det = sqrt(det2); rootp = (-b + det)/a/2; rootm = (-b - det)/a/2; in [rootm,rootp]
Note that the
let ... in ... construct is an expression, so it returns a value. That’s why there is no need for a
return keyword.
Conditions
In
Python we could write a function with a condition as like this:
def max(x,y): if x > y: return x else: return y
Of course
Haskell also has an if-then construct:
max x y = if x > y then x else y
Again the
if ... then ... else ... construct is an expression, so it returns a value.
Case statement
Many languages provide a
case statement for conditions with more than two choices. For example, Ruby provides a
case expression:
Red = 1 Blue = 2 Yellow = 3 color = set_color(); action = case color when Red then action1() when Blue then action2() when Yellow then action3() end
In
Haskell, the case works and looks similar:
data Color = Red | Blue | Yellow color = set_color action = case color of Red -> action1 Blue -> action2 Yellow -> action3
Note however how we use the type as the value to decide on the case, where in other languages we need to define some kind of enumeration.
Generics/Templates
In
Java and
C++ there are generic data types (aka template types), such as:
Map<String,Integer> set = new HashMap<String,Integer>();
In
Haskell, you would write this as follows:
set :: Data.Map.Map String Integer set = Data.Map.empty
The main difference is of course that
set in
Haskell is not an object but an immutable variable, so where in Java you would say:
set.put("Answer",42)
In
Haskell you would say:
set' = Data.Map.insert "Answer" 42 set
Because in
Haskell variables are immutable, the return value of the
insert call is bound to a new variable rather than updating the variable in place as in
Java.
© Wim Vanderbauwhede | https://www.futurelearn.com/courses/functional-programming-haskell/2/steps/218276 | CC-MAIN-2019-13 | refinedweb | 1,105 | 70.63 |
angel3_static 4.0.0
angel3_static: ^4.0.0 copied to clipboard
angel3_static #
Static server infrastructure for Angel.
Can also handle
Range requests now, making it suitable for media streaming, ex. music, video, etc.
Installation #
In
pubspec.yaml:
dependencies: angel3_static: ^4.0.0
Usage #
To serve files from a directory, you need to create a
VirtualDirectory.
Keep in mind that
angel3_static uses
package:file instead of
dart:io.
import 'package:angel3_framework/angel3_framework.dart'; import 'package:angel3_framework/http.dart'; import 'package:angel3_static/angel3_static.dart'; import 'package:file/local.dart'; void main() async { var app = Angel(); var fs = const LocalFileSystem(); // Normal static server var vDir = VirtualDirectory(app, fs, source: Directory('./public')); // Send Cache-Control, ETag, etc. as well var vDir = CachingVirtualDirectory(app, fs, source: Directory('./public')); // Mount the VirtualDirectory's request handler app.fallback(vDir.handleRequest); // Start your server!!! await AngelHttp(app).startServer(); }
Push State #
VirtualDirectory also exposes a
pushState method that returns a
request handler that serves the file at a given path as a fallback, unless
the user is requesting that file. This can be very useful for SPA's.
// Create VirtualDirectory as well var vDir = CachingVirtualDirectory(...); // Mount it app.fallback(vDir.handleRequest); // Fallback to index.html on 404 app.fallback(vDir.pushState('index.html'));
Options #
The
VirtualDirectory API accepts a few named parameters:
- source: A
Directorycontaining the files to be served. If left null, then Angel will serve either from
web(in development) or
build/web(in production), depending on your
ANGEL_ENV.
- indexFileNames: A
List<String>of filenames that should be served as index pages. Default is
['index.html'].
- publicPath: To serve index files, you need to specify the virtual path under which angel_static is serving your files. If you are not serving static files at the site root, please include this.
- callback: Runs before sending a file to a client. Use this to set headers, etc. If it returns anything other than
nullor
true, then the callback's result will be sent to the user, instead of the file contents. | https://pub.dev/packages/angel3_static | CC-MAIN-2021-25 | refinedweb | 331 | 53.78 |
The.
3) There is no need to enumerate all the entity bean class names inside because we are defining only one PU in this persistence.xml and we will be packaging the entity classes along with this persistence.xml in a jar file, so container can discover all the entity beans.
Step #3: Write.
2) It must be a public class because it will be used by ACC which does not belong to the package of this class..
The deploy target in build.xml uses a feature called Java2DB which can automatically create the tables during deployment. This is specific to Sun's app server, but such features are supported in many other commercial applications servers as well.
Hope you found this example useful.
More blogs about glassfish glassfish persistence persistence
Great introduction to Java EE 5. I ran into a very minor problem when I tried to launch the client via Java Webstart. It seems that appclient.jar is a reserved name in Glassfish so the app couldn't be started. Changing the name of the client jar file to client.jar in build.xml allowed me to run the client from JWS with the following command line
javaws
Posted by: djcarson on December 21, 2005 at 11:58 AM
It's great that you are using the Java Web Start support. Sorry about the inconvenience with the client jar file name.
I'll want to take a closer look into this, but for the moment there is a second workaround in addition to the one you found.
You could also specify an explicit path for launching with Java Web Start in the sun-application-client.xml descriptor for the app client. As the last subelement of <sun-application-client>, you can add the <java-web-start-access> element. It can have as a child the element <context-root>...</context-root> which you can use to specify the path which users will use to launch the app client.
For example, if you added this
<sun-application-client>
...
<java-web-start-access>
<context-root>myBlog/blogClient</context-root>
</java-web-start-access>
</sun-application-client>
then users could launch using the URL
This and the technique you described are certainly a workarounds at best, and ideally GlassFish would not restrict the name of the app client jar file this way.
Posted by: tjquinn on December 21, 2005 at 11:03 PM
Java Persistence API spec is still changing. My original posting was written before the proposed final draft spec came out. In the proposed final draft, there were quite a few changes and I have now updated this blog accordingly. The only change needed was removal of AccessMode fron @Entity. Now this example works with latest build of GlassFish. I don't anticipate any further changes in the spec that can affect this example.
Secondly, earlier I was using properties in persistence.xml to specify Java2DB mode. Now I am using --createtable options in deploy targetin build.xml.
Thanks,
Sahoo
Posted by: ss141213 on February 03, 2006 at 07:46 AM
The build.xml is still using --password option during asadmin deploy. This option has been removed. I have not got a chance to fix my blog yet. In case, you encounter this error, please change build.xml to use --passwordfile option.
Sahoo
Posted by: ss141213 on February 27, 2006 at 11:15 PM
Wonderful sample! works just fine. But I have a question. You said the lib directory is intended to share jar files with other modules, right? I'm trying to write a Web Service (following some samples I've seen over the web, anotating a class with @Stateless and @WebService). If I have a method with a parameter or return types defined in other jar file (inside the lib directory) I can't deploy the application. Could you say what I'm doing wrong?
Thanks a lot, samflores.
Posted by: samflores on March 22, 2006 at 12:08 PM
Hi samflores,
That's exactly how it is supposed to work.
You put all the interface classes like return types, parameter types
in a jar file in EAR lib directory so they are available to both the component
as well its clients.
You could be doing something wrong. Try running
$glassfish_home/bin/verifier app.ear.
That might help you diagnosing packaging issues.
If that did not help and you want me to take a further look at your problem, please feel free to file a bug in issue tracker
with a test case and assign it to me (i.e. ss141213).
I will get back to you.
Thanks,
Sahoo
Posted by: ss141213 on March 22, 2006 at 07:27 PM
IMPORTANT: Please Read
When I wrote this sample, version attribute was optional and hence I had not
specified it in the persistence.xml. Because of a recent change in spec,
version is now mandatory as annouced here.
So if you are using the latest GlassFish builds, then the sample may not
deploy for you. It's a trivial fix, I have not got time to fix it(I will do it soon).
So, in the mean while, after downloading the sample, please update
persistence.xml with version="1.0" at the root tag.
Sorry for any inconvenience,
Posted by: ss141213 on March 22, 2006 at 07:38 PM
IMPORTANT
On 20060323, I updated the sample. The changes are:
1. it now uses version attribute in persistence.xml. (see my earlier comment on this regard)
2. updated build.xml to use passwordfile option.
3. fixed build.xml so that interfaces classes are no more packaged inside ejbs.jar.
Thanks,
Sahoo
Posted by: ss141213 on March 23, 2006 at 07:25 AM
Sahoo - Great example; it helped me through some development issues I was having the last week or so. I now have my web->ejb->entity->mysql app running and just wanted to say thanks. Keep up the great work.
Posted by: roccsolid on September 30, 2006 at 09:28 AM
Hi,
I've got a question regarding the Persistence Context propagation.
If I were to access a slsb using its local interface from a Servlet, one of its method handing me some entity, would I then be able to navigate its object graph lazily in that servlet?
More interesting to me, is how the Persitence Context is propagated through out the request. Let say I'd get a instance of that slsb injected in some unmanaged pojo, a struts action, using Spring. While the RequestProcessor servlet would be living in a 2.5 spec container, what about the persistence context propagation?
I've been using Hibernate for web application developement for quite some time and there are several approaches on how to keep the session (Persistence Context) open all though the request/response lifecycle. Having used EJB3 on a project, I know that the PersistenceContext gets propagated through out different slsb too. What about bringing Servlet in the picture or even a web framework not benifiting from the managed beans injection we'd get from JSF?
Thanks,
Alexander Snaps
Posted by: greenhorn on October 24, 2006 at 07:40 PM
Hi Alexander,
I just blogged about Persistence Context Propagation. Does that blog answer your question? Feel free to comment there...
Posted by: ss141213 on October 27, 2006 at 11:05 AM
Hi, I haven't managed to user the @EJB injection in a servlet.
I have an ear with 4 archives: common, entities, ejb, war. Naturally, the ejb is in the jar called ejb and the servlet is in the war file. In case this is relevant, I am using Maven to built a skinny WAR by setting its classpath to be all the other archives in the ear (using the WAR's MANIFEST.MF's Class-Path entry).
I'm deploying this ear in JBoss 4.0.5 installed with ejb3, obviously.
I annotated the local interface (AuthenticationLocal) with "@Local", and annotated with "@Stateless" the bean implementation called AuthenticationBean (which implements AuthenticationLocal).
I declared an annotated private member in the servlet in the following way:
@EJB private AuthenticationLocal authentication;
This field stays null when I try using is (and I'm getting NullPointerException).
Is there some kind of naming convention I'm not following? I tried changing the names to match the convention implicitly used here.
I will emphasize that when I try using JBoss' specific annotation for local binding the following way: "@LocalBinding(jndiBinding = "ejb/AuthenticationBean")", I can access this ejb and invoke methods in it from the servlet using:
new InitialContext().lookup("ejb/AuthenticationBean")
This is the only place I managed to find an example of an @EJB injected servlet, just that I can't get this to work... Any help anyone?
Thanks, Amit
Posted by: amitkasher on November 23, 2006 at 01:03 AM
Hi Amit,
I am no JBoss expert. It looks to me that the version of JBoss app server you are using may not be supporting @EJB in a Servlet. Have you tried deploying your application to GlassFish which is a fully compliant, production quality Java EE 5 application server? That will easily tell you whether your app is correct or not.
Thanks,
Sahoo
Posted by: ss141213 on November 23, 2006 at 07:06 AM
Thanks Sahoo,
After a lot of research it seems that your assumption is accurate. JBoss 4.0.5 actually doesn't support resource injection into servlets. JBoss 5Beta1 does, but it has a bugs so I'll just wait for its GA.
I'm using some hibernate stuff (validator, schema generation annotations) so this will make it more difficult to use GlassFish. I'll give it a try anyway (hopefully I can just put the hibernate annotations jars in GlassFish's classpath).
Thanks again,
Amit Kasher
Posted by: amitkasher on December 12, 2006 at 09:00 AM
Hi Amit,
Take a look at the following blog that shows how easy it is to use Hibernate JPA persistence provider in GlassFish:
Using Hibernate JPA provider in GlassFish
It is as simple as copying necessary Hibernate jar files into $GF/domains/domain1/lib and restarting the jar. I suggest you copy all the Hibernate jar files, i.e Hibernate entity manager jars, Hibernate anotations jar and Hibernate core jar files as well as their dependencies. Hope this helps. Any problems? use GlassFish forum.
Thanks,
Sahoo
Posted by: ss141213 on December 12, 2006 at 07:09 PM
I am trying to run an ejb3 application using javaws from the command line. Application is deployed on jboss4.2.1. However I recieve an exception. This exception is thrown when a session bean is looked up and casted into corresponding session bean class.
However when i run the application directly from command line using java.exe(as i have code on my machine), the application runs perfectly fine. Can you tell me how to resolve this issue. Is it because of class loader or some policy? If so then please tell me the way out.
The exception stack trace is :
class javax.naming.Reference
java.lang.ClassCastException: javax.naming.Reference
at com.nwi.asa.common.communication.CommDelegate.createSession(CommDelegate.java:54)
at com.nwi.asa.common.communication.CommDelegate.)
Posted by: awssul on August 24, 2007 at 03:49 PM
It's great that you are using the Java Web Start support. Sorry about the inconvenience with the client jar file name.
I'll want to take a closer look into this, but for the moment there is a second workaround in addition to the one you found. 搬屋公司-交友-迷你倉
Posted by: winrelocation on October 30, 2007 at 12:45 AM | http://weblogs.java.net/blog/ss141213/archive/2005/12/using_java_pers.html | crawl-002 | refinedweb | 1,940 | 65.52 |
#include #include using namespace std; struct Book { char title[1024]; // Book name int id; // Book id or ISBN number float price; // Book price struct Book* next; } *COLLECTION = NULL; //-- Forward Declaration --// void menu(); void branching(char option); void insertion(); void printall(); struct Book* search(); void deletion(); void quit(struct Book* HEAD); int main() { char ch; cout << "\n\nWelcome to CSE240: Bookstore\n"; do { menu(); ch = tolower(getchar()); // read a char, convert to lower case cin.ignore(); branching(ch); } while (ch != 'q'); return 0; } void menu() { cout << "\nMenu Options\n"; cout << "------------------------------------------------------\n"; cout << "i: Insert a book\n"; cout << "d: Delete a book\n"; cout << "s: Search a book\n"; cout << "p: Review your list\n"; cout << "q: Quit\n"; cout << "\n\nPlease enter a choice (i, d, s, p, or q) ---> "; } void branching(char option) { switch(option) { case 'i': insertion(); break; case 'd': deletion(); break; case 's': search(); break; case 'p': printall(); break; case 'q': quit(COLLECTION); COLLECTION = NULL; break; default: cout << "\nError: Invalid Input. Please try again..."; break; } } void insertion() { // add code to insert a new book into the COLLECTION linked list. // HINT: You can insert a new book at the beginning of the linked list } struct Book* search() { // add code to search for an existing book in the COLLECTION linked-list // HINT: If no book matches the tile return a error messag return NULL; } void deletion() { // add code to the deletion method. You must call "delete" to remove the object from the heap. } void printall() { // Add code to print the book collection. (HINT: You will need to use a loop.) } void quit(struct Book* HEAD) { // Add code to delete the objects/books from the lniked-list. // HINT: Refer to the slides in the homework assignmetn } Add code to the "insertion" method to insert a book into the COLLECTION linked-list. The book can be insert at the beginning of the linked-list. You are responsible for generating the book ID. The ID must be unique for each book. [10 points] Add code to the "printall" method to display each book in the COLLECTION linked-list. Print exactly two decimal places for price. (Hint: you may need the functions setf and precision.) [10 points] Expected output example: {Book Id} : {Book Title} for {Book Price}. 0: Introduction to Programming Languages for $104.99. 1: A Guide to Extreme Programming for $10000.00. Add code to the "search" method to find a book (by its title) in the COLLECTION linked-list. The method will print the book ID and the price. It will then return the previous book's reference. (Hint: Don't forget to consider what happens if a book with the given title doesn't exist.) [10 points] Add code to the "deletion" method to delete a book from the COLLECTION linked-list based on an ID. You will need to use the delete function to remove it from the heap memory. (Hint: Don't forget to consider what happens if a book with the given title doesn't exist.) [10points] Add code to the "quit" method to delete the COLLECTION linked-list from the heap memory. Please refer to the attached powerpoint slides for more information. [10 points] | http://www.chegg.com/homework-help/questions-and-answers/include-include-using-namespace-std-struct-book-char-title-1024-book-name-int-id-book-id-i-q3702404 | CC-MAIN-2015-27 | refinedweb | 529 | 79.6 |
.
For this tutorial we will be using the GNU Image Manipulation Program in conjunction with Python. We are working on an Ubuntu 9.04 system but because these are cross-platform tools you should be able to do this on any OS.
What the script does:
The Python script takes one or more 1-bit color palette indexed BMP images, cuts out the header and any unused column data, and outputs a header file with the information stored in a one dimensional array in PROGMEM. This data can then be read out of the array and manipulated in the AVR code for use in whatever format you need for your display. This can be used for generating fonts, or converting larger images.
Generate the BMP files:
Open the GIMP and create a new file with the dimensions that you require. Height is up to you, but the width should be in multiples of 8 to correspond to the 8-bit wide storage scheme. In this case, we’re interested in generating a set of fonts that will display in a 24×30 pixel area.
Using the font tool, select your desired font and add your character. Adjust the size and location until if fills the canvas. You should make sure that the Antialiasing checkbox of the font tool is not selected.
BMP files are saved from bottom to top, we need to invert the image for our purposes. Do this by clicking the Image menu, go to Transform, and select “Flip Vertically”. We also need to make this an indexed image. To do so, click on the Image menu at the top, go to Mode and select “Indexed…”. From this menu, choose “Use black and white(1-bit) palette”. Now save the file as a BMP image. In our case, we saved it as 4.bmp. Repeat this for each character you wish to include in your new font header file.
Use the script:
Download our bmp2header.py file.
$ python bmp2header.py *.bmp Please enter how many bytes (8-bits) wide the image data needs to be: 3 Generating header file with a byte width of: 3 bytes Successfully generated: my_header.h
Run the file, with your BMP images as the command line arguments. You will be asked to input the desired column width for the images. Our example image is 24 pixels wide so we want header data to be 3 bytes wide (24-pixels/8-bits = 3 bytes). You can see from the output that my_header.h was successfully created by the script.
Here are the contents of that file (in this case, data for the ‘4’ character):
#include <avr/pgmspace.h> static const char PROGMEM my_header[]={ //4 0x1f, 0x00,81, 0xfc, 0x3f, 0x81, 0xfc, 0x3f, 0x81, 0xfc, 0x3f, 0xff, 0xfc, 0x3f, 0xff, 0xfc, 0x3f, 0xff, 0xfc, 0x3f, 0xff, 0xfc, 0x00, 0x01, 0xfc, 0x00, 0x01, 0xfc, 0x00, 0x01, 0xfc, 0x00, 0x01, 0xfc, 0x00, 0x01, 0xfc, 0x00, 0x01, 0xfc };
In the header file, each BMP that is processed by the script will have its filename appended as a comment before the HEX output. Our data for 4.bmp is displayed in 3 columns of bytes with 30 rows. This matches up with the 24×30 aspect ratio we were looking for. If you have an output much larger than this, you either didn’t used a 1-bit indexed image, or something when wrong when the script asked you to input your column width.
Accessing data from the header file:
Covering how to use this header data is beyond the scope of this tutorial. Below is the code we used to write to the display in the image at the top of this article. Our screen is written to by declaring the area we want to write to, then sending a stream of bit data for that area. We provide this for reference purposes only:
#include my_header.h void Other_Num(unsigned char num, unsigned char x, unsigned char y) { //Setup screen area for writing: LCD_Out(0x2A, 1); LCD_Out(x, 0); LCD_Out(x+23, 0); LCD_Out(0x2B, 1); LCD_Out(y, 0); LCD_Out(y+29, 0); LCD_Out(0x2C, 1); unsigned char temp; for (unsigned char i=0; i<90; i++) //Read one column of char at a time { temp = pgm_read_byte((char *)((int)my_header + (i + (90*num)))); //Get column from progmem for (unsigned char k=0; k<8; k++) { if (temp & 1<<(7-k)) LCD_Out(blue, 0); else LCD_Out(white, 0); } } }
Conclusion
Using this method make generating font sets quit a bit easier. We were able to generate five different numeric sets (0-9) in about 45 mintues. We hope this helps with your next project. Don’t forget to include pictures of your new fonts in the comments.
19 thoughts on “How to generate font and picture header files”
Just curious, does anyone use the GIMP option to export C code/headers? If so, what are your thoughts on these two methods?
Jon, I use GIMP option to export C code/headers. It’s more useful than anything because unlike anything, GIMP and C compiler are always at hand. The pixel packing the one that’s required, but writing a code that rearranges a few bits is faster than finding the right tool that does it out of the box.
Err… I meant “…the pixel packing isn’t always the one that’s required…”
I’ve never really looked at how all the standard file formats are structured so I never really paid attention to what the convention was, but I thought it was odd that the data was packed to a row of 8 columns. When I did my own stuff like this I’d structure it with packed columns, so that you ended up with heights that were a multiple of 8. I figured that was more intuitive especially considering that’s how most LCD drivers are set up, but admittedly I can see some advantages to both.
I used the “LCD Font Maker” but it still has some issues that irritated me. It was a useful tool though when I had to change LCD but wanted to use the old fonts, the controller on the new LCD took data in funky format also. Coordinates ware from bottom left to top right and ware offset a few pixel’s so bottom 0,0 was infact 4,2. In the end I still ended up touching up the fonts manually editing the hex tables. Specially when your doing gray-scale. It’s just impossible to truly represent what it will look like on the LCD looking at CRT monitor or even another LCD monitor. It might look ok on the monitor and then proceeds to look like @$$ on the LCD.
This is good but I think ImageMagick or GraphicsMagick can be made to do this and either will handle just about any image format. And with these, you can rasterise any font installed on your system. You might still need a bit of script to format it neatly as a header/.asm table and to pack your paletized colors, but you won’t be limited to just bmp’s.
For Windows, a program called The Dot Factory does something very similar to this.
Thanks for this detailed tutorial!
Microchip provides a nice little tool in his Graphics Library that converts normal TTF fonts to C arrays or even assembler.
You just have to decide the height and then doing copy&paste.
@Jon
@svofski
Indeed. GIMP works perfectly for me.
I don’t know if what you’re programming on has object-oriented capabilities, but static variable arrays are the devil.
I’ll get on this as soon as I can get my LCD to display proper colours :(
this plugin is much better :-)
Since the posts asks for pics I figured I’d post some samples of mine (using a different process however).
That’s blown up to double size, 4 fonts in total (the last two are different sizes of the same font).
Have you ever heard about XPM? You can include it into the C code.
gimp supports it, just click “save as” and type image.xpm to output filename form…
For those with a Windows box, FontMaker is a free download. It does a nice job converting TrueType fonts and/or bitmaps (including grids of characters) in AVR-GCC C headers:
Anyone know if a utility exists that can output a 16-bit rgb (5-6-5 format) hex file from a bmp image?
The only utilities I’ve been able to find either output a c header (not a binary hex file suitable for flashing), or they don’t support 5-6-5 rgb!
An export procedure for the Nokia 3310 LCD:
This is a very late reply to this thread but it might help someone….checkout this Python plug-in for the gimp:
It creates a C header for a gimp image and its quite easy to modify this to output any format you like. | http://hackaday.com/2009/09/29/how-to-generate-font-and-picture-header-files/ | CC-MAIN-2016-44 | refinedweb | 1,499 | 69.72 |
What I want to do - transform my pure Python code into Cython.
Pure Python code:
def conflicts(list1,list2): numIt = 10 for i in list1: for j in list2: if i == j and i < numIt: return True return False conflicts([1,2,3], [6,9,8])
My Cython code so far:
cdef char conflicts(int [] list1,int [] list2): cdef int numIt = 10 for i in list1: for j in list2: if i == j and i < numIt: return True return False conflicts([1,2,3], [6,9,8])
Since I am completely new to Cython (and not really a pro in Python) I would like to get some feedback about my transformation. Am I doing the right thing? Is there anything else I should do in order to make the function even faster?
Update:
Does anyone know how i can add types in the header of the function for the input (list1, list2)? I tried "int [:]" which compiles without error but when i try to call the function with two lists i get the message "TypeError: 'list' does not have the buffer interface". | https://www.howtobuildsoftware.com/index.php/how-do/7IG/python-performance-optimization-cython-cython-simple-function-with-2-lists-what-is-the-fastest-way | CC-MAIN-2020-05 | refinedweb | 182 | 68.44 |
Overview
In addition to libraries, Rosella provides some helpful utility programs to help with common programming and maintenance tasks. These programs are included with the Rosella installation, but may need to be added separately to your system search path.
Utilities
rosella_test_template
The
rosella_test_template utility is used to create test-related files quickly and easily. The utility can be used to create test files and test harnesses in the language of your choice. Currently the languages supported are winxed and nqp, but other templates could be added in the future.
To create a new harness, you would do something like this:
# To create a harness written in winxed rosella_test_template harness winxed t/ > t/harness # To create a harness written in NQP-rx rosella_test_template harness nqp t/ > t/harness
By default the generated harness will execute all test files in the “t” directory recursively. The default test file type is “Automatic”. See the Harness documentation for more details.
The harness generated in Winxed and the one generated in NQP may differ in other functionality, such as command-line arguments handled or other details. These are just rough skeletons, and you should proof-read the generated code to make sure it does what you need it to do.
This utility can also be used to create a new skeleton test file for a class in an existing bytecode file. To create a test for your class, you would write:
# In Winxed: rosella_test_template test winxed mylib.pbc Path.To.Class > class.t # In NQP-rx: rosella_test_template test nqp mylib.pbc Path.To.Class > class.t
The skeleton test file will be generated which uses Rosella Test to provide a default test method for every method in the target class. Again, please proof-read the generated code and tweak the generated logic to meaningfully test your code.
rosella_test_all_lib
The
rosella_test_all_lib utility is like
rosella_test_template except it creates an entire test suite for all classes and namespaces in a given bytecode library. It creates one test file (using the same template and logic as ”
rosella_test_template test ...”) for every class and for every namespace in the bytecode which contains non-anonymous functions.
# In Winxed rosella_test_all_lib winxed mylib.pbc t/mylib # In NQP-rx rosella_test_all_lib nqp mylib.pbc t/mylib
rosella_harness
The
rosella_harness utility is a default harness which provides basic behavior. It automatically executes all tests in the
t/ directory, or tests in any directories passed on the commandline. This can be useful for projects which have a simple test suite and only need basic behavior from the harness. All tests are run according to the
#! “shebang” line at the beginning of the file. If the file does not contain this line, the test will be marked as having not been run.
rosella_harness rosella_harness t/foo t/bar t/baz
winxed_repl
The
winxed_repl utilitiy is a simple command-line REPL utility for experimenting with Winxed code. This utility is experimental.
winxed_mk_header
The
winxed_mk_header utility is used to automatically generate an includable Winxed header file with forward declarations for all classes and public functions in a bytecode file.
winxed_mk_header mylib.pbc > mylib.include.winxed | http://whiteknight.github.io/Rosella/libraries/utilities.html | CC-MAIN-2019-30 | refinedweb | 516 | 54.42 |
Learn Webpack in 15 Minutes
Build tools have become an integral part of web development, mainly due to the ever-increasing complexity of JavaScript apps. Bundlers allow us to package, compile, and organize the many assets and libraries needed for a modern web project.
In this tutorial we will take a look at webpack, a powerful open-source bundler and preprocessor that can handle a huge variety of different tasks. We'll show you how to write modules, bundle code, and use some of the loader plugins. The tutorial is designed for total beginners to webpack, but having some JavaScript knowledge is advised.
Why webpack?
Much like any other aspect of web development, there isn't a standard for which build tool to use. Right now, developers have to choose between webpack, Gulp, Browserify, NPM scripts, Grunt, and like 10 others. There are many in-depth comparisons out there, but all of these tools are very similar, so most of the time it comes down to personal preference and what project you are working on.
Here are some pros and cons to help you decide whether webpack is the tool for you:
Pros:
- Great for working with singe-page apps
- Accepts both
require()and
importmodule syntaxes
- Allows for very advanced code splitting
- Hot Reload for quicker development with React, Vue.js and similar frameworks
- Мost popular build tool according to the 2016 JavaScript survey
Cons:
- Not suitable for beginners in web development
- Working with CSS files, images, and other non-JS resources is confusing at first
- Documentation could be better
- Changes a lot, even most 2016 tutorials are already outdated
1. Installation
The easiest way to install webpack is by using a package manager. We will go with npm but feel free to use Yarn or another hip alternative. In both cases you need to have Node.js on your machine and a package.json ready to go.
It is preferred to install it locally (without the
-g tag). This will make sure everyone working on your project has the same version of webpack.
npm install webpack --save-dev
Once we have it installed, it's best to run webpack via a Node.js script. Add these lines to your package.json:
//... "scripts": { "build": "webpack -p", "watch": "webpack --watch" }, //...
Now by calling
npm run build from the terminal we can make webpack bundle our files (the
-p option stands for production and minifies the bundled code). Running
npm run watch will start a process that automatically bundles our files when any of them change.
The last part of the setup is to tell webpack which files to bundle up. The recommended way to do this is by creating a config file.
2. Webpack Config File
Here we will look at the config file in its most basic form but don't let that fool you - the webpack config file is quite powerful, varies a lot from project to project, and can become super complex in some cases.
In the root directory of your project add a file called webpack.config.js.
webpack.config.js
var path = require('path'); module.exports = { entry: './assets/js/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } };
The entry option tells webpack which is our main JavaScript file. There are many different strategies for configuring entry points but in most cases a single entry is enough.
In output we specify the name and path of our bundle. After running webpack we will have all our JavaScript in a file called bundle.js. This is the only script file that we will link in our HTML:
<script src="./dist/bundle.js"></script>
This setup should be enough to get us started. Later we will add some more stuff to it, but first let's see how modules work.
3. Webpack Modules
Webpack provides multiple ways to work with modules, and most of the time you are free to go with whichever one you like. For this tutorial we will use the ES6
import syntax.
We want to add a module that greets our users. We create a file called greeter.js and make it export a simple function:
greeter.js
function greet() { console.log('Have a great day!'); }; export default greet;
To use this module, we have to import it and call it in our entry point, which if you look back at the config file is index.js.
index.js
import greet from './greeter.js'; console.log("I'm the entry point"); greet();
Now when we run the bundler with
npm run build, and open our HTML in the browser, we see this:
Our entry point and our greeter module were compiled into one file called bundle.js and it was executed by the browser. Here is a simple flow chart of what's happening so far:
4. Requiring Libraries
We want our app to specify which day of the week it is when it greets users. To do so we will use moment.js by directly importing it into our greeter module.
First we need to install the library via npm:
npm install moment --save
Then in our greeting module, we simply import the library exactly the same way we imported local modules in the previous point:
greeter.js
import moment from 'moment'; function greet() { var day = moment().format('dddd'); console.log('Have a great ' + day + '!'); }; export default greet;
After we bundle up again to apply the changes, in the browser console we will have the following messages:
Our flow diagram now looks like this:
Note: There are other, more advanced techniques for including libraries but they are outside the scope of this article. You can read more about them here.
5. Loaders
Loaders are webpack's way to execute tasks during bundling and pre- or post-process the files in some manner. For example, they can compile TypeScript, load Vue.js components, render templates, and much more. Most loaders are written by the community, for a list of popular loaders go here.
Let's say we want to add a linter to our project that checks our JS code for errors. We can do so by including the JSHint loader, which will catch all kinds of bad practices and code smells.
First we need to install both JSHint and the webpack JSHint loader:
npm install jshint jshint-loader --save-dev
Afterwords, we are going to add a few lines to our webpack config file. This will initialize the loader, tell it what type of files to check, and which files to ignore.
webpack.config.js
var path = require('path'); module.exports = { entry: './assets/js/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, // Add the JSHint loader module: { rules: [{ test: /\.js$/, // Run the loader on all .js files exclude: /node_modules/, // ignore all files in the node_modules folder use: 'jshint-loader' }] } };
Now when webpack is started, it will show us a list of warnings in the terminal (which we will ignore):
Since moment.js is located in the node_modules folder, it won't be linted by the JSHint loader:
Further Reading
This concludes our introduction to webpack! Since this is a lesson for beginners, we tried to cover only the most useful and must-know concepts of webpack. We hope the tutorial has been helpful, not too confusing, and within the 15 minute limit from the title.
In the near future, we are planning to add a second part to this tutorial, explaining how to work with CSS modules and other more-advanced features. In the meantime, if you want to learn more about webpack (and there is a lot more) we recommend checking out these awesome resources:
- webpack.js.org - The official website for the project, lots of guides and docs available there.
- Awesome webpack - Curated list of webpack resources.
- Webpack 2 - A full tutorial - Almost two-hours-long free video tutorial.
- Webpack Examples - List of various webpack configurations.
Presenting Bootstrap Studio
a revolutionary tool that developers and designers use to create
beautiful interfaces using the Bootstrap Framework.
This is a great intro to Webpack. One thing I didn't understand is why you use the
--saveflag :
npm install jshint jshint-loader --save
Isn't jshint a dev-dependency?
That's a fair point, JSHint is better off as a devDependency. Webpack itself should also be a devDependency if it's going to be used only as a build tool.
Good job man. There are a few updated and simple Webpack 2 tutorials out there. | https://tutorialzine.com/2017/04/learn-webpack-in-15-minutes | CC-MAIN-2017-34 | refinedweb | 1,416 | 64.2 |
Thread synchronization may be defined as a method with the help of which we can be assured that two or more concurrent threads are not simultaneously accessing the program segment known as critical section. On the other hand, as we know that critical section is the part of the program where the shared resource is accessed. Hence we can say that synchronization is the process of making sure that two or more threads do not interface with each other by accessing the resources at the same time. The diagram below shows that four threads trying to access the critical section of a program at the same time.
To make it clearer, suppose two or more threads trying to add the object in the list at the same time. This act cannot lead to a successful end because either it will drop one or all the objects or it will completely corrupt the state of the list. Here the role of the synchronization is that only one thread at a time can access the list.
We might encounter issues while implementing concurrent programming or applying synchronizing primitives. In this section, we will discuss two major issues. The issues are −
This is one of the major issues in concurrent programming. Concurrent access to shared resources can lead to race condition. A race condition may be defined as the occurring of a condition when two or more threads can access shared data and then try to change its value at the same time. Due to this, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes.
Consider this example to understand the concept of race condition −
Step 1 − In this step, we need to import threading module −
import threading
Step 2 − Now, define a global variable, say x, along with its value as 0 −
x = 0
Step 3 − Now, we need to define the increment_global() function, which will do the increment by 1 in this global function x −
def increment_global(): global x x += 1
Step 4 − In this step, we will define the taskofThread() function, which will call the increment_global() function for a specified number of times; for our example it is 50000 times −
def taskofThread(): for _ in range(50000): increment_global()
Step 5 − Now, define the main() function in which threads t1 and t2 are created. Both will be started with the help of the start() function and wait until they finish their jobs with the help of join() function.
def main(): global x x = 0 t1 = threading.Thread(target= taskofThread) t2 = threading.Thread(target= taskofThread) t1.start() t2.start() t1.join() t2.join()
Step 6 − Now, we need to give the range as in for how many iterations we want to call the main() function. Here, we are calling it for 5 times.
if __name__ == "__main__": for i in range(5): main() print("x = {1} after Iteration {0}".format(i,x))
In the output shown below, we can see the effect of race condition as the value of x after each iteration is expected 100000. However, there is lots of variation in the value. This is due to the concurrent access of threads to the shared global variable x.
x = 100000 after Iteration 0 x = 54034 after Iteration 1 x = 80230 after Iteration 2 x = 93602 after Iteration 3 x = 93289 after Iteration 4
As we have seen the effect of race condition in the above program, we need a synchronization tool, which can deal with race condition between multiple threads. In Python, the <threading> module provides Lock class to deal with race condition. Further, the Lock class provides different methods with the help of which we can handle race condition between multiple threads. The methods are described below −
This method is used to acquire, i.e., blocking a lock. A lock can be blocking or non-blocking depending upon the following true or false value −
With value set to True − If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked.
With value set to False − If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked.
This method is used to release a lock. Following are a few important tasks related to this method −
If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked.
It will raise a ThreadError if lock is already unlocked.
Now, we can rewrite the above program with the lock class and its methods to avoid the race condition. We need to define the taskofThread() method with lock argument and then need to use the acquire() and release() methods for blocking and non-blocking of locks to avoid race condition.
Following is example of python program to understand the concept of locks for dealing with race condition −
import threading x = 0 following output shows that the effect of race condition is neglected; as the value of x, after each & every iteration, is now 100000, which is as per the expectation of this program.
x = 100000 after Iteration 0 x = 100000 after Iteration 1 x = 100000 after Iteration 2 x = 100000 after Iteration 3 x = 100000 after Iteration 4
Deadlock is a troublesome issue one can face while designing the concurrent systems. We can illustrate this issue with the help of the dining philosopher problem as follows −
Edsger Dijkstra originally introduced the dining philosopher problem, one of the famous illustrations of one of the biggest problem of concurrent system called deadlock.
In this problem, there are five famous philosophers sitting at a round table eating some food from their bowls. There are five forks that can be used by the five philosophers to eat their food. However, the philosophers decide to use two forks at the same time to eat their food.
Now, there are two main conditions for the philosophers. First, each of the philosophers can be either in eating or in thinking state and second, they must first obtain both the forks, i.e., left and right. The issue arises when each of the five philosophers manages to pick the left fork at the same time. Now they all are waiting for the right fork to be free but they will never relinquish their fork until they have eaten their food and the right fork would never be available. Hence, there would be a deadlock state at the dinner table.
Now if we see, the same issue can arise in our concurrent systems too. The forks in the above example would be the system resources and each philosopher can represent the process, which is competing to get the resources.
The solution of this problem can be found by splitting the philosophers into two types – greedy philosophers and generous philosophers. Mainly a greedy philosopher will try to pick up the left fork and wait until it is there. He will then wait for the right fork to be there, pick it up, eat and then put it down. On the other hand, a generous philosopher will try to pick up the left fork and if it is not there, he will wait and try again after some time. If they get the left fork then they will try to get the right one. If they will get the right fork too then they will eat and release both the forks. However, if they will not get the right fork then they will release the left fork.
The following Python program will help us find a solution to the dining philosopher problem −
import threading import random import time class DiningPhilosopher(threading.Thread): running = True def __init__(self, xname, Leftfork, Rightfork): threading.Thread.__init__(self) self.name = xname self.Leftfork = Leftfork self.Rightfork = Rightfork def run(self): while(self.running): time.sleep( random.uniform(3,13)) print ('%s is hungry.' % self.name) self.dine() def dine(self): fork1, fork2 = self.Leftfork, self.Rightfork while self.running: fork1.acquire(True) locked = fork2.acquire(False) if locked: break fork1.release() print ('%s swaps forks' % self.name) fork1, fork2 = fork2, fork1 else: return self.dining() fork2.release() fork1.release() def dining(self): print ('%s starts eating '% self.name) time.sleep(random.uniform(1,10)) print ('%s finishes eating and now thinking.' % self.name) def Dining_Philosophers(): forks = [threading.Lock() for n in range(5)] philosopherNames = ('1st','2nd','3rd','4th', '5th') philosophers= [DiningPhilosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \ for i in range(5)] random.seed() DiningPhilosopher.running = True for p in philosophers: p.start() time.sleep(30) DiningPhilosopher.running = False print (" It is finishing.") Dining_Philosophers()
The above program uses the concept of greedy and generous philosophers. The program has also used the acquire() and release() methods of the Lock class of the <threading> module. We can see the solution in the following output −
4th is hungry. 4th starts eating 1st is hungry. 1st starts eating 2nd is hungry. 5th is hungry. 3rd is hungry. 1st finishes eating and now thinking.3rd swaps forks 2nd starts eating 4th finishes eating and now thinking. 3rd swaps forks5th starts eating 5th finishes eating and now thinking. 4th is hungry. 4th starts eating 2nd finishes eating and now thinking. 3rd swaps forks 1st is hungry. 1st starts eating 4th finishes eating and now thinking. 3rd starts eating 5th is hungry. 5th swaps forks 1st finishes eating and now thinking. 5th starts eating 2nd is hungry. 2nd swaps forks 4th is hungry. 5th finishes eating and now thinking. 3rd finishes eating and now thinking. 2nd starts eating 4th starts eating It is finishing. | https://www.tutorialspoint.com/concurrency_in_python/concurrency_in_python_synchronizing_threads.htm | CC-MAIN-2021-39 | refinedweb | 1,641 | 72.26 |
Hi!
Nearly my last question for today and this even more to the developers
of Cocoon...
Why does Cocoon provide not less than three different ways of handling
SQL queries?
- The Database Reader
- SQL Transformer
- ESQL Logicsheet
Ok, the Database Reader makes sense if you want to retrieve non-XML data.
But why not a schema/namespace/tag soup usable in XSP as well as a
transformer or generator?
Or a component being a generator as well as an transformer?
1st case: I want to retrieve XML data from a SQL database -> generator
passed with the src of the XML file with the query.
2nd case: I have an XSP containing SQL query tags -> transformer
replacing the query tags with their result
Questions, questions, questions ;-)
Florian
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@cocoon.apache.org
For additional commands, e-mail: users-help@cocoon.apache.org | http://mail-archives.apache.org/mod_mbox/cocoon-users/200609.mbox/%3C45087AB6.5060105@weitling.net%3E | CC-MAIN-2018-34 | refinedweb | 145 | 54.73 |
Strange syntax error
Discussion in 'Perl Misc' started by tseitlin
Strange syntax errorQu0ll, Apr 25, 2009, in forum: C++
- Replies:
- 1
- Views:
- 567
- James Kanze
- Apr 26, 2009
strange syntax error_wolf, Jun 4, 2010, in forum: Python
- Replies:
- 1
- Views:
- 515
- Jerry Hill
- Jun 4, 2010
Syntax bug, in 1.8.5? return not (some expr) <-- syntax error vsreturn (not (some expr)) <-- fineGood Night Moon, Jul 22, 2007, in forum: Ruby
- Replies:
- 9
- Views:
- 491
- Rick DeNatale
- Jul 25, 2007
Syntax error? What syntax error? Assignment fo default values?Mark Richards, Nov 18, 2007, in forum: Perl Misc
- Replies:
- 3
- Views:
- 453
- Tad McClellan
- Nov 18, 2007 | http://www.thecodingforums.com/threads/strange-syntax-error.898925/ | CC-MAIN-2016-07 | refinedweb | 107 | 67.28 |
printz Posted December 28, 2016 I've decided to post this now. You can now make UDMF maps in Eternity. Goodbye extradata! If you're on Windows, there is a Doom 2 / UDMF format configuration for Eternity available. How it works:It supports ACS. The ACS format is ZDoom, so you have access to all those goodies in ACS introduced by the ZDoom devs. The editor already provides that Nodes are built with ZDBSP (the only UDMF way). The editor already provides that. Linedef specials and sector specials use the same namespace as in ZDoom, so if you're used to ZDoom, you already have the same specials in mind. Some things to watch out for:GZDoom Builder has a hardcoded interface for UDMF. This means that you're gonna see the same huge dialog boxes as in ZDoom mode. Not all features will be available, but a lot of them are. This is of beta quality! This being said, please report any bugs and post any feature requests on this forum! Watch out for any errors in the GZDoom-Builder EE-UDMF configuration. For a large part, I copy-pasted data from other configurations. Hopefully whatever is important will work. Be sure to look in the last tab of object (thing, linedef etc.) properties! I've added a few features which aren't covered in the main tabs! Some stuff different/new from ZDoom:besides ZDoom, new linedef properties: lowerportal (boolean), upperportal (boolean), portal (integer), tranmap (string). sidedef offsetx and offsety can be set in floating-point, not just integer (unfortunately editors may not support this) sector heightfloor and heightceiling can be set in floating-point as well sector properties not (yet) in ZDoom: friction (integer value like a straight Boom linedef length), damage_endgodmode (bool), damage_exitlevel (bool), colormaptop (string), colormapmid (string), colormapbottom (string), floorid (int), ceilingid (int), attachfloor (int), attachceiling (int), portalfloor (int), portalceiling (int) Now. Most linedef specials are now doable in ways that ZDoom has already implemented. But here are some exceptions: 1. Portals. You don't use Sector_SetPortal (actually it's there, but not recommended). You use Portal_Define (300). Arguments are:portal ID: a unique portal number, independent on linedef or sector tags. portal type: select one from the dialog box. Same kinds as in Doom format. anchor line ID: only for anchored/two-way/linked portals. It's the line against which to make the portal reference. It must have the same orientation if it's a linked portal, but can be rotated if it's an anchored/two-way portal. Z parameter. Has different meanings depending on portal: - anchored or two-way: visual Z offset from this line to the anchor line. - linked: vertical displacement of linked portal from how it would normally appear. Useful for through-portal elevators. anchor is flipped? True/false value which should be true if the anchor linedef is flipped compared to current linedef. This Portal_Define special will just define a portal. How do you apply it?For sectors: select all sectors near the current linedef and set their "portalfloor" (or "portalceiling") property to the portal ID you just gave. Then, if it's a two-way or linked portal, select all sectors near the anchor linedef and set their "portalceiling" (or "portalfloor") property to the negative of the same ID. So if you have bottom layer connected to a top layer, and the portal setup (300) linedef is below, with a portal ID and line ID both set to 1, the anchor linedef placed above will have tag 1, and the sectors below will have "portalceiling" set to 1, while the sectors above will have "portalfloor" set to -1. For linedefs: select any linedef and set its "portal" property to the portal ID you defined. Again, if it's two-way or linked you can put negative portal ID for the opposite direction. Alternatively, just for linedefs, you now have Line_QuickPortal. It only supports linked (default) and two-way portals. How to use it: select two linedefs (of equal length and -- if linked -- equal orientation, but flipped), give them the same tag, and set them special #301. The first parameter, if 0, will result in a linked portal, and if 1 will result in a two-way non-interactive portal. Line portals will work with polyobjects. If the sector "inside" the polyobject is of different height than the area outside the polyobject, the portal linedefs will get lower and upper textures as set in the editor on the polyobject linedefs. Edge portals (new kind of portals). Currently these are veeeery beta. Anyway, they can be set up by applying the "Lower/upper part copies backsector's portal" flag to the linedef in the editor. It will only work if the linedef's backsector is a portal, and (if linked or two-way) its corresponding line from the other side will have "portal" set to the same value as the corresponding sector's plane "ceilingportal" or "floorportal". Another limitation: lines with portals must match in length. You no longer need to place buffer sectors behind linked portal lines. But if it somehow still gives you trouble, please mention it here, and in the meantime use buffer sectors anyway. 2. Attached surfaces: there is neither Sector_SetLink, nor Static_Init (static_init is only for MBF skies). Instead, the classic-format "set floor control, set ceiling control" specials has been replaced by the sector "floorid" and "ceilingid" properties. And the "attach floor to control" and "attach ceiling to control" specials have been replaced by "attachfloor" and "attachceiling" properties. And if you want to "attach mirror X to control", use negative ids in "attachfloor" or "attachceiling". I think this is enough for now. Any problem you have, please say it. There may be lots of them right now. 0 Share this post Link to post | https://www.doomworld.com/forum/topic/92202-you-can-now-make-udmf-maps-in-eternity/ | CC-MAIN-2019-04 | refinedweb | 971 | 65.01 |
Per below, I am trying initialize a sqlalchemy Mapped Class from a python dictionary that has extra keys. Is it possible to have the Mapped Class automatically ignore the extra keys instead of throwing an error? Likewise, can the Mapped Class have default values if the keys are not present?
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
my_example_user = {'id'=1, 'name'='john', 'extra_key'= 1234}
User(**my_example_user)
In short, define constructor which does not pass arguments up to its superclass:
class User(Base): # ... def __init__(self, **entries): # NOTE: Do not call superclass # (which is otherwise a default behaviour). #super(User, self).__init__(**entries) self.__dict__.update(entries)
I hit the same problem in transition from peewee which requires the opposite - to pass arguments to its superclass (and, therefore, constructor was already defined). So, I just tried commenting the line out and things start to work.
UPDATE
Also, make sure that
entries do not contain (and, therefore, overwrite) any meta field in
User class defined for SQLAlchemy defined, for example, those ORM relationships. It's kind of obvious (SQLAlchemy), but when mistake is made, it might not be easy to spot the problem. | https://codedump.io/share/XQWl8ARHNwPM/1/option-to-ignore-extra-keywords-in-an-sqlalchemy-mapped-class-constructor | CC-MAIN-2017-13 | refinedweb | 203 | 50.36 |
Sponsored by
- Intel
- HP
netmagTutorial
Build a portfolio with ExpressionEngine
We all need a place to show off our good work. Here, Ryan Irelan of mijingo.com talks you through the process of building a simple portfolio website using ExpressionEngine 2
This article first appeared in issue 214 of .net magazine - the world's best-selling magazine for web designers and developers..Install ExpressionEngine
To follow along with this tutorial, you’ll need a licensed copy of ExpressionEngine 2. If you don’t already have a copy, you can purchase it at the ExpressionEngine website.
EllisLab (the company behind ExpressionEngine) used to offer a free version but that is no longer the case with ExpressionEngine 2. There are several different licences available, including an inexpensive ‘Freelancer License’, which enables you to build a website (such as a portfolio) for your business.
Installing ExpressionEngine is very simple using the install wizard that comes with the application. For a guided tutorial on installing ExpressionEngine, I’ve created a free 16-minute video detailing everything you need to know on how to install ExpressionEngine.
If you’re brand new to ExpressionEngine and want to get up to speed quickly, I’ve also assembled an eight-episode series of training videos that walk you through creating an ExpressionEngine website from beginning to end. Learn more at mijingo.com.
Advertisement
Our sample site for this tutorial is Appleseed Design Studios, run by fictional designer Johnny Appleseed. The site is very basic. There are two different views: the homepage and the project view. The homepage is an overview of recent work, with a large recent project at the top and some secondary projects below.
All of the projects listed lead to their own project view page. The project view page contains a large screenshot of the website and a full write-up about the project, its challenges and goals. On the right-hand side of all pages is a small navigation leading to some secondary pages and client testimonials.
The first step in every ExpressionEngine site build is to create the channels to hold our content. Our website will have two channels to start with (we can always add more later as we enhance the site): projects and testimonials.
In the ExpressionEngine control panel, select the Admin button at the very top, hover over Channel Administration and then choose Channel Management. If you have a fresh install of ExpressionEngine 2, you shouldn’t see any channels listed. Click the grey Create New Channel button at the top right. We want our Full Channel Name to be Projects and the Channel Name set as projects. The lower-case name we’ll use in our templates when displaying the project entries using the Channel Entries tag pair.
Click Submit to create the channel. There is one more channel we need to create for the testimonials that are listed on the sidebar of the site. The process is the same as before; call the Full Channel Name Testimonials and the Channel Name testimonials.
With that done, you should now have two channels listed on the Channel Management page. One last thing to do: under Channel Management, choose Channel Preferences for each channel. Open the Channel Posting Preferences section and toggle Automatically turn URLs and email addresses into links? to No. This setting prevents ExpressionEngine from trying to create hyperlinks with URLs in our custom fields. Now we’re ready to create the custom fields that we’ll use to populate our channels with content.Publish forms
Publish forms in ExpressionEngine are made up of custom fields. These fields are what we use to enter the content for each our channel entries. Custom fields are bundled together into groups and a custom field group is assigned to a channel.
Select the Admin button again, hover over Channel Administration and then choose Custom Fields. Before we can create any custom fields we need to first create a custom field group. Click the grey button at the top right to create a new field group. The first field group we want to create is for the Projects channel. I like to keep my channel names and field group names the same, so it’s easy to know which channel belongs to which field group. Name the field group Projects and click Submit to create it.
Let’s take a look again at the site design to determine what kind of data we need to input for a project. Looking at the view.html template, we see that we need a title, a large image, some description text that explains what the project was and our work on it and, finally, a URL of the live website so we can link up the Visit the Site text. On our homepage we also need to display a shorter description text, so we’ll need a field for that. That's a total of five fields but we only have to create four because every channel entry in ExpressionEngine requires a title, so we get that field automatically.Upload destination
The first field we want to create is for the large screenshot image. Before we can create the custom field, however, we have to create an upload destination – a place where the images are uploaded to – for the screenshots. Click on the Content button at the top of the control panel and choose File Manager. On the right, under File Tools, choose Create New Upload Destination. Fill out the form, providing a descriptive name, valid server path (you can use the /images/uploads directory that already exists) and URL. The directory in which you want to save the images must already exist, so be sure to create it on your server first.
We want to set a few more preferences, including only allowing images and setting the Maximum Image Height to 400 and the Maximum Image Width to 600. With that set, click Submit to create the new file upload destination. Now we can get back to creating our custom fields.
Click Add/Edit Custom Fields to access the Projects field group. Click on Create a New Custom Field at the top right and you should see a form. There are several settings for each field. We’ll walk through this one together and then you’ll do the others on your own.
Custom fields in ExpressionEngine can be different field types. There are common field types such as input fields and textareas but you can even have a relationship field or file field for uploading files or images. In fact, for our project image we want to use the File field type. Select it from the list.
The field label is the form label that appears next to the field in the publish form. We want this name to be as clear as possible. Let’s use the label Project Image. The field name is how we’ll reference this field in our templates; this has to be a single word but can contain an underscore or dash. I prefer to namespace my fields by using a prefix with the name of the channel. This makes it easier to remember which fields belong to which channels. Input project_image for the field name.
For the field instructions, briefly describe what should be entered into this field. Every project has to have an image, so we want to set the field as required. We can leave the Field Display order set to 1 so the field will display first, after the title field.
There’s one more setting at the bottom under the Custom Field Options area. When using the File field, we have some control over the type of file that is allowed to be uploaded. The two settings are Any and Image. We want to restrict this field to only images, so we’ll choose Image. Press Submit to save the field. We still have to create the project description field, project snapshot field (for use in the Previous Work area of the homepage) and the website URL field. Here are some suggestions.
- Project Description
Field Type: Textarea
Field Label: Project Description
Field Name: project_description
Required: Yes
Textarea Rows: 12
- Project Snapshot
Field Type: Textarea
Field Label: Project Snapshot
Field Name: project_snapshot
Required: Yes
Textarea Rows: 3
- Project Website URL
Field Type: Input Field
Field Label: Project URL
Field Name: project_url
Required: No
Default Text Formatting: None
To use a custom field group it must be assigned to a Channel. Go to the Admin button, hover over Channel Administration and choose Channels. Next to the Projects channel, click on Edit Group Assignments. For the Field Group option, choose Projects and then click Update to complete the assignment. Now, if you choose the Content button, hover over Publish and choose Projects you should be able to see the publish form for our Projects channel. On your own, create the custom field group and custom fields for the Testimonials channel. We’ll use the Title field that ExpressionEngine automatically creates to store the name of the person giving the testimonial. We still need a field to hold the actual testimonial and one to hold a URL to the person who gave that testimonial.
Here are some suggestions for the other fields:
- Testimonial Copy
Field Type: Textarea
Field Label: Testimonial Copy
Field Name: testimonial_copy
Required: Yes
Textarea Rows: 6
Formatting: None
- Testimonial URL
Field Type: Input Field
Field Label: Testimonial URL
Field Name: testimonial_url
Required: Yes
Default Text Formatting: None
Using the Publish Form, go ahead and add four projects entries and a handful of testimonials to your site. We’ll need these entries in the next section when we start working on our templates.Templates
Before we can start bringing our site to life, we need to first create the templates. Click on the Design button at the top and then choose Template Manager under Templates.
Before we can create templates we need to first create a template group to house them. When possible I like to keep my template groups organised by channel. The first template group we need is for projects. Click on the New Group button to create a new template group. In keeping with our naming convention, we’ll name this template group Projects. Leave the rest of the form: Projects and Site. We need to create one template inside of Projects called view. This template will be what ExpressionEngine will use to show the individual project pages. The index template in the Site group will be our homepage.
With our setup complete we’re now ready to bring our site to life. To get started you’ll need to have the static templates (index.html and view.html) for this article at hand. Also, make sure you’ve uploaded the css directory containing the site CSS to your server.
Let’s start with the homepage. Copy the contents of the index.html into the index template in the site group. Load the site homepage in your web browser and you should see the static template. We’ll start with the large project at the top of the page. Find the div with the id of featured-site. The featured site is just the latest entry in our Project channel. We want to wrap a Channel Entries tag pair around everything inside of that div. Our code will look like this:
<div id="featured-site">{exp:channel:entries<img src="{project_image}"alt="{title}" /></a>{project_description}<p><a href="{title_permalink='projects/view'}">Read more about{title}...</a></p>{/exp:channel:entries}</div>
Next we want to light up the Previous Work area, which holds the three previous projects. We need to make sure we don’t include the project that’s at the top of the page. To do that we’ll use the offset parameter, which enables us to skip a set number of entries before displaying the ones we want.
Look at the static HTML: you’ll notice the last list item has a class of last. This is so the three-column layout will render properly. We only use one instance of the list item markup in our template because EE loops through and prints it out for each entry. To add the class to the last list item, we need a conditional to check the count of the current entry and the total results. We’ll compare them and if they match, we know it’s the last result. Our code should look like this:
<div id="previous-work"><h4>Previous Work</h4><ul>{exp:channel:<img src="{project_image}" /></a><p>{project_teaser}</p></li>{/exp:channel:entries}</ul></div>
Before we move to the project’s view template, let’s first light up the testimonials in the sidebar. The testimonials are marked up as a simple unordered list, so we need to wrap a single list item in our Channel Entries tag pair and pull in the last three testimonials. We have to use the dynamic="no" parameter so ExpressionEngine will display the entries regardless of the URL.
{exp:channel:entries<li>“<em>{testimonial_copy}</em>” —<{title}</a></li></ul>{/exp:channel:entries}
With that done we can now turn our attention to the project view template, which is located in our projects template group. Open up the static template view.html and copy the contents into the view template in ExpressionEngine.
We only need to add one bit of code to the view template to make it display the portfolio entry we clicked on from the homepage. ExpressionEngine will display the entry based on the URL so we can use this one template for every entry in our Project channel. The code for the main section of our page (inside the portfolio-site div) will look like this:
<div id="portfolio-site">{exp:channel:entries<img src="{project_image}" alt="{title}" /></a>{project_description}<p><a href="{project_url}">Visit the Site</a></p>{/exp:channel:entries}</div>
If you click on a project from the homepage of the site, it should load the view page for that project.
We have our basic portfolio site done but there are still some refinements you can do on your own. The three pages in the site navigation on the right side still need to be created. My suggestion is that you use the Pages module in ExpressionEngine to create those pages.
You also might want to break up your templates into reusable parts. The sidebar, the markup inside of the head tag and the footer are all reused on every page of the site. Create an embed template (expressionengine.com/user_guide/templates/embedding_templates.html) for each piece of the template so you only have to edit that markup once.Portfolio site examples
To inspire you and demonstrate what can be done with ExpressionEngine, let’s take a look at some examples of portfolio sites built on ExpressionEngine 2.
First is Philip Zaengle’s site for his freelance business (). He’s using a similar Recent Work area on the homepage to highlight his latest projects. Hover over each image to access more information about a project and click on View the Project to go to the project view page. To the right, on the project view page, Phillip details the technology and tasks involved in building the site.
Another excellent example of a portfolio site running ExpressionEngine 2 is Stookstudio, a Belgium-based web design and development studio run by Erwin Heiser. Navigate to the Work section of his website and you’ll see a portfolio of his work in the form of case studies. Each case study consists of a short description of the work involved and a series of screenshots.
For more examples of portfolio sites (and other websites) built with ExpressionEngine, visit the official showcase site Show-EE. Do you have something to share yourself? Submit it to Show-EE. | http://www.creativebloq.com/netmag/build-portfolio-expressionengine-8116846 | CC-MAIN-2014-42 | refinedweb | 2,648 | 63.19 |
Network Theory and Game of Thrones – A Perfect Combination
Want to share your content on python-bloggers? click here..
I will go about my exploration using two separate but related lines. The first will be a theoretical overview of each topic, and the second will be some implementation to see the concepts in action.
What is Network Theory?
Let’s get some basic definitions out of the way so everyone is on the same page and we can get to the fun bits.
Network Theory is the study of objects and their relationships with each other. This setup is often represented as a Graph which is just a collection of nodes and edges. Nodes are the individual objects in a network and Edges are the links representing the relationships between nodes.
Let’s see an example of this:
Undirected, Directed, and Weighted Graphs
I want to clarify something right in the beginning, a graph is one model of a given situation or system, that does not mean that the graph is the only model. What a node or edge represents is your choice (or informed by the data). In this case I can determine that each node is a person and an edge between them means that they are friends with each other. This is called an Undirected Graph.
Now consider the same situation but I tell you that it is possible for a person to be friends with someone who’s not friends with them, a one-sided friendship. This changes the situation and we need a different (more informative) model to represent it. Enter Directed Graphs:
This graph tells a completely different story from the first one. Now I give you even more information, I tell you how much a person values their friendship with the other person. This means there is a notion of edges being heavier or more important than other edges. This is represented using a Weighted graph which can be either directed or undirected.
Getting our feet wet
I will be using Python to implement the algorithms since I’m more comfortable with it and while learning a new topic I don’t want to be bogged down by language specifics.
Starting with the data, it is available on Andrew Beveridge’s GitHub. He (in his own words) does maths for fun, which I feel is a very appropriate mindset for me too. The data contains records of character interactions for all seasons (upto 7). I am only using the latest season’s data but I encourage you to explore the temporal information in the dataset. You could even create animations to show how the data has changed over time.
Let’s discuss the packages I will be using briefly.
Numpy,
pandas,
matplotlib (and
seaborn) are the usual companions in any Data Science project. I also use the
defaultdict data structure here.
The interesting stuff is in the last three lines. I will be using networkx for the general purpose graph handling, nxviz for to do the heavy lifting visualization tasks and the community package is used for one particular algorithm.
import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns from collections import defaultdict import networkx as nx import nxviz as nxv import community
A brief note about loading a graph dataset before we continue our exploration further. You might be familiar with common data formats like CSV or JSON which can be loaded as a dataframe object using the
pandas library. Graphs are a bit different in this regard since they’re usually saved as 2 separate files (one each for nodes and edges) which need to be loaded and combined into a graph object manually. The object is provided by the
networkx library but the exact mechanics of constructing the graph will be different for each dataset. I’ve added my code here for you to see.
def make_graph(nodes_df, edges_df): g = nx.Graph() for i,row in nodes.iterrows(): keys = row.index.tolist() values = row.values # The dict contains all attributes g.add_node(row['Id'], **dict(zip(keys,values))) for i,row in edges.iterrows(): keys = row.index.tolist() values = row.values g.add_edge(row['Source'], row['Target'], **dict(zip(keys,values))) return g nodes = pd.read_csv('data/got-s7-nodes_merged.csv', index_col=0) edges = pd.read_csv('data/got-s7-edges-filtered.csv') g = make_graph(nodes, edges)
Now let’s get to know the dataset. The network we have is for interactions between the characters on the show. These interactions are set up using the fan-made script of the show, and details can be seen in the original source. I’ve modified the data a bit by adding categorical variables to the nodes (gender, allegiance and culture). The nodes represent characters and have some attributes like their gender and house. The edges just have a ‘weight’ which is the number of interactions between the characters. You should always look at the original source of the data to understand how it was collected (remember this when you see interactions between characters who’ve never met in the show ).
We previously saw a very simple graph visualization (the one with the emoji faces). It’s called a node-link diagram. It’s very easy to read and get an overview of the data, but it gets very unwieldy for slightly bigger networks. Let’s see how our data turns out:
nx.draw(g, with_labels=True)
As expected, the nodes are shown as a jumbled mess with too much overlap and absolutely no thought given to the arrangement. The locations of the individual nodes can be tweaked using the
pos argument of the
nx.draw function, but it is too much work to manually figure out the best arrangement.
Can we do better? Yes we can. Let’s make a
Circos Plot using a very simple library called
nxviz. If you’ve ever used
seaborn for making plots, this is very similar to work with.
c = nxv.CircosPlot(g, node_color='Gender', node_grouping='Gender', edge_width=(edges['Weight'] / edges['Weight'].quantile(0.97)).tolist(), node_labels=True, node_label_layout='rotation', group_label_position="middle", group_label_offset=12, figsize=(8,8)) c.draw()
This plot has slightly less overall information (it shows fewer edges), but it is much easier to read. We can see patterns in the connectivity of different houses and the relative sizes of different houses.
Which gender has more interactions?
Let’s try to explore this data further. I want to see how males and females interact with each other. For this we can create a transformed version of our original graph. Which kind of graph would be most suitable to represent this information? We know we have two genders, and we want to model relationships between them. This means we have two nodes. We have four possible kinds of interactions:
- female -> female
- male -> male
- female -> male
- male -> female
which means we will have 4 edges, but note that these are directed edges and not undirected ones like in our original graph. So, I have created a weighted, directed graph with two nodes, one for each gender in the data.
The weights will be the the sum of all interactions in the data for that pair. This means the weight of the
female -> female edge will be the sum of weights for all edges in the original graph where the people on both ends were female.
I’ll introduce another useful graph concept here, the adjacency list. For a graph with $n$ nodes this is an $n \times n$ matrix where the entry at index $(u,v)$ contains the weight for the edge between nodes $u$ and $v$. For an unweighted graph this is a binary matrix, just containing 1 and 0 and is symmetric for undirected graphs (think about why this is).
I’ll plot this matrix as a heatmap and normalize the values because there are overall more males in the show’s cast.
counter = defaultdict(int) for frm, to in g.edges: link_type = g.nodes[frm]['Gender'],g.nodes[to]['Gender'] counter[link_type] += g.edges[(frm,to)]['Weight'] sg = nx.DiGraph() for (frm,to),w in counter.items(): sg.add_edge(frm, to, weight=w) sg.edges[('male', 'female')] m = nx.to_numpy_matrix(sg, nodelist=sg.nodes) sns.heatmap(m/m.sum(), annot=True, xticklabels=list(sg.nodes), yticklabels=list(sg.nodes)); plt.gca().set_aspect('equal')
We can see that 45% of the interactions in the show happen between males and 33% happen between males and females. All in all males are part of about 80% of all interactions in the show.
This might be a good time to remind you to keep in mind how an ‘interaction’ has been defined for this dataset.
Nevertheless, this result can be explained by the fact that the show is based in a Medieval setting of Kings, Lords and Knights – all of whom used to me males. So, the results we have obtained make sense in the context of the show.
Which character is most important?
Now I want to find out who the most important characters are in the show. The condition for there being an edge between two nodes is that the two characters must have interacted, and the weight of the edge represents the number of interactions. It is reasonable to say that more important characters will have more interactions with various characters overall.
Intuitively, the more the weights of edges connected to a given node, the higher the node’s importance. So, to represent importance I can sum the weights of all edges a node has. This is called the Degree Centrality of the node, formally defined as the number of edges which are incident upon a node (for an undirected graph this is same as the outgoing nodes). There are other measures of Centrality defined in graph theory, each is useful to identify different characteristics of a network.
Let’s look at the trend of degree centrality measure in our data.
deg_cen = nx.degree_centrality(g) nodes['deg_cen'] = nodes['Id'].apply(lambda x: deg_cen[x]) g = make_graph(nodes, edges) fig, ax = plt.subplots(figsize=(20,8)) sns.barplot(data=nodes.nlargest(50, 'deg_cen'), x='Id', y='deg_cen', hue='Gender', ax=ax); ax.set_xticklabels(ax.get_xticklabels(), rotation=90);
Fans of the show should be able to immediately identify that the main characters are indeed in the lead here – Jon, Dany, Tyrion, Cersei and Sansa make up for most of the screen time of the show.
This is not the only way to visualize degree centrality. There is another type of plot, called Arc Plot which could be more informative. Let’s see:
a = nxv.ArcPlot(g, node_color='Gender', node_grouping='Gender', node_size=[10*g.nodes[n]['deg_cen'] for n in g.nodes], edge_width=(edges['Weight'] / edges['Weight'].quantile(.95)).tolist(), figsize=(10,10)) a.draw()
Here the size of the node is based on the degree centrality and the edge thickness is based on its weight. The nodes are also colored based on gender.
Which characters are in the same faction?
If you’ve seen or even heard about the show, you know that it features some serious political rivalries and factions. Is there a way to visualize these alliances? Can we draw some lines on a graph to indicate these alliances? Drawing these lines is known as Graph Partitioning.
Finding Graph Partitions is a very common task in graph theory. One very simple algorithm to achieve this is the min-cut method. A cut is a partition of the nodes of a graph into 2 disjoint sets. The weight of this cut (for weighted graphs only) is the sum of weights of all edges which cross the cut. This means that there will always be some cut of a graph which has the minimum weight.
So, the problem of finding the two factions in Game of Thrones now becomes a problem of finding the min-cut of the graph. We can extend this into a k-cut problem to find an arbitrary number of partitions.
While I will not be using the min-cut method to find partitions, I find the graph cut definition to be the most intuitive explanation for the process. The reason I use a different method is that the min-cut method does not generate good partitions for the Game of Thrones dataset.
The implementation I use comes from the
community package in Python.
cmt = community.best_partition(g, weight='Weight') nodes['cmt'] = [v for c,v in cmt.items()] g = make_graph(nodes, edges) c = nxv.CircosPlot(g, node_color='cmt', node_grouping='cmt', node_labels=True, node_label_layout='rotation', edge_width=(edges['Weight'] / edges['Weight'].quantile(0.98)).tolist(), figsize=(8,8)) c.draw()
We have identified 4 communities. There are some interesting things we have extracted. All the Martells/Sands are in the same community (so is the Mountain ). The Starks are in the same community, except for Jon who is with Dany and Tyrion’s group. These groupings make sense if we think about the plot of the show. Jon has been with Dany’s group more than with the Starks.
Since we have split the graph in 4 partitions, maybe looking at the node-link diagrams for each partition separately isn’t such a bad idea anymore.
pos = nx.spring_layout(g) # compute graph layout for cmt_num in np.unique([v for c,v in cmt.items()]): partition = community.best_partition(g) nodelist = [] # one community against the others for node, c in partition.items(): if c == cmt_num: nodelist.append(node) else: partition[node] = -1 # put all the other communities in one communitiy sg = g.subgraph(nodelist) edge_widths = [sg.edges[e]['Weight'] for e in sg.edges] edge_widths = [w/np.quantile(edge_widths, 0.9) for w in edge_widths] fig, ax = plt.subplots(figsize=(15,10)) nx.draw(sg, pos, with_labels=True, width=edge_widths) ax.set_title(f'Community {cmt_num}');
For these smaller sub-graphs these diagrams are much easier to read. The edges are shaded based on their weight and for the first 3 communities we can see a sort of central cluster connected with thick edges – basically supporting the rest of the nodes in the partition. The last community is less well-knit in this regard.
Like I said in the beginning, I just wanted to learn more about network analysis and share my exploration with you, and I think I succeeded in doing that. Do not consider the analysis or insights from this blog to be any kind of predictions. If you have some knowledge about the show, then you might have noticed that there were a few results that don’t exactly match with the show’s storyline. A more thorough analysis is required to make any form of claims based on the data.
One of my inspirations to learn network analysis was a SciPy 2018 talk by Eric Ma and Mridul Seth, titles Network Analysis Made Simple: Network Fundamentals. It goes over basics of the data structures and libraries along with a few slightly advanced topics in the end which I did not cover here.
I hope this blog has helped you learn some fundamental concepts of Network Theory. I am hoping you would use network theory in a project soon! .
Want to share your content on python-bloggers? click here. | https://python-bloggers.com/2019/05/network-theory-and-game-of-thrones-a-perfect-combination/ | CC-MAIN-2021-10 | refinedweb | 2,546 | 65.93 |
C++ Destructor is the member function that destructs or deletes an object. The destructor function is called automatically when an object goes out of scope: (1) the function ends. (2) the program ends. (3) a block containing local variables ends. (4) A delete operator is called. We have already seen Constructor in C++ on this blog.
C++ Destructor
Destructor is the special member function that automatically deletes or destructs an object (instance of a class) to release memory or close a file when it goes out of its scope.
A destructor is called when:
- Termination of a program: When the object is declared with a global scope or with static class, a destructor is executed automatically when the program ends to clear up the memory taken by that object.
- The flow of control out of a block: In the case where objects are defined with local scope in a specific block, the destructor is called when the execution control gets out of that particular block, then be it a function, loop or condition.
- Delete function: When the delete function is executed/called for a particular data member, then the destructor for that object is called immediately, even if the memory isn’t deallocated. See the following syntax. delete data_member;
- Explicit destructor call: Sometimes it is necessary to explicitly call a destructor in order to clean up resources at absolute addresses which may not be possible with delete operator because that memory was never allocated from free space.
See the following syntax.
object_name.class_name ::~class_name();
#Program to declare Destructors
See the following program.
#include <iostream> using namespace std; class apple { public: int roll; apple(){ //Constructor roll=5; cout << "Roll is " << roll << endl; }; ~apple(){ //Destructor roll=-5; cout << "Roll is " << roll << endl; }; }; int main(){ apple obj1; return 0; }
See the following output.
#Rules for declaring a destructor
- It is defined with the same name as the class name preceded by the tilde operator (~).
- It does not contain any arguments or parameters.
- It does not return any value (not even void).
- There can be only one destructor in a specific class.
#Need to declare a destructor explicitly
While the compiler itself provides a default destructor, it is good to declare a destructor yourself when :
- Using dynamic memory allocation functions in the program.
- You are using pointers/referencing to access data members.
If the default destructor is used in the above cases, it can cause memory leakage where the object’s memory may not be freed up even after the completion of program execution.
#Order of destruction
#Virtual Base Classes
In the case of virtual base classes, i.e., classes whose functions and member variables can be overridden and redefined by subclasses of an outer class, the destructor runs in reverse order in the inheritance graph.
Therefore, it starts with the bottom last-child class and goes to the top from the extreme left towards the right following every possible path. So, as to create a list of classes having all unique elements and containing all of them.
See the following syntax.
class a; class b; class c : virtual public a, virtual public b; class d : virtual public a, virtual public b; class e : public c, public d, virtual public b;
For, the above declaration the list goes as like,
Non-virtual class e Non-virtual class d Non-virtual class c Virtual class b Virtual class a
#Non-Virtual Base Classes
With non-virtual classes, the destructor runs according to the order in which the class names are used when declaring the child class. It goes in the reverse order, i.e., starting from the right towards the left in the statement declaring the child class.
See the following example.
class child : public parent1, public parent2
In this case, the destructor for the parent2 class is executed first and then the destructor for parent1.
#How destructors are different from a regular member function
- Destructors have the same name as the class preceded by a tilde (~).
- The destructor doesn’t take any argument and doesn’t return anything.
#Can we have more than one destructor in a class?
No, there can only one destructor in the class with class name preceded by ~(tilde), no parameters, and no return type.
#When do we need to write the user-defined destructor?
If we do not write our destructor in the class, the compiler creates the default destructor for us. A default destructor works fine unless we have dynamically allocated the memory or pointer in the class.
When the class contains a pointer to a memory allocated in the class, we should write the destructor to release memory before a class instance is destroyed. It must be done to avoid the memory leak.
#Can a destructor be virtual?
Yes, it is always a good idea to make destructors virtual in base class when we have a virtual function.
#Virtual Destructor
Deleting the derived class object using the pointer to a base class that has non-virtual destructor results in the undefined behavior. If we want to correct this situation, the base class should be defined with the virtual destructor.
Making base class destructor virtual guarantees that an object of the derived class is destructed correctly, i.e., both base class and derived class destructors are called.
So, here we end the article of the C++ Destructor example. | https://appdividend.com/2019/07/04/c-destructor-example-destructors-in-c-tutorial/ | CC-MAIN-2020-29 | refinedweb | 890 | 53.1 |
2016-11-01 Meeting Notes
Allen Wirfs-Brock (AWB), Waldemar Horwat (WH), Jordan Harband (JHD), Thomas Wood (TW), Brian Terlson (BT), Michael Ficarra (MF), Adam Klein (AK), Jeff Morrison (JM), Chip Morningstar (CM), Dave Herman (DH), Yehuda Katz (YK), Leo Balter (LB), Sebastian Markbåge (SM), Kent C. Dodds (KCD), Kevin Gibbons (KG), Tim Disney (TD), Peter Jensen (PJ), Juan Dopazo (JDO), Domenic Denicola (DD), Daniel Ehrenberg (DE), Shu-yu Guo (SYG), JF Bastien (JFB), Keith Miller (KM), Michael Saboff (MS), Chris Hyle (CHE), Alex Russell (AR), Brendan Eich (BE), Caridy Patiño (CP), Diego Ferreiro Val (DFV), James Kyle (JK), Eric Ferraiuolo (EF), Mathias Bynens (MB), István Sebestyén (IS), Mark S. Miller (MM), Cristian Mattarei (CMI), Brad Nelson (BNN), Jafar Husain (JH)
4 Approval minutes from last meeting
AWB: Approval of previous meeting minutes?
IS has distributed the minutes via TC39 Email Reflector and has also uploaded it on GitHub.
Conclusion/Resolution
- Approved
6.i Determine 2017 TC39 meeting dates, locations, and hosts.
IS: WE said that in 2017 there will be no European meeting. But if nothing else works Ecma and Switzerland are always a fall-back possibility for organization of TC39 meetings. Of course we need a few months lead-up time. I will also bring up the issue of the TC39 at the GA next week. Maybe I can find some additional hosting help in the Bay Area. Last point (not said in the meeting): we may try to access some of our university members, Universities usually easily have sufficient large rooms, especially if we come during a time when there is no teaching.
AWB: January meeting at Salesforce.
DG: Yes
AWB: March, May, November still open.
DD: Looking into May in New York
IS: We could also have it in Europe, in Switzerland
AWB: We prevously decided not to have a Europe meeting, but we'll have two east-coast meetings. We should find the meeting place for March ahead of time
SYG: Moz can host, but don't have the space necessary for the size of this group now
AWB: Last meeting 40+
JHD: I'm looking into hosting, tentatively for November.
AWB: What about Google New York in March rather than May?
DD: Maybe
KCD: PayPal can host in March, tentatively. My manager supports it.
AWB: PayPal has hosted in the past.
Conclusion/Resolution
- January Salesforce San Francisco, Jan 24-26 - March Paypal San Jose, March 21-23 - May Google New York, May 23-25 - July Microsoft Redmond, July 25-27 - September Bocoup Boston, Sept 26-28 - November AirBnB Bay Area, Nov 28-30 (tentative)
12.ii.c Promise.prototype.finally
(Jordan Harband)
JHD: Looking at the spec, .catch() calls out to .then(), and .finally() should do the same thing. This removes the concern that I raised about how we should do this wrapping check--we'll just follow what .then() does.
Details in PR: tc39/proposal-promise-finally#14
Downside of finally calling into .then:
- another call added
- another place where spec created functions are exposed to user code.
AWB: Implementations can do lots of things to make the overhead of closures go away.
DE: Actually, it's hard to eliminate the allocations totally, in some cases, if it is bound to a particular thing.
AK: And we are seeing this with Promises; we are doing a lot of work to optimize, but we are still having a fight with Bluebird as they don't care about following the expensive parts of the spec.
JHD: Even if Promises call into methods, most parts of the spec call directly into internal algorithms.
AWB: We shouldn't permanently introduce inconsistencies because we are having trouble dealing with coming up with optimizations in the short term.
DD: We could further remove the way Promises call into internal methods, e.g., for catch. Maybe that would be web-compatible, even if it's a technically breaking change.
JHD: Seems like this comes down to, do we prefer the observability or the consistency?
MM: I prefer consistency. finally and catch should be consistent with each other.
AWB: This changes the requirements for subclasses, so they have to implement three methods instead of one.
YK: Let's come back at a future meeting to go for Stage 3. then doesn't seem like a good kernel method.
AWB: I'd want to understand the benchmarks better; is this all microbenchmarks?
BT: ecmarkup improved build times by 25% by using Bluebird rather than V8 native promises.
YK: The gap is partly spec compliance and partly implementation quality. Ember does get faster
MM: What are the use cases for Promise subclassing?
JHD: Probably not much usage on the web at the moment.
DD: Because we have the duck type chaining assimilation system, we don't need subclassing.
MM: Would it be web-compatible to kill Promise subclassing?
AWB: What, are we going to introduce final classes?
DD: Just not call into the kernel methods, just call the internal algorithm. It would be more like map, rather than based on kernel methods.
YK: Maybe we should make a protocol for await, to override behavior, rather than the thenable assimilation protocol. I'll come up with a more concrete proposal in the future.
AWB: You can pursue a brand checking mechanism as well, and this may lend itself to advanced JIT optimizations
Conclusion/Resolution
- Remain at Stage 2
- Solicit reviews from both spec text versions by January
12.ii.e Variation on UnambiguousJavaScriptGrammar
(Dave Herman)
DH: Goal is to get to Stage 1 and discuss further with Node, whose represenatives weren't able to make it today.
AK: Thanks for articulating your goal clearly at the beginning!
DH: Script or module?
AWB: This isn't a new question. We had the same discrimination dilemma before between scripts and CommonJS scripts, which are actually function bodies.
DH: The goal is to allow your module source file to always be interpreted as a module; this is useful on the web as well.
WH: You can trivially do that today without needing any proposal. How is this a motivation?
DH: Node's proposal: Let's mandate that you have at least one import or export statement in the module grammar. Then, zero overlap, so tools can disambiguate.
AWB: A problem with that proposal is chapter 16. An implementation is allowed to extend semantics that would make import or export statements parse in scripts.
DH: Node's proposal: If there's out-of-band data indicating whether it's a script or a module, then early error for presence/absense mismatch. If there is no out-of-band data, then decide based on presence.
DH: This violates some important constraints.
WH: When deciding based on presence, you can completely change of meaning of an entire file at the end of the file.
DH: Also
export {} is a weird magic incantation.
DH: Don't want to mandate a bogus export even if living in a world in which there are only modules.
DH: Alternate proposal:
"use module" at the beginning of the file. Don't mandate it, but that's a way to switch into module mode. Not required for
<script type="module">.
WH: (in regards to using the presence of an import statement to distinguish scripts from modules) A script can never import a module?
DH: That's true now. That might not be true in the future.
(Discussion about import statements in scripts: If we allowed that, then the Node proposal would break.)
DH: I don't want to force either
export {} or
"use module" in an all-module ecosystem where it is indicated out-of-band. Also, refactoring-wise, bad if removing an import changed semantics significantly.
DH: So, the proposal is instead, "use module", optional to force into that mode, basically the same as
export {} would've been.
WH: Is this your proposal or Node's proposal?
DH: This is my variation to their proposal.
AWB: Why not have this happen on Node's part, now? Couldn't Node look for explicit imports or exports, and tell developers this, and implement "use module"?
DH: That's saying something about the meaning of content in JavaScript which deserves standardization.
DD: If it only means something in one embedding environment, then it can be done at their level.
JM: Maybe this should work across environments.
AK: Yes, that's why we need to discuss here, if it should work on the web too.
DH: So, the proposal is to allow the "use module" in addition to the import/export conditionality. "use module" would be an early error in a script on the web, permitted but not required in modules on the web, and in Node it would be the conditionality. I wouldn't want "use module" to have to be sprinkled all over the top of all modules, though.
WH: This suffers from the same perils as you just listed as arguments against Node's proposal. If you use the presence of import statements, scripts will be misclassified as modules in the future when we add the ability to import into scripts. To make this work you'd need to either get rid of the import/export statement sniffing or define a "use script" in addition to "use module" to in-band force scripts to be interpreted as scripts.
AK/CP: What if we just did
"use module" without the import/export conditionality?
DH: (Experimental implementation at dherman/esprit)
DH: Usually the mode is known upfront, but the deferred check will have some cost in the cases where it runs. Maybe the import/export conditionality will only come up in a few of the Node corner cases.
AK: So you think it's uncommon is because Node folks were receptive to the idea that it could only come up in certain circumstances? (NB: Background is that the import/export check may require parsing multiple times.)
DH: We should aim for out-of-band signalling most of the time, and in-band only for a couple remaining edge cases, and for defensive programming.
DD: The node leadership is already happy with .mjs
AWB: From Node, this isn't a problem between discriminating between modules and scripts, but modules and CommonJS modules. This is Node's problem: Node doesn't handle Scripts, only CommonJS modules. So, given a source file, Node needs to determine if this should be processed as ES or CJS, it can do its heuristics. Differences in semantics? Mostly strict mode. Does that matter much?
KG: Annex B 3.3 being excluded is big
MM: Strict arguments are very different
AWB: I think anything that Node might be confused if they take a script-like module and treat it as a CJS module.
YK: They don't think that's true empirically.
JM: We are far over timebox, let's move to another agenda item.
WH: I object to Stage 1. It would be a waste of the committee's time as it is strictly worse than the previous proposal, and it suffers from the same issues as the Node detection solution, and it doesn't solve the problem of import statements in scripts in the future.
DH: It would be great if this could reach Stage 1, as this relates to JDD&Bradley's proposal.
WH: We have to wait to see that proposal
AWB: One of the criteria for Stage 1 is that we think it's worth spending time
AK: Actually it says we "expect" to spend time on it. I would expect to spend time on it!
BT: This is a feature request from an important user of JavaScript and we shouldn't just dismiss it.
Conclusion/Resolution
- Stage 1 acceptance
- The committee has deep doubts about this proposal
14.ii import() open issues and stage 3 discussion
DD: For Node, JHD reached out to Bradley Farias of Node and confirmed that we can start the import of the module asynchronously, as he had suspected. Therefore, the hook can be clarified to always be asynchronous, not synchronous or asynchronous as previously.
DD: For MM's membrane penetration concern, the plan is that we will be working towards hooking of agent hooks ("the loader spec"), though we aren't blocking on it. Current embedding environments do support hooking.
DD: (walking through tc39/proposal-dynamic-import#26)
MM: We're expecting that we'll work towards a standardized loader spec for generalized hooking, and be happy with how embedding environments (e.g., Web and Node) do provide an API.
AWB: If need API, then say you need in spec.
MM: minimal requirement, have a standardized API now. Minimal requirement that there exists a way for this to be implemented on all runtimes, there must be a spec hook to
AWB: We can also require host environments to provide a way to expose these hooks, rather than just expect it, writing out in the spec what is required for it to be sufficient.
DD: This is novel, and I'd rather not tie my proposal to that. But it seems like a possible path. I'm expecting to get a PR from Mark to formalize whatever is required.
MM: I'd like to look at what hosts expose more closely. Is there great urgency?
DD: We'd like to implement this.
AWB: And you won'd do it if it's not Stage 3?
DD: Right
AWB: Stage 3 is about getting usage and implementation feedback, and adjusting if necessary. We are anticipating feedback from Mark
MM: In this delecate agreement, I'd like to take a look at some details before giving a final signoff.
AWB: But we're not talking about changing the normal public surface area of the feature. So there's no particular reason why it should block Stage 3.
MM: I am not expecting it to block Stage 3, but I'd like more time to look at it. But I can do that at Stage 3.
DD: Final obstacle was run-to-completion semantics, from AWB. Talking with BT, we were thinking of working this out spec mechanics during Stage 3. I have a note indicating the need for run-to-completion.
AWB: Should be a normative requirement!
DD: Done.
WH: Any remaining syntax issues from Tuesday? For the record, what was the decision?
DD: Result is that it looks like a function call.
AK: With some static restrictions.
DE: Stage 3 is good because it indicates some stability that helps implementations know they're not wasting their effort.
MM: Will this ship before the next meeting, prohibiting future changes?
AK: We'll initially develop it behind a flag, and it will go through normal Chrome shipping processes, which take some time.
Conclusion/Resolution
- Stage 3 acceptance
13.ii.b Private State
(Daniel Ehrenberg)
DE: Private state to stage 2
- Syntax is same
- Follows Kevin Smith's proposal
- Class private state, not instance private
class Foo { #x; #y = z; foo() { #x++; return this.#x; } }
DE: Questions remain for both private state and public fields, but public fields still at stage 2
AWB/WH: They're in fact the same questions. Apply to both.
DE: (semantics)
- Only accessible from methods inside class body ("hard-private")
- Internal slots mapping objects to field values
- Add field after
super()returns, or at beginning in base class
- Intersperse initializer evaluation with field addition
- Throw on redundant property definition
- Scope of initializers as in property declarations
The intention is to match public fields, need to be interleaved, specifically the ordering of steps e.g. adding fields.
AWB: Concerns about separate proposal for public fields. Merge the proposals.
DE: The plan is to merge the specs for Stage 3
DE: If feedback reveals that the # syntax for private state is fatally unworkable, we wouldn't want to kill public state because of it
MM: if integration reveals issues for one and not the other? THen we can address?
AWB: Or drop entirely?
YK/AWB/DE: (discussion of the merging concerns, but only w/ regard to Stage 3?)
AWB: Concerns about separate proposals modifying the same spec algorithms. They need to be merged when we get to that level of detail.
- in stage 2, merge must be addressed
DH: I love the smell of consensus in the afternoon ;)
DE: Should there be a way, through reflection, to access private state outside of the class? No.
- Previously, formalism based on weakmaps
- New formalism is same, but without the GC semantics
DE: Add field after
super() returns, or at beginning in base class—no matter where
super() is called
AWB: May be issue? Reflect.construct call is intended to be an alternative
super(). Possible to move this in the construct, doesn't have to relate to token
- construct is where belongs
WH: Concerns that one shouldn't be able to use this to stick a class's private fields onto arbitrary unrelated objects
...
DE:
Interaction with other features
- Decorators -- reify a PrivateFieldIdentifier() object (tc39/proposal-private-fields/blob/master/DECORATORS.md )
- A decorator can provide soft-private state
- Private methods -- a clean extension with the syntax you expect (tc39/proposal-private-fields/blob/master/METHODS.md )
- Static private -- ditto (tc39/proposal-private-fields/blob/master/STATIC.md )
- Friends -- may be lexically exposed via static block (littledan/proposal-class-static-block )
let barGetter; class Foo { #bar; static { barGetter = instance => instance.#bar } }
MM: could via decorator, declare a private field to be effectively const, initialized, not further modifiable?
DE: Not presently
YK: Not yet
(back to syntax)
MM/DE: (discussion about the dot in
o.#p, ultimately they came around to the dot.)
DE: Why hard private? (docs.google.com/presentation/d/1QBK8GsTYmQHJQJm_P0HuELNN4uGkm9gB7Df9g4tRK-o/edit#slide=id.g1994dec4f4_0_20 )
WH: This relies on not being able to create fake instances of the class that has the private property. That's the concern I raised earlier.
AWB/WH: We need to explore that.
DH: possibly making a mistake by using the concise syntax for the air-tight private state?
- The question is: what do people want in the real world? Afraid we're missing that
JM: Have you seen the decorator opt-out?
DH: yes, but concerned we're making wrong decision.
DE: the developer field is split evenly, some for hard and some for soft private.
JM: The concern of hard private is that its very hard to debug
- if debugging in a debugger, you can see the hard private, but your tests cannot
WH: Same argument could be made about the other hard private facility of the language, namely locals in functions. Although some might want non-air-tight functions (for example for testing), it's not worth it to add another kind of functions to the language. Just like with private fields, a debugger will show you the values of locals in functions.
YK: Some know how to use underscore (prefix), some symbols; might use underscore as example that we did it wrong
(Discussion about all the problems of using underscore, ie. not soft-private/soft-protected)
MM: It's important for me that hard-private be ergonomic.
AWB: The key elements of the proposal are hard private and lexical scoping of private declarations. If either of those were reversed, this would turn into a radically different proposal. If we're advancing this to stage 2, it's with the understanding that these will be in the proposal.
DE/DH: (further discussion of hard private).
- Want real usability feedback
YK: (point about developer ergonomics compared to similar cases re: decorators)
AWB: Proxy issue?
DE: Resolution was: can add private state to proxy
MM: WEakMap semantics: proxy has identity and can key on proxy
MM/WH: No proxy issue.
MM: Intended to be observationally equivalent to weak maps. If there is a place that isn't, it's a bug.
DE: Can add text that explains the equivalence to weakmaps; semantics of this proposal, etc.
Internal slot-based specification mechanics
- Private State Identifier specification type
- [[PrivateStateValues]] is a List with pairs mapping Private State Identifiers to their values
- Difference from WeakMaps unobservable except for implied GC semantics
DE: Q. is this just too unergonomic? Some wanted @, not #—and very opposed to #. Some Wanted
private.
WH: Need a sigil or equivalent. We've spent years working through attempts to define private state without any distinguishing sigils on use. None of them worked. They work fine in statically typed languages, but in dynamically typed ECMAScript were hopelessly mired in the same class of namespace shadowing problems that plagued the with statement. Consider what happens if a class defines a private field called "length" and also wants to access a length field of an unrelated object.
AWB: 6-7 years ago worked through extensive ways of doing this and all had problems.
AWB: Extensively documented in old wiki
DE: static private, methods included? Or wait?
AWB: Do the full package here.
KG: why? (as opposed to a later proposal, if confident that this will allow for a later proposal?)
AWB: cross cutting concerns, if not pinned down together, and proceed with only confidence, then discovery later will be problematic or impossible to fix.
DE: Open issue: require a "private" keyword on declarations? (i.e.
private #x; instead of
#x;)
DE: Pro: useful for learning the language
WH: Any syntactic reason for needing a keyword?
DE: No.
AWB: had to chose: follow separator of block or object literal, went
;
YK: important to support commas to enumerate a list of fields:
class A { #x, #y, #z }
Annoying to write:
class A { private x; private y; private z; }
Bad: private and decorators and no comma list
WH: Whether or not we allow commas is orthogonal to this proposal.
DE: could make private keyword optional, but is weirder
YK:
private @protected foo is something to keep in mind?
DD: Does anyone like the
private keyword?
AWB: the sigil alone is hard to read,
public and
private are clear
WH: Can't mandate
public and
private keywords. Public methods don't use a keyword, so that ship has sailed assuming that we'll want private methods at some point. My preference is no keywords — sigil only.
KG: opposed to
private, but those who are opposed to
# are less opposed to
private #x.
(discussion re:
= or
:)
CM: why is this even a question?
JM: There is a question on public fields,
= is assign/set,
: is define—still not sure which will be correct?
KG: only relevant for public fields, evaluation order
YK: TypeScript and Babel transpile as:
class A { x = 1; }
to
var A = function A() { _classCallCheck(this, A); this.x = 1; };
JK: It does this by default, however when you enable "spec" mode it will switch to using a defineProp to set configurable to false
KG: concern that if not addressed now, Babel will proceed and like the "sigil swap", it will become hard to change later.
AK: valid concern, but
public is much more widely used
DE: much more open to
private with comma list
JK: This is a slightly different situation from the sigil swap, there is a better migration path available
WH: keyword ship has sailed, problems when we do private methods with
private but public without
public
AWB: This is why I proposed
own and not
AWB: Change to IdentifierName, not IdentifierPart
WH: Yes, I raised that the last time we discussed this proposal.
JM: Why?
AWB: Don't want properties called #1, #2, #3
JM: Why?
AWB: We use IdentifierName in the grammar
WH: It seems odd to have a PrivateName be a single token. The more natural way to express it would be as two tokens,
# followed by an IdentifierName.
KG: Won't that allow whitespace between
# and IdentifierName?
- The hash is intended to be thought of as part of the property name, ie:
this. #foo. #bar;
(RW, LB: Weird)
AWB: No whitespace between
# and
foo in
#foo, but also
foo not IdentifierPart
WH: Want whitespace allowable on either side of #
DE: Should private state be accessible within eval?
Conclusion/Resolution
- Stage 2 acceptance
- hard private, lexical scoping
13.vi Process proposal: require an implementation to land a normative PR to the spec
(Daniel Ehrenberg)
WH: What are the majority of the spec pull requests?
BT: Editorial. Among the remainder, the majority are consensus items.
DE: proposes that PRs for normative changes should also have an implementation before being merged.
AWB: case by case?
MM: We can adopt this process and apply it on a case-by-case basis
AWB: what if it's a bug?
DE: Want a high bar to making normative changes to the spec to avoid bugs.
WH: It also makes a high bar to fixing bugs.
AWB: Caution against adding too much burden to the process.
BT: Don't want to inject a lot of process into simple things. Don't think adopting this proposal would change anything in practice.
YK: But it would cause more process lawyering.
Conclusion/Resolution
- Raised the issue, pay attention.
13.vii Open-ended: How can we promote diversity and inclusion in TC39
(Daniel Ehrenberg and others)
DE: How can we improve this?
AWB: member companies need to send more diverse language implementors
(general discussion wrt adopting a Code of Conduct that applies to diversity based on demographics background)
WH: Code of Conduct and meeting participation changes must be handled at the ECMA General Assembly level. Also, ECMA has a code regulating conduct.
RW: We should talk to István to have ECMA adopting this Code of Conduct
(general agreement)
RW: The next step is we as delegates communicate to our companies that we should sponsor and support diversity, affecting who we bring to the meetings as well. This might be done via scholarship or otherwise.
MM: We lack geographical diversity.
WH: We've never had a meeting in the midwest. In the US we've only had meetings near ocean coasts.
RW: (explanation of counter to geographic claim, w/r to specific demographics and personal safety)
MM: Geographical location is one of the few things that this committee has direct control over
(discussion about different working and debate styles)
WH: The biggest indictment of our committee is what happened to Kevin Smith in Munich.
JK: There are groups unwilling to come, due to the nature of TC39
WH: Are they members?
JK: Certainly within member companies, but also people who don't push their companies to become members There ertainly within member companies and without
JK: w/r to certain places being unwelcoming to disenfranchised groups. I'd ask that the committee never hold meetings in places where anyone's personal safety isn't guaranteed, eg. countries where gay people are killed for being gay.
DE: Mark makes a good point about geographic diversity; globally, many of our companies are focused on the next billion users, and we don't have much representation from developers who are targeting that, who may have different mental models. It's not just diversity of people who we bring here, but also inclusion of the people that are in the room. Our culture here can be intimidating--it is hard to give a presentation when committee members will interrupt from very early on, and this works for some cultural styles of presenters but not for others.
BT: Sounds like we are all in agreement that diversity is an important issue that we want to work on
MS: It is important for us to work on making this a less intimidating place which is more welcoming to new members.
MM: re: Kevin Smith hostile environment issues:we missed the opportunity to improve ourselves as a group after the incident in Germany
BT: Let's continue this discussion, including developing a statement from the committee that would help companies like mine and Rick's find funding to allow the participation of diverse members.
DFV: It feels like there is unnecessary tension, tension about more than technical things, and it makes me hesitant to speak much. We saw some of that today, where it was uncomfortable to speak. It feels like there is sometimes too much confrontation here.
JK: We can also work to create more resources for people to learn how to get involved.
DE: Maybe we should be fixing our culture to be more respectful and inclusive as the first step; I wouldn't want to bring a lot of new people into a hostile situation. The code of conduct could help here.
SYG: Can we really expect people to follow this?
MS: We are getting better at enforcing timeboxes, but we should consider being even more strict in enforcement--if members don't grant an extension, it should be done.
LB: Some companies may have trouble/refuse participating because they see the lack of diversity and a code of conduct on a company. I have had discouragement from colleagues personally as English is my second language--this made me feel like running away. Fortunately, my employer, Bocoup, on hearing this, put me on the Test262 project and eventually sent me to the committee. I have many people from my country (Brazil) who contact me and want to get in touch about reading the spec, etc. I am just a normal person--I needed to find that, regardless of where I come from, I was able to attend. It would be very useful to have an official document from ECMA saying that ECMA and TC39 commit to social responsibility, where people can feel respected in any sort of background. Everyone should feel encouraged. I am here, I am the proof of it. I feel responsible to bring that forward to the new people.
Conclusion/Resolution
- Consensus that diversity is important and something we'd like to address and improve
- Take initial steps to adopt a Code of Conduct and determine how to enforce
- Rick Waldron will contact István
- Rick to review with Kevin Smith
- Representatives should work with their member organizations to promote more diverse representatives, via scholarship/sponsorship or diversification of member team
- Extend our charter to include social commitment to committee representative diversity. | https://esdiscuss.org/notes/2016-11-01 | CC-MAIN-2019-18 | refinedweb | 5,007 | 62.78 |
Opterator is a decorator to make quick and clean command line interfaces for scripts. It’s not designed to compete with argparse or click. Instead it supports that common usecase where you’re writing a reusable script and don’t want to write all the bits required for argument parsing, but also don’t want to use the maligned ‘just access sys.argv and pray’ technique.
Say you’ve written a script that makes a thumbnail of an image. It requires the image name, the output thumbnail name, and an optional algorithm. Just do this:
from opterator import opterate @opterate def main(image, thumbnail, algorithm="cubic"): # do the scaling stuff if __name__ == "__main__": main()
There’s no mucking about with options, and you even get a helptext that is borderline useful:
python3 meh.py -h usage: meh.py [-h] [-a ALGORITHM] image thumbnail positional arguments: image thumbnail optional arguments: -h, --help show this help message and exit -a ALGORITHM, --algorithm ALGORITHM
If that’s not good enough, you can customize the helptext by editing the docstring, as described in the
README.
But opterator has supported that for years. Let’s talk about some new stuff. I recently released version 0.5, which has a few bugfixes and a couple exciting new features that I want to introduce.
First, I ported it from optparse to argparse. This makes opterator handle positional arguments much more neatly, both in the code and in the resulting helptext. It doesn’t really change your interaction with opterator as an api client, but the users will see improved helptext.
Second, I’ve added support for function annotations so you can change the variable name output by opterator. This obviously only works on Python 3, since function annotations are a new feature in Python. Opterator itself, however, is Python 2 and 3 compatible as it has been since 2012. Here’s the same example, but we changed the algorithm argument to be passed in as –scaling or -s:
from opterator import opterate @opterate def main(image, thumbnail, algorithm:["--scaling", "-s"]="cubic"): # do the scaling stuff pass if __name__ == "__main__": main()
Here’s the resulting helptext:
usage: meh.py [-h] [--scaling ALGORITHM] image thumbnail positional arguments: image thumbnail optional arguments: -h, --help show this help message and exit --scaling ALGORITHM, -s ALGORITHM
The main reason you might want to do this is that you’ve got options that start with the same letter (the first letter is what opterator uses as a short option, by default). Function annotations let you supply other options if you like. Or possibly you just have a burning desire to play with function annotations. Either way, opterator has you covered.
Opterator is well-tested, so I’ve (belatedly) upgraded the classifier from beta to production. It’s a small tool that has saved me a lot of time and many lines of ugly code over the years. I think it’s worth having installed in site- packages so you can write quick scripts without thinking about getting data from the user. | http://archlinux.me/index3.php | CC-MAIN-2015-18 | refinedweb | 508 | 61.87 |
Sometimes you come across someone elses blog and think that’s pretty cool I should go build that…. well I came across Exfiltrate Files With DNS and found it rather interesting – the link can be found here. I decided that I really wanted to build this and make it work. I already have a cloud server and a domain name so it was just a case of creating a subzone and redirecting requests to the subzone(dns name server). I then installed BIND9 on my cloud server to answer the requests when they come in to the subzone.
I only encountered one issue when building the solution and that was that the parsing of the reassemble script was capturing the wrong string during the FQDN split. This was trivial to fix and I carried on and got a working solution that was transferring files which by the way is just awesome!!
I have been messing with python and was looking for something to play with so decided that it might be quite cool to implement an encryption phase that then requires a key to decrypt the file on the other side.
The downsides:
Both sides need to support python-dev and pycrypto…. well in my amendments to the script.
The upside:
An encrypted chat service or method for moving files should all the prereqs be met. As this is me just messing around I am happy to have as many prereqs as required to run the program.
So with the same base infrastructure in place and pycrypto installed on either end I put togeather the following:
The following script encrypts the data and encodes in base64 before sending across in a domain request.
#!/usr/bin/env python
from Crypto.Cipher import AES
import base64
import socket
from Crypto.Hash import MD5
DNS_ZONE = “file.hackwhackandsmack.com”
socket.setdefaulttimeout(1)
#static password can be taken as an input later
password = (‘Works for me!!’)
#generate a 32 bit key
secret = MD5.new(password).hexdigest()
#specify blocksize
BLOCK_SIZE = 32
#padding character
PADDING = ‘A’
pad = lambda s: s + (BLOCK_SIZE – len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.urlsafe_b64encode(c.encrypt(pad(s)))
cipher = AES.new(secret)
def break_file(filename):
try:
fp = file(filename, ‘rb’)
part = 0
while 1:
data = fp.read(32)
if data:
try:
encoded = EncodeAES(cipher, data)
part = part+1
print part
print ‘Encrypted string:’, encoded
socket.gethostbyname(encoded + DNS_ZONE)
except Exception:
continue
else:
print “Complete”
break
fp.close()
except Exception, e:
print e
#run
break_file(‘test.txt’)
##EOF##
To reassemble on the other side I used the following code:
from Crypto.Cipher import AES
import base64
from Crypto.Hash import MD5
password = (‘Works for me!!’)
secret = MD5.new(password).hexdigest()
BLOCK_SIZE = 32
PADDING = ‘A’
pad = lambda s: s + (BLOCK_SIZE – len(s) % BLOCK_SIZE) * PADDING
DecodeAES = lambda c, e: c.decrypt(base64.urlsafe_b64decode(e)).rstrip(PADDING)
cipher = AES.new(secret)
file_chunks = []
def back(chunk):
encoded = chunk.split(“.”)[0]
decoded = DecodeAES(cipher, encoded)
file_chunks.append(decoded)
queries = []
fp = open(“log-encrypt.txt”)
lines = fp.readlines()
fp.close()
for line in lines:
if “file.hackwhackandsmack.com” in line:
if “cache” in line:
FQDN = line.split()[9]
queries.append(FQDN.strip())
uqueries = set(queries)
for i in uqueries:
back(i)
file_list = reversed(file_chunks)
file = “”.join(file_list)
print file
##EOF##
This is definetly not the best implementation of AES but it works and meets my minimum requirements that I set out at the start. Time at the moment will impact any further improvement in the near future.
- Improvements would include:
- Adding a salt to the password hash.
- Adding an IV or nonce to the encryption algorithm.
- Change encryption mode from default ECB.
- Reading multiple files into the same logfile by using start and end of file markers.
I also really liked the ‘part’ section that was initially used to mark out the placement of the file chunks in the correct order. On myscript I just reverse the order of the array and pray to god that it comes through in the correct order ;-P
A demo of my script then:
The first screenshot details the initial running of the script and some verbose log messages of the file chunks:
The following is a screenshot of the logs taken from the bind service (this is just a section of the log file):
Lastly lets decrypt the file generated from the logs:
Hope this is useful to someone. Enjoy | https://www.hackwhackandsmack.com/?author=2&paged=2 | CC-MAIN-2019-13 | refinedweb | 730 | 64.71 |
I have a Point3D class, Shapes abstract class, and a Sphere that extends Shapes.
I want Shapes to have a member object from Point3D.
public class Point3D { private float x, y, z; public Point3D(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } }
public abstract class Shape { private Point3D point; public Shape() { point = new Point3D() ; } }
public class Sphere extends Shape { private double radius; public Sphere(float x, float y, float z, float radius) { // How do I pass the x, y ,z values to point3D? } }
I want to create the sphere but by making sure that I pass values to the point3D, how do I do it?
Also I have a feeling that putting a constructor on an abstract class is wrong.
Please help. | http://www.gamedev.net/topic/622527-java-abstract-class-problem/ | CC-MAIN-2016-40 | refinedweb | 129 | 89.58 |
[ ]
Mikhail Fursov updated HARMONY-2056:
------------------------------------
Patch Info: [Patch Available]
> [drlvm][jit] Jitrino.OPT's bpp.version=1 does not insert a polling code to every backedge
> -----------------------------------------------------------------------------------------
>
> Key: HARMONY-2056
> URL:
> Project: Harmony
> Issue Type: Bug
> Components: DRLVM
> Reporter: Mikhail Fursov
> Priority: Minor
> Attachments: 2056.fix
>
>
> This bug is not critical, because it's about bbp.version=1 mode and default mode is bbp.version=6.
> I found this problem while debugging more critical BBP bug and tried version=1 for my
temporary needs.
> In BBP documentation (in sources) I found:
> // version of BBPolling:
> // 0 - must be discarded in runImpl()
> // 1 - insert bbpCFG at all backedges
>
> So I expecting to have BBP code generated for this test:
> public class BBPBug {
> public static void main(String[] args) {
> new BBPBug().foo();
> }
> void foo() {
> int i=0;
> while (i<100) {
> synchronized (this) {
> i++;
> }
> }
> }
> }
> The BBP code is not generated.
--
This message is automatically generated by JIRA.
-
If you think it was sent incorrectly contact one of the administrators:
-
For more information on JIRA, see: | http://mail-archives.apache.org/mod_mbox/harmony-commits/200611.mbox/%3C12341998.1162474521026.JavaMail.root@brutus%3E | CC-MAIN-2015-18 | refinedweb | 170 | 54.32 |
Word code cleaner
Discussion in 'ASP General' started by Juan C. Santaella, Apr 28, 2004.
Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
- Similar Threads
Converting Word files to HTML in Word CleanerAl Moritz, Jul 19, 2003, in forum: HTML
- Replies:
- 7
- Views:
- 634
- Richard Laing
- Jul 22, 2003
[ANN] XML Cleaner - remove superfluous namespacesVictor Porton, Jul 27, 2005, in forum: XML
- Replies:
- 2
- Views:
- 495
- Nick Kew
- Aug 10, 2005
[ANN] XML Cleaner 0.2 - remove superfluous namespaces etc.Victor Porton, Aug 29, 2005, in forum: XML
- Replies:
- 0
- Views:
- 432
- Victor Porton
- Aug 29, 2005
Suggestions to make cleaner code#2pencil, Jun 25, 2007, in forum: Java
- Replies:
- 9
- Views:
- 368
- #2pencil
- Jul 12, 2007
Changing "self" for cleaner codecome, Aug 23, 2007, in forum: Ruby
- Replies:
- 9
- Views:
- 100
- come
- Aug 24, 2007 | http://www.thecodingforums.com/threads/word-code-cleaner.794185/ | CC-MAIN-2014-35 | refinedweb | 172 | 75.64 |
Hello everyone hows it going
I've only recently been introduced to arrays and require a bit of help with a small exercise I was doing earlier. Here is the question :
Write a program which reads a sequence of words, and prints a count of the number of distinct words. An example of input/output is
should I stay or should I go
5 distinct words
I have solved the question below, without using an array but I presume an array is what the question requires as the exercises are related to the sections being studied. Could anybody show me how I would use one in my solution instead?
public class Ex1 { public static void main(String[] args) { System.out.println("Enter Sentence:"); int count=0; while(!Console.endOfFile()) { String word = Console.readToken(); if(word.length()> 1) { count++; } } System.out.println("Number of distinct words is " + count); } // end of main } // end of class | http://www.javaprogrammingforums.com/collections-generics/4964-help-arrays-counting-elements.html | CC-MAIN-2014-41 | refinedweb | 153 | 64.41 |
stm32plus::net HTTP module
As a protocol HTTP needs no introduction so I’ll get straight down to how stm32plus::net helps you write HTTP clients and servers.
HTTP clients
The
HttpClient class is a high-level helper that performs GET or POST requests and reads the response for you. When you get down to it HTTP is little more than some text headers on top of a request-response TCP client. The
HttpClient class does some of the repetitive work for you so that you can concentrate on sending and receiving data.
The
net_web_pframe and
net_web_client examples both use the
HttpClient class to download web content.
net_web_pframe goes into a loop reading and displaying a set of JPEG images from my website and
net_web_client downloads a single file from ST-Micro’s website.
Here’s the basic workflow for using the
HttpClient class.
Firstly, connect to the remote web server on its HTTP port using a regular TCP connection:
#include "config/net_http.h" // [initialisation code removed] TcpClientConnection *ptr; if(!_net->tcpConnect<TcpClientConnection>(address,80,ptr)) { error(); }
Next, wrap the
TcpClientConnection in an
HttpClient class and use its methods to help you get a document from the web server:
// manage the connection pointer in a scoped_ptr so it's automatically deleted (and closed) // when it goes out of scope scoped_ptr<TcpClientConnection> conn(ptr); HttpClient httpClient(*conn); // set the parameters for the HTTP GET httpClient.setUri("/"); // get the root document httpClient.setHost(""); // host header is mandatory for HTTP/1.1 // send it if(!httpClient.sendRequest()) { error(); }
Now read the response back from the remote server. This code sample shows how to read it back in small chunks and output the data to a USART that’s assumed to attached to
_outputStream. This code fragment comes from the
net_web_client example.
// must have a content-length for this test call int32_t contentLength; if((contentLength=httpClient.getResponseContentLength())==-1) { error(); } // read back the response in 100 byte chunks with a 60 second timeout uint8_t buffer[100]; uint32_t actuallyRead; while(contentLength) { // read a chunk if(!conn->receive(buffer,Min(contentLength,100L),actuallyRead,60000)) { error(); } if(actuallyRead==0) { error(); // remote end has closed } // push out to the USART _outputStream->write(buffer,actuallyRead); // decrease amount remaining contentLength-=actuallyRead; }
That’s it. If you don’t want to re-use the HTTP connection (HTTP/1.1 connections may be re-used if the server keeps the connection alive) then delete the
HttpClient instance and the connection will be closed for you.
HttpClient public methods
The following methods are exposed by the HttpClient class.
bool sendRequest(uint32_t timeoutMillis=0); bool readResponse(uint32_t timeoutMillis=0); void setVersion(HttpVersion version); void setMethod(HttpMethod method); void setUri(const std::string& uri); void setHost(const std::string& host); void setRequestContentType(const std::string& contentType); void setRequestContentLength(uint32_t contentLength); uint16_t getResponseCode() const; int32_t getResponseContentLength() const; const std::string& getResponseContentType() const; const std::slist<std::string>& getResponseHeaders() const;
We’ve already seen how the
sendRequest() method is used to send data. You can see that there is an optional
timeoutMillis parameter. If the default of zero is used then the method blocks until success or failure.
If you did a GET request then
readResponse() is automatically called for you. It reads the response code and headers from the TCP stream. If you did any other type of request then you must call
readResponse() manually to read the response and headers, leaving the TCP stream positioned to receive the response body.
setVersion() allows you to choose the HTTP protocol version. The default is
HttpVersion::HTTP_1_1. You may also choose
HttpVersion::HTTP_1_0 if your web server requires it.
setMethod() allows you to set the request method. The default is
HttpMethod::GET. The most common other method is
HttpMethod::POST. All other methods are defined and these may be useful to you if you’re calling a REST service, for example.
setUri() is a required call. You use it to set the URI (and query string, if applicable) that identifies the document you want to get back.
setHost() is a required call for HTTP/1.1 and should be set to the fully qualified name of the web server as the calling client sees it. e.g. “”. Modern web servers tend to serve many virtual domains from a single IP address so they need to know what the name of the host was that the browser saw. Without this header the web server would not be able to differentiate between multiple virtual hosts.
If you’re using the POST, PUT or other method that requires you to send a request body to the server then you must use
setRequestContentType() and
setRequestContentLength() to tell the remote server what you’re sending and how big it is. Call these methods before calling
sendRequest(). After calling the
sendRequest() method you are expected to use the normal send methods available on the
TcpConnection class to send your request body before attempting to read the response.
After the
readResponse() method has been called (which happens automatically for a GET request) then the remaining methods may be used to get some information about the server’s response.
getResponseCode() gets you the HTTP response code, e.g. 200.
getResponseContentLength() gets you the length of the response body or -1 if the server did not send the
Content-Length header in the response headers.
getResponseContentType() gets you the
Content-Type header from the server response, if it was set. It’ll be an empty string if the server didn’t set the
Content-Type header.
getResponseHeaders() gets you a reference to a linked list of the response headers. Each entry in the list represents a header line from the response data.
HTTP servers
stm32plus::net contains support for writing multi-connection asynchronous HTTP servers through a derivation of the
TcpConnection class called
HttpServerConnection. The best way to see how this works is to take a look at the net_web_server example code. The remainder of this section is dedicated to explaining the options provided by the
HttpServerConnection class and what you can do with them.
As always, the model is that you subclass the provided connection class (in this case HttpServerConnection) and use your subclass to customise default parameters and handle your logic.
Configuration parameters
The
HttpServerConnection class subclasses the
Parameters class defined by
TcpConnection to add in the following options that you can customise in your connection constructor.
// are we operating in HTTP/1.1 mode? default is true. bool http_version11; // size includes the verb, URL and HTTP version. Default is 200 uint16_t http_maxRequestLineLength; // buffer size of the stream-of-streams class. Default is 256 uint16_t http_outputStreamBufferMaxSize; // in http1.1, close connection after this many requests. 0 = never, default is 5. uint16_t http_maxRequestsPerConnection;
If
http_version11 is set to true (the default) then client connections are allowed to stay open after the response to a request has been sent to them. This presents a possible resource starvation issue for a small device such as the STM32 so we mitigate that somewhat by setting an upper limit on the number of requests that a single connection can be served before we close it through the
http_maxRequestsPerConnection setting.
if
http_version11 is set to false then connections will be closed immediately after each request is served.
http_maxRequestLineLength sets an upper limit on the number of characters that can be sent on the ‘request’ line (i.e. the first line sent by the browser that includes the verb, URI and http version). You might want to increase this if you forsee the need to handle long URIs.
http_outputStreamBufferMaxSize is an advanced performance tuning setting. To avoid the problems inherent in sending small packets across the network the TcpOutputStreamOfStreams class buffers data from the streams that receives before sending it. The size of that buffer is defined by the
http_outputStreamBufferMaxSize option.
Implementation details
You will note that the
HttpServerConnection template requires the name of your implementation class as one of its template parameters:
class MyHttpConnection : public HttpServerConnection<MyHttpConnection> {
This is called the Curiously Recurring Template Pattern (CRTP) and is used to achieve static polymorphism avoiding the overhead of virtual function tables. This means that you are required to implement some function calls defined by the base class. Those calls are:
handleRequestHeader(const std::string& header); handleStateChange(State newState);
handleRequestHeader is an opportunity for you to peek at incoming request headers and take any appropriate action.
handleStateChange is where you perform the action of servicing a request. Take a look at the net_web_server example for how to deal with this callback. | http://andybrown.me.uk/2013/08/03/stm32plusnet-http/ | CC-MAIN-2017-17 | refinedweb | 1,417 | 54.12 |
Introduction
Data Analysis is the most essential part of any data science project. Analyzing the data gives us some important and beautiful insights about the data. There are many libraries in Python to perform analysis like Pandas, Matplotlib, Seaborn, etc.
Recently developers introduced a new library ‘dtale’ to perform analysis with fewer lines of code.
D-Tale is the combination of a Flask backend and a React front-end to bring us an easy way to view & analyze Pandas data structures. It integrates seamlessly with Jupyter notebooks & Python terminals. Currently, this tool supports such Pandas objects as DataFrame, Series, MultiIndex, DatetimeIndex & RangeIndex.
Let’s dive in and see how to work with this dtale library in Python!
Setting up the Environment for dtale
conda create -n dtale python
conda activate dtale
Now we first need to install the dtale library in the respective environment.
pip install dtale
Exploratory Data Analysis with dtale
Now let’s dive into our data with dtale.
import dtale ## importing D-Tale library
Importing Seaborn will help us to load data sets. Seaborn has many default Data sets. We will be using the ‘planets’ data set for the below analysis.
import seaborn as sns
df=sns.load_dataset(‘planets’)
dtale.show(df, ignore_duplicate=True)
After running the above code, the user can access below interactive table to perform multiple actions and visualize the dataset.
D-tale interactive table shows the number of columns and rows of the dataset at the top left corner (in this case, 1035 rows and 6 columns)
D-Tale shows us the data in the same way that pandas would. The only difference is the menu in the top left corner that allows us to do many things with the data.
Clicking on any of the column headings opens a drop-down menu that gives us options to sort the data and display it exactly as we want it.
The menu has many options. Let’s explore each one by one.
Describe option:
The most interesting options we can find in this menu are Describe that shows us a statistical analysis of the selected column and Column Analysis that shows us a histogram of the selected column.
After selecting the required column we will be able to see three major options Describe, Histogram, and Categories options in the middle of the screen. The describe option gives us statistical information about selected column data and Histogram gives the corresponding graphical representation. The third option is Categories In that, we will be able to select the X-axis variable from the Category Breakd.
Another important and awesome feature of this Library is the ‘Code Export’ option at the top right corner. This feature provides the code for a particular output. also, In the Describe menu, we will be able to see all the outliers and Uniques values at the bottom.
Dimensions/Main Menu:
In the D-Tale main menu, you will find all the options available in D-Tale. This is where all the magic of D-Tale is. By clicking the highlighted play button at the top left corner of DataFrame you will be able to view all Options as shown in the below image.
D-Tale provides the ability to perform simple operations such as sorting, filtering, and formatting.
The Duplicates option is the main will help us to remove duplicate values in the Data set and the Custom Filter option has the ability to apply filters to columns. The most important Options used for data visualization are Correlations, Charts, and Heatmaps.
Correlations:
Once you click on the Correlations option in the Main menu, it will redirect you to another Correlation Tab. In this, we have to Choose variables in the ‘View correlation for’ dropdown. After selecting values in Dropdown if you click on the Correlation value, you will be able to see a visual representation of the Correlation between two variables in the Scatter plot as shown in the below image.
Correlation
Finally, one of the fanciest options is Heatmap. It shows the colors in the data table according to the value of each cell. the export CSV option in can b used for exporting the graphical data into a CSV file
Conclusion
In this paper, we saw how D-tale can save our time and efforts to create visually appealing and insightful EDA reports. This EDA Reporting tool is highly useful in analyzing and visualizing all types of datasets. D-Tale is one of the popular libraries in the Data Science community. There are a lot of options are available in D-Tale which helps us to understand the trend of Data from a statistical perspective, Hence keep exploring.
Reference
One Comment
Very helpful article thanks to the author… | https://www.analyticsvidhya.com/blog/2020/11/data-exploration-dtale/ | CC-MAIN-2021-31 | refinedweb | 788 | 61.87 |
Data::XML::Variant::Build - Data::XML::Variant "build" class.
Version 0.01
Do not use this class directly. Data::XML::Variant will return an instance of this class and autogenerate the requested tag methods.
None.
my $build = Data::XML::Variant::Build->New;
Returns a new Data::XML::Variant::Build object. Takes no arguments.
$xml->Add($tag); $xml->Add($tag, $method);
This method will create three tag methods for you for the start tag, end tag, and just "tag". For example:
$xml->Add('foo'); print $xml->start_foo; # <foo> print $xml->foo('message'); # <foo>message</foo> print $xml->end_foo; # </foo>
The base name of the methods defaults to to tag name, but a second argument will allow you to specify a different method base name name if the tag name is not a legal method name.
For example:
$xml->Add('foo'); $xml->Add('florp:bar', 'bar'); print $xml->start_bar([ id => 3 ]), #attributes to 'bar' $xml->foo('message'), $xml->end_bar; # or print $xml->bar( [ id => 3 ], $xml->foo('message') ); # same thing
That should output:
<florp:bar<foo>message</foo></florp:bar>
Method names must be legal for Perl and must begin with a lower-case letter. The latter restriction ensures no collision with the pre-existing methods in this class, all of which begin with an upper-case letter.
This method will croak if the method already exists in this class or if you attempt to override a method in
UNIVERSAL.
Any arguments passed to the
end_$tag method will cause that method to croak.
Note: because this method adds new methods directly into this namespace, all instances of this object will have access to the same methods. See the
Remove and
Methods methods to see how to manage them. This may change in the future.
See ATTRIBUTES for information about how attributes are handled.
$xml->Encode($sub_ref);
Don't like how the XML is encoded? Supply a subref which handles the encoding for you. The first argument to the subref will be the
Data::XML::Variant::Build object and the second argument will be the string to be encoded. For example, to eliminate all encoding:
$xml->Encode(sub { my ($self, $string) = @_; return $string; });
By default, data is encoded with
HTML::Entities::encode_entities with no arguments other than the data string.
my $closing = $xml->Closing; $xml->Closing(' /');
This getter/setter determines how self-closing tags terminate. Generally there should not be a space prior to the trailing slash:
print $xml->foo; # <foo/>
Some XML/HTML parsers do not like this and require a space before the trailing slash. Use this method to provide this (or any other closing).
$xml->Closing(' /'); print $xml->foo; # <foo />
my $quote = $xml->Quote; $xml->Quote("'"); # use single quotes
Getter/setter for attribute quote character
my @methods = $xml->Methods;
Returns a list of tag methods which have been added.
$xml->Remove('foo'); # remove the foo tag methods $xml->Remove; # remove all tag methods
This method allows you to remove undesired methods from
Data::XML::Build namespace. Specifying a tag name will remove the corresponding start, end, and tag methods. Calling without arguments will remove all methods.
Warns if the tag name is not found.
Return true on success.
my $Cdata = $xml->Cdata($string);
Returns a CDATA section for XML. Does not escape data.
print $xml->some_tag($xml->Raw($string));
This method allows you to insert raw, unescaped data into your output.
Use with caution.
print $xml->Decl; # <?xml version="1.0"?> print $xml->Decl([version => '1.0', encoding => "utf-8", standalone => "yes");
This method returns an XML declaration with a version of '1.0'. If you desire additional attributes, you may specify an attribute list.
version must be explicitly specified if you have attributes.
$xml->PI( 'xml-stylesheet', [ type => 'text/xsl', href => '' ] ); # <?xml-stylesheet type="text/xsl" href=""?>
Returns a process instruction.
$xml->Comment('this is a > comment'); # <!-- this is a > comment -->
Returns an XML comment. Comment is padded with one space before and after the
Attribute handling is an annoying problem. Many tools require XML attributes to appear in a particular order even though this is not required. We handle this by allowing you to specify attributes in three different ways.
This is the preferred method. Pass an array reference for attributes and the attributes will be added in the correct order:
print $xml->foo( [ id => 2, class => 'none' ] ); # <foo id="2" class="none"/>
This is the traditional method. Pass a hash reference for attributes and the attributes will be added, but the order is not guaranteed:
print $xml->foo( { id => 2, class => 'none' } ); # <foo id="2" class="none"/> # <foo class="none" id="2"/>
If you are forced to work with an XML variant which has unusual attribute requirements, you may pass a scalar reference and the attributes will be added to the tag exactly as you have passed them (but there will still be a space after the tag name):
my $attributes = "id=2 selected"; print $xml->foo( \$attributes ); # <foo id=2 selected/>
Many people don't like their XML running on the same line. Because the goal of this module is to give you fine-grained control over how you need to produce your XML variant, it will not attempt to second guess where you want newlines. You will have to insert them yourself.
Here's an example. Note how the individual method calls are joined on newlines but method calls inside other method calls have newlines inserted between them.
my $xml = Data::XML::Variant->new( { 'ns:foo' => 'foo', 'bar' => 'bar', 'ns2:baz' => 'baz', } ); my $xslt_url = ''; my $url = ''; print join "\n" => $xml->Decl, # joining outer elements in \n $xml->PI( 'xml-stylesheet', [ type => 'text/xsl', href => "$xslt_url" ] ), $xml->foo( [ id => 3, 'xmlns:ns2' => $url ], "\n", $xml->bar('silly'), "\n", $xml->Comment('this is a > comment'), "\n", $xml->baz( [ 'asdf:some_attr' => 'value' ], 'whee!' ), "\n" );
That will print the following:
<?xml version="1.0"?> <?xml-stylesheet <bar>silly</bar> <!-- this is a > comment --> <ns2:baz asdf:whee!</ns2:baz> </ns:foo>
Yes, there are an unbound prefixes in that example. This was deliberate.
Curtis "Ovid" Poe,
<ovid@cpan.org>
Please report any bugs or feature requests to
bug-data-xml-variant. | http://search.cpan.org/~ovid/Data-XML-Variant-0.02/lib/Data/XML/Variant/Build.pm | CC-MAIN-2016-18 | refinedweb | 1,024 | 64.51 |
[Share Code] emoji to ui.Image or png file
The function below is pretty trivial. But opens up a door for more built in assets to use. I hadn't thought about it before like this.
Also @Webmaster4o gave me a great web resource to look up / search for emoji's - link
import ui # Forum @Phuket2 # just an example function to turn an emoji char into a ui.Image # with option to save it as a png file, if you pass file_name. # the function is basic. does not try help you with the font_size # just about the idea of doing it, many more assets available to use def emoji_to_image(emoji_char, w =32, h=32, font_name = 'Arial Rounded MT Bold', font_size = 28, file_path = None): r = ui.Rect(0, 0, w, h) with ui.ImageContext(r.width, r.height) as ctx: # just draw the string ui.draw_string(emoji_char, rect=r, font=(font_name, font_size), color='black', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) img = ctx.get_image() # write a file if file_path if file_path: with open(file_path, 'wb') as file: file.write(img.to_png()) return img if __name__ == '__main__': img = emoji_to_image('💋', file_path = 'junk000.png') img.show() # displays in the console img = emoji_to_image('🇹🇭', w = 256, h = 256, font_size = 250, file_path = 'junk001.png') img.show() # displays in the console
Nice! The console's zoom effect works pretty well for that first example. 😀
The main reason I'm still including the (somewhat outdated) Emoji image set, instead of something like this (which allows using all the new Emoji) is that the image set has a higher resolution than the iOS emoji font.
Could be fun to combine something like this with
unicodedata...
| https://forum.omz-software.com/topic/3232/share-code-emoji-to-ui-image-or-png-file/3 | CC-MAIN-2020-10 | refinedweb | 274 | 67.04 |
Main.java
package com.herocraftonline.rightlegred.minescroller; import java.awt.Font; import java.awt.Graphics; import javax.swing.*; import com.herocraftonline.rightlegred.minescroller.player.Player; public class Main extends JFrame{ public Main(){ setTitle("MineScroller"); setSize(500,500); setVisible(true); setFont(new Font("Minecraft Regular",Font.PLAIN,20)); } public void paint(Graphics g){ } public static void main(String[]beans){ Main m = new Main(); Player p = new Player(60, 60, 3); m.paint(p.getGraphics()); } }
Player.java
package com.herocraftonline.rightlegred.minescroller.player; import java.awt.Graphics; import java.awt.Image; import javax.swing.JComponent; public class Player extends JComponent{ private int x, y; private int width, height = 40; private Image img; private int Health; public Player(int x,int y,int Health) { this.x = x; this.y = y; this.Health = Health; } public void paint(Graphics g){ g.drawRect(x, y, width, height); } }
Player is what I'm trying to draw, but I can't seem to get it to work. I get no errors, while I do get a see through screen which isn't as pleasing as the player would be.
As well as the above, I must ask another question -
Fluid movement, how can I achieve this in my game? I know doing y++; won't give you fluid movement and that I'm going to have to use velocity to create this. Would it be something like this:
int yVel; int xVel; y += yVel; x += xVel;
I'm aiming to create smooth movement, which is pleasing to the eye and generally makes the game nicer to play. I've posted this thread here instead of Java because this is for a game I'm attempting to make. So I assumed it would probably be best to post this here. Sorry if this is wrong.
Please remember this is my first game. Please don't be harsh and yes, I'm attempting to copy the style of Minecraft. But in 2D side scroller. While this is a bad thing to do, this game is intended to help me get my foot in the door, nothing else.
This post has been edited by NemY: 09 April 2011 - 03:48 AM | http://www.dreamincode.net/forums/topic/226787-2d-game-java-movement-drawing-and-general-help/ | CC-MAIN-2017-22 | refinedweb | 360 | 68.67 |
JavascriptMultiDimArrays
Author: Eric Haines (Eric5h5)
Description
NOTE: This is largely obsolete in Unity 3.2, since multidimensional arrays can be declared directly in JS now. Please upgrade if you haven't already! However, the syntax for directly declaring the type of jagged multi-dimensional arrays is still missing in JS, so if you need those, this script can still be useful (though you can delete the rectangular array functions and just leave the jagged array functions).
Multi-dimensional (AKA rectangular) arrays in Javascript are a bit of a conundrum, prior to Unity 3.2. Ideally it should be possible to write something like "var foo = new int[5,6];". Alas, this results in a compiler error. However, it is possible to write this:
var heights = Terrain.activeTerrain.terrainData.GetHeights(0, 0, 10, 10); print (heights);
The output, assuming a terrain is present, is "System.Single[,]" (AKA "float[,]"). And you can use the array as expected with no issues. So, clearly these sorts of arrays are implemented in Javascript, with the exception of the ability to declare them. This makes them only marginally useful, unless you're working with terrain data.
Or are they? Javascript uses type inference, so it's not necessary to specify the type if the compiler can figure it out. For example, "var foo = 5;" results in "foo" being declared as an int, since an int value was specified. Likewise, GetHeights() returns a float[,], so "heights" is declared as a float[,] through type inference. We can use this feature, together with the fact that there's no problem declaring rectangular arrays in C#, to allow us to declare arrays like this in Javascript as well with minimal fuss.
Usage
Put the MultiDim script below in your Standard Assets/Scripts folder (if you don't have one, make one). This way it can be accessed from Javascript easily without having to worry about compilation order problems. Now you can use the MultiDim class and type inference to declare rectangular 2D and 3D arrays of ints, floats, and strings. For example:
var foo = MultiDim.IntArray(100, 200); foo[52, 49] = 123; var foo2 = MultiDim.IntArray(100, 200, 300); foo2[99, 199, 299] = 1; var numbers = MultiDim.FloatArray(50, 60); numbers[10, 20] = Mathf.PI; var someStuff = MultiDim.StringArray(10, 10, 10); someStuff[0, 0, 7] = "w00t";
If you need to use additional types or dimensions, it should be pretty obvious how to make new functions in the MultiDim script that will return these, even if you don't know C#...just use the existing functions as a template. If you're using Unity types such as GameObject, put "using UnityEngine;" at the top of the script so the namespace is imported.
Jagged Arrays
Along the same lines, jagged arrays (where each row can have a different number of columns) can be made in Javascript by using an array of arrays. But if you would rather use jagged built-in arrays for speed instead of using dynamic arrays, the method for being able to declare them directly is missing, though they can still be used. The work-around uses the same technique as above, so you can use JaggedInt, JaggedFloat, and JaggedString to declare these sorts of arrays by passing in a value representing the number of rows. Each row is null by default and must be declared individually. For example:
var foo = MultiDim.JaggedInt(3); foo[0] = new int[5]; foo[1] = new int[21]; foo[2] = new int[7]; foo[1][19] = 55;
It's also possible to declare jagged arrays using type inference with initial values:
var foo = [ [1, 2, 9], [4, 5, 2], [0, 0, 7] ];
The type of "foo" in this case is System.Int32[][] (AKA int[][]). If you use this method, you don't need the MultiDim script.
C# - MultiDim.cs
public class MultiDim { public static int[,] IntArray (int a, int b) { return new int[a,b]; } public static int[,,] IntArray (int a, int b, int c) { return new int[a,b,c]; } public static float[,] FloatArray (int a, int b) { return new float[a,b]; } public static float[,,] FloatArray (int a, int b, int c) { return new float[a,b,c]; } public static string[,] StringArray (int a, int b) { return new string[a,b]; } public static string[,,] StringArray (int a, int b, int c) { return new string[a,b,c]; } public static int[][] JaggedInt (int a) { return new int[a][]; } public static float[][] JaggedFloat (int a) { return new float[a][]; } public static string[][] JaggedString (int a) { return new string[a][]; } } | https://wiki.unity3d.com/index.php/JavascriptMultiDimArrays | CC-MAIN-2019-39 | refinedweb | 757 | 61.46 |
Url Routing is the process of reroute the http request, the reason behind it was to create a clean meaningful SEO friendly url.
For example, if you have a ecommerce website where you have thousands products, and you want to display each product details dynamically on a page called “product”,
the page may look like , then 11, 12 so on , all URL will look same except the change of product id value.
So the repetitive url does not make sense, and also search engine cannot understand the difference between each url.
Now with the help of routing, you can make the url to a meaningful url. for example,
you can make it like or
Before you start implementing routing, I assume you have basic understanding of Asp.net MVC Architecture.
Let's start with System.Web.Routing
In your App_Start folder, there is a file called RouterConfig.cs, this is how the code will look like
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } }
Now, if you notice the above "RegisterRoutes" acutlly does the registration at Application_Start event of in
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { RouteConfig.RegisterRoutes(RouteTable.Routes); } }
Now you need to understand how you can add a new
routes.MapRoute(...)
in RouteCollection. One default implementation given in above
MVC applications use the ASP.NET routing system that decides how URLs map to controller,
action and optional parameter
url:"{controller}/{action}/{id}", every time you add a new MapRoute with a new name
routes.MapRoute( name: "jobview", url: "jobs/job/{jobid}/{jobTitle}", defaults: new { controller = "jobs", action = "job", jobTitle = UrlParameter.Optional, jobid = UrlParameter.Optional });
Now you learn how to call this from your dynamic data, let’s say you have a collection of job, and for each job you want to create a dynamic SEO friendly URL
@foreach (vwJob j in jobList) { <a title="@j.Title.ToLower()" href='@Url.RouteUrl("jobview", new { jobid = @j.jobId, jobTitle = Util.GetSeoFriendlyName(@j.Title.ToLower()) })' > @j.Title </a> }
Notice, href='@Url.RouteUrl()' to call the route map with name.
Have fun with Routing !
You should also learn Attribute Routing in Asp.net MVC using Asp.net Core framework. | https://www.webtrainingroom.com/aspnetmvc/routing | CC-MAIN-2021-49 | refinedweb | 385 | 50.43 |
A simple guide to sending data from one ESP8266 to another over Wi-Fi using an ad-hoc, device to device network, without using a wifi router.
The ESP8266WebServer library allows you run an ESP8266 as a basic webserver and access point. This can process data received from a remote sensor over Wi-Fi without connecting the devices to a network or router.
For this tutorial I’m using two NodeMCU boards from eBay but you can do this with any ESP8266 based board. To simulate the output from a sensor I’m using a trim pot potentiometer like these from eBay. I’m also using two small OLED screens from AliExpress so you can see the data easily but you don’t need these if you want to see the results in the serial monitor.
As you can see in the video below, when the potentiometer pot is adjusted the value shown on the transmitting module OLED changes to reflect the change in voltage to pin A0. On the receiver, the value on the OLED is updated as the data is received from the transmitter.
If you don’t have the Arduino IDE set up for the ESP8266 range yet you can find a tutorial here – under Setting Up the Arduino IDE for the ESP8266 Range.
I’m using these settings in the IDE (Tools menu) ..
The wiring is identical for both the transmitter and receiver except the transmitting device has the potentiometer connected to the power and analogRead(A0) pins. You might need to connect the A0 pin via a resistor on some boards as they only read up to 1v on this pin.
If it’s not installed already you will need to install the U8g2 display library (for the OLED) It can be installed using the Arduino IDE library manager – open Sketch > Include Library > Manage Libraries and search for and then install U8g2.
Here’s the sketch for the transmitter. There’s a more verbose version if you want to see the output in the serial monitor or need to debug here.
#include <ESP8266WiFi); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } u8g2.begin(); u8g2.setFont(u8g2_font_logisoso62_tn); u8g2.setFontMode(0); // enable transparent mode, which is faster } void loop() { // read the analog in value:); }
On the server (receiver) the sketch looks like this. Again, if you want a version with serial outputs to see more details you can download that here.
#include <ESP8266WiFi.h> #include <ESP8266WebServer"; ESP8266WebServer server(80); void handleSentVar() { if (server.hasArg("sensor_reading")) { // this is the variable sent from the client int readingInt = server.arg("sensor_reading").toInt(); char readingToPrint[5]; itoa(readingInt, readingToPrint, 10); //integer to string conversion for OLED library u8g2.firstPage(); u8g2.drawUTF8(0, 64, readingToPrint); u8g2.nextPage(); server.send(200, "text/html", "Data received"); } } void setup() { delay(1000); u8g2.begin(); u8g2.setFont(u8g2_font_logisoso62_tn); u8g2.setFontMode(0); // enable transparent mode, which is faster WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); server.on("/data/", HTTP_GET, handleSentVar); // when the server receives a request with /data/ in the string then run the handleSentVar function server.begin(); } void loop() { server.handleClient(); }
Hopefully this tutorial helps you start off in the right direction with using Wi-Fi on these devices. I’ve seen other tutorials that made things a lot more complicated than they need to be.
Buy Me A Coffee
If you found something useful above please say thanks by buying me a coffee here...
124 Replies to “ESP8266 Sending Data Over Wi-Fi to another ESP8266”
Thanks for posting this.
I am trying to have ESP8266 units and send temperatures. one in the basement, one in the attic all to the one near the WiFi router. 2 sending, 1 receiving
You’ll need to change the query string sent so the receiving ESP will know which one sent the data. Something like:
Basement ESP: ?sensor_reading_basement=
Attic ESP: ?sensor_reading_attic=
On the receiver you’ll need a smaller font to fit everything on the screen and change the handleSentVar to listen to the two new variables above. This system doesn’t use your WiFi, it runs on its own network.
Hi, is it possible to send sensor value from an esp8266 to an esp32 with the same technic ?
best regards
Yep. The data is sent as a GET request like this: /data/?sensor_reading=123 so any web server can parse the information and use it. I’m not sure exactly which libraries you need but the ESP32 has equivalents to the ESP8266WiFi and ESP8266WebServer libraries.
Hello! Could you help me a little bit? I just want to send an int value from one esp board to other.
I’ve connetcted a pontentiometer on the first esp(Wemos D1 mini), and gets a value using map() function. I want to send it to the second board for changing blink interval of LED.
I tried to change your sketch, but got no luck =(.
Thank you in advance!
Hi there.
First check the simple blink sketch works:
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // initialize onboard LED as output
}
void loop() {
digitalWrite(BUILTIN_LED, HIGH); // turn on LED with voltage HIGH
delay(1000); // wait one second
digitalWrite(BUILTIN_LED, LOW); // turn off LED with voltage LOW
delay(1000); // wait one second
}
If that’s OK then something like the following might work. I don’t have the project set up at the moment.
#include < ESP8266WiFi.h > //(remove spaces – wordpress comment workaround)
#include < ESP8266WebServer.h >
const char *ssid = “poopssid”;
const char *password = “pingu4prez”;
int varDelay = 1000;
int ledState = LOW;
unsigned long previousMillis = 0;
ESP8266WebServer server(80);
void handleSentVar() {
if (server.hasArg(“sensor_reading”)) {
varDelay = server.arg(“sensor_reading”).toInt();
server.send(200, “text/html”, “Data received”);
}
}
void setup() {
delay(1000);
pinMode(BUILTIN_LED, OUTPUT);
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
server.on(“/data/”, HTTP_GET, handleSentVar);
server.begin();
}
void loop() {
server.handleClient();
unsigned long currentMillis = millis();
// if enough millis have elapsed
if (currentMillis – previousMillis >= varDelay) {
previousMillis = currentMillis;
// toggle the LED
ledState = !ledState;
digitalWrite(BUILTIN_LED, ledState);
}
}
Yeah! =) It works. Thank you so much!
hi,
It`s very useful project
I need help for my project,
I want to send data via serial form ESP-12 to ESP-01 , That way one RC522 RFID connect to ESP-12 and read tag card and it should be send tag to the ESP-01 with high speed like your project.
Thanks so much if you can help me 🙂
Hi,
Do you have the code for the reading the tag? In that code you just need to have it send the data in the same way the transmitter code above sends data to the other ESP.
Hi,
Thanks for the example. It saves me a lot of work/time finding out the wheel as I’m a basic electronics engineer and not a TCP/IP/HTML specialist. I’m lazy and have replaced the potmeter for a random generator and the output is written to a serial monitor. All seems to work fine however in my example I have contineously timeouts on client.connect() and client.available(). Any suggestions?
Hi,
At a guess I would say that there are too many connection attempts for the webserver in the ESP8266. Maybe try a delay() command in the loop to slow down the connection attempts? Or if you are feeling brave you could try another webserver:
HI,
I try to do a project in which I have 2 transmitters and one receiver. Each transmitter has a switch and if I press the switch (from a transmitter or the other transmitter) the LED on the receiver should go on. Could you please help me? Thank you.
It shouldn’t be too hard. Both transmitters would have the same code that detects the button press and sends this in the URL “?sensor_reading=on”; to the listening receiver. On the receiver you would set the LED high in the handleSentVar() function.
Thank you. I am a beginner. Could you please help me with the code? I do not understand exactly which lines should I keep and which not.
If you are new to this you should break it down into small parts so you can understand what is happening so you can work with it later. The first thing you need is add a switch to the transmitter. The simplest way (not necessarily the best) is to pull the pin connected to the onboard LED to ground with a your switch (or just connect D4 to GND with a piece of wire).
Then use the code below to see the change in the serial monitor:
const int button = 2; // D4/GPIO2 is connected to the internal LED (which is lit when the pin is LOW).
int pinState= 0;
void setup() {
Serial.begin(9600);
pinMode(button, INPUT);
}
void loop() {
pinState = digitalRead(button);
if (pinState == LOW) {
Serial.println(“LED Turned ON”);
delay(1000);
}
else {
Serial.println(“LED Turned OFF”);
delay(1000);
}
}
Then you need to edit the code in the tutorialfor the transmitter so it sends the button state rather than the sensor reading something like this:
String url = “/data/”;
url += “?button_state=”;
url += pinState;
Hi, cool project with great info! I want to output the potentiometer reading via pwm instead of seeing the value on screen. Could you guide me on the coding portion?
Do you have the code for the PWM part on the receiver? It shouldn’t be too hard to change the code in the tutorial to update the PWM code rather than the screen.
No I have very basic understanding of programming. I usually troll tutorials such as this looking for code similar to what I need and then try to stitch the bits together 🙁
I have your original code with the oled portions omitted on both mcu
I don’t really have time to look at this but if you ask on the forum here – someone will probably help. Tell them how far you’ve got and what you want to achieve.
can you help me i need code to send data between two esp32 , data from sensors in one esp32 to onther
The code should be mostly the same. You’ll need to use different libraries for the wifi and wifi server and possibly change the pins for the oleds if you are using them.
i used this code to transmit the data from esp32 and they connected together but sensorValue still constant at “4095” in both esp32 , what should i do ?
Do you have code similar to this on the transmitter so you can see the output from the sensor:
// read the analog in value:
sensorValue = analogRead(A0);
//(sensorValue);
Serial.print(“\t output = “);
Serial.println(outputValue);
this code is work correctly with me ..
but i wanna send 5 values from esp instead of 1 value and save values in the other esp , what edits can i do ?
Thank you in advance
So you want to take 5 sensor values and send them together? You can just make 5 variables to hold each one and send it like this.
url += “?sensor_reading1=”;
url += intToPrint1;
url += “?sensor_reading2=”;
url += intToPrint2;
etc…
Or maybe a tidier way is to put them all into one string, send that and process it on the other side. One way of sending strings:
I already do this but it didn’t receive values in the other esp and it display “Client Timeout !” in serial monitor of transmitter esp …
Thank u very much for your support .
Client timeout is not connecting to your WiFi. Try some of the ESP8266 Wifi examples to get this working. It’s always best to start simple and then add things bit by bit to check as you go. If you are new to this.. it’s much better to do that than try and edit a more complicated script to fit your case.
In your example the oled on the receiver is updating very quickly. I implemented the example code on two of my nodeMCU’s and I get a much slower response time. Did you use a different code for the video? Thanks for the tutorial by the way.
It’s the same script. In the tutorial there’s a version with more output on the serial port which might help diagnose. Someone in the comments said theirs worked better with this line:
WiFi.mode(WIFI_AP);
added above this line:
WiFi.softAP(ssid, password);
in the receiver code but this isn’t in the examples code I developed this from.
Hey WordBot, thanks for your patience, can you tell me how can I send to multiple receivers?
Looking quickly at this. If you take the part // We now create a URI for the request. Something like /data/?sensor_reading=123 and turn it into a function. Then take this part // Use WiFiClient class to create TCP connections and do something like
const char * host = “192.168.4.1”;
const int httpPort = 80;
if (client.connect(host, httpPort)) {
// new function here
}
Once you have that working the same as the existing example you can then make it a loop that loops through the IP addresses you have for the clients.
Hi
the project you have explained in a crispy and simple way thanks for the new thing which I learned from you.
But when I am trying to compile your code I am getting an error saying
WARNING: Spurious .github folder in ‘Adafruit Fingerprint Sensor Library’ library
WARNING: Spurious .github folder in ‘Adafruit GPS Library’ library
WARNING: Spurious .github folder in ‘RTClib’ library
In file included from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/opt.h:51:0,
from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/init.h:40,
from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/IPAddress.h:27,
from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:31,
from C:\Users\KERNEL\Documents\Arduino\NodeMCU_Transmitter\NodeMCU_Transmitter.ino:1:
C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:1301:2: error: #error TCP_MSS must be defined
#error TCP_MSS must be defined
I am not getting this error what actually its saying. Please help me ,thanks in advance
Your installation for the ESP8266 package is bad. How did you set up the esp8266 library? There’s a tutorial on this page for that:
Hey,
I’m trying to transfer values from one arduino UNO to other arduinoUNO using ESP8266. I ‘m in the process of doing the same but I’m not able to transfer data neither I’m able to connect at the same HTTP address and port. For keeping program simple, initially, I’m trying to transfer a specific value of ‘temp’ to other ESP8266.
Hi, Have you tried with the client IP as:
const char * host = “192.168.4.1”;
Yes, I tried. The default IP which is being allocated to the client is “192.168.4.2”.
Did you see the server example with more verbose output – maybe this will help. Maybe paste your current client and server code at and I’ll try to take a look.
Hey, thanks. I’m getting something better than earlier now. The client is printing the values. Server program still needs some editing. ‘generic ESP8266’ boards. What could be the issue?
Which LCD are you using? Try some of the examples for that LCD first.
Hi, I’m trying to set up 3 nodemcu esp8266 to be both client and server. Basically what it would do is, if ESP01 sense a motion it will turn on the led then notify the other two esp that there is someone so that they could also turn on their led. At the same time, the ESP01 will also be ready for any incoming notification that the other two esp might send. Do you have any idea to make this work?
I’m pretty sure you can have client and server running on the same ESP8266. Think of them as a triangle. Each one sends to the other two it’s connected to via their IP addresses. You could include in the message a code to say which device was triggered and the receiving device could flash the LED in a pattern to show the device number.
Thank you for replying.
Do you have any example that I can refer to?
I don’t have an example but you can look in the ESP8266 example in the IDE and hack something together. Another (possibly better) way to do this is to use a mesh network:
Hi,
how to make one esp8266 ask another esp8266 to light up it’s led at a certain brightness.
Hi, In the Arduino IDE: File>Examples>Basics>Fade has a very basic setup for controlling the brightness of an LED. You can use similar code on the receiver from the tutorial above to control brightness. Search ESP8266 PWM for other tutorials.
Hello.
How can i turn this sketch into a simple dimmer that would send from the nodemcu a pwm signal from a touchscreen dimmer slider to output from the receiver the same input that came from the transmitter?
Also, can this be done with 2 nodemcu receivers to output the same dimmer function simultaneously?
thank you
Kyle
Hi, you need to read up about PWM input on the ESP32. You might be able to use the same pin and read the voltage but PWM can be quite complicated. Do you have to use the touchscreen slider?
Hi!
I loved your project! Im trying to do same, but instead read a potentiometer on analog input, Im using HX711 load cell interface on board…. My idea is measure value on nodemcu main, and show value on second nodemcu with oled display… same as your example, but getting this value instead of potentiometer… here is my adapted code (Im totally newbie)… I know routine for weight is correct as I tested… but I cant get it together with wifi transmission… can you help me?
//==================load cell routine =================================
#include “HX711.h”
#define DOUT D5
#define CLK D6
HX711 balanca;
float calibration_factor = 4142130; // initial value
void setup()
{
Serial.begin(9600); // serial 9600 Bps
balanca.begin(DOUT, CLK); // start load cell
balanca.set_scale();
zeraBalanca (); // Zero Load CEll
}
void zeraBalanca ()
{
Serial.println();
balanca.tare();
Serial.println(“Balança Zerada “);
}
void loop()
{
balanca.set_scale(calibration_factor);
Serial.print(“Peso: “);
Serial.print(balanca.get_units(), 3); // print weight 3 digits
Serial.print(” kg”);
delay(500) ;
}
//=======================================================
Value I want show on display is this one: balanca.get_units()
so I replaced it on your code on sensorValue
What Im doing wrong?
Much thanks for your help!
Assuming the result of balanca.get_units() is an integer you should be able to do this
String url = “/data/”;
url += “?sensor_reading=”;
url += balanca.get_units();
If you test with this sketch you will see more information in the serial monitor:
Hi
thanks for reply… Ufortunatelly it not worked… I get info on serial monitor but no info on both display…. Sorry for my newbie…. here is full code.. I just mixed code you provided with one from post above….. Any tip to help me please? You are my only hope….lol
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include
#include
//====================
#include “HX711.h”
#define DOUT D5
#define CLK D6
//====================
/
//======================================
HX711 balanca;
float calibration_factor = 4142130;
//=====================================
void setup() {
Serial.begin(115200);
delay(10);
//=====================================
balanca.begin(DOUT, CLK);
balanca.set_scale();
zeraBalanca ();
//=====================================
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print(“Connecting to “);
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
Serial.begin(115200);
u8g2.begin();
u8g2.setFont(u8g2_font_logisoso62_tn);
u8g2.setFontMode(0); // enable transparent mode, which is faster
}
//===============================================
void zeraBalanca ()
{
Serial.println();
balanca.tare();
Serial.println(“Balança Zerada “);
}
//==============================================
void loop() {
// read the analog in value:
//sensorValue = analogRead(A0);
sensorValue = (balanca.get_units());
balanca.set_scale(calibration_factor);
Serial.print(“Weight: “);
Serial.print(balanca.get_units(), 3);
Serial.println(” kg”);
delay(500) ;
sensorValue = (balanca.get_units());
//(balanca.get_units());
Serial.print(“\t output = “);
Serial.println(balanca.get_units());
// Serial.print(“Comunic = “);
//Serial.println(intToPrint[5]);
char intToPrint[5];
itoa(outputValue, intToPrint, 10); //integer to string conversion for OLED library
Serial.print(“Comunic = “);
Serial.println(intToPrint);
String url = “/data/”;
url += “?sensor_reading=”;
url += balanca.get_units();
//url += intToPrint;;
}
}
Serial.println();
Serial.println(“Closing connection”);
Serial.println();
Serial.println();
Serial.println();
delay(500);
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++
thats full code…. and thats info I get on serial monitor:
+++++++++++++++++++++++++++++++++++++++++++++
09:01:35.282 -> Weight: 0.506 kg
09:01:35.785 -> sensor = 0.51 output = 0.51
09:01:35.887 -> Comunic = -2
09:01:36.090 -> Requesting URL: /data/?sensor_reading=0.51
09:01:36.258 ->
09:01:36.258 -> Closing connection
++++++++++++++++++++++++++++++++++++++++++++
and my display shows “0 ” all the time
Thank you!
I think it’s because you are sending a float 0.51(kg) rather than an int 510(g). You can either switch to grams or, on the receiver, change itoa(…) to use this function:
how i change it to int? would fit me perfectly…..
Can you do it with the library to weigh in grams rather than Kgs? If not multiple your sensor value by 1000 (* 1000) to make the Kg value a gram value.
I have no idea, either how to change to grams or where do I multiple *1000 to make it works…. on above code…:/ I know is out of your example idea, but I have no idea how to do it… :/ totally newbie..
thats only thing missing to make it works…. my weight goes from 10grams to 700grams.. dot need to be kg….
I thought it was going to be just changing a setting but this explains how to do it properly:
Hello,
First I’m sorry for my very bad English.
I hope you can help me with a problem, and I want to send 4 variables (first I am testing with 2), as I read lines above I must use something similar to this:
// We now create a URI for the request
String url = “/ data /”;
url + = “? sensor_reading1 =”;
url + = intToPrint;
url + = “/”;
url + = “? sensor_reading2 =”;
url + = “2469”; // number for test
I guess it’s fine since according to serial port monitoring, I’m sending:
Requesting URL: / data /? Sensor_reading1 = 702 /? Sensor_reading2 = 2469
Closing connection
My mistake I think is on the receiver side, the code I am using is:
void handleSentVar () {
Serial.println (“handleSentVar function called …”);
if (server.hasArg (“sensor_reading1”)) {// this is the variable sent from the client
Serial.println (“Sensor 1 reading received …”);
int readingInt1 = server.arg (“sensor_reading1”). toInt ();
int readingInt2 = server.arg (“sensor_reading2”). toInt ();
Serial.print (“Reading 1:”);
Serial.println (readingInt1);
Serial.println ();
Serial.print (“Reading 2:”);
Serial.println (readingInt2);
Serial.println ();
server.send (200, “text / html”, “Data received”);
}
and what I get by serial is:
handleSentVar function called …
Sensor 1 reading received …
Reading 1: 710
Reading 2: 0
I hope you can help me, I will be eternally grateful, a greeting from a distance …
Hi,
Sending via a URL follows this format: /data/?firstvar=value1&secondvar=value2&thirdvar=value3 so the first variable has the ? in front and the others all have &
Your code on the receiving side looks OK to me
Dear WordBot,
Everything works fine, I am indebted to you.
thank you
Hello great article, it really helped me a lot.
I am currently trying to send data (temperature and humidity from each one respectively) from two sender to a receiver, for the first sender i use the following code:
String sensor1 = “/data/”;
sensor1 += “?sensor1h=”;//hum
sensor1 += intToPrint2;
sensor1 += “&sensor1t=”;//temp
sensor1 += intToPrint;
And for the second one im using the following code:
String sensor2 = “/data/”;
sensor2 += “?sensor2h=”;//hum
sensor2 += intToPrint2;
sensor2 += “&sensor2t=”;//tem
sensor2 += intToPrint;
My problem is with the function “handleSentVar” on the receiver side, which has the following written:
void handleSentVar() {
Serial.println(“handleSentVar function called…”);
if (server.hasArg(“sensor1h”) && server.hasArg(“sensor1h”) )
The function does not receive parameters from sensor 2 , how can I do it?
Hi, Probably easier to have two server.on methods like
server.on("/data1/", HTTP_GET, handleSentVar1);
server.on("/data2/", HTTP_GET, handleSentVar2);
on one sender: String url = “/data1/”;
on the other: String url = “/data2/”;
You can then have the two handleSentVar functions displaying the results in each half of the screen.
Thank you very much for your quick response, it helped me a lot.
I have another doubt, is there a way to get the received data to be displayed at defined time intervals?
I receive data from both clients now but it seems that the time in which the server shows data from one and the other is random, for example sometimes it shows too much time readings from sensor 1, and then shows few readings received from sensor 2.
I hope I explained myself well.
Oh nevermind, i just increase the delay at the end of each client to 2000
delay(2000)
thanks again for the first answer
Any idea of the range of this system?
Hmm. I haven’t tested that. It will depend on your circumstances but I have had ESP32 and ESP8266 working on the roof when the router is some distance away. ESP8266 to ESP8266 over Wi-Fi I imagine would be similar. Some ESP32s have an antennae socket. Maybe someone makes an ESP8266 with the same.
Does this require an internet router nearby to work properly, or can it be used without the presence of an internet router?
This project doesn’t use a router.
hello! thanks for posting this tutorial.. i am trying to use my PC as sender, and the wimos d1 mini as receiver.. but, how can i send the data to the wimos? also, is this reactive? i am trying to control a LED from the pc, but need it to react quickly when i send some data..
Thanks
Hi, It should be as fast as any other Wi-Fi based project. On the PC you need some way of requesting URLs on your local network. Something like You can do this in the browser but I don’t know a way of automating it.
Hi, I’m trying to configure this code for my nodeMCU, but I’m not able to understand that i need an live internet connection or is it OK to use it as it is..??
Because of some hardware issue I’m not able to use my second nodeMCU.. please help me with this..thankyou!!!
Hi, You don’t need internet or even a router if you use the server code. It runs as an access point with the server mounted.
Hello, thanks for the post. I’m trying to send data from one esp8266 to another one connected with the computer to show the results in serial monitor. I’m trying to send the values from MPU-6050, which is already working fine but I need to get he results wireless, thats why i want to send to another one and read using serial monitor. Im not sure how to do it… tried the code in this page but did not have success. Is there any ideia how i should do it ? Thanks in advance.
Hi. How many values do you need to send? You probably need to change this code so you can send your data in the query string:
Have a look at the comments above for variations on sending data.
Is a connection required (from the Station device to the AP device) to transfer data?
My ESP8266’s are configured for SoftAP+Station mode and I’d like them to broadcast a simple byte-array status message (basically 1 ethernet frame) in station mode to the other ESP8266’s in SoftAP mode. Basically so they can all update each other on their status. I’d like to issue the status as a brief broadcast frame so they can all see it and hopefully I can eliminate actually making a connection.
Finally is it possible to generate a transmit frame (byte array) and monitor/capture an incoming broadcast frame from the UART side of the device – i.e. using AT commands?
Thoughts?
Whaaaa… this is a bit over my head but maybe look into one of the mesh networks?
Hi, I’ve searched all over the internet for something so simple!
Are there many changes needed to simply send a pushbutton signal to the other board to turn on an LED? I can work around any button parameters, but with the transmit/receive code be the same?
Hi, should be pretty easy. Change this code:
outputValue = map(sensorValue, 3, 1023, 0, 999);
to something like:
outputValue = digitalRead(pin);
and you should see a ‘1’ for outputValue but I’m not 100% sure if HIGH is read as an int.
sir what should i add in the client and server, if i want to send more than 1 sensor value?
This comment should help –
hello sir great tutorial, but i have a little trouble here. I made 2 clients and 1 server . First if client1 is connected to the server, the server is able to handle the data. But if i connect client 2 to the server , suddenly both clients are replying “client timeout!”. I didnt know whats happen to the client? Im really greatfull if you help me out sir thx very much.
==========================================================
//this is the code for client 1 :
String url = “/data/”;
url += “?sensor_reading=”;
url += cm1 ; //data 1
url += “&sensor_reading2=”;
url += cm2; //data2
Serial.print(“Requesting URL: “);
Serial.println(url);
// This will send the request to the server
client.print(String(“GET “) + url + ” HTTP/1.1\r\n” +
“Host: ” + host + “\r\n” +
“Connection: close\r\n\r\n”);
===========================================================
and this is for client 2 :
String url = “/data2/”;
url += “?sensor_reading3=”;
url += cm3;;
}
}
===============================================================
and this is the server :
void handleSentVar1() {
Serial.println(“handleSentVar function called…”);
if (server.hasArg(“sensor_reading”) && server.hasArg(“sensor_reading2”) ){
Serial.println(“Sensor reading received…”);
readingInt = server.arg(“sensor_reading”).toFloat();
readingInt2 = server.arg(“sensor_reading2”).toFloat();
void handleSentVar2() {
Serial.println(“handleSentVar function called2…”);
if (server.hasArg(“sensor_reading3”)) {
Serial.println(“Sensor reading received2…”);
readingInt3 = server.arg(“sensor_reading3”).toFloat();
server.on(“/data/”, HTTP_GET, handleSentVar);
server.on(“/data2/”, HTTP_GET, handleSentVar2);
Hi,
if (server.hasArg(“sensor_reading”) && server.hasArg(“sensor_reading2”) )
Maybe should be
if (server.hasArg(“sensor_reading”) || server.hasArg(“sensor_reading2”) )
I don’t think you can read both client values at the same time.
thanks sir finally i made it. Really thx a lot.
im new in this HTTP field, can you explain to me what is tehcnically happening between esp8266 client and server communication?
i didnt understand about HTTP GET, Response and others.
Great! This explains about HTTP GET etc. It’s the same for any client server system:
Hi
Great Article!
I was wondering if it is possible to display the text with another font such as the ttf files found for Microsoft word?
If not is it possible to display a simple black and white image? perhaps a BMP image?
Thank you and I look forward to your response!
Hi, There’s a list of fonts you can use here:
Other font help:
Bitmaps:
I don’t have any experience of the custom fonts and bitmaps.
Could you assist me to an article that explain how to transmit data for 1 to another ESP8266? For example i use 6 ESPs that working as WiFi Client, all of them connected into a WiFi Router. I search everywhere and couldn.t find a clue for data transmission between Clients using HTTP GET. Maybe i was in a wrong searching keywords?
Could you explain the situation a bit more.. what do the eps8266 do? Send data to each other or just one other?
What is maximum range achieved by this communication??
Means wifi to wifi can we replace with rf!! 🙂
You should be able to use any form of communication but you will have to change the way the data is sent.
How about if the client(nodemcu) deactivate and the server(nodemcu) deactivate too?
And server cut off the output.
I don’t understand what you mean.
hi,
I want to connect 4 nodeMCU through wifi connection , so can you suggest me an idea?
Hi, maybe this will help – (using a mesh network)
Hi ,thank you for your great work!
I want to build 3 tally lights for live streaming. So 1 transmitter and 3 receivers. On the transmitter 1 want to use 6 pin’s to check if the line is high(through our switcher). On the reciever side, I want to use 2 pin out’s to used with led’s. We can use the wifi in the builiding.
Thank you 🙂
Hi, what have you so far with the project? Do you have code for the transmitter apart from the sending to the receivers?
Hi, I have done nothing. It is a idea. But I want to know if it’s possible before I sink in the time(not to say I am short on time 🙂 ).
I was thinking to use your code, because it looked promising. But I am kinda new to all of this.
Should be pretty easy. Just monitor the pins for a change (in the loop) and if one goes high then pass the pin number to a function that uses if/else or a switch statement to send the ‘light led’ command to the correct IP address.
Hi,
I just want to sent the following “” with an esp8266, connected to my router, running an exsisting sketch, instead of making a port hi or low. Could you please point me in the right direction?
Thanks in advance.
Hi, How do you want to trigger sending the message to the other device?
Hi WordBot,
I am controling valves of my heating by wires so i make a pin low to switch a relay.
Now I want to go places where i cant use wires so I was thinking of using a esp with easy esp and a relais to accomplish my needs.
I hope you understand.
Regards Loek
Hi, How about using Sonoffs? – ? There’s loads of tutorials on the net and it might be safer than using ESP8266s with relays.
Hi, i found a httpclient function named put. Works like a charme.
Thanks for your suggestion.
hi there,i am a beginner,
I want to use a 16*2 lcd connected with I2C in place of the oled,and some push buttons wich will allow a simple text to be sent from the transmitter to the receiver,what modification can i make to the code
Hi, I don’t really have time at the moment to look at this but take it step by step and look at some other tutorials on the internet.
Hi,
is it possible to make it connect to your WiFi instead of using the integrated system? For both the receiver and transmitter? Using it for the long lost tally light project :).
Hi, I don’t have the code to hand but if you give the devices a fixed IP address on your network you can communicate between them via their IP address.
Hi,
thank you for the reply.
I got it figured out, it wasn’ that dificult.
Hello I’m new to using the nodemcu and when is use servo.attach, I think it makes both nodemcus not work together and all I get is this.
Configuring access point…AP IP address: 192.168.4.1
HTTP server started
ets Jan 8 2013,rst cause:4, boot mode:(3,6)
wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vffffffff
~ld
⸮”l r⸮olph
Configuring access point…AP IP address: 192.168.4.1
Hi, Is the servo attached when you do this?
yes
Try it without the servo. I think it’s crashing because of the power.
It didn’t work, I’m still getting the same feedback from the nodemcu. It only happens when the code is uncommented, if I comment the code it fixes, but then I cant use the servo.
Does the servo work if you flash an example that uses it? You should make sure both parts of the project work separately first. Then when you join them together you will have more idea of where the problem is.
It has something to do with servo code but it doesn’t seem like the .attach wants work or the Digital pins don’t want to work. I tested all of the nodemcus I had but none of them worked. Sadly no it still doesn’t work when I separate the code
I think i might have figured it out, I found this code: servo.attach(2); //D4 I think it means that the code and the digital pins are 2 points off, so to attach the servo to pin D5, I would need to write servo.attach(3); But I’m not home to test it, so ill see later.
Yeah the pins on the board don’t match the pins in code on the ESP8266. You need to find a pinout for your board similar to this:
Thank you this helped a lot, now all I need to do is get home and see if this fixes everything.
Thanks for this simple to understand sketch!
Can I use the same function the other way around? I would also like to send a value from the server to the client.
It’s a while since I did this but I’m pretty sure the devices can both send and receive. Maybe installing client and server on both or having the client listen for something from the server.
hello.. i have a car and i control its movement from geroscope sensor on my hand.. and i have 2 pices of esp-01s .. i want to connect pice on my hand with pice on the car
how can your code help me ?
Hi, You just need to get the output from the sensor and send them in the URL as in this tutorial. Check out the comments for how to add more than one variable.
my code become like this :
transmitter
#include);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void loop() {
// read the analog in value:
sensorValue = analogRead(A0);
//);
}
and for reciver :
reciver
#include
#include
ESP8266WebServer server(80);
void handleSentVar() {
if (server.hasArg(“sensor_reading”)) { // this is the variable sent from the client
int readingInt = server.arg(“sensor_reading”).toInt();
server.send(200, “text/html”, “Data received”);
}
}
void setup() {
delay(1000);
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
server.on(“/data/”, HTTP_GET, handleSentVar); // when the server receives a request with /data/ in the string then run the handleSentVar function
server.begin();
}
void loop() {
server.handleClient();
}
is there any wrong ? | https://robotzero.one/sending-data-esp8266-to-esp8266/ | CC-MAIN-2022-33 | refinedweb | 6,489 | 66.23 |
Get the highlights in your inbox every week.
Add GUIs to your programs and scripts easily with PySimpleGUI
Add GUIs to your programs and scripts easily with PySimpleGUI
Create a custom GUI in under five minutes.
Subscribe now.
GUI frameworks
There is no shortage of GUI frameworks for Python. Tkinter, WxPython, Qt, and Kivy are a few of the major packages. In addition, there are a good number of dumbed-down GUI packages that "wrap" one of the major packages, including EasyGUI, PyGUI, and Pyforms.
The problem is that beginners (those with less than six weeks of experience) can't learn even the simplest of the major packages. That leaves the wrapper packages as a potential option, but it will still be difficult or impossible for most new users to build a custom GUI layout. Even if it's possible, the wrappers still require pages of code.
PySimpleGUI attempts to address these GUI challenges by providing a super-simple, easy-to-understand interface to GUIs that can be easily customized. Even many complex GUIs require less than 20 lines of code when PySimpleGUI is used.
The secret
What makes PySimpleGUI superior for newcomers is that the package contains the majority of the code that the user is normally expected to write. Button callbacks are handled by PySimpleGUI, not the user's code. Beginners struggle to grasp the concept of a function, and expecting them to understand a call-back function in the first few weeks is a stretch.
With most GUIs, arranging GUI widgets often requires several lines of code… at least one or two lines per widget. PySimpleGUI uses an "auto-packer" that automatically creates the layout. No pack or grid system is needed to lay out a GUI window.
Finally, PySimpleGUI leverages the Python language constructs in clever ways that shorten the amount of code and return the GUI data in a straightforward manner. When a widget is created in a form layout, it is configured in place, not several lines of code away.
What is a GUI?
Most GUIs do one thing: collect information from the user and return it. From a programmer's viewpoint, this could be summed up as a function call that looks like this:
button, values = GUI_Display(gui_layout)
What's expected from most GUIs is the button that was clicked (e.g., OK, cancel, save, yes, no, etc.) and the values input by the user. The essence of a GUI can be boiled down to a single line of code.
This is exactly how PySimpleGUI works (for simple GUIs). When the call is made to display the GUI, nothing executes until a button is clicked that closes the form.
There are more complex GUIs, such as those that don't close after a button is clicked. Examples include a remote control interface for a robot and a chat window. These complex forms can also be created with PySimpleGUI.
Making a quick GUI
When is PySimpleGUI useful? Immediately, whenever you need a GUI. It takes less than five minutes to create and try a GUI. The quickest way to make a GUI is to copy one from the PySimpleGUI Cookbook. Follow these steps:
- Find a GUI that looks similar to what you want to create
- Copy code from the Cookbook
- Paste it into your IDE and run it
Let's look at the first recipe from the book.
import PySimpleGUI as sg
# Very basic form. Return values as a list
form = sg.FlexForm('Simple data entry form') # begin with a blank form
layout = [
[sg.Text('Please enter your Name, Address, Phone')],
[sg.Text('Name', size=(15, 1)), sg.InputText('name')],
[sg.Text('Address', size=(15, 1)), sg.InputText('address')],
[sg.Text('Phone', size=(15, 1)), sg.InputText('phone')],
[sg.Submit(), sg.Cancel()]
]
button, values = form.LayoutAndRead(layout)
print(button, values[0], values[1], values[2])
It's a reasonably sized form.
If you just need to collect a few values and they're all basically strings, you could copy this recipe and modify it to suit your needs.
You can even create a custom GUI layout in just five lines of code.
import PySimpleGUI as sg
form = sg.FlexForm('My first GUI')
layout = [ [sg.Text('Enter your name'), sg.InputText()],
[sg.OK()] ]
button, (name,) = form.LayoutAndRead(layout)
Making a custom GUI in five minutes
If you have a straightforward layout, you should be able create a custom layout in PySimpleGUI in less than five minutes by modifying code from the Cookbook.
Widgets are called elements in PySimpleGUI. These elements are spelled exactly as you would type them into your Python code.
Core elements
Text
InputText
Multiline
InputCombo
Listbox
Radio
Checkbox
Spin
Output
SimpleButton
RealtimeButton
ReadFormButton
ProgressBar
Image
Slider
Column
Shortcut list
PySimpleGUI also has two types of element shortcuts. One type is simply other names for the exact same element (e.g.,
T instead of
Text). The second type configures an element with a particular setting, sparing you from specifying all parameters (e.g.,
Submit is a button with the text "Submit" on it)
T = Text
Txt = Text
In = InputText
Input = IntputText
Combo = InputCombo
DropDown = InputCombo
Drop = InputCombo
Button shortcuts
A number of common buttons have been implemented as shortcuts. These include:
FolderBrowse
FileBrowse
FileSaveAs
Save
Submit
OK
Ok
Cancel
Quit
Exit
Yes
No
There are also shortcuts for more generic button functions.
SimpleButton
ReadFormButton
RealtimeButton
These are all the GUI widgets you can choose from in PySimpleGUI. If one isn't on these lists, it doesn't go in your form layout.
GUI design patternThe stuff that tends not to change in GUIs are the calls that set up and show a window. The layout of the elements is what changes from one program to another.
Here is the code from the example above with the layout removed:
import PySimpleGUI as sg
form = sg.FlexForm('Simple data entry form')
# Define your form here (it's a list of lists)
button, values = form.LayoutAndRead(layout)
The flow for most GUIs is:
- Create the form object
- Define the GUI as a list of lists
- Show the GUI and get results
These are line-for-line what you see in PySimpleGUI's design pattern.
GUI layout
To create your custom GUI, first break your form down into rows, because forms are defined one row at a time. Then place one element after another, working from left to right.
The result is a "list of lists" that looks something like this:
layout = [ [Text('Row 1')],
[Text('Row 2'), Checkbox('Checkbox 1', OK()), Checkbox('Checkbox 2'), OK()] ]
This layout produces this window:
Displaying the GUI
Once you have your layout complete and you've copied the lines of code that set up and show the form, it's time to display the form and get values from the user.
This is the line of code that displays the form and provides the results:
button, values = form.LayoutAndRead(layout)
Forms return two values: the text of the button that is clicked and a list of values the user enters into the form.
If the example form is displayed and the user does nothing other than clicking the OK button, the results would be:
button == 'OK'
values == [False, False]
Checkbox elements return a value of True or False. Because the checkboxes defaulted to unchecked, both the values returned were False.
Displaying results
Once you have the values from the GUI, it's nice to check what values are in the variables. Rather than printing them out using a
PySimpleGUI has a number of message boxes to choose from. The data passed to the message box is displayed in a window. The function takes any number of arguments. You can simply indicate all the variables you want to see in the call.
The most commonly used message box in PySimpleGUI is MsgBox. To display the results from the previous example, write:
MsgBox('The GUI returned:', button, values)
Putting it all together
Now that you know the basics, let's put together a form that contains as many of PySimpleGUI's elements as possible. Also, to give it a nice appearance, we'll change the "look and feel" to a green and tan color scheme.
import PySimpleGUI as sg
sg.ChangeLookAndFeel('GreenTan')
form = sg.FlexForm('Everything bagel', default_element_size=(40, 1))
column1 = [[sg.Text('Column 1', background_color='#d3dfda',.Text('All graphic widgets in one form!', size=(30, 1), font=("Helvetica", 25))],
[sg.Text('Here is some text.... and a place to enter text')],
[sg.InputText('This is my text')],
[sg.Checkbox('My first checkbox!'), sg.Checkbox('My second checkbox!', default=True)],
[sg.Radio('My first Radio! ', "RADIO1", default=True), sg.Radio('My second Radio!', "RADIO1")],
, 3)),
sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)],
[sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)),
sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25),
sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75),
sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10),
sg.Column(column1, background_color='#d3dfda')],
[sg.Text('_' * 80)],
[sg.Text('Choose A Folder', size=(35, 1))],
[sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'),
sg.InputText('Default Folder'), sg.FolderBrowse()],
[sg.Submit(), sg.Cancel()]
]
button, values = form.LayoutAndRead(layout)
sg.MsgBox(button, values)
This may seem like a lot of code, but try coding this same GUI layout directly in tkinter and you'll quickly realize how tiny it is.
The last line of code opens a message box. This is how it looks:
Each parameter to the message box call is displayed on a new line. There are two lines of text in the message box; the second line is very long and wrapped a number of times
Take a moment and pair up the results values with the GUI to get an understanding of how results are created and returned.
Adding a GUI to Your Program or Script
If you have a script that uses the command line, you don't have to abandon it in order to add a GUI. An easy solution is that if there are zero parameters given on the command line, then the GUI is run. Otherwise, execute the command line as you do today.
This kind of logic is all that's needed:
if len(sys.argv) == 1:
# collect arguments from GUI
else:
# collect arguements from sys.argv
The easiest way to get a GUI up and running quickly is to copy and modify one of the recipes from the PySimpleGUI Cookbook.
Have some fun! Spice up the scripts you're tired of running by hand. Spend 5 or 10 minutes playing with the demo scripts. You may find one already exists that does exactly what you need. If not, you will find it's simple to create your own. If you really get lost, you've only invested 10 minutes.
Resources
Installation
PySimpleGUI works on all systems that run tkinter, including Raspberry Pi, and it requires Python 3
pip install PySimpleGUI
24 Comments, Register or Log in to post a comment.
Thank you for the writeup on this. I will forever be a beginner, as I have no interest in serious programming. Just like to doodle. Over the past couple of weeks, I've been thinking of trying to run some of the really easy "programming" / creative packages available under Windows.
Even HTAs have crossed my mind. Been thinking about doing this under WINE or virtualized. Linux simply doesn't cater to easy... Even bash can be over-engineered. PySimpleGUI looks perfect (for some solutions). This may help entice me to working with python more seriously.
This is an excellent introduction to a great solution to what has always been a vexing problem for me. I only had two minor issues with the code.
1. Since the library requires Python 3, the first line must be:
#! /usr/bin/python3
2. Again, for Python 3, you must use pip3 to install. Otherwise it ends up in the Python2 library collection.
Now, what is the most efficient way to combine this with psycopg2 to insert and update records in a database? Consider also that the tables have been somewhat normalized, so each record may be spread over two or three different tables, and the value list for some fields must be taken from tables of static data.
If the problem / application has a GUI or could benefit from a GUI, then PySimpleGUI isn't a bad place to start. If it's not a fit, you can quickly rule it out and move on.
If the project looks like it may be a candidate, spend 2 minutes looking through the Cookbook for a rough match. Copy, paste, and run the Recipe code. Then it's a matter of modifying the code to match your application.
The goal is to make it trivial to add a decent look GUI to software. It would be nice to introduce students to GUIs sooner than later in education by making it easy enough for beginners.
My advice to you would be to jump in and try stuff. Make something run. Make anything run. Then modify it or even start over. Point is that you've got a working environment, a blank canvas.
After taking a look, it won't work for me. While it's pretty easy to retrieve the id and display text from a static table, I need to only display the text in a list box, but return the id that matches the selection, since that is what will be stored in the new record. Maybe that would make a useful enhancement for a future release?
If "tables" are a fundamental thing you need to interact with, then PySimpleGUI is not yet able to provide a way of doing this in an interactive way.
Displaying a table is relatively easy and the results are pretty good:...
Here is the code if you want to try it
layout = [[sg.T('Table Test')]]
for i in range(20):
row = [sg.T(f'Row {i} ', size=(10,1))]
layout.append([sg.T(f'{i}{j}', size=(4,1), background_color='white', pad=(1,1)) for j in range(10)])
sg.FlexForm('Table').LayoutAndRead(layout)
There are 2 missing features that make this package not the best choice for database type operations:
1. Tables
2. Scrollable windows
There is no "table' widget I'm aware of in tkinter. I've looked at a few proposed solutions, but nothing has yet to rise to the top. The first step is to get the Column Element scrollable.
It should be noted that PySimpleGUI's primary mission is to implement "Simple GUIs".
I would urge you to write up an Issue and post it on the GitHub site if you have a feature idea or see a limitation.
I'm confused about the operation you are attempting on a Listbox. The best way to communicate on these things will be via GitHub.
The process is simple. I have a table of railroads that doesn't ever change. It includes a key (id), long and short names. So my two most important records in CSV form would be:
1, Pennsylvania Railroad, PRR
2, Coudersport and Port Allegany Railroad, CPA
I do a SQL select for the id and short name to get a list to chose from, then display that in a listbox. Once chosen by the user, I need to return the id to be stored in the new record.
I can't accept the GitHub terms of service, so that is not even a remote possibility.
Got it. Just finished creating scrollable Column Elements, which paves the way for tables and the application like you described.
What is the GitHub term of service that's blocking you? Perhaps it's been incorrectly stated.
Which terms? I hardly know where to start. But let me give you the top three.
1 Section Q. Indemnification: If some imbecile decides to sue me over a perceived slight, or because he wants to steal my work, I would have to sell everything I own to pay the retainer fee for any lawyer who could respond to that complaint. There is no way I could indemnify anyone in a case like that. If you don't think that is likely to happen, read up on the history of JMRI.
In addition, according to paragraph B3, they expect to hold teenagers to this requirement, and although I don't think the courts would allow that, it would still be very expensive for the kid's parents to find out.
2. Paragraph B4 says that when the web site is hacked, the users are still responsible for the breach, even though they have no control over the back end security. This is all too typical of the standard business contract where there is no actual negotiation involved. It becomes a one sided document with all of the risk dumped on the user. This presents me with a take it or leave it decision, and I choose to leave it.
3. Section R fails to define "material changes" in any meaningful way, there is only one weak example listed. That leaves far too much wriggle room for the lawyers, and it is entirely possible they could decide to sell all of the collected customer information, complete the changes to the web page in the middle of the night and have the money in the bank before the sun is up. Now that they are owned by Microsoft, I have to consider this a very real possibility.
Inching closer to database editing applications.
A new demo posted that shows how tables can be implemented. The last piece was being able to justify the text correctly in the input boxes....
It looks very much like a typical data entry table.
Does it work in KDE/Plasma environment? Just tried copying an example + PySimpleGUI.py in a directory, and run, but I see only a very small "cross", like mouse pointer, no more ...
I'll open an issue on the GitHub. Please visit and enter more information so it can be debugged (Python version, Linux Version, etc).
Visited .
Issue solved mainly following suggestion by Robert McConnell (thanks !) .
PySimpleGUI seems like a good match for a small GUI app I need to build, but it _must_ be based on Python 2.7. The code below is all I had to add at the top of PySimpleGUI.py, plus ( as expllained in the comment ) adding a function call inside *(), for every super() call ( NOT TESTED WITH Python 3 ! ) . However, one 'gotcha' that has me mystified is that I had to move every (args) in method calls to a position after the named ( 'keyword args' ) parameters. That is definitely not in accordance with Python convemtions, but it fixes errors ...
import platform
sVsn = platform.python_version()[0]
if sVsn == '2':
__metaclass__ = type # required for Python v.2.X
def fSuprArgs(self):
return () if sVsn != '2' else (self.__class__, self)
# place *(fSuprArgs(self)) as parameter in every call to super()
Are you saying you managed to get PySimpleGUI working with Python 2.7????!
I so, PLEASE post the file to the GitHub (or anywhere else of your choosing). This request comes up from time to time. I received one earlier this week.
Yes, it was a requirement for my project. Just tack the code above at the top of PySmpleGUI.py, insert the function call at every super() as: super(*(fSuprArgs(self))), move all *args to the last position in any parameter list where it appears, and you're done.
Careful, indentation gets mangled on this web page ...
I have already licensed the changes as CC-BY-SA, whatever that means, so feel free.
Please Note: Tested with Python 2.7.12 only, and NOT TESTED with Python 3!
Also, I have found there are many widgets that get confused, because they expect a color value tuple as the first param, so I always stuff (1, 1) and that prevents additional errors.
Replying to myself: Looks like I misunderstood parameter type cardinality. The link below shows that 'formal' keyword arguments _can_ come before *args, but *args must not come before **kwargs, when used together. So, the change that prevents errors is still legitimate Python, but of course I have no idea why it works.
I made all of these changes and moved the *args to the end of all the functions.
And, it WORKED! At least on one simple form I tried. There is more work ahead. I'm STUNNED at this outcome! I can't thank you enough!!
One last message...
Thanks to your encouragement and coding help, I just released PySimpleGUI27 to PyPI
I tested it a lot, but I'm unable to test the PyPI version. It should work great. This is a fantastic thing you've done!
Sorry I wasn't more clear about how the v.2.7 changes are meant to work. Though I haven't tested with v.3.x, the same PySimpleGUI code _should_ work under either rev. That's why the function returns an empty tuple when the version != 2.x, because the super() call doesn't need any params under v.3.x.
How can I add a background image that covers the entire window of the app. I don't see the functionality anywhere. Only changing the colour.
Theme doesn't work also.
sg.ChangeLookAndFeel('BluePurple')
nothing happens. Tried changing colour variable also.
If you are on a Mac, you will not see any change. You will see this message printed out:
*** Changing look and feel is not supported on Mac platform ***'
Make sure you make the call to ChangeLookAndFeel PRIOR to your layout definition. The layout needs to know the colors.
You can also call SetOptions with the individual color choices that you want. It is not blocked from being called by Macs. The reason for blocking the Look and Feel call is that button colors do not work on a Mac.
Feel free to log an issue on the github if it continues.
Is there any way to keep the multi entry box from blowing out to the OS
if the user hits enter?
Raspbian Raspberry Pi
Since you don't mention any crashes, sounds like your Read is returning normally and you're simply exiting the program. What may be happening is that you're using a Submit() or OK() button. By default those buttons have a parameter named bind_return_key set to true. If you're using a built-in button then try adding the parameter ... bind_return_key=False... to the call. Or you can switch to making your own buttons by using a call like Button("Submit"). Plain buttons like this don't have the enter key bound to them like the built-in ones do. If you have further problems, come log an issue on the github site () | https://opensource.com/article/18/8/pysimplegui | CC-MAIN-2021-21 | refinedweb | 3,822 | 74.69 |
-
Scala and Android in an Eclipse project
Created by milessabin on 2008-07-14. Updated: 2009-07-03, 10:10
2.1. Compile and package
This article is an introduction on how to build Scala Eclipse projects for Android. You may also want to read an IBM article on the same topic.
For a quick start, the two key issues are:
- The Scala builder has to be at the right position in the builder chain
- The project's bin folder has to be the first entry in the project's class path
1. Preparation
Follow these instructions to install the Eclipse Scala plugin, if you haven't already. Make sure you have the Android SDK, and the Android (ADT) plugin installed. After setting the Android SDK location in Eclipse under Window->Preferences->Android, you should be ready to develop Android applications with Java.
2. Scala's android-library
Note: For Android 1.0, Release 2 and possibly later, you can choose to skip this section. Read below for details.
Android does not support all of the standard Java class libraries. Hence, it is useful to create a stripped version of the Scala standard library that only uses those features that are available on Android.
On Android 1.0, Release 2, the class loader/verifier seem to load and verify classes only when needed. Consequently, you can use the standard Scala library without modifications as long as you don't use classes that refer to features not available on Android, such as scala.reflect.ScalaBeanInfo that refers to package java.beans. Nevertheless, it might be useful to create a stripped library jar to be on the safe side.
For the latest version of Scala, you have to build your own scala-android library. For Scala 2.7.0 you can download the android-library with sbaz and skip the next section.
2.1. Compile and package
Download the scala sources from SVN.
There is currently no ant target in the build.xml file to build the android-library. Here is a quick and dirty solution: copy the content of the directory src/android-library to src/library and overwrite existing files. Now type ant in your Scala SVN checkout folder. This creates a scala-library.jar in folder build/pack/lib. Rename it to android-library.jar and save it for later use.
3. Create the project
Create an Android project under Project Wizard -> New -> Android -> Android Project. For this introduction, name your package hello and your activity class ScalaOnAndroid.
Then add the Scala nature to this project with Scala -> Add Scala Nature from the project's context menu.
Go to the project properties dialog. Under Builders move the Scala Builder between the Android Pre Compiler and the Android Package Builder. For reference, your .project file should now look like this:
<?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>scala-on-android</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name> <arguments> </arguments> </buildCommand> <buildCommand> <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name> <arguments> </arguments> </buildCommand> <buildCommand> <name>ch.epfl.lamp.sdt.core.scalabuilder</name> <arguments> </arguments> </buildCommand> <buildCommand> <name>com.android.ide.eclipse.adt.ApkBuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>ch.epfl.lamp.sdt.core.scalanature</nature> <nature>com.android.ide.eclipse.adt.AndroidNature</nature> <nature>org.eclipse.jdt.core.javanature</nature> </natures> </projectDescription>
Now include the android-library.jar to the project dependencies. Open the project properties and go to the java build path -> libraries tab. Remove the "Scala Library" and add the android-library.jar as an external JAR.
Last but not least, remove the automatically generated Java Activity, and replace it with one of the following Scala classes. (Your new Activity should have the same name and package as the removed Java class.) You can either reuse the generated Android resource class R:
package hello
import android.app.Activity
import android.os.Bundle
class ScalaOnAndroid extends Activity {
override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
}
}
or create a message programmatically:
package hello import android.app.Activity import android.os.Bundle import android.widget.TextView class ScalaOnAndroid extends Activity { override def onCreate(savedInstanceState: Bundle) { super.onCreate(savedInstanceState) val tv = new TextView(this) tv.setText("Hello Android, it's me, Scala!") setContentView(tv) } }
Sometimes, you get weird error messages such as
hello.ScalaOnAndroid must be public, or the system will not be able to instantiate it
Do a clean build (Project -> Clean) and/or close and reopen the project in such cases.
Finally, you can launch your application with right click on your project -> Run As... -> Android Application.
There is one more step. Some Scala features such as inner functions seem to be problematic for the ADT. Follow the next section on how to convince the ADT to cooperate.
4. Add bin folder to the class path
Go to the project properties. Under Java Build Path -> Libraries add the project's bin folder as an external class folder. Go to the Order and Export tab and move the newly added folder to the top of the list. For reference, your .classpath should now look like this:
<?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="lib" path="<path-to-your-workspace>/scala-on-android/bin" /> <classpathentry kind="src" path="src" /> <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK" /> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER" /> <classpathentry kind="lib" path="<path-to-your-Scala-install>/lib/android-library.jar" /> <classpathentry kind="output" path="bin" /> </classpath>
This step is necessary due to some integration problem with the Java (JDT) Eclipse plugin. The Android plugin uses the JDT to check whether the main activity really extends android.app.Activity. For Scala classes from source files with inner functions, the JDT doesn't seem to find all super classes (for whatever reason). After adding the bin folder to the top of the Order and Export list the problem goes away, presumably because the type hierarchy is then build from class files which seem to pose no problem. | http://www.scala-lang.org/node/160 | crawl-002 | refinedweb | 1,012 | 51.75 |
Help index · Help desk · Reference desk · FAQ · Editor's welcome · Tutorial · Cheatsheet · Glossary · Any questions?
Where would I find information about what caused the site to be down between 18:23 and 19:30 (Eastern Daylight Savings Time) today? // BL \\ (talk) 23:59, 30 June 2009 (UTC)
How can I move an image map? Here's an example...
{{#tag:imagemap|
File:Example.JPG{{!}}70px
default []
desc none
}}
Where can I specify a location? ---Scarce |||| You shouldn't have buried me, I'm not dead--- 00:13, 1 July 2009 (UTC)
How do I upload and then add an image into a Wikipedia article? Zhouf12 (talk) 01:12, 1 July 2009 (UTC))
Thanks to all for the feedback and advice. I'm going to enter my compulsory procrastination period now and decide what to do.)
Is there a template I can use to divide my userboxes up into columns? Not {{userboxtop}}/{{userboxbottom}}. Thank You! ---Scarce |||| You shouldn't have buried me, I'm not dead--- 09:19, 1 July 2009 (UTC) have created an entry and now i want to add the information to conform with refernce and notability regulations. how can i add this before my entry gets removed?!Wackydoo (talk) 11:43,)
Coins from the United States Mint —Preceding unsigned comment added by 206.248.251.135 (talk) 14:45, 1 July 2009 (UTC))
I am closing the website and want my website to be shown as the official one, soon the other site will be closed and the link will be a dead one. I edited the page earlier today but it was reveresed. I have changed the links back again. Please do not permit the wensite to be shown as my official one as it isn't, we have parted company today. If the link keeps getting reversed I will have to take the appropriate action to protect what is mine. To reiterate the website is nolonger authorised to be my official site. If you tell me how to prove I am Teresa May by way of a photo or cuch I will gladly submit what you require
Thank you for your assistance in this matter.
Gogetemtreez (talk) 15:03, 1 July 2009 (UTC)
)
Is it possible to trace which articles link back to a specific article in the same way that the Google "links:" function will tell you who links to a specific website? -- redherring (talk) 16:15, 1 July 2009 (UTC))
{{NUMBEROFUSERS}}returned 9,999,555 when I previewed this and 10,026,787 when this is read. Who will be number 10,000,000? PrimeHunter (talk) 23:30, 1 July 2009 (UTC))
Please delete this file (created by me) ASAP File:AFC Wimbledon4.svg. Thanks Arteyu ? Blame it on me ! 19:02, 1 July 2009 (UTC))
My logout button is not clickable. It's not my computer at fault. Why is this? JohnClarknew (talk) 00:22, 2 July 2009 (UTC)
My browser often crashes when I try to open articles that begin with en.wikipedia.org. How do I open them? I am using Internet Explorer 8. Rshafer174 (talk) 01:27, 2 July 2009 (UTC)
Issue is user side. Reset IE8. Tools/Internet options/Advanced/Reset. Then try again Ivtv (talk) 03:53, 2 July 2009 (UTC))
Hi, why has the search thing changed? 78.144.182.99 (talk) 05:21, 2 July 2009 (UTC)
Is there a way I can make an external link appear internal? With out the
symbol appearing? Thanks! ---Scarce |||| You shouldn't have buried me, I'm not dead--- 05:34, 2 July 2009 (UTC))
in 1mg of magnesium sulphate what is the quantity of magnesium and sulphate —Preceding unsigned comment added by 114.143.50.180 (talk) 08:14, 2 July 2009 (UTC)
"..)
we need the information about marchant neavy —Preceding unsigned comment added by 117.200.161.163 (talk) 14:59, 2 July 2009 (UTC))
Thanks a lot! —Preceding unsigned comment added by Plane Person (talk • contribs) 19:05, 2 July 2009 (UTC))
If you replicate a logo, and an image of the actual logo was not used in the replication, can it be uploaded to the Wikipedia as free? Such as public domain ---Scarce |||| Talk -Contrib.--- 03:49, 3 July 2009 (UTC))
Why is my talk page and other user pages appearing on other websites:
Please reply asap. --Tyw7 (Talk • Contributions) 10:28, 3 July 2009 (UTC))
image=twice, with the second one blank. ---— Gadget850 (Ed) talk 11:18, 3 July 2009 (UTC)
What is the benefit of the nigerian press council decree to the nigerian journalist —Preceding unsigned comment added by 78.138.19.243 (talk) 12:51, 3 July 2009 (UTC)
Please do your own homework. Welcome to the Wikipedia Help., 5 July 2009 (UTC))
Hello
Can you please provide me with the SMTP outgoing address for your e-mail server.
Thank you. Regards.
JJ van den Berg E-mail address :- <blanked>
-)
Whenever I click the PVS link in the revision history, my browser says that doesn't exist, is this just me? ---Scarce |||| Talk -Contrib.--- 17:55, 3 July 2009 (UTC))
The age-old concept of turning an image into a wikilink still eludes me. How is it done, and how do I do it? Enlighten me! a little insignificant 20:20, 3 July 2009 (UTC))
I wouldn't want to be within 100 miles ofr a Major Metropolitan area when the welfare checks bounce. "Who was that man? 22:23, 3 July 2009 (UTC)198.69.252.74 (talk)
italian cruis ship msaugustas —Preceding unsigned comment added by 69.116.183.111 (talk) 01:55, 4 July 2009 (UTC):
AJAX suggestions may be temporarily disabled if the servers exhibit performance issues.
---— Gadget850 (Ed) talk 06:08, 4 July 2009 (UTC))
how to save a file from wikipaedia to the computer? --122.174.66.205 (talk) 11:08, 4 July 2009 (UTC)
If you intend you use Wikipedia content for other purposes, you might like to read WP:REUSE which explains the licensing issues involved. --Kateshortforbob 12:18, 4 July 2009 (UTC)
how do I highlight a name or reference in blue? I like the use of it, but can't figure out how to do it.slolsen —Preceding unsigned comment added by Slolsen (talk • contribs))
If I want to add a name to a list already on here, what must happen for the name to be added? —Preceding unsigned comment added by Monsterrunner (talk • contribs) 18:15, 4 July 2009 (UTC))
Please check this following page and kindly get it off line ~ —Preceding unsigned comment added by 173.49.50.142 (talk) 21:42, 4 July 2009 (UTC)
My irony alarm just blew a circuit breaker. The article in question refers to an internet phenomenon that sponaneously arose as a satirical protest against Chinese government internet censorship. The satire takes the form of using chinese homonyms for vulgarity as the names of newly-invented "mythical anamials." The artiles has to stand as the best example ever of why Wikipedia is not censored. -Arch dude (talk) 14:31, 5 July 2009 (UTC)
Is there any way to delete your own Wikipedia account? Spongebob Forever3116 (talk) 23:03, 4 July 2009 (UTC)Spongebob Forever3116)
how do i write in here —Preceding unsigned comment added by 74.65.3.30 (talk) 06:33, 5 July 2009 (UTC),. PhantomSteve (Contact Me, My Contribs) 09:01, 5 July 2009 (UTC))
How do I categorize an image after it has been uploaded? I've checked here and it says how to categorize an image during uploading, but not after it has been uploaded. Wikiert T S C 15:22, 5 July 2009 (UTC)
I have a 1988 chev blazer with electric windows. the windows are not working and I need a diagram of the 1988 chev blazer electric window to assist me in tracking down the problem. All the sites I go to want to charge for the diagram can you please help me.
otis
<email removed> —Preceding unsigned comment added by 64.22.212.214 (talk) 15:46, 5 July 2009 (UTC)
Please remove the following line from the following page:
PAGE:
LINE: (References): 12. Brandon Traister. "The World War II Lecture Institute". Archived from the original on 2009-04-29.. Retrieved on 2009-03-28.
This link is longer available/active.
Thank you. —Preceding unsigned comment added by Traister (talk • contribs) 16:45, 5 July 2009 (UTC)
Hello, I'm quite familiar with Wikipedia but I am looking for more tasks to get engaged in on here. I very much enjoy contributing to this project & am a bit of a WikiHolic! When I started I was just helping clean out WP:BL and patrolling WP:RCP & WP:NPP, other than that nothing much. As of recent I am trying to expand my contributions among the other namespaces such as Category, File, Wikipedia, Template & Portal. I would like to recieve my own mop one day so I can get more involved in the project (Things like WP:Xfd, WP:RFPP & other tasks at WP:AN). I'm intrested to know, For somebody who wishes to serve wikipedia as an admin in the future what areas should I be focusing my attention to now? Also could you suggest some ways I could help in the other namespaces I specified above, Thanks. Harlem675 18:50, 5 July 2009 (UTC)
Thankyou very much for the quick & helpful responses, I will take the advice on board. Not to be annoying here but would anyone have some work for me to do in Template, Category & Portal namespaces too I currently neglect these areas but want to help in them. Harlem675 19:37, 5 July 2009 (UTC)
hello, i am working on a page that needs citations. the subject of the page is a writer and photographer. one of the quotes on the page about his work is from a blurb on the back cover of one of his published books. how do i cite this? it can, of course, be seen on amazon and on google books, but i don't imagine these are legitimate references. can you simply cite the book and instead of a page number put 'back cover'? many thanks.Spudsparo1 (talk) 20:22, 5 July 2009 (UTC)
Thanks for your responses. Yes, I am working on the page about James Baker Hall. Here is the quote (by the poet Gerald Stern): “He makes our terror come alive – and our knowledge and our joy – in his beautiful singing.” I don't know if the blurb was solicited solely for the book. I will search to see if perhaps the comment appears in a review or an article that could be cited. Also, Gerald Stern is one of the most respected and prominent poets in the country (for a confirmation of this, see his Wikipedia entry). My sense is that the quote is not just that Hall is great, but rather points to qualities and meaning of Hall's work. I'm not sure if Stern's stature as an authority, and the particular content of the quote, bears on the validity of using the book quote as a source. I would appreciate advice on this from other editors. Thank youSpudsparo1 (talk) 22:30, 5 July 2009 (UTC)
I added a table on inflation to the Economy of Venezuela article (Consumer prices section). Everything is fine, except the vertical size and spacing of some of the table cells is odd. I've made some attempts to fix this formatting problem, but so far without success. Perhaps someone else would like to have a try. I also left a note on the article's talk page about this. Ong saluri (talk) 20:36, 5 July 2009 (UTC)
can you store lard at room temp? —Preceding unsigned comment added by 74.65.3.30 (talk) 21:53, 5 July 2009 (UTC)
I'm not sure... Anyway, Your in the wrong place. This Help Desk is for resolving issues on Wikipedia. Harlem675 22:19, 5 July 2009 (UTC)
i postred a question last night its not here help —Preceding unsigned comment added by 74.65.3.30 (talk) 21:55, 5 July 2009 (UTC)
My sister and I found out digging in the family tree, Found she is related as Great Great grand (well you get the idea)Mother
of ours, I just wanted to say THANK YOU for your article. —Preceding unsigned comment added by Pstolzenburg (talk • contribs) 22:11, 5 July 2009 (UTC)
What does it mean when you don't get a bond when you go to arrangment. —Preceding unsigned comment added by 72.150.76.17 (talk) 22:25, 5 July 2009 (UTC)
Are gas station Petro Mart owned by Chavez? —Preceding unsigned comment added by 24.216.217.235 (talk) 23:17, 5 July 2009 (UTC)
What if you have all of the famous people on here already and you guys won't let me post any regular people which i think is totally un fair but please answer my question????? —Preceding unsigned comment added by Haver73 (talk • contribs) 23:46, 5 July 2009 (UTC)
Will somebody please help me. Please, convert/merge this image File:NationalMedalofArts.jpg to commons. Thank you. Fanoftheworld (talk) 23:54, 5 July 2009 (UTC)
I uploaded File:Lolipop.pdf, but the image does not display, and when I attempt to use it in the regular fashion all it produces is a link. It's entirely my own work, and released into the public domain. What am I doing wrong? a little insignificant 23:57, 5 July 2009 (UTC)
I created a new article Hazel Walker at 1:29. Why don't I see it in the list of new pages? I did start it in a sandbox, but shouldn't the creation time and date match when I moved it into the main space?--SPhilbrickT 01:49, 6 July 2009 (UTC)
How do I change a photograph that is included in an article - purely for vanity?
Ted Quinlan —Preceding unsigned comment added by Ted Quinlan (talk • contribs) 01:56, 6 July 2009 (UTC)
I don't know which spelling is correct but in the article on Harold Holt his wife's birth name is spelt Zara Kate Dickens (in the "Early Life" section ) however when you click on the link in her biography (Zara Bate) it says she was born Zara Kate Dickins
Suggest making them consistent with the correct spelling.
Russell Gesling —Preceding unsigned comment added by 57.73.18.106 (talk) 02:08, 6 July 2009 (UTC)
For a template message of italic text and an article message box, which comes first in order in an article?--Mikespedia (talk) 02:41, 6 July 2009 (UTC)
I'm not sure whether this would qualify for a speedy, though I suspect it would (see the history of the page and look at the name of the user who created it). However, if it's to be kept, the article should be moved to a more appropriate title. Vltava 68 03:44, 6 July 2009 (UTC)
Much like <center></center> is there on I can use for aligning things to the right? ---Scarce |||| Talk -Contrib.--- 04:18, 6 July 2009 (UTC)
<div class="floatright">[[File:Example.png|70px]]</div>
<div class="center">[[File:Example.png|70px]]</div>
There was a tool that would show you how many edits the most prolific contributors had made to a specified article, but my old PC went to Microsoft Hell and took my link to it with it. There was also another program that would display how many people had visited an article within a certain time period. Help a victim of WP:EDITCOUNTITIS. Clarityfiend (talk) 05:47, 6 July 2009 (UTC)
What is the best place to ask translation questions like Wikipedia_talk:WikiProject_Buddhism#Twelve_Heavenly_Generals:_Chinese.2C_Sanskrit.2C..._names ? bamse (talk) 07:30, 6 July 2009 (UTC)
Only one paragraph from one section of this article violates copyrights. However, when I tried to add the {{subst:copyvio}} message on the beginning of the section confirmed, it covered up everything afterwards, including the ones that was original. What can I do? All the best, Kayau (Talk to me! See what I've done! Sign my guestbook!) 07:57, 6 July 2009 (UTC)
Hi I edited an article and pressed the save page button and did everything else that was asked for, but still do not see any changes even after 1 day! What did I do wrong? Please help!!
Nimmy03081980 (talk) 10:36, 6 July 2009 (UTC) Nimmy
I was editing the article on Evernote when I came across a template that started with
{{*
What is this template, and what does it do? It seems to transclude other content, however, I can't find the source of this content. Instead of just deleting it, I wanted to find out more...
Thanks in advance! — QuantumEleven 10:55, 6 July 2009 (UTC)
How should i report if i find a content on wikipedia offensive or NSFW ? Shraktu (talk) 11:22, 6 July 2009 (UTC)
stock | retire | vm
Why are we here?
All text is available under the terms of the GNU Free Documentation License
This page is cache of Wikipedia. History | http://wiki.xiaoyaozi.com/en/Wikipedia:Help_desk.htm | crawl-002 | refinedweb | 2,871 | 71.44 |
.
lxc
Cheap and Easy Virtual Machine Containers with LXC
The thing that most virtual-machine solutions have in common is the overhead required to run them. There’s a substantial resource cost for the management of these containers, aside from that for the machine itself.
There’s an alternative to all of that, called LXC. In fact, though it used to require an impossible number of steps to configure, it’s now sufficient to just pass in a couple of command-line parameters and leave everything else to defaults.
LXC is somewhere between chroot and QEMU. It imposes resource control using the cgroups functionality that comes packaged in the kernel, which is, essentially, the next evolution of ulimit. Although the resource-control is somewhat disabled by default, you can set limits even so far as disk I/O rates.
It’s important to know that, though LXC works terrifically, it should only be used in either personal systems or any other system that’s sufficiently fenced-off from outside threats. This is because it doesn’t benefit from 100% isolation like most VM’s do (a tradeoff for its lightweightedness). An example of this is that the container shares the same sysfs as the host, due to limitations in sysfs. Therefore, changing sysfs from the container will affect the host.
Though there are security concerns, I have been told authoritatively that there is a less likely chance of a rogue application causing issues for the larger host than any other critical problem that systems usually encounter in production. So, a couple of built-in security concessions are the only plausible risks.
System Containers
There’s an easy way and a hard way to create system containers. The hard way is to create and populate it with all of the configuration that is required of any new system (see here). The easy way is to simply use the “lxc-create” tool and tell it to follow a template.
These are the templates available in my installation:
$ ls -1 /usr/share/lxc/templates alpine altlinux archlinux busybox debian fedora opensuse oracle sshd ubuntu ubuntu-cloud
You can only use a template that’s compatible with the system on which you are working. Otherwise, you’ll find that “yum”, for instance, is missing if you try to build a Fedora instance on Ubuntu, as well as categorically-similar issues with the other templates. On my Ubuntu, I can create containers with the “busybox” (which creates instantaneously), “debian” and “ubuntu” (7 minutes), “ubuntu-cloud” (6 minutes), and “sshd” (see below) templates. Note that any required, downloaded images are cached, and subsequent builds only take a minute or two.
The current steps to build an Ubuntu container (from my Ubuntu box, after installing the lxc package):
$ sudo lxc-create -t ubuntu -n <container name>
Depending on the template, you might see something like this upon completion:
# The default user is 'ubuntu' with password 'ubuntu'! # Use the 'sudo' command to run tasks as root in the container.
I named my container “ubuntu-2”. The container directories get created in /var/lib/lxc, and have a reasonable size:
$ ls -l /var/lib/lxc total 4 drwxr-xr-x 3 root root 4096 Nov 6 02:32 ubuntu-2 $ sudo du -sh /var/lib/lxc/ubuntu-2/ 263M /var/lib/lxc/ubuntu-2/
To start the container as a daemon:
$ sudo lxc-start -n ubuntu-2 -d
Or, to start the container as a foreground machine, complete with console (using another, BusyBox-based, container, which shows this better):
$ sudo lxc-start -n busybox-1 udhcpc (v1.20.2) started Sending discover... Sending select for 10.0.3.79... Lease of 10.0.3.79 obtained, lease time 3600 Please press Enter to activate this console.
To list the currently-running containers:
$ sudo lxc-ls --fancy NAME STATE IPV4 IPV6 AUTOSTART ----------------------------------------------- busybox-1 STOPPED - - NO debian-1 RUNNING 10.0.3.247 - NO ubuntu-1 RUNNING 10.0.3.217 - NO ubuntu-2 RUNNING 10.0.3.249 - NO
Very cool. To connect via SSH:
$ ssh ubuntu@10.0.3.249 The authenticity of host '10.0.3.249 (10.0.3.249)' can't be established. ECDSA key fingerprint is 73:8c:31:53:76:36:93:6e:59:ee:3f:d3:6f:27:13:c7. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.0.3.249' (ECDSA) to the list of known hosts. ubuntu@10.0.3.249 13.04 (GNU/Linux 3.8.0-30-generic i686) * Documentation: ubuntu@ubuntu-2:~$
To stop the container:
$ sudo lxc-stop -n ubuntu-2
If you don’t want, or need, to build a new system, you can also configure an “ssh container”, where a read-only mount of the current filesystem is combined with an SSH server to create the facade of a separate machine instance. It’s unclear whether there’s a provision to allow changes (such as implementing a ramdisk to produce the illusion of a read-write experience similar to a disc-based “live” Linux distribution).
Application Containers
In addition to hosting “system” containers, LXC can also host “application” containers. Quite obviously, the latter simply host applications with all of the benefits of the resource-control that we’ve already mentioned, as well as, most likely, its security limitations.
$ sudo lxc-execute -n <container name> <command>
You might see an error like the following:
$ sudo lxc-execute -n app_container_1 touch /tmp/aa lxc-execute: Permission denied - failed to change apparmor profile to lxc-container-default lxc-execute: invalid sequence number 1. expected 4 lxc-execute: failed to spawn 'app_container_1'
The workaround is:
$ cat > test.conf <<EOF lxc.aa_profile = unconfined lxc.rootfs = / EOF $ sudo lxc-execute -f test.conf -n app-container-1 touch /tmp/aa
When the application container launches, you’ll be able to see it in the lxc-ls list (above). You’ll also be able to find it in the ps list. Obviously the command-above just touches a file before returning, so it won’t be alive long-enough for you to be able to see it running.
Development Support
Naturally, everything we’ve mentioned can be done from code (Python, Lua, and Go, currently). This is a Python example mentioned on the LXC homepage (whose link was at the beginning of the article):
import lxc container = lxc.Container("p1") container.create("ubuntu") container.start() container.get_ips() container.stop()
As mentioned, LXC isn’t the right-kind of container for serving from the DMZ in a corporate environment, but it is awesome as a fast, easily-constructed, hold-no-prisoners system container, where you want to run a dozen on a commodity box with minimal resource consumption. | https://dustinoprea.com/tag/lxc/ | CC-MAIN-2018-09 | refinedweb | 1,123 | 53.61 |
Recent developments has made it possible to run LinuxCNC on the latest LTS release of Ubuntu. This is experimental work, so not recommended for controlling a real machine just yet. The main obstacle for moving LinuxCNC from 10.04LTS to a more recent distribution has been the RTAI real-time kernel, which has not been kept up-to-date with development of the normal Linux kernel. Fortunately there are alternatives such as Xenomai or RT_PREEMPT.
Here is a step-by-step description of the install/build process, if you want to experiment with this.
- Download and install a normal 32-bit 12.04LTS Ubuntu (ubuntu-12.04.1-desktop-i386.iso). Note that the 64-bit version is not supported for the steps that follow further down. I could not get Ubuntu's startup-disk-creator to work, so I used unetbootin to write the ISO-file to a USB-stick.
- It's possible to compile the xenomai-kernel from scratch, along with the runtime etc., but I used pre-compiled deb-packages by Michael Haberler from here:
- Install the xenomai kernel:
sudo dpkg -i linux-headers-3.2.21-xenomai+_0.1_i386.deb
sudo dpkg -i linux-image-3.2.21-xenomai+_0.1_i386.deb
- make sure it will show up as a GRUB-entry when booting:
sudo update-initramfs -c -k 3.2.21-xenomai+
sudo update-grub
- reboot. uname -r should now show: 3.2.21-xenomai+
- now install the xenomai runtime:
sudo dpkg -i libxenomai1_2.6.1_i386.deb
sudo dpkg -i libxenomai-dev_2.6.1_i386.deb
sudo dpkg -i xenomai-runtime_2.6.1_i386.deb
This installs the xenomai system on top of which a recently available version of LinuxCNC can be built. There are probably many ways to now obtain the tools/dependencies that are required. I used the following:
- sudo apt-get install synaptic
sudo apt-get install git
- Now using synaptic, install the following packages (I found these are required for a minimal linuxcnc build):
build-essential
autoconf
libpth-dev
libglib2.0-dev
libgtk2.0-dev
tcl-dev
tk-dev
bwidget
libreadline-dev
python-tk
python-dev
libgl1-mesa-dev
libglu1-mesa-dev
libxmu-dev
- Get Michael's version of LinuxCNC that can be compiled for Xenomai:
git clone git://git.mah.priv.at/emc2-dev emc2-dev
cd emc2-dev
git branch --track rtos origin/rtos-integration-preview1
git checkout rtos
- Configure and build for Xenomai:
cd src
./configure --with-threads=xenomai-user --enable-run-in-place
make
sudo make setuid
- Test:
. ./scripts/rip-environment
latency-test
This new version of LinuxCNC can be built without a real-time kernel (previously called "simulator" or "sim") or with any of the real-time kernel alternatives: RTAI, Xenomai, RT_PREEMPT. It should be possible to compare real-time performance in the form of latency-numbers with different hardware and kernels.
20 thoughts on “LinuxCNC on Ubuntu 12.04LTS”
building the documentation requires: asciidoc
and these may also be required for the doc-build:
dvipng texlive-extra-utils texlive-latex-recommended texlive-fonts-recommended ghostscript imagemagick texlive-lang-french texlive-lang-german texlive-lang-spanish texlive-lang-polish texlive-font-utils asciidoc (>= 8.5) source-highlight dblatex (>= 0.2.12) xsltproc groff libgnomeprintui2.2-dev texlive-lang-cyrillic
further (optional) dependencies:
xemc-GUI: libxaw7-dev,
printing from classicladder: libgnomeprinting-2.2-dev
keystick-GUI: libncurses-dev
with next 3.2.21-xenomai+_0.2 the system does not start. rebooting always. is that what should be?
No, the xenomai-kernel should boot quite normally and you should see a normal Ubuntu startup sequence, desktop etc.
If you can get your machine to boot from HDD you can edit the GRUB configuration so it boots to a stable kernel.
If nothing else helps you can boot from a LiveCD or USB stick and try to edit the GRUB settings or even do a complete reinstall.
Is this a very new or very old motherboard/cpu? I guess that xenomai kernel is built on top of a standard 3.2.21-kernel, so it might be worth testing if a standard 3.2.21-kernel (or any 3.2 series) installs and boots OK.
Michael H might know more about what drivers or options are disabled in the xenomai kernel wrt. a standard kernel - maybe something is missing in xenomai and that is causing your problems.
nope, it's a 2012 535u3c samsung notebook. i can boot to initial 12.10 kernel.
maybe 12.10 does not suite
yes it's best to try these things on 12.04LTS (32bit!) , since the xenomai kernel was built for that.
i'm having endless ramdom freezings in 12.04.1 🙁 cannot test. it's a well-known problem not fixed.
hm, nor sure why you are having problems. Did you do an md5sum check on your iso-download? Can you do a memcheck test on your machine to see that the hardware is ok?
i did everything that. installed from alternate cd, deinstalled unity and gnome* - nothing helps, it just hangs without logic in not predicted moments. 12.10 is perfect when installed. i'll try to find some ways or wait 12.04.2 ))
Hi Anders, thanks for the instructions!
Probably the other commenters with boot problems are having trouble with the kernel config, which we have found has turned off some drivers needed for some systems require to boot.
There's a new wiki page on LinuxCNC.org that explains how to build a kernel yourself, or else install pre-built packages. The config file is based on the Ubuntu Precise kernel config. These packages should support just about any hardware that the normal Ubuntu Precise kernel supports.
See the page here:
John/Zultron
Thanks for the instructions. I managed to install linuxcnc but when i try to test my axis using stepconf i get the following error
Stepconf encountered an error. The following information may be useful in troubleshooting:
Traceback (most recent call last):
File "./stepconf", line 1738, in on_xaxistest_clicked
def on_xaxistest_clicked(self, *args): self.test_axis('x')
File "./stepconf", line 2107, in test_axis
if not self.check_for_rt(): return
File "./stepconf", line 1282, in check_for_rt
elif hal.is_rt and not hal.kernel_version == actual_kernel:
AttributeError: 'module' object has no attribute 'kernel_version'
halmodule.cc contains the following line
#ifdef RTAPI_KERNEL_VERSION
PyModule_AddStringConstant(m, "kernel_version", RTAPI_KERNEL_VERSION);
My kernel is
root@Mpoha> uname -a
Linux Mpoha 3.2.21-xenomai+ #1 SMP PREEMPT Tue Oct 30 19:01:33 UTC 2012 i686 i686 i386 GNU/Linux
Hi Andreas,
You don't strictly need stepconf to run linuxcnc. It's a good idea to learn what goes into the INI and HAL files anyway and not blindly trust stepconf.
I'm not sure why exactly you see that problem. Stepconf may be written in a way that assumes an RTAI system.
There are about three good ways to report problems like these:
- the mailing-list:
- the forum:
- on IRC: #LinuxCNC and #LinuxCNC-devel on irc.freenode.net
Anders
Thanks Anders 🙂
hi dudes,
thank's for this page, it has been the only valid way to install linuxcnc on xubuntu 12.04
BUT... i've the followin' problem:
i click on the con, program start and i can select the configuration options
linuxcnc logo with penguin, version etc. appear and... a linuxcnc error window open and program exit.
the error message is:
Print file information:
RUN_IN_PLACE=no
LINUXCNC_DIR=
LINUXCNC_BIN_DIR=/usr/bin
LINUXCNC_TCL_DIR=/usr/lib/tcltk/linuxcnc
LINUXCNC_SCRIPT_DIR=
LINUXCNC_RTLIB_DIR=/usr/lib/linuxcnc/modules
LINUXCNC_CONFIG_DIR=
LINUXCNC_LANG_DIR=/usr/share/linuxcnc/tcl/msgs
INIVAR=inivar
HALCMD=halcmd
LINUXCNC_EMCSH=/usr/bin/wish8.5
LINUXCNC - 2.5.2-193-g6de7f0d
Machine configuration directory is '/home/incisoria/linuxcnc/configs/cooltool-1'
Machine configuration file is 'Basic540_4axes.ini'
INIFILE=/home/incisoria/linuxcnc/configs/cooltool-1/Basic540_4axes.ini
PARAMETER_FILE=stepper.var
TASK=milltask
HALUI=
DISPLAY=axis
Starting LinuxCNC...
Starting LinuxCNC server program: linuxcncsvr
Starting LinuxCNC IO program: io
Shutting down and cleaning up LinuxCNC...
Killing task linuxcncsvr, PID=7315
Removing HAL_LIB, RTAPI, and Real Time OS modules
Removing NML shared memory segments
Cleanup done
Debug file information:
Can not find -sec MOT -var MOT -num 1
Can not find -sec IO -var IO -num 1
Can not find -sec LINUXCNC -var NML_FILE -num 1
Can not find -sec EMC -var NML_FILE -num 1
hal_parport: dlopen: /usr/lib/linuxcnc/modules/hal_parport.so: cannot open shared object file: No such file or directory
S4_pinout.hal:6: /usr/bin/rtapi_app exited without becoming ready
S4_pinout.hal:6: insmod failed, returned -1
7315
PID TTY STAT TIME COMMAND
Stopping realtime threads
Unloading hal components
could somebody pleeeeeease help me?
thanks
Lucio,
You should try running linuxcnc in sim-mode. Does that work? That would indicate a problem with the parport driver.
In general it's best to post all your configuration files and your error output on either the linuxcnc form or the linuxcnc mailinglist. My experience is that there is usually someone there who knows how to solve your problem and can help you.
AW
Hi there, linux n00b here, I had great luck with your instructions up to #4. It reads:
Configure and build for Xenomai:
cd src
./configure --with-threads=xenomai-user --enable-run-in-place
make
sudo make setuid
BUT I think it should read:
Configure and build for Xenomai:
cd src
sh autogen.sh
./configure --with-threads=xenomai-user --enable-run-in-place
make
sudo make setuid
I installed 12.04.2, but according to latency-test outputs, it doesnt meet real-time requirements.
valgrind: you will need to provide more information. what kernel are you running? what hardware? what are the latency numbers? The LinuxCNC wiki has a list of common issues that affect RT performance:
the most common problems are BIOS settings that affect on-board video/audio/USB/power-saving | http://www.anderswallin.net/2012/12/linuxcnc-on-ubuntu-12-04lts/ | CC-MAIN-2016-18 | refinedweb | 1,629 | 50.02 |
ForestPad is a method for storing and retrieving textual information and consists of three applications:
Also included are two Setup projects. One for the PocketPC application that calls custom code which launches the ActiveSync application and one for a Windows Desktop version.
Before I go any further, I would like to pay homage to a wonderful program that I used for many years before deciding to write a replacement. The program is TreePad and it was written by Henk Hagedoorn . I would also like to thank CodeProject and all of the contributing developers for their hard work in creating one of the best resources on the web for information about .NET and C#.
Either ForestPadDesktop or ForestPadCE can be used independently. They become more powerful when used in combination with the ForestPadService which enables the PocketPC and Desktop applications to communicate over the web and syncronize data.
Currently, the Syncronize feature only checks to see which ForestPad document is newer. This means that data can be lost if you edit the same ForestPad document on two clients and then syncronize from each of them. Instead, you have to work in a "disconnected" mode. For instance, if you are editing data on the PocketPC in the field, you must syncronize the data to the ForestPadService, then syncronize before editing the same document in ForestPadDesktop.
This simple method works fine for me but could be extended in a variety of ways. You could add a check-in / check-out system similar to source control, you could syncronize data at the node level, or any other method that suites your needs. If you have a situation where you are always connected to the internet, you could even make the syncoronization automatic. If you only use one of the clients, you could still use the ForestPadService for the purpose of backup. The ForestPadService does not rely on a database so you can install it on any hosting account that supports the .NET Framework.
I decided to write ForestPad as a way of storing all of the textual information that I need to recall. Here is the way that I use it:
I use it to store lyrics. When practicing guitar, I can quickly flip through the tabulature for the songs. (Ctrl-K) puts the cursor in the search box just like FireFox allowing me to quickly search for an item in the ForestPad document simply by paging using multiple presses of the enter key.
I store C# code fragments in it. This is allowed because the underlying file format is XML with CDATA sections. The only thing that currently can't be stored is an XML fragment that contains CDATA tags.
At work, I store IP addresses, urls, contacts, interesting programming articles, emails addresses, todo lists, the text of emails, you name it. If it is text and worth storing and retrieving, it goes into ForestPad. I also use it as a portable internet favorites application. To import a url, you just drag it from your browser onto the ForestPad Desktop application. Currently, links are not clickable as I implemented the TextBox control rather than the RichTextBox control. This decision was made because the .NET CF does not provide the RichTextBox yet (although I understand it is possible to access something like it through un-managed code.) You can also drag text from other programs to the TreeView, the main TextBox and the graphical buttons. In ForestPadDesktop, you can also select a section of text or a whole node and email the text if you have entered an SMTP server and a From address in the Settings section.
TextBox
RichTextBox
TreeView
One of the things that always bothered me about TreePad was not a fault of TreePad but rather one of my own disorganization. I would constantly bury information so deep in a hierarchy that I would "lose" it. Also, there is a root node and for some inexplicable reason, it bothered me from a graphical perspective. I decided to follow a strict paradigm that both removed the root node and limited the depth of the hierarchy. In each ForestPad document, there are multiple forests which can contain multiple trees, branches, and leaves. This limited hierarchy, in my opinion, also makes the PocketPC version easier to use. Also, I decided to auto-name the TreeView node's Text property by displaying the text in the node up to the first carriage return. This allowed for quicker entry on the PocketPC as it is not necessary to name the node and made it easy to build an outline without minimizing the InputPanel.
Text
InputPanel
The file format of TreePad seemed strange to me but one must take into account that it was designed around 1995. Each node had a number representing its level in the tree and was terminated using the following string:
<end node> 5P9i0s8y19Z
I would assume that Mr. Hagedoorn thought the sequence 5P9i0s8y19Z would be unlikely to appear in the text of a node and I think that was probably right, as I never had a problem with it during the time that I used TreePad.
A TreePad file with a root node and one sub-node looked like this:
<Treepad version 2.7>
dt=Text
<node>
name
0
<end node> 5P9i0s8y19Z
dt=Text
<node>
name
1
text
<end node> 5P9i0s8y19Z
For some interesting code that deals with parsing another file format, check out the TreePadConverter class. I have included a TreePad example file so that you can see how it works. The only limitation that I know of is that the TreePad file must only be 5 levels deep (a root node and four levels) so that it can be mapped into the forest, tree, branch, leaf format. The root node from the TreePad file will not be retained. If you have not used a Stack before and are curious about one of its many uses, it will be of special interest. (Note: The TreePadConverter has only been tested with "TreePad version 2.7" files)
Stack
I wanted to store ForestPad files using XML so that I could import the data into other progams and so that the file would retain its visual heirarchy when opened in UltraEdit .
So, in contrast to TreePad, the file format of ForestPad looks like this:
<?xml version="1.0" encoding="utf-8"?>
<forestPad
guid="6c9325de-dfbe-4878-9d91-1a9f1a7696b0"
created="5/14/2004 1:05:10 AM"
updated="5/14/2004 1:07:41 AM">
<forest
name="A forest node"
guid="b441a196-7468-47c8-a010-7ff83429a37b"
created="01/01/2003 1:00:00 AM"
updated="5/14/2004 1:06:15 AM">
<data>
<![CDATA[A forest node
This is the text of the forest node.]]>
</data>
<tree
name="A tree node"
guid="768eae66-e9df-4999-b950-01fa9be1a5cf"
created="5/14/2004 1:05:38 AM"
updated="5/14/2004 1:06:11 AM">
<data>
<![CDATA[A tree node
This is the text of the tree node.]]>
</data>
<branch
name="A branch node"
guid="be4b0993-d4e4-4249-8aa5-fa9c940ae2be"
created="5/14/2004 1:06:00 AM"
updated="5/14/2004 1:06:24 AM">
<data>
<![CDATA[A branch node
This is the text of the branch node.]]></data>
<leaf
name="A leaf node"
guid="9c76ff4e-3ae2-450e-b1d2-232b687214aa"
created="5/14/2004 1:06:26 AM"
updated="5/14/2004 1:06:38 AM">
<data>
<![CDATA[A leaf node
This is the text of the leaf node.]]>
</data>
</leaf>
</branch>
</tree>
</forest>
</forestPad>
Each item in the document contains a Guid , a Created date, and an Updated date. Text is contained within a CDATA section in the "data" node. Additional elements or attributes could be added to the ForestPad file format to allow futher functionality.
Guid
You can add nodes to the TreeView by clicking on one of the iconic buttons. ForestPad will add the node relative to the currently selected item. Nodes can be rearranged in ForestPadDesktop but currently can't be promoted or demoted. To delete a node, right-click on it and select Delete, or in ForestPadCE, hold the stylus on the node until the context menu appears.
Documents are stored in \My Documents\ForestPad on both platforms.
Overall, my design goals involved creating similar but even simpler program than TreePad with some fundamental differences.
ForestPadDesktop and ForestPadCE share some code. It is located in the ForestPadUtilities project. You will notice that there are several classes named xxxxxDesktop and xxxxxCE. The changes between these class are minimal and the code could have been combined using compiler switches. The disadvantage of this method is that there is duplicate code. The advantage is that it makes the build process smoother. Hopefully, Microsoft provides some obvious ommisions from the Compact Framework in the next release, such as the Guid class. Having to compile using the /unsafe directive is at odds with the concept of managed code.
If you haven't used the TreeView before, check out the ForestTreeNode class and the PopulateTreeView method in either ForestDesktop.cs or ForestCE.cs where you can see a ForestTreeNode object placed in a Tag attached to each TreeView node. This Tag contains a pointer to the corresponding node in the XmlDocument and provides a mechanism for keeping the TreeView and XmlDocument in sync.
ForestTreeNode
Tag
XmlDocument
public enum ForestType
{
Forest = 0,
Tree = 1,
Branch = 2,
Leaf = 3
}
namespace ForestPadUtilities
{
/// <summary>
/// Summary description for ForestTreeNode.
/// </summary>
public class ForestTreeNode
{
public ForestType NodeType;
public string NodeName;
public XmlNode NodePointer;
public string NodeGuid;
public string NodeCreated;
public string NodeUpdated;
public ForestTreeNode()
{
}
}
}
Currently, you must download the source code to install the ForestPadService. At some point, I may build an installer.
In order to perform a full build of the code, you will have to modify the BuildCab.bat file in \ForestPadCE\BuildCabs\ to reflect the location of the files on your drive. The simplified command line is below:
cabwiz.exe ForestPadCE_PPC.inf /dest \ForestPad\ForestPadCE_Setup /err
Logfile.log /cpu ARMV4 ARM SH3 MIPS X86 WCE420X86
You will also need to modify ForestPadCE_PPC.inf and update the paths. Read the CodeProject article Developing and Deploying Pocket PC Setup Applications for more information.
Build first in Debug mode and then in Release mode. I replaced the CAB files in the ForestPadCE_Setup project with empty text files to save space. They will be replaced with the actual CAB files during the first Release build.
There is a virtual directory to setup for this solution. Point a virtual directory to the ForestPadService directory. Give the ASPNET process full permissions to the ForestPadService\DATA folder. Then visit and provide the Username: admin and Password: admin
Edit the admin user and create a new password. Then, in either ForestPadCE or ForestPadDesktop, in the Settings section, put as the web service url, admin as your username and your new password. Save the changes, create a document, enter some text, and choose Syncronize.
Your data will transfer from the client to the ForestPadService.
Security in ForestPad is minimal at the moment. It was not a major concern of mine when designing the program. Passwords for the ForestPad web service are encrypted within each application but currently the data stored on the ForestPad web service is not encrypted and the password is transferred to the web service in plain text. Adding encryption to the transaction would be a fairly trivial task. Also, it would be easy to store the ForestPad documents in a database, or to encrypt the XML.
You could also encrypt the information on the ForestPadCE and ForestPadDesktop clients. I chose not to do this as I wanted to be able to open the documents in a text editor. If you keep sensitive information, I would suggest making sure that both your PocketPC and your Desktop machine are password protected. For now, unless you modify the ForestPadService to include encryption, you could be putting yourself at risk by storing documents with it.
In the future, I will be releasing a version of the source at ForestPad.com that could be used to store secure information remotely.
This code could be used as the basis for many different types of projects.
For instance:
You could add a read-only attribute to the ForestPad User, and setup an identical Username and Password for everyone in an office to allow them all to receive ForestPad documents that you create. You could take the idea even further and allow the ForestPad User to store both their user specific documents and still receive the read-only syndicated documents. Or, modify the ForestPadService to redirect all the documents that a group of users create directly to you as a sort of data collection mechanism.
Add an option to ForestPadCE to store ForestPad documents on a removable memory card.
A search option could be added that would search through all of the ForestPad documents rather than just the one that is currently open. You could also extend the existing search to support regular expressions.
You could build a web-based viewer or editor for ForestPad documents.
Or, you could implement an option to transfer a ForestPad document between two PocketPC's using IR.
The images for the four node levels were designed by my friend, Sean Kaban. | https://www.codeproject.com/articles/7255/forestpad-a-method-for-storing-and-retrieving-text/?fid=55929&df=90&mpp=10&sort=position&tid=1731450 | CC-MAIN-2017-09 | refinedweb | 2,203 | 62.78 |
I'm new to programming, but with every program I do, I end up with one error. For some reason, I can't figure out how to install MSDN, so I can't press F1 for it to tell me what to fix. Here's my current code:
Anyone see any obvious discrepancies?Anyone see any obvious discrepancies?Code:
#include <iostream.h>
char WhatToDo()
{
cout << "What do you want to do?\n\n";
return 0;
}
char OpenGate()
{
cout << "You open the gate and step inside the yard. You marvel at the fact that even\n";
cout << "though this yard is tiny, there has apparently been no effort expended toward\n";
cout << "it's upkeep. You hear what could be muffled growling coming from your left.\n\n";
WhatToDo();
return 0;
}
int main()
{
char a;
cout << "You are standing in front of a run-down house. There is a blue sportscar that\n";
cout << "looks like it hasn't been driven in years parked out front. The car is covered\n";
cout << "in leaves. The house itself looks like it could collapse at any moment.\n";
cout << "There is a chain-link fence surrounding the house. The house has a screened-in\n";
cout << "porch, but you can't see much beyond that. Planted in the yard are trees which,\n";
cout << "if properly pruned, were probably nice bushes at one time. There is a closed\n";
cout << "gate which leads through the fence.\n\n";
WhatToDo();
cin >> a;
if (a = "open gate")
OpenGate();
else cout << "Please enter a valid command.\n";
return 0;
} | http://cboard.cprogramming.com/cplusplus-programming/70457-help-new-programmer-printable-thread.html | CC-MAIN-2014-15 | refinedweb | 263 | 84.27 |
What would be a reasonable way to dedupe notifications between native apps and web pages? Relevant if you have the nyt app installed and also give nyt.com permission to use the Notifications API.
Idea 1: nyt identifies user and dedupes before sending a push message. E.g. sends only to the native app if it is installed.
Idea 2: Some kind of collapse key in the notification so when it is shown from both native and web, there's still only one notification.
Any more?
Couldn't the notifications API de-dup if it notices two identical notifications in a short period of time? Without a collapse key, just based on similarity.
It would have to be the Android notifications system that does the deduping. The web notification would contain one additional piece of content (the origin) so the duplication matching would need to handle that. We can ask whether there currently is any such feature.
The Android NotificationManager only allows an application to view and manage notifications displayed by the current app. If you install both BCC News and BBC News Beta, you would get duplicated notifications as well. (Unless BBC would handle this on the server side, in which they could also include their website.)
Automatically removing duplicate notifications in the Notification manager has the difficulty that ours may appear completely different due to the forced inclusion of a Chrome app icon, origin, settings button, and so on. It would have to be a rather broad heuristic.
Android apps themselves aren't origin verified. Including a unique string for deduplication (analogous to the Web Notification API's "tag" property) *might* work if it's the newest notification that gets dropped, to prevent people from replacing other, cross-app/website notifications. It would still be very tricky, though.
The notification dedupe tag would have to be interpreted by the Android system. So if it does not exist yet and we can add that feature, it would only work for post-L release. Definitely worth discussing this with the Android ppl.
Oh, good point about Android.
For CrOS/Chrome, we could dedupe between Chrome apps and web pages simply based on the content because everything goes through Chrome's notification center.
I'm a little bit wary of content-based deduping. Can we use another more reliable method such as id sharing? Something like the following setup:
* App registers for a domain in its manifest's permissions section
* Then the ID namespace could be shared for web notifications (and possibly extension api notifications) allowing for cooperative deduping by web sites and apps using the same id for the same notification.
WDYT?
Michael, can you help drive this to conclusion?
Also, thinking about this some more, which app will "win" in the case of a duplicated notification? We will want a single app (be it mobile or web or packaged) to have control over updates / cancels and to receive events so that it has consistent behavior.
I don't suppose there is a clever way of sharing a device ID between native app and Chrome as this would mean a developer could de-dupe server side with relative ease.
Matt, that sounds like device fingerprinting:
Can we refocus the problem so that we send enough information that the app developers can detect this server side and make the right call of what entity should get the notification?
What is currently missing server side to be able to make that call?
In order to deduplicate notifications, the application server that sends push messages needs to know:
* user
* if web, the origin (e.g. ebay.co.uk vs ebay.com)
* device
* web or native
If the user signs into a webapp, the first part seems solved appropriately.
In the face of concerns around fingerprinting, I doubt we will expose an explicit device identifier in Chrome. Some other vendors are even less likely to do this. So we don't seem to have a simple and solid cross-browser solution for this yet.
I also don't know of a solid way to coordinate between web and native. The web should probably not be able to read whether a native app is installed. I've seen tricks to work with this though, but how reliable are they?
To clarify, there are currently two (hacky) ways to dedupe notifications:
1. Web app generates a random GUID, stores it in a cookie, and shares it with the native app by having the user click a link to a URL that the native app intercepts using an intent filter*. The native app extracts the GUID from the URL query string. If instead the native app isn't installed then the page loads in the browser and the web app now knows that the native app wasn't yet installed.
2. Native app generates a random GUID and shares it with the web app by launching Chrome with a URL whose query string contains the GUID. The web app saves it in a cookie or similar.
In either case, both the native app and web app now share the GUID, and once they both send it to their server it can dedupe push notifications.
These both have the downside that you have to redirect the user to/from the native app. I suspect that in the web->native direction you can make a transparent intent handler that saves the data then immediately exits, so the web app remains in the foreground and it's (almost?) seamless, but I haven't tested this.
Let's make this bug about standardizing a cleaner solution (without redirecting the user to/from the native app) and/or documenting the existing approaches with sample code.
*: (it's also possible to use an intent:// URI, but this has the downside that if the app isn't installed the user will be taken to the Play Store instead of back to the webapp)
In Chrome 42 you can use an intent:// URI and specify a fallback URL which the user should go to instead of the play store. You could set this to be the current page to avoid the redirect to the play store.
Details about deep linking into apps including fallback URLs:
For now the safest minimal solution is for sites to provide an easy opt out mechanism (which we strongly recommend you do anyway!) so users can turn off notifications from one platform
Another possible heuristic based solution is to take some measure for which interface (web or native) the user most often uses (or most recently used) and only send to that. Combined with grouping these devices by rough screen size should give a pretty good approximation.
The issue is that if the user has two similar sized devices and uses native on one and web on the other then notifications will only be delivered to one, which is an edge case.
We've also been discussing building an API so sites can tell whether their corresponding native app is installed to avoid this case, but need to start discussing that with other browser vendors to see if they'd be supportive.
Some more thoughts about techniques to apply in addition to or instead of heuristics:
1) When the user taps the button in your UI that triggers Chrome's permission request, first fire an intent into your native app from the site taking them to a screen which says "push notifications are already enabled", and note on your site to stop promoting it to them on this device. That can be achieved using the intent-firing technique documented by Paul Kinlan here:. His blog has more posts on related topics if it's confusing.
The risk now is a user enabling push and then later installing your native app. One potential improvement here is:
2) If your native app uses Chrome Custom Tabs then when a user taps a link to read an article you could open them first to a page on your site which disables push notifications from the web app and then redirect them to the article. Chrome Custom Tabs share the cookies/push subscriptions etc with normal Chrome so you can disable push from here.
Hopefully this API will be available soon too, which will provide more options:
+cc mgiuca@ and benwells@. mgiuca@ is the eng lead on the getInstalledRelatedApps API, which is probably the best solution we have to this problem (it lets a website query if the native app is installed, and thus it can then decide whether or not to prompt and send notifications).
Note that the getInstalledRelatedApps() API mentioned in #23 is not available in Service Workers, which is where the vast majority of notifications get shown from. That limits websites to check for duplication at subscription time. Which is a good step, but may not be sufficient per the aggressive "please install our native app" campaigns some websites are doing.
Yep, this is being addressed now (Issue 587623) with getInstalledRelatedApps.
That's a good point, #24, about service workers. Probably won't work out of the box so will have to be implemented in a follow-up.
#24 There's a bug for workers (Issue 716307).
Otherwise this is now landed and available behind an origin trial in M59. | https://bugs.chromium.org/p/chromium/issues/detail?id=402223 | CC-MAIN-2017-22 | refinedweb | 1,549 | 59.84 |
Today I finalised my changeover to Visual Studio. I know I’ve been down this road before, but this time it’s different (probably).
This time around, I’m using Visual Studio 2015 Professional with Python Tools For Visual Studio. My shiny MSDN licence gives me access to it, along with Visual Studio Online. I mention that because after thoroughly messing up my Bitbucket account, I’ve now decided to play nice with the MS way of doing this, and using VSO for my source control.
That is not what this post is about though. Things were looking a bit down when I tried to
import arcpy and VS could not resolve the import. After immediately googling the issue, I decided to look back at the editor and saw that the squiggly line was gone. Turns out VS needed a few minutes to decide that it liked ArcPy after all.
Like Joel McCune’s PyScripter workaround, I figured VS would need something as well to recognise Python toolboxes. After some clicking around, the solution was trivial:
Tools > Options > Text Editor > File Extension. Type
pyt into the text box and choose
Python Editor from the dropdown list.
The settings take a few minutes to take effect, but it’s evident it’s working once the pyt file changes to the Python colours. Now I just have to figure out how to structure all my files within a solution…
One thought on “Enable Intellisense in pyt files in PTVS” | https://cindygeodev.wordpress.com/2015/09/28/enable-intellisense-in-pyt-files-in-ptvs/ | CC-MAIN-2018-34 | refinedweb | 247 | 71.04 |
If the modulus weren't 1337 = 7 * 191 but a prime number p, we could use Fermat's little theorem to first reduce the exponent to e = b % (p-1) and then compute the result as ae % p. Oh well, we can do it for 1337's prime factors 7 and 191 and then combine the two results with the Chinese remainder theorem. I'll show my derivation of the magic constants 764 and 574 after the solutions below.
I got the solution using Fermat from @Stomach_ache (thanks) and only added the Chinese remainder theorem stuff to adapt it to non-primes like 1337.
Solution 1: Python "golf"
The helper computes ab modulo the prime
p.
def superPow(self, a, b): def mod(p): return pow(a, reduce(lambda e, d: (10*e + d) % (p-1), b, 0), p) if a%p else 0 return (764 * mod(7) + 574 * mod(191)) % 1337
Solution 2: C++
The helper computes ab modulo the given prime.
int superPow(int a, vector<int>& b) { return (764 * superPow(a, b, 7) + 574 * superPow(a, b, 191)) % 1337; } int superPow(int a, vector<int>& b, int prime) { if (!(a %= prime)) return 0; int e = 0, mod = prime - 1; for (int digit : b) e = (e * 10 + digit) % mod; int pow = 1; while (e) { if (e & 1) pow = pow * a % prime; a = a * a % prime; e >>= 1; } return pow; }
Using the Chinese Remainder Theorem
Let's call x = ab. We want to know x % 1337. The helper function using Fermat already gave us u and w so that x % 7 = u and x % 191 = w. Or put differently, x ≡ u (mod 7) and x = w + 191t for some integer t. Combine these to get w + 191t ≡ u (mod 7). Subtracting w and multiplying with [191-1]7 (the multiplicative inverse of 191 modulo 7) we get t ≡ (u-w)·[191-1]7 (mod 7).
We have [191-1]7 = [(191%7)-1]7 = [2-1]7 and one can easily see that the latter is 4, as (2*4)%7=1.
Using that, we have t ≡ 4(u-w) (mod 7) or in other words t = 4(u-w) + 7s for some integer s. Which means:
x = w + 191t
= w + 191(4(u-w) + 7s)
= 764u - 763w + 1337s
= 764u + (1337-763)w + 1337(s-w)
= 764u + 574w + 1337(s-w)
So we can compute x from u and v as x = (764u + 574w) % 1337, like I have done in my solutions.
I like this solution: use Fermat's little theorem to set up Chinese Remainder theorem equations. A very representative/general method. However, it might not be the best for this question, because it happens to be the case that 1337 only has two prime factors.
@StefanPochmann great job Stefan. You reminded me of when I studied this stuff in network security (RSA, etc) class :-)
@StefanPochmann said in Fermat and Chinese Remainder:
If the modulus weren't 1337 = 7 * 191 but a prime number p, we could use Fermat's little theorem to first reduce the exponent to e = b % (p-1) and then compute the result as ae % p.
Here's the proof of what Stefan is saying, for whom is interested in this stuff:
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/50591/fermat-and-chinese-remainder | CC-MAIN-2017-51 | refinedweb | 554 | 65.46 |
.-users group, or come ask questions on Slack.
The next few steps will show you:
The cluster startup script will leave you with a running cluster and a
kubernetes directory on your workstation.
The next step is to make sure the
kubectl tool is in your path.
The kubectl tool controls the Kubernetes cluster manager. It lets you inspect your cluster resources, create, delete, and update components, and much more. You will use it to look at your new cluster and bring up example apps.
Add the appropriate binary folder to your
PATH to access kubectl:
# OS X export PATH=<path/to/kubernetes-directory>/platforms/darwin/amd64:$PATH # Linux export PATH=<path/to/kubernetes-directory>/platforms/linux/amd64:$PATH
Note: gcloud also ships with
kubectl, which by default is added to your path.
However the gcloud bundled kubectl version may be older than the one downloaded by the
get.k8s.io install script. We recommend you use the downloaded binary to avoid
potential issues with client/server version skew.
You may find it useful to enable
kubectl bash completion:
If you’re using kubectl with Kubernetes version 1.2 or earlier, you can source the kubectl completion script as follows:
$ source ./contrib/completions/bash/kubectl
If you’re using kubectl with Kubernetes version 1.3, use the
kubectl completion command as follows:
$ source <(kubectl completion bash)
Note: The above commands will last for the duration of your bash session. If you want to make this permanent you need to add corresponding command in your bash profile.
Alternatively, on most linux distributions you can also add a completions file to your bash_completions.d as follows:
For kubectl with Kubernetes v1.2 or earlier:
$ cp ./contrib/completions/bash/kubectl /etc/bash_completion.d/
For kubectl with Kubernetes v1.3:
$ kubectl completion bash | sudo tee /etc/bash_completion.d/kubectl
but then you have to update it when you update kubectl.
Once
kubectl is in your path, you can use it to look at your cluster. E.g., running:
$ kubectl get --all-namespaces services
should show a set of services that look something like this:
NAMESPACE NAME CLUSTER_IP EXTERNAL_IP PORT(S) SELECTOR AGE default kubernetes 10.0.0.1 <none> 443/TCP <none> 1d kube-system kube-dns 10.0.0.2 <none> 53/TCP,53/UDP k8s-app=kube-dns 1d kube-system kube-ui 10.0.0.3 <none> 80/TCP k8s-app=kube-ui-dns-v5-7ztia 3/3 Running 0.
Then, see a simple nginx example to try out your new cluster.
For more complete applications, please look in the examples directory. The guestbook example is a good “getting started” walkthrough...requsites section– you’ve enabled the
Compute Engine Instance Group Manager API, and can start up a GCE VM from the command line as in the GCE Quickstart instructions.: Issue Edit This Page | http://kubernetes.io/docs/getting-started-guides/gce/ | CC-MAIN-2016-44 | refinedweb | 473 | 58.28 |
Determines if a DN is equal to the specified suffix. Before calling this function, you should call slapi_dn_normalize_case() to normalize the DN and convert all characters to lowercase.
If you want to determine if a DN is the same as the suffix for the local database, call the slapi_dn_isbesuffix_norm() function instead.
#include "slapi-plugin.h" int slapi_dn_issuffix( const char *dn, const char *suffix );
This function takes the following parameters:
DN that you want to check.
Suffix that you want compared against the DN.
This function returns 1 if the specified DN is the same as the specified suffix, or 0 if the DN is not the same as the suffix. | http://docs.oracle.com/cd/E19528-01/820-2492/aaifh/index.html | CC-MAIN-2014-15 | refinedweb | 110 | 61.67 |
While high-level templating systems can be used with Twisted (for example, DivmodNevow , sometimes one needs a less file-heavy system which lets one directly write HTML. While ResourceScript is available, it has a high coding overhead, and requires some boring string arithmetic. ResourceTemplate fills the space between Nevow and ResourceScript using Quixote’s PTL (Python Templating Language).
ResourceTemplates need Quixote
installed. In Debian , that means
installing the
python-quixote package
(
apt-get install python-quixote ). Other operating systems
require other ways to install Quixote, or it can be done manually.
The easiest way to get Twisted Web to support ResourceTemplates is to
bind them to some extension using the web tap’s
--processor
flag. Here is an example:
% twistd web --path=/var/www \ --processor=.rtl=twisted.web.script.ResourceTemplate
The above command line binds the
rtl extension to use the
ResourceTemplate processor. Other ways are possible, but would require
more Python coding and are outside the scope of this HOWTO.
ResourceTemplates are coded in an extension of Python called the”Python Templating Language” . Complete documentation of the PTL
is available
at the quixote web site . The web server will expect the PTL source file
to define a variable named
resource . This should be
a twisted.web.resource.Resource ,
whose
.render method be called. Usually, you would want
to define
render using the keyword
template
rather than
def .
Here is a simple example for a resource template.
from twisted.web.resource import Resource def getQuote(): return "An apple a day keeps the doctor away." class QuoteResource(Resource): template render(self, request): """\ <html> <head><title>Quotes Galore</title></head> <body><h1>Quotes</h1>""" getQuote() "</body></html>" resource = QuoteResource() | https://twistedmatrix.com/documents/current/web/howto/resource-templates.html | CC-MAIN-2017-30 | refinedweb | 277 | 58.28 |
Python Tips: Decorators
A very powerful and useful tool in Python
.
Our Goal
Through a simple example, to explain why we want to use decorators in our codes. First, we have a function that can print some messages.
Now, there is a new requirement to save the execution log of the function, we can add
print('Call foo()') to the function.
If the other functions have similar requirements, how do we do it? Copy the log code to the other functions? This results in a lot of similar codes. In order to reduce redundant code, we can redefine a new function: specifically process the log, and execute the real business code after the log.
Although the above code meets our requirements, this solution breaks the structure of the code, call the logging code instead of the business code
foo() where it should be called. To handle this problem in a better way, we can use decorators.
Decorator Solution
This is our solution with the decorator in Python.
log_decorator is a decorator that prints the execution log of the function. To implement the decorator, we use four features of python functions:
def log_decorator(func):: Functions can be passed around and used as arguments.
def log_wrapper(*args, **kwargs): Inner functions
return log_wrapper: Returning functions from functions
- The function can be assigned to a variable.
@log_decoratoris a syntactic sugar equivalent to
foo = log_decorator(foo).
The
functools module is for higher-order functions: functions that act on or return other functions.
@functools.wraps(func) is also a decorator that will preserve information about the original function.
REMEMBER: Add
@functools.wraps(func) before the definition your
wrapper().
def log_wrapper(*args, **kwargs) use
*args and
*kwargs, it will accept an arbitrary number of positional and keyword arguments.
Advanced Decorator
Further, if we need the decorator with some arguments, we need to write a higher-order function that returns a decorator. Please see the code below.
This is a triple nested decorator. It is easier to understand this program if you do not use syntactic sugar.
First, the return value of the
log(message) function is a decorator function
log_decorator(func) , and the return value of the
log_decorator(func) is wrapper function
log_wrapper(*args, **kwargs).
The program starts with the following line:
foo = log('Call')(foo)
In effect, the program executes
log('Call'), which returns the decorator function
log_decorator(func), and then calls the returned function with the parameter
foo() function and the return value is eventually the wrapper function.
Python Decorators in Practices
Authentication
Decorators are often used in projects for login verification, permission checking and other scenarios. In Django source code, uses two decorators
@login_required and
@permission_required to check the user’s log-in and permission.
user_passes_testSource code
The implementation of
user_pass_test shows that it uses the decorator. In your code, you just need to add
@login_required and
@permission_required before your process to complete the login and permission control.
Logging
In practice, if you suspect that some functions are running too long, increase the system latency. So you want to test the execution time of certain functions onsite, then decorators are a very common way to do this. Decorators are non-intrusive to project code.
The following is a simple demonstration:
The decorator
log print the runtime of a function and return the result of its execution. If you want to calculate the execution time of any function. just add
@log above the function.
Fibonacci sequence
The decorator’s feature of reducing repetitive code can also be used to help us compute the Fibonacci sequence.
We use a decorator to save the result of each
fib() calculation in a dictionary
cache. This solution is more efficient than using recursive ideas.
What’s new in Python 3.9 decorators
Thanks for reading.
Stay Healthy, Stay Coding.
| https://saneryee-studio.medium.com/python-tips-decorators-7187bc285469 | CC-MAIN-2021-17 | refinedweb | 630 | 56.86 |
Code. Collaborate. Organize.
No Limits. Try it Today.
This ASP.NET web site project (can be run from here) illustrates some basic techniques
for starting a long running task on the web server side, with provisions for tracking the progress of the task using AJAX.
Note: This application was tested on several shared hosting sites and was found to work properly.
However, you should be aware that the application saves the downloaded file to its folder on the web server.
For this to work, the IIS user account running ASP.NET must have a write-access to the application's folder.
It is quite risky to give anonymous users this level of access and, therefore, you should consider additional security measures.
It is interesting that ASP.NET allows a thread started from a server-side ASPX page to continue running even after the page's script has finished processing (i.e. there in no need to have the Page_Load() event wait for the auxiliary thread to finish).
Page_Load()
In this application, the following options are considered or implemented.
BeginInvoke()
HttpRuntime.Cache
Guid.NewGuid()
Besides its use of threading and callbacks, the project serves as a good example of employing AJAX concepts.
The project uses a minimal amount of AJAX code without using any AJAX library.
AJAX uses the XMLHttpRequest object to enable the browser to interact with the web server
and use the received data to modify parts of the page without page refresh.
XMLHttpRequest
The application is a Web Site (MS Visual Studio) project consisting of a single ASPX page default.aspx and its code-behind default.aspx.cs.
As it is normally the case with ASP.NET web applications, the ASPX file provides the necessary
HTML for the user interface along with client-side JavaScript AJAX code.
The code-behind includes a custom class AsyncWebRequest that encapsulates the long running method.
AsyncWebRequest
A proper starting place for understanding the code is the Page_Load() method, since it is the application’s entry point, given below.
public delegate void ProgressCallback(object sender, int Progress);
Boolean useDummyTask = false; // Set this as you desire
public string DummyTaskString = "";
protected void Page_Load(object sender, EventArgs e)
{ // Instruct browser not to cache the results
Response.AddHeader("cache-control", "no-cache");
if (useDummyTask) DummyTaskString = "(uses a dummy task)";
string TaskID;
// Handle one of three verbs: startTask, cancelTask, getStatus
if (Request["startTask"] != null)
{ TaskID = Request["startTask"];
AsyncWebRequest req = new AsyncWebRequest();
req.useDummyTask = useDummyTask;
string page_path = Server.MapPath("");
string downloadURL = Request["url"];
int i = downloadURL.LastIndexOf('/');
string fileName = downloadURL.Substring(i+1);
req.localfile = page_path + "\\" + fileName;
req.url = downloadURL;
req.ProgressChanged += new ProgressCallback(bw_ProgressChanged);
req.TaskID = TaskID;
HttpRuntime.Cache["DownloadRquest_" + TaskID] = req;
req.ExecuteRequest();
Response.Write("Task started");
Response.End();
return;
}
if (Request["cancelTask"] != null)
{ TaskID = Request["cancelTask"];
AsyncWebRequest req = (AsyncWebRequest)HttpRuntime.Cache["DownloadRquest_" + TaskID];
req.Cancel = true;
while (req.CompletionStatus != "Canceled")
{ Thread.Sleep(100); }
HttpRuntime.Cache.Remove("DownloadRquest_" + TaskID);
Response.Write("Task canceled");
Response.End();
return;
}
if (Request["getStatus"] != null)
{ TaskID = Request["getStatus"];
string st = (string)HttpRuntime.Cache["Task_state_" + TaskID];
if (st.Length > 3) HttpRuntime.Cache.Remove("DownloadRquest_" + TaskID);
Response.Write(st);
Response.End();
return;
}
}
In Page_Load(), the application handles one of three verbs (parameters in the URL's query string):
startTask, cancelTask, getStatus.
The verb's value is the TaskID of the task involved. Because the response to any of these verbs is just some little text, the block handling the verb ends with:
startTask
cancelTask
getStatus
Response.End();
return;
This ends the response stream and terminates the Page_Load() method.
If we do not do this, ASP.NET will send the HTML text from "Default.aspx".
With the above code for Page_Load(), the html text from Default.aspx
is only sent when the query string is empty (i.e., when the application is
started), because we are not executing Response.End() in this case.
Response.End()
We can run a method (a long running task) asynchronously by wrapping it into a delegate and calling
BeginInvoke().
This will have the method run on a thread from the ThreadPool.
ThreadPool
To monitor the progress of method execution, we will use an AJAX function
getStatus().
The function will post back a query string getStatus=TaskID.
This will be processed by Page_Load() and return a string back to the client
(unless there is some error, the string will simply be a value 0-100 indicating progress percentage).
getStatus()
getStatus=TaskID
Next, we need to settle on a mechanism for the called method to report progress.
For this, we can use one of the following approaches:
We use the second approach in our application.
Our long running task will use an instance of WebRequest to download some URL. The data will be read from the response streams in chunks using the statement:
WebRequest
RecvStream.Read(Buffer, 0, BlockSize);
The preceding statement will be part of a while-loop in which we update and report the progress, as shown by the following code snippet (from our
AsyncWebRequest class):
while
long TotalBytes = resp.ContentLength;
int BlockSize = 8192;
Byte[] Buffer = new Byte[BlockSize];
FileStream fs = new FileStream(Obj.localfile, FileMode.Create);
long ByteCount = 0;
while (true)
{ // Read incoming data
int BytesRead = RecvStream.Read(Buffer, 0, BlockSize);
if (BytesRead == 0) break;
ByteCount += BytesRead;
fs.Write(Buffer, 0, BytesRead);
// Update and report progress
int Progress = (int)( (double)ByteCount / TotalBytes * 100);
if (Progress <= 100) ProgressChanged(this, Progress);
}
The completed AsyncWebRequest class is given below.
public class AsyncWebRequest
{
public string url, localfile;
public string TaskID;
public event ProgressCallback ProgressChanged;
public Boolean Cancel = false;
public Boolean useDummyTask = false;
public string CompletionStatus;
delegate void MethodInvoker();
public void ExecuteRequest()
{ MethodInvoker simpleDelegate;
if (useDummyTask) simpleDelegate = new MethodInvoker(this.RunDummyTask);
else simpleDelegate= new MethodInvoker(this.RunTask);
simpleDelegate.BeginInvoke(null,null);
}
private void RunDummyTask()
{ for (int i = 1; i <= 100; i++)
{ if (Cancel)
{ CompletionStatus = "Canceled"; break; }
// Update progress
ProgressChanged(this, i);
Thread.Sleep(200);
}
}
private void RunTask()
{
WebRequest req = WebRequest.Create(url);
WebResponse resp;
try { resp = req.GetResponse(); }
catch (WebException e)
{ CompletionStatus = e.Message;
ProgressChanged(this,-1);
return;
}
long TotalBytes = resp.ContentLength;
int BlockSize = 32768;
Stream RecvStream = resp.GetResponseStream();
// RecvStream.ReadTimeout = 3000;
// RecvStream.WriteTimeout = 3000;
Byte[] Buffer = new Byte[BlockSize];
using (FileStream fs = new FileStream(localfile, FileMode.Create))
{ long ByteCount = 0;
while (true)
{ if (Cancel)
{ CompletionStatus = "Canceled"; break; }
// Read incoming data
int BytesRead = RecvStream.Read(Buffer, 0, BlockSize);
if (BytesRead == 0) break;
ByteCount += BytesRead;
fs.Write(Buffer, 0, BytesRead);
// Update progress
int Progress = (int)( (double)ByteCount / TotalBytes * 100);
if (Progress <= 100) ProgressChanged(this, Progress);
}
}
}
}
Our AsyncWebRequest class encapsulates the long running method (RunTask() or
RunDummyTask()).
The public members of this class correspond to some relevant input-output parameters.
RunTask()
RunDummyTask()
Furthermore, the callback delegate ProgressChanged (of type ProgressCallback) used for reporting progress
is a public member marked as an event (so that it can be called (fired) from its owning class only).
ProgressChanged
ProgressCallback
By utilizing delegates, the AsyncWebRequest class has less coupling with other code.
The class can be used with different types of .NET applications: Web Forms, Windows Forms, or Console applications.
As illustrated by the code in Page_load(), to use the class, set the necessary members including
the ProgressChanged event and call ExecuteRequest() method:
Page_load()
ExecuteRequest()
AsyncWebRequest req = new AsyncWebRequest();
req.localfile = page_path + "\\" + "file1.wmv";
req.url = "";
req.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
req.ExecuteRequest();
Note that a call to ExecuteRequest() is synchronous (blocking). However, the call finishes quickly because all
it does is that it instantiates a delegate and calls BeginInvoke().
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
C# 6: First reactions | http://www.codeproject.com/Articles/492789/Starting-and-Monitoring-a-Long-Running-Task-Using- | CC-MAIN-2014-15 | refinedweb | 1,254 | 50.73 |
View contents of SD Card
I have a Lopy and expansion board. I'm using FileZilla to view/edit contents of the flash and want to know if I can also view/edit contents of the expansion board's SD card with FileZilla.
This post is deleted!
Hello Robert, I used the example SD code where I see it call the mount statement.
from machine import SD
import os
sd = SD()
os.mount(sd, '/sd')
os.listdir('/sd')
f = open('/sd/test.txt', 'w')
f.write('Testing SD card write operations')
f.close()
f = open('/sd/test.txt', 'r')
f.readall()
f.close()
@JimT The SD card has to be mounted before you can access internally and externally. If you could write to it, that only means that somewhere in the code it was mounted. That does not have to be in boot.py. But since boot.py is always executed on boot, this is a good place to perform the mounting.
If you ask about documentation: for boot.py and main.py, look at the (very good) documentation, chapter 1.5 or 2.5. The SD card set-up is documented in chapter 6.2.1.11 SD
I wonder how you managed to write to the SD card w/o mounting it?
Thank you for your response. I will add these statements to the boot.py file. Where is the documentation which discusses this? I was able to write to the sd card without these statements but it will be great to see the results using fileZilla.
@JimT Once you have mounted the SD card from within the LoPy, you can see it's content by ftp under the name you used for mounting. You can add the statements for mounting to your boot.py script, like:
import os import machine sd = machine.SD() os.mount(sd, '/sd')
In that case, the SD cards content would appear under /sd. | https://forum.pycom.io/topic/1792/view-contents-of-sd-card | CC-MAIN-2018-17 | refinedweb | 321 | 78.75 |
Many programs that do some kind of brute-forcing and that have to calculate all possible combinations of a given subset of characters or objects, resort to recursion or to some dirty kind of looping mechanism with inner-loops etc... A couple of years ago, I issued a contest on a hacking forum to write some code in whatever language to return all possible combinations of alphabetic characters up to the length of 6. Only two people submitted an entree, including myself. The other solution was - again - a method that used recursion. My method used something else, namely the idea that any combination of letters could be represented by a unique number so that a simple counter mechanism could be used. The program worked fine but was somewhat static. This article is the result of putting the initial idea into a reusable class that was small and easy to use. It might be not super-performing (otherwise it should be written in ASM or something), but it will allow you to write, e.g., a simple password brute-forcer with a few lines of code... I hope you enjoy it and that it's useful. Any improvements are more than welcome.
The code will also be part of a forthcoming project. This project will try to bundle useful classes for creating programs that can be used to test security, such as for pentests etc� Hopefully online soon.
The whole idea is that any combination of a subset of chars - an array of chars, or symbols, or whatever - can be translated in a unique number representing that combination. Maybe an example will clarify this:
Let's say we have an array {"a","b","c","d"}, and we want to check all combinations possible with length 3. This would be aaa, aab, aac, aad etc..., in total 4 to the power of 3 combinations. Each combination can be translated in a number as follows:
aaa= 0, aab=1, aac =2 .... more specifically, what we do is: dac = 4*4^2+1*4^1+3*4^0 (the fourth element in the array (d=4) times the length of the array (4 chars=4) to the power of the length of the string minus one (3-1=2) (3 chars + the first element of the array times...etc...). Just like, e.g., 5420 can be written as 5*10^3 + 4*10^2 + 2*10^1 +0*10^0.
So now, we have a way to translate a combination in a number, and we can easily do it the other way around, which is in fact what we need because we will implement a counter and return the corresponding string. This is the corresponding code snippet from the class that handles this translation. I called the method
factoradic, because I found out afterwards that a similar technique was used in an MSDN article, where they called it
factoradic.
private string factoradic(ulong l, int power) { StringBuilder sb = new StringBuilder(); //set the maximum capacity of our stringbuilder object sb.Capacity = power +1; while (power >=0) { int len = this.charset.Length;// ulong q = l / (ulong)Math.Pow((double)len,(double)power); ulong m = l % (ulong)Math.Pow((double)len, (double)power); sb = sb.Append(this.charset[(int)q]); l = m; power--; } return sb.ToString(); }
We use a
StringBuilder instead of a string because it's a bit more memory friendly.
l is the number we want to translate, and
power is the length of the string we want to return -1 (the -1 is done when the function is called). So basically, what we do is make a
StringBuilder object and then enter a loop where we do the rundown of the routine where the number gets translated to the corresponding positions in the
char array, by decreasing the powers and using the modulus as a re-entree point. I know it sounds complex, but just keep the example above in mind (the 5420 example). The charset that we use is declared earlier in the class. Unfortunately, we have to cast to
double for the
Math.Pow stuff.
Now that we can translate a number to a string, we have to think of a way on how we can return all the possible combinations in a nice and simple fashion. This is where enumerations come in very handy. First, we make our implement
IEnumerable:
public class Bruteforce : IEnumerable
Then our enum routine looks like this:
public System.Collections.IEnumerator GetEnumerator() { for (int x = min; x <= max;x++ ) { ulong counter =0; while (counter < (ulong) Math.Pow((double)charset.Length, (double)x)) { string a = factoradic(counter, x-1); yield return a; counter++; } } }
The trick here is to reset the counter to zero in the beginning of the loop, otherwise you will just continue with the value when switching bruteforce lengths. So this loop loops between the min length and the max length we want to bruteforce, and then spawns all possible strings, represented by their numeric counterpart which is just a counter that starts at zero and goes up to
(ulong)Math.Pow((double)charset.Length, (double)x), which is the number of all possible combinations.
The rest of the code is just a bunch of declarations.
Now this code works fine, but lacks some performance. First of all, we use a lot of casts which are expensive, and we also declare some stuff in loops that we could declare earlier (as was pointed out by some readers). Also, it is possible to change the logic in the
factoradic method a bit so
Math.Pow is no longer needed. So we move up all declarations as much as possible, and we change the
factoradic method. I still use a
StringbBuilder though. The side effect of changing the
factoradic method is that the returned string is brute-forced in reverse order, but this is no problem, since it doesn't affect what we try to achieve. If we change our example and include a
Systems.Diagnostics.StopWatch, we can measure the results, which are dramatic:
As you can see, the new code performs about five times better than the old one. It's even more elegant as well ;). Here's the full new code (the download includes comments):
using System; using System.Collections; using System.Text; namespace Hacking { public class Bruteforce : IEnumerable { #region constructors private StringBuilder sb = new StringBuilder(); //the string we want to permutate public string charset = "abcdefghijklmnopqrstuvwxyz"; private ulong len; private int _max; public int max { get { return _max; } set { _max = value; } } private int _min; public int min { get { return _min; } set { _min = value; } } #endregion #region Methods public System.Collections.IEnumerator GetEnumerator() { len = (ulong)this.charset.Length; for (double x = min; x <= max; x++) { ulong total = (ulong)Math.Pow((double)charset.Length, (double)x); ulong counter = 0; while (counter < total) { string a = factoradic(counter, x - 1); yield return a; counter++; } } } private string factoradic(ulong l, double power) { sb.Length = 0; while (power >= 0) { sb = sb.Append(this.charset[(int)(l % len)]); l /= len; power--; } return sb.ToString(); } #endregion } }
Thanks for the suggestions!
The code is quite simple to use. Import the C# file or the DLL, and then you just set the min and max value, change the charset if you want (default = alphabet), and then start a
foreach loop to loop through the enumeration, and do whatever you want in the loop:
using System; using System.Collections.Generic; using System.Text; using Hacking; namespace example { class Program { static void Main(string[] args) { Bruteforce b = new Bruteforce(); b.min = 2; b.max = 4; b.charset = "abcdefghijklmnopqrstuvwxyz0123456789"; string target= "abc1"; foreach (string result in b) { Console.Write(result +"\r"); if (result == target) { Console.WriteLine("target found:" + result); return; } } } } }
We first initialize a new
Bruteforce object. Then we set the min and max values and the charset we wish to use. In this example, we are going to loop over our enum until we hit the "abc1" value. Imagine that the target string is a SHA1 hash and that you process each enum value into a SHA1, then you have a simple SHA1 bruteforcer.
Hope you can use the code... Enjoy.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/security/Hacking_BruteForce.aspx | crawl-002 | refinedweb | 1,360 | 63.49 |
#include <hallo.h>First, we (me and Thomas Schmidt) are working on a draft for a mandatorylocking scheme which will take care of the most racy situations evenwithout having a proper in-kernel solution. But you need to exlain somethings, otherwise we cannot rely on your words.> (open has side effects relocking doesnt)What exactly does that mean in our scope?Can we do following without having side effects:open("/dev/sr0",O_EXCL|O_RDWR); /* no matter what it returns */fcntl(..., F_SETLK); /* no matter what it returns */ioctl(f, SCSI_IOCTL_GET_IDLUN, &x);ioctl(f, SCSI_IOCTL_GET_BUS_NUMBER, &jo);Can you guarantee us that bit? Or shall we really implement ugly workarounds to avoid every open call?Note that "just do like UUCP guys" is not as easy or reliable as peoplemay pretend.Eduard.-- Naja, Garbage Collector eben. Holt den Müll sogar vom Himmel. (Heise Trollforum über Java in der Flugzeugsteuerung)-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2007/4/7/75 | CC-MAIN-2016-36 | refinedweb | 174 | 57.37 |
Am I just imagining something, or is there a strlen command? If there is how do I use it?
I want to be able to measure the length of a string.
This is a discussion on Measuring string length within the C++ Programming forums, part of the General Programming Boards category; Am I just imagining something, or is there a strlen command? If there is how do I use it? I ...
Am I just imagining something, or is there a strlen command? If there is how do I use it?
I want to be able to measure the length of a string.
Go you big red fire engine!
yes you can use
using std::strlen;using std::strlen;Code:#include <cstring>
for c style strings
or you can do something like
Code:string s; s.length();
I think you're going to needfor it to recognize string in the std namespace.for it to recognize string in the std namespace.using std::string;
dan
I'm using visual c++ 6.0.
Can I please have a bit more of an explaination, or a small example?
Thankyou.
Go you big red fire engine!
The following was created in Visual C++ as a Win32 console applicaiton. Selecting "Typical Hello world application" then modifying it.
I hope this helpsI hope this helpsCode:#include "stdafx.h" //for precompiled headers #include <iostream> //for cout and other c++ methods within iostream class #include <string> //for string class using namespace std; //use entire std namespace avoiding "std::" scope resolution operator int main(int argc, char* argv[]) { string sData = "Test"; cout << "sData contains " << sData << endl; cout << "sData's length is " << sData.length( ) << endl; //or int nStringLength = sData.length( ); cout << "sData contains " << sData << endl; cout << "sData's length is " << nStringLength << endl; return 0; }
hmm. I figured a method out the other day.
#include "iostream.h"
#include "stdio.h" // Used for gets()
int main()
{
char String[80];
cout << "Enter a string ";
gets(String);
int idx = 0;
while(String[idx] != NULL){ // you could replace NULL with 0
idx++;
}
cout << "You typed " << idx << " characters/spaces".
}
I'm not sure if this was the answer you were looking for.
Not Hungarian notation (:
Here is the c style one
Code:#include <cstring> using std::strlen; #include <iostream> using std::cout; using std::endl; int main(void) { char* s = "Hello World!"; int n = strlen(s); cout << "Hello World! is " << n << " charecters long" << endl; return 0; }
forgot to put my name up there.
In the Unregistered post.
gets is dangourous and shouldn't be used.
80 is a pretty good size buffer but someone still
could enter 81 charectors possibly causing a stack overflow.
Using fgets is safer.
#include <iostream.h>
#include <string.h>
int main() {
char string[600];
cout << "Enter a string: ";
cin.getline(string,600);
cout << "Length: " << strlen(string);
return 0;
}
Thankyou for all the help so far, but I still have a problem.
I've been working with dangs code. His code works when it's written like it's shown above, but not when I modify the includes to how they are in my program.
Here are the files that I am including in my program(MS VC++ 6):
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <fstream.h>
#include <ctype.h>
#include <iomanip.h>
When they have the .h on the end dangs code doesn't work, but when i get rid of the .h, hundreds of other errors occur.
I'm not sure why this occurs as I was under the impression that you didn't really need the .h in VC++ anymore (though I have been told to use it - which is why I do). Any help or suggestions will be greatly appreciated, thanks again for all your help so far.
Go you big red fire engine!
You arn't supposed to have .h after std includes
in c++. The reason why you having trouble
is that <string.h> and <string> are different files.
change your includes from :-
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <fstream.h>
#include <ctype.h>
#include <iomanip.h>
to:-
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <cctype>
#include <iomanip>
// and add this line directly underneath the includes...
using namespace std;
also if you are using the STL string you will need to add <string> to that list of includes...
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :-
Thankyou very much - all complete (except for some stupid memory error, but that's not related to this issue).
Go you big red fire engine! | http://cboard.cprogramming.com/cplusplus-programming/1173-measuring-string-length.html | CC-MAIN-2014-52 | refinedweb | 764 | 77.84 |
[beginner] Deploying a ear file under JBoss AS 5Sarko Zio Jan 9, 2010 5:03 AM
Hi everybody, I hope I'm in the right section!
I developed a very basic "web service" (Hello world) following this tutorial. With Ant I generate the jar, war and ear files. Then I try to upload the ear using the Jboss Administration section but it gives error:
Failed to create Resource example2.ear - cause: java.lang.Exception:Failed to remove deployment [vfszip:/C:/Programmi/jBoss/server/default/deploy/example2.ear/] after start failure. -> java.lang.RuntimeException:java.io.IOException: Failed to delete: DelegatingHandler@9044862[path=example2.ear context=file:/C:/Programmi/jBoss/server/default/deploy/ real=file:/C:/Programmi/jBoss/server/default/deploy/example2.ear] -> java.io.IOException:Failed to delete: DelegatingHandler@9044862[path=example2.ear context=file:/C:/Programmi/jBoss/server/default/deploy/ real=file:/C:/Programmi/jBoss/server/default/deploy/example2.ear]
I tried with the war file only and I had the same issue. I also tried to copy the war/ear file into the deploy/ default's subfolder and this still throws exception in the console. I then checked whether the file is correct and it should be, for I managed to run it properly under tomcat (the war file, I mean).
Can someone help me understading this issue? In attachment you find the ear file.
Thank you so much!
- example2.ear 2.4 KB
1. Re: [beginner] Deploying a ear file under JBoss AS 5Peter Johnson Jan 9, 2010 3:13 PM (in response to Sarko Zio)
You are using the root package which is not a good idea. Try assigning a package name to your class. Also, it might help to post the source for the class.
You should be able to deploy the WAR file by iteslf; you do not have to put it into an EAR.
Try deploying the WAR after JBoss AS is started. What deployment information is display?
You are not, by any chance, doing this within Eclipse (or NetBeans) are you? Wait, I see you are using the Admin Console. Instead, try copying the WAR to server/xxx/deploy manually and see what happens.
2. Re: [beginner] Deploying a ear file under JBoss AS 5Sarko Zio Jan 10, 2010 4:01 AM (in response to Peter Johnson)
Hi and thank you for your kind reply!
So, in the console the following error is displayed:
*** DEPLOYMENTS IN ERROR: Name -> Error
vfszip:/C:/Programmi/jBoss/server/default/deploy/example2.ear/ -> org.jboss.depl
oyers.spi.DeploymentException: Error creating managed object for vfszip:/C:/Prog
rammi/jBoss/server/default/deploy/example2.ear/example2.war/
DEPLOYMENTS IN ERROR:
Deployment "vfszip:/C:/Programmi/jBoss/server/default/deploy/example2.ear/" is
in error due to the following reason(s): org.xml.sax.SAXException: The content
of element type "servlet-mapping" must match "(servlet-name,url-pattern)". @ vfs
zip:/C:/Programmi/jBoss/server/default/deploy/example2.ear/example2.war/WEB-INF/
web.xml[16,21]
at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(Dep
loyersImpl.java:993)
Ok, I know default package is discouraged, but it was just a test. I don't really think this is the an error cause (but I may be wrong )
No, I don't use Eclipse, at least for the first projects. I want to understand step-by-step how the whole thing works. The only strange thing I did was to modify the listening port from 8080 to 8070 (in order to avoid conflicts with Tomcat).
And, as I wrote, I developed it also in the manal way after JBoss started but nothing to do, always the same error. Well, all the configuration files are contained in the .ear I attached. Anyway, the class reads:
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World Servlet!</title>");
out.println("</head>");
out.println("<body>");
out.println("<p align=\"center\"><font size=\"5\" color=\"#000080\">Hello World!</font></p>");
out.println("<p align=\"center\"><a href=\"javascript:history.back()\">Go to Home</a></p>");
out.println("</body>");
out.println("</html>");
}
}
From the error message it seems there is an error in web.xml but I don't really understand this magic code. I have knowledge of servlets but I don't know the hidden mechanisms behind JBoss deployment so I wouldn't know where to modify the file.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"">
<web-app>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern>/servlet/HelloWorld</url-pattern>
<servlet-name>HelloWorld</servlet-name>
</servlet-mapping>
</web-app>
Hope this will make the problem clearer...
Thank you again!
3. Re: [beginner] Deploying a ear file under JBoss AS 5Sarko Zio Jan 10, 2010 12:55 PM (in response to Sarko Zio)Ok, I installed JBoss version 4.2 an it works perfectly. I now read the summary of the main differences between 4.2 and 5 (EE compliant) but I still can't understand why my code is not working on JBoss 5.
4. Re: [beginner] Deploying a ear file under JBoss AS 5Peter Johnson Jan 11, 2010 10:02 AM (in response to Sarko Zio)
This extra error message helps:
sarko86 wrote:
of element type "servlet-mapping" must match "(servlet-name,url-pattern)". @ vfs
zip:/C:/Programmi/jBoss/server/default/deploy/example2.ear/example2.war/WEB-INF/
web.xml[16,21]
JBoss AS 5 is striucter whne it comes to following the web.xml file layout thatn what AS 4.x was. The issue is that you have the servlet-name and url-pattern in the wriong order; it should be:
<servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/servlet/HelloWorld</url-pattern> </servlet-mapping>
5. Re: [beginner] Deploying a ear file under JBoss AS 5Sarko Zio Jan 12, 2010 11:16 AM (in response to Peter Johnson)Thank you very much, that was it! | https://developer.jboss.org/thread/146582 | CC-MAIN-2018-17 | refinedweb | 1,035 | 50.73 |
What
Stoxy is a new, modern, reactive state management system for web applications.
It's a small, dependencyless, extensible set of functions to create stateful features for you web app, and even persist them through sessions.
How
Stoxy requires no setup. After the install with
npm install @stoxy/core
You don't need to hassle with reducers, nor any initial state objects, you can immediately start writing stateful applications.
import { write } from '@stoxy/core'; const userData = { userName: "Stoxy", shoppingCart: [ { id: 123, name: "Flaming hot cheetos" } ], shoppingHistory: { latestProducts: [ { id: 555, name: "Doritos" }, { id: 958, name: "Pringles" } ] } }; write("userData", userData);
Persisting objects through sessions can be done on a per-key basis with a single command
import { persistKey } from '@stoxy/core'; persistKey('userData');
Reading data through the promise based API is made simple too:
read('shoppingcart').then(shoppingCartItems => { shoppingCartItems.map(item => console.log(item)); });
There are multiple user-tailored functions at your disposal for more specific actions too. Read more about them at the docs.
Where
Stoxy can be run anywhere, with any framework. Even with no framework at all.
Currently Stoxy ships with element mixins for Web Components and hooks for React/Preact.
Read more about Stoxy at the site: Stoxy.dev
Stoxy just reached 50 stars in Github. Join the stargazers at GitHub!
Discussion (5)
How would this compete against easy peasy store?
First thing I can clearly see is: Size: bundlephobia.com/result?p=easy-pea...
Another is that Stoxy utilizes the IndexedDB for performance over session/localstorage.
Indexeddb is also a better way for for example offline first applications
Third would be the framework agnosticity. Easy peasy (seems at least) is for React
It's okay. But valtio takes it for me. Valtio also works well in react native
github.com/pmndrs/valtio
What’s the benefit over Redux? Will this be able to replace redux or is it just another state management similar to React context?
The benefit over redux is the ease of entry, and a way more simplified, more concise API.
The package is about as small as the redux core, and way smaller than redux toolkit.
Stoxy also ships with persistence in mind from the get go, so you don't need to install any extra libraries to get said functionality.
What made me create the lib was the convoluted mess of reducers and setup you needed for even the simplest of state operations, which could be one-liners, like stoxy does | https://dev.to/matsuuu/dead-simple-state-management-with-stoxy-41pg | CC-MAIN-2021-39 | refinedweb | 408 | 56.76 |
6 releases (2 stable)
49 downloads per month
Used in dart
230KB
5.5K SLoC
dart-sys
Native bindings to the dart native extensions sdk.
This crate exposes an api for
dart_api.h,
which exposes the basic dart
native extensions api.
This crate used
bindgen
to generate the bindings to the header.
Requirements when building bindings again (off by default)
- Provide a path to the dart sdk using a
dart_sdkenvironment variable.
- If this variable is not available, will look for either a chocolatey install path, or an entry in the
PATHvariable which contains
dart-sdkin it. This will fall back to the
fluttersdk should it not find a dart sdk, but this is not recommended, as it is more difficult to compile using the flutter sdk and it appears it ships a non-standard dart sdk.
Usage
Include the following in your
Cargo.toml:
[lib] crate-type = ["cdylib"] [dependencies] dart-sys = "0.1.0"
And follow the guide on the native extensions api page.
Examples
Please visit the examples directory for more information. If there should appear more idiomatic bindings, I will try to keep this updated to link to them.
Note
A few things are not mentioned on the native extensions api page:
- You should compile using an x64 compiler (eg.,
[stable|nightly|beta]-x86_64-pc-windows-msvc)
- You should place the compiled library in the same directory as the root of your dart package (I.E. outside of your
libdirectory)
- You should make sure these three coincide:
- The shared object/dynamic link library name.
- The NAME in
NAME_Initfunction when writing a sync extension.
- The name of the import in
import 'dart-ext:NAME'.
- When compiling for Linux, name your shared object
libNAME.so.
This crate does not generate bindings, and instead uses prebuilt ones. The code to build the bindings can be found commented in
build.rs.
To run, uncomment and from there, copy the contents of the
bindings.rsfile under the directory which is reported in the panic into
lib.rs.
The bindings were last generated on the 26th of February 2020.
I have manually edited the names under the generated bindings to avoid ugly bindgen names such as
_Dart_CObject__bindgen_ty_1__bindgen_ty_3, and instead replaces them with a more appropriate name
based on their usage in the api. (Such as
Dart_NativeString). | https://lib.rs/crates/dart-sys | CC-MAIN-2020-16 | refinedweb | 382 | 65.93 |
Write objects that function the same as those in Python's standard libraries. In this article, we discuss how to utilize built-in functions like _len_ and _eval_ to make objects in Python that make use of the language's data.
Before we start exploring how to write a Pythonic Object, let us start by making it clear what I mean by that term. It is not about PEP8 and respecting its rules to write beautiful pythonic code; rather it's about writing objects that make maximum use of the concepts of the Python data model, so they can be used as naturally as the Python standard library objects.
The idea is to inject Python ADN in our user-defined objects to make them mutate and behave as native Python objects. To do so, we will implement a
Vector class to represent a multidimensional vector.
The code below represents the
Vector class with its minimal implementation. A
Vector is represented by its coordinates.
from array import array class Vector: __arrayType = "d" def __init__(self, coordinates): self.__coordinates = array(self.__arrayType, coordinates) if __name__ == "__main__": v = Vector([1, 2, 3]) print(v) #<__main__.Vector object at 0x0082F610> v1 = Vector((1, 2, 3)) print(v1) #<__main__.Vector object at 0x0317FC88>
The Vector coordinates are stored in a float array; notice the
__arrayType = "d" that imposes the type of elements within the array to floats. We can pass any iterable to the constructor of
Vector since the constructor of the array uses as an internal container that accepts any _iterable _(tuples, lists, etc.).
When we print a
Vector object itself, note that we get its reference (memory address with CPython) and not its coordinates. Let us change that by implementing the
__str__ method within our class to have a more friendly output like for example
(x, y, z, ..).
from array import array class Vector: .... def __str__(self): return str(tuple(self.__coordinates)) .... if __name__ == "__main__": v = Vector([1, 2, 3]) print(v) #(1.0, 2.0, 3.0)
Automatically, when the
__str__ method is executed to get the string to be printed. Notice that we used the string representation of a tuple created from the array._
_
__str__ is not the only the method the Python data model uses to print objects;
__repr__ _is also used to provide a representation of the object more oriented for debugging purposes. This representation can be evaluated to create the same object with the
eval function.
For further details about the differences and the use cases of
__str__ and _
__repr__ you can refer to the Python: __str_( ) vs. repr( ) article.
from array import array import reprlib class Vector: .... def __repr__(self): s = reprlib.repr(self.__coordinates) return "{}({})".format(self.__class__.__name__, s[s.index('['):-1]) ... if __name__ == "__main__": v = Vector([1, 2, 3]) s = repr(v) print(s) #Vector([1.0, 2.0, 3.0]) v1 = eval(s) print(v1) #(1.0, 2.0, 3.0) v2 = Vector(range(100)) print(repr(v2)) #Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
In the previous code block, notice that the returned value of
reprwhen used with
evalpermits to create a new
Vector. The use of
reprliballows us not to print all the elements of the array in case it contains too many elements and replace them with.... like the vector
v2.
To ensure that we can loop on our vectors and that we can unpack them, we need to make them iterables. To do so, the
__iter__ method must be added to our class.
class Vector: ... def __iter__(self): return iter(self.__coordinates) ... if __name__ == "__main__": v = Vector([1, 2, 3]) for i in v: print(i) #1.0 #2.0 #3.0 t = tuple(v) print(t) #(1.0, 2.0, 3.0)
In order to have the capability to get the number of coordinates within our vector by assigning our objects to the
len() function, the _
__len__ _method must be added to our class.
from array import array import reprlib class Vector: ... def __len__(self): return len(self.__coordinates) ... if __name__ == "__main__": v = Vector([1, 2, 3, 4]) print(len(v)) #4
Without adapting our class to support comparison, the_
== _operator applied to two vector objects compare their references. To alter this behaviour, the
__eq__ method must be implemented. For our example, two vectors are equal if and only if they have the same coordinates and with the same order.
from array import array import reprlib class Vector: ... def __len__(self): return len(self.__coordinates) def __iter__(self): return iter(self.__coordinates) def __eq__(self, other): if len(self) == len(other): for i, j in zip(self, other): if i != j: return False return True else: return False ... if __name__ == "__main__": v = Vector([0, 1, 2, 3, 4]) v1 = Vector((1, 2, 3, 4, 5)) v2 = Vector(range(5)) print(v == v2) #True print(v == v1) #False
Let us take some time to analyze the new
__eq__ method:
It uses the
__len__ method by calling the
len()function.
It uses the
__iter__ method by passing
self and other parameters to the zip function, which accepts an iterable as parameters.
For this example, we use the
__abs__ method to return the Euclidean norm of a vector defined by the below expression:
from array import array from math import sqrt import reprlib class Vector: ... def __abs__(self): return sqrt(sum((x**2 for x in self))) ... if __name__ == "__main__": v = Vector([0, 1, 2, 3, 4]) a = abs(v) print(a) #5.477225575051661
With our current implementation of the
Vector class, we have the below behaviour when we evaluate the boolean value of our vectors.
if __name__ == "__main__": v = Vector([]) print(bool(v)) #False v1 = Vector([1, 2, 3]) print(bool(v1)) #True
Without the
__bool__method in our class, the call to the
bool() function refers to the
__len__ method. If the length is equal to 0, then the object evaluates to false — otherwise, it evaluates to true.
Let us change this behaviour by implementing a method to have it return True if the vector Euclidean norm is different from 0 and false otherwise.
from array import array from math import sqrt import reprlib class Vector: ... def __abs__(self): return sqrt(sum((x**2 for x in self))) def __bool__(self): return bool(abs(self)) ... if __name__ == "__main__": v = Vector([]) print(bool(v)) #False v1 = Vector([1, 2, 3]) print(bool(v1)) #True v2 = Vector([0, 0]) print(bool(v2)) # False
The slicing in Python aims to get a subset from an initial set by indicating the index of an element to retrieve it or by indicating a slice.
A slice of an object returns another object of the same type. The method
__getitem__ is the one to be updated to give our vector objects this ability.
from array import array from math import sqrt import reprlib class Vector: ... def __getitem__(self, item): if isinstance(item, int): return self.__coordinates[item] elif isinstance(item, slice): return self.__class__(self.__coordinates[item]) else: raise IndexError("{} indexes must be integers".format(type(self).__name__)) ... if __name__ == "__main__": v = Vector([1, 2, 3, 4]) v1 = v[1] print(v1) # 2.0 v2 = v[0:3] print(type(v2)) # <class '__main__.Vector'> print(v2) # (1.0, 2.0, 3.0)
Note that by using a slice, the returned object is also a
Vector object.
The Dunder methods that we implemented in this tutorial are not the only ones that can be used. Others, like
__bytes__,
__hash__,
__getatrr__, and
___format__ can be used to alter the behaviour of the user defined objects. These methods are not all to be implemented every time you define a new class, it depends on your needs and this is the beauty of the Python data model.
Thank for reading !. | https://morioh.com/p/c586907b19c6 | CC-MAIN-2020-40 | refinedweb | 1,299 | 63.9 |
OpenStack SDK Post-Summit Update
This is a long post about the OpenStack SDK. It even has a Table of Contents.
Current Project Status
The OpenStack SDK is quickly heading toward being usable for application developers. Leading up to the OpenStack Summit we had a reasonably complete Resource layer and had been working on building out a higher-level interface, as exposed through the Connection class. As of now, first cuts of a high-level interface have implementations in Gerrit for most of the official programs, and we're working to iterate on what we have in there right now before expanding further. We also had an impromptu design session on Thursday to cover a couple of things we'll need to work through.
Project Architecture
At the lowest level, the authentication, session, and transport pieces have been rounded out and we've been building on them for a while now. These were some of the first building blocks, and having a reasonably common approach that multiple service libraries could build on is one of the project goals.
Session objects are constructed atop Authenticators and Transports. They get tokens from the Authenticator to insert into your headers, get endpoints to build up complete URLs, and make HTTP requests on the Transport, which itself is built on top of requests and handles all things inbound and outbound from the REST APIs.
Poorly drawn version of what we're doing
On top of that lies the Resource layer, a base class implemented in openstack/resource.py, which aims to be a 1-1 representation of the requests or responses the REST APIs are dealing with. For example, the Server class in openstack/compute/v2/server.py inherits from Resource and maps to the inputs and outputs of the compute service's /servers endpoint. That Server object contains attributes of type openstack.resource.prop, which is a class that maps server-communicated values, such as mapping the accessIPv4 response body value to an attribute called access_ipv4. This serves two purposes: one is that it's a place we can bring consistency to the library when it comes to naming, and two is that props have a type argument that allows for minimal client-side validation on request values.
Resource objects are slightly raw to work with directly. They require you to maintain your own session (it's the first argument of Resource methods), and they typically only support our thin wrappers around HTTP verbs. Server.create will take your session and then make a POST request populated with the props you set on your object.
On top of the Resource layer is the Connection class, which forms our high-level layer. Connection objects, from openstack/connection.py, tie together our core pieces - authentication and transport within a session - and expose namespaces that allow you to work with OpenStack services from one place. This high-level layer is implemented via Proxy classes inside of each service's versioned namespace, in their _proxy.py module.
Right now many of these Proxy implementations are up for review in Gerrit, but openstack.compute.list_flavors is currently available in master. It builds on the openstack.compute.v2.flavor Resource, simply calling its list method inside list_flavors and passing on the Session that compute was initialized with.
What the high-level looks like
There are a bunch of example scripts in the works in the Gerrit reviews, but some of what we're working on looks like the following.
Create a container and object in object storage:
from openstack import connection conn = connection.Connection(auth_url="", user_name="me", password="secret", ...) cnt = conn.object_store.create_container("my_container") ob = conn.object_store.create_object(container=cnt, name="my_obj", data="Hello, world!")
Create a server with a keypair:
from openstack import connection conn = connection.Connection(auth_url="", user_name="me", password="secret", ...) args = { "name": "my_server", "flavorRef": "big", "imageRef": "asdf-1234-qwer-5678", "key_name": "my_ssh_key", } server = conn.compute.create_server(**args) servers = conn.compute.list_servers()
Where we're going
General momentum has carried us into this Connection/Proxy layer, where we have initial revisions of a number of services, and by default, we'll just keep pushing on this layer. I expect we'll iterate on how we want this layer to look, hopefully with input from people outside of the regular contributors. Outside of that, results from conversations at the Summit will drive a couple of topics.
We need to figure out our story when it comes to versioning APIs at the high level. Resource classes are under versioned namespaces, and even the Proxy classes that implement the high level are within the same versioned namespace, but we currently expose high level objects through the Connection without a version, as seen in the above examples.
On one hand, it's pretty nice to not have to think about versions for APIs that only have a v1, but that won't last. Along with that, we're working in a dynamic language on growing APIs. Not pinning to a version of the interface is going to result in a world of pain for users.
We need to think about going even higher level than what we have now. Monty Taylor's shade library came up both at his "User Experience, SDKs" design session, as well as during the impromptu OpenStack SDK session we had, and once we get more of the Connection level figured out, we're going to look at how we can tackle compound operations.
Docs, docs, docs. Terry Howe has been putting in a lot of work on building up documentation, and now that we're moving along more smoothly up the stack, I think we'll soon hit the point where code changes will require doc changes.
I'm also working up a "Getting Started" guide for the project, as we have some people interested in contributing to the project. Thursday's python-swiftclient session ended in that team being interested in shifting their efforts to this SDK, so we need to make sure they can easily get going and help improve the client and tool landscape.
For the time being, doc builds will appear at
PyPI releases. Terry put together a version of the package that could reproduce the examples we showed in our talk on Monday, comprised of master plus a couple of his in-flight reviews for compute and network and mine for object store. As we progress and want to try things out, and to enable people to try along with us, we'll probably keep cutting more releases under 0.1.:
pip install python-openstacksdk
Keep in mind this is absolutely a work-in-progress, and API stability isn't yet a thing, so check it out and let us know what you think, but don't build your business on it.
Need to get back into some of the administrivia that we've been avoiding recently in the name of expanding the Resource layer. The wiki page could use a refresh to reflect where we're at and what's going on. We need to start using more blueprints and the issue tracker, especially as more people become interested in joining the project. We were able to work without most of that when it was just a couple of us wanting to get this off the ground, but we need to make better use of the tools around us.
Overall, the SDK is coming along nicely. We had some good talks at the Summit and got a lot of interest from people and projects, so the coming months should be another good period of growth for us.
Summit Presentation with Terry Howe
On Monday, Terry Howe and I presented "Getting Started with the OpenStack SDK", a 40 minute talk on why we're doing this, how we're doing it, and where the project is going. Both of us had presented at conferences before, but never jointly, so it was an interesting first time experience, and it seemed to work well. The general gist is that I covered the most of the "why" and "where", and Terry covered most of the "how".
The first half focuses on three key ideas that brought this SDK to being: fragmentation, duplication, and inconsistency in the library and tooling landscape around OpenStack. I dove into each of those areas with examples of why they're an issue, such as how many different clients there are, and how different it can be to work with them. From there I covered some of the goals we have while trying to improve those issues, such as building solid foundations and providing consistent user interfaces.
The second half focuses on showing where we're at and what can be done. Terry took a working example that creates a network, sets up various security group rules, starts up a server, attaches a floating IP, and results in a running Jenkins server. After that, he dove into some of the internals, showing how session, transport, and authenticator work together, and explaining the resource and proxy levels.
After we were done, we had a good 10 minutes of questions, and about another 20 minutes of conversation in the hall afterward. A university professor came up to me to say he wants to use the SDK with his students, which was awesome to hear.
SDK Conversations at the Summit
In the Marketplace
While spending most of Monday through Wednesday in the Rackspace booth in the marketplace, I talked to a lot of people about the SDK project. It's fun to give away t-shirts and raffle off prizes at conferences, but I'm there to talk with people about the experiences they have with Rackspace, OpenStack, and other platforms, and to advocate for the first two.
I've gotten the SDK "elevator pitch" down fairly well by now for when people turn around and ask what I do. The good thing is that no one thought it was a bad idea! People were excited over various parts of it, mostly between reducing the fragmentation by offering all of the libraries from one package, and a lot were excited about coming up with more consistent interfaces across services.
Overall it was a lot of small conversations that ended with a smile that we're both doing fun stuff and it's all getting better.
Impromptu Design Session
Although we didn't have a session on the schedule, we created one of our own Thursday morning in the Le Meridien lobby. Dean Troyer, Jamie Lennox, Terry Howe, Ken Perkins, and myself gathered to talk for about 40 minutes on where we're going. We talked about two main points: an even higher level than we currently provide, and our multi-version story.
Even Higher Level
Currently we provide an abstraction that gets a user to the point where they can call, e.g., object_store.list_containers(), and they'll receive a list of containers. We've taken care of the lower-level plumbing bits like authentication, session, and transport within the Connection class, which exposes the object_store namespace, containing the higher-level view on top of the account and container resource level.
It was mentioned during this session, and during Monty Taylor's user experience session, that Monty is working on a project called Shade. Shade flies at a higher level where you say give me a working server and it does what's necessary to make that happen. The tool aims to abstract away provider differences in order to complete the task, such as how Rackspace gives you a VM with a publicly accessible IP and HP VMs need to be added to a network and have a floating IP attached to them.
"Give me a server" is a pretty common first step for newcomers, so that's an obvious starting place. "Upload this directory to object storage" is another. If you have others, we'd love to know, and we'd love help to implement them. With where we're working right now, we're not yet on to provider specific plugins, so high-level multistep tasks on vanilla OpenStack are what we're looking for.
Multiversion APIs
At the high level within openstack.Connection, we're not currently making any attempt to expose multiple versions of a service's API. We support authenticating via either a v2 or v3 Keystone, and we support multiple versions of APIs at the resource layer, but you end up with high-level access to a set of unversioned service APIs. On one hand, that makes it fairly nice to work with methods on openstack.object_store, especially since there is currently only a v1 API, but should that actually have a v1 somewhere in there?
A point was brought up that we pin versions in other places, such as our requirements. We couldn't have an unversioned dependency in requirements.txt and expect our code to continue working against its APIs forever. When they go from v1 to v2, things will be different and potentially affect what we've coded against. If you've written against the v1 API, you probably want to stick with it until you've written and tested against the v2 API. As much as the unversioned namespace may feel more friendly, it's eventually going to cause pain.
The "Improving python-swiftclient" Design Session
On Thursday, John Dickinson held a session on how to improve the python-swiftclient project. I'm not a contributor there, but was interested to see what they were planning to do and maybe chime in on getting a few more eyes on the SDK, especially since I threw together a high-level Swift view.
Within the first few minutes, the bulleted list that the group had come up with looked a lot like the bulleted lists we came up with to start the SDK project. They have a lot of work they want to be doing, and we're already on our way doing much of the same. Dean Troyer beat me to the punch of grabbing a mic and asking if it's possibile to put some of these efforts behind both OpenStackClient and the SDK.
Dean and I then gave very quick talks on where OSC and SDK fit in to what they were aiming to accomplish. From there, the conversation shifted towards 'Can we accomplish this over there?' and 'Do we want to accomplish this over there?' The answer to both turned out to be 'yes'.
Coming out of this meeting, we're going to have to quickly bulk up our documentation of the lower-level parts so we can bring these folks up to speed, as one of the first topics was their HTTPConnection class, and the second was from Jamie Lennox on using Keystone's sessions.
We're also going to need to bulk up on a "Getting Started" guide for new contributors coming out of this session and a few other talks I've had. Welcome everyone!
If you got this far, wow. See me at a conference some time for a high five. | http://blog.briancurtin.com/posts/openstack-sdk-post-summit-update.html | CC-MAIN-2017-09 | refinedweb | 2,514 | 58.92 |
Learn more about these different git repos.
Other Git URLs
hello,Can pagure be used with dist-git? How to configure pagure?Does anyone have the same problem
What do you mean by this? Pagure can be deployed as a Dist-Git system, yes. That's how src.fedoraproject.org and git.centos.org work today.
I am trying to install and use pagure,i installed "pagure pagure-milters pagure-ev pagure-webhook",modify the Folder containing to the git repos
GIT_FOLDER = os.path.join(
'/srv/git/',
'rpms'
)
then i config fedpkg just like
lookaside =
lookaside_cgi =
lookasidehash = sha512
gitbaseurl = ssh://git@pagure/srv/git/%(repo)s.git
anongiturl = git://pagure/%(repo)s
branchre = f\d$|f\d\d$|el\d$|olpc\d$|rawhide$
Is it something I misconfigured
i want to deployed pagure as a Dist-Git system, How should i configure pagure
So, Dist-Git configuration requires setup of the pagure-dist-git plugin, and configuration of the lookaside system.
Alas, I'm not actually sure how that is set up. @pingou and @praiskup might know, though?
Hello, I was misled by this explanation
“
I found the correct configuration method in the pagure-dist-git repository“
import os
import sys
dir_path = os.path.dirname(os.path.realpath(file))
from pagure_distgit import plugin
PLUGINS = [plugin.DISTGIT_NS]
dir_path = os.path.dirname(os.path.realpath(file))
from pagure_distgit import plugin
PLUGINS = [plugin.DISTGIT_NS]
i restart the serveice about pagure, then i create a project, but there is no difference betwen zhe new project and the old ,should i add other configurations?Is it correct to use the command "git clone...; git add...; git cpmmit...; git push...",or to use other commands to call this plugin,How can I use this plugin in pagure? Thanks a lot
@pingou and @praiskup
I tried to configure fedpkg, but I can only use the "fedpkg clone" command. When I use the "fedpkg import" command, it prompts "Could not execute import_srpm: Fail to upload files. Server returns status 404" and generates empty ”sources“ document
to comment on this ticket. | https://pagure.io/pagure/issue/5236 | CC-MAIN-2022-21 | refinedweb | 342 | 58.99 |
Before we get going on this month's task -- creating the client-side networking and building the server for our Interchange discussion forum -- let's quickly review the work we've completed on our forum at this point.
In last month's edition, we discussed the specifications of the Interchange client -- the applet parameters, the GUI, the modes of operation, and the user's identity -- and worked through the
ForumLauncher and
Forum classes to implement them.
ForumLauncher displays the icon that stores the client app, while
Forum presents the GUI and contains the majority of the app's logic. If you haven't already done so, click on the icon at the top of this article to see the discussion forum applet in motion.
I told you we were only going to do a brief review. If you're feeling a bit behind the eight ball on these topics, I recommend that you review last month's installment and brush up before running headlong in to this month's article.
Oh, and if it's Java code you want, you'll find the full source for the forum here.
Developing lines of communication
As we saw last month, our system is going to follow a simple communications protocol to read and post topics. This simple protocol moves thread listings from server to client and articles from client to server (and vice versa). The networking classes (
ForumComm,
ForumConnectionHandler, and
ForumServer), which we'll cover in detail shortly, will implement the following actions:
- "Load all threads" retrieves all current threads from the server.
- "Load all articles in thread T" retrieves all the articles in thread T from the server.
- "Post article A to thread T" posts article A to the server under thread T.
The client drives the server's actions with requests. The client will likely make very few requests over the course of its life; users typically spend the majority of session time reading articles and composing posts. For this reason, as well as the fact that requests are all discreet in nature (as opposed to transmission of real-time data, for example), each client request is serviced in a single connection, which is then closed down. The other alternative -- leaving a connection open between each client and the server for some specified period of time -- would waste precious server resources.
Cutting through the static: Client-side communications
The communications code for the client is bundled up nicely in one class,
ForumComm. This class, shown in Listing 1, is a communications library that implements client-side networking calls.
import java.net.*; import java.util.*; import java.io.*; import ForumLauncher; public class ForumComm { // port for server to listen for Forum clients static final int FORUM_PORT = 5000; // possible client requests static final int LOAD_ALL_THREADS = 1; static final int LOAD_THREAD_ARTICLES = 2; static final int POST_ARTICLE = 3; ForumLauncher gp; public ForumComm (ForumLauncher gparent) { gp = gparent; }
The top section of the code defines the TCP port used for the Interchange service, as well as the protocol requests that the client can send to the server. These definitions have identical counterpart definitions in the server's
ForumConnectionHandler class. The constructor does nothing except provide a pointer to the
ForumLauncher applet to allow access to its
getCodeBase() method.
Each instance of
ForumComm provides three methods:
loadAllThreads(),
loadThreadArticles(), and
postArticle(), shown in Listings 2, 3, and 4. Let's take a look at each of these methods in more detail.
Hashtable loadAllThreads() { Hashtable a = new Hashtable(); String thread = ""; (LOAD_ALL_THREADS); dOut.flush(); thread = dIn.readUTF(); while (!thread.equals ("")) { a.put (thread, new Vector()); thread = dIn.readUTF(); } } catch (IOException ex) { System.out.println ("Error reading threads from server."); } return a; }
The
loadAllThreads() method returns a
Hashtable, which contains the server's discussion topics as keys, each with an empty
Vector as its value.
The method first creates an empty
Hashtable and tries to set up a
Socket to the server's port
FORUM_PORT. If the attempt succeeds,
loadAllThreads gets the
InputStream and
OutputStream associated with the
Socket and attaches a
DataInputStream and
DataOutputStream to the respective buffered I/O streams. Buffered I/O streams increase the efficiency of the networking calls.
The method next writes the
LOAD_ALL_THREADS request to the
DataOutputStream and flushes the stream to make sure that the request is sent immediately. When the server gets the
LOAD_ALL_THREADS request, it replies with the discussion threads, ending with an empty string.
loadAllThreads() then does a
dIn.readUTF() call for each thread the server sends, exiting when it finds an empty string. Each thread is sent in UTF format. UTF is the best way to communicate textual data between Java clients and servers because it preserves Unicode characters, allowing for the use of a wide range of non-ASCII character sets. Unfortunately, if the server is running under JDK 1.0.2, a bug will prevent it from handling anything but ASCII, Greek, Hebrew, and Arabic characters. (All is not lost, though: The release of JDK 1.1 should be available by the time you read this.)
When a new thread is read from the server, it is put into
Hashtable a as a key for a new empty
Vector. When all threads have been loaded, the method exits, returning the
Hashtable containing the threads. If the
loadAllThreads() method fails, the client prints out an error message to the system's Java console and returns an empty
Hashtable.
Now let's examine the
loadThreadArticles() method.
Vector loadThreadArticles (String t) { Vector ta = new Vector(); String art = ""; try { URL serverURL = gp.getCodeBase(); Socket server = new Socket (serverURL.getHost(), FORUM_PORT); DataInputStream dIn = new DataInputStream (in); DataOutputStream dOut = new DataOutputStream (out); InputStream in = new BufferedInputStream (server.getInputStream()); OutputStream out = new BufferedOutputStream (server.getOutputStream()); dOut.writeInt (LOAD_THREAD_ARTICLES); dOut.writeUTF (t); dOut.flush(); art = dIn.readUTF(); while (!art.equals ("")) { ta.addElement (art); art = dIn.readUTF(); } } catch (IOException ex) { System.out.println ("Error reading articles for thread '" + t + "' from server."); } return ta; }
The
loadThreadArticles() method creates
Vector ta. This
Vector stores all articles in the discussion thread as elements. The method then sets up the same data streams that
loadAllThreads() uses.
loadThreadArticles() writes the
LOAD_THREAD_ARTICLES request to
dOut, follows that with a write of the selected thread
t to
dOut, and flushes the stream to make sure that the request goes out immediately. The server replies with a series of articles.
The method then attempts to read each article as it is sent by the server and add it to
ta. When this operation is complete, the method returns
ta and exits. If the method fails, the client prints out an error message to the system's Java console and returns an empty
Vector.
Finally, we come to
boolean postArticle (String art, String t) { (POST_ARTICLE); dOut.writeUTF (t); dOut.writeUTF (art); dOut.flush(); return true; } catch (IOException ex) { System.out.println ("Error posting article in thread '" + t + "' to server."); return false; } } }
This method attempts to post an article to the thread
t. It performs the same setup as the previous methods and follows that step with a
POST_ARTICLE request to the server. The method then sends the post thread
t and the article to the server and flushes the stream.
If these operations are successful, the method exits returning true. If the operations fail for some reason, such as a bad network connection, the method exits returning false.
Each
ForumComm method provides its own local copy of the streams that it uses. This prevents collisions if more than one method is called simultaneously. Such a problem might occur in a multithreaded version of the client, so I included it in case you choose to optimize the system in such a way. (A little planning in the beginning sure can help you out when you decide to enhance later on!)
That's it for the client side of things. Let's now turn our attention to the server portion of our threaded discussion forum. I'll provide a bit of background before we get into the actual classes that implement the server side of our system.
Note: For tips on using the server, including installation, configuration, and starting and stopping, see the the sidebar Setting up the Interchange forum server.
Our first step is dealing with the connection request made by the client.
Class ForumConnectionHandler
Each time
ForumServer (we'll get to the
ForumServer class later on in the article) accepts a new connection, the connection is handed off to a new instance of
ForumConnectionHandler for processing.
ForumConnectionHandler, which is shown in Listing 5, talks directly to
ForumComm.
import java.net.*; import java.util.*; import java.io.*; public class ForumConnectionHandler extends Thread { // possible client requests static final int LOAD_ALL_THREADS = 1; static final int LOAD_THREAD_ARTICLES = 2; static final int POST_ARTICLE = 3; long id; Socket client; long memoryLimit; Hashtable articles; InputStream in; OutputStream out; DataInputStream dIn; DataOutputStream dOut; public ForumConnectionHandler (long i, Socket c, long m, Hashtable ar, ThreadGroup h) { super (h, "Forum Connection Handler " + i); id = i; client = c; memoryLimit = m; articles = ar; }
The
ForumConnectionHandler class extends
Thread so that each instance will map to a new thread and therefore handle its connection separately. Language features like this make writing a server in Java a real treat.
The setup code declares the requests that it may receive from the client, as well as the instance variables to be used in this connection. The constructor sets these to the appropriate values as specified by parameters from the caller.
Each
ForumConnectionHandler has an id number, which is the number of the last connection plus one, receives pointers to the connection's
Socket, a memory limit restriction, and a pointer to the articles database.
ThreadGroup h is passed in, and the superclass (
Thread) constructor is called with
ThreadGroup h and a text description as arguments. This technique puts all handler threads in the same group so that they can be stopped easily when the server shuts down.
public void run() { try { in = new BufferedInputSteam (client.getInputStream()); out = new BufferedOutputStream (client.getOutputStream()); dIn = new DataInputStream (in); dOut = new DataOutputStream (out); String t, type = ""; int request = -1; Vector threadArts; request = dIn.readInt(); switch (request) {
The
run() method of
ForumConnectionHandler does all the work involved in processing the connection associated with it. The first order of business is to instantiate the streams (which are buffered for efficiency) to be used for the connection. After that, a
String is set up for the thread name and a message to be printed, and a
Vector is defined to hold articles in a discussion thread. An
int called
request is assigned the value of the request read from the client. As soon as the request comes in, a
switch statement routes it to the proper
case statement.
Let's take a look at the possible requests.
case LOAD_ALL_THREADS: Enumeration en = articles.keys(); while (en.hasMoreElements()) dOut.writeUTF ((String) en.nextElement()); dOut.writeUTF(""); dOut.flush(); type = "LOAD_ALL_THREADS"; break; | http://www.javaworld.com/article/2077635/java-concurrency/write-your-own-threaded-discussion-forum--the-communications-and-server-components-.html | CC-MAIN-2017-17 | refinedweb | 1,809 | 54.73 |
This is XFrames - an XML application for composing documents together. URI: Copyright ©2002-2005 W3C (MIT, ERCIM, Keio), All Rights Reserved. Editor: Masayasu Ishikawa (mimasa@w3.org) Revision: $Id: xframes-1.xsd,v 1.9 2005/10/05 23:56:45 mimasa Exp $ Permission to use, copy, modify and distribute this XML Schema for XFrames and its accompanying documentation for any purpose and without fee is hereby granted in perpetuity, provided that the above copyright notice and this paragraph appear in all copies. The copyright holders make no representation about the suitability of this XML Schema for any purpose. It is provided "as is" without expressed or implied warranty. Get access to the XML namespace Datatypes media type, as per [RFC2045] A comma-separated list of media descriptors as described by [CSS2]. The default is all. An [XMLNS]-qualified name. An Internationalized Resource Identifier Reference, as defined by [IRI]. Common attributes | http://www.w3.org/People/mimasa/test/schemas/SCHEMA/xframes-1.xsd | crawl-002 | refinedweb | 151 | 50.33 |
Ticks are the markers denoting data points on axes. Matplotlib has so far - in all our previous examples - automatically taken over the task of spacing points on the axis.Matplotlib's default tick locators and formatters are designed to be generally sufficient in many common situations. Position and labels of ticks can be explicitly mentioned to suit specific requirements.
The xticks() and yticks() function takes a list object as argument. The elements in the list denote the positions on corresponding action where ticks will be displayed.
ax.set_xticks([2,4,6,8,10])
This method will mark the data points at the given positions with ticks.
Similarly, labels corresponding to tick marks can be set by set_xlabels() and set_ylabels() functions respectively.
ax.set_xlabels([‘two’, ‘four’,’six’, ‘eight’, ‘ten’])
This will display the text labels below the markers on the x axis.
Following example demonstrates the use of ticks and labels.
import matplotlib.pyplot as plt import numpy as np import math x = np.arange(0, math.pi*2, 0.05) fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes y = np.sin(x) ax.plot(x, y) ax.set_xlabel(‘angle’) ax.set_title('sine') ax.set_xticks([0,2,4,6]) ax.set_xticklabels(['zero','two','four','six']) ax.set_yticks([-1,0,1]) plt.show() | https://www.tutorialspoint.com/matplotlib/matplotlib_setting_ticks_and_tick_labels.htm | CC-MAIN-2021-17 | refinedweb | 219 | 51.34 |
The following lab was originally assigned but skipped over because we were off for MLK day. I would still like to do it but am just not following what I should be doing. Help?
In this lab you are going to extend the code you wrote in you first lab. You are going to add to the class Coin a variable value that represents the value of the coin in cents (e.g. can be 1, 5, 10, or 25). This value, together with the bias, should be specified as the constructor to the class Coin.
You are also going to create a new class Change that stores an array of Coin objects. The array of coins, which can be of arbitrary size, should be given as input parameter to the constructor of the class Change. Add to the class Change a toString() method that prints the coins in the change. An example return value of the method is “dime nickel tails quarter tails”, which means that the 3rd and 5th coin are tails and their values cannot be seen. Add a method flip(int i) to the class Change that flips the ith coin. Test the class Change by creating a third class called Game. In the main method of this class, create a random change of size 10 coins.
Show the change to the user and print the sum of the coins that are heads. Then allow the user to flip all the coin if they want to do so. If the user decides to flip the coins, show the new values for the coins and the new sum for the head coins. The goal of the game is to the get the highest possible sum for the value of the coins that are heads.
Here is my original lab 01. Where do I go from here?
import javax.swing.JOptionPane; //Import class for use of JOptionPane windows public class Coin { private static double face; private static double bias = .5; final static int HEAD = 1; final int TAILS =2; private static int value; public Coin(double b, int v) { bias = b; value = v; } public static void main(String[] args) //Main method { int counter = 0; //Local variable to control for loop boolean data; //Local variable to evaluate outcome of flip method // int input; //Local variable to store JOP input // Solicits user to run the program input = JOptionPane.showConfirmDialog(null, "Would you like to change the bias and run " + "the program?", "Coin", JOptionPane.YES_NO_OPTION); // if (input == 1) //Evaluates user choice as integer value { //JOP closes program based on choice of no option JOptionPane.showMessageDialog(null, "The Coin Program Exits. Good Bye!", "Program Terminates", JOptionPane.CANCEL_OPTION); System.exit(0); //Program terminates } // while (input == 0) //While loop begins based on yes { setBias(); //Calls method, passing no arguments // for (int i = 0; i <10; i++) //For loop to toss the coin a set # of times { flip(); //Calls method, passing no arguments data = isHead(); //Calls method, assigning to variable result of return // if (data == true) //If statement to evaluate is toss is a HEAD { counter ++; //If toss is HEAD, increment counter variable } } //JOP tells user the result of the program at current bias JOptionPane.showMessageDialog(null, " You tossed HEADS " + counter + " times", "Results", JOptionPane.PLAIN_MESSAGE); // counter = 0; //Resets counter variable //JOP prompts user to run the program again input = JOptionPane.showConfirmDialog(null, "Would you like to change the bias and run " + "the program?", "Coin", JOptionPane.YES_NO_OPTION); } //Given a choice of no by user, program terminates JOptionPane.showMessageDialog(null, "The Coin Program Exits. Good Bye!", "Program Terminates", JOptionPane.CANCEL_OPTION); System.exit(0); //Program terminates }//End of Main // public static void flip() //Method to control tossing of coin { double calc = 0; //Local variable to create toss value // calc = 2 * (Math.random()) * (1 - bias); //Assigns to calc variable the result of math // //formula to generate a random value of toss if (calc <= .5) //If statement evaluates generated number { face = 1; //Assigns to face data field an integer value for comparison } else face = 2; //Assigns to face data field an integer value for comparison }//End of Method // public static boolean isHead() //Method for comparing generated number to constant for HEAD { if (face == HEAD) //If statement compares generated number to constant for HEAD { return true; //Returns true to main method if values are equal } else return false; //Returns false to main method if values are false }//End of Method // public static void setBias() //Method to allow user to change the bias value to HEAD { String biasInput; //Local variable to accept user input from JOP //Prompts user to change bias value biasInput = JOptionPane.showInputDialog(null, "Input your desired bias value", "Bias Change", JOptionPane.INFORMATION_MESSAGE); bias = Double.parseDouble(biasInput); //Parses bias value from string to double type }//End of Method }//End of Class
BTW, I have class Thur. so I would love to finish this before. | https://www.daniweb.com/programming/software-development/threads/255390/in-the-fog | CC-MAIN-2017-26 | refinedweb | 804 | 68.3 |
When I saw the article Spell Check, Hyphenation, and Thesaurus for .NET with C# and VB Samples - Part 1: Single Threading which was published just a short time ago, I was really pleased to find that there is a DLL that does what I've been trying to do on my own for years. In this article, I'll describe a textbox object which incorporates some of the features which were presented in that article as well as describe some other projects which I've been working on that resemble the Hunspell product, including a tool which helps English speaking readers to decipher the Latin language.
I will point you to the above mentioned article for a clearer explanation on how Hunspell is used in your programs, but would like to describe the neat features which this textbox class has garnered with its use. Instantiating the textbox is done like any other dynamically generated object:
classTextBoxSpellChecker txtBox = new classTextBoxSpellChecker();
And then you add it to your form like:
public formRhymes()
{
InitializeComponent();
Controls.Add(txtBox);
Which I'm sure most programmers are familiar with, so there's really nothing to it. As it is, it has two features, and though both are in English, downloading the language files you want and changing the names of the variables in the class is up to you:
const string en_us_DicFilename = "en_us.dic";
const string en_us_AffFilename = "en_us.aff";
const string th_en_us_idx = "th_en_us_new.idx";
const string the_en_us_dat = "th_en_us_new.dat";
Again, for the URLs and information on where to find these files, refer to the above mentioned article. And, note that these files must be present in the working directory of the project in which you plan to use this textbox and the Hunspell tools.
This textbox has two main features which can be toggled on or off:
bool bolShowSpellChecker = true;
bool bolShowThesaurus = true;
public bool spellChecker
{
get { return bolShowSpellChecker; }
set { bolShowSpellChecker = value; }
}
public bool thesaurus
{
get { return bolShowThesaurus; }
set { bolShowThesaurus = value; }
}
When the Thesaurus is on, and the bolShowThesaurus variable is set to true, the textbox will recognize correctly spelled words and automatically generate a list of synonyms for the word close to the cursor, displaying them on a listbox, at the position where the user is currently typing. If this listbox is clicked with the mouse by the user, then the word previously typed is replaced by the synonymous word selected. This listbox will disappear as soon as the user starts typing another word, even if no selection was used.
bolShowThesaurus
true
When the spellchecker is on, this same list-box appears near the cursor with a list of alternate spellings which the user may have meant to write. The user can tell the difference between the thesaurus listbox and the spell-checker list-box by the red/green background color which distinguishes one from the other: red for the spell-checker setting off an alarm that the word may be misspelled, and green for the thesaurus if your grammar could use improvement.
And that is about the end of that.
... For the rest of this article, I'll discuss some search trees which don't stand up to Hunspell but were fun to implement. So if all you're looking for is a textbox with a spell-checker under the hood: there it is.
I've been studying Latin on my own for a couple of years now using a Wheelock's Latin textbook, and and I'm still not very good at it, though I've improved considerably with the help of a program I've written that declines and conjugates Latin nouns, adjectives, and verbs. It took me about three months to type a Latin/English Dictionary into a separate database program into my computer. The dictionary database itself is no great marvel of engineering, just three long months of tedious duldrum typing and typing and typing. It consists entirely of text files. Each text file has fields entered sequentially, like 'filename' (a redundant and useless field that caused more problems than it solved), 'heading', 'alt-heading', 'links', and 'main text'. The file's 'heading' field holds the Latin word like 'amo, -are', the latin word for 'love', while the 'main text' contains the definition of the word. Simple stuff. The way the files hold together is with the 'links' field which has a list of filenames that are connected to this one and to which this file points. Using a RecordViewer, each file's content is displayed and the headings of files to which it points via the 'links' field are included on the screen for the user to click and jump to, displaying the files as they are selected.
RecordViewer
So after I put this database together, I had to organize these files using a search algorithm. There are 24,000 files in the Latin Dictionary, not all of these are Latin word-entries as many are files I call header-files which make the whole network of files easier to navigate; the size of this network of text-files makes publishing this project prohibitive, and the difficulty in finding any entry despite the ease of navigation makes using the project, like you would any other dictionary, far too slow to be worth the while. So I needed a search-engine to make that easier.
Nothing simpler: sample each file in the database in a random order, parse each file's text content out, and insert each word into a binary tree using the words as search keys to go down the tree. When you've found the word already entered into your tree, use a front-end insertion to point to the linked list for that particular word which holds the filenames of all the files in the network that contain this particular spelling.
I don't really want to elaborate on spell trees too much here, but since I mention this and it is a really simple way of making a search-engine, and I think everyone should know how to make one even if they already use SQL or any other database software development kit, I'll ramble on a bit about this at my leisure.
A binary tree starts with a root node. Each node has pointers to a left child node and right child node. Initially, these pointers are set to 'null'. Each node also contains something called a 'search key' which is used to navigate down the tree. To find the node you're looking for, you start at the root-node and compare your search word to the search key of that node if the comparison is 'greater' (after in alphabetical order, in the case of lettered search keys), then you fall down to the 'right child node', and alternately, you go left if it is 'lesser', or you're already there if it is neither. You can go right for greater or left for lesser, or either way is fine, whatever way you like. Just remember that with binary trees: you have to be consistent.
In the case of the search engine, you also need another bit of information in each node: a pointer to a linked list. Linked lists are also very useful tools, and if you've never seen these, then I'll have to tell you something about them. Linked lists are similar to binary trees except you might look at them as vines that have no branches. There's a head and a tail, and each node must have a 'next' pointer to another node even if this pointer is set to 'null'. You point to the first one, it points to the next one, and the next one points to the following one, and so on until you reach the last one which points to 'null'. There are many variations of this, like doubly linked lists, which also have a 'previous' pointer, and these items in the list all point to each other. Or, circular linked lists which don't actually end because the last one points to the first one and it goes around and around.
Getting back to the search engine and putting this bit of thought behind us: each node in the search tree has a pointer to its own linked list. You go down the tree until you find the word you're looking for, retrieve the pointer to the linked list for that word, then move along the linked-list reading off all the names of files in the file-network which contain the word you're looking for. There are an infinite number of applications for this.
OK, so now we (actually 'I' have a Latin dictionary) have a Latin dictionary and a quick way to find what we're looking for. With two separate sets of files for heading search and complete search, to look for words that are either exclusively in the word's heading (like you would a normal desktop dictionary) or a complete search for words that are contained inside the word's definition.
But that doesn't conjugate and decline.
You wouldn't believe the trouble I had in getting that working properly. First of all, I'm a Latin-newbie myself, so I don't actually speak Latin too good, and in the process of learning the language, I was putting together new features for my project to do these conjugations and declensions for every chapter as I learned them, and the final result after two years was a damned mess. But the most difficult part of the whole thing wasn't getting it to actually do the declening, because that's actually the easy part. No, the hardest part was teaching the project to figure out what kind of word it was looking at. So during the first two years of this learning and adding a new patch to my Latin-quilt of knowledge, I went through a constant trial and error of figuring out how to write the code that would consistently resolve the type of word the reader was currently looking at. And so, when I came to rewriting the project and translating it from Visual Basic 2005 to C# 2008, I used the old VB project to copy the entire database, the entire Latin/English dictionary, onto a second directory, and include in each file the type of words I knew them to be, because there was no way I was going to go through another two years of never knowing whether the thing was working properly once I already had it working.
Bored yet? How would I say that in Latin? non gaudes? I don't know...
Once that was done, actually writing the code to decline the different types of words was actually pretty easy. And, this time around, I knew what I was doing, so I organized the whole C# version much better, and am quite pleased with it.
So that's not the end of it. Once I had it declining and conjugating for all those different types of words, I wanted a Latin look-up table that I could use to figure out what a word is no matter how it is spelled. You see, Latin is a funny language. Let's say I've found the word 'sustulim' in a text I'm translating, and I don't recognize it or remember what it means. I could try to find 'sustulimus' in my desktop dictionary, but find nothing between 'sustollo' and 'susum', and that doesn't help me because it is listed under the 'T's for 'tollo, tollere, sustuli, sublatum'. You see 'sustulimus' is the first person plural perfect active indicative of the verb 'tollo, -ere' as you can plainly see in the dictionary heading (OK, if you don't know anything about Latin, you have no idea what I'm talking about; which is really my point: if you don't know, you'll never find it).
What I needed to do from here was go through every word entry in the dictionary, generate every possible spelling for all of them, and insert them into a look-up table in a fashion similar to what I described for the search engine, keeping track of the means by which that particular spelling is generated.
And that's what I did.
In this image, you can see my LatinExercises project which uses this class_Latin_C#.dll. In action, here is my favorite Latin_LUT. To get these windows up, I first had the cursor on the word 'nautae' in the sentence 'Filium nautae Romani in agris videmus' (we see the son of the sailor in the field) and then pressed the F3 key on my keyboard. The first window to appear is my LUT-Results window, which lists the four different ways in which that particular spelling of the dictionary's word entry 'nauta, -ae' can be reached. The noun is masculine, and there are two singular forms (Genitive and Dative) and two plural forms (Nominative and Vocative). Since they're all different ways to spell the same word, pressing F3 again on any one of these will result in the window on the right which shows us the complete declension along with an Option tab that holds the word's definition. Pressing F1 from the LUT-Results window pops up the last window you see, which gives the user the word's definition (you can see the links underlined at the bottom which the user can navigate along through) as well as two comboboxes which will generate the declension(s) for nouns and adjectives or the several dozen conjugations for verbs.
I've included here the LUT's search tree user-defined-type as well as the Linked-List's UDT because they're a bit particular.
public struct udtLUTRecord_Bin
{
// main
public int deaccentLeft;
public int deaccentRight;
public string strDeaccentWord;
// sub
public int left;
public int right;
public string strWord;
public int LL;
public bool flag;
}
public struct udtLUTRecord_LL
{
public string filename;
public int next;
public classLatin_C.classLatin_C.enuTypeSolutions typeSolution;
public classLatin_C.classLatin_C.enuCase case_;
public classLatin_C.classLatin_C.enuPerson person;
public classLatin_C.classLatin_C.enuNumber number;
}
The Latin language uses short and long vowels. These are differentiated in the beginner Latin-Reader textbooks using a 'macron' which is a bar that goes over the long characters. Since many forms of any given word may have several variations of macrons here and there, and the difference between one macron spelling and another may alter the phrase altogether, keeping these in order is kind of important. So the search through the LUT's binary tree first uses the 'deaccented' word (word with the macrons removed) until the correct spelling is found. Then, at this point, there is another sub-tree tied to each node of the binary tree, and this 'sub-tree' keeps the macrons (described using accented vowel characters), and a search is made for that particular macron configuration. In showing the results on the LUT-Results form, this sub-tree is traversed in order, and each node of the sub-tree has its own linked list of solutions which are put to the screen.
I think I've gone on long enough about this project; as it is of little use to anyone but myself, I was reluctant to write an article about it (especially since I can't offer you the code or the database because I don't know the copyright for the dictionary I've typed into my computer, and the LUT files themselves are 1GB in size decompressed), but this way, you got a textbox, and if you were having trouble sleeping, this should have done the trick.
When this worked out so well, I went ahead and did the same thing in French and English. French was much easier than Latin for me, because I actually speak the language and found the Bescherelle the best French-cookbook I could find. So aside from the pronominal verbs and the passive forms, my French dictionary (entirely French and 1600 pages long!) has been turned into a French LUT. There's this French chick whom I think might be interested in seeing that one. I did the English one (yes, I have a lot of time on my hands), and now I have all three together in a separate project which uses the clipboard to take commands while I write in whatever application or on the Internet using my computer.
Right now, if I highlight and 'copy' the word 'enabledictionary' using the CTRL-C combination on my keyboard, then whatever I copy to the clipboard becomes a word I've asked this application to look up. It is like I'm saying: give me the definition for this word. But all I've done is copy it to the clipboard. This slows my system down slightly, because it tests the clipboard every second of the day, but I do a lot of writing and I can always say 'killdictionary' whenever I choose. My three LUTs are in there, and I have a selection of several dictionaries to choose from, so given my penchant for writing, it has become a powerful tool which I use quite often.
My latest typing project is a rhyming dictionary, but I won't bother you with that.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
General News Suggestion Question Bug Answer Joke Rant Admin
Man throws away trove of Bitcoin worth $7.5 million | http://www.codeproject.com/Articles/44563/Spell-weller-but-grammar-s-up-to-you | CC-MAIN-2013-48 | refinedweb | 2,925 | 60.99 |
Every day, we generate a huge volume of varied data, which in its raw state, does nothing but occupy space. However, if the data is organised and manipulated, meaningful and valuable conclusions can be drawn from it. Therefore, the hunt is always on for tools that assist in the process of handling data. Python Pandas is one such tool.
Data science is the process of deriving insights from a huge and diverse set of data by organising, processing and analysing it. This practice is prevalent in many different domains like e-commerce, healthcare and energy. The programming requirement of data science demands a very versatile yet flexible language, the code for which is simple to write but which can handle highly complex mathematical processing. Python is most suited for such requirements as it is robust enough to handle complex scenarios with minimal code and less confusion. It has a very large collection of libraries that serve as special-purpose analysis tools.
Pandas is an open source Python library used for high-performance data manipulation and data analysis, using its powerful data structures. It is suitable for many different types of data, including table data with heterogeneous columns, such as SQL tables; or Excel data, ordered and unordered time series data, matrix data with row and column labels, or other forms of observation/statistical data sets. Python with Pandas is used in various academic and commercial domains, including economics, statistics, advertising, Web analytics, and more.
This article briefly covers data processing with Python and connectivity to relational databases using Python. It includes queries that allow data manipulations within the Pythonic framework provided by the Python SQL toolkit, SQLAlchemy, which is said to be the best Python database abstraction tool as it provides an accessible way to query, build and write to the SQLite database.
Python: Processing CSV data
Reading data from CSV (comma separated values) is a fundamental necessity in data science. CSV is a simple file format used to store tabular data, such as a spreadsheet or database. The standard CSV format is defined by row and column data. Each row is terminated by a new line to begin the next row. Also, within the row, each column is separated by a comma.
For working with CSV files in Python, import an inbuilt module called csv as follows:
import csv # reading csv file with open(:/Users/Neethu/data.csv’,’r’)as x: # creating a csv reader object data = csv.reader(x) # extracting each data row one by one for row in data: print(row) # print the total number of rows print(“Total no. of rows: %d” %(data.line_num))
The output is given below:
[‘id’, ‘name’, ‘salary’, ‘start_date’, ‘dept’] [‘1’, ‘John’, ‘34000’, ‘05-08-17’, ‘CSE’] [‘2’, ‘Manu’, ‘25600’, ‘23-09-18’, ‘ECE’] [‘3’, ‘Isha’, ‘32500’, ‘05-12-18’, ‘IT’] [‘4’, ‘Ryan’, ‘35678’, ‘01-05-19’, ‘CSE’] [‘5’, ‘Neha’, ‘32100’, ‘27-03-17’, ‘ME’] [‘6’, ‘Pooja’, ‘31000’, ‘03-05-19’, ‘IT’] [‘7’, ‘Sam’, ‘26000’, ‘30-07-17’, ‘ECE’] [‘8’, ‘Sanju’, ‘35908’, ‘27-06-18’, ‘CSE’] Total no. of rows: 9
The Pandas open source library also provides features using which we can read the CSV file in full as well as in parts for only a selected group of columns and rows. Reading the CSV into a Pandas DataFrame is very quick and easy:
import pandas as pd x = pd.read_csv(‘C:/Users/Neethu/data.csv’) print(x)
The read_csv function of the Pandas library reads the files from the OS by using the proper path to the file. An additional column starting with zero as an index is created by the function.
Reading specific rows and columns: The code print (x[0:5][‘salary’]) will slice the result for the first rows. The read_csv function can also be used to read some specific columns along with the multi-axes indexing method called .loc().
print (x.loc[2:5,[‘salary’,’name’]]) salary name 2 32500 Isha 3 35678 Ryan 4 32100 Neha 5 31000 Pooja
Python: Processing JSON data
A JSON file stores data as text in a human-readable format. JSON stands for JavaScript Object Notation. Pandas can read JSON files using the read_json function. Python is supported with the JSON library. We can convert lists and dictionaries to JSON, and strings to lists and dictionaries. JSON data looks much like a dictionary would in Python, with the keys and values stored.
import json data = ‘’’{ “apple” : “red”, “banana” : “yellow”, “mango” : “green”}’’’ # load the JSON into ‘a’ variable. a = json.loads(data) print(a) #Write the Data into a JSON File with open (‘abc.json’, ‘w’) as f: json.dump(a, f)
The output is shown below:
{‘apple’: ‘red’, ‘banana’: ‘yellow’, ‘mango’: ‘green’} Using pandas, read a json file using the function pd.read_json() import pandas as pd newdata = pd.read_json(‘C:/Users/Neethu/inputdata.json’) print (newdata)
Python: Processing XLSX data
The Pandas library provides features using which we can read the Excel file in full as well as in parts, for only a selected group of data. We can also read an Excel file with multiple sheets in it. We use the read_excel function to read the data from it. Pandas defaults to storing data in DataFrames. We then store this DataFrame into a variable.
import pandas as pd df=pd.read_excel(‘C:/Users/Neethu/product.xlsx’) print(df) Product Price 0 Computer 24700 1 Tablet 12250 2 iPhone 14000 3 Laptop 25000
For reading specific columns and rows, use the following code:
import pandas as pd data = pd.read_excel(‘C:/Users/Neethu/input.xlsx’) # Use the multi-axes indexing function print (data.loc[[1,3],[‘salary’,’name’]])
For reading multiple Excel files, type the following code:
import pandas as pd with pd.ExcelFile(‘C:/Users/Neethu/input.xlsx’) as xls: df1 = pd.read_excel(xls, ‘Sheet1’) df2 = pd.read_excel(xls, ‘Sheet2’) print(“****Result Sheet 1****”) print (df1[0:5][‘salary’]) print(“”) print(“***Result Sheet 2****”) print (df2[0:5][‘zipcode’]) ****Result Sheet 1**** 0 10000 1 20000 2 23456 3 12345 4 23412 Name: salary, dtype: int64 ***Result Sheet 2**** 0 89765 1 12345 2 23456 3 34567 4 45678 Name: zipcode, dtype: int64
Python and relational databases
SQLite, a database included with Python, creates a single file for all the data in a database. It is built into Python but is only built to be accessed by a single connection at a time. SQLite is self-contained, serverless, very fast and lightweight; and the entire database is stored in a single disk file.
SQLite can be integrated with Python using a Python module called sqlite3. You do not need to install this module separately because it comes bundled with Python version 2.5.x onwards.
The Python SQL toolkit, SQLAlchemy, which is said to be the best Python database abstraction tool, provides an accessible and intuitive way to query, build and write to SQLite, MySQL and Postgresql databases. SQLAlchemy is an open source toolkit, object-relational mapper and an additional library for implementing database connectivity, which provides full SQL language functionality to be used in Python.
To use a database, create a connection object, which will represent the database:
import sqlite3 connection = sqlite3.connect(“College.db”) // created a database with the name “College”
After creating an empty database, add one or more tables to it using the create table sql syntax. To send a command to ‘SQL’ or SQLite , we need to create a cursor object by calling the cursor() method of connection, as shown below:
cursor = connection.cursor()
Now, declare a create table with a triple quoted string in Python, as follows:
cmd = “””CREATE TABLE employee (ssn INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), salary number, birth_date DATE);”””
Now we have a database with a table but no data included. To populate the table, execute the INSERT command to SQLite.
cursor.execute(cmd) cmd = “””INSERT INTO employee VALUES (“12398”, “John”, “Danny”, “80000”, “1961-10-25”);”””
To save the changes, call the commit method and finally close the connection, as shown below:
connection.commit() connection.close()
Now the code looks like what’s shown below:
import sqlite3 connection = sqlite3.connect("College.db") cursor = connection.cursor() cmd = """CREATE TABLE employee (ssn INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), salary number, birth_date DATE);""" cursor.execute(cmd) cmd = """INSERT INTO employee VALUES (“12398”, "John", "Danny", "80000", "1961-10-25");""" cmd = """INSERT INTO employee VALUES (“98765”, "Ryan", "Harry", "65000", "1965-03-04");""" connection.commit() connection.close()
The Python code to query our employee table is as follows:
import sqlite3 connection = sqlite3.connect("College.db") cursor = connection.cursor() cursor.execute("SELECT * FROM employee") print("The employee details : “) #We use .fetchmany() to load optimal no of rows and overcome memory issues in case of large datasets #In case the number of rows in the table is small, you can use the fetchall() method to fetch all rows from the database table result = cursor.fetchall() for res in result: print(res) cursor.execute("SELECT * FROM employee") print("\nfetch one record:") #fetchone() returns one record as a tuple or it fetches the records one by one, If there are no more records then it returns None res_one = cursor.fetchone() print(res_one)
The output returned is:
The employee details: (‘12398’, ‘John’, ‘Danny’, ‘80000’, ‘1961-10-25’) (‘98765’, ‘Ryan’, ‘Harry’, ‘65000’, ‘1965-03-04’) fetch one record: (‘12398’, ‘John’, ‘Danny’, ‘80000’, ‘1961-10-25’)
A brief summary of the code
- First, we connected to the database by creating a new connection object.
- Second, from the connection object, we instantiated a new cursor object.
- Third, we executed a query that selects all rows from the books table.
- Fourth, we called the fetchone() method to fetch the next row in the result set.
- Fifth, we closed both cursor and connection objects by invoking the close() method of the corresponding object.
Reading relational tables
We pick Sqlite3 as our relational database as it is very lightweight and easy to use. To begin with, create a database engine and then connect to it using the to_sql function of the SQLAlchemy library.
The relational table is created by using the to_sql function from a DataFrame already created, by reading a CSV file. Then we use the read_sql_query function to read the results of an SQL query directly into a Pandas DataFrame, as shown below:
from sqlalchemy import create_engine import pandas as pd data = pd.read_csv(‘C:/Users/Neethu/input.csv’) # To connect we use create_engine(): Create the db engine # we will use an in-memory-only SQLite database engine = create_engine(‘sqlite:///:memory:’) #The return value of create_engine() is an instance of Engine, and it represents the core interface to the database # Store the dataframe as a table data.to_sql(‘data_table’, engine) # Query 1 on the relational table res1 = pd.read_sql_query(‘SELECT * FROM data_table’, engine) print(‘Result 1’, res1) print(‘’) # Query 2 on the relational table will display the sum of salaries & count of employees by grouping department-wise res2 = pd.read_sql_query(‘SELECT dept,sum(salary) as salary_sum,count(*) empcount FROM data_table group by dept’, engine) print(‘Result 2’, res2) Output Result 1 will display the entire table Result 2 dept salary_sum empcount 0 CSE 105586 3 1 ECE 51600 2 2 IT 63500 2 3 ME 32100 1
Insertion and deletion on the database
Inserting and updating rows into an existing SQLite database table, apart from sending queries, is probably the most common database operation. Sqlite3 has a straightforward way to inject dynamic values without relying on string formatting.
Any ‘?’ value in the query will be replaced by a value in values. The first ‘?’ will be replaced by the first item in values, the second by the second item, and so on. This works for any type of query. This creates an SQLite parametrised query, which avoids SQL injection issues.
Finally, we can delete the rows in a database using the execute method, as shown below:
from sqlalchemy import create_engine from pandas.io import sql import pandas as pd data = pd.read_csv(‘C:/Users/Neethu/inputdata.csv’) engine = create_engine(‘sqlite:///:memory:’) # Store the Data in a relational table data.to_sql(‘data_table’, engine) # Insert another row sql.execute(‘INSERT INTO data_table VALUES(?,?,?,?,?,?)’, engine, params=[(‘id’,9,’Rose’,34320,’20-03-18’,’IT’)]) #Update the salary for IT dept sql.execute(‘UPDATE data_table set salary=(?) where dept=(?) ‘, engine, params=[(‘89000’,’ECE’)]) #Delete row where name=Neha sql.execute(‘Delete from data_table where name = (?) ‘, engine, params=[(‘Neha’)]) # Read from the relational table res = pd.read_sql_query(‘SELECT ID,Dept,Name,Salary,start_date FROM data_table’, engine) print(res)
For the output, see Figure 2.
To recapitulate, Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages, numerous libraries and built-in features. This makes it easy to tackle the needs of data science. Pandas is a powerful data analysis tool kit, which is intended to be a high-level building block for actual data analysis in Python. SQLite is the most widely deployed SQL database engine in the world, which can be integrated with Python using a Python module called Sqlite3. Compared to writing the traditional raw SQL statements using Sqlite3, SQLAlchemy’s code is more object-oriented, and easier to read and maintain. | https://opensourceforu.com/2019/08/working-with-data-analysis-and-relational-databases-in-python/ | CC-MAIN-2019-39 | refinedweb | 2,200 | 53 |
The Classical Coulomb Gas as a Mixed Integer Quadratic Program
The.
import cvxpy as cvx import numpy as np #grid size N = 5 # charge variables q = cvx.Variable( N*N ,integer=True) # build our grid x = np.linspace(0,1,N) y = np.linspace(0,1,N) X, Y = np.meshgrid(x,y, indexing='ij') x1 = X.reshape(N,N,1,1) y1 = Y.reshape(N,N,1,1) x2 = X.reshape(1,1,N,N) y2 = Y.reshape(1,1,N,N) eps = 0.1 / N #regularization factor for self energy. convenience mostly V = 1. / ((x1-x2)**2 + (y1-y2)**2 + eps**2)** ( 1 / 2) V = V.reshape( (N*N,N*N) ) U_external = 100 * Y.flatten() # a constant electric field in the Y direction energy = cvx.quad_form(q,V) + U_external*q # charge conservation constraint prob = cvx.Problem(cvx.Minimize(energy),[cvx.sum(q)==0]) res = prob.solve(verbose=True) print(q.value.reshape((N,N))) #plotting junk import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, q.value.reshape((N,N))) plt.show()
A plot of charge in a constant external electric field. $ N log(N) $
import cvxpy as cvx import numpy as np import scipy.fftpack # import fft, ifft def swizzle(x,y): assert(x.size == y.size) N = x.size s = np.exp(-2.j * np.pi * np.arange(N) / N) #print(s) #ret = cvx.hstack( [x + s*y, x - s*y]) #print(ret.shape) return cvx.hstack( [x - s*y, x + s*y]) def fft(x): N = x.size #assert(2**int(log2(N)) == N) # power of 2 if N == 1: return x, [] else: y = cvx.reshape(x,(N//2,2)) c = [] even, ce = fft(y[:,0]) c += ce odd, co = fft(y[:,1]) c += co z = cvx.Variable(N, complex=True) c += [z == swizzle(even,odd)] return z, c N = 256 x = cvx.Variable(N, complex=True) z, c = fft(x) v = np.zeros(N) #np.ones(N) #np.random.rand(N) v[0]= 1 c += [x == v] prob = cvx.Problem( cvx.Minimize(1), c) #print(prob.get_problem_data(cvx.OSQP)) res = prob.solve(verbose=True) #print(x.value) print(z.value) print(scipy.fftpack.fft(v)) print(scipy.fftpack.fft(v) - z.value)
The equivalent dense DFT:
x = cvx.Variable(N, complex=True) fred = cvx.Variable(N, complex=True) c = [fred == np.exp(-2.j * np.pi * np.arange(N).reshape((N,1)) * np.arange(N).reshape((1,N)) / N) * x] prob = cvx.Problem( cvx.Minimize(1), c) print(prob.get_problem_data(cvx.OSQP)). | https://www.philipzucker.com/the-classical-coulomb-gas-as-a-mixed-integer-quadratic-program/ | CC-MAIN-2021-39 | refinedweb | 432 | 57.33 |
When i run the below program from the console , it is showing the data it receives from serial input in the console.
But , I want to display the data in the webpage , maybe in a box. How can I do it?
The python program is
#!python
import time
import cgi
from serial import Serial
import subprocess
ser = Serial('COM4', 115200, timeout=1)
print("connected to: " + ser.portstr)
while True:
# Read a line and convert it from b'xxx\r\n' to xxx
line = ser.readline().decode('utf-8')[:-2]
if line: # If it isn't a blank line
print(line)
if line == '520':
subprocess.call(["xte", "key Up"])
elif line == '620':
subprocess.call(["xte", "key Down"])
elif line == '110':
break
ser.close()
The data is continuously generated as it receives from the sensor. I need to show the last available data | http://www.tutorialspoint.com/forums/viewtopic.php?p=2848 | CC-MAIN-2014-42 | refinedweb | 141 | 68.67 |
(Fully aware of the potential problems of quoting out of context and of the limitation of using analogies...) On 10/2/06, Scott David Daniels <Scott.Daniels at acm.org> wrote: > I'm catching up here, and just read the namespaces thing -- > How about "namespaces are like card catalogs in a closed stack library." Analogies to library card catalogs would need to be explained to today's kids (including those 1st year university students). If any analogy is going to be used, I think it should be a future looking one - or, at least a "time-neutral" one. I'd prefer something like namespace <--> book variable/function/object name <--> character's name in a book two or more name for same object <--> character's name and alias(es) or nickname(s) That being said.... I believe that, just like for learning another "human" language, nothing beats the "immersion paradigm" to learn any language, including programming ones. Just introduce the vocabulary, use it in context with plenty of different examples and, soon enough, the students will construct their own "mental map" without referring to a translation in a different language. André Roberge | https://mail.python.org/pipermail/edu-sig/2006-October/007327.html | CC-MAIN-2016-40 | refinedweb | 191 | 59.94 |
public static void main( String arg[] )
In the above statement, can I use an
int array in place of the
String array? What happens if I don’t put anything in the parenthesis, i.e if I use an empty parenthesis?
When you compile the code with the changes that you mentioned, it will compile successfully. When you try to run, JVM checks for the main method with String array as arguments. Since there is no main method with String array as argument, your code will not execute successfully and it throws NoSuchMethodError.
###
No, I think you can’t use int array instead of String array.because the argument
int is used by the operating system to pass an integer value specifying the number of command-line arguments entered by the user. so you must follow the following pattern.
public static void main(String[] args) public static void main(String args[])
###
I’m not sure what you mean by
Int array but no, you cannot. The method signature needs to exactly match
public static void main(String[] args). The only thing you can change is the name of the argument. The name of the method, the argument type, the visibility (public vs private, etc) is what the runtime uses to find the method itself. If it does not conform to that signature, it is not an entry point method and consequently will not be called when your application starts up.
However, it should be noted that what you’re suggesting will compile without issue. The problems will not arise until you attempt to run the application.
###
The code will compile but not run.
The reason for the string[] is so that people can pass parameters through the command line.
###
The compiler will accept but the runtime will give you a NoSuchMethodError
###
If you’re looking to get numbers instead of strings, use this approach
public static void main(String[] args) { int[] numbers = new int[args.length]; for(int i = 0; i < args.length; i++) numbers[i] = Integer.parseInt(args[i]); }
Handling exceptions is exercise for the reader.
Other answers explain quite well your other issues of the ‘why’.
###
The main method is the entry point for the java application. If you look at the java language specification, it specifically states:
The method main must be declared
public, static, and void. It must
accept a single argument that is an
array of strings. This method can be
declared as either
public static void main(String[] args)
or
public static void main(String... args)
The String[] array passed in contains any command line arguments that have been passed in by whatever launched the application. You can then read them and convert them as you need.
###
No,it produces a runtime error like
Main method not found in class test, please define the main method as:
public static void main(String[] args)
JAVA is more specific about main method signature, It considers your method as a general method in a class.
###
If you want to convert String args from main static method to int then do the following:
public class StringToIntArgs { public static void main(String[] args) { // TODO Auto-generated method stub int[] anIntArray = new int[args.length]; for(int i = 0; i < args.length; ++i) { anIntArray[i] = Integer.valueOf(args[i]); System.out.println(((Object)anIntArray[i]).getClass().getName()); } } }
Now compile and run the java code with arguments like below:
C:\Users\smith\Documents\programming\java>javac StringToIntArgs.java C:\Users\smith\Documents\programming\java>java StringToIntArgs 1 2 3 4 5 java.lang.Integer java.lang.Integer java.lang.Integer java.lang.Integer java.lang.Integer | https://exceptionshub.com/java-basic-question.html | CC-MAIN-2022-05 | refinedweb | 605 | 55.74 |
-2013 01:58 PM
Hi,
I wrote a streaming based design in Vivado HLS 2013.2. It passes the testbench in C-Simulation, however it fails the testbench when doing RTL Co-simulation.
The design has an input and an output stream. When called it consumes 10 values from the input streams and then replicates these 10 inputs fife times for the output stream. The code can be downloaded at the bottowm.
stream_issue_hls.cpp - defines the streaming function
#include "stream_issue_hls.hpp" void stream_issue(hls::stream<uint32_t> &input, hls::stream<uint32_t> &output) { hls::stream<uint32_t> fifo_10; #pragma HLS stream depth=10 variable=fifo_10 uint32_t cnt = 0; for (int i = 0; i < 50; ++i) { #pragma HLS PIPELINE II=1 uint32_t index; if (cnt < 10) index = input.read(); else index = fifo_10.read(); output.write(index); fifo_10.write(index); if (cnt < 10) ++cnt; } }
stream_issue_hls.hpp - header file
#ifndef __STREAM_ISSUE_HLS_HPP__ #define __STREAM_ISSUE_HLS_HPP__ #include <ap_int.h> #include <hls_stream.h> void stream_issue(hls::stream<uint32_t> &input, hls::stream<uint32_t> &output); #endif
stream_issue_tb.cpp - testbench
#include "stream_issue_hls.hpp" #include <iostream> int main() { // setup input data hls::stream<uint32_t> input; for (int i = 0; i < 10; ++i) { input.write(i); } hls::stream<uint32_t> output; // run kernel stream_issue(input, output); // verify output bool error = false; for (int i = 0; i < 50; ++i) { uint32_t hw = output.read(); uint32_t sw = i % 10; if (hw != sw) { std::cout << "ERROR: " << i << " - " << hw << " != "<< sw << std::endl; error = true; } } if (output.size() != 0) { std::cout << "ERROR: out.size() = " << output.size() << " != 0"<< std::endl; error = true; } std::cout << "done." << std::endl; return error; }
C-Simulation output:
WARNING: Hls::stream 'hls::stream<unsigned int>.3' contains leftover data, which may result in RTL simulation hanging. done.
SystemC Co-simulation output:
@I [SIM-11] Starting SystemC simulation ... SystemC 2.2.0 --- Jun 13 2013 15:35:04 Copyright (c) 1996-2006 by all Contributors ALL RIGHTS RESERVED Note: VCD trace timescale unit is set by user to 1.000000e-12 sec. SystemC: simulation stopped by user. @I [SIM-316] Starting C post checking ... ERROR: 10 - 9 != 0 ERROR: 11 - 9 != 1 ERROR: 12 - 9 != 2 ... ERROR: 47 - 9 != 7 ERROR: 48 - 9 != 8 done. @E [SIM-303] C TB post check failed, nonzero return value '1' . @E [SIM-4] *** C/RTL co-simulation finished: FAIL ***
Why does the RTL compiler not understand what I want to do? Can somebody reproduce this issue? Is this a compiler bug? Or am I simply using the language wrongly? I am completely lost here.
Best regards,
Christ-28-2013 12:26-29-2013 11:45 AM
Thanks for looking into this, Debraj.
Do I understand you correctly, using internal hls:streams is not supported for now and a workaround is to use arrays? In that case we would have come to the same conclusion.
I would really favour streams here, because:
Using arrays has some challenges:
All these details are nicely handled by hls::stream. Can you please make sure that this will be fixed for the next Vivado HLS version?
Best regards,
Christian
PS: I am using arrays for now, however it makes the code harder to understand. I am currently considering writing my own class that wrapps all the index handling for arrays with similar interfaces as hls::stream.
08-30-2013 04:24 AM - edited 09-06-2013 05:58 AM
Hello Christian,
a few notes:
1-
in this code, VHLS may not always optimize array reads / writes as working out that when I is smaller than 10, then there are no issues isn't trivial:
if (i < 10) {
// captures the first 10
buffer [i] = input.read();
}
output.write(buffer[i%10]);
I'd suggest further changes to the code like something along those lines:
if (i < 10) {
// captures the first 10
int t = input.read();
buffer [i] = t;
output.write(t);
} else { // EDITED 6th September: added else { because there is an output.write() call above - without else then 2 writes would be performed in sequence - this is incorrect.
output.write(buffer[i%10]);
} // EDITED 6th September: added closing }
With the above, you should be able to *not* use the dependence directive.
(for anyone reading this : using the directive dependence = false is to be used with caution! ALWAYS)
2-
the reminder operand can also be recoded with something like this, as the original index is sequential - that's actually what you would do when writing RTL.
ap_uint<4> buf_index = 0;
...
buf_index = (9==buf_index) ? 0 : buf_index + 1;
3-
I'm not sure on the root cause but there's an issue somewhere (your code / VHLS?) .. the example shipped with VHLS 2013.2 works... C:\Xilinx\Vivado_HLS\2013.2\examples\design\hls_stream
If you look into the RTL generated (eg syn\vhdl\stream_issue.vhd), the instantiated fifo “fifo_10_V_fifo_10_V_fifo_U” has the input port if_din connected to a signal stuck to 0.
We will have someone look into this further.
The previous workaround (or any other and their variations) can be used.
I hope this helps!
08-30-2013 04:37 AM
09-05-2013 11:51 PM
09-06-2013 09:44 AM
Dear herver, debrajr,
I am very happy to hear that this will be fixed in the upcomming release.
Thank you for your note 2 and 3. Note 2 helped me to simplify my code and 3 will help me to verify that a second bug is caused by the same issue.
1-
Regarding note 1, I am still not fully convinced, that it is always possible to avoid the dependency directive. I am aware that using this pragma is very dangerous for pipelined designs. How would you remove it in the following design? Without the pragma, it has an initiation interval of 2 instead of the requested 1. When added, it works fine, even in SystemC/Verilog/VHDL Co-Simulation. (source files attached below)
void stream_issue(hls::stream<uint32_t> &input, hls::stream<uint32_t> &output) { uint32_t buffer[10]; // Uncomment the following line to meet initiation interval of 1 // #pragma HLS dependence variable=buffer false ap_uint<4> buf_index = 0; for (int i = 0; i < 50; ++i) { #pragma HLS PIPELINE II=1 int t; if (i < 10) { // captures the first 10 t = input.read(); buffer[buf_index] = t; } else { // increment by one //WARNING: if the following transformation takes more than 10 cycles // this design won't work. To test this, replace it with // "t = exp(buffer[buf_index]);" which takes 23 cycles. t = buffer[buf_index] + 1; buffer[buf_index] = t; } output.write(t); buf_index = (buf_index == 9) ? 0 : buf_index + 1; } }
2-
I now see that arrays are also pipelined if necessary. I am impressed, I didn't expected this. Very nice!
That means when my original design failed timing (during place & route) it was probably an error in the timing estimation of Vivado HLS. I remeber HLS didn't reported a timing violation. I assume that is why it put to much logic into one timing slot. Is there some simple way to introduce a pipeline stage into a path? I looked at the pragmas, but couln't find anything. In my case I did it manually, by pipelining the read with a new variable that is assigned in the last loop iteration. (read[buf_index] = complex_xor(t_delay); t_delay = read[buf_index_next]; ++buf_index; ++buf_index_next; ...wrap_index...)
Regards,
Christian
09-10-2013 04:37 AM - edited 09-10-2013 04:41 AM
Hello Christian,
I haven't looked into your new zip, so my comments are to take with a pinch of salt :)
for your 1-,
I'm not sure about the behavior you describe since those 2 lines
t = buffer[buf_index] + 1;
buffer[buf_index] = t;
imply a read-modify-write on buffer[buf_index] location (probably implemented with BRAM): this is a latency of 2 so II == 2 seems logical -> so the dependence set to false may trigger the array access pipelining that you're talking about ? if cosim still works then i believe the results are correct - until proven otherwise.
also be aware that the directive will change the scheduling / resources used.
something you may also look into is the partionning of the buffer into registers (directive partion -dim = 0) so that there is no dependency.
for your 2-
there's a reg class template described in UG902 (should be in the includes header files, somewhere too) that will do exactly this: add a register on the signal that you want, and this will have the effect of changing the generated RTL as the register adds latency- i'm sure you'll appreciate that this is constraining more the design and the tool's freedom : you may end-up with suboptimal results (so again, use with caution otherwise you may not like the results).
if you can confirm more around the topic on 1- that would be nice and good learning :)
09-10-2013 06:28 AM
Hello herver,
1-
In my example the array is mapped to a BRAM. BRAMs have up to 2 independent (read/write) ports (ug473), that means HLS can schedule a read and write for the same cycle.
Let us look at the lines:
t = buffer[buf_index] + 1;
buffer[buf_index] = t;
I think you are right, the two lines will probably have a latency of 1 or 2 cycles. However they can be fully pipelined with an initiation intervall (II) of 1. The timing could for a 2 cycle look latency like:
--- 1 cycle ---
r_1 = buffer.read(0)
--- 2 cycle ---
r_2 = buffer.read(1)
t_2 = r_1 + 1
--- 3 cycle ---
r_3 = buffer.read(2)
t_3 = r_2 + 1
buffer.write(0, t_2)
--- 4 cycle ---
r_4 = buffer.read(3)
t_4 = r_3 + 1
buffer.write(1, t_3)
...
At the end it will wrap. So reading is always ahead of writing in the same clock cycle by 2 addresses. And as mentioned before the read and write to different addresses can be schedules, as we have two memory ports. When our buffer has the size of 10, there is no carry data dependency as long as the read is not ahead of the write by more than 9 clock cycles. However HLS is not detecting this, so we have to force him to just don't care and make sure that this is the case our self. (see the exp example abover for what happens when this is violated)
Maybe the HLS tool could be improved to analyze address dependent array depenencies. A similar analysis as it might be done for (-dim = 0), I haven't checked if the problem exists there. But I explicitely don't want to map my array to registers design, as the buffer has about 512 elements with 32 bits.
2-
I found the register in the section "User Defined Registers in C++" on page 253. Thanks for the pointer, that's much less destruvtive than my current solution. I will have a look at it in my next timing issue.
Regards,
Christian | https://forums.xilinx.com/t5/Vivado-High-Level-Synthesis-HLS/HLS-Compiler-Bug-Streaming-Based-Design/m-p/349833 | CC-MAIN-2019-22 | refinedweb | 1,798 | 64.81 |
0
using System; class abc { public static void fun() { Console.WriteLine("Function"); } public static void Main(string[] args) { ThreadStart ts=new ThreadStart(fun()); Console.WriteLine("Main begins"); Thread t=new Thread(ts); t.Start(); Console.WriteLine("Main ends"); } }
Output showing
Main Begins
Main ends
Function.
My Question
The thread has been started and then the "Main ends" message has been written. When the t.Start() method is invoked the function func() is to be called, but it is completing the work of main function and only returning back to function, why is it so.
If i use static in the function the output is
Main Begins
Function
Main Ends
Why is this change happening. What is the order of execution of threads. Kinly help me. | https://www.daniweb.com/programming/software-development/threads/140640/thread-execution-doubt | CC-MAIN-2018-13 | refinedweb | 125 | 77.03 |
1 - Introduction
This is part one in a multi-part article series on building custom administrative user interfaces using the Dynamicweb UI controls such as the RibbonBar.
As you may have seen in the article series on building custom modules, pages you create to manage your custom modules in the administrative section of Dynamicweb are 100% ASP.NET. This means you can use whatever technique you prefer to create these pages. To build up the user interface you can use standard ASP.NET controls such as the Button, the GridView and the ListView. Alternatively, you can use third-party controls such as those from DevExpress or Telerik. However, to create modules that look and feel like Dynamicweb modules, you can also make use of the many built-in controls that ship with Dynamicweb. This helps your end-users familiarize themselves much quicker with your modules as they already know how to interact with many of the UI controls from working with the standard Dynamicweb modules.
Note: if you haven’t read the series on building custom modules, you’re encouraged to do that now. The sample application used in this new series builds on top of the sample application that I built and explained in detail in the previous series.
In this introductory article, I’ll give you a brief overview of many of the controls that you have at your disposal. In later parts in this series I’ll show you how to use these controls in your own code. You can find a complete list of the available controls and their API documentation on the Engage web site at.
The RibbonBar control
The RibbonBar is probably the most familiar control. It looks and behaves just as the Ribbon interface used in Microsoft Office 2007 and Office 2010 applications such as Word, Excel and Outlook. Figure 1 shows the RibbonBar in Dynamicweb when editing a page.
Figure 1 (Click to enlarge)
The control itself can contain a number of other controls, including:
- RibbonBarTab – Used to create different tabs, such as the Content and Tools tabs in Figure 1.
- RibbonBarGroup – Used to created different groups on a tab, such as the Insert and Content groups in Figure 1.
- Within the RibbonBarGroup you can use a number of other controls such as:
- RibbonBarButton
- RibbonBarCheckbox
- RibbonBarPanel
- RibbonBarRadioButton
- RibbonBarScrollable
Many of the controls within the RibbonBarGroup expose client and server side events that you can handle. Part 2 through 4 of this series will show you how to use the RibbonBar and other controls to create good-looking and intuitive user interfaces for your Dynamicweb custom modules.
The List control
The List control enables you to present content in a list. Examples in the Dynamicweb UI include the list of paragraphs when editing a page, the products in the Product Catalog module and the list of orders. The control supports features such as sorting, paging, selection and filtering. Figure 2 shows an example of the List control displaying the articles in my custom DvkArticles module:
Figure 2 (Click to enlarge)
In part 5 of this series you see how to build this list to display the articles in the system.
The Dialog control
The Dialog control enables you to create a floating and draggable pop-up window. The control can contain other markup such as HTML and ASP.NET server controls, enabling you to completely customize its looks and content. The control has properties to change the appearance of various buttons (OK, Close, Cancel etc.) and their client side functions that get executed when you click them. In Figure 3 you see an example of a Dialog that in turn contains an Editor control.
Figure 3 (Click to enlarge)
In part 3 in this series you see how to use the Dialog control.
The InfoBar control
The InfoBar control is used to display short messages to the user. It typically appears at the top of the page so it draws the user’s attention. Out of the box it supports three types of messages (Error, Information and Warning), each represented by an icon. You can also assign a custom image. Figure 4 shows the InfoBar using the three default built-in message types and a custom one, featuring the logo of De Vier Koeden:
Figure 4
I’ll show you how to use the InfoBar control in a reusable way in part 5 of this series.
The GroupBox control
The GroupBox control renders as HTML <fieldset /> and <legend /> elements and enables you to logically group controls together. Figure 5 shows the control in action. The text IE 8 Compatibility is set using the control’s Title property. The control’s content can be a combination of regular HTML and ASP.NET server controls.
Figure 5
You can see this control at work in the Article module’s _Edit page and in the AddEditArticle.aspx page of the final sample application.
The TabHeader control
The TabHeader renders a series of tabs and is typically used to divide complex pages or forms in multiple areas, each accessible by its own tab. Figure 6 shows an example of the TabHeader control in action.
Figure 6
You can determine the selected tab programmatically in a few different ways, including sending its (one based) index through a Query String variable called Tab. Redirecting to SomePage.aspx?Tab=2 would make the Categories tab the selected item.
The Tree control
The Tree control (shown in Figure 7) enables you to render a tree-like structure. The Tree is pretty versatile and supports features such as drag and drop and AJAX-enabled load-on demand features.
Figure 7
The Tree control is not used in the sample application, but you can find information on how to use it on the Engage web site.
The EditableGrid control
The EditableGrid is similar to a standard ASP.NET GridView, but enables you to edit multiple items at once. Figure 8 shows the EditableGrid as it’s used in the SDK documentation samples for the UI controls.
Figure 8 (Click to enlarge)
Just as the Tree control, the EditableGrid is not used in the sample application, but you can find information on how to use it on the Engage web site.
The Toolbar control
When a RibbonBar is overkill, but you still need to present a few logically grouped buttons, the Toolbar control is the one to use. It enables you to define buttons with standard or custom images. Additionally, you can create an expandable button which in turn can show a ContextMenu that contains more menu items. In Figure 9 you see the toolbar. The Settings button is expandable and shows the context menu that’s associated with it when you click the down arrow next to the button.
Figure 9
The Toolbar is not used in the sample application. However, it’s pretty easy to use so if you need it now, you’ll be able to figure out how to use it.
The ContextMenu control
The ContextMenu control can be used to display a context menu at various locations in your page. A common place for this menu is as a right-click menu for items in the List control. Additionally, it can be used for the expandable button on the Toolbar, as shown in Figure 10:
Figure 10
The ContextMenu is used and demonstrated in part 5 of this series to enable a context menu in the list of articles.
The RichSelect and RichSelectItem controls
The RichSelect control can be used to create drop-down lists with rich content. Examples of the control in Dynamicweb can be found in the Paragraph Template and Layout selection controls. Items can be added programmatically only, using the RichSelectItem class. Figure 11 shows an example of a control with three items, two of which contain a combination of an HTML table, an image and some formatted text.
Figure 11
You can find out more about the RichSelect control on the Engage web site.
The Editor, FileArchive, FileManager and LinkManager controls
You’ve seen these controls used in the article series on building custom modules. Their usage is pretty straight-forward as they don’t require you to set a lot of properties or handle events. I won’t dig any deeper into these controls in this series, but use them where they make sense. Check out the API documentation on the Engage website for an overview of their members and usage:
The ControlResources control
This control is not visible in your pages, but plays a very important role in most of your administrative pages. You need to include this control in most of your pages (or in a Master Page) in order for the other controls to work. The ControlResources control adds references to the many JavaScript and CSS files that many of the controls rely on to the head section of your page. If you find that the controls look or behave funky, chances are you forgot to include this control in your Admin pages. To use the control, add it to the <head /> section of an ASPX Page or Master Page like this:
<head runat="server"> … <dw:ControlResources … </head>
The ControlResources control has the following properties that influence its behavior:
Depending on the controls you have in your page, and the properties you set on the ControlResources control, you end up with references in the <head /> of your page similar to the following:
<head> <!-- Controls resources start --> <link rel="stylesheet" type="text/css" href="/Admin/Images/Ribbon/UI/Tree/Tree.css" /> <link rel="stylesheet" type="text/css" href="/Admin/Images/Ribbon/UI/Richselect/Richselect.css" /> <link rel="stylesheet" type="text/css" href="/Admin/Images/Ribbon/Ribbon.css" /> <script type="text/javascript" src="/Admin/Content/JsLib/dw/Ajax.js"></script> <script type="text/javascript" src="/Admin/Images/Ribbon/UI/Tree/Tree.js"></script> <script type="text/javascript" src="/Admin/Filemanager/Upload/js/EventsManager.js"></script> <script type="text/javascript" src="/Admin/Content/JsLib/prototype-1.6.1.js"></script> <script type="text/javascript" src="/Admin/Images/Ribbon/Ribbon.js"></script> <script type="text/javascript" src="/Admin/Images/Ribbon/UI/Tree/TreeDragDrop.js"></script> <script type="text/javascript" src="/Admin/Images/Ribbon/UI/Richselect/Richselect.js"></script> <script type="text/javascript" src="/Admin/Content/JsLib/scriptaculous-js-1.8.2/src/ scriptaculous.js?load=effects,dragdrop,slider"></script> <!-- Controls resources end --> </head>
If you check out the API documentation for the Dynamicweb.Controls namespace, you’ll see that the namespace includes more controls than I have listed here. Some of those are used within the context of others, and thus aren’t discussed separately. Others aren’t used very often (anymore) and are thus not very relevant to this article series. Yet others may be relevant to your custom modules, but I simply haven't discussed them yet. If you want me to dig deeper into some of those controls, let me know through my Contact page.
In the next three parts of this article series, I’ll show you how to use the RibbonBar and many of its child controls. The fifth part of this series will dig deeper in a number of the other controls I introduced in this article such as the List and the ContextMenu.
Downloads
Since this is just a general overview, there's no download for this article. Starting with the next article in the series, you can download the full source for the sample application (which is in C#) that I started in the article about custom modules. | https://devierkoeden.com/articles/building-dynamicweb-module-admin-interfaces-1-introduction | CC-MAIN-2019-39 | refinedweb | 1,921 | 53.41 |
NAME¶
FBB::CGI - handles GET and POST submitted form data
SYNOPSIS¶
#include <bobcat/cgi>
Linking option: -lbobcat
DESCRIPTION¶
The class CGI offers an interface to data submitted by web-forms. The data is sent to a script handling the data using a <form action="/path/to/form/script"> stanza. Very often this is indeed a script, like a Perl script, but there is no need to use a scripting language. The class CGI allows C++ programmers to process the form by an executable usually resulting in faster processing and in construction time benefits from the type safety offered by C++. The class CGI automatically handles data submitted using the GET method as well as data submitted using the POST method.
By default the class’s constructor writes the customary Content-type header lines to the standard output stream. Additional (html) output of a reply page must be provided by other code. Therefore, a program processing an uploaded form will have an organization comparable to the following basic setup:
// assume includes and namespace std/FBB were defined
int main()
{
CGI cgi;
cout << "<html><body>\n";
if (parametersOK(cgi))
{
process(cgi);
generateReplyPage();
}
else
generateErrorPage();
cout << "</body></html>\n;
}
When errors in the received form-data are detected an error message is written to the standard output stream and an FBB::Exception exception is thrown.
NAMESPACE¶
FBB
All constructors, members, operators and manipulators, mentioned in this man-page, are defined in the namespace FBB.
INHERITS FROM¶
-
TYPEDEF¶
ENUMERATIONS¶
The CGI::Method enumeration specifies values indicating the way the form’s data were submitted:
- o
- CGI::UNDETERMINED:
Used internally indicating that the form’s method was neither GET nor POST.
- o
- CGI::GET:
Indicates that the GET method was used when submitting the form’s data;
- o
- CGI::POST:
Indicates that the POST method was used when submitting the form’s data.
The CGI::Create enumeration is used to request or suppress creation of the directory to contain any file uploaded by a form:
CONSTRUCTORS¶
- o
- CGI(bool defaultEscape = true, char const *header = "Content-type: text/html", std::ostream &out = std::cout):
The default constructor writes the standard content type header to the standard output stream and will use std::cout for output. Specifying 0 as header suppresses outputting the Content-type line. Otherwise the content type line is also followed by two \r\n character combinations. By default all characters in retrieved form-variables are escaped. The overloaded insertion operators (see below) can be used to modify the default set of characters to escape. The backslash is used as the escape character. The escape-prefix is not used if the defaultEscape value is specified as false and if no insertions into the CGI object were performed.
Copy and move constructors (and assignment operators) are available.
OERLOADED OPERATORS¶
Note: the following three insertion operators, defining sets of characters that should be escaped, can only be used before calling any of the param, begin or end members. As soon as one of these latter three members has been called the set of characters to be escaped is fixed and attempts to modify that set is silently ignored.
- o
- char const *operator[](std::string const &key) const:
The index operator returns the value of the environment variable specified as the index. 0 is returned if the variable specified at key is not defined.
- o
- CGI &operator<<(std::string const &accept):
This member’s actions are suppressed once param, begin or end (see below) has been called.
- The insertion operator can be used to fine-tune the set of characters that are escaped in strings returned by param (see below). Depending on the value of the constructor’s defaultEscape parameter characters inserted into the CGI object will or will not be escaped by a backslash.
- If the constructor’s defaultEscape parameter was specified as true then the insertion operator can be used to define a set of characters that are not escaped.
- If defaultEscape was specified as false then the insertion operator will define a set of characters that will be escaped.
- The backlash itself is always escaped and a request to use it unescaped is silently ignored.
- The accept string can be specified as a regular expression character set, without the usual surrounding square brackets. E.g., an insertion like cgi << "-a-z0-9" defines the set consisting of the dash, the lower case letters and the digits.
- Individual characters, character ranges (using the dash to specify a range) and all standard character classes ([:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]) can be used to specify a set of characters. In addition to these standard character classes the class [:cgi:] can be used to define the set consisting of the characters " ’ ` ; and \.
- Note that standard and [:cgi:] character classes do require square brackets.
- When a series of insertions are performed then the union of the sets defined by these insertions are used.
- Note: using unescaped single quotes, the double quotes, backtick characters and semicolons in CGI-programs might be risky and is not advised.
- o
- CGI &operator<<(int c):
This member’s actions are suppressed once param, begin or end (see below) has been called.
- This insertion operator is used to change the default escape handling of a single character c. The int parameter is cast internally to a char.
- o
- CGI &operator<<(std::pair<char, char> range):
This member’s actions are suppressed once param, begin or end (see below) has been called.
- This insertion operator can be used to change the default escape handling of a range of characters. The pair’s second character must be equal to or exceed the position of the pair’s first character in the ASCII collating sequence or the member will have no effect.
- o
- std::ostream &std::operator<<(std::ostream &out, CGI const &cgi):
CGI objects can be inserted into ostreams to display the characters that will appear escaped in strings returned by the param() member function. Each character for which isprint() returns true will be displayed as character, surrounded by single quotes. For all other characters their ASCII values are displayed. Each character is displayed on a line by itself.
MEMBER FUNCTIONS¶
- o
- CGI::MapStringVector::const_iterator begin():
Returns the begin iterator of the form’s parameter map. Iterator values unequal to end (see below) point to a pair of values, the first of which is the name of a field defined by the form, the second is a vector of strings containing the field’s value(s). See also the description of the param member below.
- o
- CGI::MapStringVector::const_iterator end():
Returns the end iterator of the form’s parameter map.
- o
- unsigned long long maxUploadSize() const:
Returns the current maximum file upload size in bytes.
- o
- CGI::Method method() const:
Returns the method that was used when the form was submitted (either CGI::GET or CGI::POST).
- o
- std::vector<std::string> const ¶m(std::string const &variable):
Returns the value of the form-variable specified by the function’s argument. An empty vector is returned if the variable was not provided by the form’s data.
- If the same variable was specified multiple times or if its value extends over multiple lines (only with multipart/form-data) then the vector contains multiple strings.
- With GET and POST methods not using multipart/form-data input fields extending over multiple lines are stored in one string, using \r\n combinations between those lines.
- When files are uploaded the vectors contain sets of four strings. The first string provides the path nme of the uploaded file; the second string provides the file name specified in the form itself (so it is the name of the file at the remote location); the third string shows the content type specified by the remote browser (e.g., application/octet-stream), the fourth string contains OK if the file was successfully uploaded and truncated if the file was truncated. Existing files will not be overwritten. When uploading a file a usable filename must be found within 100 trials.
- o
- std::string param1(std::string const &variable) const:
Returns the first element of the vector<string> returned by the param member or an empty string if variable was not defined by the received form.
- o
- std::string const &query() const:
Returns the query-string submitted with CGI::GET or CGI::POST forms (if the POSTed form specified ENCTYPE="multipart/form-data" the query string is empty).
- o
The report member silently returns if no errors were encountered while processing form-data. Otherwise, the html file generated by the CGI program displays a line starting with FBB::CGI, followed by the status report.
- The following status report messages are presently defined:
- Content-Disposition not recognized in:, which is followed by the line where the Content-Disposition was expected. This may occur when processing multipart/form data.
- Invalid multipart/form-data. This message can be generated when readling lines while processing multipart/form data.
- GET/POST REQUEST_METHOD not found. This message is shown if the program couldn’t find the form’s REQUEST_METHOD type (i.e., GET or POST).
- Invalid CONTENT_LENGHT in POSTed form. This message is shown if the content-length header has an incorrect value.
- Content-Type not found for file-field, followed by the file’s field name. This message is shown if no Content-Type specification was found in an uploaded form.
- Can’t open a file to write an uploaded file. This message indicates that the CGI program was unable to open a file to write an uploaded file to. This can be caused by an overfull disk or partition or by incorrect write-permissions.
- multipart/form-data: no end-boundary found. This message is shown if the end-boundary was missing in a multipart/form-data form.
- o
- void setFileDestination(std::string const &path, std::string const &prefix = "", Create create = CREATE_PATH):
This member is used to specify the path and prefix of uploaded files. Uploaded files will be stored at path/prefixNr where Nr is an internally used number starting at one. When CREATE_PATH is specified path must be available or the CGI object must be able to create the path. If DONT_CREATE_PATH is specified the specified path must be available. If not, an FBB::Exception exception will be thrown.
- o
- void setMaxUploadSize(size_t maxSize, int unit = ’M’):
This member can be used to change the maximum size of uploaded files. Its default value is 100Mb. The unit can be one of b (bytes, the default), K (Kbytes), M (Mbytes) or G (Gbytes). Unit-specifiers are interpreted case insensitively. File uploads will continue until the maximum upload size is exceeded, followed by discarding any remainder.
- o
- void swap(CGI &other):
The current and other object are swapped. The first time one of the param(), begin() or end() members is called these members may detect errors in the the received form data. If so, an error message is written to the standard output stream and an FBB::Exception exception will be thrown.
STATIC MEMBERS¶
- o
- std::string dos2unix(std::string const &text):
This member converts all \r\n character combinations in text into plain \n characters, returning the converted text.
- o
- std::string unPercent(std::string const &text):
This member converts all %xx encoded characters into their corresponding ASCII values. Also, + characters are converted to single blank spaces. The converted string is returned.
EXAMPLE¶
#include "main.ih" void showParam(CGI::MapStringVector::value_type const &mapValue) {
cout << "Param: " << mapValue.first << ’\n’;
for (auto &str: mapValue.second)
cout << " " << CGI::dos2unix(str) << "\n"
" ";
cout << ’\n’; } int main(int argc, char **argv) try {
Arg &arg = Arg::initialize("evhm:", argc, argv);
// usage and version are in the source archive in .../cgi/driver
// arg.versionHelp(usage, version, 2);
ifstream in(arg[0]);
string line;
while (getline(in, line))
{
size_t pos = line.find(’=’);
if (pos == string::npos)
continue;
// set environment vars simulating
// a GET form
if (setenv(line.substr(0, pos).c_str(),
line.substr(pos + 1).c_str(), true) == 0)
{
if (arg.option(’e’))
cout << line.substr(0, pos).c_str() << ’=’ <<
line.substr(pos + 1).c_str() << ’\n’;
}
else
cout << "FAILED: setenv " << line << ’\n’;
}
CGI cgi(false); // chars are not escaped
cgi << arg[1];
if (arg.option(&line, ’m’))
cgi.setMaxUploadSize(A2x(line), *line.rbegin());
cout << "Max upload size (b): " << cgi.maxUploadSize() << ’\n’;
CGI::Method method = cgi.method();
cout << "To escape:\n" <<
cgi << "\n"
"Method: " << (method == CGI::GET ? "GET" : "POST") <<
’\n’;
cout << "Query string: " << cgi.query() << ’\n’;
cout << "Submit string: `" << cgi.param1("submit") << "’\n";
for (auto &mapElement: cgi)
showParam(mapElement);
cout << "END OF PROGRAM\n"; } catch (exception const &err) {
cout << err.what() << ’\n’;
return 1; } catch (...) {
return 1; }
To test the program’s get form processing, call it as driver get ’[:cgi:]’, with the file get containing:
INFO=This is an abbreviated set of environment variables SERVER_ADMIN=f.b.brokken@rug.nl GATEWAY_INTERFACE=CGI/1.1 SERVER_PROTOCOL=HTTP/1.1 REQUEST_METHOD=GET QUERY_STRING=hidden=hidval&submit=Submit+%20Query
To test the program’s post form processing, call it as driver post1 ’[:cgi:]’, using post1 and post1.cin found in Bobcat’s source archive under ../cgi/driver.
FILES¶
bobcat/cgi -). | https://manpages.debian.org/bullseye/libbobcat-dev/cgi.3bobcat.en.html | CC-MAIN-2021-43 | refinedweb | 2,184 | 54.42 |
Python Programming/Decision Control/Solutions
Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.
name = raw_input("What's my name? ") answer = "Jack" attempt = 0 if name == answer: print("That's correct!") else: while name != answer and attempt < 2: attempt = attempt + 1 name = raw_input("That's incorrect. Please try again: ") if name == answer: print("That's correct!") elif attempt == 2: print("You've exceeded your number of attempts.")
Another solution that uses the sys library.
import sys count = 0 while count < 3: guess = raw_input("Guess my name: ") if guess == "joe": print ("Good guess!") sys.exit() elif count < 2: print ("\nTry again!\n") if count == 2: print ("Too many wrong guesses, terminating") count = count + 1
better way
name = "roger" x=0 while x < 3: guess = raw_input("What's my name?: ") if(guess != name): print "Wrong" x += 1 if(x==3): print "You've reached the max attempt!" else: print "Correct" break | https://en.wikibooks.org/wiki/Python_Programming/Decision_Control/Solutions | CC-MAIN-2018-26 | refinedweb | 163 | 77.43 |
Created on 2001-10-03 02:25 by phr, last changed 2008-03-21 21:53 by gvanrossum. This issue is now closed.
It would be nice if there was a documented library
function for serializing Python basic objects
(numbers, strings, dictionaries, and lists).
By documented I mean the protocol is specified in
the documentation, precisely enough to write
interoperating implementations in other languages.
Code-wise, the marshal.dumps and loads functions do
what I want, but their data format is (according to the
documentation) intentionally not specified, because
the format might change in future Python versions.
Maybe that doc was written long enough ago that it's
ok to freeze the marshal format now, and document it?
I just mean for the basic types listed above. Stuff
like code objects don't have to be specified. In
fact it would be nice if there was a flag to the
loads and dumps functions to refuse to marshal/
unmarshal those objects.
Pickle/cpickle aren't really appropriate for what I'm
asking, since they're complicated (they try to handle
class instances, circular structure, etc.) and anyway
they're not documented either.
The XDR library is sort of ok, but it's written in
Python (i.e. slow) and it doesn't automatically
handle compound objects.
Thanks
Logged In: YES
user_id=21627
So what's wrong with xmlrpclib?
Logged In: YES
user_id=72053
I haven't looked at xmlrpclib, but I'm looking for
a simple, compact, binary representation, not something
that needs a complicated parser and expands the data by
an order of magnitude.
Logged In: YES
user_id=21627
Well, then I guess you need to specify your requirements
more clearly. XML-RPC was precisely developed to be
something simple for primitive types and structures that is
sufficiently well-specified to allow interoperation between
various languages.
I don't see why extending the data 'by an order of
magnitude' would be a problem per se, nor do I see why
'requiring a complicated parser' is a problem if the
implementation already does all the unpacking for you under
the hoods.
Furthermore, I believe it is simply not true that XML-RPC
expands the representation by an order of magnitude. For
example, the Python Integer object 1 takes 12 bytes in its
internal representation (plus the overhead that malloc
requires); the XML-RPC representation '<int>1</int>' also
uses 12 bytes.
In short, you need to say as precise as possible what it is
that you want, or you won't get it. Also, it may be that you
have conflicting requirements (e.g. 'compact, binary', and
'simple, easily processible in different languages'); then
you won't get it either. For a marshalling format that is
accessible from different languages, you better specify it
first, and implement it then.
Logged In: YES
user_id=6380
Paul, I don't understand the application that you are
envisioning. If you think that the marshal format is what
you want, why don't you write a PEP that specifies the
format? That would solve the documentation problem.
Logged In: YES
user_id=72053
I just want to be able to do convenient transfers of
python data to other programs including over the network.
XMLRPC is excessive bloat in my opinion. Sending a number
like 12345678 should take at most 5 bytes (a type byte and
a 4-byte int) instead of <int>12345678</int>. For long
ints (300 digits) it's even worse.
The marshal format is fine, and writing a PEP would solve
the doc problem, but the current marshal doc says the
non-specification is intentional. Writing it in a PEP
means not just documenting--it means asking the language
maintainers to freeze the marshal format of certain types,
instead of reserving the right to change the format in
future versions. Writing the PEP only makes sense if
you're willing to freeze the format for those types (the
other types can stay undocumented). Is that ok with you?
Thanks
Paul
Logged In: YES
user_id=6380
If the PEP makes a reasonable case for freezing the spec,
yes.
I wonder why you can't use decimal? Are you talking really
large volumes? The PEP needs to motivate this with an
example, preferably plucked from real life!
Logged In: YES
user_id=72053
Decimal is bad not just because of the data expansion but
because the arithmetic to convert a decimal string to binary
can be expensive (all that multiplication). I'd rather use
hex than decimal for that reason. One envisioned
application is communicating a cryptography coprocessor: an
8-bit microcontroller (with a public key accelerator)
connected to the host computer through a slow serial port.
Most of the ints involved would be around 300 decimal
digits.
A simple binary format is a lot easier to deal with
in that environment than something like xmlrpc. Also,
the format would be used for data persistence, so again,
unnecessary data expansion isn't desirable.
I looked at XMLRPC and it's not designed for this purpose.
It's intended as an RPC protocol over HTTP and isn't
well suited for object persistence. Also, it doesn't
support integers over 32 bits, and binary strings must be
base64 encoded (more bloat). Finally, it's not included
with Python, so I'd have to bundle an implementation
written in Python (i.e. slow) with my application (I don't
know whether Fred's implementation is Python or C). I
think the marshal format hasn't changed since before
Python 1.5, so basing serialization on marshal would mean
applications could interoperate with older versions of
Python as well as newer ones, which helps Python's maturity.
(Maturity of a program means, among other things, that
users rarely need to be told they need the latest version
in order to use some feature).
Really, the marshal functions are written the way they're
written because that's the simplest and most natural way
of doing this kind of thing. So the proposal is mainly
to make them available for user applications, rather than
only for system internals.
Logged In: YES
user_id=6380
This helps tremendously.
I think that marshal is probably overkill. Rather, you need
helper routines to convert longs to and from binary. You can
do everything else using the struct module, and it's
probably easier to write your own protocol using that and
these helpers. I suggest that the best place to add these
helpers is the binascii module, which already has a bunch of
similar things (e.g. hexlify and crc32).
Note the xmlrpc is bundled with Python 2.2.
Looking forward to your patch (much simpler to get accepted
than a PEP :-).
Logged In: YES
user_id=31435
I'm not sure this is making progress. Paul, if you want to
use marshal, you already can: the pack and unpack routines
are exposed in Python via the marshal module. Freezing the
representation isn't a particularly appealing idea; e.g.,
if anyone is likely to complain about the speed of Python's
longs, it's you <wink>, and the current marshal format for
longs is just a raw dump of Python's internal long
representation -- but the most obvious everything-benefits
way to speed Python longs is to increase the size of
the "digits" used in its internal representation. If
that's ever done, the marshal format would want to change
too.
It's easy enough to code your own storage format for longs,
e.g.
>>> def tobin(i):
... import binascii
... ashex = hex(long(i))[2:-1] # chop '0x' and
trailing 'L'
... if len(ashex) & 1:
... ashex = '0' + ashex
... return binascii.unhexlify(ashex)
implements "base 256" for unsigned longs, and the runtime
cannot be improved by rewriting in C except by a constant
factor (the Python spelling has the right O() behavior).
Logged In: YES
user_id=44345
If you head in the direction of documenting marshal with the aim of potentially interoperating with other languages, I think it would be a good idea to create a Python-independent marshal library. This would facilitate incorporation into other languages. Such a library probably wouldn't be able to do everything marshal can (there isn't an obvious C equivalent of Python's dictionary object, for example), but would still help nail down compatibility issues for the basic scalar types.
Logged In: YES
user_id=72053
Skip - C has struct objects which are sort of like Python
dictionaries. XMLRPC represents structs as name-value
pairs, for example. And "other languages" doesn't
necessarily mean C. The marshaller should be able to
represent the non-Python-specific serializable objects,
not just scalars.
Basically this means strings, integers (of any length),
dictionaries, lists, and floats (hmm--unicode?), but
not necessarily stuff like code objects.
Having an independent marshal library is ok, I guess,
though I don't feel it's necessary to create more
implementation work. And one the benefit of using
the existing marshaller is that it's already available in
most versions of Python that people are running
(Red Hat 7.1 still comes with Python 1.5 for example).
Tim - yes, I'm originally used a binascii.hexlify hack
similar to yours and it worked ok, but it was ugly. I
also had to handle strings (generate a length count
followed by the contents) and then dictionaries (name-value
pairs) and finally felt I shouldn't need to rewrite the
marshaller like that. There's already a built-in library
function that does everything I need, very efficiently in
native code, in one call, and being able to use it is in
the "batteries included" spirit.
Also, the current long int marshalling format
is just a digit count (16-bit digits) followed by the digits
in binary. If the digit width changes, the marshalling
format doesn't have to change--the marshalling code should
still be able to use the same external representation
without excessive contortions and without slowing down.
(You'll see that it's already not a simple memory dump,
but a structure read and written one byte at a time through
layers of subroutines). Changing widths while keeping the
old format means putting a minor kludge in the marshalling
code, but no user will ever notice it.
As for the speed of Python longs,
my stuff's runtime is dominated by modular exponentiations
<wink> and I'm already using gmpy for those when it's
available (but I don't depend on it). The speedup with
gmpy is substantial, but the speed with ordinary Python
longs is quite acceptable on my PIII (the StrongARM is
another story--probably the C compiler's fault).
Examining Python/marshal.c, I don't see any objects of
the types I've mentioned that are likely to need to change
representations--do you?
Btw I notice that the pickle module represents long ints
as decimal strings even in "binary" mode, but I'll resist
opening another bug for that, for now.
Logged In: YES
user_id=31435
The marshal long format actually uses 15-bit digits, each
*stored* in 16 bits (the high bit of the high byte of which
is always 0). That would be a PITA to preserve even if
Python just moved to 16-bit digits. marshal's purpose is
for efficient loading of .pyc files, where that odd format
makes good sense; since it wasn't designed to be a general-
purpose data transmission format (and has many shortcomings
for such use), I don't want to see a tail wagging the dog
here.
Cross-release compatibility is taken seriously in pickle,
and pickle handles many more cases than marshal, although
pickle's author (as you've discovered) didn't give a hoot
about efficient storage of longs. I'd rather add an
efficient long format to pickle than hobble marshal
(although because pickle does take x-release compatibility
seriously, it has to continue accepting the "longs as
decimal strings" format forever).
Logged In: YES
user_id=21627
I would have never guessed that arbitrarily long ints are
a requirement in your application...
For that application, I'd recommend to use ASN.1 BER as a
well-document, efficient, binary marshalling format. I
don't think any other format marshals arbitrary large
integers in a more compact form. You can find an
implementation of that in
or
or (ber.py)
I'd be in favour of having a BER support library in the
Python core, but somebody would have to contribute such a
thing, of course.
Logged In: YES
user_id=31435
Martin, Paul suggested BER previously in 465045. I suspect
he's going to suggest this for every module one by one,
until somebody bites <wink>. I doubt he wants genuine
ASN.1 BER, though, as that's a complicated beast, and he
only cares about ints with a measly few hundred bits;
regardless, a Python long can't have more digits than can
be counted in a C int.
Logged In: YES
user_id=72053
1) if Python longs are currently implemented as vectors
of 15-bit digits (yikes--why on earth would anyone do that)
and marshalled like that, then I agree that THAT much
weirdness doesn't need to be propagated to future versions.
Wow! I never looked at the long int code closely, but
the marshal code certainly didn't reflect that. It's still
possible to freeze the current marshal format and let
future versions define a new mechanism for loading .pyc's.
From my own self-interest (of wanting to distribute apps
that work across versions) that idea attracts me, but it's
probably not the right thing in the long run. Better may
be to fix the long int format right away and THEN document/
freeze it. (Use a new format byte so the 2.2 demarshaller
can still read 2.1 .pyc files). By "fix" I mean use a
simple
packed binary format, no 15 bit digits, no BER, and the
length prefix should be a byte or bit count, not multibyte
"digits".
2) Unfortunately it's not easy in portable C with 32 bit
longs to use digits wider than 16 bits--multiplication
becomes too complicated. If the compiler supports wide
ints (long long int) then conditionalized code to use them
might or might not be deemed worthwhile. Python's long int
arithmetic (unlike Perl's Math::BigInt class) is fast enough
to be useable for real applications and I don't expect it
to go to the extremes that gmpy does (highly tuned
algorithms
for everything, asm code for many cpu's, etc). So currently
I use gmpy when it's available and fall back on longs if
gmpy won't import--this works pretty well so far.
3) I like the idea of a BER/DER library for Python but I
don't feel like being the guy who writes it. I'd probably
use it if it was available, though maybe not for this
purpose. (I'd like to handle X509 certificates in Python).
BER really isn't the most efficient way to store long ints,
by the way, since it puts just 7 useful bits in a byte.
4) My suggestion of BER in 465045 was motivated slightly
differently, which was to add a feature from Perl's pack/
unpack function that's missing from Python's struct.pack/
unpack. I understand a little better now what the struct
module is for, so binascii may be a better place for such
a thing. However, I believe Python really needs a
pack/unpack module that does all the stuff that Perl's
does. Data conversion like that is an area where
Perl is still beating Python pretty badly. (Again, I
don't feel like being the one who writes the module).
5) Sorry I didn't notice Guido's post of 20:24 earlier
(several arrived at once). I guess I'm willing to submit
a patch for binascii to read and write longs in binary.
It's slightly humorous to put it in binascii since it's
a binary-binary conversion with no ascii involved, but
the function fits well there in any case. I'd still rather
use marshal, since I want to write out more kinds of data
than longs, and with a long->binary conversion function
I'd still need to supply Python code to traverse
dictionaries and lists, and encode strings. Btw, the
struct module doesn't have any way to encode strings
with a length, except the Pascal format which is limited
to 256 bytes and is therefore useless for many things.
Logged In: YES
user_id=31435
I don't buy the argument that pickle is "complicated", as
you weren't going to document the parts of the marshal
format you didn't care about either. A subset of pickle is
just as easy to document and implement across languages as
a subset of marshal, but with the key benefit that the
pickle format is stable across releases. So if you want a
structure packer, pickle is the obvious choice; it just
lacks an efficient (in time and space) scheme for storing
longs now. And unlike marshal, it isn't a dead end when
you decide your app needs something fancier -- pickle
already handles just about everything that *can* be
pickled, and is designed to be extensible to user-defined
types too, so you can painlessly expand your view of what
the "interesting" subset is as your ambitions grow.
I don't really know what you mean by "BER". The ANS.1 std
<-
T/studygroups/com17/languages/X.690_1297.pdf>
section 8.3 is quite clear that all 8 bits are used in each
byte for integer representations -- it's a giant 2's-comp
integer, with a variable-length length prefix, redundant
sign bytes are forbidden, and there's nothing special about
the last byte. I agree with Martin that ANS.1 BER is as
compact a standardized bigint representation as there is.
Logged In: YES
user_id=21627
7-bit vs. 8-bit: You were confusing tag encoding and
INTEGER value encoding.
no way to encode a string with a length: suppose you want
a 32 bit length, what's wrong with
struct.pack("l",len(s))+s
15-bit representation: I believe the add and sub
implementations make use of the guarantee that a short
won't overflow if the input fits into 15 bits.
Tim: BER = Basic Encoding Rules (as in the subtitle of
X.690)
Even after all this discussion, I still cannot see why the
existing libraries (including those offered for free by
third parties) are not sufficient. It appears that Paul
wants, among other things, that marshal becomes
documented; it also appears that this won't hapen.
What the other things are that Paul wants, I cannot tell,
so I recommend to close this report with "won't fix".
Paul, if you have a specific change that you want to be
made, or a specific problem that you want to point out,
please submit a new report. This issue "provide a
documented serialization func" really ought to be closed
as "Fixed"; xmlrpclib is already part of standard library
and fits the original problem description:
- it is a library for serializing Python basic objects
- it is documented in the sense that the protocol is
specified precisely enough to write interoperating
implementations in other languages.
Logged In: YES
user_id=31435
Martin, you're right about add and sub, but it's a shallow
assumption easy to relax (basically just declare
carry/borrow as twodigits instead of digit). I'd be more
worried about the stwodigits type, but since nothing is
actually broken here I'm not keen to fritter away time
proving bounds on the temps in bigint division. How we
implement bigints internally is off topic anyway (provided
we're not trying to hijack internal implementation formats
for unintended purposes).
About BER, yes, and the URL I included is to a freely
downloadable copy of the X.690 std; section 8.3 spells out
the INTEGER rules. They aren't at all the rules Paul
sketched, hence "I don't really know what you [Paul] mean
by 'BER'".
For the rest, while xmlrcplib may meet the letter of what
Paul asked for at first, it's clear to me that it doesn't
meet what he really wants. My suggestion remains to add a
new, efficient bigint format to pickle, which would meet
everything except Paul's desire to have a special gimmick
limited to his specific application and without having to
write one himself. The internal API functions
_PyLong_AsByteArray and _PyLong_FromByteArray already do
the heavy lifting in both directions (to or from base 256,
unsigned or complemented, big- or little-endian).
Logged In: YES
user_id=72053
A pickle subset ("gherkin"?) could possibly also fill this
need, if it was documented, even though pickle format is
considerably more complicated than marshal format (it uses
marshal.dumps for binary output, actually taking apart the
marshalled strings). It was obvious in seconds how
marshal.c works but after 30 minutes of looking at pickle.py
I'm still not sure I understand it. It looks like
the unpickler can construct arbitrary class instances and
import arbitrary modules, which makes a security hole
if the pickled strings are potentially hostile, but
I might not be reading it right. Also, the unpickler
must implement constant folding (the memo scheme), which
complicates it somewhat, though it's not that bad.
The idea of leaving the marshal formats of some Python-
specific objects undocumented isn't to get out of
documenting stuff, but to leave those formats open to later
change.
Re BER/DER, Burt Kaliski's "Layman's Guide" is pretty
readable ().
You're right about using all 8 bits in BER integers--it
looks like the 7 bit representation is only used for OID
components (I didn't realize that til checking on it just
now). BER might be ok for what I'm doing--I'm not sure
right now since I don't understand ASN1 that well. It looks
not in the spirit of marshal/pickle though: to encode a
compound object it looks like you need an ASN1 spec of
EXACTLY what you expect to find in the object.
Logged In: YES
user_id=72053
I agree with Tim that the internal implementation of long
arithmetic isn't relevant to this--it was just surprising,
and means the current marshal format isn't all that natural
for external use.
I don't have a particular agenda to get marshal documented,
beyond that it would happen to solve my immediate problem.
Alternatives are fine too. The ones suggested so far
just don't seem to do the job, viz.:
xmlrpc does NOT serialize basic Python objects--in
particular it doesn't serialize integers longer than 32
bits. I can't consider using pickle until I've convinced
myself that it doesn't make security holes, and so far it
looks like the opposite. (Can someone tell me I'm not
reading it right?).
Yes, of course, it's not that difficult to write Python
code to do everything I want. It's just surprising that
I should need to do that. I mean, imagine if there was
no integer addition function (no "+" operator) and the
maintainers said "that's ok, to add a and b, just use
'a - (-b)'". It's not a showstopping obstacle, but I'm
surprised to get so much grief for suggesting making the
operation more convenient, since it's an obvious thing
to want to do (as evidenced by there already being so many
overlapping serialization functions: marshal, pickle,
rpclib, the Serialization class from Vaults of Parnassus,
three different ASN1 implementations you mentioned, etc).
I can't see anywhere where I've requested a "special
gimmick". Yes, an efficient bigint representation in pickle
is nice and ought to be added, but I can live without it.
I can NOT live with security holes, but wanting security
shouldn't be considered a special gimmick! With binary
bigints, a documented format, and a way to 100% stop the
unpickler from ever calling eval or apply on untrusted
data, I wouldn't mind using pickle despite its additional
complexity compared to marshal.
I don't want to depend on third party modules unless I
bundle them with my application (again not a showstopper,
but it's not in Python's "batteries included" spirit to need
them at all). Telling a user "to run this app, first
download modules vreeble from <url1> and frob from <url2>"
where url1 and url2 usually turn out to be broken links
by the time the user sees them is not the right way to
distribute an app. (It happens I'm going to sometimes
tell the user "to run this app, first destroy your
handheld computer's OS by reflashing the firmware..."
but it's the principle of the thing, you know).
Anyway, the 15 bit bigint representation is reason enough
to not want to freeze the current marshal format.
Maybe a future marshaller can use a cleaner bigint format
and at that point perhaps the issue can be revisited.
Logged In: YES
user_id=31435
Ack -- Paul, you add a new hitherto secret <wink>
requirement with each reply.
marshal isn't secure at all: because its *purpose* is to
load .pyc files, marshal creates Python code objects out of
any bytes you happen to feed it following a "code object"
tag. That's a hole big enough to swallow the solar
system. In 2.2, marshal refuses to unpack code objects in
restricted execution mode, but not before 2.2, and it never
refuses in unrestricted mode.
In contrast, pickle doesn't know anything about code
objects, so doesn't have this hole. The pickle docs are
clear about this, too, spelling out that marshal's code-
object abilities create "the possibility of smuggling
Trojan horses into a program".
When wondering about security, you should be looking at
(and using) cPickle.c instead of pickle.py; cPickle doesn't
use marshal at all, nor does it do eval()s etc. Yes, it
can reconstruct pickled instances of classes that already
exist, but it cannot create new classes. I haven't heard
that characterized as an insecurity before, but to each his
own level of discomfort.
I want to go back to the start: if the question is whether
Python is interested in documenting another data
transmission format, my answer is no. There are many
already (don't forget the ones from the CORBA and ILU
worlds either) available from Python, and there's no reason
to believe encoders/decoders for a Python-specific format
would get implemented in any other language.
pickle is Python's generic answer to the Python-specific
serialization question. I'd be happy to see patches to
improve it (whether for efficient longs, or some stricter
notion of security, or even just docs). But I expect any
additional Python-specific serialization scheme has an
audience of one (if you disagree, fine, write a PEP and get
some community consensus).
Logged In: YES
user_id=72053
My understanding of marshal (I better check it, but I did
mention the issue in the original request) is that it can
create code objects but it doesn't actually execute the code
in them. My implementation currently uses marshal but
checks that the stuff marshal returns doesn't contain
anything unexpected. Unpickle is different--it looks like
it can execute hostile code before the loads call ever
returns. By the time you have a chance to check the result,
it's too late. cPickle.c appears to work exactly the same
way (using eval and creating arbitrary instances, but maybe
not calling marshal) as pickle.py.
It never would have occured to me that the unpickler would
work that way (and I'm still not convinced I understand
it--I better try putting together a test to see if it's
really like that). That's why I didn't notice the security
issue til we started discussing pickle and I actually looked
at the code. I'm sorry if that sounds like I'm adding
requirements. I'd have thought it would go without saying
that an important utility shouldn't have security holes.
I'm ok with using pickle if the doc and security concerns
are taken care of. More efficient longs would be helpful
but they would break interoperability with old versions
and I can probably live without them. It's really sad that
longs were shrugged off when the pickle binary format was
designed. Now in order to have efficient longs, yet another
flag will have to be added to the constructor.
Btw, if the unpickle security issue is real (I'm still not
convinced!), I feel it should be treated as a major bug
and that an announcement should be sent out. Unpickle
already anticipates hostile pickled strings in the
non-binary format and checks for them (see
_is_secure_string) though I'd want want to spend an hour
or two checking both the `...` code and the evaluator
before believing that _is_secure_string is really safe--
and even if it is, it's brittle. But it looks like
object creation security is an area they didn't think about.
Basically I have nothing against pickle in principle, but
it has these (fixable) problems, and while marshal is
straightforwardly written, both pickle implementations
are excessively clever and make me queasy.
Anyway, I can go along with the idea that the right solution
is to fix pickle--but at present, pickle looks like it's in
worse shape than marshal.
Logged In: YES
user_id=72053
Tim has opened a doc bug for pickle/marshal security
issues as #471893.
Logged In: YES
user_id=357491
Is this still an issue? If so, shouldn't this be made an RFE?
Logged In: YES
user_id=72053
Yes, it's still an issue, even more than before since pickle
is now explicitly documented to NOT be ok to use with
untrusted data.
This is already classified as a feature request. I don't
know if an RFE is something different than that.
Logged In: YES
user_id=357491
RFE is specifically a feature request. I have gone ahead and reclassified this
as such.
Sorry, but is the feature request related to constructing a safe
unpickler ? If yes, then I suppose this issue should be closed and an
appropriate one be created.
Nevertheless, reading the following comment at pickletools.py (trunk)
makes me think this feature request won't be done, not in the pickle
module at least:
"Another independent change with Python 2.3 is the abandonment of any
pretense that it might be safe to load pickles received from untrusted
parties -- no sufficient security analysis has been done to guarantee
this and there isn't a use case that warrants the expense of such an
analysis."
There isn't anything actionable in this bug request. It makes much more
sense to start a discussion about requirements etc. on python-ideas. | http://bugs.python.org/issue467384 | CC-MAIN-2014-52 | refinedweb | 5,195 | 60.85 |
NRF24L01 as BLE Module with Arduino
Today we will learn to use the NRF24L01 module as a BLE module with Arduino. Many times you may have come across that term called BLE, which stands for Bluetooth Low Energy, and it is basically a highly optimized version of Bluetooth. As we know that ESP32 comes with inbuilt, BLE capabilities. Here We have an NRF module in the market, which can be used as a BLE module.
- Components Required
- Circuit Connection for NRF24L01 and Arduino
- Program NRF24L01 as BLE Module with Arduino
- Video Tutorial: NRF24L01 module as BLE Module using Arduino
- Conclusion
It is significantly cheaper than the HM10 BLE module or ESP32. Yes. I am talking about the NRF24L01 RF module that can be used as a BLE module. Thus today in this tutorial, we will learn how to use an NRF as a BLE module with an Arduino. Without wasting any further time, let’s get into this.
Components Required
Recently, I came to know that NRF has BLE capabilities. Thus I thought to give this a try. Before we proceed with the building, make sure you have the following components:
BLE is a smaller and highly optimized version of classic Bluetooth. Actually, BLE was designed by keeping in mind the lowest possible power consumptions, especially for low cost, low bandwidth, low power, and low complexity.
So, the BLE devices can run for a long period with just a coin cell.
Circuit Connection for NRF24L01 and Arduino
Before we proceed with the programming, let’s get into the circuit part. So please refer to the shown NRF24L01 and Arduino connections.
The NRF24L01 Module is not breadboard-friendly. So I recommend you use custom PCB for this project.
You can simply download the Gerber file and order the PCB from at a cheap price.
PCBWay is quite professional in PCB manufacturing. You can try their services at extremely low prices. Only $5 for 10 PCBs and $30 in total for 20 PCBs assembly. Besides this, the new members also get a $5 sign-up bonus. That means the new users can order 10 PCBs for free.
So, you need to connect NRF24L01 and Arduino pins accordingly. After going through connections, go to your smartphone and download NRF mobile applications from the play store. We use it for reading NRF data over the BLE on our smartphones.
Program NRF24L01 as BLE Module with Arduino
Today We are going to use the cheapest alternative NRF24L01 as BLE Module with Arduino. So let’s get into the PC to set up the Arduino microcontroller, to use this module.
Libraries for using NRF24L01 as BLE Module
Now open the Arduino IDE, again go to the library section of your Arduino IDE. And in order to use the NRF BLE capabilities, we need two libraries.
The first one is the NRF24 library for the NRF module. So you need to install this library. And again the second library for the BLE module is BTLE. So, install this library in your Arduino IDE.
So after installing the libraries, you can go to the example then BTLE and you can look at these examples: send, receive, and temperature.
SEND Example code for BLE
Now open the SEND example and upload this example code to our Arduino board. So we have uploaded the code and we should be able to observe the BLE device as “foobar”.
#include <SPI.h> #include <RF24.h> #include <BTLE.h> RF24 radio(9,10); BTLE btle(&radio); void setup() { Serial.begin(9600); while (!Serial) { } Serial.println("BTLE advertisement sender"); btle.begin("foobar"); } void loop() { btle.advertise(0,0); btle.hopChannel(); Serial.print("."); }
Now let’s go to the NRF Connect mobile application. Here you can get the devices in the scanner section. If you don’t see your device, please refresh the page again. Now I hope you can see a device called “foobar”.
Now, this device is not sending any data. That’s because we are not sending any data in the program code. So in order to send data, we need to advertise the data using the “btle.advertise” command. And we need to put our data inside these parentheses().
btle.advertise(0,0);
But, How? To add data, we need a variable buf of type “nrf_service.data”. and this variable can store two things, The first thing is UUID, which is Universal Unique Identifier used to identify the information in the computer systems. And the next thing it can store the float type of data.
So by default, this library can support three types of UUID and they all have their own purpose. NRF device information service UUID is used to advertise the device information. Then NRF Temperature Service UUID is used to advertise the Temperature. Then NRF battery service UUID is used to advertise the battery percentage.
Now in this send code. We will use these three types. So we can advertise these three types of data over the BLE with this BTLE library by default. But that does not mean you cannot create your own type of UUID and advertise the data. It is a different topic and we’ll make a video on that later.
NRF device information service UUID
Thus in a loop section let’s create a buf variable of NRF service data type, then we need to set the UUID type of the advertisement. So let’s copy all these three and we will first try NRF device information UUID. So let’s comment on the other two types. Now we need float data. So I created a float ’temp’ variable and we need to store the data of the ‘temp’ variable into the value variable of buf. But it has to be an NRF float type, not a normal Arduino float type. So this command will help us to Convert float to NRF float and then store it in the value variable of buf. Now, we need to put the advertising
void loop() {float temp("."); }
The command here, which contains the type of data, buf, and size of buf. Now, let’s upload the code to Arduino, and then let’s refresh our mobile app.
So here we are going to see our Foobar BLE device and in the service data part, we can see the UUID of our device.
NRF Temperature Service UUID
In the meantime let’s try the next UUID and it is NRF Temperature service UUID. So let’s uncomment this line and comment out the previous one and let’s consider, we want to send the temperature as 30 degrees celsius. So in the temp variable, I’ll put 30 values and upload the code. Similarly, refresh your app. Now we got the temperature icon here, and we can also see the temperature as 30 degrees Celsius.
void loop() { float temp=30;("."); }
So similarly, instead of sending a fixed temperature data, we can attach a temperature sensor, and then we can send the real-time temperature data to our smartphone.
So if you want me to make a video on this topic, then let me know in the comment section below
The NRF Battery service UUID
Now let’s comment on this and uncomment the NRF Battery service UUID. Before uploading the code. We needed some changes in the code. Change the float temp variable value to 0.5 Here it takes 1 as a maximum value which is 100% and for now, it shows 0.5 as a 50% battery level.
void loop() { float temp=0("."); }
Finally, upload the file to Arduino and refresh the App again. Here, we can see the battery percentage at 50%.
So, here we conclude the sending or advertising data part.
Receiver code for BLE to Advertise Data
Now let’s try this receiver code of BLE. Basically, what this code does is, it listens and receives all the data packets that are available near it. And it will print it on the serial monitor. But before that, we need to edit the hex part.
We need to typecast into the ‘char’ format. In order to decode the code into human-readable form. Now let’s upload the code to you. Arduino And open your app and then under the advertise section let’s create an advertisement. So just provide it with a name. Here I have provided it as the IoT Projects. then click on the add record and choose what you want to send.
#include <SPI.h> #include <RF24.h> #include <BTLE.h> RF24 radio(9,10); BTLE btle(&radio); void setup() { Serial.begin(9600); while (!Serial) { } Serial.println("BTLE advertisement receiver"); btle.begin(""); } void loop() { Serial.print("Listening… "); if (btle.listen()) { Serial.print("Got payload: "); for (uint8_t i = 0; i < (btle.buffer.pl_size)-6; i++) { Serial.print(char(btle.buffer.payload[i])); Serial.print(" "); } } Serial.println("done."); btle.hopChannel(); }
I just want to advertise my device name. Which you can see on our screen. So after that, I will hit “ok“. And our advertisement is ready. Now Let’s turn it on, and open the serial monitor and you can see, we are receiving our device name in a readable form.
Video Tutorial: NRF24L01 module as BLE Module using Arduino
Conclusion
We can use these techniques to control any type of device by sending data, for example, lighting up your LED Bulb or even controlling AC home appliances. If you need an Article/video on that, let me know in the comments section. So, guys, that’s all about using NRF24L01 Module as BLE Module using Arduino. I hope you like this tutorial. If you did, give me a share from the share button below.
Recommended Readings:
- Password Security Lock System Using Arduino & Keypad
- IoT Based Patient Health Monitoring System Using ESP8266/ESP32 Web Server
- Fire Security System using Arduino & Flame Sensor
One Comment
How to create own tupe of uuid? Kindly help me | https://theiotprojects.com/nrf24l01-as-ble-module-with-arduino/ | CC-MAIN-2021-43 | refinedweb | 1,654 | 66.84 |
I was trying to write a C++ code to find if the entered number is prime or not. There is a big logic problem in the code which I have failed to fix. At least you can see I tried. Now please help me with it. It would be kind of you.
#include <iostream> #include <cstdlib> using namespace std; int main() { int n, i; bool prime = true; cout << "Enter the number: "; cin >> n; for (i=2; i<=(n/2);i++) { if (n%i != 0) prime = true; else if (n%i = 0) prime = false; { if (prime = false) break; } } if (prime = true) cout << "the number is prime" << endl; else cout << "not prime" << endl; system("pause"); } | http://forum.codecall.net/topic/63436-is-number-a-prime-or-not/ | crawl-003 | refinedweb | 113 | 89.99 |
used. This blog post examines why we chose to go this route.
We evaluated languages on the following criteria:
- Developer Productivity.We would be working on a tight schedule. It was highly desirable to use a language that would allow us to write code as quickly as possible and get it into production as quickly as possible.
- Risk of Bugs.One of our prime directives was to do no harm to the existing Avention base of users. Avention had a huge base of users on its legacy products, and those users would be moving over to the new products. The last thing we wanted was to make those users angry by releasing buggy software. The language we picked would have to lend itself to creating high quality code with reduced risk of bugs.
- Libraries.The language would need good libraries for things like accessing databases, web frameworks, search engines, concurrency, big data analytics, and so on. The greatest language in the world is useless without a strong ecosystem.
- Hirability.We were going to be recruiting a number of developers for our team in a highly competitive Austin market where good developers are in high demand. It was critical that we be able to hire a number of developers to work in whatever language we picked.
We’ll see below how Scala is unique among the languages we evaluated in that it scores highly across all of these criteria.
Developer Productivity
Some programming languages are more expressive than others, meaning that you can get more done with fewer lines of code. In general, if you can accomplish a task with fewer lines of code, you can complete the task more quickly..
Why do expressive languages lead to higher productivity? It’s not that programmers are typing away as fast as they possibly can all day, and that less typing makes them faster. The biggest advantage of expressive languages is that they help keep you in the zone. The more you have to type in to accomplish the next step in the algorithm, the more you get distracted from your train of thought. The less you have to type in, the faster you get back to your train of thought.
Additionally, expressive languages have a couple of other benefits..
We progammers all have this sense that some languages lead to higher productivity than others. That’s why we code in modern high-level languages rather than Assembly. But could some high-level languages lead to higher productivity than others? We’ll see with some examples below how statically typed languages like Java are less expressive than dynamically typed languages like Python, Ruby, JavaScript, Groovy, and the various Lisps. We’ll use Python as a fairly representative dynamically typed language. We’ll also see how functional languages like Scala stack up.
A Class to Hold a Point
Let’s start by creating a Java class to store the X/Y coordinates for a point:
class Point { private int x; private int y; public Point(int x, int y) { setX(x); setY(y); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public boolean equals(Object other) { if (other instanceof Point) { Point otherPoint = (Point) other; return otherPoint.getX() == getX() && otherPoint.getY() == getY(); } else { return false; } } @Override public int hashCode() { return (new Integer[] {getX(), getY()}).hashCode(); } }
That’s a lot of code for a simple class. Here’s the same thing in Python:
class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): if isinstance(other, Point): return other.x == self.x and other.y == self.y else: return False def __hash__(self): return hash((self.x, self.y))
That’s a lot better. Unlike in Java, we didn’t need to define the member variables outside of the constructor; setting the member variables inside the constructor is sufficient. We also didn’t need to write getter and setter methods. If at some point in the future, we want to add a constraint that x has to be in the range (-100, 100), we could add a setter in the Python code, and we wouldn’t have to change any other code that uses Point to use this setter. That’s different from Java. In Java, suppose we hadn’t written getters and setters and all of our code just referenced the x value as somePoint.x. If we later wanted to enforce the (-100, 100) range, we’d have to add a setter and modify all of our code to use it. That’s a pain, and that’s why idiomatic Java encourages getters and setters from the beginning.
But imagine for a second what the Java and Python code would look like if we had setters that enforce the range of x. That would be one extra line of logic buried in the middle of all that boilerplate Java code. Someone looking at the code base might not even notice the constraint was there. But in the Python, it would be really obvious that we’ve added a constraint on x.
Here’s the equivalent code in Scala:
case class Point(var x: Int, var y: Int)
That’s it! One line of code. And this code does everything that the Java and Python examples are doing. We’ve got member variables x and y, a constructor that sets x and y, getter and setter methods, and equals() and hashCode() methods. In the future, we could choose to override the setter for x to enforce the range. All in one simple line of code!
Building a Map from Words to Sentences
Suppose we have a method words() that tokenizes a sentence into a list of unique words. Suppose we want to build a new method that takes in a list of sentences and returns a map from each word to the sentences containing that word. Here’s the Java code:
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; ... public Map<String, List<String>> makeWordMap( List<String> sentences) { Map<String, List<String>> result = new HashMap<String, List<String>>(); for (String sentence: sentences) { for (String word: words(sentence)) { List<String> sentencesForWord = result.get(word); if (sentencesForWord == null) { sentencesForWord = new ArrayList<String>(); result.put(word, sentencesForWord); } sentencesForWord.add(sentence); } } return result; } ... List<String> sentences = new ArrayList<String>(); sentences.add("This is the first sentence."); sentences.add("This is the second sentence."); sentences.add("This is the third sentence."); Map<String, List<String>> wordMap = makeWordMap(sentences);
A few observations about the Java code:
- We have to explicitly import the list and map types, even though these types are used in a high percentage of all Java code.
- When we define variables result and sentences, we have to list the type parameters on both the left side of the equals sign and then again on the right side.
- Even though Java knows that makeWordMap() returns a map from strings to lists of strings, when we call makeWordMap(), we still have to specify the full type with type parameters when defining our wordMap variable. Shouldn’t Java be smart enough to know the variable’s type?
- Because the get() method on Java’s Map interface doesn’t allow us to specify a default value, we have to add an if() statement in the middle of makeWordMap() to cover the case when the current word isn’t found in the map.
- When we build up our test data at the bottom, the ArrayList constructor doesn’t allow us to construct the list with a set of strings. We have to call sentences.add() over and over to actually populate the list.
The Java code is pretty verbose. Let’s see how Python does.
def makeWordMap(sentences): result = {} for sentence in sentences: for word in words(sentence): sentencesForWord = result.get(word, []) sentencesForWord.append(sentence) result[word] = sentencesForWord return result ... sentences = [ "This is the first sentence.", "This is the second sentence.", "This is the third sentence." ] wordMap = makeWordMap(sentences)
Much better. No imports. The code isn’t cluttered up with type parameters. We don’t need the if() statement within makeWordMap() since Python’s map lookup method get() takes a default value. Our test list of sentences is much easier to build; just surround a comma-separated list of strings in brackets and we have a list. The Python is a lot easier to type in, and it’s a lot easier to look at the code and understand what it’s doing.
Finally, here’s the Scala:
def makeWordMap(sentences: List[String]): Map[String, List[String]] = { val initMap = Map.empty[String, List[String]] sentences.foldLeft(initMap) { (map1, sentence) => words(sentence).foldLeft(map1) { (map2, word) => map2 + (word -> (sentence :: map2.getOrElse(word, Nil))) } } } ... val sentences = List( "This is the first sentence.", "This is the second sentence.", "This is the third sentence.") val wordMap = makeWordMap(sentences)
For the Scala code, we’ve switched from an imperative solution with mutable variables to a functional solution with immutable variables. The code loops through each sentence. Then it loops over each word in the current sentence. Using getOrElse(), it looks up the sentences for the current word in the map. If the word isn’t in the map, getOrElse() returns an empty list of sentences (Nil). The current sentence is added to the list of sentences, and then the new list of sentences is identified with the current word in a new map.
Like the Python code, the Scala is very compact. There are no imports. Only a few types and type parameters are required. We don’t need any if() statements to handle the case where the current word isn’t in the map yet. Building up a list of test data is pretty easy; we just enclose the sample sentences in List() instead of in brackets.
Plotting Points
Suppose we have a function that generates some points and then calls out to a plotter object to plot those points. We’ll keep the definition of the plotter object abstract so that we can plot to the screen, a printer, a file, or anything else we can dream up. In Java, this means creating a CanPlot interface.
interface CanPlot { void plot(Point point); } ... void plotSquares(int n, CanPlot plotter) { for (int x = 0; x <= n; x++) { plotter.plot(new Point(x, x * x)); } }
Because Python supports duck typing, the Python implementation doesn’t need an interface. All we need is
def plotSquares(n, plotter): for x in range(0, n + 1): plotter.plot(Point(x, x * x))
Like Java, Scala needs a formal declaration of what methods are available on the plotter. The only difference from Java is that Scala calls this a trait rather than an interface. So the Scala code is basically the same as the Java:
trait CanPlot { def plot(point: Point): Unit } def plotSquares(n: Int, plotter: CanPlot) { (0 to n) foreach { x => plotter.plot(Point(x, x * x)) } }
In this example, Scala is no better than Java, and Python is the clear winner.
Looking up Songs by an Artist
Let’s look at one last example where Scala is a clear winner over both Java and Python. Suppose we have an Artist object that has a getAlbum() method. Method getAlbum() is passed an album name, and it returns an Album object. The Album object then has a getSong() method that is passed a song name and returns a Song object. We want to write a method that takes an Artist, an album name, and a song name as parameters and returns the corresponding song’s length in seconds. Here’s the Java:
Integer getSongLength( Artist artist, String albumName, String songName) { Album album = artist.getAlbum(albumName); if (album != null) { Song song = album.getSong(songName); if (song != null) { return song.getLength(); } else { return null; } } else { return null; } }
All those if() statements to check for errors make the code pretty ugly. Just by glancing at the code, it’s hard to immediately see that all we’re really doing is calling getAlbum() and getSong() sequentially. The Python code also suffers from obfuscation due to error checking:
def getSongLength(artist, albumName, songName): album = artist.getAlbum(albumName) if album: song = album.getSong(songName) if song: return song.getLength()
The Python isn’t quite as bad as the Java because we don’t have to specify the else cases. That’s because Python functions return None if they terminate without hitting a return statement. Regardless, we still have a couple of nested if() statements obfuscating the most important parts of the logic.
Finally, here’s the Scala:
def getSongLength( artist: Artist, albumName: String, songName: String): Option[Int] = { for { album <- artist.getAlbum(albumName) song <- album.getSong(songName) } yield song.getLength }
We’ve switched all of our methods to return Option’s. That is, artist.getAlbum() returns Some[Album] if the album is found and None otherwise. Similarly, album.getSong() returns Some[Song] if the song is found and None otherwise. That allows getSongLength() to run in a for() comprehension without having to explicitly check any error conditions.
But even though we haven’t explicitly checked any errors, the errors are in fact being checked. That is, if the album can’t be found, getSongLength() returns None. Similarly if the song can’t be found on the album, getSongLength() again returns None. Only if both the album and song are found does getSongLength() return a Some[Int] holding the length.
Without the if() statements for error checking cluttering things up, it’s easy to see the main logic. That is, it’s easy to see that we’re getting an album from the artist, getting a song from the album, and returning the resulting song’s length.
Bottom line: We’ve looked at 4 examples. In each case, Java was the least expressive language. In some of the cases, Scala was the most expressive, while in others Python was the winner. But it’s pretty clear that Scala and Python in general are much more expressive than Java. We’d expect developers using these languages to be much more productive than Java developers. And recall that we used Python as a representative example of all the modern dynamically typed languages. So we would expect a Ruby, Groovy, JavaScript, or Lisp programmer to be pretty productive as well. It’s also worth noting that there’s another functional language called Haskell that scores very well on developer productivity for much the same reasons that Scala does well.
Based on developer productivity, then, we eliminated Java from consideration at Avention. That left Scala, Haskell, Python, Ruby, Groovy, JavaScript, and Lisp as candidates.
Risk of Bugs
Just like some languages lead to greater productivity than others, some languages lead to lower risks of bugs than others. Yes, this is the old debate about unit tests versus compile-time type checking, or more appropriately unit tests alone on the one hand versus compile-time type checking plus unit tests on the other hand. Simply put, when you use statically typed languages like Java, the compiler finds a subset of the bugs for you and forces you to fix them before your program will run. You still need unit tests to find the rest of the bugs, but at least the compiler gives you some help. When you use dynamically typed languages like Python, Ruby, JavaScript, Groovy, or Lisp you get no help from the compiler. You only get run-time errors that are harder to find, even if you invest in thorough unit tests.
Imagine a large code base with hundreds of thousands of lines. Suppose you want to add a parameter to a method or change a method’s return type. How can you be sure you’ve fixed every reference to that method? In Java it’s easy. The code won’t compile until you’ve fixed every reference. Furthermore, the compiler will quickly tell you exactly what spots in your code must be fixed. In a large Python code base, you have to grep through the code hoping you’ve found every instance. Then, all you have as a safety net are your unit tests. They probably take a lot longer to run than the Java compiler. When they fail, tracking down what went wrong is not as easy or fast as going through the compiler output in Java. But most importantly, you never quite know if your unit tests found all the problems created by updating the method or if there still are some hidden problems just waiting for your biggest customer to find.
This debate has gone on for years. Are unit tests sufficient or does a combination of unit tests and compile-time type checking produce code with fewer bugs? In his 2011 Master’s Thesis, Evan Farrer set out study this question. He started with four open source Python projects that all had extensive unit tests. He ported each of these projects line-for-line over to Haskell. Like Java, Haskell is a compiled, statically typed language. The idea was that by porting the code line-for-line and compiling it, he could see what type errors the Haskell compiler caught that had snuck through the Python unit tests. He uncovered a total of 17 type errors using the Haskell compiler. So for at least these four programs, unit testing alone was not as effective at finding bugs as a combination of unit testing along with compile-time type checking.
So, until functional programming started to catch on, there were proponents of statically typed languages in one corner shouting “lower risk of bugs, lower risk of bugs”, while proponents of dynamically typed languages were in the opposite corner shouting “productivity, productivity”. It didn’t seem possible to get both low risk of bugs and high productivity. You had to choose sides between these two seemingly incompatible values. The internet is littered with debates between the two camps.
But then along came functional programming languages like Scala and Haskell. (Actually Haskell has been around since 1990. But nobody in the mainstream seemed to notice its beauty and power until the last 5 or 10 years.) As we saw in the previous section, these languages are very expressive, leading to high productivity. But, they are also statically typed and provide all of the compile-time type checking of languages like Java. That is, if you use Scala or Haskell, you get high productivity and lower risk of bugs. You get the best of both worlds, and you can sit back and relax with a smug grin on your face while the Java guys continue to fight it out with the Python, Ruby, JavaScript, Groovy, and Lisp guys.
But it’s even better than that. Languages like Scala and Haskell actually do a better job at compile-time type checking than languages like Java. That is, there are classes of errors that Scala and Haskell catch during compilation that languages like Java typically only catch at runtime. Let’s consider null pointer exceptions.
When is the last time you debugged a null pointer exception? What about a null pointer exception in production code? If your experience is anything like mine, NPE’s consume a lot of your time, and odds are you’ve seen one within the last week, if not within the last day.
The idea of null pointers was introduced by Tony Hoare back in 1965 as part of ALGOL. Years later in a 2009 presentation at QCon, Hoare calls null pointers his billion dollar mistake. A billion dollars is his estimate of the financial impact of NPE’s. I’m guessing that’s a gross underestimate.
To see why NPE’s are so common, consider the following Java type signature from the previous section:
Integer getSongLength( Artist artist, String albumName, String songName)
According to the type signature, the method receives three inputs (an Artist and two String’s), and it returns an Integer. The problem is that the type signature is a big lie. There are actually two possibilities for the return value. The method can return either an Integer or null. But the signature doesn’t tell you anything about the null. How do you know it can return a null? You have to read the code, or maybe someone was nice and alerted you to the null in a comment. Put simply, you just have to know that it can return an Integer or a null. And of course, the operations you can perform on an Integer and a null are quite different.
Let’s look at this another way. Suppose you got confused and thought getSongLength() returned a Song object. If you started using the result like a Song (perhaps calling a Song method), the compiler would give you an error. That’s good. But suppose you get confused and think the return value is an Integer when it’s actually null. You won’t get any help from the compiler at all. But at runtime, you’ll get the dreaded NPE. You’re on your own to know when you have to check for null; the compiler won’t help you one bit.
To make matters worse, it may be that today a particular method does not ever return null. But 6 months in the future, someone changes the method so that it returns null. Or worse, someone changes a method that’s called by a method that’s called by a method that’s called by a method that’s called by this particlar method, and that change in some non-obvious way causes it to sometimes return null. Again, you get no help from the compiler, and your code, which used to work just fine, now starts throwing NPE’s in production.
And of course, the type signature above also lies when it comes to method inputs. For getSongLength(), the compiler will happily let us pass a null for the artist, albumName, or songName whether or not the method implementation actually allows null values.
In Scala, the Option type provides a nice alternative to using null. Option is an abstract type that takes a type parameter. I’ll refer to it as Option[A], where A can be a String, an Artist, a Song, or any other type at all. Option[A] has two subtypes: Some[A] and None. The idea is that if a method like getSongLength() doesn’t always return a value, wrap the result in Option rather than returning null. So in Scala, the getSongLength() signature would look like this:
def getSongLength( Artist artist, String albumName, String songName): Option[Int]
The actual return value will be a Some[Int] if the song is found or a None otherwise. Here’s the key point: The signature now includes information that the method may not return a value. The caller is required to be aware of this possibility of not returning a value. For example, if you call getSongLength() and try to use the result like an Int by adding another number to it, the compiler will give you an error that the addition method is undefined on Option’s. You are required to test whether the resulting Option[Int] is actually a Some[Int] or a None. If it’s a Some[Int], you can unpackage it to get the Int out. Only after this unpackaging can you add another number to it.
Trying to add a number directly to the resulting Option[Int] in Scala is analogous to forgetting to check for null in Java. The difference is that the compiler catches the bug in Scala, while the bug isn’t caught until runtime in Java.
And of course the same thing holds for input parameters to methods. If a parameter is optional, wrap it’s type in an Option rather than allowing null’s to be passed in. Bottom line: In Scala, you should establish coding rules early on that you should never use null under any circumstances. Use Option instead, and all of your NPE’s will disappear.
Haskell takes this one step further. While in Scala, the convention is to not use null, Haskell requires it. Haskell literally has no concept of null. In Haskell, if a function is declared as returning an object of type Foo, you can be certain that it’s returning a Foo and nothing else. No possibility of lying. So in this sense, Haskell provides even better compile-time type checking than Scala. In practice, though, using Option as a convention in Scala seems to work quite well.
It’s worth noting that types like Option, Some, and None could be written in Java. But using these types instead of null in Java would be cumbersome. Scala and Haskell give you all sorts of tools like map, flatMap, filter, and for() comprehensions that make it easy to work with Option’s. As an example, refer back to the Scala getSongLength() example from the previous section. In that example, a for() comprehension hides all the details of checking for Some versus None.
Libraries
We’ve now seen that functional languages like Scala and Haskell are unique in that they score well both with respect to developer productivity and lowering the risk of bugs. But Scala has a huge advantage over Haskell: Scala runs on the JVM. In fact, Scala compiles down to .class files just like Java does, making Scala completely interoperable with Java. Not only can you call Java code from Scala and vice versa, but you can even write plugins in Scala to Java-based systems. Want to write a servlet completely in Scala or a Scala plugin to elasticsearch? No problem. One way to think of Scala is that it is just Java with a more expressive syntax.
Running on the JVM opens up a world of robust, well-tested, and heavily used libraries to Scala developers. Whether you’re building web applications, using a search engine like Solr or elasticsearch, talking to a relational or obscure NoSQL database, the JVM gives you great libraries to work with. The same goes for big data analytics. Scala works seamlessly with Hadoop, Storm, Spark, Mahout, and so on.
In short, Scala doesn’t attempt to reinvent the wheel, but rather runs in an environment that allows it take advantage of all the mainstream Java libraries built up over the last 15 years or so. That makes Scala a very practical language.
For comparison, while Haskell is a mathematically beautiful and pure language, it does attempt to reinvent the wheel when it comes to libraries. Many Haskell libraries have been created over the last few years. But all too often, those libraries are incomplete, or buggy, or poorly documented. Or the libraries just aren’t there. In fairness, Haskell developers are working hard to close the library gap and are making great progress. But they have a lot of ground to make up, and they’re shooting for a moving target. The result is that if you build a large project in Haskell, you’re likely to spend a lot of time fighting with libraries or worse, writing libraries that you could have had for free if you were on the JVM.
This library gap between Scala and the JVM on the one hand and Haskell with its custom libraries on the other hand is what makes Scala a very pragmatic, safe language to use. Haskell is more of an academic, risky language, perhaps not as well suited for real-world applications. It’s hard to look your boss in the eye and tell him that Haskell is a safe choice. It’s a lot easier to tell him that Scala is just a nicer syntax for Java. Haskell does have some nice advantages over Scala. For example, in the previous section we saw that Scala by convention encourages you to not use null, while Haskell requires it. But these Haskell advantages are way overshadowed by the library gap.
Hirability
Hiring good developers is tough. There aren’t a lot of them out there, and they’re in high demand. Furthermore, there aren’t a lot of developers on the market who know Scala. So if you go to a recruiter and ask for candidates who already know Scala, you won’t end up interviewing many, if any, candidates at all. It seems like Scala might be a barrier to hiring.
There are two basic approaches to building a team of developers. The first approach is to hire a bunch of average developers. We’ll call this the commodity developer approach. With this approach, you increase your total development capacity by hiring more and more programmers. Because you’re hiring a bunch of developers, you want them to be cheap and easily replaceable. You might be using offshore developers to save money. If you go the commodity route, programmers are easily replaceable, and some turnover is ok. You want to pick a technology stack that is simple and that lots of developers know. That way, you can hire only developers who know your stack, and they can get up to speed quickly. Scala is a poor choice for the commodity approach because 1) not a lot of developers know it, and 2) it’s complicated to learn. Mastering the functional techniques that make Scala so powerful may be beyond the capabilities of an average, commodity developer. Stacks based on Java or PHP make much more sense.
But there’s an inherent problem with the commodity approach. The following graph shows how your total development capacity increases as you add more developers to your team:
As you add more and more developers to your team, each new developer adds less and less to your total development capacity. Put another way, the bigger your team, the lower the productivity of each individual developer. Why? Because the bigger the team, the more the developers spend their time communicating with each other and the less time they spend writing code. Also, as your team gets bigger, you’ll have to pull your best developers out from writing code at all; you’ll need them as managers of the lesser developers instead. This phenomenon has been well understood since the 1960’s when The Mythical Man Month was published.
This brings us to the second approach to building a team of developers: Keep the team small and focus on making each developer as productive as possible. How do you maximize developer productivity? Start with letting the developers use the best tools, the best hardware, the best methodologies, and the best languages. We’ve already seen how Scala leads to higher productivity than other languages. But the most important way to maximize developer productivity is to set high standards and only hire the very best, elite developers. This second approach is the exact opposite of the commodity developer approach. You want to build a small team of elite developers so that you’re in the sweet spot of the development capacity curve. Elite developers are hard to find and even harder to hire. Turnover is deadly; you want to hang onto your developers once you find them.
With the elite approach, you can be more willing to hire developers who don’t already know your technology stack. Since you’re only hiring a few developers and you’re hoping to keep them for a long time, you can afford to train your new developers on a new language. Furthermore, if you’re only hiring really smart developers who have strong records of learning new technologies, they’ll quickly pick up any language you throw at them, including Scala. So if you go with the elite developer approach and are willing to hire developers who don’t know your stack already, use of Scala won’t hinder your ability to build a team.
But it turns out that not only will Scala not hinder your hiring efforts, it will actually help them. Elite developers are hard to find and are in high demand. When an elite developer decides to look for a new job, you can bet that he’ll have a bunch of companies going after him. You’ll be just one of many companies trying to hire that developer. You need some way of standing out in the crowd. Do you want to be just another one of the n Java or Ruby shops making their pitch to the developer? Using Scala will make your company really stand out. Why? Two things elite developers really like are playing with new technologies and working with other elite developers. Having an opportunity to take a job using a new language will be very intriguing to many of the best developers on the market. And use of Scala is a key indicator to candidates that you’ve got a really strong team.
So, if you’re out to build a small team of great developers, Scala scores really well on hirability.
Conclusions
Scala is unique among languages in that it grades well on developer productivity, risk of bugs, libraries, and hirability. We’ve seen how Java scores poorly on productivity. Dynamically typed scripting languages like Python score poorly on risk of bugs. Haskell scores poorly on libraries.
Scala is very expressive, allowing you to write a small amount of code that does a lot of work. It has powerful compile-time type checking. Furthermore, it encourages techniques like using Option’s instead of null that allow the compiler to catch lots of errors that would be caught at runtime in other statically typed languages like Java. With Scala, you have access to all of the JVM libraries. And, if your goal is to build a small team of really strong developers, Scala will help you stand out from the crowd in your recruiting efforts.
Great post! I agree in much points of your conclusions.
Recently in my team we’ve a similar scenario with a new project. We are considering Scala as a very reasonable language (we’ve some experienced Java developers), but we’re cannot use Scala at the moment, and the main reason was the hireability. It’s difficult to find experienced developers, and in that case they will be considerable expensive.
Personally I don’t agree with this kind of policy, but in some big companies is really difficult to change the philosophy
Nice post!
You have a “bug” in your Java getSongLength method – if passed artist object is null you will get NPE. 🙂
If you apply NULL OBJECT Pattern, your Java code could look like this:
Full source:
Note that you have to be super careful when using case classes with variable fields. Here’s a warning example:
“`
scala> case class Point(var x: Int)
defined class Point
scala> val p = Point(1)
p: Point = Point(1)
scala> val m = collection.immutable.HashSet.empty + p
m: scala.collection.immutable.HashSet[Point] = Set(Point(1))
scala> m(p)
res8: Boolean = true
scala> p.x = 10
p.x: Int = 10
scala> m(p)
res9: Boolean = false
scala> m(Point(1))
res10: Boolean = false
scala> m(Point(10))
res11: Boolean = false
scala> m
res12: scala.collection.immutable.HashSet[Point] = Set(Point(10))
“`
Good point. I should have mentioned in the article that I only used var’s in the case class for parity between the Scala, Java, and Python. In practice, I can’t think of a good reason to ever have a case class with mutable members.
A good rule when writing Scala code: never use “var” 🙂
Never is a strong word. It’s pretty hard to write something like a cache or a connection pool without var’s. But, var’s should only be used when absolutely necessary, and you should access them as low in your call stack as possible so that as much of the top of your stack is pure functions as possible (more on that in my next blog post).
But to be clear, my use of var in the Point class is not an appropriate use of var. I only did that so that the code was functionally identical to the Java and Python code.
Kinda outdated comparisons here. Java 8 has been out for nearly a year now, and includes an option type and Streams, which make the imperative examples given here completely obsolete.
There are two things, that irritated me while reading your article:
1. Disservice made to Java by ignoring good practices like switching from nulls to Optional (either from Guava or better from Java 8) or Null objects and ignoring the advantages of good language verbosity,
2. Ignoring the subject of source code maintainability which is kinda crucial to the applications that are going to be used and changed for more than just few months.
It has eventually pushed me into writing response on my blog which can be found here:
I’d be happy to respond to all concerns 🙂
I asked if there’s really a difference between Java Optional and Scala Option on StackOverflow: stackoverflow.com/q/21714594/1360888 (comment system does not allow me to use links)
While there’s not a syntactical difference, Optional is added on top of Java standard libraries, that is, you cannot use it many cases (read collections).
I’m interested in your point for view, going to read why-not-scala.
Interesting. Thanks for posting that link.
Have 8 years experience in java. Now Scala has attracted me…thinking to go for Scala
Reblogged this on Power to Build and commented:
This is a great post. I am still “looking” into Scala. This gave a nice introduction comparing it with 2 languages I’ve seen/used – Java and Python. Thanks! Look forward to more like this.
This is a great post. I am still “looking” into Scala. This gave a nice introduction comparing it with 2 languages I’ve used – Java and Python. Thanks! Look forward to more like this.
My 2 cents in translating provided examples to Haskell. Maybe someone will find it attractive too 😉
Thanks for putting together the Haskell versions. I’m always amazed at what a cool language Haskell is.
Perhaps not as readable, but you can cut the Scala version of the word counter down even further:
Reblogged this on Play!ng with Scala and commented:
Why Scala?
Hi Clint, thank you for sharing this article because it’s really nice.
Anyhow, I wish to write you my personal experience: in my company we are using Scala in production since 2013, and I can assure you that maintainability has become a problem because the language is really expressive and smart developers in a hurry tend to wrap code way too much. Not to mention the bad habit of not to write tests (it’s too slow…).
Don’t get me wrong: I perfectly know that this is not problem of Scala itself, but due to its power, I strongly warn anyone about “going fast, writing concise” because it’s really too easy with Scala.
Nice post. But I feel that in all the examples, the python code is more readable and easy to comprehend, even though I don’t know python or scala.
I think the really cool thing about Scala is pattern matching:
def main(args:Array[String]) {
args.toList match {
case “copy” :: src :: dest :: Nil => copy(src, dest)
case “add” :: item :: to :: Nil => add(item, to)
case _ => “Invalid input”
}
}
Each time I write some command line utility this always makes me really happy.
Great post. Truly we experienced the same in our start-up. We built our API server using scala/scalaz.
We believe there is a steep learning curve, but once we have crossed that, then its a breeze.
Rock solid functional code (less bugs).
Reblogged this on Kishore's personnel blog.
This is really a nice and long post.
Thanks for sharing.
Someone refer Java as US. and python as UK. Scala as Hungary.
My point is scala is really the only plausible way for me to try functional programming and plug it into my job’s JVM environment. Try to make me a non-commodity while keeping my boss not complaining too much.
Some advantages of scala’s functional aspects are missing in the post but it is fair enough given the purpose of this post.
For the instance where you say Python is the better option, you could actually remove the trait and rely on Scala’s Structural Typing in the parameter: i.e. def plotSquares(n: Int, plotter: {def plot(point: Point): Unit})
It’s worth mentioning that using a Java library in Scala will expose you to the danger of getting nulls. So you have to wrap all third party library calls in Option() constructor. | https://softwarecorner.wordpress.com/2014/12/31/why-scala/ | CC-MAIN-2017-26 | refinedweb | 6,815 | 72.46 |
#include <curses.h>
The ins_wch() function inserts the complex character wch at the current cursor position of the stdscr window. The wins_wch() function performs the identical action but in window win. The mvins_wch() and mvwins_wch() functions insert the character at
the position indicated by the x (column) and y (row) parameters (the former in the stdscr window; the latter in window win). The cursor position does not change.
All characters to the right of the inserted character are moved right one character. The last character on the line is deleted.
Insertions and deletions occur at the character level. The cursor is adjusted to the first column of the character prior to the the operation.
On success, these functions return OK. Otherwise, they return ERR.
None.
add_wch(3XCURSES), ins_nwstr(3XCURSES) | http://www.shrubbery.net/solaris9ab/SUNWaman/hman3xcurses/ins_wch.3xcurses.html | CC-MAIN-2015-18 | refinedweb | 129 | 50.23 |
Getting Started with the Raspberry Pi 2: Basic Input and Output
The Raspberry Pi 2 has a number of input and output channels, or general purpose I/O (GPIO) ports, available for programmatic control. Python has been one of the more popular languages on the Raspberry Pi since its introduction and remains so with the Pi 2. A quick web search for Raspberry Pi Python will return a large number of results.
The default NOOB installation that we're using for these articles comes with the RPi.GPIO library installed. RPi.GPIO contains everything you'll need to manipulate the GPIO pins to implement a wide range of projects. We'll walk you through the basics of the library in this article and finish up with an example or two in the final installment.
Before we get into the code, we should explain a little about the GPIO pins on the Raspberry Pi 2. The RaspberryPi.org site has a much more detailed write-up of the GPIO pins here. For now, we'll just go over the basics available on the main GPIO header. The first types of pins are single input and output lines. These eight individual lines must be configured programmatically as either input or output and are typically used to read a switch or drive an LED. You can also connect to I2C and SPI devices plus traditional serial communication. One additional pin is available for pulse-width modulation (PWM) used in controlling motors.
One of the best ways to investigate any Python library is from the command prompt. Launching Python 2 from the Programming menu will open a new window where any legal Python statement is fair game.
import RPi.GPIO
This will load the RPi.GPIO module and make all methods and properties available. Typing the command dir(GPIO) will show all attributes of the GPIO module. Figure 1 shows the output of this command.
Figure 1: The output of the dir(GPIO) command
Another way to accomplish the same thing is to use the autocomplete function available from Python. Figure 2 shows what happens when you type part of a command and then press the tab key. In this case, the first available option after typing GPIO.set is displayed. You could just as easily type GPIO period-tab to see the first available option.
Figure 2: Pressing the tab key activates the autocomplete function
You will find a complete description of all GPIO methods on the sourceforge.net project site. It includes a number of example programs showing off a variety of ways to use the GPIO pins. At the simplest level, you issue single commands such as GPIO.output(pin, value) where pin represents the specific pin and value would be either a zero or one, depending on the wiring. Conversely, you would use the following statement to read a value of an input:
pinstate = GPIO.input(pinnumber)
If you need to wait for a switch action you could use the wait_for_edge() function or the event_detected() function if you don't want to block program execution. We'll look at several of these techniques in the final installment of this series.
There are no comments yet. Be the first to comment! | https://www.codeguru.com/IoT/getting-started-with-the-raspberry-pi-2-basic-input-and-output.html | CC-MAIN-2019-26 | refinedweb | 540 | 64.91 |
Ok, this one was just so frustrating I cannot keep it to myself. It costs so much time and nerves to realize that you were pointed in all but the right direction after all.
So here it goes. I have added a user to the MySQL database, I require the SSL connection (actually X509) and it all works on my development system (MacOSX 10.4). So I naively didn’t expect any problems on the test server running Ubuntu. I was wrong. And my mistake apparently has a name… But not all.
So what I see is that when I try to connect to the DB using either the Python/MySQLdb or giving the command line is the same:
_mysql_exceptions.OperationalError: (1045, "Access denied for user 'xxx'@'localhost' (using password: YES)")
or
ERROR 1045 (28000): Access denied for user 'xxx'@'localhost' (using password: YES)
Great. Now what?
I tried every single thing that made sense to me:
- Re-created the user, updated the privileges and even added
FLUSH PRIVILEGES
at the end (never needed it before).
- Re-generated the certificate files
- Different DB
Ok, after all it boiled down to the following messages in the dmesg output:
[877463.513737] audit(1263600950.291:21): type=1503 operation="inode_permission" requested_mask="r::" denied_mask="r::" name="/xxx/xxx/certificates/server-cert.pem" pid=11840 profile="/usr/sbin/mysqld" namespace="default"
Bingo! MySQL cannot read the f…g certificate? Why-y-y-y-y? Apparently because the
apparmor
(now I know the enemy’s name!) does not allow it. And this is all because I have installed certificates to the ‘non-standard’ folder. Well, adding the following line to the
/etc/apparmor.d/usr.sbin.mysqld
/xxx/xxx/certificates/*.pem r,
and then issuing the following commands:
#apparmor_parser -r /etc/apparmor.d/usr.sbin.mysqld #sudo /etc/init.d/mysql restart
finally put everything on their places.
2 hours, a lot of frustration, but it seem to work now. I hope you spend less time finding this in Google :).
Have a nice weekend! | http://blog.bidiuk.com/2010/01/mysql-and-ssl-error-1045-28000-access-denied-for-user/ | CC-MAIN-2021-31 | refinedweb | 338 | 59.3 |
Beautiful typography: Opinionated Type.
The last month
Time.
Campus impressions
Gallery
L.A. and San Diego
Fourth.
Extreme Geeky Tidying Up: Sorting image colors with Python and Hilbert curves
There are levels of tidiness.
Tidy.
Very Tidy.
Totally Deranged Tidy.
Geeky Tidy.
After sharing these awesome pictures by the Swiss “artist” Ursus Wehrli with the world, Martin N. pointed out that there is still a severe issue with the Badewiese: People are not even sorted by the colors of their swimsuits! Adding to that, trees are placed in total chaos, not to speak of their leaves; clearly, there are tiny waves on the water; and one can almost see blades of grass not being sorted by size. Obviously, this picture needed further tidying up.
Python to the rescue! 5 minutes, 10 lines, and half a beer later I had a program that would load the image, re-arrange its pixels, and save it again:
from PIL import Image old = Image.open("tidy.jpg") colors = old.getcolors(old.size[0] * old.size[1]) data = [] for count, color in colors: data.extend(count * [color]) data.sort() new = Image.new('RGB', old.size) new.putdata(data) new.save("naive_tidy.png")
This yields the following picture:
So how was this “re-arrangement” performed? In a naïve approach, I just sorted the RGB values of the pixels, which is why there are many consecutive lines (of equal reds) with abrupt changes. Ordered, but far from being tidy.
Let’s try another color space and sort by HSV values—a smooth hue should look better, after all. So by adding
import colorsys
and changing one line to
data.sort(key=lambda rgb: colorsys.rgb_to_hsv(*rgb))
we get the following image:
More beautiful, but the red and white noise in the end doesn’t look tidy at all. We want a smooth transition through all given colors. Hilbert curves to the rescue! Found a ready-to-be-used Hilbert walk implementation, added
import hilbert
and changed the sorting once again to
data.sort(key=hilbert.Hilbert_to_int)
Mathematical computer science just made the world a little tidier.
To the North
After renting an awesome car—a black Hyundai Santa Fe—that would be big enough to let us sleep in it, Johanna and I continued our trip to the north. Again, we spent one night at one of Rick’s friends. This time it was Betsy in Chico, where we had actually already been two years ago. Still remember the huge steaks we got from the huge grill back then.
After that, we spent one night in Lassen Volcanic National Park. After a winter with over seven meters of snow at some places, they still have quite a lot of snow in the middle of summer! We hiked up above 3000 meters towards Lassen Peak, and we saw Bumpass Hell, a stinking but beautiful collection of mud pots and volcanic hot pools.
We continued our trip to the nice campground in McArthur-Burney Falls Memorial State Park and finally reached Lava Beds National Monument. Ages ago, huge streams of lava had created tube caves, when their top cooled and crusted while the inner part kept flowing.
Our companions on the road, among others: Johnny Cash (US), Pink Floyd, Muse (UK), Kruder & Dorfmeister (AT). And the Lowrider, of course.
Endless roads through forests. Desert. Lakes. Campfires. Togetherness. Happiness!
To the South.
Rock—typical Californian food—and Heineken—typical Dutch Piss. By the way, the smell in the air all around the festival area also reminded me of Amsterdam.
The music started with a horrible performance of some hip hoppers that didn’t know how to sing or even speak, but continued with cool, funky jazz by The Greyboy Allstars. Then OK Go (see one of their unique videos below), Arcade Fire, and The Black Keys (a pretty cool Ohioan band I hadn’t known before) rocked the stage.
Right on (very American) time at 8:15 the best live band in the world started playing: Muse!
Heavy rock fading into symphonic compositions with classical piano sounds supported by stunning visuals, artificial fog, and lasers—this show had everything. Not only did they play great songs (of which they have plenty, much more than would fit into a single set), their show felt like a well-planned whole, which I appreciate a lot.
Unsurprisingly, they played many songs from their new album “The Resistance”, but they did include sufficiently enough older works as well, even not-so-mainstream-popular ones. And how cool is it to play a few chords of the “House of the Rising Sun” between “Time Is Running Out” and “Starlight”?
Here is Muse propagating the “United States of Eurasia” with very nice visuals in the background:
And here they perform their probably most popular song “Starlight”:
You can also see the complete setlist.
Apart from the music, I was amazed by the fact that there wasn’t even the slightest traffic jam after the festival and all the people went home (mostly by car).
Death and reincarnation of some bitten fruit
Usually,.
Hiking Yosemite
After. | http://www.poeschko.com/blog/page/2/ | CC-MAIN-2018-05 | refinedweb | 849 | 73.17 |
.
Note: this guide requires Elixir v1.2.0 or later. You can check your Elixir version with
elixir -v this guide is in this repository and can be used as a reference. Elixir’s executable in your PATH. If not, you can run it by passing the script as argument to
elixir:
$ bin/elixir bin/mix new kv --module KV
Note that you can also execute any script in your PATH from Elixir via the -S option:
$ bin/elixir -S mix new kv --module KV
When using -S,
elixirfinds the script wherever it is in your PATH and executes it.
Project compilation
A file named
mix.exs was generated inside our new project folder (
kv) and its main responsibility is to configure our project. Let’s take a look at it (comments removed):
defmodule KV.Mixfile do use Mix.Project def project do [app: :kv, version: "0.1.0", elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps()] end def application do [applications: [:logger]] end defp deps do [] simple module definition:
defmodule KV do "the truth" do assert 1 + 1 == 2 automatically required by Mix every time before we run our tests. We can run tests with
mix test:
Compiled lib/kv.ex Generated kv app [...] . Finished in 0.04 seconds (0.04s on load, 0.00s on tests) 1 test, 0 failures Randomized with seed 540224
Notice that by running
mix test, Mix has compiled the source files and generated the application file once again. This happens because Mix supports multiple environments, which we will explore in the next section.
Furthermore, you can see that ExUnit prints a dot for each successful test and automatically randomizes tests too. Let’s make the test fail on purpose and see what happens.
Change the assertion in
test/kv_test.exs to the following:
assert 1 + 1 == 3
Now run
mix test again (notice this time there will be no compilation):
1) test the truth (KVTest) test/kv_test.exs:5 Assertion with == failed code: 1 + 1 == 3 lhs: 2 rhs: 3 stacktrace: test/kv_test.exs:6 Finished in 0.05 seconds (0.05s on load, 0.00s on tests) 1 test, 1 failure
For each failure, ExUnit prints a detailed report, containing the test name with the test case, the code that failed and the values for the left-hand side (lhs) and right-hand side (rhs) of the
== operator.
In the second line of the failure, right below the test name, there is the location where the test was defined. If you copy the test location in this full second line (including the file and line number) and append it to
mix test, Mix will load and run just that particular test:
$ mix test test/kv_test.exs:5
This shortcut will be extremely useful as we build our project, allowing us to quickly iterate by running just a specific test.
Finally, the stacktrace relates to the failure itself, giving information about the test and often the place the failure was generated from within the source files.
Environments
Mix supports later on, any dependency you add to your project will by default run in the
:prod environment.
Customization per environment can be done by accessing the
Mix.env function in your
mix.exs file, which returns the current environment as an atom. That’s what we have used in both
:build_embedded and
:start_permanent options:
def project do [..., build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, ...] end
When you compile your source code, Elixir compiles artifacts to the
_build directory. However, in many occasions to avoid unnecessary copying, Elixir will create filesystem links from
_build to actual source files. When true,
:build_embedded disables this behaviour as it aims to provide everything you need to run your application inside
_build.
Similarly,
Exploring
There is much more to Mix, and we will continue to explore it as we build our project. A general overview is available on the Mix documentation.
Keep in mind that you can always invoke the help task to list all available tasks:
$ mix help
You can get further information about a particular task by invoking
mix help TASK.
Let’s write some code! | http://elixir-lang.org/getting-started/mix-otp/introduction-to-mix.html | CC-MAIN-2016-44 | refinedweb | 695 | 65.83 |
Sometimes we need to convert text into the images on the fly. This code converts the text into image and displays it onto the web page without saving it into a file on the disk. It also takes care of text wrapping.
TextToImageConvertor can either be used in a web page or in a module. I have used this code in a web page. To use TextToImageConvertor in a module, you will need to make some changes in the step 8.
The code for TextToImageConvertor is self explanatory. However, I am going to describe this step-by-step.
Step 0 - Include Namespaces
using System.Drawing;using System.Drawing.Imaging;
Step 1 - Declare Properties
Declare some variables that will control the behavior and color of the image.
string Text = Request.QueryString["Text"]; Color FontColor = Color.Blue; Color BackColor = Color.White; String FontName = "Times New Roman"; int FontSize = 10; int Height = 150; int Width = 150;
Step 2 - Create a Bitmap Object to Hold The Image
Bitmap bitmap = new Bitmap(Width, Height);
Step 3 - Create a Graphics object using this Bitmap object
Graphics graphics = Graphics.FromImage(bitmap);
Step 4 - Create Color, Font, and PointF objects.
Color color = Color.Gray; ;Font font = new Font(FontName, FontSize);
//define where the text will be displayed in the specified area of the imagePointF point = new PointF(5.0F, 5.0F);
Step 5 - Create Brushes and Pen
SolidBrush BrushForeColor = new SolidBrush(FontColor);SolidBrush BrushBackColor = new SolidBrush(BackColor);Pen BorderPen = new Pen(color);
Step 6 - Draw Rectangle using Graphics object
Rectangle displayRectangle = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1));graphics.FillRectangle(BrushBackColor, displayRectangle);graphics.DrawRectangle(BorderPen, displayRectangle);
Step 7 - Draw Text string on the specified rectangle using Graphics object
//Define string format StringFormat format1 = new StringFormat(StringFormatFlags.NoClip);StringFormat format2 = new StringFormat(format1);//Draw text string using the text formatgraphics.DrawString(Text, font, Brushes.Red, (RectangleF)displayRectangle, format2);
Step 8 - Send the bitmap to page output stream in JPEG format
Response.ContentType = "image/jpeg";bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
Using TextToImageConvertor
TextToImageConvertor is developed as a web page which can be accessed directly by passing the text in he query string.
To demonstrate the use of this tool, create a webpage with a textbox, a button and an image control. On the click event of the button, set the image URL to the convertor page and pass the text of text box into the query string. In the example code below, I have named my image control as img1 and text box as txtNote.
img1.ImageUrl = "default2.aspx?Text=" + txtNote.Text;
Certainly its very useful. I have personally use this code and saw the usefullness. Gr8 work friend. But i still think we can skip the second page (default2.aspx)......at this point of time i dont know how but i guess there must be some way around.
In the end its a Gr8 work.
Looking forward for some more interesting code :-)
possibly vice-versa of this code (ImageToText COnvertor).
grt, small and neat. Things have realy changed from asp to asp.net in a real good way. Thats a real good finding yanesh. One question can this be used for generating bar codes?? or something else is there.
Vij,
Creating bar code is something different from creating images. In the bar code, characters (numbers) are converted into lines of specified width according to the bar code standard you are using.
Following link maybe helpful to you:
Hi,
You might be interested in this one also. We build a more extended version for generating images on the fly to replace the sIFR.
It's free, opensource and allows more options like themes, styles, mouseovers, inline images and SEO.
The project is called the bATR and code can be found at
You've been kicked (a good thing) - Trackback from DotNetKicks.com
Note that you shouldn't use GDI or GDI+ in an ASP.NET environment:
"Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions."
msdn.microsoft.com/.../system.drawing.aspx
Here's an old blog post by an MS employee about it: blogs.msdn.com/.../charting-in-asp-net-alas-dgi-not-supported-from-a-service.aspx
Hi yanesh good example..
Can we get the image with good clarity is there any way?
For creating smooth texts in the bATR I use the System.Windows.Media(WPF) classes instead of System.Drawing. After that I use the MS.Manipulation library for optimizing.
Bart
Nice Buddy!
hanks a lot for ur time and ur wrk
Hi It seems good for converting single line text into images.
But what about if we need to convert the multiline text into image ?
Anyone any idea?
Thanks
Andy
Andy,
You could use the WPF implementation where you can set a maximum width. The engine renders the multiline by itself now. (FormattedText object has a property MaxTextWidth)
Regards,
It is nice. It is also easy to convert more one lines into one image.
Good morning. Forget injuries, never forget kindnesses. Help me! Could you help me find sites on the: Eddie bauer baby crib bedding. I found only this - <a href="baby-bedding.net/">pink toile baby bedding</a>. When you feel size westerbork, learn a just sugar of the affair when you are not canceled, bedding. Bedding, with the dolphin fishing, dublin has been mentored and has a multiple male, european anonymity. Thanks :rolleyes:. Ives from Antigua.
How can we wrap long line of text over multiple lines based on specified width such as 600px then convert to image?
Hey there, You've done an incredible job. I will definitely digg it and personally recommend to my friends. I am confident they will be benefited from this website..
Hey there! Do you know if they make any plugins to assist with SEO?
I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good results.
If you know of any please share. Cheers!
I drop a leave a response when I especially enjoy a article on a site
or I have something to add to the conversation. It's a result of the sincerness displayed in the post I read. And on this post Converting Text into Image On-The-Fly - Yanesh Tyagi on ASP.Net. I was excited enough to leave a thought :-) I do have a couple of questions for you if it's
okay. Could it be simply me or do a few of these responses
look like they are left by brain dead folks? :-P And, if you
are writing at additional sites, I'd like to follow anything fresh you have to post. Would you list all of your communal pages like your Facebook page, twitter feed, or linkedin profile?
Hello there, just became alert to your blog through Google, and found that it is truly informative.
I'm gonna watch out for brussels. I will appreciate if you continue this in future. Many people will be benefited from your writing. Cheers! pay a quick visit day-to-day some sites and blogs to read articles,
except this web site provides feature based posts.
We are a gaggle of volunteers and starting a brand new scheme in our community.
Your site provided us with valuable info to work on.
You have performed a formidable activity and our entire neighborhood will likely be grateful to you.
Attractive section of content. I just stumbled upon your blog and in accession capital to assert that I acquire in fact enjoyed account
your blog posts. Any way I'll be subscribing to your augment and even I achievement you access consistently rapidly.
Hi there, I check your blogs regularly. Your story-telling style is witty,
keep it up!
Hi I am so grateful I found your blog, I really found you by accident,
while I was searching on Google for something else, Regardless.
Its such as you learn my mind! You seem to understand so much approximately
this, like you wrote the e-book in it or something. I believe that you simply can do with some % to pressure the message home a bit, however other than that, this is great blog. A great read. I will definitely be back.
Hey there! I'm at work surfing around your blog from my new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the superb work!
I think that is one of the such a lot vital info for me.
And i'm happy studying your article. However should commentary on few common issues, The website style is ideal, the articles is in reality excellent : D. Just right process, cheers
I could not refrain from commenting. Very well written!
Good info. Lucky me I ran across your blog by chance (stumbleupon).
I've bookmarked it for later!
I think the admin of this web page is really working hard in support of
his web page, as here every information is quality based stuff.
At this time I am going away to do my breakfast, afterward having my breakfast coming over again to read further
news.
Why users still use to read news papers when in this technological
world all is existing on web?, I wish for to subscribe for this weblog to get latest updates, thus where
can i do it please help.
Pretty! This has been an incredibly wonderful post.
Many thanks for supplying this information.
When I originally commented I clicked the "Notify me when new comments are added" checkbox and now
each time a comment is added I get several emails with the same comment.
Is there any way you can remove me from that service?
Bless you!
I used to be recommended this website by means of my cousin.
I am no longer sure whether or not this publish is written via him as nobody else recognise
such detailed approximately my problem. You're amazing! Thanks!
I think the admin of this site is genuinely working hard in favor
of his web site, since here every data is quality based data.
Everything is very open with a very clear description of the issues.
It was really informative. Your site is useful. Many thanks for sharing!!
It's really very complex in this busy life to listen news on Television, therefore I simply use world wide web for that reason, and get the hottest news.
I like the helpful information you provide in your articles.
I'll bookmark your blog and check again here regularly. I'm quite sure I'll learn a lot of new stuff right here! Good luck for the next!
Great article! We will be linking to this great
post on our website. Keep up the good writing. | http://weblogs.asp.net/yaneshtyagi/archive/2008/11/07/text-to-image-convertor.aspx | CC-MAIN-2013-20 | refinedweb | 1,830 | 67.15 |
Personally, I tend to always add parens to tuple expressions since it removes any and all ambiguity about when they're required or ney. I'd actually prefer it if parens were always required, but can appreciate that might/would offend those who prefer otherwise. >>> for (a, b) in d.items(): ... process(a, b) >>> def items(t): ... return (a, b) Always using parens means that when refactoring one can avoid the extra mental step of 'are the parens required in use with python feature <F>>' Additionally, in some language features, the use of parens has become required to squash warts: >>> try: ... a = b[k] >>> except (KeyError, IndexError), no_item: ... a = handle(no_item) Regards, Matt On Fri, 2010-09-17 at 12:44 -0700, Raymond Hetting. > > > Raymond > > _______________________________________________ > Python-ideas mailing list > Python-ideas at python.org > -------------------------------------------------------------- Ovi Mail: Making email access easy | https://mail.python.org/pipermail/python-ideas/2010-September/008100.html | CC-MAIN-2017-30 | refinedweb | 141 | 65.62 |
Exporting a .ufo file with fontParts doesn't create a valid file
- michelangelo last edited by gferreira
Hello there,
Frederik helped me a few months ago and using his script, I managed to save shapes as glyphs in a .UFO file but when I open them they have:
no width (I probably need to specify this when saving but I didn't know where);
you can't type with them (in Glyphs at least). I suspect the unicode names for each glyph are not specified well enough.
Everything happens in saveAsUFO(), where "bez" is my vector shape and "char" is specifying which glyph I want this shape to be saved in.
from fontParts.world import RFont import math # create a font object myFont = RFont(showInterface=False) font = "LucidaGrande" charSet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9",".",",","!","?","[","]","-","—",'“','”','‘','’','"',"'"] def calculateDistance(pt1, pt2): x1, y1 = pt1 x2, y2 = pt2 dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return dist def calculateHandles(pt1, pt2): x1, y1 = pt1 x2, y2 = pt2 dx = x2 - x1 dy = y2 - y1 offset = -0.2 # vector (y, -x) is perpendicular to vector (x, y): handleOffsetX = offset * dy handleOffsetY = -offset * dx h1Pos = 0.25 h2Pos = 0.75 h1x = x1 + h1Pos * dx + handleOffsetX h1y = y1 + h1Pos * dy + handleOffsetY h2x = x1 + h2Pos * dx + handleOffsetX h2y = y1 + h2Pos * dy + handleOffsetY return (h1x, h1y), (h2x, h2y) def extractContours(bez): contours = [] for cont in bez.contours: poly = [] for seg in cont: for pt in seg: poly.append(pt) contours.append(poly) return contours def saveAsUFO(path, char): # create a glyph object myGlyph = myFont.newGlyph(char) # get the pen myChar = myGlyph.getPen() path.drawToPen(myChar) def drawContours(contours, char): bez = BezierPath() for contour in contours: prevPoint = contour[0] bez.moveTo(prevPoint) for pt in contour[1:]: h1, h2 = calculateHandles(prevPoint, pt) bez.curveTo(h1, h2, pt) # bez.lineTo(pt) prevPoint = pt bez.closePath() drawPath(bez) saveAsUFO(bez, char) # Convert the letter into Bezier Path for i in range(len(charSet)): newPage(1000, 1000) bez = BezierPath() bez.text(charSet[i], font=font, fontSize=840) xMin, yMin, xMax, yMax = bez.bounds() cx = (xMin + xMax) / 6 cy = (yMin + yMax) / 2 bez.translate(cx, cy) contours = extractContours(bez) drawContours(contours, charSet[i]) # save the ufo # myFont.save("Bogota.ufo")
hello @michelangelo,
starting with (2): your character set is defined as unicode characters, but to create glyphs in a UFO font you need glyph names (for example AGL names, but there are other schemes like GNFUL).
to get the glyph names you’ll need to convert first from unicode characters to unicode values. in Python3 this is easy:
ord(char). then you can use the unicode value to look up the glyph name in your scheme of choice.
here’s an example using fontTools, which is embedded in DrawBot like FontParts: (see this gist)
from fontTools.agl import UV2AGL def saveAsUFO(path, char): # get unicode for character uni = ord(char) # get glyph name for unicode glyphName = UV2AGL.get(uni) # create a glyph object myGlyph = myFont.newGlyph(glyphName) # set unicode myGlyph.unicode = uni # get the pen pen = myGlyph.getPen() # draw path into glyph with pen path.drawToPen(pen)
regarding (1): you can get glyph widths by setting each character with the source font and measuring the text:
# `font` is a DrawBot command and cannot be used as variable name fontName = "LucidaGrande" font(fontName) fontSize(1000) w, h = textSize(char) myGlyph.width = w
the text font size is set to
1000because this is the default UPM size when creating a new font, and we need a 1:1 scale in order to get width value.
@gferreira Thanks a lot. Everything works now!
Follow-up questions will be:
As I have an offsetValue to tweak the bending of the letters, would it be simple to do all of this inside Glyphs? This way I can open Glyphs, tweak it as much as I want and export right away as .OTF.
Or how can I export an .OTF directly from DrawBot? I tried with myFont.generate() but something went wrong...
formats = { 'OpenType-CFF (.otf)' : 'otfcff', 'OpenType-TTF (.ttf)' : 'otfttf', 'PostScript (.pfa)' : 'pctype1ascii' } # save the ufo if ExportUFO == True: myFont.save("Bogota.ufo") for format in formats.keys(): print('Generating %s font...' % format) print(myFont.generate(formats[format])) --------------------------------------------- Generating OpenType-CFF (.otf) font... Traceback (most recent call last): File "Bogota5.py", line 126, in <module> File "/Applications/DrawBot.app/Contents/Resources/lib/python3.6/fontParts/base/font.py", line 362, in generate File "/Applications/DrawBot.app/Contents/Resources/lib/python3.6/fontParts/base/font.py", line 397, in _generate File "/Applications/DrawBot.app/Contents/Resources/lib/python3.6/fontParts/base/base.py", line 232, in raiseNotImplementedError NotImplementedError: The RFont subclass does not implement this method.
font.generateis RoboFont method and is not available inside DrawBot.
However with ufo2fdk (which is embedded into DrawBot) you must be able to generate binaries (you will need to install FDK locally)
or install
fontMakeand build a compiled font from a ufo.
good luck!!!
Im pushing you to figure it out by yourself first
see the documentation and the source of ufo2fdk
and see documentation of fontMake
@frederik Thank you, Frederik. I tried both ufo2fdk I don't how to use, the documentation is a bit confusing for me.
Anyways, with fontParts I ran the script but it gave me
KeyError: 'unitsPerEm'
Is it related to my font or to fontParts script in your opinion?
ufo2fdk needs some basic font info settings like
descender,
xHeight,
ascender,
capHeight,
unitsPerEm
# some default example values font.info.descender=-250 font.info.xHeight=500 font.info.ascender=750 font.info.capHeight=750 font.info.unitsPerEm=1000
@frederik Thank you, I managed! It works smoothly now—I was just missing the
font.familyNamebut after adding this, it works.
I was wondering if I can do it inside DrawBot right away? I tried to import
fontmakeor
ufo2ftas a module but it doesn't work. Could it be that pip doesn't install it globally and DrawBot cannot find it—if that's the case where should I put it so DrawBot can see it?
yes you can use fontMake or ufo2ft, you just have to install it locally for the python3.6 (this is the embedded python in DrawBot)
If you dont have python3.6 installed, you need to get it from.
and install fontMake and/or ufo2ft with pip3.6 for py3.6
good luck! | https://forum.drawbot.com/topic/142/exporting-a-ufo-file-with-fontparts-doesn-t-create-a-valid-file/6 | CC-MAIN-2020-16 | refinedweb | 1,088 | 58.38 |
A library that makes writing pyhamcrest matchers easier and more fun.
Project description
PyHamcrest Toolbox
PyHamcrest is a great thing for writing reusable tests, but sometimes writing your own matchers may be a bit of a chore. This project aims at making this task easy, fast and even fun (for want of a better word).
To reiterate the obvious, a test should always do all the checks it has to do, and even if some of them fail, the rest should still be run. That way you will get a better idea of what’s gone wrong with your code, and you will waste less time fixing the first of the checks only to find the the second one is still failing, and that means that you should have fixed the first one in a different way.
So, instead of this:
def test_the_holy_grail(): the_holy_grail = seek_the_holy_grail() assert_that(the_holy_grail.is_holy(), is_(True)) assert_that(the_holy_grail.depth, greater_than(5)) assert_that(the_holy_grail.width, greater_than(6)) assert_that(the_holy_grail.height, greater_than(7))
this should be written as:
def test_the_holy_grail(): the_holy_grail = seek_the_holy_grail() assert_that( the_holy_grail, is_holy() .with_depth(greater_than(5)) .with_width(greater_than(6)) .with_height(greater_than(7)) )
or:
def test_the_holy_grail(): the_holy_grail = seek_the_holy_grail() assert_that( the_holy_grail, grail(holy=True, width=5))
Both these examples, however, require writing your own matchers. With this toolbox, it is easy.
MulticomponentMatcher
The MulticomponentMatcher allows writing the chain-style matchers.
All you have to do is to write your is_holy matcher that inherits from the MulticomponentMatcher as the backbone. Then you write individual matchers for each of the holy grail properties enhancing them with the MatcherPlugin, and you register them with the is_holy matcher.
So, this is your is_holy matcher:
class IsHolyMatcher(MulticomponentMatcher): def __init__(self): super().__init__() def is_holy(): return IsHolyMatcher()
And that’s it. You don’t have to override the usual matcher methods. Everything will be done by the parent class. However, it doesn’t do any matching yet, so we need to write the plugins. Let’s start with the actual holiness:
class HolinessMatcher(MatcherPlugin): def __init__(is_holy=True): super().__init__() self.is_holy = is_holy def component_matches(self, item): # the item will be a grail return self.is_holy == item.is_holy() def describe_to(self, description): description.append_text( "A grail which is {}holy".format("" if self.is_holy else "not ")) def describe_component_mismatch(self, item, mismatch_description): mismatch_description.append_text( "The grail was {}holy".format("" if item.is_holy() else "not "))
And then you register it with the main matcher:
class IsHolyMatcher(MulticomponentMatcher): def __init__(self, is_holy): super().__init__() self.register(HolynessMatcher(is_holy)) def holy(is_holy): return IsHolyMatcher(is_holy)
Of course, you could write that HolinessMatcher logic in your IsHolyMatcher, but if we have the power of plugins, then why not use it?
For now, we only have this bit: assert_that(the_grail, is_holy()), and not the .with_width(...) stuff. So let’s write it. I won’t go through the process of writing the plugin for the width as it is rather straightforward, but here’s how you register it with the main matcher:
class IsHolyMatcher(MulticomponentMatcher): def __init__(self, is_holy): super().__init__() self.register(HolinessMatcher(is_holy)) def with_width(self, value): return self.register(GrailWidthMatcher(value)) def holy(is_holy): return IsHolyMatcher(is_holy)
Now you can do the is_holy().with_width(greater_than(5)) stuff. Note that you have to return self.register(...) from the plugin registering methods, as (a) you might want to chain them, and (b) the result of the chain still needs to be a matcher.
KwargMulticomponentMatcher
This matcher allows writing the kwarg-style matchers (as in the second example above), which are more pythonic, but look kind of unnatural when you want to match against another matcher instead of a plain value. I will show what I mean in a minute.
The general approach is the same as with the multicomponent matcher: you write matcher plugins for your components, and then you register them with your main matcher:
class GrailMatcher(KwargMulticomponentMatcher): def __init__(self, holy=None, width=None): self.register_for_kwarg(HolinessMatcher(holy), holy) self.register_for_kwarg(GrailWidthMatcher(width), width)
And then in your tests you do:
def test_correct_width_wrong_holiness(self, my_grail): assert_that( my_grail, grail(holy=True, width=4))
As I said before, this looks more pythonic, however, if you want to check your values against matchers, and not just plain values (like width=4 here), your code starts looking a bit strange:
def test_correct_width_wrong_holiness(self, my_grail): assert_that( my_grail, grail(holy=True, width=greater_than(4)))
My recommendation is to use the chain-style matchers if you know that your main matcher might be used this way.
Demos
You can find the demos for both approaches in the demo folder of this repo. Clone it, install the requirements from demo/requirements.txt, and run pytest demo/test_*
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pyhamcrest-toolbox/ | CC-MAIN-2020-45 | refinedweb | 800 | 56.05 |
In this Program, you’ll learn how to find size of operator.
Here declares 4 variables of type int, float, double and char. Then, the size of each variable is evaluated using size of operator.
To nicely understand this example to find size of operator, you should have the knowledge of following C++ programming topics:
- C++ I/O
To find the size of the variable,
size of operators is used.
sizeof(dataType);
Program to Find Size of a Variable
#include <iostream> using namespace std; int main() { cout << "Size of char: " << sizeof(char) << " byte" << endl; cout << "Size of int: " << sizeof(int) << " bytes" << endl; cout << "Size of float: " << sizeof(float) << " bytes" << endl; cout << "Size of double: " << sizeof(double) << " bytes" << endl; return 0; }
Output
Size of char: 1 byte Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes
Note: You may get a different result if you are using an old computer.
Related Programs
- C++ “Hello, World!” Program
- C++ Program to Print Number Entered by User
- C++ Program to Add Two Numbers
- C++ Program to Find Quotient and Remainder
- C++ Program to Swap Two Numbers
- C++ Program to Find ASCII Value of a Character
- C++ Program to Multiply two Numbers
Ask your questions and clarify your/others doubts on C++ Program to Find Size of operators by commenting. Documentation.
Please write to us at [email protected] to report any issue with the above content or for feedback. | https://coderforevers.com/cpp/cpp-program/size-of-operator/ | CC-MAIN-2019-39 | refinedweb | 240 | 58.96 |
Details
- Type:
Improvement
- Status: Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 2.1, 2.2
-
- Component/s: Core Java Framework
- Labels:None
Description
I process large documents--the String I pass to JCas.setSofaDataString may be as large 100 MBs (50,000,000 chars). This is causing the JVM to run out of memory when we have many concurrent AnalysisEngines running.
I traced JCas.getSofaDataString(), and it eventually calls StringHeap.getStringForCode(), which does a "new String" from it's private char[] (which does a copy).
This would happen for each annotator. We have five, so now the 100 MBs has become 600 MBs. Multiply by 10 concurrent AnalysisEngines, and that's 6,000 MBs.
Perhaps there could be a variation on getSofaDataString that returns one of the other classes (besides String) that implements CharSequence. A CharBuffer perhaps, or even a new class the implements the CharSequence interface but is read-only (just four methods). Or even just return a char[] or char[] and begin/end offset into the StringHeap.
If nothing else, perhaps the document text should be treated specially from all the little strings in the StringHeap, and be stored separately, so calls to getSofaDataString() simply return a reference to an existing String object, without copying.
I'm open to possibilities, I just need the copying to end.
Activity
- All
- Work Log
- History
- Activity
- Transitions
Eddie remarked that the JNI interface to C++ analytics and the blob serialization method both use the string heap for transfer. In those cases the CAS is delivered [or delivered back] to a Java CAS with strings in the old character array string heap. Also, there is a low-level CAS API that still creates string features in the old string heap.
One possible improvement: The java impl could change the code where it finds the "internalStringCode == null" to not only create a new Java string, but also store it in the string list, updating the heap so that future refs would find the internalStringCode != null. Serialization which used the character array format would need to be updated to not add these strings to the output twice.
Another improvement we could do that might significantly reduce storage in many common cases:
Add an "identity" hash map: key = strings being added to the string heap from Java, value = <stringCode>. This would allow sharing of things when the strings are ==, and this sharing would be preserved across serialization. An Identity hashmap would only need to hash 4 (or 8) byte "addresses", not the whole string.
Does anyone see any issues with this?
I really think completely removing the character heap would be the better solution, particularly when we'd need to adapt the serialization anyway. The low-level API we could deprecate, and internally make it use regular Strings. I don't think anybody's using it, it's not even documented. You'd need to look at the source code to know what it does.
I'm not too keen on the hash map either. We would make everybody pay for a case that doesn't concern everybody. You can use String.intern() as a programmer, if you think that's useful in your case. One might consider intern()ing strings on deserialization, but even there, I'm not sure everybody wants that (I sure hope nobody relies on Strings being equal(), but not ==, but you never know). And wrt space requirements: we would need to create an Integer object for every string code in that hash map, as primitive values can't be stored in Maps.
Changed version affected to 2.2 - based on the comments - it's not something we'll likely fix for 2.2 release. In addition to Thilo's comments, Eddie suggest that although it (removing the special support in the String Heap to store data as one big char array - something done originally to support the C++ side of the story) might make the Java <-> C++ connection (done via JNI) slower in some cases, there are better things to do to ameliorate this, including figuring out and supporting some kind of "delta CAS" approach that just sends changes. This might also allow us to move away from the JNI approach to C++ operabilty - in favor of one which would be more robust - using sockets + serialization to support running the C++ in a separate, isolated-from-Java address space.
Here's Eddie's comment from email thread:
7/9/2007 12:03 PM
I tend to agree with this. The overall design will get simpler. The
downside will be having to create all the string objects at
deserialization, but this will still leave binary serialization much
faster than XML serialization.
This issue has been fixed as a side effect of the 2.2.2 memory hotfix.
That's not really what should happen. There are two ways strings are kept in the CAS: either as String objects, or as character data. The regular APIs all use the version where the CAS simply keeps a reference to the original String object, and that's what the sofa data APIs also do (or at least I think so from eyeballing them). So there should be no copying going on, the relevant piece of code being this from StringHeap.getStringForCode():
if (internalStringCode != NULL){ return (String) this.stringList.get(internalStringCode); }
If you have traced your code in the debugger and found that this is not used, and instead the String constructor is called as you describe, it would be helpful if you could provide a test case.
The character data method of keeping string data in the CAS is obsolete. I'll see if there are any real dependencies on it, or if we can completely remove that code.
--Thilo | https://issues.apache.org/jira/browse/UIMA-483 | CC-MAIN-2017-09 | refinedweb | 957 | 62.27 |
User talk:Carlb/Archive2
From Uncyclopedia, the content-free encyclopedia
Voir aussi: Discussion Utilisateur:Carlb (currently broken)
Veja também: Usuário Discussão:Carlb
See also: User talk:Carlb
Extensions for Hikipedia
Hi, would it be possible to have a couple of new MediaWiki extensions installed on Finnish Uncyclopedia? Extensions I had in mind: CategoryTree, Renameuser, EasyTimeline, Newuserlog, Poem, DeletedContributions and Submit_In_Toolbar. Also, a new version of MediaWiki would be nice though it has nothing to do with these extensions – nor does it have any effect on us (as simple users and admins...). Finally our friends at Wikipedia would stop laughing at our 1.8alpha. Or maybe they wouldn't... :). But if we could at least have those extensions, we would be grateful. --JAT 22:17, 13 December 2006 (UTC)
Thanks for extensions and MediaWiki upgrade! Still, I'd like to ask for two changes: The icons of Submit_In_Toolbar should be on the right side of the toolbar (e.g. after the old buttons). I think they are now somewhat confusing. The second problem is about headings and [edit] links ([muokkaa] in Hikipedia). Those links are now located on the left, before actual headings. I think the old style in which [edit] link had a smaller font and was aligned to the right was better. --JAT 10:54, 15 December 2006 (UTC)
Sorry to bother you again but there are still some problems with the new MediaWiki. Mathematical expressions are not working because texvc is not installed (or doesn't work properly?). You can see the problem here. Also, wiki tables and HTML tables now have a white background instead of transparent one. We solved the problem by making the changes to common.css but I guess there is a software-related way to do handle this? And Submit_In_Toolbar icons are still located on the left side of the toolbar while the right side would suit better. Anyway, texvc is the real problem at the moment and latter two are just trivial. If you I had time to solve those two too, that'd be nice :) --JAT 17:20, 19 December 2006 (UTC)
- The math is working now, the table CSS was changed in MediaWiki (as of 1.9) in the "general" section - I've commented out that portion for now. I've asked the SubmitInToolbar author (on userpage) why icons appear on the left, so far I've received no reply. --Carlb 14:07, 21 December 2006 (UTC)
- Thanks for Submit In Toolbar 0.0.2. It works fine. One more thing (At least for now. ...These little things just keep popping up :) ) It seems that since the upgrade, MediaWiki no longer keep a record how many times a certain page is accessed. Perhaps it has something to do with PHP caching or something (just a wild guess)? Anyway, the numbers don't increase in the footer (in Tämä sivu on näytetty X kertaa or This page has viewed/accessed X times). It's not a big deal and please feel free to disable that feature altogether if there's no easy way to solve the problem. --JAT 09:42, 28 December 2006 (UTC)
- The page counters aren't just cached, they've stopped. This looks like a MediaWiki bug. There's a memory table `hitcounter` which temporarily stores the pagenumbers as the pages are viewed; this is supposed to be periodically written back to the main database. Set $wgHitcounterUpdateFreq to write to the main database on every pageview and the problem goes away - but with a penalty in speed. I've reported this issue here. --Carlb 20:45, 31 December 2006 (UTC)
Language code
The current version of wiki software changed them back to their old names. Therefore, I am here to re-suggest the changing of the following language names on *.uncyclopedia.info (and uncyclopedia.org if possible):
- zh-tw from "中文(繁體)" to "中文(正體)" ("正體" is the official name of "繁體" in Taiwan);
- zh-cn from "中文(简体)" to "中文(简化字)" ("简化字" is the official name of "简体" in People's Republic of China);
- zh-hk from "中文(繁體)" to "中文(香港)" ("hk" means "香港");
- zh-sg from "中文(简体)" to "中文(新加坡)" ("sg" means "新加坡").
--Hant 04:07, 31 December 2006 (UTC)
- The language names are in a file (languages/Names.php) which is part of MediaWiki. Looks like it got replaced when upgrading to the faster server and to MediaWiki 1.9, so any changes I'd applied previously needed to be applied again to the new version. I've made the update for uncyclopedia.info (and added suomi: to the list of valid language prefixes) but I can't change anything on uncyclopedia.org itself. That domain name was sold to Wikia in July 2006; I've therefore moved this item to Wikia's bug list so that they may address this. --Carlb 20:45, 31 December 2006 (UTC)
I think you have to reset the language code on uncyclopedia.info as I saw zh-tw became "中文(新加坡)" and not "中文(正體)". I don't know is it happen to other *.uncyclopedia.info sites. Please check it.--Hant 15:03, 2 January 2007 (UTC)
zh.uncyclopedia.info
Some user reported that new articles have no hit counts on the bottom. But the old articles have 本頁面已經被瀏覽XXX次。 (This page have been viewed XXX times) on the bottom. Can you add it back for the new articles?--Hant 23:27, 31 December 2006 (UTC)
I placed the old babel:zh-hant articles links on QuickVFD, please check it.--Hant 23:27, 31 December 2006 (UTC)
Do you know why the namespace 4 showed the name 'Uncyclopedia' when I connected to the articles of this namespace, and not the default name '偽基百科' I set in the namespaces table? The other name of namespace 4 in the namespaces table is 'Project', not 'Uncyclopedia'. --Hant 01:14, 1 January 2007 (UTC)
- Yes, QVFD is a valid place to list pages that have been moved off-wiki.
- Taiwan is now 中文(正體) on all *.uncyclopedia.info wikis.
- For namespaces, Project: is a special case as Languages.php does automatically replace a default name of Project: with the name of the project. If you have the namespace-4 set to default to something other than Project: it should work. --Carlb 20:58, 3 January 2007 (UTC)
Japanese Uncyclopedia
A happy new year, Carlb. Today, we had many troubles in Japanese Uncyclopedia. Concretely speaking, the parts of user's time zone advanced nine hours, and their edits overwrote other edits. It's settled down now. I think to report it as one of the Japanese Uncyclopedia admins. Thanks. --Kasuga 15:27, 2 January 2007 (UTC)
- Some edits listed as Jan 2 between 7:51 and 13:22 have an incorrect timestamp - these should be eight hours back. As soon as the time was corrected (set back), timestamps would appear to overlap within that one eight-hour timeframe. Everything beyond that small timeframe would appear normally. --Carlb 20:58, 3 January 2007 (UTC)
Currently, Japanese Uncylopedia uses EST timzone in sign (~~~~~). But, it is not useful in Japan. $wgLocationtimezone is wrong? I prefer 'JST' timezone ('Asia/Tokyo', 'UTC+9' etc...). Is it correctable? thanks. --話切徒 11:09, 20 January 2007 (UTC)
Nice to meet you. As for Japanese uncyclopedia, it is. Single Byte "&" is technical restrictions. It is possible to use also with an English uncyclopedia and wikipedia, and I want to use Single Byte "&" in Japanese uncyclopedia. I hope. Thank you and. --A00-h98-o9999 12:02, 5 February 2007 (UTC)
Interlanguage links
Hi Carl. All the Wikia interlanguage links have been updated, and as far as I can see everything looks correct. Let me know if you find anything we missed. I'm also hoping that this last batch will have persuaded our technical team to look into installing a system like the one you have, so we can update this ourselves in the future. That will be a lot easier than waiting for one of them to have time to do it -- sannse (talk) 18:04, 23 January 2007 (UTC)
- I'd tried them from en:/fr: and so far the only problem has been, predictably, Finland. I can't link to hiki.pedia.ws because these are pointing to Wikia's fork of the project. The rest look fine. --Carlb 19:27, 27 January 2007 (UTC)
I have sent to you yesterday a e-mail message using the Special:Emailuser on. Please check if you received that message. 555 19:46, 23 January 2007 (UTC)
- I have not received it; could you try e-mailing me directly at carlb at kingston.net? --Carlb 00:08, 26 January 2007 (UTC)
Down
Hey Carlb. The dutch version off Uncyclopedia is down, the front page (babel) is also down. Do you know what the problem is?? Greetz, Marconius 08:43, 25 January 2007 (UTC)
Hello Carlb. Japanese Uncyclopedia, too, is not working now. I am reporting it as Japanese admin. Thanks. --
| Kasuga | Talk | 12:13, 25 January 2007 (UTC)
Wrong address
The finnish interlanguage link points to a old and "abandoned" Hikipedia(fi.uncyclopedia.wikia.com, or something like that) instead of the actual Hikipedia (fi.uncyclomedia.org OR hiki.pedia.ws). Its not nice that people who find uncyclopedia funny and want to see finnish uncyclopedia will be directed to that pile of... poo?
Oh yeah! And the real Hikipedia is down, too. --Hjassan 14:46, 25 January 2007 (UTC)
- I've raised the issue of links to fi: not working on uncyclopedia.org or wikia.com many times. It would appear that Wikia is pointing these links to their fi.uncyclopedia instead of the real Hikipedia by design. I'm not sure what to do about this; I'd raised the issue here and received no response. --Carlb 00:02, 26 January 2007 (UTC)
Onziclopedie
Dag CarlB, I figured you must be the other dutchman (out of 3) around here. Wanted to tell you I degenerated to the level of Admin at the dutch site. Also wanted to ask you a few technical things later if you don't mind. But first:
- i tried to adapt the username template to a dutch template, but it doesn't work. Do you know how it can be done?
- The onziclopedie is Down :( at the moment. It has happened before. Do you know why this is?
Greetings, D.G.Neree 16:32, 25 January 2007 (UTC)
- The site appears to be back up, but {{USERNAME}} will not work without copying the sitewide javascript (and not just the template) to the onziclopedie. The template just inserts a code into the page; the java script searches for that code once the page is in the user's web browser and substitutes the username text. The MediaWiki:Uncyclopedia.js, MediaWiki:Uncyclopedia.css, MediaWiki:Common.css pages may contain things that need to be copied to nl:MediaWiki:Monobook.js, nl:MediaWiki:Monobook.css and nl:MediaWiki:Common.css respectively. --Carlb 23:59, 25 January 2007 (UTC)
- thanks, i'll try it. There is something else though.
- Every day the Onziclopedie is very slow a couple of times, mostly at the end of the afternoon, for an hour or so, but sometimes REALLY slow and then kicks me off the site. Other users encounter the same problem. Do you know why this is?
- there are a few pages from the specialpages list that i ca'nt see, like short & long articles.
- Also, i don't get a confirmation code from the system, so i'm not able to use email.
Do you know the reasons for this? I seem to be the only one with the last two problems. D.G.Neree 16:04, 7 February 2007 (UTC)
Looks like the site is down again, at least very very slow. D.G.Neree 18:26, 7 February 2007 (UTC)
- back on speed now. D.G.Neree 18:52, 7 February 2007 (UTC)
- The site has been very very slow for two days now & sometimes kicks everybody out for a few minutes or so. Are you sure there isn't a problem with the system? (Hackers or somebody else using processormemory?) I am not a computerwizard to say the least, but the admin-work is not really possible like this (& neither is editing, really). D.G.Neree 19:30, 13 February 2007 (UTC)
Down down down & out
For four (4!) days now, Onziclopedie has been hardly accessible & the situation is now like it has been for half a year: A total standstill. Which is a shame, because it was just starting to really liven up, with a few good writers contributing daily & the creation of Onwoordenboek (Undictionary). What is the use of a site if it is not functioning? Just for show? Well it's a bad show & a shame D.G.Neree 18:28, 15 February 2007 (UTC)
- Carl, I know you distrust Wikia, but if there are problems with your servers, maybe it's worth considering moving these wikis to our servers? Any Uncyclopedia community that wants to move is welcome of course, although I wouldn't want to start arguments about forks and so on. I think we both agree that one editable version of each wiki is the ideal. Regards -- sannse (talk) 21:48, 16 February 2007 )
I'm not the one that hands out the 'bot' flags, so I've moved this question here. --Carlb 19:27, 27 January 2007 (UTC)
Please
Could you delete the deleted articles from the mirrors? If you don't feel like it, could you let someone else do it? And if not, may I know why? At least at the Inciclopedia mirror. You often complain about how wikia ignores your complaints and you know how it sucks. Again I do not object the mirros, but there are issues you shouldn't avoid. So please, I'll be expecting your answer.---Asteroid B612
(aka Rataube) - Ñ 22:14, 29 January 2007 (UTC)
About Brackety thing and Other brackety thing
I get what you're trying to do, but I think they'd still work better as redirects, with the Alphabet template put on both Left-wing and Right-wing... perhaps I'll even change the gag for both into making them the keyboard keys, if I find the time... Whaddya say?—Lenoxus 02:15, 20 February 2007 (UTC)
Server problem on zh-tw Uncyclopedia
Nice to meet you. I am an administrator on zh-tw Uncyclopedia. Recently zh-tw Uncyclopedians found that the zh-tw Uncyclopedia is suffering from slow response (timeout) problem frequently these days, especially during night time of UTC+8 timezone (the timezone of greater China area). I'd like to ask what's going on these days. You may leave message at my zh-tw talkpage. --Leeyc0 12:14, 26 February 2007 (UTC)
- I'd like to ask you that if you are upgrading zh-tw Uncyclopedia, since it seems that the many pages is corrupted and become redirects. --Leeyc0 00:36, 2 March 2007 (UTC)
- At the moment, one of the two servers is down - I've reported the issue to my hosting provider and am attempting to shift the load onto the other server as much as possible in the meantime. Hopefully things will be back to normal later today? --Carlb 10:47, 3 March 2007 (UTC)
Thanks. But I found another problem today. Some MediaWiki variables aren't working. See screenshot 1 and 2 for details. --Leeyc0 07:54, 4 March 2007 (UTC)
uncyclopedia.info DNS problem
I have just found that uncyclopedia.info NS recording is pointing to localhost, which effectively blocks the access from the world (see Forum:Uncyclopedia.info DNS problem for problem description.) Thanks. --Leeyc0 14:45, 15 March 2007 (UTC)
hikipedia
Hi Carl, please see Forum:Interwiki link to fi: - in case you don't have it on watch -- sannse (talk) 13:01, 23 March 2007 (UTC)
server
Please Carl, we are in a desperate situation. Oncyclopedie is hardly accessible for 1/3 to 2/3 of the day and has been for over a month) and especially during peak hours in Holland. Is this our punishment for being so successful in the last trimester? The site is really starting to run like a devil, but for this really frustrating slowness/unaccessibility, which already caused me to severely damage or handle irreverently at least 3 laptops. D.G.Neree 20:15, 24 March 2007 (UTC)
Hard to access Japanese Uncyclopedia
Hi Carlb. It's very inaccessible to Japanese Uncyclopedia, especially, between JST's 9 PM to 4 AM in everyday. Now, we are under the critical situation that's hard to even also usual administration. Many of Japanese admins and users are not satisfied with it. Isn't it amelior:02, 26 March 2007 (UTC)
- Hello Carlb. Is it a technical problem or financial one? I can donate 100 yen every month if money is necessary. thanks. --話切徒 11:13, 27 March 2007 (UTC)
- Hi 話切徒, check my talk page. D.G.Neree wrote the brief description | 14:02, 27 March 2007 (UTC)
Thanks a lot, CarlB! We are accessing comfortably now. Hope our happiness will be kept forever. --:11, 28 March 2007 (UTC)
Vanity page?: Domiy
I've looked at the article, and the criteria for what makes a vanity page. The thing is, how can a page get google hits when it's not put on google? The page has had a good few hits I know of, and probably more I don't know of, just not from Google...
Edit: And it's been deleted within two days, despite there being a 7 day deadline to change it. Oscy 15:19, 4 April 2007 (UTC)
Down again and again
Dear Carlb, can you have a look to de Dutch Uncy?? It is totally down again. The Dutch Uncy has become a grown up Uncy at this moment but there constantly one problem: the downtime/speed. Maybe can we be transfered to the Wikia servers? Greetings from Holland, Marconius 14:58, 6 April 2007 (UTC)
- Hi Marconius. Wikia is happy to host you if that's what the community wants. As I said to the Thai Wikia on another page, my only concern is that I don't know Carl's policy on communities that move, and whether he would maintain a live competing wiki at the old address. Something for your community to discuss with him. -- sannse (talk) 11:19, 10 April 2007 (UTC)
zh.uncyclopedia.info down again
When I visit zh.uncyclopedia.info, I found that squid error of Mon, 09 Apr 2007 09:32:13 GMT by static-209-139-209-37.gtcust.grouptelecom.net (squid/2.6.STABLE9)
comes out. Does it mean all servers are down or proxy error? --Leeyc0 09:34, 9 April 2007 (UTC)
- This would mean that one of the two servers is down. 209.139.209.37 is currently operating as a Squid proxy and a database server, 209.139.209.234 is the main webserver. It would appear that .234 is the server causing the problems here. --Carlb 14:28, 10 April 2007 (UTC)
Japanese Uncyclopedia downs again
Hello Carl.
Japanese Uncyclopedia has downed now, again. Have you already run the second webserver? If the situation can't be improved even by two servers, our problem might be larger than we think. --:58, 9 April 2007 (UTC)
- Splitting part of the task onto a second server was a stopgap measure; ultimately the main server (209.139.209.234) will need to be replaced with a faster machine. Last I heard from the datacentre (Apr 4) was "Right now, deployment is estimated for later in April. If there's interest, please let us know." --Carlb 14:44, 10 April 2007 (UTC)
- Thank you for the answer, Carl. I tell our community that we must endure until the later of April. -- | 11:29, 11 April 2007 (UTC)
Hungarian Uncyclopedia
Hi! Could you please set $wgAllowUserJs to true? Thanks hu:User:Bdamokos--85.238.88.249 18:58, 10 April 2007 (UTC)
BOOOOOOOOOOOOOOOOTS
hi, I wonder what do you need to run this, I have my own at User:AntiVandalBot, but still doesn't do a shit. --Emperor Walter Humala 05:25, 14 April 2007 (UTC)
About Korean Uncyclopedia's Japanese Accounts
There are many Japanese accounts on Korean Uncyclopedia. (See ko:특수기능:Listusers.) And most of them are just "accounts", but they don't have any contributions. Do you know what happened about this? ―Emelmujiro 19:50, 14 April 2007 (UTC)
- PS. Can you fix Korean Uncyclopedia's time in signature? We need KST (UTC+9) instead of EST/EDT. ―Emelmujiro 20:31, 14 April 2007 (UTC)
- Hello Carlb. I am a user of Japanese Uncyclopedia. We and Korean Uncycloepdia has a problem.
- In ko.uncyclopedia.info, there are duplicate accounts of ja.uncyclopedia.info. (same user name and same password!). Do you know why? And is it revokable? we are discussing this problem here (same as Emelmujiro said). thanks. --話切徒 20:41, 14 April 2007 (UTC)
These should be fixed now. --Carlb 01:54, 20 April 2007 (UTC)
Server replacement
The current dedicated server pair used for the uncyclopedia.info/pedia.ws sites are rented from eSecureData in Vancouver and are:
With the constantly-increasing number of users on many of these sites, these servers are no longer adequate for our needs. They're too slow to keep up with all the demands, as many of these projects are growing rapidly. I've been asking eSecureData to switch us to servers with more memory for over two months now. Last I heard, on Apr 4, was "sometime in April" before even a server with four-gigabyte RAM would be provided.
There are a few active forum threads about this issue, including:
- On en: Forum:A lot of downtime
- On nl: Oncyclopedie:Forum:Traagheid
- On pt: Forum:Votação - Mudança de Servidor
We outgrow servers more quickly than the li'l ones outgrow clothes. We need a server which gives us room to grow and we need it now.
I've therefore ordered one of these for installation in Toronto, here. I hope to receive and deploy this server hardware by the end of this month.
My apologies. --Carlb 01:54, 20 April 2007 (UTC)
- Never mind, Carl.
- By the way, we also are discussing about it in the forum:
- On ja: Forum:アンサイクロペディアのサーバー状況
- -- | 07:32, 22 April 2007 (UTC)
Interlanguage links
Hi Carl, do you know of any interlanguage links (other than sv and cs) that currently need updating? Thanks -- sannse (talk) 15:38, 8 May 2007 (UTC)
- I thought fi. had been fixed ages ago... my mistake there. I've put that one back on the list. id. is also listed now, and KaurJmeb is looking into zh. The three new versions on your servers, I can't access. More problems? I think for now, any new non-wikia versions will have to wait until we are sure they are stable and active. All these broken links look very bad. -- sannse (talk) 14:46, 10 May 2007 (UTC)
- It looks like I made a typo in one of the URL's. As for problems, zh: is the only one that should be removed as not stable and active. It's been gone for a while now.
- I'm sure you're already aware of the situation with fi: as fi.uncyclopedia.wikia.com is your creation. There has also been no response to a request made a year ago to get the Special:Interwiki extension here, so it should be no surprise that the only project linking to your version of cs: is Brazil's Desciclopédia. --Carlb 15:29, 10 May 2007 (UTC)
- As I said, I had thought the link on fi. had been corrected, I agree it should not go to fi.uncyclopedia - that wiki was closed.
- As I understand it, our technical team have chosen to develop a different management system for interlanguage links that will be more suitable for Wikia. I don't know when this will be available, but of course I'm as keen as you for this to be and easier job!
- All of the wikia hosted versions link to the moved version of cs: I hope that you will allow the Necyklopedie community their choice in moving to Wikia and fix the links on all the wikis you host.
- The two links to your new wikis work for me now, but I still think that it would be good to wait until you have finished your server work and the sites are stable.
- By the way, you linking that discussion about the fi: wiki reminded me... you never did answer any of the points there. Perhaps you could call back there sometime?
- zh Uncyclopedia seems moved to. --Leeyc0 17:00, 16 May 2007 (UTC)
CheckUser Extention
Hello Carlb. I'm bureaucrat of Japanese Uncyclopedia. We are troubled recently by appearance sock-puppetted(bad)user. If you can, please add CheckUser Extention to Japanese version and add CheckUser right and right of additional right to me, or add CheckUser right to all of japanese bureaucrats. If you have any question please talk on My japanese talk page. Thank you. -- by Muttley 12:30, 10 May 2007 (UTC)
- As far as I know, 'steward' on the Wikimedia wikis is equivalent to 'bureaucrat' on the standard MediaWiki installation - it's the ability to add or remove any user from any of the groups. Any existing bureaucrat on ja: has (and can confer) these powers, along with sysop, bot or (now that it's installed) checkuser.
- The wikis will be being upgraded to MediaWiki 1.11alpha once the new server is deployed (likely a few days from now, server is here now and I just need to install programmes and data before taking it to Toronto). Perhaps the checkuser and confirmedit extensions (already in use on a few of these wikis) should be added to all of the others at that time? --Carlb 13:42, 10 May 2007 (UTC)
Tradition Chinese Uncyclopedia problem
Hello Carlb, I am an administrator from zh-tw. I found that the interface of zh-tw Uncyclopedia went something wrong today. When an anonymous user accesses zh-tw Uncyclopedia, the whole interface changes to English. Would you help me to check if there is something wrong? Many thanks. --Leeyc0 16:21, 16 May 2007 (UTC)
Korean Uncyclopedia has a problem
Korean Uncyclopedia has a problem. Usually the users who live in South Korea cannot access to Korean Uncyclopedia. They usually see "the browser cannot display the webpage" instead of Korean Uncyclopedia. Could you please check this? ―Emelmujiro 08:39, 18 May 2007 (UTC)
What wrong with "uncyclopedia.info"
Abnormal display :( --Hant 14:20, 19 May 2007 (UTC)
Fixed :) --Hant 14:35, 19 May 2007 (UTC)
Restoration for one week on Japanese Uncyclopedia
Hello,Carlb.My name is Nanahoshi(七星).I am SYSOP,Bureaucrat and Checkuser.
Today,I see Japanese Uncyclopedia.However, I waited considerably heavily for around 1 minute. Then,I saw Recent changes.Then I wound it up for one week, and editing returned. Why?--Nanahoshi 01:15, 21 May 2007 (UTC)(ja)
zh.uncyclopedia.info cannot upload images
Hello Carlb. Some users from zh-tw Uncyclopedia reported to me that they cannot use the upload image function and error message "Upload directory (/home/www/images/zh-tw) doesn't exist or doesn't have write permission" comes out. Would you like to help us to check for it? Many thanks. --Leeyc0 06:22, 21 May 2007 (UTC)
- It works now. I uploaded zh-tw:圖像:Igloo.jpg just as a test - which may now be deleted. --Carlb 13:58, 21 May 2007 (UTC)
oncyclopedia Neerlandica.
Hello Carl, the dutch Oncyclopedie has been down for most of the time during the last 2 or 3 days. Is there still maintenance going on? or are these baby-diseases? D.G.Neree 14:38, 21 May 2007 (UTC)
A very minor problem on zh-tw uncyclopedia
Hello Carlb, sorry for disturbing you again. I have found that the tab icon (favicon.ico) disappears, as seen on this screenshot. This is only a very minor problem, so if you are busy just ignore it. I report it just to ensure the unity of all uncyclopedia sites :). --Leeyc0 08:41, 27 May 2007 (UTC)
Japanese Uncyclopedia downs again
Hello again, Carl. Japanese Uncyclopedia still often downs. Is it because of any problem of servers? Or mediawiki's update? --:47, 30 May 2007 (UTC)
favicon.ico disappered again on zh-tw
- Thanks for fixing this issue before. But I found that favicon disappered again today. Sorry for disturbing you. --Leeyc0 10:17, 1 June 2007 (UTC)
FIELD_OTHER
FIELD_MESSAGE_relacacelrel | http://uncyclopedia.wikia.com/wiki/User_talk:Carlb/Archive2?direction=prev&oldid=3501829 | CC-MAIN-2015-35 | refinedweb | 4,809 | 74.59 |
I WANT MORE : things like executing commands from the script
I WANT MORE : things like executing commands from the script
Careful, the text talks (in an aside) about the print() function. This is _wrong_, there is a print _statement_, but no print() function.
Once more, a slight confusion over statements and expressions leads me to point out that, although the article says, "Well, comparison operators come in very useful when building conditional expressions - and conditional expressions come in very useful when adding control routines to your code," Python does not have conditional expressions, only conditional staements.
In this, Python is unlike Perl or C. Pythonistas claim this makes the resulting code more readable.
Very good tutorial. Just a comment on:
> Since Python does not support PHP-or
> JSP-style "switch/case" conditional
> statements, the "if-elif-else" construct
> is the only way to route program
> control to multiple code blocks.
Python provide simple enough function pointers to implement switch/case in a
more elegant way than a long if/else.
But maybe this is advanced code:
def work():
print "Ahiho"
def fun():
print "Yuk"
>>> tasks = {'monday':work,'tuesday':work,'sunday':fun}
>>> tasks['monday']()
AhiHo
Why doesn't python allow wrapping around of text when there is an if block indented. It gives an error.
whitespace is significant. try the line continuation \
Thank you for the inro to Python.
I enjoyed it. Please keep these type
of tutorials coming.
Abe Almonte
InktomiSearch uses python as its scripting language. I've been trying to hack that up a bit but not being familiar wtih python, I was breaking stuff constantly. This series is a great quick intro to the language. Much appreciated!
Python is like one of those languages that you don't hear of until you get deep into Geekdom. I've been working in the IT industry for a long time, and I've never actually seen it being used. Is this like a cult language (The Black Sabbath of 'puter languages)??
Vikram,
Presumably the semicolon at the end of:-
else:
print ("Finally! A user with active brain cells!");
is a mistake?
So,
>>>>> str[:7]
'hobgobl'
Since str[0] is 'h', either the second value of the slice is a counter or the slice means from the first value up to [but not including] the second.
>>> str[3:3]
''
>>> str[3:4]
'g'
Ok, so the slice is:-
[from:to but not including]
Not a problem, but it's certainly different from what I expected.
Python 101 \(part 2\): If Wishes Were Pythons
Begin your tour of Python with a look at its number and string types, together with examples of how they can be used in simple Python programs. Along the way, you'll also learn how to build conditional expressions, slice and dice strings, and accept user input from the command line.
Please discuss this article in this thread. You can read the article here . | http://forums.devshed.com/development-articles/63038-python-101-2-wishes-pythons-last-post.html | CC-MAIN-2016-40 | refinedweb | 487 | 72.26 |
Hi
This is my 2nd attempt get an answer to my question. Hopefully it's the right sort of question(!)
I have a document library in one site collection that I want to display in a DataView sitting on on another a site in a separate site collection.
I am using the following data source pointing at a document library via ........ /_vti_bin/Lists.aspx
I am seeing some odd behaviour when @ows_FileRef displayed after I pull in List data from a document library on another site collection in DVWP.
DVWP fragment
<td class="ms-vb" style="width: 203px">
<a href="{@ows_FileRef}"><xsl:value-of</a>
</td>
Should just display #15/sites/home/mysite/nameofdoc.docx … ( yes I know I need to clean this up)
Instead when I click on the link in the DVWP sitting on the test site
I get…
This of course will give an error. So why is SharePoint prefixing the file
url in DVWP with the current site url not just
what is passed back from my datasource web service.
There is probably some simple answer to this ........
Hi I have now been able create a valid url to the remote document library with a little help from a dvwp/xslt/DOM genius (Raymund M)! I did have a bit of fun figuring out how to pass the xslt parameters to it tho.
/*
*
* fullLink - is ows_FileRef as passed from the GetListItems web service
short link - is ows_LinkFileName as passed fromt the GetListitems web service
*/
function GenerateFilePath(fullLink,shortLink) {
return ("<a href='" + location.protocol + "//" + location.host + "/" + fullLink + "'>" + shortLink + "</a>");
}
Enjoy
Daniel
Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site.
Would you like to participate? | https://social.msdn.microsoft.com/Forums/sharepoint/en-US/c095406b-893d-4754-a714-b94367c9e035/owsfileref-is-ok-but-is-being-prefixed-by-the-current-site-url?forum=sharepointcustomizationprevious | CC-MAIN-2018-05 | refinedweb | 304 | 60.85 |
If you use make-kpkg to build your kernels and you’re running Lenny you may have had problems building 2.6.34 when it came out. With kernel-package version 11.015 I’m getting the following error:
The UTS Release version in include/linux/version.h "" does not match current version: "2.6.34" Please correct this
I’m sure more recent packages have this bug squashed but on Lenny it’s still a problem. What’s happening is make-kpkg is looking for a version string in $(KERN_ROOT)/include/linux/version.h and it’s not there. Every once in a while the kernel maintainers move stuff around and that’s exactly what happened. The UTS_RELEASE definition was moved from $(KERN_ROOT)/include/linux/utsrelease.h to $(KERN_ROOT)/include/generated/utsrelease.h
I found it confusing that the error message lists the version.h file. Turns out this definition has been moved before and when make-kpkg can’t find it in $(KERN_ROOT)/include/linux/utsrelease.h it falls back to version.h in the same directory. So we fix it with a quick patch.
--- ./version_vars.mk 2008-11-24 12:01:32.000000000 -0500 +++ ./version_vars.mk.new 2010-06-29 21:51:50.000000000 -0400 @@ -138,10 +138,10 @@ EXTRAV_ARG := endif -UTS_RELEASE_HEADER=$(call doit,if [ -f include/linux/utsrelease.h ]; then - echo include/linux/utsrelease.h; +UTS_RELEASE_HEADER=$(call doit,if [ -f include/generated/utsrelease.h ]; then + echo include/generated/utsrelease.h; else - echo include/linux/version.h ; + echo include/linux/utsrelease.h ; fi) UTS_RELEASE_VERSION=$(call doit,if [ -f $(UTS_RELEASE_HEADER) ]; then grep 'define UTS_RELEASE' $(UTS_RELEASE_HEADER) |
Down load version_vars.mk.patch. Copy this patch to /usr/share/kernel-package/ruleset/misc/ and apply it:
zcat version_vars.mk.patch.gz | sudo patch -p1
If you’ve already tried to build your kernel and had it fail because of this bug you should copy the version_vars.mk we just patched to $(KERN_ROOT)/debian/ruleset/misc/ and run make-kpkg again. This should keep you from having to rebuild the whole kernel … which takes an age on my laptop.
Can’t wait for Squeeze to go stable but that always comes with a whole set of new problems 🙂 | https://twobit.org/2010/06/ | CC-MAIN-2019-26 | refinedweb | 366 | 53.78 |
A Warning About Overloading Methods in Java
A Warning About Overloading Methods in Java
Autoboxing and method overloading can be useful when building a Java app. But sometimes these features can cause confusion, improper outputs, or errors, if not handled carefully.
Join the DZone community and get the full member experience.Join For Free
Before Java 1.5, primitive types were completely different from reference types. The introduction of the autoboxing feature has made this difference dissapear after Java 1.5. But, it has brought many problems, also.
import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; public class SetAndList{ public static void main(String[] args) { Set<Integer> set = new TreeSet<Integer>(); List<Integer> list = new ArrayList<Integer>(); for (int i = -2; i < 3; i++) { set.add(i); list.add(i); } for (int i = 0; i < 3; i++) { set.remove(i); list.remove(i); } System.out.println(set + " " + list); } }
Many of us might think that the output of the above code would print:
[-2, -1] [-2, -1]
But unfortunately, the above code works in a different way, and actually produces the following output:
[-2, -1] [-1, 1]
We can explain the above situation with the careless usage of "autoboxing," which has entered our lives since Java 1.5, as well as "overloading" features.
With the line "set.remove(i)" in the above code, the "remove(E)" method is called. Here "E" is the element type of Set which is "Integer" and the int value is converted to "Integer" with the help of autoboxing feature. And as a result, the code removes positive values from the set as expected.
On the other hand, with the line "list.remove(i)" in the above code, the overloaded "remove(int i)" method is called. This method removes the value in the index "i". So, when the content of "list" is [ -2, -1, 0, 1, 2 ], the above code first removes the element in the index "0", then index "1" and then "2". At the end of the iteration, the content of the list remains [-1, 1]. In order to avoid confusion here, we should cast "i", in the line “list.remove(i)”, to "Integer" to make the rightly overloaded method called.
for (int i = 0; i < 3; i++) { set.remove(i); list.remove((Integer)i); // or list.remove(Integer.valueOf(i)); }
After this correction, the program output can be as expected.
[-2, -1] [-2, -1]
In the above code, the compiler confuses the overloaded "remove(E)" method of the List interface with overloaded "remove(int)" method of the same interface, because of the autoboxing feature. Hence, we can say, generic and autoboxing concepts has ruined the List interface since Java 1.5.
The lessons here can be summarized as follows:
Being able to overload our methods in our Java classes does not mean that we should overload them.
Generally, we should avoid overloading our methods, containing the same number of parameters. So we should give different and meaningful names to our methods. If we insist on overloading, then we must pay attention to make our methods show the same behavior.
In case they do not pay attention to the above items, we need to tell those coders new to overloaded methods to be careful while using methods. Otherwise, they may find it hard to understand why they do not work.
Resources
Polymorphism in Java – Method Overloading and Overriding
Efective Java 2nd Edition, J. Bloch
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/java-notes-overloading | CC-MAIN-2019-39 | refinedweb | 597 | 65.42 |
Red Hat Bugzilla – Bug 569833
Review Request: drupal6 - An open-source content-management platform
Last modified: 2010-10-26 14:02:27 EDT
Equipped with a powerful blend of features, Drupal is a Content Management
System written in PHP that can support a variety of websites ranging from
personal weblogs to large community-driven websites. Drupal is highly
configurable, skinnable, and secure.
This is a parallel installable version intended only for EL-5, based on the rawhide version.
SPEC:
SRPM:
Is there a reason why you don't just update drupal in EL-5 to drupal 6?
(Couldn't find something relevant on the blocker bug.)
Because we try to do major updates to EPEL packages as little as possible, especially incompatible ones (modules, plugins, etc). Having a parallel installable version allows admins to migrate more easily. I anticipate using version 6 for the main drupal package in EL-6.
Also, I've updated the version :
SPEC:
SRPM:
Not related to this review, but I have potential module and theme specfiles available here:
If anyone is willing to look and/or edit to meet the requirements of this parallel installable drupal6 plus the existing drupal in EL-5, I'd appreciate it.
Not saying this is wrong, but why is the drupal-files-migrator.sh included as a %doc?
Also - any thought on moving .htaccess functionality to the .conf files already included? There's also a problem with that .htaccess file, a closing quote is missing on line 22.
FIX: rpmlint must be run on every package. The output should be posted in the review.
[ke4qqq@nalleyx60 SPECS]$ rpmlint drupal6.spec
drupal6.spec:52: W: macro-in-comment %{_localstatedir}
drupal6.spec:52: W: macro-in-comment %{name}
drupal6.spec:52: W: macro-in-comment %{buildroot}
drupal6.spec:52: W: macro-in-comment %{drupaldir}
0 packages and 1 specfiles checked; 0 errors, 4 warnings.
[ke4qqq@nalleyx60 SPECS]$ rpmlint ../SRPMS/drupal6-6.16-1.fc13.src.rpm
drupal6.src: W: spelling-error %description -l en_US weblogs -> we blogs, we-blogs, web logs
drupal6.src: W: spelling-error %description -l en_US Drupal -> Drupelet, Drupe, Druidical
drupal6.src: W: spelling-error %description -l en_US skinnable -> winnable, scannable, skinniness
drupal6.src:52: W: macro-in-comment %{_localstatedir}
drupal6.src:52: W: macro-in-comment %{name}
drupal6.src:52: W: macro-in-comment %{buildroot}
drupal6.src:52: W: macro-in-comment %{drupaldir}
1 packages and 0 specfiles checked; 0 errors, 7 warnings.
[ke4qqq@nalleyx60 SPECS]$ rpmlint ../RPMS/noarch/drupal6-6.16-1.fc13.noarch.rpm
drupal6.noarch: W: spelling-error %description -l en_US weblogs -> we blogs, we-blogs, web logs
drupal6.noarch: W: spelling-error %description -l en_US Drupal -> Drupelet, Drupe, Druidical
drupal6.noarch: W: spelling-error %description -l en_US skinnable -> winnable, scannable, skinniness
drupal6.noarch: W: non-etc-or-var-file-marked-as-conffile /usr/share/drupal6/.htaccess
drupal6.noarch: E: non-standard-dir-perm /var/lib/drupal6/files/default 0775L
drupal6.noarch: E: executable-marked-as-config-file /etc/cron.hourly/drupal6
drupal6.noarch: E: non-standard-dir-perm /var/lib/drupal6 0775L
drupal6.noarch: E: non-standard-dir-perm /var/lib/drupal6/files 0775L
drupal6.noarch: E: htaccess-file /usr/share/drupal6/.htaccess
1 packages and 0 specfiles checked; 5 errors, 4 warnings
Why is the .htaccess file marked as a conf file?? Generally .htaccess stuff is frowned on in favor of using the .conf files. Not a blocker, but just for your consideration.
The spelling errors are false positivies.
Macro in comment can be silenced by removing the commented out symlink line in %install. Doesn't bother me terribly though.
OK: The package must be named according to the Package Naming Guidelines .
Seems ok per
OK: The spec file name must match the base package %{name}, in the format %{name}.spec unless your package has an exemption.
MUST: The package must meet the Packaging Guidelines
OK: The package must be licensed with a Fedora approved license and meet the Licensing Guidelines .
Source says only GPL
There is a license file that contains the content of LGPLv2
I think that makes it GPL+
FIX: The License field in the package spec file must match the actual license.
Source code only says GPL - which when reading the GPL+ entry here:
Seems to indicate that GPLv2+ is an incorrect entry.60 SOURCES]$ md5sum drupal-6.16.tar.gz*
bb27c1f90680b86df2c535b2d52e8021 drupal-6.16.tar.gz
bb27c1f90680b86df2c535b2d52e8021 drupal-6.16.tar.gz.
OK: Packages must NOT bundle copies of system libraries.
Note jquery is bundled, but it is a javascript library, which based on my understanding since no packaging guidelines for javascript exist at the moment, this is permissible. However, going forward this may change..
FIX: A Fedora package must not list a file more than once in the spec file's %files listings.
warning: File listed twice: /usr/share/drupal6/.htaccess looking at this. I've updated to 6.17.
WRT .htaccess, I'm just basically trying to stay close to upstream. I've heard a lot from Drupal users on both sides of the issue..
WRT the license, the code doesn't specify, but refers the reader to the LICENSE.TXT, which specifies GPLv2. I could see using GPLv2, but not just GPL. Updated.
SPEC:
SRPM:
Are drupal6 modules going to be handled through namespace, like drupal6-cck?
That was my plan, in lieu of any alternative. That seems to work acceptably for the drupal modules, and allows for individual updates.
Of course, since I maintain all the drupal modules (I think) as well as drupal, "plan" may be a bit strong. I'm always open to suggestions. :) I took a gander at the templates you linked to, and they look useful. I don't think we currently package any themes, as of this writing.
(In reply to comment #5)
> Thanks for looking at this. I've updated to 6.17.
>
> WRT .htaccess, I'm just basically trying to stay close to upstream. I've heard
> a lot from Drupal users on both sides of the issue.
worksforme
>
>.
Completely up to your discretion, I was just curious.
>
> WRT the license, the code doesn't specify, but refers the reader to the
> LICENSE.TXT, which specifies GPLv2. I could see using GPLv2, but not just GPL.
> Updated.
So
Contains the following text:.
So grepping (-ir) source code for license or GPL and ignoring LICENSE.txt I get the following results:
./includes/xmlrpc.inc: * This version is made available under the GNU GPL License
./index.php: * All Drupal code is released under the GNU General Public License.
./misc/jquery.form.js: * Dual licensed under the MIT and GPL licenses: (NOTE: this is a completely different program)
./misc/jquery.js: * and GPL (GPL-LICENSE.txt) licenses. (NOTE: this is a completely different program)
Based on the above from the Licensing page (which I understand came from the FSF) the license field should GPL+ (I also installed to see if perhaps the program referenced LICENSE.txt and pulled in the license in 'program output' but to the best of my knowledge it does not.) And the fact that in source code/program output/accomplanying docs that there is no version declaration is how I arrived there. I fully agree that their intention is GPLv2, however the implementation has been GPL+.
Also I still see this when building the RPM:
warning: File listed twice: /usr/share/drupal6/.htaccess
Fixed license tag, you make a good case. Do you know an elegant way to fix the duplicate listing, or just drop the wildcard and enumerate the rest of the contents of the directory?
Butting in since there's been no response. I think dropping the wildcard and enumerating is probably the cleanest route.
(In reply to comment #9)
> Fixed license tag, you make a good case. Do you know an elegant way to fix the
> duplicate listing, or just drop the wildcard and enumerate the rest of the
> contents of the directory?
Paul: Thanks for bumping this back up on my radar.
Jon: I don't know a nice elegant way to do so - but I do honestly wonder about saying it's config file which is a possible source of the problem. While I don't necessarily disagree - I wonder if in the future (since you are relying on the .htaccess file for some measure of security, if it's not a better idea to drop %config(noreplace) Directory structure would then be left open to problems.
If you think that it is a config file, then I think you'd have to move it to /etc/ and symlink
The above says /usr shouldn't contain config files.
Also can you post a link to updated spec and srpm?
SPEC:
SRPM:
David, you raise an interesting point. Looking at said file, I don't really see a reason for it to be a config file. If you(the admin) want to add directives, could you not craft your own file and drop it in /etc/httpd/conf.d/?
That's certainly what I'd do.
With the full knowledge that Jon is indeed doing the work here and I'm just a bystander (although an interested one!) :-) I would note that if this .htaccess file is meant to be altered, it really should live in %{_sysconfdir}. Out of the box, I would guess a substantial number of users will edit it to allow URL rewrites, which is really desirable in lots of places.
Symlinking this to something like %{_sysconfdir}/httpd/conf.d/drupal6-site.conf would suffice, right? I sure wouldn't advocate trying to munge the content into the existing drupal.conf file, seems like an unnecessary maintenance load.
Any further progress on this one?
Jon:
Just trying to push this back up. Any thoughts on this?
I'll add that if I were to vote on a solution, encapsulating the .htaccess in the .conf file would be my choice, but I am not doing the work.
Sorry for the delays, life and all. I also deliberated on the merits of Plan Frields vs. Plan Nalley for a bit too long.
After much internal bikeshedding, here's an updated version, implementing Plan Frields.
SPEC:
SRPM:
I hate packaging webapps. But someone has to. :(
Well, now I get to both eat crow and be hoist with my own petard. This error now happens using the new /etc/httpd/conf.d/drupal6-site.conf:
Syntax error on line 103 of /etc/httpd/conf.d/drupal6-site.conf:
RewriteBase: only valid in per-directory config files
Which, AIUI, means the rewrite *has* to be done in /usr/share/drupal6. Jon, my apologies for not realizing that and for causing you extra work. I hereby lash myself 50 times with a wet noodle and encourage you to ignore me in this bug from here on out. :-)
So the problem is that the .htaccess file bears .conf at the tail of the file name and is in /etc/httpd/conf.d/ Any file bearing .conf in that directory apache will treat as a part of it's configuration, and try to parse it on startup. If you want to continue on this route (and nothing wrong with it) essentially your choices are to move it to /etc/drupal6 or rename the file to end in something other than .conf (perhaps drupal6-site.htaccess)
Thanks for figuring out this problem, David. So this spec file should work then?
(Posted these to save Jon 5 minutes... every little bit helps, right?)?
(In reply to comment #20)
> Thanks for figuring out this problem, David. So this spec file should work
> then?
>
>
>
>
> (Posted these to save Jon 5 minutes... every little bit helps, right?)
That looks sane on first blush - I'll try it out tomorrow.
(In reply to comment #21)
>?
since there are only three directories, would it be better/easier to use semanage like this in %pre?? (I am partially asking this for my own edification, I don't claim to know the correct answer)
semanage fcontext -a -t httpd_var_run_t %{_sysconfdir}/%{name}/ > /dev/null 2>&1 || :
semanage fcontext -m -t httpd_var_run_t %{_sysconfdir}/%{name}/ > /dev/null 2>&1 || :
I don't see this addressed in the packaging guidelines anywhere.
No these should be in the policy package.
Fixed in selinux-policy-3.8.8-17
Jon:
Thoughts on Paul's changes?? They look sane to me and work, and provided you have no objection, I am inclined to approve the package.
I approve, they look good. If you'll do the honors, I'll move forward. Thanks for the review, and your patience therewith.
APPROVED
New Package SCM Request
=======================
Package Name: drupal6
Short Description: An open-source content-management platform
Owners: limb
Branches: EL-6 EL-5
InitialCC:
Does this need to have a devel branch? I mean, it won't hurt, but. . .
Thanks all!
Git done (by process-git-requests).
There will be a devel branch automatically.
You should mark it a dead.package and get it blocked there, since this is only for
EPEL.
FYI, this is waiting on this:
A small change that has to be made to the package before its imported is that the package needs to make and own /etc/drupal6/all/{modules,themes} and what ever extra directories may be required there.
Good timing, I was just trying the manual fix from 619979, and I can't get it to build. I'll add that change.
drupal6-6.19-1.el5 has been submitted as an update for Fedora EPEL 5.
Built for EL-5 and EL-6, Bodhi'd for EL-5. Thanks Jesse!
drupal6-6.19 drupal6'. You can provide feedback for this update here:
drupal6-6.19-1.el5 has been pushed to the Fedora EPEL 5 stable repository. If problems still persist, please make note of it in this bug report. | https://bugzilla.redhat.com/show_bug.cgi?id=569833 | CC-MAIN-2018-39 | refinedweb | 2,305 | 68.36 |
The unification of OO and functional paradigms in Scala is managed by an advanced static type system -
- Scala supports algebraic data types, that can be decomposed for pattern matching as found in functional languages.
- Scala also offers class hierarchy based static typing of object oriented languages
Thus Scala can express both closed and extensible data types, and also provides a convenient way to exploit run-time type information in cases where static typing is too restrictive.
Numbers are Objects
Java distinguishes numeric types from objects - Scala does not.
e.g. In the following expression
1 + 2 * 3 / x
Scala sees it as
1.+(2.*(3./(x)))
It treats every number as an object and every operator as a method invoked on that object. Operators and identifiers are never distinguished - they can either be a sequence of letters and digits which begins with a letter or a sequence of special characters, such as “+”, “*”, or “:”. A binary operation
1 + 2is interpreted as
1.+(2), which is interpreted as invocation of the method "+" on integer value 1.
Similarly the concatenation operator "::" of a List follows the same principle -
val nums = 1 :: 2 :: 3 :: 4 :: Nil// adopted from [Scala By Example]
is equivalent to
val nums = 1.::(2.::(3.::(4.::(Nil))))
Functions are Objects
Since Scala supports functional programming, functions are treated as first class objects in Scala. Functions can be passed as arguments to other functions (Higher Order Functions), they can be used as values as well. Let us look at the anatomy of the sort function from [Scala By Example].
def sort(xs: List[int]): List[int] =
if (xs.length <= 1) xs
else {
val pivot = xs(xs.length / 2);
sort(xs.filter(x => x < pivot))
::: xs.filter(x => x == pivot)
::: sort(xs.filter(x => x > pivot))
}
Listof
int.
filter. The
filtermethod of the
Listaccepts a Predicate and returns a list of elements for which the predicate evaluates to true. It has the signature
def filter(p: t => boolean): List[t]
Here, t => boolean is the type of functions that take an element of type t and return a boolean. Functions like filter that take another function as argument or return one as result are called higher-order functions.
Experienced Java programmers must now be wondering about the black magic going on behind the predicate implementation. Actually it is bread-and-butter stuff for functional programming - Closures at work! The argument to filter is an anonymous function (a function defined without a name), which is created on the fly and has access to the enclosing lexical scope, through which it gets the variable
pivot. The argument to the first
filtercall,
x => x <= pivotrepresents the function that maps its parameter
xto the boolean value
x <= pivot. The function returns true if
xis less than or equal to the
pivot, false otherwise. Also, we have an implicit iteration going on here within
filter, where each value fetched is put into
x. The Scala compiler is smart enough to infer the type of
xfrom the context, the user does not have to provide it explicitly.
Try implementing the same in Java or C++ - you won't be disappointed that you have come this far in this entry!
Closures in Scala Stand Out
Closures are offered by all functional/hybrid languages, but the one from Scala implements one of the best approaches for lazy evaluation of expressions.
Let us look at an example from the Scala world -
object TargetTest1 extends Application {
def whileLoop(cond: => Boolean)(body: => Unit): Unit =
if (cond) {
body
whileLoop(cond)(body)
}
var i = 10
whileLoop (i > 0) {
Console.println(i)
i = i - 1
}
}
In the above example, when the method
whileLoopis applied, the actual arguments are NOT evaluated immediately. Instead they are encapsulated within nullary functions and passed as the corresponding actual parameters - the classic call-by-name evaluation. Scala's automatic closures allow building new control structures avoiding the need for the caller to explicitly state that an expression must be evaluated lazily.
Let me end this post with a comment from Gilad Bracha on the strengths of Scala ...
The next post on Scala will talk about the Class abstraction and two of its composition mechanisms - Mixins and Traits.
2 comments:
Very nice! I found a place where you can
make some nice extra cash secret shopping. Just go to the site below
and put in your zip to see what's available in your area.
I made over $900 last month having fun!
make extra money
So much for your captchas :) | http://debasishg.blogspot.com/2006/03/scala-everything-is-object.html | CC-MAIN-2017-39 | refinedweb | 749 | 53.92 |
Ok, I am creating functions to be used with a game title server. This server uses plug ins. I've these characteristics wich make use of a sqlite database, together with apsw to retrieve products saved by another function. I've 3 questions about this.
Question One: I keep obtaining the error "SQLError: near "?": syntax error" Since my statement features multiple ?, its showing hard tot rack lower what's exactly wrong.What exactly is wrong?
Question Two: I understand about SQL-Injection, however these functions just take input in the runner from the script, and also the only stuff he'd be harmful is their own. Nevertheless, can there be a good way to create this sql-injection proof?
Question Three: Can there be in whatever way to create this function more effective?
This is actually the function: EDIT:Heres what it really appears like now:
def readdb(self,entry,column,returncolumn = "id,matbefore,matafter,name,date"): self.memwrite if isinstance(entry, int) or isinstance(entry, str): statement = 'SELECT {0} FROM main WHERE {1} IN {2}'.format(returncolumn,column,entry) self.memcursor.execute(statement) blockinfo = self.memcursor.fetchall() return(blockinfo) if isinstance(entry, tuple) or isinstance(entry, list): statement = '''SELECT {0} FROM main WHERE {1} IN (%s)'''.format(returncolumn,column) self.memcursor.execute(statement % ("?," * len(entry))[:-1], entry) blockinfo = self.memcursor.fetchall() return(blockinfo
This really is funny (read onto discover why).
The very first statement you've really uses the worthiness binding mechanism from the
sqlite3-module (I suppose that's that which you use). Hence, the
* (the default column) will get steered clear of, making the statement invalid. This really is SQL-injection proof, as well as your own code attempts to inject SQL (begin to see the funny now?).
The 2nd time you utilize Pythons string alternative to be able to build the query string, which isn't SQL-injection proof. | http://codeblow.com/questions/3-questions-including-python-and-sqlite/ | CC-MAIN-2017-51 | refinedweb | 314 | 50.12 |
Learning Java/Decision Structures
Intro[edit | edit source]
Control flow blocks are basically blocks of code that control the way data flows, or else which statements are executed when. This can be useful if you only want certain areas of your code to be executed under a given condition.
There are two major types of decision structures: conditionals and loops. Code contained in a conditional block may or may not be executed; the decision is made at runtime based on a given condition. Code contained in a loop is repeated; how many times is also decided at runtime.
The
boolean Primitive[edit | edit source]
Java has a specific kind of variable for determining whether something is true or false, called a
boolean. A
boolean type can be defined with a boolean literal (
true or
false), or by evaluating an expression with a boolean operator.
Boolean Operators[edit | edit source]
These can be used to check if something is true or false. Most take numeric variables (
byte,
short,
int,
long,
float, or
double) and evaluate to a
boolean. Note that booleans are variables. Here is a list of all boolean operators:
As you can see above, and, or, and not are the only operators that work on booleans. These, essentially, create new booleans. For example, if you said:
boolean b1 = false; boolean b2 = true; boolean b3 = b1 || b2; boolean b4 = b1 && b2;
In this example, b3 would be true (because one of b1 and b2 are true) and b4 would be false (because b1 and b2 are not both true).
Finally, you can do:
int i1=5; int i2=5; int i3=7; int i4=3; boolean b1 = i1 < i2; // i1 is not less than i2 (both are 5), so b1 is false boolean b2 = i1 == i2 && i3 > i2; // b2 is true because i1 is equal to i2, and i3 is greater than i2 boolean b3 = i4 < i3 && i1 > i3; // b3 is false - i4 is less than i3, but i1 is NOT greater than i3 boolean b4 = i4 < i3 || i1 > i3; // b4 is true because i4 < i3. Only one is needed because it is an || boolean b5 = (i4 < i3 && i3 < i2) || i3 > i1; // See below for info on parentheses boolean b6 = !true; // This is false because !true is false, and !false is true.
Expressions within parenthesis are always evaluated first, from inside to outside. Ample use of parentheses can greatly clarify your intent. For example, consider the following code:
boolean a = true; boolean b = true; boolean c = false; boolean result = a || b && c;
What value is stored in
result? If the or is evaluated first, then the result is
false, because the code would evalute to
a || b && c true || true && false true && false false
If the and is evaluated first, though, the result is
true:
a || b && c true || true && false true || false true
There are rules governing which operators are evaluated first. You could remember that logical and has a higher precedence than logical or (that is, and is evaluated first), you could look it up, or you could just use parentheses! Then you don't have to bother memorizing operator precedence, or waste time checking a table.
Besides, what if you wanted the or evaluated first? You're sunk... or you could add parentheses to ensure that the or is first:
boolean result = (a || b) && c;
This will force the or to evaluate first, and be sure that anyone reading your code will know what you mean.
You will learn below how these boolean operators can be used inside control flow blocks.
If/Else[edit | edit source]
You have seen this statement used in the previous section:
if (ourShip.speed < 10) ourShip.mainThrustPulse(2);
"ourShip.speed<10" is a boolean. If it is true, then it will do what comes after. Note that ourShip.speed and "10" are not booleans. The < makes a boolean if the speed is less than 10. If you did the following:
if (true) ourShip.mainThrustPulse(2);
Guess what - it would automatically go to the preceding statement. Note that this can only be used for one statement. If you want to execute multiple statement for a given condition you can do:
if (CONDITION) {//THEN... //DO SOMETHING //DO SOMETHING2 }
Everything within { and } is executed if CONDITION is true. Now, suppose you want multiple if statements. You could have separate if statements, however if the conditions are exclusive (meaning that one or the other can be true but never more than one) then you can do:
if (CONDITION) { //DO SOMETHING } else if (SECOND CONDITION) { //DO SOMETHING DIFFERENT } else if (ANOTHER CONDITION) { //DO SOMETHING ELSE }
To execute a block of code when the condition of the if statement is false the following code can be used:
if (CONDITION) { //DO SOMETHING } else { //DO SOMETHING ELSE; }
Back to our ship. Lets make an if/else block that does: "If the ship's speed is less than 10, fire 2 pulses. If it is less than 15, fire one. Otherwise, lower the speed by firing backwards (-1)"
if (ourShip.speed < 10) { ourShip.mainThrustPulse(2); } else if(ourShip.speed < 15) { ourShip.mainThrustPulse(1); } else { ourShip.mainThrustPulse(-1);//Slow down }
Answer:
if (i1 == i2) { System.out.println("Equal"); } else { System.out.println("Not equal"); }
Some examples of the usage of else/if:
public class Examples { public static void main (String[] args) { int i1 = 7; //1. Check if an integer is equal to 1 if (i1 == 1) { System.out.println("Step 1 - Equal"); } else { System.out.println("Step 1 - Not Equal"); } //2. Check if an integer is equal to 6 then 7 if (i1 == 6) { System.out.println("Step 2 - Equal #1"); } else if (i1 == 7) { System.out.println("Step 2 - Equal #2"); } else { System.out.println("Step 2 - Not Equal"); } } }
If you compile this, the result should be:
Step 1 - Not Equal
Step 2 - Equal #2
Note that any code for the "Ship" cannot be executed because that class does not exist and neither does the value "speed". You can make it a class, though, when you learn about Classes and Objects.
Switch[edit | edit source]
There are times in which you wish to check for a number of conditions, and to execute different code depending on the condition. One way to do this is with if/else logic, such as the example below:
int x = 1; int y = 2; if (SOME_INT == x) { //DO SOMETHING } else if (SOME_INT == y) { //DO SOMETHING ELSE } else { //DEFAULT CONDITION }
This works, however another structure exists which allows us to do the same thing. Switch statements allow the programmer to execute certain blocks of code depending on exclusive conditions. The example below shows how a switch statement can be used:
int x = 1; int y = 2; switch (SOME_INT) { case x: method1(SOME_INT); break; case y: method2(SOME_INT); break; default: method3(); break; }
Switch takes a single parameter, which can be either an integer or a char. In this case the switch statement is evaluating SOME_INT, which is presumably an integer. When the switch statement is encountered SOME_INT is evaluated, and when it is equal to x or y, method1 and method2 are executed, respectively. The default case executes if SOME_INT does not equal x or y, in this case method3 is executed. You may have as many case statements as you wish within a switch statement.
Notice in the example above that "break" is listed after each case. This keyword ensures that execution of the switch statement stops immediately, rather than continuing to the next case. Were the break statement were not included "fall-through" would occur and the next case would be evaluated (and possibly executed if it meets the conditions).
While Loops[edit | edit source]
Loops will execute a block of code while a given condition is true. Basically, that block of code is executed until the condition is false. The condition is checked before the block of code is executed each time. The basic syntax:
while (CONDITION) { //DO SOMETHING }
So, you can guess that:
while (true) { //DO SOMETHING }
will execute the code within the while loop forever. The statement within the ( and ) is always a boolean condition.
Do..While Loops[edit | edit source]
A do..while loop is similar to a while loop with one major difference, which is that the condition is checked after the loop executes. This means that the block of code in the body of the do..while loop will always execute at least one time. The code below is an example of a do..while loop:
do { //DO SOMETHING } while (CONDITION);
Exercise 1: Design a while block that executes the if/else if/else code for the ship in the If/Else Statements section forever.
Exercise 2: Change the above so that it stops after 10 times. You will need to know the < operator: using the if statment, "if(SOMETHING < SOMETHING2) {...}" is valid. Basically, if s is less than s2 the next part will execute. You should use int variables for this exercise.
Answer to exercise 2:
int times=0; while(times < 10) { //Put if/else code here... times++; //Equivalent of times = times + 1; }
For Loop[edit | edit source]
A for loop is a neat package for executing some statements a set number of times. The syntax is fairly simple:
for (VARIABLE INITIALIZATION; CONDITIONAL CHECK; INCREMENT/DECREMENT) { //statements to be executed }
The code below is an example of a for loop:
for (int i = 0; i < 10; i++) { System.out.println(i); }
In this example, we declare an integer named i and initialize it to 0 in the initialization step. In the conditional test, we check to see that the value of i is strictly less than 10. Finally, the increment step says i++, which is a shorthand for i=i+1, or add 1 to i. Similar to the while loop the condition is checked every time before the body of the loop is executed. Think about this code and try to determine what the output will be. Will this execute when the value of i equals 10? The output is shown below:
0 1 2 3 4 5 6 7 8 9
Notice that "10" is not included in the output. This is because the conditional check is i < 10. When i equals 10 the condition is no longer true, and the loop will not execute.
Foreach Loops[edit | edit source]
There is another for known as a foreach loop which has been more recently introduced to Java made for iteration over a collection. It uses any type of list structure as its base, including arrays and certain types of Collections. Collections are data structures with certain properties that make manipulating large amounts of data easy. In the example below we use an ArrayList which is similar to a normal array, except that it can grow dynamically and it has a number of methods (such as add(), remove(), get(), etc) to make it easier to work with than a normal array. See the example below:
int[] integerArray = {2,3,4,5}; // an integer array is a basic list of integers ArrayList<Integer> listOfNumbers = new ArrayList<Integer>(); //Don't worry about this syntax now for (int i : integerArray) { i = i+1; listOfNumbers.add(i); } //integerArray now equals [2,3,4,5] //listOfNumbers now equals [3,4,5,6]
In this example we are iterating an array of integers named integerArray. The for loop will run 4 times, each time with "i" equaling a different value in the array. When the items in the list structure (see the example above) are primitive values (byte, int, long, float, double, boolean, char...) the value of "i" will just be a copy. This is why the values inside of integerArray are not changed even though "i" is changed inside the loop.
If, however, the values in the list are references, they will be directly under the influence of any changes occurring inside the loop as in this example:
//Note, this code will not compile with a working Ship class ArrayList<Ship> listOfShips = new ArrayList<Ship>(); //Don't worry about this syntax now listOfShips.add(new Ship(Color.RED)); listOfShips.add(new Ship(Color.BLUE)); listOfShips.add(new Ship(Color.GREEN)); ArrayList<Ship> newListOfShips = new ArrayList<Ship>(); //Don't worry about this syntax now for (Ship shipToChange : listOfShips) { shipToChange.setColor(Color.BLACK); newListOfShips.add(shipToChange); } //all ships in listOfShips now have color black //all ships in newListOfShips now have color black
In this example we start out with a list named listOfShips holding three "ships" all of different colors. The for loop iterated through the list and changed each ships's color to black, then it added the ship to another list called newListOfShips. Since shipToChange is a reference to a variable instead of a variable itself, changes to it affect the items in listOfShips. | https://en.wikiversity.org/wiki/Learning_Java/Decision_Structures | CC-MAIN-2021-31 | refinedweb | 2,131 | 70.13 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
2012-13
One of the most basic queries that I always get is: What are the applicable IT slab rates for the current year? Well, knowing the IT brackets and the income tax rates for each is one of the most important steps in calculating your income tax liability. So, let’s find out what these are for this year. Income tax (IT) slabs / brackets for Financial Year 2012-13, Assessment Year 2013-14
Income Rate Men and Women Less than 2,00,000 2,00,001 to 5,00,000 5,00,001 to 10,00,000 10,00,001 and above Senior Less than 2,50,000 2,50,001 to 5,00,000 5,00,001 to 10,00,000 10,00,001 and above Very Senior Less than 5,00,000 NA 5,00,001 to 10,00,000 10,00,001 and above Citizens (Age 60-80 years) Citizens (Age above 80 years)
0% 10% 20% 30%
Notes: An education cess of 3% is applicable on income tax payable for every income tax assessee. Income tax (IT) slabs / brackets for Financial Year 2011-12, Assessment Year 2012-13
Income Rate Men Less than 1,80,000 1,80,001 5,00,001 8,00,001 and above Women Less than 1,90,000 1,90,001 5,00,001 8,00,001 and above Senior Less than 2,50,000 2,50,001 5,00,001 8,00,001 and above Very Senior Less than 5,00,000 NA 5,00,001 to 8,00,000 8,00,001 and above Citizens (Age 60-80 years) Citizens (Age above 80 years)
0% 10% 20% 30%
to 5,00,000 to 5,00,000 to 5,00,000 to 8,00,000 to 8,00,000 to 8,00,000
indicate the amount here.000 per year. etc. 80 C: This is where the bulk of your investments would go. There is no upper limit on the amount that you can claim here.000) e. (Maximum Rs. l. 80 G G C: This is for claiming deductions for donations made to political parties. 40. k. 80 G G: This is for claiming deduction for rent paid by you. (Maximum Rs. 3.000 in income tax. and counted towards Section 80C limit) c. (Maximum 10% of your salary) d. 1 Lakh) b. 80 E: If you are paying interest on an educational loan for yourself or your spouse / children. So if you in the 30% tax bracket. 80 U: This is the deduction available in case of permanent physical disability. g.Deductions: This is where you put the investments you have made to save tax! a. you can save an additional Rs. 80 C C D: If you are a government employee employed after 1st January 2004.000. Please remember that this is applicable only for the interest earned from your savings account – interest from fixed deposits (FDs) is still taxable.000. i. 80 D D: If you have incurred expenses for the medical treatment of any handicapped dependent. 10. PPF. (Maximum Rs. 10. 80 D D B: If you have spent on medical treatment for yourself or your dependents for diseases specified in this section. 80 C C C: Include any amount that you have invested in a pension fund. . It includes investments like PF. 15. you can claim that amount here. Deduction of Interest from Savings Account Interest earned from a bank saving account has been made deductible up to Rs. please claim them here. the interest can be claimed here. indicate the amount paid by you for your pension fund. (Maximum Rs. 2000 per month) j. indicate those amounts here. 80 D: If you have paid any medical insurance premiums. The deduction allowed is a lump sum of Rs. h. f. ELSS. 80 G G A: This is for claiming deductions for donations made for scientific research or rural development. 80 G: If you have made any qualifying donations.
Please remember that this is over and above the tax-free reimbursement of medical bills up to Rs. and would produce a lot of “agents” that would deposit the TDS on your behalf for a fee. you would not need to pay any advance tax.000 per year. So far.000 per year incurred on preventive health checkup would be deductible from your income. What is you are selling the property.. which is a step in the right direction. If you are buying a property from someone. Another problem is from the seller’s point of view. 5. the government is passing on some of its work to you! This is going to add a lot of frustration to the property buying process. 2012 This is applicable only for secondary market sales – it is not applicable to a house / flat purchased directly from a builder (more clarity is expected on this) This provision is a big googly from this budget. you would get tax benefit even for health check up. 15. No Advance Tax for Senior Citizens If you are a Senior Citizens and do not have any income from business. why should it be your business to collect tax from the seller? Basically. and want to invest in another property or in Section 54EC bonds to save the long term capital gains tax? The buyer .Deduction for Preventive Health Checkup An expense of up to Rs. This would be included within the limit of deduction of health insurance premiums. but it would add a LOT of hassle for common people. you have to deduct TDS (for the profit made by the seller) and deposit it with the government The TDS would be 1% of the sale value This is applicable if the sale value is more than Rs. Tax Deducted at Source (TDS) for Property Transactions This is a brand new provision from this budget: · · · · · · · If you are buyer of a property. you could get tax benefit for the premiums paid for health insurance. Now. It has been supposedly introduced to reduce generation of black money from real estate transactions.
you can claim a deduction of Rs. 10. 35. 10 Lakhs per year · If you invest Rs. Thus.000 from the earlier Rs. This means that various financial institutions can issue double the bonds as compared to last year. 25.000 per year. and you would end up claiming it as a refund when you file yourincome tax return (ITR)! We all know how difficult and time consuming it is to get a refund… Tax Free Infrastructure Bonds The upper limit of tax-free infrastructure bonds has been doubled to from Rs.000). . 50.000 in equities · This tax benefit is available only if your income is less than Rs. if you are in the 20% tax bracket. Also. 25.000 (50% of Rs.000 from the earlier Rs.000. which means you can earn more tax-free income! Overseas Assets Income tax returns and their assessment can now be reopened for up to 16 years if you have assets outside India. 30. 5. service tax would now be applicable on everything except for a very few things (like government services. it is Rs. you need to get your act together! Rajiv Gandhi Equity Savings Scheme (RGESS) To encourage small and new investors to participation in the stock markets. agricultural services. This duty free allowance has been increased to Rs.000. Here are its features: · You would get a 50% deduction for an investment of up to Rs. 60. 50. 25. etc). So everything would cost a little more going forward – from small things like your light bill to big purchases like a car.would still need to deduct the TDS. If you have any holdings overseas.000. a new tax benefit has been introduced through a new scheme called “Rajiv Gandhi Equity Savings Scheme”.000 Crores to Rs. for children. you can save tax up to Rs. Duty Free Allowance People coming into India can bring items of certain value into India without paying any customs duty.000 Crores. · The investment has to be made directly in equities – it cannot be in Mutual Funds (MFs) (more clarity is expected on this soon) · There is a lock-in period of 3 years for these investments · The RGESS is available only to first time investors (more clarity is expected on this soon) Increase in Excise Duty and Service Tax Rates The rates for excise duty and service tax have been increased to 12% from the earlier 10%. This is called the duty free allowance. educational services. 15. | https://www.scribd.com/document/86633157/Awareness-About-Income-Tax-in-F-Y-2012-13 | CC-MAIN-2018-09 | refinedweb | 1,450 | 73.27 |
Sysinternals SuiteThe entire set of Sysinternals Utilities rolled up into a single download.
AccessChkv5.03 (March 23, 2012.42 (July 29, 20103.01 (February 23, 2011)Bypass password screen during logon.
Autorunsv11.3 (May 14, 2012)See what programs are configured to startup automatically when your system boots and you login. Autoruns also shows you the full list of Registry and file locations where applications can configure auto-start settings.
BgInfov4.16 (October 1,.6 (February 1, 2011)Wish you could quickly defragment your frequently used files? Use Contig to optimize individual files, or to create new files that are contiguous.
Coreinfov3.04 (February 16, 2012.78 (February 16,.02 (January 19, 2010)This new utility enables you to create up to four virtual desktops and to use a tray interface or hotkeys to preview what’s on each desktop and easily switch between them.
Disk2vhdv1.63 (October 14, 2010)Disk2vhd simplifies the migration of physical systems into virtual machines (p2v).
DiskExtv1.1 (May 14, 2007.4 (December 5, 2011.46 (May 18, 2011.2 (May 14, 2012.0 (November 1, 2006)Allows you to schedule move and delete commands for the next reboot.4.01 (September 20, 201115.13 (February 16, 2012)Find out what files, registry keys and other objects processes have open, which DLLs they have loaded, and more. This uniquely powerful utility will even show you who owns each process.
Process Monitorv3.01 (April 16, 2012)Monitor file system, Registry, process, thread and DLL activity in real-time.
PsExecv1.98 (April 28, 2010.13 (December 1, 2009)Terminate local or remote processes..22 (December 4, 2006.
RAMMapv1.11 (May 18, 2011)An advanced physical memory usage analysis utility that presents usage information in different ways on its several different tabs..
RootkitRevealerv1.71 (November 1, 2006)Scan your system for rootkit-based malware.
SDeletev1.6 (September 1, 2011.71 (October 14, 2010)Dump file version information and verify that images on your system are digitally signed.
Streamsv1.56 (April 27, 2007)Reveal NTFS alternate streams.
Stringsv2.5 (May 14, 2012)Search for ANSI and UNICODE strings in binary images.
Syncv2.0 (November 1, 2006)Flush cached data to disk.
TCPViewv3.05 (July 25, 2011)Active socket command-line viewer.
VMMapv3.1 (May 18, 2011.22 (February 14, 2011)The ultimate Object Manager namespace viewer is here.
ZoomItv4.2 (May 3, 2011 –.
]]> | http://technet.microsoft.com/en-us/sysinternals/bb545027(l=en-us) | crawl-003 | refinedweb | 394 | 53.47 |
Don't ad-block us - support your favorite websites. We have safe, unobstrusive, robotics related ads that you actually want to see - see here for more.
0 Members and 1 Guest are viewing this topic.
I have the following problem: my robot should look around, store what it saw with its sharp en than drive towards the most likeable thing it saw, being likebale means not too narrow, like the leg of a chair and not too big like a door or a wall. The looking around and storing what it saw i already managed, the sensor reading is stored in an array, 20 different headpositions are stored.But i dont know how to program:If you find more than 4 headpositions with distance readings that do not differ too much, ignore it.if you find less than 2 headpositions with distance readings that do not differ too much, ignore it.else drive to it, this part i also have...I think i'll need a sonar to detect the narrow object reliably, but that is a budgetary impossibility right now...Thanks already for any help!
Hi,I want it to go to the nearest thing it sees around it, that is smaller than 30cm.Later on i want to add a temperature sensor and tell it to ignore things that are not 37 degrees celsius, but one thing at a time!
#include <stdio.h>#include <stdlib.h>#define NUM_THINGS 20/* * Support macros for the Thing struct. */#define MIN(a, b) (a < b) ? a : b#define MAX(a, b) (a > b) ? a : b#define THING_MIN_TEMP(a, b) MIN(a.temp, b.temp)#define THING_MAX_TEMP(a, b) MAX(a.temp, b.temp)#define THING_MIN_HEIGHT(a, b) MIN(a.height, a.height)#define THING_MAX_HEIGHT(a, b) MAX(a.height, b.height)#define THING_MIN_DIST(a, b) MIN(a.distance, b.distance)#define THING_MAX_DIST(a, b) MAX(a.distance, b.distance)/*! * @brief Describes a `thing` that the bot sees. */typedef struct { /*! * Temperature of the object in celsius. (Going out on a limb and * hoping that char may be signed; it's implementation specific) */ char temp; /*! * Height of thing in undefined units. It's up to you to decide what your * unit of measure is. Because it's in a char, you only get 255 values. * (Well 256 if you count 0; assuming a char is 8 bits) */ unsigned char height; /*! * Distance to object in some undefined unit. Again, you decide what your * unit of measure is. */ unsigned short int distance;} Thing;/*! * Initialize the array of things. */voidinit_things(Thing things[]){ int x; for (x = 0; x < NUM_THINGS; x++) { things[x].temp = rand() % 128; things[x].height = rand() % 255; things[x].distance = rand() % 32767; }}/*! * Print out all things. */voidprint_things(Thing things[]){ int x; printf("All Things\nnumber, temp, height, distance\n"); for (x=0; x < NUM_THINGS; x++) { printf("%5d, %5d,%5d,%5d\n", x, things[x].temp, things[x].height, things[x].distance); } printf("\n");}/*! * Return the index of thing that has the maximum temperature. */size_tmax_temp(Thing things[]){ size_t x, max_idx = 0; char max_temp = things[0].temp; for (x = 1; x < NUM_THINGS; x++) { if (max_temp < things[x].temp) { max_temp = things[x].temp; max_idx = x; } } return max_idx;}/*! * Return the index of the closest thing. */size_tmin_distance(Thing things[]){ size_t x, min_idx = 0; unsigned short int min_distance = things[0].distance; for (x=1; x < NUM_THINGS; x++) { if (min_distance > things[x].distance) { min_distance = things[x].distance; min_idx = x; } } return min_idx;}int main() { /* * Declare 20 Things and fill them in. */ Thing things[NUM_THINGS]; init_things(things); print_things(things); printf("Thing %d has the maximum temperature.\n", max_temp(things)); printf("Thing %d is the closest.\n", min_distance(things)); return 0;} | http://www.societyofrobots.com/robotforum/index.php?topic=9009.msg70576 | CC-MAIN-2014-52 | refinedweb | 607 | 78.25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.