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
This chapter describes how to test rules from Rules Designer of Oracle JDeveloper by using the Rules Test Framework provided by Oracle Business Rules. It also discusses how to test rules and Decision Tables by creating an Oracle Business Rules Function. In addition, it covers at run time, how to test a SOA Application that uses Oracle Business Rules through a decision service by using Oracle Enterprise Manager Fusion Middleware Control Console. The chapter includes the following sections: Section 8.1, "Testing Oracle Business Rules at Design Time" Section 8.2, "Testing Oracle Business Rules at Runtime" Oracle Business Rules provides a test framework that allows you to test rules with complex input parameters. This framework enables you to test rules at the time of designing so that you can validate or refine the rules as per your requirement. Another way of testing rules is by defining a test function, where you can construct the input, execute rules, and validate the output. Because inputs are constructed and outputs are validated programmatically, test functions are typically used for simple tests, and the test framework is used for comprehensive tests. In addition, this test function is active only for functions that do not take any parameters and only return boolean values. Oracle Business Rules provides an 'out-of-the-box' functionality that enables you to test whether the rules you are defining works fine with a given set of inputs at the time of designing. The granularity of testing provided is at the level of decision functions. When you define decision functions in a dictionary, you can define test suites and execute those test suites for each of the decision functions. Oracle Business Rules supports multiple types of facts, such as Java facts, XML facts, RL facts, and ADFBC facts. The test framework currently only supports XML facts. So, if the decision function, which you have defined, have inputs or outputs referring to non-XML facts, the test framework cannot be used to test the decision function. If you use non-XML facts, a warning or error message is displayed indicating that you cannot use the test feature for that decision function. To test rules, you need to create a decision function as the prerequisite. Open Oracle JDeveloper. From the Application Navigator, open the project file containing the dictionary whose rules you want to test, say BaseDictionary.rules under Business Rules. In the dictionary section, click Decision Functions to open the list of decision functions. In the decision functions section, click the Create icon (the plus sign) to display the Edit Decision Function dialog box. Enter the name of the decision function in the Name field, say TestDF. In the Input tab, enter the input name under Name and press Enter. In this example, enter songs. Select the fact type from the Fact Type list. Ensure that you select XML facts. In this example, select Song as the fact type. Similarly, another input variable with the name as artists and fact type as Artist has been added. Select Tree or List as required. See Section 6.2.1, "How to Add or Edit a Decision Function" for more information on tree or list mode rules. In the Output tab, enter an output name under Name and press Enter. In this example, enter songs. Select the fact type from the Fact Type list. Ensure that you select XML facts. In this example, select Song. Under Rulesets & Decision Functions, select the ruleset that you want to invoke from the Available box, and use the shutter (>) icon to move it to the Selected box. In this example, SongArtistRules has been selected. Note: This example uses sample schema and corresponding facts. Click OK to create the decision function. Figure 8-1 displays the Edit Decision Function dialog box. Figure 8-1 The Edit Decision Function Dialog When you create a decision function, two XML schemas (xsd files) get automatically generated to help in testing the decision function. These schemas have suffixes _TestSuite and _Types respectively. Further, these schemas are stored in an xsd folder under the testsuites folder, which can be seen in the Application Navigator as shown in Figure 8-2. You need to define the test suites, which are created for the decision function, based on the schema with the suffix _TestSuite. Figure 8-2 Application Navigator Displaying XSDs The generated schema files follows the following naming convention: <DictionaryName>_<DecisionFunctionName>_TestSuite.xsd: This file contains the test suite schema for the decision function. Test Suites created for this decision function should conform to this schema. The following is a sample of the TestSuite.xsd file: <?xml version = '1.0' encoding = 'UTF-8'?> <schema xmlns="" xmlns: <annotation> <documentation> Decision Function Test Suite Schema </documentation> </annotation> <import namespace="" schemaLocation="BaseDictionary_BaseDF_Types.xsd"/> <element name="testSuite"> <complexType> <sequence> <element name="decisionFunction" type="string" minOccurs="1" maxOccurs="1"/> <element name="testCase" type="tns:testCaseType" minOccurs="1" maxOccurs="unbounded"/> </sequence> </complexType> </element> <complexType name="testCaseType"> <sequence> <element name="testInput" type="df:parameterList" minOccurs="0" maxOccurs="1"/> <element name="expectedOutput" type="df:resultList" minOccurs="0" maxOccurs="1"/> </sequence> <attribute name="name" type="string" use="required"/> </complexType> </schema> As you can see in the preceding sample, the schema contains a master testSuite element, which in turn contains an element called decisionFunction that defines to which decision function does this test suite corresponds.The testSuite element also contains one or more testCase elements. Each testCase contains a testInput and expectedOutput elements and a name. The testInput values are the ones that are used as inputs to the test cases and expectedOutput values are the ones against which the actual outputs are matched. The types of testInput and expectedOutput ( parameterList and resultList respectively) have been defined in the subsequent XSD. <DictionaryName>_<DecisionFunctionName>_Types.xsd: This schema contains two complexTypes elements, parameterList and resultList. These two types are used in the TestSuite schema but are defined here. The parameterList type corresponds to the decision function input and the resultList type corresponds to the decision function output. This is because a decision function has specific inputs and outputs. When you write a test case for a decision function, then the test case input need to correspond to the inputs accepted by the decision function and the expected output need to correspond to the decision function outputs. paramaterList and the resultList are single complexTypes. For example, a decision function requires 10 inputs and 5 outputs, then the parameterList type will be a single ComplexType that collectively defines 10 different elements that need to be provided as the decision function input. The following is a sample of the Types.xsd: <?xml version = '1.0' encoding = 'UTF-8'?> <schema xmlns="" targetNamespace="" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns: <import namespace="" schemaLocation="../../xsd/XMLFactTypes2.xsd"/> <import namespace="" schemaLocation="DecisionFunctionPrimitiveTypes.xsd"/> <complexType name="parameterList"> <sequence> <element name="tSongElement" type="ns1:tSong"/> <element ref="ns1:Artist"/> </sequence> </complexType> <complexType name="resultList"> <sequence> <element name="tSongElement" type="ns1:tSong"/> </sequence> </complexType> </schema> Every time there is an update to the decision function, the corresponding two schemas get updated. For example, if you change the name of the decision function, then the names of the associated schemas are changed. If you delete the decision functions, the corresponding schemas get deleted.Even changes to the inputs and outputs of the decision function results in the associated schemas getting changed. So a decision function and its corresponding test schemas are always in sync. In case you make any changes to the decision function, for example delete the decision function, typically the schemas get deleted. When you click the Undo icon on the dictionary toolbar, the decision function is retrieved. However, the corresponding schemas remain deleted. You need to manually regenerate the schemas for the decision function in this case. So the sync between the decision function and its corresponding test schemas is not supported in undo and redo operations. To manually regenerate the schemas: Click the Generate test suite schemas for all decision functions icon on the dictionary toolbar as shown in Figure 8-3. Figure 8-3 Manually Regenerating Test Suite Schemas When you click the icon to regenerate the test suite schemas, a bulk regeneration activity takes place, and all the test suite schemas pertaining to all the available decision functions in the dictionary gets regenerated. If the schemas already exist, those are overwritten. This activity is particularly used in the following cases: When you have deleted or modified the decision function and have undone the changes: This results in the decision function and the associated schemas getting out of sync. To get them in sync, you use this option so that the schemas are regenerated to correspond to the decision function. When you migrate old dictionaries: Consider a situation when you already have dictionaries from earlier releases with a number of decision functions defined and you want to use the rules testing feature for defining test suites for those decision functions to test them. In this case, either you have to open each decision function in the editor window after migrating, and then click the OK button. This would generate the corresponding test suite schemas. However, this is time-consuming when you have hundreds of decision functions. In this case, you can use the option of regenerating the schemas at one go. Note: You need to ensure that the migrated decision functions have XML facts as inputs and outputs, else the inputs and outputs defined in the test suite schema files will be empty. Once you have created the decision function for testing the rules, you can test rules. To test rules: Select the decision function name, say TestDF in this case, in the dictionary page and then click the Test button to display the Decision Function Test dialog box. Click the Create icon (the plus sign) to display the Create Test Suite dialog box. Enter the name for the test suite, say TestDFTestSuite1 and click OK as displayed in Figure 8-4. Figure 8-4 Creating a Test Suite Click Close in the Decision Function test dialog box. When you create a test suite, a <test suite name>.xml file gets automatically generated and gets stored in the <base dictionary name> folder under the rules folder inside the testsuites folder. You can view the file in the Application Navigator window. For every test suite that you create, a corresponding XML file gets generated. However, the newly created test suite file is empty, which does not contain any test case, input definitions, or output definitions. Open the <test suite name>.XML and write the required test cases that conform to the test suite XSD file, in this case the TestDF XSDs corresponding to the decision function under test. The following is a sample test suite file containing test cases: <?xml version = '1.0' encoding = 'UTF-8'?> <testSuite xmlns="" xmlns: <decisionFunction>G}-733d3b8f:12f76ddad3a:-7c02</decisionFunction> <testCase name="TestDFTestSuite1_TestCase1"> <testInput> <ns2:tSongElement> <ns3:Title>Come What May</ns3:Title> <ns3:Composer>Artist</ns3:Composer> > <ns3:Artist> <ns3:name>MJ</ns3:name> <ns3:age>20</ns3:age> <ns3:recordLabel>BMG Music</ns3:recordLabel> </ns3:Artist> </testInput> <expectedOutput> <ns2:tSongElement> <ns3:Title>Come What May</ns3:Title> <ns3:Composer>MJ</ns3:Composer> <ns3:Publisher>BMG Music</ns3:Publisher> > </expectedOutput> </testCase> </testSuite> Save the test suite file. Open the dictionary page, select the decision function name (say TestDF), and click the Test button to display the Decision Function test dialog box. Select TestDFTestSuite1 from the Test Suite list and click Run Test as shown in Figure 8-5. Figure 8-5 Running the Test This executes all the test cases in the test suite file. You can see the test details for the decision function in a tabular form. The details contain the test suite name, the overall result, and the test case details, such as: The test case name The result of the test case The trace info such as which are the facts that were asserted, which are the rules that were activated, which are the rules that were fired and the resultant change in facts. Figure 8-6 displays the test results. Figure 8-6 The Results Page The Comments section in the Results page displays any error details in case a test case fails. You may have a situation where your test suite XML file does not conform to the test suite XSD file. In that case when you open the Decision Function Test window, in the Test Suite list, adjacent to the test suite name, a yellow warning triangle appears as shown in Figure 8-7. Figure 8-7 Invalid Test Suite If you try to run an erroneous test suite, you will get the following error message: If the test suite XML file is malformed, then the test suite name does not appear in the list of test suites in the Decision Function Test window. In addition, for an invalid dictionary , when you test the Decision Function, the following error message is displayed: Dictionary is invalid, fix validation errors and try again. Consider a situation, where you have a base dictionary and a custom dictionary. The custom dictionary has a link to the base dictionary. Now, navigate to the Decision Functions section of the custom dictionary. Note that the list of decision functions in the custom dictionary includes the decision functions from the linked/base dictionary. You can test the decision functions of the base dictionary from the custom dictionary. In case your test case fails, the Results page displays the probable reasons of failure in the Comments section. A test case can fail due to the following reasons: The expected output specified for the test case is different from the actual output as the following: The Comments section clearly states that there is a mismatch between the expected output and the actual output. The test case executes, but no output is generated as the following: You can see that the Comments section displays that the test generated no results and some more details on the probable cause. The test case executes, but multiple outputs are generated as the following: The Comments section displays that multiple outputs were generated on test execution along with some details on the probable cause. The test case does not fire any rule as the following: This can be because the asserted fact failed to activate any rule resulting in no rules getting fired. So, the Comments section indicates that this may be due to a rule modelling error, because in all probabilities, the provided input failed to match any rule condition. You can test rulesets by creating a decision function and calling the decision function from Rules Designer with an Oracle Business Rules function. In the body of the Oracle Business Rules function you create input facts, call a decision function, and validate the facts output from the decision function. For more information, see Section 6.1, "Introduction to Decision Functions" and Section 2.5, "Working with Oracle Business Rules Functions". To test a decision function using an Oracle Business Rules function: Confirm that your dictionary is valid. For more information on dictionary validation, see Section 4.4.4, "How to Validate a Dictionary" In Rules Designer, select the Functions navigation tab. In the Functions area click the Create... icon. Enter the function name in the Name field, or use the default name. Select the return type from the Return Type list. For a test function, select boolean. In the Arguments table, confirm that there are no arguments. For a test function, you cannot specify any arguments. In the Body area, enter the test function body. In the body of the test function you can call a decision function using assign new to call and get the return value of the decision function (in the body of the test function you create input facts, call a decision function, and validate the facts output from the decision function). A decision function call returns a List. Thus, to test a decision function in a test function you do the following: You create the input data as required for the decision function input arguments. You call the decision function with the arguments you create in the test function. You place results in a List, for example, in the following: assign new List resultsList = DecisionFunction_1(testScore) Figure 8-8 shows a test function that calls a decision function. Figure 8-8 Test Function to Call a Decision Function that Returns a List Select the function and click the Test Function icon. The function is executed. The output is shown in a Function Test Result dialog, as Figure 8-9 shows. Figure 8-9 Test Function Results for Grade Test Click OK to dismiss the Function Test Result dialog. You can use Oracle Business Rules Functions to test decision functions from within Rules Designer. Keep the following points in mind when using a test function: The Test Function icon is gray if the dictionary associated with the test Oracle Business Rules Function contains any validation warnings. The Test Function icon is only shown when the dictionary validates without warnings. To enable logging you can call RL. watch.all(). For more information on RL Language functions, see Oracle Fusion Middleware Language Reference Guide for Oracle Business Rules. In this guide, RL.watch.all() is an alias for the RL Language function watchAll(). As an alternative to the example shown in Figure 8-8, you can enter the function body that is shown in Example 8-1. This function runs and shows the RL.watch.all() output. The dialog shows "Test Passed" when the grade is in the B range as shown in Figure 8-10. The dialog shows "Test Failed" when the grade asserted is not in the B range, as shown in Figure 8-11. Example 8-1 Function Body with True or False Return Value call RL.watch.all() assign new TestScore testScore = new TestScore() modify (testScore, name: "Bill Reynolds", testName: "Math Test", testScore: 81) assign new TestGrade testGrade = (TestGrade)DecisionFunction_1(testScore).get(0) return testGrade.grade == Grade.B For the testScore value 81, this function returns "Test Passed" as shown in Figure 8-10. For the testScore value 91, this returns "Test Failed", as shown in Figure 8-11. Figure 8-10 Test Passed Test Function Output Figure 8-11 Test Failed Test Function Output In an SOA application that uses Oracle Business Rules with a Decision Service you can test rules at runtime with Oracle Enterprise Manager Fusion Middleware Control Console Test function. For more information on using the Test function, see Oracle Fusion Middleware Administrator's Guide for Oracle SOA Suite and Oracle Business Process Management Suite.
http://docs.oracle.com/cd/E23943_01/user.1111/e10228/testing.htm
CC-MAIN-2016-26
refinedweb
3,111
54.12
Ecto v2.2.11 Ecto.Query View Source Provides the Query DSL. Queries are used to retrieve and manipulate data from a repository (see Ecto.Repo). Ecto queries come in two flavors: keyword-based and macro-based. Most examples will use the keyword-based syntax, the macro one will be explored in later sections. Let’s see a sample query: # Imports only from/2 of Ecto.Query import Ecto.Query, only: [from: 2] # Create a query query = from u in "users", where: u.age > 18, select: u.name # Send the query to the repository Repo.all(query) In the example above, we are directly querying the “users” table from the database. Query expressions Ecto allows a limited set of expressions inside queries. In the query below, for example, we use u.age to access a field, the > comparison operator and the literal 0: query = from u in "users", where: u.age > 0, select: u.name You can find the full list of operations in Ecto.Query.API. Besides the operations listed there, the following literals are supported in queries: - Integers: 1, 2, 3 - Floats: 1.0, 2.0, 3.0 - Booleans: true, false - Binaries: <<1, 2, 3>> - Strings: "foo bar", ~s(this is a string) - Arrays: [1, 2, 3], ~w(interpolate words) All other types and dynamic values must be passed as a parameter using interpolation as explained below. Interpolation and casting External values and Elixir expressions can be injected into a query expression with ^: def with_minimum(age, height_ft) do from u in "users", where: u.age > ^age and u.height > ^(height_ft * 3.28), select: u.name end with_minimum(18, 5.0) When interpolating values, you may want to explicitly tell Ecto what is the expected type of the value being interpolated: age = "18" Repo.all(from u in "users", where: u.age > type(^age, :integer), select: u.name) In the example above, Ecto will cast the age to type integer. When a value cannot be cast, Ecto.Query.CastError is raised. To avoid the repetition of always specifying the types, you may define an Ecto.Schema. In such cases, Ecto will analyze your queries and automatically cast the interpolated “age” when compared to the u.age field, as long as the age field is defined with type :integer in your schema: age = "18" Repo.all(from u in User, where: u.age > ^age, select: u.name) Another advantage of using schemas is that we no longer need to specify the select option in queries, as by default Ecto will retrieve all fields specified in the schema: age = "18" Repo.all(from u in User, where: u.age > ^age) For this reason, we will use schemas on the remaining examples but remember Ecto does not require them in order to write queries. Composition Ecto queries are composable. For example, the query above can actually be defined in two parts: # Create a query query = from u in User, where: u.age > 18 # Extend the query query = from u in query, select: u.name Composing queries uses the same syntax as creating a query. The difference is that, instead of passing a schema like User on the right side of in, we passed the query itself. Any value can be used on the right-side of in as long as it implements the Ecto.Queryable protocol. For now, we know the protocol is implemented for both atoms (like User) and strings (like “users”). In any case, regardless if a schema has been given or not, Ecto queries are always composable thanks to its binding system. Query bindings On the left side of in we specify the query bindings. This is done inside from and join clauses. In the query below u is a binding and u.age is a field access using this binding. query = from u in User, where: u.age > 18 Bindings are not exposed from the query. When composing queries you must specify bindings again for each refinement query. For example to further narrow-down above query we again need to tell Ecto what bindings to expect: query = from u in query, select: u.city Bindings in Ecto are positional, and the names do not have to be consistent between input and refinement queries. For example, the query above could also be written as: query = from q in query, select: q.city It would make no difference to Ecto. This is important because it allows developers to compose queries without caring about the bindings used in the initial query. When using joins, the bindings should be matched in the order they are specified: # Create a query query = from p in Post, join: c in Comment, where: c.post_id == p.id # Extend the query query = from [p, c] in query, select: {p.title, c.body} You are not required to specify all bindings when composing. For example, if we would like to order the results above by post insertion date, we could further extend it as: query = from q in query, order_by: q.inserted_at The example above will work if the input query has 1 or 10 bindings. In the example above, we will always sort by the inserted_at column from the from source. Similarly, if you are interested only on the last binding (or the last bindings) in a query, you can use … to specify “all bindings before” and match on the last one. For instance, imagine you wrote: posts_with_comments = from p in query, join: c in Comment, where: c.post_id == p.id And now we want to make sure to return both the post title and the comment body. Although we may not know how many bindings there are in the query, we are sure posts is the first binding and comments are the last one, so we can write: from [p, ..., c] in posts_with_comments, select: {p.title, c.body} In other words, ... will include all the binding between the first and the last, which may be no binding at all, one or many. Using ... can be handy from time to time but most of its uses can be avoided by relying on the keyword query syntax when writing queries. Bindingless operations Although bindings are extremely useful when working with joins, they are not necessary when the query has only the from clause. For such cases, Ecto supports a way for building queries without specifying the binding: from Post, where: [category: "fresh and new"], order_by: [desc: :published_at], select: [:id, :title, :body] The query above will select all posts with category “fresh and new”, order by the most recently published, and return Post structs with only the id, title and body fields set. It is equivalent to: from p in Post, where: p.category == "fresh and new", order_by: [desc: p.published_at], select: struct(p, [:id, :title, :body]) One advantage of bindingless queries is that they are data-driven and therefore useful for dynamically building queries. For example, the query above could also be written as: where = [category: "fresh and new"] order_by = [desc: :published_at] select = [:id, :title, :body] from Post, where: ^where, order_by: ^order_by, select: ^select This feature is very useful when queries need to be built based on some user input, like web search forms, CLIs and so on. Fragments If you need an escape hatch, Ecto provides fragments (see Ecto.Query.API.fragment/1) to inject SQL (and non-SQL) fragments into queries. For example, to get all posts while running the “lower(?)” function in the database where p.title is interpolated in place of ?, one can write: from p in Post, where: is_nil(p.published_at) and fragment("lower(?)", p.title) == ^title Also, most adapters provide direct APIs for queries, like Ecto.Adapters.SQL.query/4, allowing developers to completely bypass Ecto queries. Macro API In all examples so far we have used the keywords query syntax to create a query: import Ecto.Query from u in "users", where: u.age > 18, select: u.name Due to the prevalence of the pipe operator in Elixir, Ecto also supports a pipe-based syntax: "users" |> where([u], u.age > 18) |> select([u], u.name) The keyword-based and pipe-based examples are equivalent. The downside of using macros is that the binding must be specified for every operation. However, since keyword-based and pipe-based examples are equivalent, the bindingless syntax also works for macros: "users" |> where([u], u.age > 18) |> select([:name]) Such allows developers to write queries using bindings only in more complex query expressions. This module documents each of those macros, providing examples in both the keywords query and pipe expression formats. Query Prefix It is possible to set a prefix for the queries. For Postgres users, this will specify the schema where the table is located, while for MySQL users this will specify the database where the table is located. When no prefix is set, Postgres queries are assumed to be in the public schema, while MySQL queries are assumed to be in the database set in the config for the repo. To set the prefix on a query: results = query # May be User or an Ecto.Query itself |> Ecto.Queryable.to_query |> Map.put(:prefix, "foo") |> Repo.all When a prefix is set in a query, all loaded structs will belong to that prefix, so operations like update and delete will be applied to the proper prefix. In case you want to manually set the prefix for new data, specially on insert, use Ecto.put_meta/2. Link to this section Summary Functions A distinct query expression Builds a dynamic query expression Resets a previously set field on a query Restricts the query to return the first result ordered by primary key Creates a query A group by query expression An AND having query expression A join query expression Restricts the query to return the last result ordered by primary key A limit query expression A lock query expression An offset query expression An OR having query expression An OR where query expression An order by query expression Preloads the associations into the given struct A select query expression Mergeable select query expression Converts a query into a subquery An update query expression An AND where query expression Link to this section Types Link to this section Functions A distinct query expression. When true, only keeps distinct values from the resulting select expression. If supported by your database, you can also pass query expressions to distinct and it will generate a query with DISTINCT ON. In such cases, distinct accepts exactly the same expressions as order_by and any distinct expression will be automatically prepended to the order_by expressions in case there is any order_by expression. Keywords examples # Returns the list of different categories in the Post schema from(p in Post, distinct: true, select: p.category) # If your database supports DISTINCT ON(), # you can pass expressions to distinct too from(p in Post, distinct: p.category, order_by: [p.date]) # The DISTINCT ON() also supports ordering similar to ORDER BY. from(p in Post, distinct: [desc: p.category], order_by: [p.date]) # Using atoms from(p in Post, distinct: :category, order_by: :date) Expressions example Post |> distinct(true) |> order_by([p], [p.category, p.author]) Builds a dynamic query expression. Dynamic query expressions allows developers to build queries expression bit by bit so they are later interpolated in a query. Examples For example, imagine you have a set of conditions you want to build your query on: dynamic = false dynamic = if params["is_public"] do dynamic([p], p.is_public or ^dynamic) else dynamic end dynamic = if params["allow_reviewers"] do dynamic([p, a], a.reviewer == true or ^dynamic) else dynamic end from query, where: ^dynamic In the example above, we were able to build the query expressions bit by bit, using different bindings, and later interpolate it all at once inside the query. A dynamic expression can always be interpolated inside another dynamic expression and into the constructs described below. where, having and a join’s `on’ dynamic can be interpolated at the root of a where, having or a join’s on. For example, the following is forbidden because it is not at the root of a where: from q in query, where: q.some_condition and ^dynamic Fortunately that’s easily solvable by simply rewriting it to: dynamic = dynamic([q], q.some_condition and ^dynamic) from query, where: ^dynamic Updates Dynamic is also supported as each field in an update, for example: update_to = dynamic([p], p.sum / p.count) from query, update: [set: [average: ^update_to]] Resets a previously set field on a query. It can reset any query field except the query source ( from). Example query |> Ecto.Query.exclude(:select) Restricts the query to return the first result ordered by primary key. The query will be automatically ordered by the primary key unless order_by is given or order_by is set in the query. Limit is always set to 1. Examples Post |> first |> Repo.one query |> first(:inserted_at) |> Repo.one Creates a query. It can either be a keyword query or a query expression. If it is a keyword query the first argument must be either an in expression, or a value that implements the Ecto.Queryable protocol. If the query needs a reference to the data source in any other part of the expression, then an in must be used to create a reference variable. The second argument should be a keyword query where the keys are expression types and the values are expressions. If it is a query expression the first argument must be a value that implements the Ecto.Queryable protocol and the second argument the expression. Keywords example from(c in City, select: c) Expressions example City |> select([c], c) Examples def paginate(query, page, size) do from query, limit: ^size, offset: ^((page-1) * size) end The example above does not use in because limit and offset do not require a reference to the data source. However, extending the query with a where expression would require the use of in: def published(query) do from p in query, where: not(is_nil(p.published_at)) end Notice we have created a p variable to reference the query’s original data source. This assumes that the original query only had one source. When the given query has more than one source, a variable must be given for each in the order they were bound: def published_multi(query) do from [p,o] in query, where: not(is_nil(p.published_at)) and not(is_nil(o.published_at)) end Note the variables p and o can be named whatever you like as they have no importance in the query sent to the database. A group by query expression. Groups together rows from the schema that have the same values in the given fields. Using group_by “groups” the query giving it different semantics in the select expression. If a query is grouped, only fields that were referenced in the group_by can be used in the select or if the field is given as an argument to an aggregate function. group_by also accepts a list of atoms where each atom refers to a field in source. Keywords examples # Returns the number of posts in each category from(p in Post, group_by: p.category, select: {p.category, count(p.id)}) # Using atoms from(p in Post, group_by: :category, select: {p.category, count(p.id)}) Expressions example Post |> group_by([p], p.category) |> select([p], count(p.id)) An AND having query expression. Like where, having filters rows from the schema, but after the grouping is performed giving it the same semantics as select for a grouped query (see group_by/3). having groups the query even if the query has no group_by expression. Keywords example # Returns the number of posts in each category where the # average number of comments is above ten from(p in Post, group_by: p.category, having: avg(p.num_comments) > 10, select: {p.category, count(p.id)}) Expressions example Post |> group_by([p], p.category) |> having([p], avg(p.num_comments) > 10) |> select([p], count(p.id)) A join query expression. Receives a source that is to be joined to the query and a condition for the join. The join condition can be any expression that evaluates to a boolean value. The join is by default an inner join, the qualifier can be changed by giving the atoms: :inner, :left, :right, :cross, :full, :inner_lateral or :left_lateral. For a keyword query the :join keyword can be changed to: :inner_join, :left_join, :right_join, :cross_join, :full_join, :inner_lateral_join or :left_lateral_join. Currently it is possible to join on: - an Ecto.Schema, such as p in Post - an Ecto query with zero or more where clauses, such as from "posts", where: [public: true] - an association, such as c in assoc(post, :comments) - a query fragment, such as c in fragment("SOME COMPLEX QUERY") - a subquery, such as c in subquery(another_query) The fragment support exists mostly for handling lateral joins. See “Joining with fragments” below. Keywords examples from c in Comment, join: p in Post, on: p.id == c.post_id, select: {p.title, c.text} from p in Post, left_join: c in assoc(p, :comments), select: {p, c} Keywords can also be given or interpolated as part of on: from c in Comment, join: p in Post, on: [id: c.post_id], select: {p.title, c.text} Any key in on will apply to the currently joined expression. It is also possible to interpolate an Ecto query on the right side of in. For example, the query above can also be written as: posts = Post from c in Comment, join: p in ^posts, on: [id: c.post_id], select: {p.title, c.text} The above is specially useful to dynamically join on existing queries, for example, choosing between public posts or posts that have been recently published: posts = if params["drafts"] do from p in Post, where: [drafts: true] else from p in Post, where: [public: true] end from c in Comment, join: p in ^posts, on: [id: c.post_id], select: {p.title, c.text} Only simple queries with where expressions can be interpolated in join. Expressions examples Comment |> join(:inner, [c], p in Post, c.post_id == p.id) |> select([c, p], {p.title, c.text}) Post |> join(:left, [p], c in assoc(p, :comments)) |> select([p, c], {p, c}) Post |> join(:left, [p], c in Comment, c.post_id == p.id and c.is_visible == true) |> select([p, c], {p, c}) Joining with fragments When you need to join on a complex query, Ecto supports fragments in joins: Comment |> join(:inner, [c], p in fragment("SOME COMPLEX QUERY", c.id, ^some_param)) Although using fragments in joins is discouraged in favor of Ecto Query syntax, they are necessary when writing lateral joins as lateral joins require a subquery that refer to previous bindings: Game |> join(:inner_lateral, [g], gs in fragment("SELECT * FROM games_sold AS gs WHERE gs.game_id = ? ORDER BY gs.sold_on LIMIT 2", g.id)) |> select([g, gs], {g.name, gs.sold_on}) Restricts the query to return the last result ordered by primary key. The query ordering will be automatically reversed, with ASC columns becoming DESC columns (and vice-versa) and limit is set to 1. If there is no ordering, the query will be automatically ordered decreasingly by primary key. Examples Post |> last |> Repo.one query |> last(:inserted_at) |> Repo.one A limit query expression. Limits the number of rows returned from the result. Can be any expression but has to evaluate to an integer value and it can’t include any field. If limit is given twice, it overrides the previous value. Keywords example from(u in User, where: u.id == ^current_user, limit: 1) Expressions example User |> where([u], u.id == ^current_user) |> limit(1) A lock query expression. Provides support for row-level pessimistic locking using SELECT ... FOR UPDATE or other, database-specific, locking clauses. expr can be any expression but has to evaluate to a boolean value or to a string and it can’t include any fields. If lock is used more than once, the last one used takes precedence. Ecto also supports optimistic locking but not through queries. For more information on optimistic locking, have a look at the Ecto.Changeset.optimistic_lock/3 function Keywords example from(u in User, where: u.id == ^current_user, lock: "FOR SHARE NOWAIT") Expressions example User |> where(u.id == ^current_user) |> lock("FOR SHARE NOWAIT") An offset query expression. Offsets the number of rows selected from the result. Can be any expression but it must evaluate to an integer value and it can’t include any field. If offset is given twice, it overrides the previous value. Keywords example # Get all posts on page 4 from(p in Post, limit: 10, offset: 30) Expressions example Post |> limit(10) |> offset(30) An OR having query expression. Like having but combines with the previous expression by using OR. or_having behaves for having the same way or_where behaves for where. Keywords example # Augment a previous group_by with a having condition. from(p in query, or_having: avg(p.num_comments) > 10) Expressions example # Augment a previous group_by with a having condition. Post |> or_having([p], avg(p.num_comments) > 10) An OR where query expression. Behaves exactly the same as where except it combines with any previous expression by using an OR. All expressions have to evaluate to a boolean value. or_where also accepts a keyword list where each key is a field to be compared with the given value. Each key-value pair will be combined using AND, exactly as in where. Keywords example from(c in City, where: [country: "Sweden"], or_where: [country: "Brazil"]) If interpolating keyword lists, the keyword list entries are combined using ANDs and joined to any existing expression with an OR: filters = [country: "USA", name: "New York"] from(c in City, where: [country: "Sweden"], or_where: ^filters) is equivalent to: from c in City, where: (c.country == "Sweden") or (c.country == "USA" and c.name == "New York") The behaviour above is by design to keep the changes between where and or_where minimal. Plus, if you have a keyword list and you would like each pair to be combined using or, it can be easily done with Enum.reduce/3: filters = [country: "USA", is_tax_exempt: true] Enum.reduce(filters, City, fn {key, value}, query -> from q in query, or_where: field(q, ^key) == ^value end) which will be equivalent to: from c in City, or_where: (c.country == "USA"), or_where: c.is_tax_exempt == true Expressions example City |> where([c], c.country == "Sweden") |> or_where([c], c.country == "Brazil") An order by query expression. Orders the fields based on one or more fields. It accepts a single field or a list of fields. The default direction is ascending ( :asc) and can be customized in a keyword list as shown in the examples. There can be several order by expressions in a query and new expressions are always appended to the previous ones. order_by also accepts a list of atoms where each atom refers to a field in source or a keyword list where the direction is given as key and the field to order as value. Keywords examples from(c in City, order_by: c.name, order_by: c.population) from(c in City, order_by: [c.name, c.population]) from(c in City, order_by: [asc: c.name, desc: c.population]) from(c in City, order_by: [:name, :population]) from(c in City, order_by: [asc: :name, desc: :population]) A keyword list can also be interpolated: values = [asc: :name, desc: :population] from(c in City, order_by: ^values) Expressions example City |> order_by([c], asc: c.name, desc: c.population) City |> order_by(asc: :name) # Sorts by the cities name Preloads the associations into the given struct. Preloading allows developers to specify associations that are preloaded into the struct. Consider this example: Repo.all from p in Post, preload: [:comments] The example above will fetch all posts from the database and then do a separate query returning all comments associated with the given posts. However, often times, you want posts and comments to be selected and filtered in the same query. For such cases, you can explicitly tell the association to be preloaded into the struct: Repo.all from p in Post, join: c in assoc(p, :comments), where: c.published_at > p.updated_at, preload: [comments: c] In the example above, instead of issuing a separate query to fetch comments, Ecto will fetch posts and comments in a single query. Nested associations can also be preloaded in both formats: Repo.all from p in Post, preload: [comments: :likes] Repo.all from p in Post, join: c in assoc(p, :comments), join: l in assoc(c, :likes), where: l.inserted_at > c.updated_at, preload: [comments: {c, likes: l}] Keep in mind neither format can be nested arbitrarily. For example, the query below is invalid because we cannot preload likes with the join association c. Repo.all from p in Post, join: c in assoc(p, :comments), preload: [comments: {c, :likes}] Preload queries Preload also allows queries to be given, allowing you to filter or customize how the preloads are fetched: comments_query = from c in Comment, order_by: c.published_at Repo.all from p in Post, preload: [comments: ^comments_query] The example above will issue two queries, one for loading posts and then another for loading the comments associated with the posts. published_at. Note: keep in mind operations like limit and offset in the preload query will affect the whole result set and not each association. For example, the query below: comments_query = from c in Comment, order_by: c.popularity, limit: 5 Repo.all from p in Post, preload: [comments: ^comments_query] won’t bring the top of comments per post. Rather, it will only bring the 5 top comments across all posts. Preload functions Preload also allows functions to be given. In such cases, the function receives the IDs to be fetched and it must return the associated data. This data will then be mapped and sorted by the relationship key: comment_preloader = fn post_ids -> fetch_comments_by_post_ids(post_ids) end Repo.all from p in Post, preload: [comments: ^comment_preloader] This is useful when the whole dataset was already loaded or must be explicitly fetched from elsewhere. Keywords example # Returns all posts, their associated comments, and the associated # likes for those comments. from(p in Post, preload: [:comments, comments: :likes], select: p) Expressions examples Post |> preload(:comments) |> select([p], p) Post |> join(:left, [p], c in assoc(p, :comments)) |> preload([p, c], [:user, comments: c]) |> select([p], p) A select query expression. Selects which fields will be selected from the schema and any transformations that should be performed on the fields. Any expression that is accepted in a query can be a select field. Select also allows each expression to be wrapped in lists, tuples or maps as shown in the examples below. A full schema can also be selected. There can only be one select expression in a query, if the select expression is omitted, the query will by default select the full schema. If select is given more than once, an error is raised. Use exclude/2 if you would like to remove a previous select for overriding or see select_merge/3 for a limited version of select that is composable and can be called multiple times. select also accepts a list of atoms where each atom refers to a field in the source to be selected. Keywords examples from(c in City, select: c) # returns the schema as a struct from(c in City, select: {c.name, c.population}) from(c in City, select: [c.name, c.county]) from(c in City, select: %{n: c.name, answer: 42}) from(c in City, select: %{c | alternative_name: c.name}) from(c in City, select: %Data{name: c.name}) It is also possible to select a struct and limit the returned fields at the same time: from(City, select: [:name]) The syntax above is equivalent to: from(city in City, select: struct(city, [:name])) You can also write: from(city in City, select: map(city, [:name])) If you want a map with only the selected fields to be returned. For more information, read the docs for Ecto.Query.API.struct/2 and Ecto.Query.API.map/2. Expressions examples City |> select([c], c) City |> select([c], {c.name, c.country}) City |> select([c], %{"name" => c.name}) City |> select([:name]) City |> select([c], struct(c, [:name])) City |> select([c], map(c, [:name])) Mergeable select query expression. This macro is similar to select/3 except it may be specified multiple times as long as every entry is a map. This is useful for merging and composing selects. For example: query = from p in Post, select: %{} query = if include_title? do from p in query, select_merge: %{title: p.title} else query end query = if include_visits? do from p in query, select_merge: %{visits: p.visits} else query end In the example above, the query is built little by little by merging into a final map. If both conditions above are true, the final query would be equivalent to: from p in Post, select: %{title: p.title, visits: p.visits} If :select_merge is called and there is no value selected previously, it will default to the source, p in the example above. The left-side of a merge can be a struct or a map. The right side must always be a map. If the left-side is a struct, the fields on the right side must be part of the struct, otherwise an error is raised. Converts a query into a subquery. If a subquery is given, returns the subquery itself. If any other value is given, it is converted to a query via Ecto.Queryable and wrapped in the Ecto.SubQuery struct. Subqueries are currently only supported in the from and join fields. Examples # Get the average salary of the top 10 highest salaries query = from Employee, order_by: [desc: :salary], limit: 10 from e in subquery(query), select: avg(e.salary) A prefix can be specified for a subquery, similar to standard repo operations: query = from Employee, order_by: [desc: :salary], limit: 10 from e in subquery(query, prefix: "my_prefix"), select: avg(e.salary) Although subqueries are not allowed in WHERE expressions, most subqueries in WHERE expression can be rewritten as JOINs. Imagine you want to write this query: UPDATE posts SET sync_started_at = $1 WHERE id IN ( SELECT id FROM posts WHERE synced = false AND (sync_started_at IS NULL OR sync_started_at < $1) LIMIT $2 ) If you attempt to write it as where: p.id in ^subquery(foo), Ecto won’t accept such query. However, the subquery above can be written as a JOIN, which is supported by Ecto. The final Ecto query will look like this: subset_query = from(p in Post, where: p.synced == false and (is_nil(p.sync_started_at) or p.sync_started_at < ^min_sync_started_at), limit: ^batch_size ) Repo.update_all( from(p in Post, join: s in subquery(subset_query), on: s.id == p.id), set: [sync_started_at: NaiveDateTime.utc_now()] end) An update query expression. Updates are used to update the filtered entries. In order for updates to be applied, Ecto.Repo.update_all/3 must be invoked. Keywords example from(u in User, update: [set: [name: "new name"]]) Expressions example User |> update([u], set: [name: "new name"]) User |> update(set: [name: "new name"]) Interpolation new_name = "new name" from(u in User, update: [set: [name: ^new_name]]) new_name = "new name" from(u in User, update: [set: [name: fragment("upper(?)", ^new_name)]]) Operators The update expression in Ecto supports the following operators: set- sets the given field in the table to the given value from(u in User, update: [set: [name: “new name”]]) inc- increments (or decrements if the value is negative) the given field in the table by the given value from(u in User, update: [inc: [accesses: 1]]) push- pushes (appends) the given value to the end of the array field from(u in User, update: [push: [tags: “cool”]]) pull- pulls (removes) the given value from the array field from(u in User, update: [pull: [tags: “not cool”]]) An AND where query expression. where expressions are used to filter the result set. If there is more than one where expression, they are combined with an and operator. All where expressions have to evaluate to a boolean value. where also accepts a keyword list where the field given as key is going to be compared with the given value. The fields will always refer to the source given in from. Keywords example from(c in City, where: c.country == "Sweden") from(c in City, where: [country: "Sweden"]) It is also possible to interpolate the whole keyword list, allowing you to dynamically filter the source: filters = [country: "Sweden"] from(c in City, where: ^filters) Expressions example City |> where([c], c.country == "Sweden") City |> where(country: "Sweden")
https://hexdocs.pm/ecto/Ecto.Query.html
CC-MAIN-2018-43
refinedweb
5,418
65.01
XHTML Contents 1 Definition XHTML is a family of current and future Web document types and modules that reproduce, subset, and extend HTML4.01. XHTML family document types are XML conformant, and designed to work in conjunction with XML-based editors and user agents. XHTML markup is pretty much the same as HTML markup, i.e. the XHTML 1.0 version use the same tags as the respective HTML 4.01x version (with some exceptions) See also: - Overviews: HTML, HTML5 and HTML links - Tags (elements): HTML and XHTML elements and attributes - Regarding XML: XML, DTDs. 2 XHTML documents 2.1 Valid XHTML documents XHTML documents must be wellformed and valid according to the XML specification, except that an XML declaration is not mandatory (only encouraged). All XHTML tags were defined in lower case. In XML, as opposed to SGML, case does matter. In addition: - It must conform to the constraints expressed in one of the variants introduced below. - The root element of the document must be html - The root element of the document must contain an xmlns declaration for the XHTML namespace. Examples: <html xmlns= "" xml: <h:html xmlns: - There must be a DOCTYPE declaration in the document prior to the root element. - The DTD subset must not be used to override any parameter entities in the DTD. - An XML declaration on top of the file is mandatory if the character set used is different from UTF-8 or UTF-16. 2.2 XHTML Versions - XHTML 1.0 (26 jan 2000, revised 1 Aug 2002) According to the XHTML2 Working Group Home Page (retrieved 15:19, 1 September 2009 (UTC)), XHTML 1.0 is specified in three "flavors": (1) XHTML 1.0 Strict - Use this when you want really clean structural mark-up, free of any markup associated with layout. Use this together with W3C's Cascading Style Sheet language (CSS) to get the font, color, and layout effects you want. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> (2) element with bgcolor, text and link attributes. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> (3) XHTML 1.0 Frameset - Use this when you want to use Frames to partition the browser window into two or more frames. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" ""> - XHTML 1.1 additions (module-based XHTML) - XHTML Basic 1.1 is a mini-version of XHTML 1.0 for small devices (e.g. cell phones and PDAs). In principle, a successor for older WAP standards. Note there also exists a XHTML Mobile Profile which is a superset defined by the Open Mobile Alliance. - XHTML 1.1 is similar to XHTML 1.0 strict (but with a modular design). - XHTML 2.x - dead project - There were many new features, e.g. HTML forms, frames and DOM events will be replaced by XML standards - Any element can be a link - Nested <section> elements with a single heading element. - XHTML was quite a different language. Too much to cope for industry we believe, but in our opinion it was a better way to think about documents than HTML 4.x/XHTML 1.x - Daniel K. Schneider 15:19, 1 September 2009 (UTC). - XHTML 5 - under development - HTML5 adds many extra features to HTML 4.x and includes some of ideas that went into the XHTML 2 project, e.g. sectioning elements. XHTML5 refers to an XML serialization of HTML5, i.e. a document would use XML syntax and an XML mimetype. The DOM (internal representation) should be the same for both HTML5 and XHTML5 if we understand right. 2.3 XHTML strict example <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html xmlns="" xml: <head> <title>Virtual Library</title> </head> <body> <p>Moved to <a href="">example.org</a>.</p> </body> </html> 3 XHTML elements and attributes See the HTML and XHTML elements and attributes entry. 4 Composite XHTML 1.x documents - XHTML can include other namespaced languages, e.g. SVG or MathML or your own XML. However, for the moment it is not possible to validate composite documents. - MathML example (See file xhtml-with-mathml-test.xhtml) <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" "" > <html xmlns="" xmlns: <head> <title>XTHML with MATHML</title> </head> <body> <p> <b>Corollary 2</b> [Contractive Sequence Theorem] <em>If <math xmlns=''> <mo>(</mo><msub><mi>x</mi> <mi>n</mi></msub><mo>)</mo></math> is a sequence, for which there is a number <math xmlns=''><mi>C</mi><mi><</mi><mn>1</mn></math> such that <math xmlns=''><mo>|</mo> <msub><mi>x</mi> <mrow><mi>n</mi><mo>+</mo><mn>2</mn></mrow></msub><mo>-</mo> <msub><mi>x</mi><mrow><mi>n</mi><mo>+</mo><mn>1</mn></mrow></msub> <mo>|</mo><mo>≤</mo><mi>C</mi><mo>⋅</mo><mo>|</mo><msub><mi>x</mi> <mrow><mi>n</mi><mo>+</mo><mn>1</mn></mrow></msub> <mo>-</mo><msub><mi>x</mi> <mi>n</mi></msub><mo>|</mo></math> , then <math xmlns=''> <mo>(</mo><msub><mi>x</mi> <mi>n</mi></msub><mo>)</mo></math> converges;</em></p> </body> </html> SVG example (you can see it here) <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "" > <html xmlns="" xmlns: <head> <title>SVG within XHTML Demo</title> </head> <body> <p> You can embed SVG into XHTML, provided that your browser natively implements SVG. E.g. Firefox 1.5 supports most of static SVG. </p> The SVG part starts below <hr /> <svg xmlns="" version="1.1" width="400" height="300"> <!-- un petit rectangle avec des coins arroundis --> <rect x="50" y="50" rx="5" ry="5" width="300" height="100" style="fill:#CCCCFF;stroke:#000099"/> <!-- un texte au meme endroit --> <text x="55" y="90" style="stroke:#000099;fill:#000099;font-size:24;"> HELLO cher visiteur </text> </svg> <hr /> The SVG part ended above </body> </html> It is also possible to include XHTML tags in any XML document markup. E.g. here is an example: (live example) <?xml version="1.0" ?> <?xml-stylesheet <title>Hello friend</title> <list> <!-- we use an HTML tag below to include a picture --> <html:img <item price="10"> White plate </item> <item price="20"> Gold plate </item> <item price="15"> Silver plate </item> </list> <comment> Written by <html:aDKS/Tecfa</html:a> , feb 2007 </comment> </page> 5 Issues IE support XHTML was badly supported by IE6, IE7 and IE8. These Microsoft browsers did not recognize the application/xhtml+xml mimetype, which made it difficult to include XSLT stylesheets or other languages such as SVG or MathML. The reason why MS did not support "real" XHTML is simple. They would have had to rewrite the whole parser as it is explained by Chris Wilson in the IEBlog. Microsoft finally got there with IE9/10. But by then the XHTML "concept" was dead and replaced by HTML5 If you send XHTML as simple HTML "text/html" files you will loose all XML-related advantages. XHTML id render in IE 6-8 since it was simply translated to HTML 4.1. There were workarounds to somewhat deal with IE 6/7/8 - Using server-side rewrite rules - Serve a document as XML or HTML with *.xml and *.htm/ *.html file extensions from your your webserver and add this: <?xml version="1.0" encoding="ISO-8859-1"?> <!-- prevent IE from rendering a DOM tree --> <?xml-stylesheet type="text/xsl" href="xhtml.xsl"?> <?xml version="1.0"?> <xsl:stylesheet xmlns: <xsl:template <xsl:copy-of </xsl:template> </xsl:stylesheet> See Dean Edwards and Anne Van Kersteren XML requirements XML states that pages with errors should not display. Since most programmers can't produce correct (X)HTML code, this can be seen a stumbling block for creating web sites and web applications .... 6 Tools To author (X)HTML Pages you can: - Use a simple editor and type tags (not recommened) - Use an XML editor (for XHTML only) or a programmer's editor for both version. - Use a web authoring system - Translate from a wordprocessor or some multimedia authoring systems 7 Links See HTML links (a page with links for both HTML and XHTML) 7.1 Standards - HTML, Latest Version (XHTML 1.0 as of 15:53, 12 March 2007 (MET)] - XHTML 1.0 - XHTML Basic 1.1 (still a working draft as of March 2007). - XHTML 2.0 (working draft 2006). The project is dead: .” (W3C news, retrieved 15:19, 1 September 2009 (UTC). 7.2 Links - Beware of XHTML by David Hammond (last checked Jan 2014) - [ XHTML — myths and reality] by Tina Holmboe (last checked Jan 2014)
http://edutechwiki.unige.ch/en/XHTML
CC-MAIN-2018-05
refinedweb
1,452
66.54
(I've pulled this out from where it was embedded in one of my posts about implementing ICompositeView because it didn't really fit there and modified it but it’s still pretty badly researched.) A few gory implementation details for the Workflow Designer’s Undo/Redo features. There are a few classes in System.Activities.Presentation.Model heavily involved in undo and redo: - ModelEditingScope [msdn] (public abstract class ModelEditingScope, protected constructor) - EditingScope [msdn] (public class EditingScope, private/internal constructor) - Change [msdn] (public abstract class Change, protected constructor) The most atomic class to understand here is abstract class Change, which is shaped like this: Blue Text Doubleyou Tee Eff. Ignore it. Change is the core extensibility mechanism for Undo/Redo. A Change is meant to model an action or side-effect in the designer which knows how to undo and redo itself. Internally to System.Activities.Presentation, there are several subclasses of Change such as PropertyChange which the designer uses to build up its undo-redo stack. Since Change is public and non-sealed, we should also be able to create our own subclasses if we want to introduce any new side-effects which need support for undo and redo in the designer. The other two classes, ModelEditingScope and EditingScope are rather confusingly named, but they are basically two versions of the same thing - a group of Changes which will be undone and redone all at one time. What happens when we press Ctrl+Z? Let’s walk through the steps. The Change or EditingScope on top of the Undo/Redo Stack is going to be: - Invert()ed - Apply()ed - Moved from top of the undo stack to top of the redo stack. Simple enough. So far everything I’ve described is still abstract, and I haven’t explained how exactly you create a Change and add it to the Undo stack in concrete terms. The good news, is that you shouldn’t need to. Every edit you make to the designer’s Model Tree automatically becomes a Change and gets added to the current editing scope. Here’s a rather dumb example just to make the point: void SetChildActivity(ModelItem mi, Activity newChild) { //this SetValue() call automatically creates a Change and adds it to the current editing scope mi.Properties[“Child”].SetValue(newChild); } If there is no current editing scope (as created by ModelItem.BeginEdit()), the change executes immediately. When you implement complex UI in designer you may notice und/redo is not all smooth sailing. Model changes are getting created automatically, but you may find yourself wondering how to fix consistency issues with non-model state: e.g. Change aren’t being created to undo everything you do in the WPF view tree, therefore your Model and View become desynced after undo and redo. Actually that is the scenario we encounter in the ICompositeView posts, but a recap here: What are the options we might have for fixing this? One approach might be for us to introduce our own subclasses of Change which know how to undo/redo the action of adding or removing an element from the Visual Tree. If we also add these Changes to the active ModelEditingScope, then the Workflow Designer will magically store all the info it needs to undo the Visual changes on the undo redo stack. This would be a bad idea. But why? Because we would be mixing our View and our Model. Ramraj spent some time kindly pointing out to me why it would be a really good idea to keep them separate. Firstly, usability - changing View is not considered an ‘edit’ by the user, therefore switching View is not something they care to treat as an actual undoable action. Another issue might be that as Views get created and destroyed a lot, and can be relatively heavy objects compared to Model objects. If we keep Views on our undo stack, it might get expensive! What do we normally choose to do instead? Use the idea of binding. (Again, see the article linked at top for details.) When doesn’t binding work? When you’re really trying to extend the model, or work outside of the model. Here we branch off into new territory. Extending the model: Suppose it’s not the View we want to add undo/redo support for because we’ve instead figured out how to do it by binding and handling change events. Suppose we actually want to extend the capabilities of the model, and what is editable by the user, say for instance by adding something like the ViewStateService. How should we go about it? Here ViewStateService should be a pretty good model – it basically managed to add undo/redo support by having one method – StoreViewStateWithUndo(). What does it do? 1) Create a ViewStateChange (custom subclass of Change). The Change is created in the forward direction. 2) Call ‘AddToCurrentEditingScope()’ Uh oh! Step 2 is calling an internal API. That isn’t going to work for us. Is Workflow Undo/Redo actually that unextensible? (Also what about that work outside of the model idea?) Well, I’m not sure yet! There are actually two parts to the Workflow Designer Undo/Redo API, and so far we have been overfocused on the part for implementing Undo for the ModelTree. But there is also a more general looking Undo/Redo API, based around a class called System.Activities.Presentation.UndoUnit. [OK. This is better than what I had before I started tidying up loose ends, I just realized I don’t know anything about UndoEngine, it’s late, and this is getting long so I think I will have to go multipart again, to cover UndoUnit and UndoEngine late. Until next time!] Hi Tim, If I use IActivityTemplateFactory, to do stuff like add child activities, variable, etc, to preconfigure my activity, what will happen in terms of undo/redo behaviour, should a user undo adding my activity to the designer? Is it part of one transaction or multiple? Thanks, Notre That depends… 🙂 …on what you do inside IActivityTemplateFactory.Create(), that is. If no ModelItems are involved then the only thing visible to the undo/redo stack would be the ‘Add’ it does of the item returned from create, so it’s ‘atomic’. Tim Thanks Tim. I think ultimately, everything eventually becomes a model item in the designer, so by saying "ModelItems" are involved do, you mean explicitly doing something to update the model item tree? If ModelItems are involved, what should be done to ensure an atomic transaction? Wrap the operations on the model items in a ModelEditingScope (by using activity BeginEdit and Complete calls)? Thanks, Notre Understand the expected timing. Things can turn into model items in the designer, but it’s not supposed to be a model item until after it is returned from IActivityTemplateFactory.Create(). Tim
https://blogs.msdn.microsoft.com/tilovell/2010/01/12/some-gory-details-of-workflowdesigner-undo-redo/?replytocom=153
CC-MAIN-2018-05
refinedweb
1,141
54.63
Hi First off, nice to be here. A really good place for starters and advance users alike. I have begun to refresh my C++ skills after 6 years of electronics study at college. Here is the problem: This program takes a text in the char array "test" and stores alternate characters in two different char arrays a and b (even and odd positions). (this may not be clear, im really tired) but the code explains in detail. I am having trouble in getting the output after the 'for' loop. The 'for' loop that supposedly does the main work and also displays the content of two arrays. The next time I try to display the arrays, its a different output. Code: #include <iostream> #include <string> using namespace std; //Initializing two empty (?) char arrays to store the alternate chars from //the test string. char a[]=""; char b[]=""; int main() { // Initialization of the test srting. using no space to make it simple for now, // but spaces also work char test[]="HelloWorldHowAreYou"; cout << "The string is " << test << " of size " << sizeof(test) << endl; // Loop test to output the string "test" using loop. // Used unsigned int to avoid any warnings in comparisson. cout << "\nLoop Test: \n"; for (unsigned int j=0;j<sizeof(test);j++) { cout << test[j] << " "; } cout << "\n\n\n"; // The main program to store alternate chars in two different char arrays. // Loop using unsigned int. The output of this process is correct! for (unsigned int i=0;i<sizeof(test);i++) { a[i]=test[(2*i)]; b[i]=test[(2*i)+1]; cout << "a " << i << " is: " << a[i] << endl; cout << "b " << i << " is: " << b[i] << endl; } cout << "\n\n\n"; // This is where it gets really annoying, I dont get a meaningful output. // Even if the previous 'for' loop correctly places the chars alternatively // The output given here is completely incorrect. Example: a[3] is supposed to be // "o" and b[3] = "r", but the output is mixed up. // I do realize it could be because of the way arrays work, but please // explain. I would like to understand this better. cout << "The output after the storing of alternate chars in a,b. \n\n"; for (unsigned int k=0;k<sizeof(test);k++) { cout << "a " << k << " is: " << a[k] << endl; cout << "b " << k << " is: " << b[k] << endl; } //cout << "\n" << a << b << endl; return 0; }
http://cboard.cprogramming.com/cplusplus-programming/126055-cannot-understand-char-array-text-problem-printable-thread.html
CC-MAIN-2014-41
refinedweb
392
72.87
C# 6.0 has not introduced any new concepts like other versions of C# but instead it introduced some of very interesting and useful features which will help you to write more clean code with less typing. I am sure as a developer you are going to love these features. Lets figure out what are those: 1. Getter-only auto Property. C# 6.0 allows you to define getter-only property and initialize it as part of constructor or directly. class Features { public string FirstName { get; } public string LastName { get; } = "Mahto"; public Features() { FirstName = "Binod"; } } 2. Using static members: Use static with using directive for namespace reference. It allow you to access static members of a type without having to qualify the access with the type name, using static System.Math; and now when you need to call say Sqrt, you don't need to write Math.Sqrt(...) instead just write Sqrt(...). using CSharp6Features2.Day; //Here Day is an enum which I have defined. so next time I don't need to specify Enum type 'Day' while calling it's property. 3. String interpolation: Get rid of using value tokens with "string.Format" to format string. Example: Old way: string fName = "Binod", lName = "Mahto"; Console.WriteLine(string.Format("My name is {0} {1}", fName, lName)); in C#6.0 string fName = "Binod", lName = "Mahto"; Console.WriteLine($"My name is {fName} {lName}"); 4. Expression-bodied properties: Convert your methods or properties which returns data based on some calculation, to one line code like property using lambda expression. for example: Old way: private double GetFullName(string fname, string lname) { return fname + " " + lname; } in C# 6.0 public string FullName => $"{fname} {lname}"; 5. Index Initializers: C# 6.0 has extended the object initializers to allow to set values to keys through any indexer that the new object has. Example: Old Way: public JObject ToJson() { var obj = new JObject(); obj["X"] = "Binod"; obj["Y"] = "Mahto"; return obj; } in C#6.0: public JObject ToJson() { var obj = new JObject() {["FName"] = "Binod",["LName"] = "Mahto" }; return obj; } OR public JObject ToJson() => new JObject() {["FName"] = "Binod",["LName"] = "Mahto" }; 6. Null-conditional operators(?): It helps to avoid lot of codes which we write while accessing objects, like do null check for objects then do null check of that objects properties and so on. Let see the example: Old way: public string FromJson(JObject json) { if(json != null && json["FName"] != null && json["FName"].Type == JTokenType.String & json["LName"] != null && json["LName"].Type == JTokenType.String) { return $"{json["FName"]} {json["LName"]}"; } return string.Empty; } in C# 6.0 public string FromJson(JObject json) { if (json?["FName"]?.Type == JTokenType.String && json?["LName"]?.Type == JTokenType.String) { return $"{json["FName"]} {json["LName"]}"; } return string.Empty; } it is also very useful to do the event null check before triggering the event. Ex: OnChanged?.Invloke(this, args); in this case event will be triggered only if event is not null. 7. The nameof operator: There are scenarios when we need to know the name of program elements (property/parameter name), specially while throwing exceptions. private static int Calculate(ABC obj) { if (obj.y == 0) throw new DivideByZeroException(nameof(obj.y)); else return obj.x / obj.y; } At last, this is the feature which I noticed in Visual Studio 2015 which impressed me a lot. Your visual studio itself will let you know about some tips to clean your code (as Resharper does) Ex: namespace references in using directive which are not used. There are lot many, I am sure these features you are going to love it. That's it. Thank You for reading. Feel free to give your feedback/comment.
http://binodmahto.blogspot.com/2015/09/whats-new-in-c-60.html
CC-MAIN-2017-39
refinedweb
604
58.48
Transactional Interceptors By Linda DeMichiel on May 24, 2012 As part of our goal of aligning managed bean technology across the Java EE Platform, one of the improvements we've targeted for Java EE 7 is a JTA transactional interceptor facility. The intent here is to bring the ease of use of EJB's "container-managed" transactions to the platform as a whole via a more general solution based on CDI interceptors so that these would be usable both by CDI managed beans and other Java EE components. There has been large-scale support for this direction from members of the Java EE 7 Platform Expert Group. To achieve this, we plan to add an annotation and standardized values in the javax.transaction package. For example: @Inherited @InterceptorBinding @Target({TYPE, METHOD}) @Retention(RUNTIME) public @interface Transactional { TxType value() default TxType.REQUIRED } public enum TxType { REQUIRED, REQUIRED_NEW, MANDATORY, SUPPORTS, NOT_SUPPORTED, NEVER } public class ShoppingCart { ... @Transactional public void checkOut() {...} ... } Our plan is to define the semantics of the corresponding interceptor classes as part of an update to the JTA spec. This work will be done under the Java EE 7 umbrella as part of the JTA spec project on java.net. The hard part, as usual, will be nailing down the details. A point on which we've had considerable discussion (but haven't yet converged) has to do with how the exceptions which reach a transactional interceptor affect the transaction in progress. - Do they always cause rollback? - Do they never cause rollback? - Do they cause rollback only if they are runtime exceptions? - Do they cause rollback unless this behavior is overridden by annotations? - Do they never cause rollback unless this behavior is overridden by annotations? - If the overriding of behavior is configurable by annotations, what form do these annotations take? While most members of the Java EE 7 Expert Group agree that some exceptions should result in the current transaction being marked for rollback, there is a wide range of opinion as to how this should best be made configurable. You can read the details of our discussion on the thread that starts here. Before trying to resolve this, we'd really like to get feedback from more of the developer community. You can help contribute to this discussion by posting your input here, by joining the users@javaee-spec.java.net email list on the Java EE spec project and adding to the thread, and/or by joining the JTA spec project. Thanks!
https://blogs.oracle.com/ldemichiel/date/201205
CC-MAIN-2015-27
refinedweb
413
53.21
Create an Image Cropping Application in Flash with ActionScript 3 Get a free year on Tuts+ this month when you purchase a Siteground hosting plan from $3.95/mo In this Premium Tutorial, we'll learn how to manipulate Bitmaps in ActionScript 3 to produce a helpful image cropping application. Keep reading! Final Result Preview Image by Swami Stream licenced under Creative Commons. Step 1: Overview Using the Flash Tools we'll create an attractive interface that will be powered by several ActionScript 3 classes like MouseCursor, Bitmap, BitmapData, Rectangle, Point, Tween, FileReference and even external libraries. The user will be able to crop an image multiple times to later select the best option and save it to disk. Step 2: Set Up Flash Open Flash and create a 600 pixels wide, 400 pixels tall document. Set the Frame rate to 24fps. Step 3: Interface A nice looking mac-like interface will power our code, this involves multiple timeline based buttons, custom cursors and more. Continue to the next steps to learn how to create this GUI. Step 4: Background No science in the background, just create a 600x400px black rectangle and center it in the stage. You can also change the background color in the Stage Properties. Step 5: Image We will need an image to crop, select your prefered image and import it to the stage (Cmd + R). Image by Swami Stream licenced under Creative Commons. Step 6: Custom Cursor We'll make a custom cursor to use it as feedback to the user, letting him know where he can crop. Select the Rectangle Tool (R) and make a 3px wide, 17px tall white rectangle. Duplicate the shape (Cmd+D) and rotate it 90 degrees to form a cross. Repeat this process with a 1px wide, 15 px tall black rectangle. Convert the final shape to MovieClip (F8) and set its instance name to cursor. Step 7: Action Buttons These buttons handle secondary actions based in the crop, these actions are: - Save: Saves the current crop. - Cancel: Returns the current crop to its position and brings back the original image. - Clear: Erases all the crops and brings back the original image. Select the Rectangle Primitive Tool (R) and change the corner radius to 10, draw a 70x18px rectangle and fill it with #666666. Duplicate the shape (Cmd + D), resize it to 68x16px and change its color to this linear gradient #222222 to #444444. Use the Gradient Transform Tool (F) to rotate the gradient. Next, use the Text Tool (T) to write a label for the button. Use this format: Lucida Grande Regular, 12pt, #CCCCCC. Use the same technique to create the Cancel and Clear buttons. Step 8: Buttons Timeline A well made GUI button has 4 states: - Up: The normal state of the button. - Over: The graphics shown when the Mouse Cursor is over the button. - Down: Shown when the Mouse is clicking the button. - Hit: The area where the mouse can click. Convert your buttons to MovieClip and double click them to enter edit mode. Open the Timeline Panel (Window > Timeline). You'll notice that the Up state is already created, these are the shapes you converted to MovieClip. Press F6 to create a new Frame and change the center shape gradient fill to #222222, #5B5B5B. This will be the Over state. For the Down state, select the center shape and flip it vertically (Modify > Tranform > Flip Vertical). The Hit state is by default, the bigger shape area, as the clickable area we want is the whole button, there will be no need to create a frame for this. Step 9: Position and Instance Names When all your buttons are ready, exit edit mode and place them as shown in the following screenshot. The white text indicates the button instance name. Step 10: Button Bar A button bar will be used to place and highlight the crop button. Use the Rectangle Tool to create a 600x50 px rectangle and fill it this gradient fill #AFAFAF to #C4C4C4. Align the bar in the bottom of the stage. To create a embossed effect, draw two 600x1px lines and place them above the button bar, fill the top one with #858585 and the other with #D8D8D8. Step 11: Crop Button The Crop button will start the Main ActionScript function that will manipulate the bitmaps in the stage. With the Rectangle Tool, create a 33x6px and a 26x6px rectangles and use them to form a right angle. Duplicate the shape and rotate it 180 degrees to form a square. Move the duplicated shape 5px up and 5px to the right. Fill the resulting shape with this gradient fill: #444444 to #222222. Use the Gradient Transform Tool to rotate the fill. You can add more detail by adding a shadow; duplicate the current shape and move it 1px down and 1px right. Lastly, convert the shape to MovieClip and name it cropButton. Step 12: Crop Shape The crop shape is an image that will be used to indicate the area that will be cropped. Select the Rectangle Tool and change the stroke color to white and the fill color to white with 1% alpha (this will help us drag the crop shape). Draw a 10x10px square and center it. Select a 1px part of the square and change its color to black. Duplicate the shape and do the same on all the side. Repeat this process on all the sides. Convert the result to MovieClip and name it cropShape, mark the Export for ActionScript box. Double click it to enter edit mode, create a new Keyframe in frame 5 and rotate the shape 180 degrees. Add 4 frames more and exit edit mode. This ends the graphic part, let's start with ActionScript! Step 13: New ActionScript Class Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder. Step 14: 15: Import Directive These are the classes we'll need to import for our class to work, the import directive makes externally defined classes and packages available to your code. import flash.display.Sprite; import flash.events.MouseEvent; import flash.ui.Mouse; import flash.ui.MouseCursor; import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Rectangle; import flash.geom.Point; import fl.transitions.Tween; import fl.transitions.easing.Strong; import flash.net.FileReference; import flash.utils.ByteArray; import com.adobe.images.JPGEncoder; import flash.events.Event; Step 16: JPGEncoder In order to save the image crop, we'll use a class which is part of the as3corelib. Follow the link and download the library. Step 17:: Variables These are the variables we'll use, read the comments in the code to find out more about them. private var cropShape:CropShape; //This is an instance of the cropShape we created before private var pointX:Number; //This var will hold the x position where the crop shape is started private var pointY:Number; //This var will hold the y position where the crop shape is started private var added:Boolean; //Checks if the crop shape is in stage private var images:Array = new Array(); //Stores the images crops private var bmd:BitmapData; //A bitmap data object, used to manipulate the main image data private var bmd2:BitmapData; //A second bitmap data object, this one will hold the data of the image we want to save private var croppedImage:Sprite; //Holds the cropped images private var cropThumb:int = 0; //The number of thumbs already created private var thumbPosX:Array = [5, 5, 5, 505, 505, 505]; //Stores the x positions of the thumbs private var thumbPosY:Array = [37, 135, 233, 37, 135, 233]; //Stores the y positions of the thumbs private var tween:Tween; //A tween object, the default animation library in flash private var fileReference:FileReference; //Used to save the file to disk private var byteArray:ByteArray; //Stores binary data, used to save the file to disk private var jpg:JPGEncoder = new JPGEncoder(); //The image encoder private var zoomed:Boolean; //Checks if the thumbnail is zoomed in or out private var currentCrop:Bitmap; //Holds the current zoomed thumbnail, the one that will be saved private var currentSprite:*; //Used to know what thumb is active private var latestX:Number; //Checks the latest x of the zoomed thumb private var latestY:Number; //Checks the latest y of the zoomed thumb Step 19: Constructor The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class. public function Main():void { Step 20: Initial Listeners These are the listeners that will be defined at launch, they basically add Mouse related events to buttons. image.addEventListener(MouseEvent.MOUSE_DOWN, getStartPoint); image.addEventListener(MouseEvent.MOUSE_UP, stopDrawing); cropButton.addEventListener(MouseEvent.MOUSE_UP, crop); image.addEventListener(MouseEvent.MOUSE_OVER, customCursor); image.addEventListener(MouseEvent.MOUSE_OUT, removeCustomCursor); saveButton.addEventListener(MouseEvent.MOUSE_UP, saveImage); cancelButton.addEventListener(MouseEvent.MOUSE_UP, cancel); clearButton.addEventListener(MouseEvent.MOUSE_UP, clearThumbs); Step 21: Hide Buttons This code hides the buttons that aren't in use at the moment. saveButton.visible = false; cancelButton.visible = false; clearButton.visible = false; cursor.visible = false; Step 22: Add Custom Cursor The following function makes the custom cursor visible when the mouse pointer is over the main image. private function customCursor(e:MouseEvent):void { cursor.visible = true; Mouse.hide(); cursor.startDrag(true); } Step 23: Remove Custom Cursor Hides the custom cursor when the mouse pointer leaves the main image. private function removeCustomCursor(e:MouseEvent):void { cursor.visible = false; Mouse.show(); cursor.stopDrag(); } Step 24: Get Start Point A very important function, gets and stores the mouse click coordinates and places the cropShape movieclip in them, the current value will be used later to determine the size of the crop shape. private function getStartPoint(e:MouseEvent):void { pointX = mouseX; pointY = mouseY; if (! added) { cropShape = new CropShape(); cropShape.x = pointX; cropShape.y = pointY; addChild(cropShape); added = true; } else { removeChild(cropShape); cropShape = new CropShape(); cropShape.x = pointX; cropShape.y = pointY; addChild(cropShape); } Step 25: Crop Mouse Listeners Adds a listener in the main image to expand the crop shape on mouse movement and adds the listener to stop expanding on mouse up. image.addEventListener(MouseEvent.MOUSE_MOVE, drawCropShape); cropShape.addEventListener(MouseEvent.MOUSE_UP, stopDrawing); Step 26: Draw Crop Shape Expands the cropShape according to the saved coordinates and the current ones. private function drawCropShape(e:MouseEvent):void { cropShape.width = mouseX - pointX; cropShape.height = mouseY - pointY; } Step 27: Stop Crop Shape Stops the crop shape expansion and adds some listeners that will be used by the next functions. private function stopDrawing(e:MouseEvent):void { image.removeEventListener(MouseEvent.MOUSE_MOVE, drawCropShape); cropShape.addEventListener(MouseEvent.MOUSE_OVER, showHandCursor); cropShape.addEventListener(MouseEvent.MOUSE_OUT, hideHandCursor); cropShape.addEventListener(MouseEvent.MOUSE_DOWN, dragCrop); cropShape.addEventListener(MouseEvent.MOUSE_UP, stopDragCrop); } Step 28: Show Hand Cursor Uses the Mouse class to manipulate the mouse cursor, this code will show the Hand cursor when the mouse is over the crop shape. private function showHandCursor(e:MouseEvent):void { Mouse.cursor = MouseCursor.HAND; } Step 29: Hide Hand Cursor Restores mouse cursor original behaviour. private function hideHandCursor(e:MouseEvent):void { Mouse.cursor = MouseCursor.AUTO; } Step 30: Drag Crop The crop shape will be draggable, this will help select the area we want easily. private function dragCrop(e:MouseEvent):void { cropShape.startDrag(); } Step 31: Stop Drag Crop Stops the drag on mouse up. private function stopDragCrop(e:MouseEvent):void { cropShape.stopDrag(); } Step 32: Crop Function This function will handle the image cropping, using the images bitmap data and the sprite class to create a series of thumbnails that will be elegible to save. private function crop(e:MouseEvent):void { Step 33: Bitmap Data The next lines handle the bitmap data required to crop the image. bmd = new BitmapData(image.width,image.height,false,0x00000000); //Creates a new bitmap data object using the size of the main image bmd.draw(image); //Copies the main image data to the instance bmd2 = new BitmapData(cropShape.width,cropShape.height,false,0x00000000); //Creates a new bitmap data using the actual size of the crop shape Step 34: Copy Image Pixels The next line copies the pixels of the main Image situated in the crop shape position to the bitmap data object bmp2. The parameters work as listed below: - bmd: The source bitmap data to copy from, the main image - Rectangle: Specifies the position of the pixels to copy, the crop shape position - Point: Specifies the point to start copying, from the point 0 of the rectangle bmd2.copyPixels(bmd, new Rectangle(cropShape.x - image.x, cropShape.y - image.y, cropShape.width, cropShape.height), new Point(0, 0)); Step 35: Create Thumbnail We are going to let the user crop six times and save those previews at the side of the main image, for that, we create a new bitmap that will store the bitmap data of the cropped thumbnail and then we add it as a 90x70px sprite. We also add a listener to zoom in and out the thumbnail. if(cropThumb < 6) { var bmp:Bitmap = new Bitmap(bmd2); var thumb:Sprite = new Sprite(); thumb.addChild(bmp); thumb.width = 90; thumb.height = 70; thumb.addEventListener(MouseEvent.MOUSE_UP, zoomThumb); addChild(thumb); Step 36: Access Thumbnail As we create a new sprite in every crop, the last sprite will be inaccesible using its instance name, time to use the array we created before. This array will store the created thumbnails to access them outside the function. images.push(thumb); Step 37: Tween Thumbnails When the user presses the crop button a thumbnail is created using the cropped image, this thumbnail is later animated to the sides of the application depending on a variable. The thumbnail position is determined by this variable and the thumbPos arrays. tween = new Tween(thumb, "x", Strong.easeOut, cropShape.x, thumbPosX[cropThumb], 0.5, true); tween = new Tween(thumb, "y", Strong.easeOut, cropShape.y, thumbPosY[cropThumb], 0.5, true); cropThumb++; // Adds one to the number of thumbs Step 38: Save Image). private function saveImage(e:MouseEvent):void { fileReference = new FileReference(); byteArray = jpg.encode(currentCrop.bitmapData); fileReference.save(byteArray, "Crop.jpg"); fileReference.addEventListener(Event.COMPLETE, saveComplete); } Step 39: Save Complete Once the image is saved, the thumbnails are removed from the stage and from the array. The buttons are hidden and the main image returns. private function saveComplete(e:Event) 40: Cancel There is also a cancel button that will let you browse through the thumbnails without saving any of them. When this button is pressed it returns all the thumbnails to postition and brings back the main image to crop more (if possible). private function cancel(e:MouseEvent):void { tween = new Tween(currentSprite,"width",Strong.easeOut,currentSprite.width,90,0.5,true); tween = new Tween(currentSprite,"height",Strong.easeOut,currentSprite.height,70,0.5,true); tween = new Tween(currentSprite,"x",Strong.easeOut,currentSprite.x,latestX,0.5,true); tween = new Tween(currentSprite,"y",Strong.easeOut,currentSprite.y,latestY,0.5,true); tween = new Tween(image,"y",Strong.easeOut,image.y,stage.stageHeight / 2 - image.height / 2 - 30,0.5,true); added = false; saveButton.visible = false; cancelButton.visible = false; clearButton.visible = false; cropButton.visible = true; zoomed = false; } Step 41: Clear Thumbnails If the user has cropped the 6 times allowed by the app, and none of them is the expected result, there's always a way to crop even more times. This is the task that the clear button will achieve. It removes all thumbnails from the stage and from the array, returns the main image to stage and hides the unused buttons. private function clearThumbs(e:MouseEvent) 42: Document Class We'll make use of the Document Class in this tutorial, if you don't know how to use it or are a bit confused please read this QuickTip. Conclusion The final result is a helpful Image Cropping application that teaches you how to manipulate bitmaps to modify them, and almost without knowing it, you also learned how to create and implement a very nice interface. I hope you liked this tutorial, thank you for reading! Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
http://code.tutsplus.com/tutorials/create-an-image-cropping-application-in-flash-with-actionscript-3--active-4598
CC-MAIN-2015-22
refinedweb
2,691
65.83
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo Ok, you have the following problems: 1) If you do not start a toplevel there will not be any active restarts. This is logical: it is your program's responsibility to set them up! So if you want a function to be able to use ABORT then define an evaluating function that sets the restart up. 2) You are using cl_eval(...) which does not set up those restarts. ECL ships with a function, si_safe_eval (ext:safe-eval) which performs evaluation in a safe way, with a handler for errors that returns a default value. 3) It is recommended generally to have a catch-all region around your C code. This sets up a point that protects from unwanted QUIT statements and sets up a point to jump to in case of stack overflows, memory exhaustion, etc See 4) Instead of c_string_to_object() you might want to use ecl_read_from_string_safe(s,v) where "v" is the value returned in case of error condition. The program, in one possible shape #include <ecl/ecl.h> #define READCL(expr) (c_string_to_object(# expr)) int main(int argc, char **argv) { cl_object x; cl_boot(1, &argv[0]); CL_CATCH_ALL_BEGIN(ecl_process_env()) { x = c_string_to_object("(format t \"Hello~%\")"); cl_print(1,x); x = si_safe_eval(3, x, Cnil, Cnil); cl_print(1,x); // Forces program to halt, reading from stdin x = c_string_to_object("(vvvvformat t \"Hello~%\")"); cl_print(1,x); x = si_safe_eval(3, x, Cnil, Cnil); cl_print(1,x); } CL_CATCH_ALL_END; cl_shutdown(); } The output is fine (notice lack of error messages!) (FORMAT T "Hello~%") Hello NIL (VVVVFORMAT T "Hello~%") VVVVFORMAT NIL -- Instituto de Física Fundamental, CSIC c/ Serrano, 113b, Madrid 28006 (Spain) Hi, I am having a lot of trouble figuring out how to prevent the debugger becoming active in embedded mode. I have tried: + Calling ecl_disable_interrupts(); before cl_eval() + Executing the following in ecl: (setf *debugger-hook* #'debug-ignore) + And also this: (setf si::*interrupt-enable* nil) Mmm... I want to evaluate something like si_safe_eval(3,c_string_to_object("(vvvvformat t \"Hello\")"), Cnil, OBJNULL); and not have my program stop. Logging something would be fine. When I execute the following code, #define READCL(expr) (c_string_to_object(# expr)) int main(int argv, char* argv[]) { char* exec_name = (char*) get_exec_name(); cl_boot(1, &argv[0]); ecl_disable_interrupts(); // Initialise the whispy-one lisp environment cl_eval(READCL((setf *debugger-hook* #'debug-ignore))); cl_eval(READCL((setf si::*interrupt-enable* nil))); // All good cl_eval(READCL((format t "Hello~%"))); // Forces program to halt, reading from stdin cl_eval(READCL((vvvvformat t "Hello~%"))); cl_shutdown(); } I get this: Hello VVVVFORMAT #<a UNDEFINED-FUNCTION> Condition of type: SIMPLE-CONTROL-ERROR Restart ABORT is not active. No restarts available. Top level in: #<process TOP-LEVEL>. > And my program is stuck. Logging something would be fine, but freezing the program is no good. Thanks in advance On Tue, Feb 22, 2011 at 6:07 AM, <aaron@...> wrote: > Hi, I am having a lot of trouble figuring out how to prevent the debugger > becoming active in embedded mode. > I have tried: > + Calling ecl_disable_interrupts(); before cl_eval() > Nothing to do with that. These are Unix interrupts > + And also this: (setf si::*interrupt-enable* nil) > See above. > + Executing the following in ecl: (setf *debugger-hook* #'debug-ignore) > What does your *debugger-hook* function do? Just returning? This is not going to work at all. First try doing it in Common Lisp, then port the stuff to your program > Mmm... I want to evaluate something like > si_safe_eval(3,c_string_to_object("(vvvvformat t \"Hello\")"), Cnil, > OBJNULL); > Problem 1: the expression you are going to evaluate is ill formed. SAFE-EVAL can not protect you because the error happens _before_ this function is ever invoked. Problem 2: your debug-ignore function does not do what is expected to do. When an error handler is invoked it should either offer an interactive debugger or perform some transfer of control to an outer point, as in (block nil (handler-bind ((error #'(lambda (c) (return 2)))) (cos 'a))) I presume that debug-ignore does not do this: it simply returns and the debugger just gets invoked again (the error has not been solved). Alternative: if you know you are going to get ill formed expressions, convert the READ_CL forms into a standalone function that detects and ignores errors. Fortunately there is an undocumented function that c_string_to_object is based on #define ecl_read_from_cstring(s) si_string_to_object(1,make_constant_base_string(s)) #define ecl_read_from_cstring_safe(s,v) si_string_to_object(2,make_constant_base_string(s),(v)) The second version does it safely. Juanjo -- Instituto de Física Fundamental, CSIC c/ Serrano, 113b, Madrid 28006 (Spain) > > What does your *debugger-hook* function do? Just returning? This is not > going to work at all. First try doing it in Common Lisp, then port the > stuff > to your program Opps, it went: (defun debug-ignore (c h) (declare (ignore h)) (print c) (abort)) I tried this as well (defun debugger-stub (condition hook) (declare (ignore hook)) (when (find-restart 'abort condition) (format *error-output* "~&~a~% [Condition of type ~a]~%" condition (type-of condition)) (abort condition))) Neither worked... and neither did running: (block nil (handler-bind ((error #'(lambda (c) (return 2)))) (cos 'a))) The behaviour is different in the ECL command line, as opposed to the embedded ECL. In the command-line REPL, the error is ignored and ECL is ready for more action. However, in the embedded version, it says: <snip> VVVVFORMAT Condition of type: UNDEFINED-FUNCTION The function VVVVFORMAT is undefined. No restarts available. Top level in: #<process TOP-LEVEL>. > </snip> Okay..., so there is no restart available, and no aborts either it would seem. I don't even know what to type into the prompt to get it to continue the execution. For example, typing <snip> > (abort) Debugger received error of type: SIMPLE-CONTROL-ERROR Restart ABORT is not active. Error flushed. > </snip> I went to try the ecl_read_from_cstring_safe(s,v) macro... what is the value of v? Thanks in advance Thanks, it works now, and my mind has been expanded, Aaron
http://sourceforge.net/p/ecls/mailman/message/27102126/
CC-MAIN-2015-22
refinedweb
989
52.09
The only thing i seen was using pg.mixer.music.queue() after load to queue in the next song. But that has been unsuccessful for me. It never goes to the next song. The other thing would be hoe to randomize the playlist once you start to get it working? It appears that you cannot do the same method with music as you can with images....load them in a list, and loop and display them, or rather loop them and play them? - Code: Select all class Music: def __init__(self): self.path = 'resources/music' self.load() def load(self): for f in os.listdir(self.path): end_path = os.path.join(self.path, f) abspath = os.path.abspath(end_path) pg.mixer.music.load(abspath) pg.mixer.music.queue(abspath) - Code: Select all self.music = Music() pg.mixer.music.set_volume(.1) pg.mixer.music.play(-1, 0.0) I messed around with the first arfument of play() but i am not sure how to get it acting like a playlist.
http://www.python-forum.org/viewtopic.php?f=26&t=9948
CC-MAIN-2016-22
refinedweb
169
71
Message-ID: <1840562339.84902.1397676823210.JavaMail.haus-conf@codehaus02.managed.contegix.com> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_84901_1285379816.1397676823209" ------=_Part_84901_1285379816.1397676823209 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: Note: This page may not follow the explanations from the= JLS. Java has two basic informal rules for scoping: Principle #1: "A variable is only visible in the b= lock it is defined in and in nested blocks". Principle #= 2: "A variable can't be visible more than one time". Java does know classwide variables and local variables. Local variables = are defined as method parameter or inside the method block. Classwide varia= bles are defined as attributes of the class. Of course Java does violate th= is first principle I showed at top here a little since I can access class w= ide variables from outside the class, if the access modifier is for example= public. A local variable of the same name as an attribute does not violate= the second principle, as the attribute is hidden by the local variable and= with this no longer visible without using a qualifier like "this"= ;. In Groovy we also have these two principles, but since we have different= constructs, we may lay out these principles in a different way. Let us sta= rt with local variables. Scripts are. When you define a variable in a script it is always local. = But methods are not part of that scope. So defining a method using differen= t variables as if they were attributes and then defining these variables no= rmally in the script leads to problems. Example: String attribute =3D "bar" void aMethod(){ assert attribute =3D=3D "bar" // Not allowed ! } aMethod()=20 Executing this code you get an exception talking about a missing propert= y or field. The only things the method has access to are: That's easy. When it is not defined, it is in the binding. String localVar =3D "I am a local variable" bindingVar =3D "I am a binding variable"=20 The trick is - and that is admittedly not easy for Java programers - to = not to define the variable before using it, and it will go= into the binding. Any defined variable is local. Please note: the = binding exists only for scripts. "def" is a replacement for a type name. In variable definition= s it is used to indicate that you don't care about the type. In variable de= finitions it is mandatory to either provide a type name explicitly or to us= e "def" in replacement. This is needed to the make variable defin= itions detectable for the Groovy parser. These definitions may occur for local variables in a script or for local= variables and properties/fields in a class.=20 =20 "def" can also replace "void" as the return type in = a method definiton. def dynamic =3D 1 dynamic =3D "I am a String stored in a variable of dynamic type" int typed =3D 2 typed =3D "I am a String stored in a variable of type int??" /= / throws ClassCastException=20 The assignment of a string, to a variable of type int will fail. A varia= ble typed with "def" allows this. In the terms of the principles above a closure is a block. A variable de= fined in a block is visible in that block and all blocks that are defined i= n that block. For example in Java: { int i=3D1; { System.out.println (i); } }=20. def closure =3D { int i; int i }=20 And of course, the same for combinations with nested closures. def outer =3D { int i def inner =3D { int i } }=20 A block ends with its corresponding "}". So it is allowed to r= euse that name later in a different block. def closure1 =3D { parameter -> println parameter } def closure2 =3D { parameter -> println parameter }=20 Both closures define a local varibale named "parameter", but s= ince these closures are not nested, this is allowed. Note: unlike e= arly versions of Groovy and unlike PHP, a variable is visible in the block,= not outside. Just like in Java. "it" is a special variable name, that is defined automatically= inside a closure. It refers always to the first parameter of the closure, = or null, if the closure doesn't have any parameters. def c =3D { it } assert c() =3D=3D null assert c(1) =3D=3D 1=20 When using nested cosures (closures in closures) the meaning of "it= " depends on the closure you are in. def outer =3D { def inner =3D { it+1 } inner(it+1) } assert outer(1) =3D=3D 3=20 You see, that "it" is used two times, the "it" in &q= uot;inner" means the first parameter of the closure "inner",= the following "it" means the first parameter of "outer"= ;. This helps a lot when copying code from one place to another containing = closure that are using it. "static" is a modifier for attributes (and methods, but this i= s not at issue here). It defines the "static scope". That means a= ll variables not defined with "static" are not part of that stati= c scope and as such not visible there. There is no special magic to this in= Groovy. So for an explanation of "static" use any Java book.
http://docs.codehaus.org/exportword?pageId=58025
CC-MAIN-2014-15
refinedweb
885
63.29
Array.Sort<T> Method (T[], Comparison<T>) Sorts the elements in an Array using the specified Comparison<T>. Assembly: mscorlib (in mscorlib.dll) Parameters - comparison - Type: System.Comparison<T> The Comparison<T> to use when comparing elements. Type Parameters - T The type of the elements of the array. If the sort is not successfully completed, the results are undefined. This method uses introspective sort (introsort) algorithm. For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array. Notes to Callers: The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. Starting with the .NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. For the most part, this applies to arrays with fewer than 16 elements. The following code example demonstrates the Sort(Comparison<T>) method overload. The code example defines an alternative comparison method for strings, named CompareDinosByLength. This method works as follows: First, the comparandsare tested fornull, and a null reference is treated as less than a non-null. Second, the string lengths are compared, and the longer string is deemed to be greater. Third, if the lengths are equal, ordinary string comparison is used. A array of strings is created and populated with four strings, in no particular order. The list also includes an empty string and a null reference. The list is displayed, sorted using a Comparison<T> generic delegate representing the CompareDinosByLength method, and displayed again. using System; using System.Collections.Generic; public class Example { private static int CompareDinosByLength(string x, string y) { if (x == null) { if (y == null) { // If x is null and y is null, they're // equal. return 0; } else { // If x is null and y is not null, y // is greater. return -1; } } else { // If x is not null... // if (y == null) // ...and y is null, x is greater. { return 1; } else { // ...and y is not null, compare the // lengths of the two strings. // int retval = x.Length.CompareTo(y.Length); if (retval != 0) { // If the strings are not of equal length, // the longer string is greater. // return retval; } else { // If the strings are of equal length, // sort them with ordinary string comparison. // return x.CompareTo(y); } } } } public static void Main() { string[] dinosaurs = { "Pachycephalosaurus", "Amargasaurus", "", null, "Mamenchisaurus", "Deinonychus" }; Display(dinosaurs); Console.WriteLine("\nSort with generic Comparison<string> delegate:"); Array.Sort(dinosaurs, CompareDinosByLength); Display(dinosaurs); } private static void Display(string[] arr) { Console.WriteLine(); foreach( string s in arr ) { if (s == null) Console.WriteLine("(null)"); else Console.WriteLine("\"{0}\"", s); } } } /* This code example produces the following output: "Pachycephalosaurus" "Amargasaurus" "" (null) "Mamenchisaurus" "Deinonychus" Sort with generic Comparison<string> delegate: (null) "" "Deinonychus" "Amargasaurus" "Mamenchisaurus" "Pachycephalosaurus" */ Available since 4.5 .NET Framework Available since 2.0 Portable Class Library Supported in: portable .NET platforms Silverlight Available since 2.0 Windows Phone Silverlight Available since 7.0 Windows Phone Available since 8.1
https://msdn.microsoft.com/en-us/library/cxt053xf.aspx
CC-MAIN-2016-07
refinedweb
535
60.61
by Stanislav Termosa An Introduction to Flutter: The Basics I’ve been hearing about how amazing Flutter is and I’ve decided to try it out to learn something new. I wished to have more topics to discuss with colleagues. It started by watching, then reading, and then I started coding. It was a good experience. Apps were running, and everything that was written wasn’t hard to understand. However, the process wasn’t smooth enough - some of the details were not explained in that resources. Also, since everything was new to me (the platform itself, programming language, approaches and even mobile app development), the lack of those details was painful. Any time something didn’t work, I didn’t know what to Google: Dart, Flutter, Window, Screen, Route, Widget? I decided that reading the documentation on Dart, Flutter and all of its widgets wouldn’t be a good idea as it would be too time consuming. Also, I didn’t have a lot of time as the purpose was to get to know the new thing, and not to become an expert in the field. I thought at that moment that it would be amazing if there was a short guide on Flutter, that would describe all the necessary concepts to understand the framework and be able to write simple apps, but no more! About The Guide Most of the articles on this topic are well written and straightforward. The problem is that they require you to know some basic things, and those small things are not described in articles that are suppose to give you basic knowledge. In this series, I’ll try to avoid that problem. We’ll start from scratch and create applications sorting out every step we do. During this series, we will use all basic widgets, design a unique interface, interact with native modules, and build our app for both iOS and Android platforms. This series is written from the perspective of a web developer. Most of you are probably familiar with this stack. The analogy with a familiar platform is better than one where you have to build houses or use Animal, Dog, Foo, Bar, etc. I’ll keep it short, to save your time. For the most curious of you, I’ll put useful links around the text. About The Platform Flutter is very new, but a promising platform, that has attracted the attention of large companies who’ve released their apps already. It is interesting because of its simplicity compared to developing web applications, and because of its speed as compared with native applications. High performance and productivity in Flutter are achieved by using several techniques: - Unlike many other popular mobile platforms, Flutter doesn’t use JavaScript in any way. Dart is the programming language. It compiles to binary code, and that’s why it runs with the native performance of Objective-C, Swift, Java or Kotlin. - Flutter doesn’t use native UI components. That may sound awkward at first. However, because components are implemented in Flutter itself, there is no communication layer between the view and your code. Due to this, games hit the best speed for their graphics out of the smartphones. So buttons, text, media elements, background are all drawn by Flutter’s graphics engine. As an aside, it should be mentioned that the bundle of the Flutter “Hello, World” application is quite small: iOS ≈ 2.5Mb and Android ≈ 4Mb. - Flutter uses a declarative approach, inspired by the React web framework, to build its UI based on widgets (named “components” in the world of the web). To get more out of widgets, they are rendered only when necessary, usually when their state has been changed (just like the Virtual DOM does for us). - In addition to all of the above, the framework has integrated Hot-reload, so typical for the web, but still missing on native platforms. This allows the Flutter framework to automatically rebuild the widget tree, allowing you to quickly view the effects of your changes. There is an excellent article on the practical use of these features from an Android developer who recreated his application from Java to Dart and shared his impressions. I wanted to share with you some numbers from his article. - Java (before): Number of files = 179 and Lines of code 12,176 - Dart (after): Number of files = 31 and Lines of code 1,735. You can read more about the technical details of the platform or look at examples of applications. About Dart Dart is a programming language that we’ll use to develop our application in Flutter. Learning it isn’t hard if you have experience with Java or JavaScript. You will quickly get it. I tried to write an article on Dart for you, to describe the minimal scope that is required for Flutter. After several attempts, I was still failing to write it so that it was short and covered the core concepts at the same time. Authors of A Tour of the Dart Language coped well with this task! Initial Setup This topic, just like a Dart, is well covered in the official guide — so I won’t copy it here. Go through this short setup guide, by choosing your OS and following it step-by-step. Also, configure your preferred editor to work with Dart and Flutter (usually it requires 2 different plugins). Run your application to make sure that you are ready to continue. Here is a tip for MacOS users. If you don’t like how much space is wasted by virtual device bezels, you can turn them off, and switch to an iPhone 8 model (it is not as long as iPhone X): - Hardware → Device → iOS # → iPhone 8 - Window → Show Device Bezels It is possible to live without virtual buttons as we have hot keys: Shift + Cmd (⌘) + H - go home, Cmd (⌘) + Right - rotate the phone, and you can find more in the Hardware menu. I would also recommend to turn on the on-screen keyboard, as it is important to understand if your application is usable when half of the screen is overlapped. To do so you press Cmd (⌘) + K after you focus on an input field. Project Structure Let’s first see what’s in the project generated by the Flutter framework: - lib/ - just as pub (Dart’s package manager), all the code will be here - pubspec.yml - stores a list of packages that are required to run the application, just like package.json does it. You should remember that in Flutter projects you cannot use pub directly, but instead, you will use the Flutter command: flutter pub get <package_name> - test/ - I’m sure you know what this is about. Right? You can run them via flutter test - ios/ & android/ - the code specific for each platform, including app icons and settings where you set what permissions you’ll need for your application (like access to location, Bluetooth). We don’t need to know more about the files in the folder for now. Let’s open the lib/ folder where main.dart is waiting for us. As you can guess this one is the entry point of our application. Just like in the C language (or tons of others) the app will be executed by calling the main() function. About widgets (Hello World is here) In Flutter everything is built on Widgets. UI elements, styles, themes, and even state is managed in specific Widgets. Let’s start from a small application. Replace the code from main.dart with the one given below, read the comments, and run the application. import 'package:flutter/widgets.dart'; // basic set of widgets // When Dart is running the application, it calls to the main() function main() => runApp( // The function runApp() starts the Flutter application Text( // this is a widget, it renders the given text (think of it like a <span>) 'Hello, World!!!', // the first argument is a text that needs to be rendered textDirection: TextDirection.ltr, // here we set the direction "left to right" ), ); runApp(…) only has a widget argument. The widget will become the root widget for the whole application. BTW, changing the root widget cannot be handled by Hot-reload so you’ll have to restart your application to see changes. Text(…) - Flutter cannot render text without knowing what’s the preference for text direction. To render text, we have to set Text.textDirection. Don’t confuse it with the CSS text-align rule. It is the analogy of direction - the part of the internationalization API. However, don’t worry, we won’t need to set it for each Text widget - later we’ll see how to set it for the whole app. Is your application running already? Yay! “Hello, World!” is on the screen now. Right? Eh, something went wrong. The text is overlapped by the notch. We can use the whole screen for our application, and we have printed our content at the very top of it where system information is also rendered. Let’s try to shift our content. import 'package:flutter/widgets.dart'; main() => runApp( Center( // The widget that aligns content in the center child: Text( 'Hello, World!', textDirection: TextDirection.ltr, ), ), ); Center(…) is the widget that aligns another widget given in child property in the center of itself. You’ll often see child and children properties in Flutter applications, because almost all widgets are using them if they need one or several widgets to be rendered inside of them. A composition of widgets in Flutter is used to represent an interface, to change its look, and to share data. For example, Directionality(…) sets the direction for the text for all nested widgets (so we don’t need to specify it for Text every time). import 'package:flutter/widgets.dart'; main() => runApp( Directionality( textDirection: TextDirection.ltr, child: Center( child: Text('Hello, World!'), ), ), ); Let’s take a look at one very important widget, and change the design of our application: import 'package:flutter/widgets.dart'; main() => runApp( Directionality( textDirection: TextDirection.ltr, child: Container( // the new widget! It is <div> for the Flutter's world // For [Container], property [color] means the color of the background color: Color(0xFF444444), child: Center( child: Text( 'Hello, World!', style: TextStyle( // we use the [TextStyle] widget to customize text color: Color(0xFFFD620A), // set the color fontSize: 32.0, // and the font size ), ), ), ), ), ); There are several options on how to use the Color(…) widget. We have used the widget with the number given to it using hexadecimal notation. This looks almost the same as we set HEX-colors on the web, but here we have 2 additional symbols at the beginning. This is a number that represents the transparency where 0x00 is fully transparent, and 0xFF is not transparent at all. TextStyle(…) is more interesting. You can use it to set a color, font size and weight, line spacing, underline text, etc. The Flutter application is complete! You can read how to build it for Android and iOS, where you can also learn how to publish it to the relevant app store. If it’s not enough for you, I’ve covered a few more topics below. About Stateless Widgets Now we know how easy it is to use widgets. The next logical step would be to create our widgets. I’ve mentioned before that there are two kinds of widgets (actually more, but let’s not over complicate it for now). There are stateless and stateful widgets. We’ve been using stateless widgets in the previous examples. “Stateless” doesn’t mean they don’t have a state at all. Widgets are Dart classes, that can be declared with properties. But changing those properties in a stateless widget won’t affect what has already been rendered. Updating properties of a stateful widget will trigger life cycle hooks and render its content using the new state. We’ll start with Stateless widgets as they seem to be a bit easier. To create one, we need: - A beautiful name for the new class. - To extend our class from StatelessWidget. - Implement the build() method, that will receive one argument of type BuildContext and return a result of type Widget. import 'package:flutter/widgets.dart'; main() => runApp( Directionality( textDirection: TextDirection.ltr, child: Center( child: MyStatelessWidget() ), ), ); class MyStatelessWidget extends StatelessWidget { // @override annotation is needed for optimization, by using it // we say that we don't need the same method from the parent class // so the compiler can drop it @override Widget build(BuildContext context) { // I'll describe [context] later return Text('Hello!'); } } An example of the widget with an argument: // … class MyStatelessWidget extends StatelessWidget { // All properties of the Stateless widget must be declared with final or const keyword final String name; // usual class property MyStatelessWidget(this.name); // usual class constructor @override Widget build(BuildContext context) { // it is yet to early to describe [context] return Text('Hello, $name!'); } } I have nothing more to add about Stateless widgets. They are simple. About Hot Reload Notice that once we have moved our application content to the separate widget, the application is re-rendered each time we save our changes. This is hot-reload in action. It is also crucial to understand, that while you are working in development mode with hot-reload enabled, the application will work much slower than in release mode. About GestureDetector We will create a StatefulWidget in the next section. To make sure it will be interesting we need to be able to change the state of the widget, right? We’ll use GestureDetector(…) for this purpose. This widget will not render anything to the screen but handles user interaction with the screen and calls related functions given to it. The example below creates a blue button in the center of the screen, and once this button is pressed, the text is printed to the terminal: import 'package:flutter/widgets.dart'; main() => runApp( Directionality( textDirection: TextDirection.ltr, child: Container( color: Color(0xFFFFFFFF), child: App(), ), ), ); class App extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: GestureDetector( // just a normal widget onTap: () { // one of the [GestureDetector] properties // This function will be called when child widget is pressed print('You pressed me'); }, child: Container( // the [Container] will represent our button decoration: BoxDecoration( // this is how you style the [Container] shape: BoxShape.circle, // change its shape from rectangular to circular color: Color(0xFF17A2B8), // and paint it in blue ), width: 80.0, height: 80.0, ), ), ); } } Press the button, and the message will be printed to the terminal. Press it again, and the text will appear again. About Stateful Widgets StatefulWidget’s are simple. Yeah, even simpler than StatelessWidget’s! However, there is a nuance. They do not exist by themselves. They require an extra class to store the state of the widget. Moreover, the visual part of the widget becomes its state. Here is the example of the StatefulWidget class: // … class Counter extends StatefulWidget { // The state is stored not in the widget, but in the specific class // that is created by createState() @override State<Counter> createState() => _CounterState(); // The result of the function is an object, that must be // of the type State<Counter> (where Counter is the name of our widget) } We’ve created an “empty” widget that implements only one method and doesn’t contain state or UI representation. Forcing such separation, Flutter seeks greater optimization of the application. The state object is also not complicated. Indeed, it is just like our StatelessWidget. The main difference is its parent class. // … class _CounterState extends State<Counter> { // Finally, we can declare dynamic variables inside of our classes, // to store the state of our widgets // In this case, we'll store the number int counter = 0; // The rest is super simple, we just implement the familiar to us build() method, // in the same way as we did it for our [StatelessWidget] @override Widget build(BuildContext context) { // Almost nothing has changed since the last example. // I've added comments to highlight the difference return Center( child: GestureDetector( onTap: () { // Once the button is tapped we increase the value of [counter] variable setState(() { // Using setState() is required to trigger lifecycle hooks // so the widget will know that it should be updated ++counter; }); }, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Color(0xFF17A2B8), ), width: 80.0, child: Center( child: Text( // here we print the value of the [counter] '$counter', // to see how it changes style: TextStyle(fontSize: 30.0), ), ), ), ), ); } } I named our state class starting with an underscore. In the Dart language all names that begin with an underscore are private (unlike JavaScript or Python they are truly unavailable outside of the library). Usually, we don’t need to expose our state classes outside of the library, so it is good practice to keep them private. We’ve built such a wonderful application. Great result! Before we end this part, let’s take a look at a few more interesting widgets. This time we’ll write more code at once, and I won’t explain every line. You can probably already understand most of the code: import 'package:flutter/widgets.dart'; main() => runApp(App()); class App extends StatelessWidget { @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Container( padding: EdgeInsets.symmetric( vertical: 60.0, horizontal: 80.0, ), color: Color(0xFFFFFFFF), child: Content(), ), ); } } class Content extends StatelessWidget { @override Widget build(BuildContext context) { return Column( children: [ Counter('Manchester United'), Counter('Juventus'), ], ); } } class Counter extends StatefulWidget { final String _name; Counter(this._name); @override State<Counter> createState() => _CounterState(); } class _CounterState extends State<Counter> { int count = 0; @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.only(bottom: 10.0), padding: EdgeInsets.all(4.0), decoration: BoxDecoration( border: Border.all(color: Color(0xFFFD6A02)), borderRadius: BorderRadius.circular(4.0), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ // [widget] is the property of the State class that stores // the instance of the [StatefulWidget] ([Counter] in our case) _CounterLabel(widget._name), _CounterButton( count, onPressed: () { setState(() { ++count; }); }, ), ], ), ); } } class _CounterLabel extends StatelessWidget { static const textStyle = TextStyle( color: Color(0xFF000000), fontSize: 26.0, ); final String _label; _CounterLabel(this._label); @override Widget build(BuildContext context) { return Text( _label, style: _CounterLabel.textStyle, ); } } class _CounterButton extends StatelessWidget { final count; final onPressed; _CounterButton(this.count, {@required this.onPressed}); @override Widget build(BuildContext context) { return GestureDetector( onTap: onPressed, child: Container( padding: EdgeInsets.symmetric(horizontal: 6.0), decoration: BoxDecoration( color: Color(0xFFFD6A02), borderRadius: BorderRadius.circular(4.0), ), child: Center( child: Text( '$count', style: TextStyle(fontSize: 20.0), ), ), ), ); } } So we have used two new widgets: Column() and Row(). It is not difficult to guess what their purpose is. In the next article, we will look at them more precisely. We will also learn how to assemble several widgets and create a sexy app using Flutter’s Material library. Additional Resources If you wish to learn more about mentioned topics here is the list of interesting links: - - Coding using VS Code and IntelliJ - More details on widgets - It is also important to read about Hot reload to understand when and why your application may not be updated automatically.
https://www.freecodecamp.org/news/an-introduction-to-flutter-the-basics-9fe541fd39e2/
CC-MAIN-2022-05
refinedweb
3,155
63.7
- a standard (and a library, usually shipped with a compiler), widely used in external libraries; TBB - a newer parallelization library optimized for task-based parallelism and concurrent environments. OpenMP historically has been used by a large number of libraries. It is known for a relative ease of use and support for loop-based parallelism and other primitives.. Tuning the number of threads¶ The following simple script shows how a runtime of matrix multiplication changes with the number of threads: import timeit runtimes = [] threads = [1] + [t for t in range(2, 49, 2)] for t in threads: torch.set_num_threads(t) r = timeit.timeit(setup = "import torch; x = torch.randn(1024, 1024); y = torch.randn(1024, 1024)", stmt="torch.mm(x, y)", number=100) runtimes.append(r) # ... plotting (threads, runtimes) ... Running the script on a system with 24 physical CPU cores (Xeon E5-2680, MKL and OpenMP based build) results in the following runtimes: The following considerations should be taken into account when tuning the number of intra- and inter-op threads: When choosing the number of threads one needs to avoid oversubscription (using too many threads, leads to performance degradation). For example, in an application that uses a large application thread pool or heavily relies on inter-op parallelism, one might find disabling intra-op parallelism as a possible option (i.e. by calling set_num_threads(1)); In a typical application one might encounter a trade off between latency (time spent on processing an inference request) and throughput (amount of work done per unit of time). Tuning the number of threads can be a useful tool to adjust this trade off in one way or another. For example, in latency critical applications one might want to increase the number of intra-op threads to process each request as fast as possible. At the same time, parallel implementations of ops may add an extra overhead that increases amount work done per single request and thus reduces the overall throughput. Warning OpenMP does not guarantee that a single per-process intra-op thread pool is going to be used in the application. On the contrary, two different application or inter-op threads may use different OpenMP thread pools for intra-op work. This might result in a large number of threads used by the application. Extra care in tuning the number of threads is needed to avoid oversubscription in multi-threaded applications in OpenMP case. Note Pre-built PyTorch releases are compiled with OpenMP support. Note parallel_info utility prints information about thread settings and can be used for debugging. Similar output can be also obtained in Python with torch.__config__.parallel_info() call.
https://pytorch.org/docs/stable/notes/cpu_threading_torchscript_inference.html
CC-MAIN-2021-31
refinedweb
438
53.51
OpenCV 3.0.0, FaceRecognizer and Python Bindings Hi there - I am very new to OpenCV and am using it for a school project on the Raspberry Pi (Mine is the B+ model). I have followed numerous guides to get the FaceRecognizer to work in Python, but to no avail. My specific problem is - model = cv2.createEigenFaceRecognizer() attributeError: 'module' object has no attribute 'createEigenFaceRecognizer' I also want to note that I can do import cv2 with no issues, and run functions such as cv2.imwrite(), cv2.cvtColor() with no problems, so there isn't an issue with OpenCV not working in general. My problem is with this specific class (faceRecognizer) which is critical for me. To elaborate, I am running OpenCV 3.0.0 and Python 2.7.3. To install OpenCV, I basically followed the tutorial at..., but instead of getting the file from sourceforge, I cloned from the OpenCV repository for the latest version, and in cMake, I added a flag BUILD_PYTHON_NEW_SUPPORT=ON (per a suggestion found online.) I googled extensively to find a solution, most notably......... and most sources tell me just to "recompile from the latest source". That's what I thought I did. I'm stuck as where to go now - did I compile the library incorrectly? I am aware that OpenCV is written in C++ and there are python bindings to make functions work in python, but I'm not sure where I'm going wrong here. Any input is much appreciated. Hmm the interface for algorithms is reshaped in OpenCV3.0. As far as I understand you need to access it through a pointer interface. @berak is more of an expert in this, I will let him do the talking here. How can I clone and compile from the opencv_contrib repo ?
https://answers.opencv.org/question/56859/opencv-300-facerecognizer-and-python-bindings/?answer=56871
CC-MAIN-2019-35
refinedweb
298
65.62
----------------------------------------------------------------------------- -- | -- Module: Control.Monad.ST.Freeze -- License: BSD3 -- Maintainer: Reiner Pope <reiner.pope@gmail.com> -- Stability: experimental -- Portability: portable -- --'. ----------------------------------------------------------------------------- module Control.Monad.ST.Freeze ( -- * Stage names Normal, Freeze, -- * MonadST class MonadST(..), STNormal, STFreeze, STRead, -- * ST monad ST, runST, -- * ST transformer STT, STTBase(..), ) where import Control.Applicative import Control.Monad import Control.Monad.Identity(Identity(..)) import qualified Control.Monad.ST as S import Control.Monad.Indexed(IxMonad(..),IxFunctor(..),IxPointed(..),IxApplicative(..)) import System.IO.Unsafe data Normal s data Freeze s -- | A computation containing some writes but no freezes: it starts -- | and ends in the 'Normal' stage. type STNormal st s a = st (Normal s) (Normal s) a -- | A computation containing only reads: it starts and ends in any -- stage, but does not change stage. (Note that there would be no loss -- of safety in allowing the stage to change, but it may result in -- ambiguous types, or extra type annotations being required.) type STRead st s a = forall stg. st (stg s) (stg s) a -- | A computation containing some freezes but no writes: it starts in -- | any stage, but ends in the Freeze stage. type STFreeze st s a = forall stg. st (stg s) (Freeze s) a class IxMonad st => MonadST st where -- | For lifting any operations containing writes but no freezes. liftST :: S.ST s a -> STNormal st s a -- | For lifting any operations containing reads but no writes or freezes. liftRead :: S.ST s a -> STRead st s a -- | For lifting an @unsafeFreeze@ operation liftUnsafeFreeze :: S.ST s a -> STFreeze st s a -- |. newtype STT m s t a = STT { unSTT :: IO a } class STTBase m where -- | Runs the monad runSTT :: (forall s. STT m (stg1 s) (stg2 s) a) -> m a -- | A restricted analog of Control.Monad.Trans.lift. lift :: m a -> STT m (stg s) (stg s) a type ST = STT Identity -- | @runST = 'runIdentity' . 'runSTT'@ runST :: (forall s. STT Identity (stg1 s) (stg2 s) a) -> a runST = runIdentity . runSTT instance STTBase IO where runSTT m = unSTT m lift = STT instance STTBase Identity where runSTT m = Identity (unsafePerformIO (unSTT m)) lift = STT . return . runIdentity instance IxFunctor (STT m) where imap f (STT m) = STT (fmap f m) instance IxPointed (STT m) where ireturn a = STT (return a) instance IxApplicative (STT m) where iap (STT m) (STT n) = STT (m `ap` n) instance IxMonad (STT m) where ibind k (STT m) = STT (m >>= (unSTT . k)) instance MonadST (STT m) where liftST s = STT (S.unsafeSTToIO s) liftRead s = STT (S.unsafeSTToIO s) liftUnsafeFreeze s = STT (S.unsafeSTToIO s) instance Functor (STT m s t) where fmap f = imap f instance Applicative (STT m s s) where pure = ireturn (<*>) = iap instance Monad (STT m s s) where (>>=) = flip ibind return = ireturn
http://hackage.haskell.org/package/safe-freeze-0.0/docs/src/Control-Monad-ST-Freeze.html
CC-MAIN-2014-42
refinedweb
450
65.83
Hello Guys today I am going to show you how to search element in React in Real Time without clicking a button. The Search will be Real time , when you type a word then all the elements containing that word will be filtered and showed to you . I have used a sample data for this code, You can use your data for this code as well. Data - const Data = [ { "id": "61050f211ab57ba6cd86b1e8", "name": "Valeria Ramos" }, { "id": "61050f21aa707624a853421b", "name": "Campos Daniels" }, { "id": "61050f21ec0c4d434eedda85", "name": "Kate Gilbert" }, { "id": "61050f21a4543be9235f4643", "name": "Hunt Lynch" }, . . . . . ]; Code for Searching - import React,{useState} from 'react' import Data from './SampleData' import './App.css'; function App() { const [list, setList] = useState(""); return ( <div className="text-center my-5"> <input type="text" placeholder="search..." onChange={(event) => { setList(event.target.value); }} /> <div className="main"> {Data.filter((item) => { if(list === ""){ return item; } else if(item.name.toLowerCase() .includes(list.toLowerCase())){ return item } }).map((item) => ( <div key={item.id}><p className="items"> {item.name} </p></div> )) } </div> </div> ) } export default App; Working - - First we created a state for the input element using useState. - Then we created an input element using input tag and inside it we have onChange event and inside onChange we change the state of the list matching to the word typed in the input field. - Then we filtered the Data using Filter method. 4.if(list===""){ return item;} , it means if the input field is empty, then return the whole data. - else if(item.name.toLowerCase().includes(list.toLowerCase())){ return item } It first convert the name to lowercase using toLowerCase() method then it checks that the typed word is included in the Dataset or not using included() method and also it converts the input word in to lowercase using toLowerCase() method because the names are also in lowercase format. - Then after filtering the data, we mapped the data using map() method CSS - p{ border-radius: 50%; width: 150px; height: 150px; background-color: crimson; display: flex; justify-content: center; align-items: center; color: antiquewhite; } .main{ margin: 5rem; display: grid; grid-template-columns: repeat(4,1fr); justify-content: center; text-align: center; } Output - Before Searching After Searching Hope you understand the process and if there is any mistake please mention it in the comment section. It will help me also to know my mistakes so that i can fix it. THANK YOU FOR READING THIS POST Discussion (7) As I see, it's not real time. What happen when you have lots of items, you need request the server to get them, so it will request every time you enter a character. I think you should research a bit about 'debouncing' and ''managing server state" Instead of denounce we can also use onBlurto request server. I don't know about fetching data from server and other server states , Its just a front-end part with Some JSON data I will learn other topics later You can simulate it using Promise with a setTimeout. Remeber to set the valueattribute of input to match the currentState: Cheers! The most important is data is got from server. But you store data in a variable. Its About logic here only that's why I used the data in a variable
https://practicaldev-herokuapp-com.global.ssl.fastly.net/shubhamtiwari909/real-time-searching-in-reactjs-3mfm
CC-MAIN-2021-43
refinedweb
532
61.77
howabout 1.1 A library to suggest similar strings. Howabout is a Python library to suggest similar strings. Use it in a command-line project or anywhere where simple misspellings occur. from howabout import best_match choices = ['sat', 'sot'] # returns 'sat', since # 'sat' -> 'sate' # 'sot' -> 'sat' -> 'sate' best_match('sate', choices) Examples can be found under examples/. Argparse Python’s argparse library is not supported out of the box as it cannot be extended or patched. Installation Install with pip: $ pip install howabout Testing Use tox to run the tests. $ virtualenv --no-site-packages .python && source .python/bin/activate $ pip install -r requirements.txt $ tox - Downloads (All Versions): - 6 downloads in the last day - 31 downloads in the last week - 35 downloads in the last month - Author: Charlie Liban - Download URL: - Keywords: cli - License: MIT License - Categories - Package Index Owner: clibc - DOAP record: howabout-1.1.xml
https://pypi.python.org/pypi/howabout
CC-MAIN-2015-11
refinedweb
145
63.09
Components in Vue.js Introduction Vue JS is a single-page application framework written in JavaScript (SPAs). Components in Vue.js are Vue objects that can be reused and have custom HTML elements. Components can be reused as many times as desired or used as a child component in another component. We can use data, computed, watch, and methods in a Vue component. Let us look into basic components in Vue.js. Types of Vue components There are two ways to define components in Vue.js: locally and globally. Global components Components registered globally in the project can be utilized anywhere without a need to export or import the file they're in. We can use the following syntax to construct a global component; it accepts two parameters: the component's name and the object describing its properties. vue.component('name of component, {properties}') Example: // Defining component globally Vue.component('welcome-note', { template: '<p> Hello World </p>' }) // The first Vue instance new Vue({ el: '#app1' }) // The second vue instance new Vue({ el: '#app2' }) Local components When a component is built locally, we can only use it where it was made. Example: // Defining the component const welcomeNote = { // Defining the props props: ['name'], template: '<h2> Hello {{ name }}</h2>' }; // Creating a vue instance new Vue({ el: '#app', // Registering the components locally components:{ welcomeNote } }); The welcome-note component was built locally in the example above by assigning the component object to a variable (component name). It is then registered locally in the Vue instance, which can only be used there. Props Components will be useless unless we can supply data to the component, such as the title and content of the particular post we want to display. This is where props can help with it. Props are used to send data down from parent to child components unidirectionally. Custom properties that we can register on a component are known as props. When a value is supplied to a prop attribute on a component instance, it becomes property. The value of that property, like any other component property, is available from within the template. A component can have as many props as it wants, and any value can be supplied to any of them by default. Let’s see an example. App.vue <template> <div> <Hello name = "Ram" /> <Hello name = "Shyam" /> <Hello name = "Geeta" /> </div> </template> <script> import Hello from "./Hello.vue" export default { name: "App", components: { Hello, } }; </script> Hello.vue <template> <h1>Hello {{name}} </h1> </template> <script> export default { name: "Hello", props: ['name'] }; </script> Output Note: We must use v-bind to dynamically pass props. This is really useful when we don't know the exact content we're going to render. Dynamic components Sometimes, it's useful to dynamically switch between components. It is more efficient to switch between components dynamically without routing. The following is the syntax: <component v-bind:is=”currentComponent”></component> It is necessary to use the component tag. The is attribute switches the currently selected component. Example: <template> <div id="app"> <!-- Creating button events to dynamically switch components --> <button @Show Green Card</button> <button @Show Purple Card</button> <hr> <!-- Binding the current component to the property --> <component :</component> </div> </template> <script> // Importing the components into the app import PurpleCard from "./PurpleCard.vue"; import GreenCard from "./GreenCard.vue"; export default { name: "app", components: { GreenCard, PurpleCard }, data:function(){ return{ // Assigning the current component selectedComponent: "GreenCard" } } }; </script> In the above example, we defined two separate components in the programme. The ': is' bind attribute allows the current component to be dynamically assigned; after that, the button events are used to switch between the two components. Single file components It's best to split large web apps with several functionalities into single file components while constructing large web applications. This allows us to combine all of the templates, scripts, and styles into a single.vue file: Example: import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false // Instantiate the vue instance new Vue({ render: h => h(App), }).$mount('#app') In the above example, the component was defined in a single file in the example above, then imported into the app, which was then rendered to the DOM using the Vue instance. DOM Template Parsing Caveats If we write our Vue templates directly in the DOM, Vue will have to retrieve the template string from the DOM. This can lead to some caveats due to the browsers' native HTML parsing behaviour. This is known as DOM template parsing caveats. Element Placement Restrictions HTML elements, like <table>, <ol>, <ul>, and <select> have some restrictions on which elements can come inside them. Some elements such as <option>, <li>, and <tr> can only come inside some other elements. This will create issues when using components with elements that have such restrictions. For example: <table> <row></row> </table> The custom component <row> will be raised out as invalid content. This will cause errors in the eventually rendered output. We can use the special is an attribute as a workaround. <table> <tr is="vue:row"></tr> </table> Case Insensitivity Attribute names in HTML are case-insensitive. Due to this browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names and event handler parameters need to use their kebab-cased (hyphen-delimited) equivalents: // camelCase in JavaScript app.component('blog-post', { props: ['postTitle'], template: ` <h3>{{ postTitle }}</h3> ` }) <!-- kebab-case in HTML --> <blog-post</blog-post> FAQs - What exactly is a Vue component? In Vue.js, components are reusable Vue objects with custom HTML elements. We can reuse components indefinitely or be utilised as a child component in another component. - What are Vue props? Props are used to deliver data in a unidirectional manner from parent to child components. Props are custom properties that you can register on a component. A property is created when a value is passed to a prop attribute on a component instance. - What are the two ways to name components? The two ways to name components are: Kebab case: my-component-name Pascal case: MyComponentName - What is the use of the $emit method? The emit method is used to notify the parent component that something changed. - How can parent choose to listen to any event on the child? Using v-on or @, the parent can choose to listen to any event on the child component. Key Takeaways Some of the most important properties of Components in Vue.js have been discussed. Vue components are reusable Vue objects with configurable HTML elements. We can reuse components an unlimited number of times. Props are used to deliver data in a unidirectional manner from parent to child components. The use of Dynamic and Single File components in Vue.js is also discussed. Don't stop here. If you liked this blog about Components in Vue.js, check out our Learn Vue free course to learn Vue from scratch. Also, feel free to check out the blog Vue JS Vs. React in 2021.
https://www.codingninjas.com/codestudio/library/components-in-vue-js
CC-MAIN-2022-27
refinedweb
1,164
57.37
tensorflow:: serving:: LoaderHarness #include <loader_harness.h> LoaderHarness is a widget the Manager uses to hold on to and talk to a Loader while it owns it. Summary It tracks the overall state of a Servable such that Manager can determine which state transitions to make at what times. A manager implementation can also add some additional state with each harness. For example, a manager could put ACL or lifecycle metadata here. The ownership is maintained by the harness. This class is thread-safe. Public types State State State of the underlying servable, from the perspective of the LoaderHarness and for the purpose of communication between it and a Manager. Not equivalent to the semantic servable states in servable_state.h. Valid transitions: kNew>kLoading>kReady>kQuiescing>kQuiesced>kUnloading>kDisabled as well as: any_state>kError. Public functions DoneQuiescing Status DoneQuiescing() Transitions the state to kQuiesced, which means that there are no more live handles to this servable available in the frontend. At this point, we can unload this object. REQUIRES: State is kQuiescing when called. Otherwise DCHECK-fails, transitions to state kError and invokes 'options_.error_callback'. Error void Error( const Status & status ) Transitions the state to kError and invokes 'options_.error_callback'. Load Status Load() Transitions to kLoading, delegates to Servable::Load(), then transitions either to kReady if Load() succeeds, or to kError (and invokes 'options_. error_callback') if Load() fails. This call may take a long time. We retry the Servable::Load() according to the options set during construction of this class. We stop retrying and give up if 1. we have reached max_num_load_retries or, 2. if cancel_load() is set to true. REQUIRES: State is kLoadApproved when called. Otherwise DCHECK-fails, transitions to state kError and invokes 'options_.error_callback'. LoadApproved Status LoadApproved() Transitions to kLoadApproved. REQUIRES: State is kLoadRequested when called. Otherwise DCHECK-fails, transitions to state kError and invokes 'options_.error_callback'. LoadRequested Status LoadRequested() LoaderHarness LoaderHarness( const ServableId & id, std::unique_ptr< Loader > loader, const Options & options ) LoaderHarness LoaderHarness( const ServableId & id, std::unique_ptr< Loader > loader, std::unique_ptr< T > additional_state, const Options & options ) Constructor to create a harness with additional state, which a manager needs. StartQuiescing Status StartQuiescing() Transitions the state to kQuiescing, which means that we would like to not give out any more handles to this servable. REQUIRES: State is kUnloadRequested when called. Otherwise DCHECK-fails, transitions to state kError and invokes 'options_.error_callback'. Unload Status Unload() UnloadRequested Status UnloadRequested() additional_state T * additional_state() Gets the additional state. Returns nullptr if the type mismatches or if it wasn't set. cancel_load_retry bool cancel_load_retry() id ServableId id() const Returns the identifier of underlying Servable. loader Loader * loader() const Returns a pointer to the wrapped loader. Ownership remains with this class. loader_state_snapshot ServableStateSnapshot< T > loader_state_snapshot() Returns the current overall state snapshot of the underlying Servable. loader_state_snapshot ServableStateSnapshot< std::nullptr_t > loader_state_snapshot() const set_cancel_load_retry void set_cancel_load_retry( bool value ) Cancels retrying the load of the servable. This is best-effort, and does not preempt a Load() which is already happening, only subsequent calls. If the retries are cancelled, the servable goes into a state dependent on the last Load() called on it. If the last Load() was successful, it will be in state kReady, else in kError. status Status status() Whether anything has gone wrong with this servable. If state is kError, this will be non-OK. If not OK, the error could be something that occurred in a Source or SourceAdapter, in the Loader, in the Manager, or elsewhere. All errors pertaining to the servable are reported here, regardless of origin. ~LoaderHarness ~LoaderHarness() Legal to destruct iff current state is one of kNew, kDisabled or kError. Check-fails if violated.
https://www.tensorflow.org/tfx/serving/api_docs/cc/class/tensorflow/serving/loader-harness?hl=zh_tw
CC-MAIN-2022-21
refinedweb
604
50.63
Questions to Ajith, the XML guru Sheriff Oh, I forgot. Congratulations! No, Big Envious Congraulations! Uncontrolled vocabularies "I try my best to make *all* my posts nice, even when I feel upset" -- Philippe Maquet Well, use caution before you call me guru...I'm still learning. ( so much to paint the "I'm humble" picture A lot of people don't know about IBM certification because it is VERY new. But if you want to get some credentials in the ( should I say the bleeding-edge ) XML technology, this is the ONLY available test out there. Checkout the official XML certification page at IBM for more details. This certification is tough and tricky( and hence justifies the 50% passing marks ). The questions are evenly distributed across theoretical and practical concepts. I took about 2 months to prepare for the test ( don't forget I have 8-5 J.O.B ) with about 2-3 hrs of study per (working) day. Weekends not included. Since the whole thing is still in its infancy, you will face some hurdles on the way. Unlike the famous Java certification, there are no certification guides or tutorials for this exam. IBM recommends reading the W3C core specs for all the XML related stuff, but if you haven't read such specs before you will lose interest in the whole thing. They are as "unfriendly" as a legal document There are two( yes, only TWO!! ) resources for this exam. One is the tutorial from Certificationguru.com and the otherone is the EGroups discussion board for XML certification. I found the certguru tutorial grossly inadequate and the egroups discussion board not so helpful. Before you start shooting off questions( I don't blame your curiosity and/or enthusiasm), checkout the following quickFAQ ( QFAC ) - What study materials did I use ? I read the XML Bible cover to cover.I would recommend this book. I am avoiding the word "strongly" for two reasons, one is that it is out of date (this is not a big deal as you can download the updated chapters from the author's web site) and the other is that it does not discuss DOM & SAX (again, the author's web site comes to our rescue). This book is otherwise a great resource. The author could have made it more interesting with smaller examples, rather than using baseball statistics running into many pages. If you do not mind torturing yourself for the sake of learning from the horse's mouth, go ahead and read the W3C documents. If you are used to reading cryptic legal parlance, you are better off than I am, go ahead !. Having said that, I should acknowledge that I found the W3C DOM document to be, should I say readable! Alternatively, you could read the book Inside XML. I saw the book in bookstore and it looked good. I cannot comment if this is better book that XML Bible as I have not read it. It is definitely more complete from exam point of view as it discusses DOM and SAX as well. I wouldnot want to miss mentioning the very cool XML databases by (our own ) Kevin. Though this book is an overkill for certification guide, it is a must have on your bookshelf if you are planning serious XML development. I was really impressed by the DOM coverage this book has. There are hundreds of free XML-related internet resources. You CAN pass the exam without spending a penny on the book. Remember that For namespace check this out, very useful: I found Zvon tutorial () to be pretty cool and useful. XML exam from brainbench.com will help you practice, but in no way it compares with the actual exam. IBM's exam is much tougher. - What tools did I use ?. I used XML Spy for IDE and apache's Java based DOM and SAX APIs, and also apache's command line XML parser. Try working out with some tools to understand how they work in general and how do they notify errors and exceptions. XML Spy IDE is very elegant and it has neat well formedness and validity checking and notification. Try to play with as many parsers as you can get. Just like Java compilers, some of them give better description of the error(s) when compared to others. The more you have, the merrier it will be Note: Do not go overboard with using XML IDE tools. Most of them expect support from IE5.x system files (probably the DLLs) for their functioning. IE5.x does not stick to W3C recommendations in full, specially the way they handle default template rules. So beware of W3C XML Vs Microsoft XML - What is the nature of the exam ? The exam probably tends to test your skills at a very fundamental level. What I mean is that you will find very few questions like, you have this XML file and if you apply this XSLT, what will be the result ?. You got what I am saying. So working tons of XML and XSLT tutorials neglecting the fundamental concepts may not be sufficient. Please refer to IBM's practice test questions to a have feel of what I am saying. The actual exam pattern is similar. Caution - there will be a lot of tricky questions. You will have to know ALL the objectives mentioned on the IBM site. Don't neglect anything, even if you think you know it. Give equal importance to all objectives. - The myth about CSS, XSL-FO, SAX, SCHEMAs ... ? The exam syllabus does not emphatically specify their inclusion (barring XSL-FO). But the reality is slightly different. I had a direct questions on SAX, XSL-FO, SCHEMA and some questions relating to CSS Vs XSL. I would definitely recommend you to know about these, if not entirely. If you've worked with CSS before, you need not read those concepts again. - How tough is the exam ? The exam is not very tough, but not very easy either. It is definitely not a piece of cake. The notion that questions in the exam are much easier that IBM sample questions is not true at all!. Some questions are easier and some are as tough, a lot of them are even tougher. You will have just enough time to complete it. Timing is an issue. You may not have time to revisit all the questions, unless you have a very fast CPU. - What additional reading do I recommend ?[list] Distribution of questions The books XML Bible and Inside XML do not teach much on XML design, applying XML to a specific domain, testing and implemantation etc. There are many questions specific on how XML technology can be applied to differnt industrial domains like, finacial institutions, e-bussiness, b2b, legacy systems etc. You need to perhaps refer to some other books. Try to surf the internet and find additional resources, this will also help you realize that you are talking about bleeding edge evolving technology. Last but not least, come here, to JavarRanch XML forum and ask questions. Though they may not directly related to your certification, it will help you learn newer things faster. [/list] Phew! That was a long one!. Hope it helps other aspirants! As always, if you have questions ask me and I'll try to help Good luck, ------------------ Ajith Kallambella M. Sun Certified Programmer for the Java�2 Platform. IBM Certified Developer - XML and Related Technologies, V1. [This message has been edited by Ajith Kallambella (edited February 12, 2001).] Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA). You are our pioneer. I've noticed that you reference this thread frequently and I thought I would use it to ask you a question that is nagging me. Thus putting up in front of the thread subjects. Feel free to transplant this elsewhere. I have three full days left to study for the XML certification exam. I seemed to be passing on the separate mock exams provided by yourself and IBM Corporation respectively (77.8% for IBM and 66% on yours). The question is: Have you found any suitable study material in print or on the web that comfortably addresses the Implementation/Testing category of the exam? It seems to be the hardest area to find writing on. If the mock exams are simliar to the actual exam as I have heard, it seems like it often asks you to have the correct "sense" (as in "common sense" only it may not be as common) in order to answer correctly. Thus supplementing the study of code standards with the study of good tutorials seems like the best way to find some of this "sense" (after actually having experience using it on projects, that is). But Implementation and Testing, which I has scored lowest on is a little elusive. It did seem like many of those Implementation/Testing questions could be redefined as Design. Perhaps that is my best option. Do you have any recommendations on this area from your experience? Meadowlark Bradsher, SCJ2P club member and XML Disciple. Meadowlark Bradsher SCJ2P, IBM XML V1, Series 7/63 Have you found any suitable study material in print or on the web that comfortably addresses the Implementation/Testing category of the exam? It seems to be the hardest area to find writing on. You are absolutely right. The only folks who can crack these questions are the ones who are working on full-throttle XML-based projects. This technology being so new( and the test itself is called V1 - version one!! ) it is hard to gain real life experiece. I used two strategies - second guess and use common sense. Common Sence - If you have worked on testing phase of any big project you can apply the same rules for an XML based project too. For example - stress/performance testing should be given weightage, testing should cover all the real-life scenarios, yada yada yada. Second guess( and review ) - Plan your time in such a way you have some time to revisit Testing/Implementation questions. BE VERY THRIFTY ON MANAGING YOUR TIME. IT IS HARDER THAN SCJP. Since questions from various topics come in no particular order, don't spend too much time munching over confusing questions. Mark them and move on. When you have moved to the end of the test, you can revisit the questions marked for review - the software works just like the SCJP exam application. When your mind goes "blank", go with your gut feel. I know my answer may not sound very convincing, but as I said, there are hardly any materials out there that 'teaches' best practices of XML implementation/testing. One comforting fact is that you only need 50% to pass the exam and sufficient knowledge about other objectives - XML 101, XSL, XSLT, DOM spec, Parsing etc. is good enough to reach there! Good luck, Ajith Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA). Gemini, sorry I looked and I can't find the link to Ajith's test. I want to give you the url to the actual test app. Its more fun than just the text questions and answers. Perhaps Ajith can give it to you. Otherwise I am sure I can find the original post with the questions put forth in plain text if you want that. If this thread is a reuseable document (Ajith points to it often) then it might be good to have that url on it too. Ajith, do you have it handy? I used these exams to measure my weakness not my growth because they were a one time shot. After the first use I'd likely memorize many of the answers. So I took them the day that I had a terrible headache and I went to a local cafe where I knew people would try to talk to me. It was the perfect environment. :-) Well, perhaps I should start relaxing soon to be sure that I get good rest. -Meadowlark Bradsher Meadowlark Bradsher SCJ2P, IBM XML V1, Series 7/63 Map, where have you hidden your precious app?? About this mock itself, I promised to add a few more questions but couldn't find time. It is still on my plate Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA). Sheriff List of XML-mocks-to-be is here Warning: I'll improve is as soon as I figure out how to get new FTP access Uncontrolled vocabularies "I try my best to make *all* my posts nice, even when I feel upset" -- Philippe Maquet I passed! :-) It seemed like there were more questions about xsl tags than I expected. But I answered everything the first time I read it and "marked" the doubtful ones for me to return to. That way if I ran out of time at least something would be selected. Actually I ended up having 20 minutes to review these and I changed only a few (hopefiully for the better - but perhaps I'll never know). Either way, whoopee! Thanks, Meadowlark Bradsher Sun Certified Java 2 Programmer IBM Certified Developer - XML and Related Technolgies, V1. Meadowlark Bradsher SCJ2P, IBM XML V1, Series 7/63 Originally posted by rajala yoganand: Hey All, Hello Yoganand, Congratulations!!! Thankyou for providing the useful information about the examination pattern. Even i am planning to take the exam within a month, so please if you can give me the URL's for the tutorials you referred, it will be very helpful for me. Thank you. XML Mock Exam list at Javaranch - Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA). Thank you for your understanding ! Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA). for it. regds. - satya Take a Minute, Donate an Hour, Change a Life It may be useful for those who preparing for xml certification. Initially as everybody said, there is no mention of xml schemas in "XML bible" book, so here it is!! Thanks Ashish Jain Ashish Jain<br />MCP, SJCP, IBM XML, SCEA
http://www.coderanch.com/t/146015/po/certification/Questions-Ajith-XML-guru
CC-MAIN-2016-26
refinedweb
2,372
74.39
XMonad.Layout.Stoppable Description. Note that the stopped application won't be able to communicate with X11 clipboard. For this, the module actually stops applications after a certain delay, giving a chance for a user to complete copy-paste sequence. By default, the delay equals to 15 seconds, it is configurable via Stoppable constructor. The stoppable modifier prepends a mark (by default equals to "Stoppable") to the layout description (alternatively, you can choose your own mark and use it with Stoppable constructor). The stoppable layout (identified by a mark) spans to multiple workspaces, letting you to create groups of stoppable workspaces that only stop processes when none of the workspaces are visible, and conversely, unfreezing all processes even if one of the stoppable workspaces are visible. To stop the process we use signals, which works for most cases. For processes that tinker with signal handling (debuggers), another (Linux-centric) approach may be used. See - Note This module doesn't work on programs that do fancy things with processes (such as Chromium) and programs that do not set _NET_WM_PID. Documentation You can use this module with the following in your ~/.xmonad/xmonad.hs: import XMonad import XMonad.Layout.Stoppable main = xmonad def { layoutHook = layoutHook def ||| stoppable (layoutHook def) } Note that the module has to distinguish between local and remote proccesses, which means that it needs to know the hostname, so it looks for environment variables (e.g. HOST). Environment variables will work for most cases, but won't work if the hostname changes. To cover dynamic hostnames case, in addition to layoutHook you have to provide manageHook from XMonad.Util.RemoteWindows module. For more detailed instructions on editing the layoutHook see: data Stoppable a Source # Data type for ModifiedLayout. The constructor lets you to specify a custom mark/description modifier and a delay. You can also use stoppable helper function. Constructors Instances stoppable :: l a -> ModifiedLayout Stoppable l a Source # Convert a layout to a stoppable layout using the default mark ("Stoppable") and a delay of 15 seconds.
https://hackage.haskell.org/package/xmonad-contrib-0.15/docs/XMonad-Layout-Stoppable.html
CC-MAIN-2018-51
refinedweb
337
52.29
writing a suite of Python-based tools to supplement some of the functionality of OpenNMS, and may eventually refactor and release them to the community (or to Contrib at OpenNMS, if they'll have them). I just now whipped up a little script, which I'll later rewrite as part of a larger utility class (with a Jython wrapper), which might be useful to some people. I'd noticed that my OpenNMS installation had discovered a large number of IP interfaces without corresponding DNS entries, and wrote a suite of tools to exercise the DNS - look for A records w/o corresponding PTR records, PTR records without A records, etc. - and so started writing these tools. Here's one: ####################################################### #!/usr/local/bin/python # # This script extracts IP addresses from the OpenNMS # PostgresQL database which do not have corresponding # DNS, SNMP, or WinBios-derived textual node labels. # The presence of such "bare IP" entries might indicate # the lack of a proper reverse DNS (PTR) entry or even # the lack of any DNS entry referencing the IP address. # # Author: Russell Whitaker <whitaker(at)best.com> # Silicon Valley OpenNMS Users Group (SVOUG) # from pg import DB def extractBareIPAddrs(): "Extract node labels like IP addresses" addresses = [] field = 'iphostname' table = 'ipinterface' query = "SELECT " + field + \ " FROM " + table + \ " WHERE " + field + " NOTNULL " + \ " AND " + field + " !~* '[a-z]' " + \ " ORDER BY " + field conn = DB('opennms', user='opennms') for ip in conn.query(query).getresult(): addresses.append(ip[0]) return addresses if __name__ == '__main__': for address in extractBareIPAddrs(): print address #################################################### This is actually an adaptation of a Momjian PostgreSQL cookbook recipe: ""; Feel free to comment on / poke holes in this utility. I've tested it with Python versions 1.5.2 and 2.2.1. Russell -- Russell Whitaker Silicon Valley OpenNMS Users Group (SVOUG) In my situation, I have about 2/3 of the router recognized as their own nodes. Each of these nodes have unique SNMP data, unique MAC addresses, unique IPs etc. The only common factor is that they are the same manufacturer. The remaining 1/3 are "grouped". They all have unique IP addresses, MAC addresses, SNMP data etc. The only common factor is that they are the same manufacturer. These routers were discovered and were clumped under a single IP address IP address, although each of the node IP addresses are listed under the IP address. Because they each have unique SNMP data, we frequently get notices that the node info has changed -- it simply rotates the SNMP data between the "child" nodes. Because these are unique nodes, I would like to break them apart so that when a node or service goes down, I know the actual node IP, instead of the "master" ip, which is a different node. Thanks for any assistance. +---------------------------- Timothy M. Butkiewicz Director of Office Technologies cyberM.I.N.D. 877.373.6680 x 20 -----Original Message----- From: Ian Wallace [mailto:iwallace@...] Sent: Friday, May 17, 2002 2:29 PM To: Discuss OpenNMS Subject: Re: [opennms-discuss] To many interfaces for a node. Roger - I don't want to muddy the waters here but you have two routers with interfaces that have the exact same ip's? I'm assuming for a redundant network setup? So the MAC addresses of the NIC's is about the only thing that is really unique about the interfaces? So from OpenNMS it sees the same node twice basically (or do they have different SNMP information setup for each?). I'm just trying to figure out how OpenNMS would have a method of telling them apart, I'm guessing it's either got to be MAC address of the cards (coupled with IP), or some SNMP information to tell me that this is Router2, and not Router1 - or am I just way off base here? cheers ian On Fri, 2002-05-17 at 12:01, Roger Weeks wrote: > Does anyone have a fix for this problem? I have two Cisco routers, > using addresses 10.1.2.5 and 10.1.2.6, that are showing up as a single > node. How do I get opennms to recognize each one as a single router? > > Roger Weeks > > Timothy M. Butkiewicz discuss@... > Tue, 7 May 2002 13:53:29 -0400 (EDT) > > ------------------------------------------------------------------------ > -------- > > I have an interesting situation with OpenNMS 1.0. > > I have about 50 routers (efficient networks) that I am monitoring. Most > get discovered as their own node (each router). This is good. > > Though several have been clustered. One node lists several IP addresses > that are associated with different routers and includes all of the sub > information of the individual router. I am referring to this as a router > clump. Each of the routers is configured for SNMP. Furthermore every > once in a while the SNMP data displayed in OpenNMS for the router clump > will rotate between the different devices... so notices are generated > that Node info has changed. Details are included below. > > My question is - Is there a way to break apart the clump and separate > out the routers so that they display as single nodes, instead of one > node containing several routers? > > Further details below. > > This is running on a redhat 7.2 server > Version: 1.0.0-3 > Server Time: Tue May 07 13:46:25 EDT 2002 > Client Time: Tue May 7 13:48:09 EDT 2002 > Java Version 1.4.0 Sun Microsystems Inc. > Java Virtual Machine: 1.4.0-b92 Sun Microsystems Inc. > Operating System: Linux 2.4.7-10 (i386) > Servlet Container: Apache Tomcat/4.0.3 (Servlet Spec 2.3) > User Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0; > cyberMIND) > > > Good Device: > Non-IP (ifIndex: 3-CONSOLE/0) > Non-IP (ifIndex: 2-FR/0) > 200.10.10.253 > 1.2.3.4 (1.2.3.4) > > Bad Device: > Interfaces > 2.3.4.5 (2.3.4.5) > 3.4.5.6 (3.4.5.6) > 4.5.6.7 (4.5.6.7) > 5.6.7.8 (5.6.7.8) > Non-IP (ifIndex: 5-CONSOLE/0) > Non-IP (ifIndex: 4-ATM-VC/2) > Non-IP (ifIndex: 2-SDSL/0) > Non-IP (ifIndex: 3-ATM-VC/1) > 200.200.200.10 > 192.168.1.2 > > _______________________________________________ > discuss mailing list (discuss@...) > To subscribe, unsubscribe, or change your list options, go to: > _______________________________________________ discuss mailing list (discuss@...) To subscribe, unsubscribe, or change your list options, go to: Gang: I am hoping to revive an old OpenNMS tradition of weekly updates. While I lack both the talent and the wit of Shane O'Donnell, I hope you will find them useful and not too dry. Project Status: --------------- OpenNMS version 1.0 is out, and it is the most stable and feature rich version ever. The process of vetting 0.9.9 as long as we did insured that 1.0 would be as bug free as possible. While a few bugs have been fixed in CVS, it is good enough to be going into production in numerous NOCs around the world. I have been working with network management products for quite a long time, and I like OpenNMS so much that I am focusing a large part of my company, Sortova Consulting Group, on the support and promotion of the product. For years we have done consulting with proprietary products from such companies as Hewlett-Packard, IBM and Micromuse, and now with OpenNMS we have a powerful tool to both improve our client's ability to manage their networks and cut costs at the same time. [Sorry, I've been drinking the Kool-Aid. I get so excited that at one seminar a guy replied "Man, you *made* the Kool-Aid".] (grin) As part of our promotion efforts, we want to make sure that everyone who wants to become active with the project is able to do so. Plus, expect some updated documentation real soon. We have approached O'Reilly about the prospect of an OpenNMS book, but in the meantime look for at least one good How-To a week. A Call to Arms: --------------- When I do OpenNMS seminars, a common question is "how can I get involved". Well, now is your chance. We are in the process of moving CVS to SourceForge so that more people can use their SourceForge account to improve on the product. Interested? Send me a note and let me know how you want to get involved. If you are a Java expert, and really want to get into the OpenNMS code, I will be looking for maintainers for the following areas: o Graphical User Interface o The Database o Pollers o Collectors o Service Level Reports o Performance Reports o Events/Notifications Roadmap: -------- We have about a week's worth of work to transition OpenNMS resources to new servers, and after that I want to get busy moving forward. First, we will need to issue version 1.0.1 packages. There have been a few bug fixes entered into OpenNMS and a few more brought up on the discuss list. Second, we need to put a stake in the ground on a 1.1 release date and what features will be included. I have two pet projects I am working on: response time stats from pollers into RRDs and an initial notification delay. Some popular requests include a MIB compiler and Localization. How about "skins" for the GUI? I also would like to see a post-process that related SNMP traps to Interfaces in the event table. Get your ideas into Bugzilla (as enhancement requests) by Thursday of next week, and I will put out a ballot in next Friday's update. We'll rank them in order of desire and complexity and settle on a feature list for 1.1 Bug of the Week: ---------------- This feature will spotlight a particular issue that seems to have caused the most problems. This week it is the "admin/admin Doesn't Work After Install".. Some people have found that they get the login prompt when going to http://<localhost>:8080/opennms after install, but username="admin", password="admin" doesn't seem to work. I have not been able to accurately recreate this problem after numerous tries, but I did see it once and discovered the following clues: 1) run "ps -ef | grep post". This should return only the postmaster process for Postgres, but if you see some processes with the words "opennms" you may have experienced this problem. Something hung during the database configuration. 2) run "ls -l /var/tomcat4/conf" and look at the dates. If all of the file dates are the same, then server.xml never got updated and thus the passwords were never entered. OpenNMS has to modify this file in order for admin/admin to work, and so it should reflect the date and time of the OpenNMS install. Here's a workaround: 1) "killall java" (repeat until no processes are found). 2) If you did find extra "opennms" processes in the grep for post above, perform a "service postgresql restart". Re-run the grep and insure that only the postmaster is running. 3) "rpm -qa | grep opennms" (this will list the three opennms rpm packages) 4) "rpm -e <packages>" (where <packages> are the three opennms packages) Now you need to reinstall OpenNMS. You can do this in one of two ways: 1) Using apt: a) apt-get update b) apt-get install <packages> [where the <packages> are the ones from above] or 2) use "ncftp" and locate the RPMS in /pub/releases/latest. Download the RPMs to a temporary directory and run "rpm -Uvh openn*.rpm" After re-installing, look at the Tomcat conf directory again and see if server.xml was properly modified. If so, restart opennms and tomcat and you should be able to get in. Final Notes: ------------ OpenNMS is a pretty unique solution in the world of network management. Literally millions of dollars was spent in its development, and yet it is available for free. The reason is that network management is too hard to be solved with a software application on its own - it requires people - which means the software is just a tool. No one knows better on how to improve a tool then the ones who use it, and thus by default OpenNMS has the potential to be the best network management tool ever built. I am betting the (literal) farm on it. Due to the success of the early adopters in the OpenNMS.com product line, I am convinced that we can build something valuable and have a fun time doing it. Please, keep the cards and letters coming, and I'll drop another note next week. -T -- Tarus Balog Consultant Sortova Consulting Group +1-919-686-7625 tarus@... I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/opennms/mailman/opennms-discuss/?viewmonth=200205&viewday=18
CC-MAIN-2017-04
refinedweb
2,159
64.3
Can't connect to device when main.py is running I'm not sure if this is by design (I hope not) or if I'm running into a strange issue. I have a simple boot.py file that starts up a UART serial and connects my wipy to my home network, and that seems to work fine. I have a main.py file that, once uploaded, seems to mostly work in terms of the buttons that it's supposed to interact with, but whenever main.py is running, I cannot make any connections to the board via FTP, SSH, OR serial-over-USB. I overrided main.py by pulling g28 to 3v3, connecting to FTP, and then deleting main.py. Now on restart I can connect again, but even if I try only to "Run" my script from atom/pymakr, I immediately lose the ability to connect to the device by any means. I can post my code if you think it'll help but wanted to check to see if this is known or if other people were having similar issues. @ccarducci you could enable a for loop running every second, this way you can interrupt your program every second. @ccarducci there are currently a few calls that are actually not interrupted by Ctrl-C, so you have to wait until that call has ended for it to take effect. It was interesting. At this point I'm assuming the issues are actually with the Pymakr plugin for Atom, and not the board itself. When I came back home I plugged the board back in and tried to reconnect. As I was renaming the file and getting ready to try to override main.py and re-upload my newly named file, I decided to try once more to kill off main.py from a connection. Despite the fact that the REPL prompt in atom/pymakr never showed that I actually connected, I think it was. At first ctrl+C wasn't working at all, but in my frustration I decided to just keep hitting it for a while, and after a few repeated keystrokes the board finally terminated main.py. Once I got that done, I was continuously able to replicate just by being patient and by repeatedly hitting ctrl+c after hitting the "Connect" button until it decided to take the keypress. After that I had to make a few tweaks to code where I was doing stupid things, and now it's all running smoothly. I'm going to stick mostly to putty/filezilla until the plugin feels a bit more 'baked' than it is. @ccarducci looks like legit code. How is the renaming working out? @dendeze Yes, sorry, the format of this forum is weirding me out. The way it was displayed it looked like I was responding to myself, not you, so I tried to delete and re-respond. I've re-posted now, not that I think it looks any better. also I can't post more than every 10 minutes because I'm a new user, which is really irritating when you're trying to actively reply in a thread. I also changed the formatting of my post to be three backticks instead of a four-space indent on each line, not that it makes much of a difference after it's already posted... @dendeze I will post the code below. I used the correct IP address. The MAC for my Wipy is reserved on my router. I haven't changed the IP in filezilla or atom. I get ping responses even when I cannot connect, and the pings stop when I unpower the wipy. When I override boot.py and main.py, I can connect to that same IP. My network is completely flat. I'm at x.x.x.110/24, the device is at x.x.x.115/24 UART baud, for me, is set in boot.py at 115200. I can try to rename and execfile() when I get home. from machine import RTC import utime import pycom from machine import Pin def isDST(day, month, dow): """ DST Checker. This checks if the current day is DST """ # dow in this implementation is mon-sun, not sun-sat if dow == 6: dow = 0 else: dow = dow + 1 # January, february, and december are out. previousSunday = day - dow if (month < 3 or month > 11): return False # April to October are in elif (month > 3 and month < 11): return True # In march, we are DST if our previous sunday was on or after the 8th. elif (month == 3): return previousSunday >= 8 # In november we must be before the first sunday to be dst. # That means the previous sunday must be before the 1st. else: return previousSunday <= 0 def currentTime(): # return a dict with all of the day selections? global cycleday curtime = utime.gmtime(utime.time()) now = {"year":curtime[0], "month":curtime[1], "day":curtime[2], "hour":curtime[3], "minute":curtime[4], "second":curtime[5], "dow":curtime[6], "doy":curtime[7]} return now def setTimeZone(): """ Time Zone Setter. This function sets the current time zone depending on the day and whether or not it's DST """ now = currentTime() if isDST(now["day"], now["month"], now["dow"]): utime.timezone(dst) else: utime.timezone(est) def isNewDay(): global cycleday, taken, logged now = currentTime() if (int(now["day"]) > int(cycleday)) or (cycleday == 100): cycleday = int(now["day"]) logged = False taken = False pycom.rgbled(0xFF0000) def logButton(): global logged pycom.rgbled(0x001100) logged = True # do something to log in Google drive or somewhere def pin_handler(arg): global taken taken = True def mainloop(): """ The main loop of the program. Cycles through updating the LED if meds have been taken, as well as checking to make sure that the day hasn't changed. If the day has changed, then mainloop will change the LED back to red, and start the next day's cycle. """ global taken, logged if (taken == True) and (logged == False): logButton() isNewDay() dst = -14400 est = -18000 taken = False logged = False cycleday = 100 p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP) p_in.callback(Pin.IRQ_FALLING, pin_handler, arg=None) pycom.heartbeat(False) pycom.rgbled(0x000011) rtc = RTC() server = "pool.ntp.org" rtc.ntp_sync(server) setTimeZone() isNewDay() while True: mainloop() You just posted your code and removed it... This post is deleted! I would be happy to see your code, did you use the correct IP adres? Are you in a different subnet? Is your uart baud rate set in the main.py? you could alternatively try to rename your main.py to main1.py and execute after uploading and connectiong true uart with:
https://forum.pycom.io/topic/1893/can-t-connect-to-device-when-main-py-is-running
CC-MAIN-2019-43
refinedweb
1,106
74.19
How to replace a number range with same rang just adding an offset. ie find a 3 digit number between say 133 to 183, add 64 and replace the original number. HI. I feel there is a simple way to do this but so far I cant see the way. I wonder if the reg expression people can assist? In an original table of numbers (other stuff included like colons, letters etc) from 133 to 183 for instance, I then copy this to a new location and want to increment the original value range by adding an offset like 64. I would select the new range, use find and replace to take the original range numbers 133 to 183 then add 64 and replace the number in the range with the new number. I am just not sure of the terminology to do this. \d means a number, just need a push in the right direction next. Thanks again. Hi, minsikau I don’t think than you can easily perform a S/R, with computation, with the present BOOST regex engine, used by Notepad++ :-( But this goal could be reached, if you would install the N++ Python plugin of Dave Brotherstone Just refer to that link below, for some information : I’m not completely sure, but be aware that, in this script, the command editor.pyreplace....., should be replaced with the command editor.rereplace, with the last 1.0.8.0 version of the N++ Python plugin No doubt, that, very soon, Claudia Franck, ( a definitive Python fan and master ! ) will propose you a "ready-to-use" script, to achieve your goals ! Best Regards, guy038 Hello @minsikau and guy038 yes, python can do it as long as I do the correct regexes ;-) This one line should do the trick. Once you have installed python script plugin you can run this in the console (Plugins->Python Script->Show Console) or create a new Script and run it afterwards. editor.rereplace('[1][3][3-9]|[1][4-7][0-9]|[1][8][0-3]', lambda m: str(int(m.group(0)) + 60)) To get the number range I did the following alternations either the number starts with 1 followed by 3 and follows by digits 3-9 [1][3][3-9] or number starts with 1 followed by digits 4-7 and follows by digits 0-9 [1][4-7][0-9] or number starts with 1 followed by 8 and follows by digits 0-3 [1][8][0-3] If there is a better/nicer/quicker/usefuller (?) regex, maybe someone (guy038 ;-) can enlight me? Cheers Claudia Hello, minsikau and Claudia, minsikau, if you’re exactly searching for a three digits number, from 133 to 183, a possible regex could be : \b1(3[3-9]|[4-7]\d|8[0-3])\b Notes : The \bassertion, which represents the limit between a word character and a non-word character or the opposite, ensure that a right number, as 157, will NOT be matched if it’s glued in a bigger number as, for instance, in the number 3415798 ! Then, the first digit 1 is needed, in every case, and for the "ten" and "unit" digits, we have to choose between 3 possibilities : - The ten digit 3, followed with the unit digit between 3 and 9 - The ten digit between 4 and 7, followed by any digit ( \d) - The ten digit 8, followed with the unit digit between 0 and 3 And, finally, a second \bassertion Remark : Strictly speaking, for characters displayed by the usual Courrier New font, the regex syntax \drepresents a single digit, in one of the four lines below : 0123456789 Digit Zero to Nine [\x{0030}-\x{0039}] or [0-9] ¹²³ Superscript One, Two and Three [\x{00b9}\x{00b2}\x{00b3}] or [¹²³] ٠١٢٣٤٥٦٧٨٩ Arabic-Indic digits Zero to Nine [\x{0660}-\x{0669}] ۰۱۲۳۴۵۶۷۸۹ Eastern Arabic-Indic digits Zero to Nine [\x{06f0}-\x{06f9}] Happily, most of the time, these details, don’t matter at all ! So, to conclude, the Python script could be : editor.rereplace('\b1(3[3-9]|[4-7]\d|8[0-3])\b', lambda m: str(int(m.group(0)) + 64)) Cheers, guy038 Thanks so much for the tips. You GUYS are awesome. I am a bloke but love you all :) Pun intended especially for GUY038 which i have just read. Seems like some very useful information here. I added the Python.script plugin and when opening the console it shows an “unknown exception” error. I changed configuration for loading at “startup” and NPP++ opens fine, only when I try to open the python script console. Hmm now it opened without error! (too early in the morning, here its 5am!). Now i can try the script. The actual sequence i am working on is :REG_137:137:S :REG_138:138:U :REG_139:139:U :REG_140:140:U and to replace all ocurrences of the number 137, 138,139,140 with a new set of numbers that happen to be currently 64 (may not be this exactly in future) higher. in other words this is a cpu register translation file. I am probably going to be copying in a batch of these, and just wanting to update a selection to a different memory block range. I hope the extra info helps narrow down the requirements. My steps so far. I select just the number range in NPP++, then in the python script console paste the suggested command and press run. the command then appears in the console area with a >>>> beginning but doesnt do anything on the selected text. Scratched head. What am i doing wrong. \b1(3[3-9]|[4-7]\d|8[0-3])\b I use this in my find box and it is finding numbers from 133 to 183 but only the last number in the row. Too much to learn! REG_137:137:S I need to find both 137 and 137 then replace them with the new number. my example number could be from 10-99 or 100-999 and need to learn what makes the number range. Happy to work on a block of 100, even that would be super useful. again thanks. Also how to makeit work on the selected range. I can then manually select the column range then apply the script? I don’t think you did something wrong, it looks like the installation of the plugin didn’t succeed. The unexpected error is a strong indication. Do you mind installing the python script plugin again? But this time use the MSI package from here. Just install, no need to remove it first it will overwrite existing files. The code needs to be modified, the word boundaries must be escaped. editor.rereplace('\\b1(3[3-9]|[4-7]\d|8[0-3])\\b', lambda m: str(int(m.group(0)) + 64)) But as guy038 already mentioned, it does only replace numbers which aren’t bind to other chars. :REG_137:137:S :REG_138:138:U :REG_139:139:U :REG_140:140:U The first 137 … is bind to REG_ If you can be sure that no numbers like 51374 appear and needs to be replaced, remove the \\b from the code and it should replace all instances in the editor not only the selected ones. If you want to work on selection than you must use one particular way to select the numbers because it would result in different selections otherwise. Cheers Claudia Thanks Claudia. I have downloaded the MSI and installed that which seems to run fine, no complaints this time. In the console it now shows ok and works on my selection. However it only works on the last number in the row. ie :REG_133_1:197:B:0 The 133 is original, the 197 is the newly updated number. Even if the first 133 is in the selection in column mode it doesnt touch it obviously considers the whole line before doing its magic. Maybe its binding to “_” ? I am happy to just do a small block at a time as anything is much faster than looking between different documents to do it manually. So i prefer the work on selection method. Really appreciate the guidance here. So many power things to use if only I could learn them all. I can see now the python script plugin opens up many new manipulations. Hello minsikau, If you want to operate on selection a one liner isn’t possible anymore. Use Plguins->Python Script->New Script and copy the following script into it. Save it with a meaningful name. Important, the selection made must be either a single line or made in column mode, this is by pressing ALT key and then selecting the text. import re def replaceIt(word): return re.sub('1(3[3-9]|[4-7]\d|8[0-3])', lambda m: str(int(m.group(0)) + 64),word) for i in range(editor.getSelections()): start = editor.getSelectionNStart(i) end = editor.getSelectionNEnd(i) word = editor.getTextRange(start,end) if len(word) > 0 and (word.isspace() != True): editor.setTarget(start, end) editor.replaceTarget('{0}'.format(replaceIt(word))) So, selcet text and run script from menu. If there are any questions let me know. Cheers Claudia thanks Claudia. I have moved past those files so cant test currently. In future I will be back to the pesky lists again so will check then. Really appreciate the guidance. MInsik
https://notepad-plus-plus.org/community/topic/11635/how-to-replace-a-number-range-with-same-rang-just-adding-an-offset-ie-find-a-3-digit-number-between-say-133-to-183-add-64-and-replace-the-original-number
CC-MAIN-2017-39
refinedweb
1,573
72.26
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project. On Wed, Jun 11, 2014 at 11:28:05PM +0530, Siddhesh Poyarekar wrote: > On Thu, May 15, 2014 at 09:43:05PM +0000, Joseph S. Myers wrote: > > diff --git a/conform/data/sys/mman.h-data b/conform/data/sys/mman.h-data > > index 0555fd1..3a88684 100644 > > --- a/conform/data/sys/mman.h-data > > +++ b/conform/data/sys/mman.h-data > > @@ -39,8 +39,10 @@ optional-function int posix_typed_mem_get_info (int, struct posix_typed_mem_info > > optional-function int posix_typed_mem_open (const char*, int, int) > > # endif > > > > +# ifndef POSIX > > type size_t > > type off_t > > +# endif > > The earliest POSIX I could access (2001) as this text: > > The size_t and off_t types are defined as described in > <sys/types.h>. > > Since I didn't have a copy of the POSIX 1995/6, Carlos suggested I > look at the next best available thing, which was the Susv1 and that > too had the same text. Wouldn't that make this change incorrect? > > > type suseconds_t > > # endif > > +# ifndef POSIX > > type time_t > > The Susv1 has time_t in sys/types.h. I went through your second similar patch proposal for wait.h and the number of inconsistencies leads me to believe that I am getting something wrong, especially since I'm not even looking at the exact document you cited for verification. I'll defer review to someone who actually has access to the document or has other means to verify the change. Siddhesh Attachment: pgpCO9XExVtal.pgp Description: PGP signature
http://sourceware.org/ml/libc-alpha/2014-06/msg00269.html
CC-MAIN-2020-05
refinedweb
252
57.57
Varnish SSL and hitch SSL termination super bad performance I'm testing around with loader.io and noticed SSL (termination) in front of varnish serves very badly. My Digital Ocean graph seems to show Disk I/O maxed at 1.21MB/s (isn't this incredibly low? My M4 SSD runs around 1.500MB/s which is not the same as 1.5 right?) Cache-Control: max-age=333s I have setup Hitch as SSL termination like so: sudo nano /etc/hitch/hitch.conf # ADD: ## # List of PEM files, each with key, certificates and dhparams pem-file = "/var/lib/acme/live/website.io/haproxy" # END ADD And varnish like so: sudo nano /etc/varnish/acmetool.vcl # ADD: backend acmetool { .host = "127.0.0.1"; .port = "402"; } sub vcl_recv { if (req.url ~ "^/.well-known/acme-challenge/") { set req.backend_hint = acmetool; return(pass); } } # END ADD # include acmetool settings in default.vcl cp /dev/null /etc/varnish/default.vcl sudo nano /etc/varnish/default.vcl # ADD: vcl 4.0; import std; backend default { .host = "127.0.0.1"; .port = "8080"; } sub vcl_recv { if (std.port(local.ip) == 80) { set req.http.x-redir = "https://" + req.http.host + req.url; return(synth(850, "Moved permanently")); } } sub vcl_synth { if (resp.status == 850) { set resp.http.Location = req.http.x-redir; set resp.status = 301; return (deliver); } } include "/etc/varnish/acmetool.vcl"; # END ADD What's wrong with my setup and how can I improve performance?
https://www.digitalocean.com/community/questions/varnish-ssl-and-hitch-ssl-termination-super-bad-performance?answer=34011
CC-MAIN-2017-43
refinedweb
240
56.01
Introduction: AirPlay Speakers. Step 1: Materials You will need... -Raspberry pi running raspbian -power supply -wifi adapter -some speakers(or you can have it play through HDMI if you want) EXTRA: -LED -a couple female to female leads Step 2: Installing the Software You need your wifi adapter in and connected to the wifi (there are lots of tutorials online if you don't know how to do this). This step is from Jordan Burgess's AirPlay tutorial: First, upgrade your packages by entering the following commands into LX Terminal: sudo apt-get install update sudo apt-get install upgrade Next, you can set the audio output to whichever port you want. For this tutorial, we will set it to the headphone port: sudo amixer cset numid=3 1 Now you need to get shairport. Enter the following command, (yes it is very long and it will take a while to finish so you might as well go do something else while you wait): sudo apt-get install git libao-dev libssl-dev libcrypt-openssl-rsa-perl libio-socket-inet6-perl libwww-perl avahi-utils libmodule-build-perl Now you have to install Perl Net-SDP: git clone perl-net-sdp cd perl-net-sdp perl Build.PL sudo ./Build sudo ./Build test sudo ./Build install cd .. Now setup Shairport: git clone cd shairport make Step 3: Running Airplay You can now run AirPlay from any LX Terminal session If you aren't already, go to the shairport directory by entering cd shaiport Now run it by entering ./shairport.pl -a (server name) If you are connected to wifi, it should say something like "Established under name....." Now, go on whatever iOS device you want, pull up AirPlay, and connect. You can now stream music wirelessly to you speakers. Step 4: Running AirPlay at Boot First what you have to do is make your pi login automatically at boot. Enter the following command: sudo nano /etc/inittab This will open a text file. Now find the line that starts with '1:2345...' Comment it out by putting a # in front of it. Now, below it, add the line 1:2345:respawn:/bin/login -f pi tty1 /dev/tty1 2>&1 Close it with CONTROL+X, Y, ENTER Your pi should now no longer require a username or password. Next we have to add an AirPlay File. Enter the following command: sudo nano AirPlay This will pull up a blank text editor. Enter your AirPlay commands: cd shairport ./shairport.pl -a (server name) Now close it by doing control+X, then Y, then ENTER Next, make that file executable. Enter: sudo chmod +x AirPlay Now open .bashrc by entering sudo nano .bashrc And add the line ./AirPlay Now close it by doing CONTROL+X, Y, ENTER Now your pi should automatically start an AirPlay server when you plug it in. It will take a while to get it started, it's still running a normal boot, but now, when ever you log in, which it does automatically now, it starts an AirPlay server. All you need to do is plug it in with the wifi adapter and some speakers and you have a working AirPlay server. Enjoy! Step 5: Extra: Notification LED I decided to add a little LED Bulb that would go on about when the AirPlay Server goes up. There is a slight delay between when the bulb goes on and when the server goes up by about 5 seconds, but it is still kinda cool. Take LED and connect one side to GPIO18 and the other to a Ground. To do this, You can use some Female to Female leads and connect directly to the LED. I only had male to males, but I found that if I took pliers, I could pull out the metal tip, leaving a female header that worked perfectly. It's a very tight fit though and you have to be careful not to Bend the pins, but it works really well. Now you have to create a python script that will activate the pins. Open a new script and add the following lines of code: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.output(18,True) Now save the file as LEDON.py Next reopen the AirPlay nano editor with the command sudo nano AirPlay And add the following at the top, before 'cd shairport' sudo Python LEDON.py Next, save and exit. Now if you reboot, the LED will go on a few seconds before the AirPlay server goes up. NOTE: The LED doesn't turn off on its own. I did this by creating a new Python script named LEDOFF.py with the following commands: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18,GPIO.OUT) GPIO.output(18, False) Then I added it to the end off .bashrc by entering: sudo nano .bashrc Then adding -- sudo python LEDOFF.py -- Below the './AirPlay' Now when the server is running, if you cancel it by doing CONTROL+C, it will stop the server and turn off the LED Participated in the Coded Creations 6 Comments 5 years ago I realize this is an old thread, but what the hell, I got this to work, but the volume is REALLY low....ideas? (yes, everything is turned up to max but still quiet) 6 years ago on Introduction It actually shows up in System Preferences, but says "The selected device has no output controls" 6 years ago I'm not sure, I've always had a few seconds of delay, so it's probably just the pi, you've probably learned by now that it's not the fastest computer... 6 years ago If you mean between the device that You've connected to the pi, then yes. It's normal, just slow internet. The music is getting streamed through your internet so the slower your internet the bigger the delay. Reply 6 years ago My lan is pretty fast, and no other devices have this issue, wired or wireless, just the py and py2, could it be the code itself that creates a little delay? 6 years ago Hi, nice tutorial, I always have a sound delay between my other devices and a rasp pi (multiroom setup), do you have experience with that issue?
https://www.instructables.com/AirPlay-Speakers/
CC-MAIN-2022-21
refinedweb
1,062
70.23
Amazon DynamoDB What is Amazon DynamoDB? Amazon DynamoDB is a fast, highly scalable non-relational database service. DynamoDB removes traditional scalability limitations on data storage while maintaining low latency and predictable performance. Key Concepts The DynamoDB data model concepts include tables, items, and attributes. Tables In Amazon DynamoDB, a database is a collection of tables. A table is a collection of items and each item is a collection of attributes. In a relational database, a table has a predefined schema such as the table name, primary key, list of its column names and their data types. All records stored in the table must have the same set of columns. In contrast, DynamoDB only requires that a table has a primary key, but does not require you to define all of the attribute names and data types in advance. To learn more about working with tables, see Working with Tables in DynamoDB. Items and Attributes Individual items in a DynamoDB table can have any number of attributes, although there is a limit of 400 KB on the item size. An item size is the sum of lengths of its attribute names and values (binary and UTF-8 lengths).. For example, consider storing a catalog of products in DynamoDB. You can create a table, ProductCatalog, with the Id attribute as its primary key. The primary key uniquely identifies each item, so that no two products in the table can have the same ID. To learn more about working with items, see Working with Items in DynamoDB. Data Types Amazon DynamoDB supports the following data types: Scalar types – Number, String, Binary, Boolean, and Null. Multi-valued types – String Set, Number Set, and Binary Set. Document types – List and Map. For more information about Scalar Data Types, Multi-Valued Data Types, and Document Data Types, see DynamoDB Data Types. Primary Key When you create a table, in addition to the table name, you must specify the primary key of the table. The primary key uniquely identifies each item in the table, so that no two items can have the same key. DynamoDB supports the following two types of primary keys: Hash Key: The primary key is made of one attribute, a hash attribute. DynamoDB builds an unordered hash index on this primary key attribute. Each item in the table is uniquely identified by its hash key value. Hash and Range Key: The primary key is made of two attributes. The first attribute is the hash attribute and the second one is the range attribute. DynamoDB builds an unordered hash index on the hash primary key attribute, and a sorted range index on the range primary key attribute. Each item in the table is uniquely identified by the combination of its hash and range key values. It is possible for two items to have the same hash key value, but those two items must have different range key values. Secondary Indexes When you create a table with a hash and range key, you can optionally define one or more secondary indexes on that table. A secondary index lets you query the data in the table using an alternate key, in addition to queries against the primary key. DynamoDB supports two kinds of secondary indexes: local secondary indexes and global secondary indexes. Local secondary index: An index that has the same hash key as the table, but a different range key. Global secondary index: An index with a hash and range key that can be different from those on the table. You can define up to 5 global secondary indexes and 5 local secondary indexes per table. For more information, see Improving Data Access with Secondary Indexes in DynamoDB in the DynamoDB Developer Guide. Query and Scan In addition to using primary keys to access items, Amazon DynamoDB also provides two APIs for searching the data: Query and Scan. We recommend that you read Guidelines for Query and Scan in the DynamoDB Developer Guide to familiarize yourself with some best practices. Query A Query operation finds items in a table or a secondary index using only primary key attribute values. You must provide a hash key attribute name and a distinct value to search for. You can optionally provide a range key attribute name and value, and use a comparison operator to refine the search results. For sample queries, see: For more information on Query, see Query in the DynamoDB Developer Guide. Scan. For sample scans, see: For more information on Scan, see Scan in the DynamoDB Developer Guide. Project Setup Prerequisites To use DynamoDB in your application, you'll need to add the SDK to your project. To do so, follow the instructions in Setting Up the AWS Mobile SDK for .NET and Xamarin. Create a DynamoDB Table To create a table, go to the DynamoDB console and follow these steps: Click Create Table. Enter the name of the table. Select Hash as the primary key type. Select a type and enter a value for the hash attribute name. Click Continue. On the Add Indexes page, if you plan to to use global secondary indexes, set Index Type to "Global Secondary Index" and under Index Hash Key, enter a value for the secondary index. This will allow you to query and scan using both the primary index and secondary index. Click Add Index To Table, and then click Continue. To skip using global secondary indexes, click Continue. Set the read and write capacity to your desired levels. For more information on configuring capacity, see Provisioned Throughput in Amazon DynamoDB. Click Continue. On the next screen, enter a notification email to create throughput alarms, if desired. Click Continue. On the summary page, click Create. DynamoDB will create your database. Set Permissions for DynamoDB To use DynamoDB in an application, you must set the correct permissions. The following IAM policy allows the user to delete, get, put, query, scan, and update items in a specific DynamoDB table, which is identified by ARN: { "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:Scan", "dynamodb:UpdateItem" ], "Resource": "arn:aws:dynamodb:us-west-2:123456789012:table/MyTable" } ] } You can modify policies in the DynamoDB Developer Guide. Integrating DynamoDB with your Application The AWS Mobile SDK for .NET and Xamarin. The AWS Mobile SDK for .NET and Xamarin allows you to make calls using APIs from the AWS SDK for .NET to work with DynamoDB. All of the APIs are available in the AWSSDK.dll. For information about downloading the AWS SDK for .NET, see AWS SDK for .NET. There are three ways you can interact with DynamoDB in your Xamarin application: Document Model: This API provides wrapper classes around the low-level DyanmoDB API to further simplify your programming tasks. The Table and Document are the key wrapper classes. You can use the document model for the data operations such as create, retrieve, update and delete items. The API is available in the Amazon.DynamoDB.DocumentModel namespace. Object Persistence Model: The Object Persistence API enables you to map your client-side classes to the DynamoDB tables. Each object instance then maps to an item in the corresponding tables. The DynamoDBContext class in this API provides methods for you to save client-side objects to a table, retrieve items as objects and perform query and scan. You can use the Object Persistence model for the data operations such as create, retrieve, update and delete items. You must first create your tables using the Service Client API and then use the object persistence model to map your classes to the tables. The API is available in the Amazon.DynamoDB.DataModel namespace. Service Client API: This is the protocol-level API that maps closely to the DynamoDB API. You can use this low-level API for all table and item operations such as create, update, delete table and items. You can also query and scan your tables. This API is available in the Amazon.DynamoDB namespace. These three models are explored in-depth in the following topics: Topics
https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/dynamodb.html
CC-MAIN-2018-09
refinedweb
1,339
64.3
Hi folks! First of all, thanks a lot to all who sent me comments about lintian and reported bugs! I've fixed a lot of things in lintian (see below) and checked the whole archive again. The new report is available at lintian home page Please have a look at the reports and tell me about - bugs in lintian - policy exceptions to add to the overrides file - other comments about lintian or policy Note, that I haven't had time to update my mirror yet. Just ignore the errors that lintian has found if there is already an updated package on master. I plan to do a few more changes to lintian in the next days and hope that I can finally release a first lintian package by the end of this week. As always, _any_ comments are welcome! Thanks, Chris --------------------------------------------------------------------------- CHANGES / FIXES TO LINTIAN: - improved manpage check: binaries in /usr/games must have a manual page too (e.g., freeciv--thanks to Richard for pointing this out!) - fixed bug in files check: binaries like "w-bassman" have been reported as possible-namespace-pollution by mistake (thanks to Joey Hess!) - fixed bug in copyright check: due to a buggy perl regexp, the symlink-without-dependency has been reported even if the dependency was defined (thanks to Richard!) - description check: removed check whether the package description contains a copyright notice since this produced too many reports by mistake (thanks to Manoj for checking out the available file!) - improved description check: check for package descriptions that start with leading spaces (description-starts-with-leading-spaces tag) - copyright check: renamed tag into `old-fsf-address-in-copyright-file' (thanks to Santiago for pointing out that the old tag was inaccurate) - fixed bug in files check: the directory `.etc' has been treated as `etc' (e.g., smartlist--thanks to Santiago for tell me) - improved `files' check: the following binaries are not reported as `possible-namespace-pollution' anymore: w [ at ar as bc bg cc cd cp cu dd df du ed ex fc fg id ln lp ls m4 mv nl nm od pg pr ps rm sh tr vi wc ci co dc ld su. (If you know other important binaries to add to this list, please tell me.) - improved output of `files' and `shared-library' check: use octal numbers for file permissions, e.g., use 755 instead of `-rwx-r-xr-x' (Thanks to Richard for the suggestion!) - improved `files' check: allow game directories or files to be group-writable/setgid if owner is `root/games' (Thanks to Joey Hess for pointing this out!) - implemented `overrides' file and started to collect overrides (Thanks to all who told me about exceptions/override entries!) - fixed copyright check: don't report debmake-templates/fsf-address bugs more than once per package - improved `md5sums' check: ignore if conffiles are not included in the md5sums .
https://lists.debian.org/debian-devel/1998/02/msg00697.html
CC-MAIN-2016-40
refinedweb
478
65.96
Introduction to Python Pygame Programming via gaming is a teaching tool nowadays. Gaming includes logics, physics, math and AI sometimes. Python language uses pygame to carry out the programming. Pygame is the best module so far helping in game development. Pygame is a module used to build games that are usually 2D. Knowing Pygame proficiently can take you far in developing extreme ranges of games or big games. Syntax and Parameters of Python Pygame Below are the syntax and parameters: Syntax import pygame from pygame.locals import * Parameters - importing pygame module followed by accessing key coordinates easily from locals - From there you write your game code where you want to insert objects movable, sizeable, etc. Then initialize the pygame module. Examples to Implement Python Pygame Below are the examples: 1. initializing the pygame pygame.init() This is a function call. Before calling other pygame functions, we always call this first just after importing the pygame module. If you see an error that says font not initialized, go back and check if you forgot pygame.init() insertion at the very start. 2. Surface Object pygame.display.set_mode((500, 500)) This function call returns the pygame.Surface object. The tuple within tells the pixel parameters about width and height. This creates an error if not done properly which says argument 1 must be 2 items sequences, not int. Code: import pygame from pygame.locals import * pygame init() display_window = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!') while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() Output: #Let’s make a character move on the screen. Code: import pygame pygame.init() win = pygame.display.set_mode((500, 500)) pygame.display.set_mode = ("First game") x = 50 y = 50 width = 40 height = 60 vel = 5 run = True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= vel if keys[pygame.K_RIGHT]: x += vel if keys[pygame.K_UP]: y -= vel if keys[pygame.K_DOWN]: y += vel win.fill ((0,0,0)) pygame.draw.rect(win, (255, 0, 0),(x, y, widty, height)) pygame.display.update() pygame.quit() - First, we initialize the pygame module by importing it. - Now, we give the parameters for the window size of the game we are constructing. - Naming the game to the first game, which is the name of the window. - Now, creating a character, it needs parameters. Let’s say we create a rectangle. A rectangle needs height, width, x and y coordinates to be placed in the window, the velocity with which it should move across the window. Output: This is how the output seems for creating a character, that is, in this case, a rectangle. - Then we need to start writing out the main loop which considers the character movement. In this program the main loop is going to check for its collision, its mouse events, it’s also going to check if you hit something. This is one of the simple ways to do it. - Now we make a run variable. In the loop, we are going to check the collision. Giving the loop a time delay is going to help you by delaying the things happen real quick in the window. This regards kind od a clock in pygame. You cannot normally import the clock in pygame but this is the easy way to do it. - For checking an event: Events in pygame are anything that is caused by the user. Like, moving the mouse in general, accessing the computer to create files. So, to check for the events, we happened to create a loop check for events. - Then we draw a rectangle that is movable which is a surface on the pygame window. All the colors in pygame are in RGB so 255 is red and the giving in the defined parameters width, height, x, y coordinates. Then we update the window which displays us a rectangle at those particular coordinates and parameters. Now, to move the rectangle, we need to move it continuously. For that, I need to set up a list. We give in, down, left and right arrows. Then we quit the pygame which closes the window for us. Output: With the use of keys on the keyboard, one can move the rectangle. The output is shown like this. stop and play are used to play the sounds. The immediate recognition of play, gives immediate hear of beep and stops when recognizes stop. We can even play a background music time by uploading it. The file can be of type MP3, MIDI or WAV. Code: play_sound = pygame.mixer.Sound(‘beeps.wav’) play_sound.play() import time time.sleep(5)#lets the sound play for 5 seconds. play_sound.stop() Conclusion If one knows the basics of Python programming, he can learn the gaming modules on his own. Using loops, variables, if-else statements, the code interprets how the program behaves. There are many such changes you can make by inserting objects like fonts, clock object, pixel objects and coordinates, drawings, transparent colors, game loops and states, and many more. Recommended Articles This is a guide to Python Pygame. Here we discuss an introduction to Python Pygame along with syntax, parameter and respective examples to implement. You can also go through our other related articles to learn more –
https://www.educba.com/python-pygame/?source=leftnav
CC-MAIN-2021-04
refinedweb
902
77.84
I ran into the need of monkeypatching a large number of classes (for what I think are very good reasons :-) and invented two new recipes. These don't depend on Py3k, and the second one actually works all the way back to Python 2.2. Neither of these allows monkeypatching built-in types like list. If you don't know what monkeypatching is, see see. I think it's useful to share these recipes, if only to to establish whether they have been discovered before, or to decide whether they are worthy of a place in the standard library. I didn't find any relevant hits on the ASPN Python cookbook. First, a decorator to add a single method to an existing class: def monkeypatch_method(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator To use: from <somewhere> import <someclass> @monkeypatch_method(<someclass>) def <newmethod>(self, args): return <whatever> This adds <newmethod> to <someclass> Second, a "metaclass" to add a number of methods (or other attributes) to an existing class, using a convenient class notation: def monkeypatch_class(name, bases, namespace): assert len(bases) == 1, "Exactly one base class required" base = bases[0] for name, value in namespace.iteritems(): if name != "__metaclass__": setattr(base, name, value) return base To use: from <somewhere> import <someclass> class <newclass>(<someclass>): __metaclass__ = monkeypatch_class def <method1>(...): ... def <method2>(...): ... ... This adds <method1>, <method2>, etc. to <someclass>, and makes <newclass> a local alias for <someclass>. -- --Guido van Rossum (home page:)
http://mail.python.org/pipermail/python-dev/2008-January/076194.html
crawl-002
refinedweb
245
62.17
Deleting an entity from another entity?Robert Benkovitz Dec 12, 2005 4:53 PM This might be a stupid question, but I can't seem to find the answer to it. I'm fairly new to JBoss/Hibernate/EJB3.0, but I have a good deal of experience using TopLink. I have a collection of entity objects contained in another entity object. When I remove an entity from the collection (via a method on the owning entity) I would like to remove it from the datastore - how do I go about it? Do I need to get a handle to the EntityManager and call remove()? If so, what is the best way to get a handle to the EntityManager inside an Entity Bean? TopLink has a setting called 'Private Owned', which would automatically delete an object if you removed it from the owning entity's collection. I see that Hibernate does this for simple collections (Strings and the like), but not for Entity collections. Thanks for any help. 1. Re: Deleting an entity from another entity?Jacek Olszak Dec 13, 2005 4:33 AM (in response to Robert Benkovitz) Hmm... maybe you should addnotate the collection with Cascade.REMOVE ? For example: public class Container { private List<Item> items; @OneToMany(cascade=CascadeType.REMOVE) public List<Item> getItems(); } When you remove an item from the list, you removed the entity from the datastore too. getItems().remove(0); em.merge(container); I think it should work, but not sure for 100%. 2. Re: Deleting an entity from another entity?Robert Benkovitz Dec 13, 2005 10:51 AM (in response to Robert Benkovitz) Thanks for the reply. Collection is already annotated with Cascade.REMOVE - merge() doesn't work in this instance. I think I need a way to get to the EntityManager inside my Entity Bean. For example: @Entity public class Container { private List<Item> items; @OneToMany(mappedBy="security", cascade=CascadeType.ALL) @MapKey (name="key") public Map<String, SecProperty>getProperties(); ... public void removeProperty(String key) { if (getProperties().containsKey(key)) { Object obj = getMyProperties().remove(key); // // This is where I think I could use the EntityManager // to delete from database: // em.remove(obj); } } } What is the best way to inject the EntityManager into an Entity Bean? Or is there is another way to accomplish this without using the EntityManager? 3. Re: Deleting an entity from another entity?Robert Benkovitz Dec 13, 2005 3:21 PM (in response to Robert Benkovitz) Okay - more searching led to a 'workaround' using Hibernate's native CascadeTyp.DELETE_ORPHAN setting. I'm not quite sure why a facility like this or like TopLink's 'Private Owned' flag is left out of the EJB spec - it seems like a fairly common mechanism.
https://developer.jboss.org/thread/106706
CC-MAIN-2018-17
refinedweb
449
58.69
0 All, I am using lock() to try and sync threads writing to the same file, but my threads are still stepping on one another. Can anyone tell me why this doesn't work and how to fix it? Here is some sample code. In the real program the writes are very infrequent, happening only when there is an error condition. // This is Program.cs using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace Threadtest { class Program { static void Main(string[] args) { WriteToFile wtf1 = new WriteToFile("T1"); WriteToFile wtf2 = new WriteToFile("T2"); Thread t1 = new Thread(wtf1.writeJunk); Thread t2 = new Thread(wtf2.writeJunk); Console.WriteLine("Running..."); t1.Start(); t2.Start(); } } } // This is WriteToFile.cs using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; namespace Threadtest { class WriteToFile { private String threadName; private System.Object lockThis = new System.Object(); public WriteToFile(String threadName) { this.threadName = threadName; } public void writeJunk() { while (true) { try { lock (lockThis) { using (StreamWriter outStream = File.AppendText("test.txt")) { outStream.WriteLine("This was written by thread: " + threadName); } } } catch (Exception e) { Console.WriteLine("We should never end up here, but sometimes we do."); } Thread.Sleep(100); } } } } Thanks, Bill
https://www.daniweb.com/programming/software-development/threads/445223/multiple-threads-writing-to-1-file
CC-MAIN-2018-39
refinedweb
198
55.5
The Family of Charles Lee Dibrell: i. John Lee Dibrell b. 04 Jun 1777, Buckingham Co, VA d. cir 1861, Whitley Co, KY m1 Ellender Cocke, 5 Feb 1805, Wayne Co, KY m2 Lavina Reagan, bef. 1835 ii. Elizabeth Dibrell b. 1780, Buckingham Co, VA d. 1843 m. Drewry Shrewsbury, 21 Aug 1799, Pulaski Co, KY iii. Mary Dibrell b. 1783, Silver Creek, Madison Co, KY d. aft 1860 m. Nathaniel Shrewsbury, Jr iv. Anthony Dibrell b. 04 Jun 1788, Silver Creek, Madison Co, KY d. 25 Jan 1875, Sparta, White County, TN m. Mildred Carter, 26 Apr 1811, Wayne Co, KY v. Leanna Dibrell b. 03 Nov 1790, Silver Creek, Madison Co, KY d. 19 May 1876, Obion County, TN m. George Washington Gibbs, 12 Apr 1810, Wayne Co, KY vi. Judith Dibrell b. 26 Oct 1792, Silver Creek, Madison Co, KY d. 22 Aug 1837, Elizabethtown, Hardin County, KY m. Temple Poston, 3 Sep 1810, Wayne Co, KY vii. Charles Lee Dibrell, Jr b. 24 Nov 1794, Silver Creek, Madison Co, KY d. 1860, Chickasaw Nation, IT m. Alzira Mitchell, ca 1821, Natchez, MS viii. Joseph Burton Dibrell b. 1797, Silver Creek, Madison Co, KY d. 1872, Gibson Co, TN m1 Emaline Jane (Dibrell), bef 1818 m2 Letha Lee Haley, 1820 m2 Lucy Patteson, 24 Sep 1800, Campbell Co, VA. b. 1760 d. 1825 Children of Charles Dibrell and Lucy Patteson are: ix. Panthea Dibrell b. 1804 m. Nathaniel Bramlett x. Elvira Dibrell b. 2 Apr 1804, Wayne Co, KY d. 18 Sep 1847, Carroll Co, AR m. Joel Dyer Mitchell, 22 May 1825, Sparta, White Co, TN xi. Agnes Dibrell b. 1808, Wayne Co, KY d. 1904, Watterson, Bastrop Co, TX m. James Warrent Eastland xii. Obediah Patteson Dibrell b. 1810 d. aft 1860, IT Full listing of Descendants Charles Lee Dibrell, by Mary Nan Crowther (28 Nov 1997) [Brackets indicate additional material inserted by Phil Crowther] Charles Lee Dibrell was the oldest son born to Anthony and Elizabeth Lee Dibrell on October 24, 1757. He was the first of three children: Leeanna, Judith, and Anthony, Jr. were the other siblings. Charles received forty pounds upon the death of one of his mother's brothers, John Lee, which enabled him to obtain some education. This was to be a big help in handling his business as well as when he served in the county government of Kentucky. In 1776 Charles married Martha Burton, daughter of John Burton of Henrico County. And on June 4, 1777, their first child, John Lee, was born. During this same time, Charles began his Revolutionary War Service, as detailed in the section on "Dibrells in the Revolution". In the 1782 Federal Census of Buckingham County Virginia, Charles is shown as having two children and four slaves. It was also in 1782 that Charles and Martha became a part of the ever increasing number of brave pioneers who made the long journey over the mountains that led to the land of Kentucky. Some years before Daniel Boone had helped to open the Wilderness Road and led many parties into the country which had always seemed to exist as a mystery beyond the Barrier of the Appalachian Mountains. As the colonists had fought the British beyond the mountains, they became familiar with the territory and when the war was over, many wanted to move there and settle. At first they were not encouraged to do this, but eventually the government realized that this would be good for the country to explore and settle further west. Thus began the great migration. Kentucky had long been known as the "dark and bloody ground" which may be one of the meanings to the Indian word "Kan-tuck-hee." This was their name for the area which became known as Kentucky. Not many Indians actually lived within the area, but it was considered a common hunting ground for the northern and southern tribes. As such it was often fought over and that is how it earned its name. Rene Robert Cavelier de La Salle may have been one of the early white explorers to come into the area, when he entered in 1669. Other French explorers most likely followed, and when the English heard about their explorations their interest peaked and they wanted to find out about this land beyond the mountains. Gabriel Arthur penetrated the northeastern part with a party of Indians in 1673, and it is believed that he was the first Englishman to do this. For another 70 years nothing more was done. In 1742 John Peter Salley with a party of Virginians entered the region, where he was captured by the French; after his release his account aroused interest in Kentucky. In 1750 the Loyal Land Company of Virginia sent out an expedition under Dr. Thomas Walker; this party passed through Cumberland Gap, and erected a log house on the Cumberland River near the site of present-day Barbourville, but abandoned it after an Indian attack. The next year the Ohio Company sent Christopher Gist, but settlement awaited termination of the struggle by the French and the English for control. Even after the British had gained control of the region, settlement was delayed as the British forbade settlement beyond the mountains. They reasoned that it would be too expensive to provide protection to the people from Indian attack. However, other people visited the area and in 1773 the Transylvania Company was founded by Judge Richard Henderson of North Carolina secured a large land grant, made a treaty with the Cherokees, and commissioned Daniel Boone to blaze a trail into Kentucky. In May 1775, Boonsboro was founded. Meanwhile James Harrod in 1774 led a party of surveyors down the Ohio and up the Kentucky River to the present site of Harrodsburg, but when Dunmore's War broke out they were forced to retire. In June 1775 they returned and established Harrodsburg. Naturally there arose rivalry between the two factions. George Rogers Clark took the side of the North Carolina group and they won. Then the Transylvania Company was declared illegal. Virginia established Kentucky County which enveloped the whole region. During the American Revolutionary War the area was mostly ignored, but after 1778 the area became constantly harassed by the Indians. On August 19, 1782 at the Battle of Blue Licks, the Kentuckians were routed by the Indians and the British with a loss of about 70 killed and captured. In 1780 settlement received a big boost when 300 boats came down the Ohio with some 3,000 persons. By that time Kentucky County was divided into three counties: Lincoln, Fayette, and Jefferson. Dissatisfaction by the settlers arose when it was acknowledged that enforcement of any peace treaties with the Indians could not be carried out because of the great distance to Virginia. Ten conventions were held in an attempt to create a permanent government. There were some advocates of setting Kentucky up as a separate country while others preferred to become a state within the Union. Some even wanted to join Spain which at that time controlled New Orleans and the land west of Mississippi River. Although at first Virginia refused to consent to separation, it finally agreed in 1789. On June 1, 1792 Kentucky entered the Union as the 15th state. Thus, this was the region that Charles Dibrell chose to make his home and his story follows. There are many stories about this adventure and it has to be with admiration that we follow the story of these early families who made this trip. It was not easy especially where women and children were concerned. Travel was very difficult because the road had to be cut as they slowly progressed up and over the mountains. Remember these were not trail-hardened mountain men making the trip. These were ordinary people that often consisted of families with small children. A steady stream of settlers were to deepen the ruts that carried the carts and wagons on the trails leading from Virginia and North Carolina into the valleys of eastern and middle Tennessee and north-central Kentucky. The solid rocky spine of the Appalachians did more than rear a frowning geographical barrier; in time it formed a psychological dividing point beyond which Virginians were to become Kentuckians. At this time the Wilderness Road was only a trail meant for men traveling by foot or horseback or drivers of live stock. This was a magnificent virgin forest through which they had to cut their way by the use of an ax or tomahawk. It would be very tedious and time-consuming as the men made the passage way wider and helped to accommodate the assemblage of wagons and carts. The trip was to take by the oppressive Clinch Mountain along the Holston River in southern Virginia which they crossed near the site of present day Knoxville. From there they took the Indian Trail that traversed to the northwest to the mouth of Obey's River or on Brimstone Creek where it followed the ridge on the eastern side of the Big South Fork. The trail then turned down into the Cumberland Valley where they crossed the river at Smith Shoals. This route had become popular with the Kentucky settlers as early as 1781. The main body of the Great Lakes Trail follows the route almost identical with that of the Cincinnati Southern Railroad which at one time had laid their tracks along the route. The Great Lakes Trail then would continue northward crossing the Ohio River near the present site of Cincinnati, and continued on up into the northern region of the Great Lakes intersecting on the way with many lesser trails. There were numerous side trails with a converging of the two main north-south trails near King's Mountain of Revolutionary War fame as the Indians over the centuries had traveled from one area to another. Some of the points along the trail were Parleyville, Mill Springs, Whitley City, and Rockwood, Tennessee. Here the Great Lakes Trail made a great loop south of the Cumberland touching the river at the mouth of Meadow Creek near Price's Meadows as well as at Smith Shoals where the main trail crossed. Can you imagine the awe and reverence these people must have felt when they saw a grove of towering tulip poplars that would shoot up from the riverbank and cliff shoulders with the precision of an arrow shot? In those days these magnificent trees stood a hundred and fifty feet in the air and measured ten to twelve feet in diameter at the height of a man's chest. Surely these were sights unseen even in Virginia. It would not have been considered too wild, if one had the thought that they might be experiencing a bit of heaven here on earth. Of course, any thoughts such as those would have been realized as a dream only because there were always the Indians to be fearful about. Wild game flourished including the buffalo which included the small game such as rabbits, squirrels, raccoons, and such. Deer was plentiful as well as bears and panthers. The streams and rivers were filled abundantly with fish of a size unheard of today. It was not unusual to catch a fish measuring five feet in length. The settlers must have been overjoyed to find the land so rich. Better than even their wildest dreams. It would be to this area on the Cumberland River that Charles and his family would return a few years later. At the present time the group continued on their way to where Daniel Boone had opened an area to which he encouraged the settlement of these early people. The more people gathered together seemed a good idea as Indians were still close by. It is hard to visualize what these settlements must have been like. We have been told they were often crude huts strung along the river or creek bank. Or at other times they were dotted in the clearings, but so few in number that isolation was the rule. The Blue Grass region of Kentucky had what could be called islands of concentrated population. As we see they were located near a small body of water which was very important. In the year 1782 Lexington was little more than a military stockade. This was the year when Charles made the hazardous journey with his family and settled on land located on Silver Creek which must have been near the other settlers who had traveled the trail with them. As mentioned before they found the land and fauna in Kentucky to be even better than they had anticipated. However, this brought with it some problems. The most profound would be the Indians. It was the hunting ground for a large number of Indians and they would not appreciate the intrusion of the white people within their territory. By 1783 the United States government formed the Treaty of Nashville with the Chickasaw Indians that formed the basis for future Indian treaties including that with the Cherokee at Hopewell in 1785. No matter how many treaties were to be written with the Indians, there were certain areas that they deemed belonged to them and they would do whatever they felt was necessary to discourage the white people. The ultimate aim of the Indians even after a century of white settlers was that surely could do something that would send the whites back across the ocean where they belonged. As a result of this feeling, the Indians began to intrude upon the land of the settlers and either just made them uncomfortable or carried out a reign of terror. By the treaty with the Cherokee they held all land south of the Cumberland River east of a point forty miles above Nashville, but this boundary went unobserved by the white man. A map of the Tennessee Government, formerly part of North Carolina, taken chiefly from surveys by General Daniel Smith and others and pictured in "Carey's General Atlas, 1795" showed that all of the land drained by the Big South Fork as well as most of what is now Wayne County along with all of the Plateau of Tennessee as belonging to the Cherokee at this date. The end of the American Revolution settled nothing as far as the Indians were concerned. The Red inhabitants of the Ohio Valley lost their faith in the White Fathers, whether French, British, or native born. North of the Ohio in 1790 there existed all of the ingredients needed for an explosion. The Miami and Wabash tribes had become the chief troublemakers. It is estimated that they and other tribes killed, wounded or took prisoner nearly 1500 men, women and children near the Ohio and its tributaries. Besides this there were constant irritating attacks on boats navigating the midwestern rivers even as far south as the Tennessee River. By 1792 Kentucky had to do something to protect those settlers that they had encouraged to come into this land. The Kentucky Militia was formed. Charles Lee Dibrell became a Captain according to the Executive Journal of Governor Isaac Shelby on June 28, 1792. Charles became a part of the 7th Regiment in Madison County and served in the campaign that drove the Indians to the north across the Ohio River and on into the land of Indiana and Illinois. The militia was to find that the prairie grass grew abundantly tall in this area measuring about twelve feet high which could provide good cover for the Indians. It was not an easy campaign because of this. After a time a settlement was made with the Indians, and peace came to the area. The Indians withdrew and did not encroach on the land again. By 1792 Kentucky became a state and while still living in Madison County Charles became a Justice of the Pace on December 21, 1792. This was an appointment by the Governor. Duties involved in being a Justice of the Peace at this time meant that a Justice could "bind over to good behavior" the following: whore makers, fathers of bastards, cheats, idle vagabonds, night walkers, eavesdroppers, men haunting bawdy houses with women of bad fame, or men keeping such women. More pleasant duties would be to perform marriages, take a disposition regarding loss or theft that could substitute as a sworn statement in court, and two judges sitting together could haul before them and fine "a single woman with child." There was much work for these men to do as the area tried to become more civilized and more like the homeland they had left behind. Settling land claims would become a big problem for Kentucky. In rushing land claimants had posted claims to more than three times the amount of land available. This problem was not helped by the fact that the original surveyor's notes read more like botanical inventories of Kentucky's virgin forests then as foundations for legal instruments. Now that they had arrived at what they considered to be their home the pioneers could turn their attention to providing a home for themselves and their families. They were to find that though it was rich in many resources with which to provide themselves with food and other necessities, it would not be as easy as it had been in Virginia. Life would be harder, but with hard work and diligence they could achieve much of what they wanted. One of the problems was that now they were much further away from the large cities that could provide many of the articles that made life easier. As a result of this the lifestyle of the people became simpler. The clothing for the women became quite simple. Since the beginning of the Revolution more commonly home grown flax and wool were the materials chosen with which to make their clothing. There was also a mixture later known as linsey-woolsey that was often made into a skirt and worn with blouses or waists of thinner material such as linen, wool, and sometimes cotton. Depending upon the season this gave the ladies a choice of just how comfortable they wished to be. The men often wore knee breeches, linen shirts, waistcoats, coats, and for cold weather the usual greatcoat, caped with many pockets and also made commodious, no doubt for comfort. The cut and materials as well as the ornamentation depended upon the purse, inclination, and, of course, the time and place of wearing the garment. The better homes were often built safe behind picketed walls and usually had a basement or cellar as such was commonly known. However, less prosperous pioneers usually built a good home with some form of cellar beneath. Usually they were built of good sized logs on a rock foundation with the cellar being reached by lifting a floor board. For cooking and heating purposes a fireplace was always included. The men had log-rollings, house-raisings, barn coverings, and corn-shucking. Working together was more enjoyable and often made it possible to get things accomplished much faster. The wives had apple-peelings, bean-hullings, rag-tackings, and quilting parties. Getting together helped them to become acquainted and often helped with solving some problems that might have developed within family relationships. After all in those days doctors were not often available and it was up to the wives to handle most medical emergencies to the best of their abilities. Thus it would just seem natural that the women would pass around their favorite recipes for cooking, as well as treating illnesses that may occurred. The young people were not left out of festivities to make life more enjoyable. They were always ready for a candy-pulling, or to be at a "stirring-off" when sorghum was made. These often ended with the evening spent dancing to the music of a fiddle played by the neighborhood Negro fiddler. The French were to become quite well represented on the Cumberland River. Quite a few Frenchmen who had settled on the Rappahanock and elsewhere in the Virginia Tidewater area came to be found on the Cumberland. Settlers such as Hatcher, Dibrell, Le Grand, and Maury were among these. With the long memories of the Indians to gain a foothold in the area of Kentucky, they began to stir up trouble again for the settlers. On December 20, 1799, which was one month after the organization of the companies of Patrollers, Governor James Garrard organized a new regiment of Kentucky militia, the 44th embracing the County of Pulaski. Jesse Richardson was Lieutenant Colonel with Charles Dibrell and Tom Fox as Majors of the 1st and 2nd Battalions. The Militia fought the Indians again at the Battle of Blue Licks and the central part of Kentucky became safe once again from Indian attack. It is a bit confusing to put Charles and his family into just one county. In county histories events occur in various counties so it is really difficult to determine for sure when Charles moved down to build his home on the banks of the Cumberland River. In the First Federal Census for Kentucky in 1799 and again in the Second Federal Census for Kentucky 1800, Charles is listed in Cumberland County, Kentucky. It was not until 1799 that Virginia and then Kentucky permitted counties to be created on the Cumberland River. When they moved to Pulaski County is not proven. But they were there when Wayne County was formed as Charles was one of the Justices who helped form the new county which was taken from part of Pulaski County. Commerce was provided by the river. Business went down the river and even East Tennessee was easily reached by the Great Lakes Indian trail so few bothered to go to the Blue Grass in Kentucky to record a deed or stock mark. From 1807 to 1812 the years were not easy for pioneer farmers in the valleys of the Ohio, Cumberland and Tennessee. Markets were so few and prices so low that the grower of hemp or tobacco or even corn could not secure enough cash to import necessary commodities or to meet payments on land which he had bought a few years earlier. During this period patriotic sentiments were sedulously preached in Fourth of July orations, political sermons, and magazine articles. The recurrent theme made clear that Americans were a chosen people, established in a divinely selected habitat for an experiment unique in the annals of human freedom. In 1800 Kentucky, Virginia, and North Carolina were the only states where neither rule of court nor legislature act fixed definite periods for legal training of lawyers. While no uniformity existed, the court regulations usually called for a clerkship of from three to seven years with appropriate credit for courses completed in college. Most young men "reading law" spent time copying papers, looking up cases, preparing abstracts and briefs and learning legal procedure by haunting the county courts. As mentioned previously Charles was appointed one of the first Justices in Wayne County by Governor James Garrard. This occurred on December 20, 1800. Charles was on the court that formed the county of Wayne from Pulaski County. Monticello became the County Seat. At this time there was a lot of county rearranging going on in which some land would be taken from various counties and boundaries were changed. The shape of Wayne County was also changed as this went on. As a result some people may have appeared to have moved when it was rather the counties that had moved. It seems likely that sometime after 1794 and before 1801 Martha Burton Dibrell passed away leaving Charles with eight children. Some of them were still young. On March 16, 1801 Micah Taul wrote in his "Memoirs" that all of the Justices attended Court with the exception of Charles Dibrell who was absent in Virginia. It is possible that he was visiting his brother, Anthony, in Virginia, and that he either knew or made the acquaintance of Miss Patterson at this time. This seems to be the time when he married his second wife. It is possible that her first name was Lucy as this name appears on a deed with Charles in 1818 and none of the children had this name. From this marriage Charles would have four children who would all be born in Tennessee most likely in White County, where his second boy, Anthony, would reside and work as a lawyer while raising his family. However, prior to this Charles received land in both 1800 and 1810 under the Headright Provision. In the 1801 Wayne County Tax List Charles Dibrell is shown as owning 400 acres. It is not known whether all or part of this fell under the Headright Provision. [On 13 Dec 1802, Charles Debrel was appointed Colonel in charge of the Wayne County Regiment (the 53rd Regiment) of the Kentucky Militia. This was known as the "Cornstalk Militia" because those who did not have guns practiced with cornstalks. Also in the Regiment were Isaac Chrisman (Major, 1st Battalion), Isaac Meadows (Captain), William Mullins (Captain) and Micajah Taul (Adjutant). [G. Glen Clift, "The Corn Stalk Militia of Kentucky 1792 - 1811" (1957), pp. 152-153] This makes him one of the first "Kentucky Colonels".] In 1810 Third Census of Kentucky - Wayne County, Charles has this listing: On July 17, 1815 Charles was a witness for the will of Michael Stoner in open court in Wayne County. In 1820 Federal Census of Kentucky - Wayne County, Charles is listed: About 1822 Charles and his family comprised of two teen-aged boys, plus four small children plus himself and his wife lived in Sparta, Tennessee which was in White County. About this time his son, Anthony, was serving as State Treasurer. A daughter, Leeanna, lived there also with her husband George W. Gibbs. At sometime while he lived in Tennessee Charles became friends with Andrew Jackson who was quite a powerful force in the state. He also became acquainted with the young Sam Houston. Evidently Charles had retained his interest in politics. It has been said that this friendship was instrumental in preventing a duel between Andrew Jackson and George W. Gibbs, Charles' son-in-law, who apparently had different political beliefs and did not agree with Jackson and called him a name which was not appreciated. No doubt it was this friendship that enabled Charles and his wife to attend the festivities when the Marquis Lafayette arrived in Nashville while on his Grand Tour in 1824. Andrew Jackson had issued the invitation which included a state dinner where the Marquis presented the ladies with French silk shawls. This brown shawl has been passed down through the family through the years and in 1965 was presented to the State Archives in Tennessee in Nashville by Mrs. William Freeman. In July Charles was visiting his daughter Leeanna and her husband George in Union City, Tennessee where they then lived. He became ill and died on July 16, 1840. He was buried in the cemetery there and his grave has been marked by the local Daughters of the American Revolution. His ensign, John Mope, who served with him in the war has been buried nearby. It is not known when the second wife of Charles died, but must assume that it was in Tennessee as it appears that their four children remained there. Source Documents Charles Dibrell, (1757-1840), served as a minute man, as ensign of the convention guards and was under Lafayette at Yorktown. He was born in Va.; died in Union City, Tenn. [The National Society of the Daughters of the American Revolution, Volume 44 page 283] DIBRELL, Charles, or Charles Dibrill or Debrill, S21160, VA Line, sol was b 24 Oct 1757 in Buckingham Cty VA & lived there at enl & about 1782 he moved to KY & in 1790 was living in Madison Cty KY & about 1822 moved to White Cty TN & sold appl there 6 Sep 1832, in 1832 an Anthony Dibrell was Clerk of the Circuit Court of White Cty TN but no relationship was stated, sol d 16 Jul 1840. [Abstracts of Rev. War Pensions, p. 967]. DIBRELL, Charles, b. 1757, Va.; d. 1840, Union City, Tenn.; served in Rev. War; m. Martha Burton. DAR No. 65 722; DAR No. 75 709. [Dorothy Fork Wulfeck, Marriages of Some Virginia Residents (Genealogical Publishing Co., 1986), Vol. 1] LAND GRANTS AND DEEDS- Wayne County, Kentucky Deed Book, Vol. 21, 06 Nov 1803. 250 Acres to Charles Dibrell south of Green River. Page 231. 250 Acres to Charles Dibrell south of Green River. Page 231. Deed Book, Vol. A. p. 107. 30 Sep 1804. * * * 1 Sept 1810 Mashack Gregory, Drum Major for Col. Charles Dibrell, Col. of Wayne Co. 53rd Reg. - paid $12 for his services. [The Kentucky Genealogist, Vol. 17 #3 Jul-Sep 1975, p. 106].
http://home.southwind.net/~crowther/Dibrell/CLD.html
crawl-002
refinedweb
4,825
70.33
Here is what I am trying to do case class MessageModel (time: Long, content: String) {} val message = MessageModel(123, "Hello World") def jsonParser[A] (obj: A) : String = obj.asJson.noSpaces println jsonParser[MessageModel](message) Encoding and decoding in circe are provided by type classes, which means that you have to be able to prove at compile time that you have a type class instance for A if you want to encode (or decode) a value of type A. This means that when you write something like this: import io.circe.syntax._ def jsonPrinter[A](obj: A): String = obj.asJson.noSpaces You're not providing enough information about A for circe to be able to print values of that type. You can fix this with a context bound: import io.circe.Encoder import io.circe.syntax._ def jsonPrinter[A: Encoder](obj: A): String = obj.asJson.noSpaces Which is Scala's syntactic sugar for something like this: def jsonPrinter[A](obj: A)(implicit encoder: Encoder[A]): String = obj.asJson.noSpaces Both of these will compile, and you can pass them a value of any type that has an implicit Encoder instance. For your MessageModel specifically, you could use circe's generic derivation, since it's a case class: scala> import io.circe.generic.auto._ import io.circe.generic.auto._ scala> case class MessageModel(time: Long, content: String) defined class MessageModel scala> val message = MessageModel(123, "Hello World") message: MessageModel = MessageModel(123,Hello World) scala> jsonPrinter(message) res0: String = {"time":123,"content":"Hello World"} Note that this wouldn't work without the auto import, which is providing Encoder instances for any case class (or sealed trait hierarchy) whose members are all also encodeable.
https://codedump.io/share/RGe21ZHHbtdL/1/how-does-circe-parse-a-generic-type-object-to-json
CC-MAIN-2016-50
refinedweb
284
53.1
The Map Viewer app is an interactive tool for browsing map data. With it you can: Assemble layers of vector and raster geodata and render them in 2-D Import, reorder, symbolize, hide, and delete data layers Identify coordinate locations List data attributes Display selected data attributes as data tips (signposts that identify attribute values, such as place names or route numbers) The following example illustrates these capabilities. Open the Map Viewer app. On the Apps tab, in the Image Processing and Computer Vision section, click Map Viewer . You can also start the Map Viewer using the mapview command. The Map Viewer opens with a blank canvas. (No data is present.) Note that The Map Viewer is designed primarily for working with data sets that refer to a projected map coordinate system (as opposed to a geographic, latitude-longitude system), so the coordinate axes are named X and Y. Import map data. In the Map Viewer, select the File menu and then choose Import From File. Navigate to the folder, where matlabroot\toolbox\map\mapdata matlabroot represents your MATLAB® installation folder, and open the GeoTIFF file boston.tif. The file opens in the Map Viewer. The image is a visible red, green, and blue composite from a georeferenced IKONOS-2 panchromatic/multispectral product created by GeoEye™. Copyright © GeoEye, all rights reserved. For further information about the image, refer to the text files boston.txt and boston_metadata.txt. To open boston.txt, type the following at the command line: open 'boston.txt' Set the map scale in the Map Viewer. To do this, you must first set the map distance units. Click the Map units menu at the bottom center and select US Survey Feet. Set the map scale. Type 1:25000 in the Scale box, which is above the Map units menu, and press Enter. The Map Viewer now looks like this. Get the map coordinates for a location on the map, interactively. Place the cursor over a location on the map. The example puts the cursor over the bridge that goes over the pond in Boston Garden. The map coordinates for this location are shown at the lower left as 772,423.18 feet easting (X), 2,954,372.40 feet northing (Y), in Massachusetts State Plane coordinates. Import a vector data layer. For this example, import a line shapefile that contains data about the streets and highways in the central Boston area. boston_roads = shaperead('boston_roads.shp'); The shaperead function returns the data as a geographic data structure. Convert the X and Y coordinate fields of boston_roads.shp from meters to U.S. survey feet. As is frequently the case when overlaying geodata, the coordinate system used by boston_roads.shp (in units of meters) does not completely agree with the one for the satellite image, boston.tif (in units of feet). If you were to ignore this, the two data sets would be out of registration by a large distance. surveyFeetPerMeter = unitsratio('survey feet','meter'); for k = 1:numel(boston_roads) boston_roads(k).X = surveyFeetPerMeter * boston_roads(k).X; boston_roads(k).Y = surveyFeetPerMeter * boston_roads(k).Y; end unitsratiofunction computes conversion factors between a variety of units of length. In the Map Viewer File menu, select Import From Workspace > Vector Data > Geographic Data Structure. In the Import Vector Data dialog box, select the variable boston_roads as the data to import from the workspace, and click OK. You could clear the workspace now if you wanted, because all the data that the Map Viewer needs is now loaded into it. After the Map Viewer finishes importing the roads layer, it selects a random color and renders all the shapes with that color as solid lines. The view looks like this. Being random, the color you see for the road layer may differ. Explore the attributes of the vector layer. First, make the vector layer the active layer using the Active layer menu at the bottom right. Select boston_roads. You can designate any layer to be the active layer; it does not need to be the topmost layer. By default, the first layer imported is active. Changing the active layer has no visual effect on the map. Doing so allows you to query attributes of the layer you select. For example, once you make the vector layer the active layer, the Info tool button near the right end of the toolbar becomes enabled. Select the Info tool, the cursor changes to a cross-hairs shape. Click any location on the map to view attributes of the selected object. The selected road is Massachusetts Avenue (Route 2A). As the above figure shows, the boston_roads vectors have six attributes, including an implicit INDEX attribute added by the Map Viewer. Use this tool to explore other roads. Dismiss open Info windows by clicking their close boxes. Use a data tip to annotate the map with other attribute values. From the Layers menu, select boston_roads > Set Label Attribute. From the list in the Attribute Names dialog, select CLASS and click OK. From the Tools menu, select the Datatip tool. A dialog box appears to remind you how to change attributes. Click OK to dismiss the box. The cursor assumes a cross-hairs ( +) shape. Click on a road segment in the map and the data tip tool puts a small marker on the road that contains a numeric identifier that indicates the administrative class. The class of the road crossing the Charles river we explored earlier is of class 3. You can change how the roads are rendered by identifying an attribute to which to key line symbology. Color roads according to their CLASS attribute, which takes on the values 1:6. Do this by creating a symbolspec in the workspace. A symbolspec is a cell array that associates attribute names and values to graphic properties for a specified geometric class ( 'Point', 'MultiPoint', 'Line', 'Polygon', or 'Patch'). To create a symbolspec for line objects (in this case roads) that have a CLASS attribute, type: roadcolors = makesymbolspec('Line', ... {'CLASS',1,'Color',[1 1 1]}, {'CLASS',2,'Color',[1 1 0]}, ... {'CLASS',3,'Color',[0 1 0]}, {'CLASS',4,'Color',[0 1 1]}, ... {'CLASS',5,'Color',[1 0 1]}, {'CLASS',6,'Color',[0 0 1]}) The following output appears: roadcolors = ShapeType: 'Line' Color: {6x3 cell} The Map Viewer recognizes and imports symbolspecs from the workspace. To apply the one you just created, from the Layers menu, select boston_roads > Set Symbol Spec. From the Layer Symbols dialog, select the roadcolors symbolspec you just created and click OK. After the Map Viewer has read and applied the symbolspec, the map looks like this. Remove the data tips before going on. To dismiss data tips, right-click one of them and select Delete all data tips from the menu that appears. Add another layer, a set of points that identifies 13 Boston landmarks. As you did with the boston_roads layer, import it from a shapefile: boston_placenames = shaperead('boston_placenames.shp'); Convert the coordinates of these landmarks to units of survey feet before importing them into Map Viewer. The locations for these landmarks are given in meters. surveyFeetPerMeter = unitsratio('survey feet','meter'); for k = 1:numel(boston_placenames) boston_placenames(k).X = ... surveyFeetPerMeter * boston_placenames(k).X; boston_placenames(k).Y = ... surveyFeetPerMeter * boston_placenames(k).Y; end From the File menu, select Import From Workspace > Vector Data > Geographic Data Structure. Choose boston_placenames as the data to import from the workspace and click OK. The boston_placenames markers are symbolized as small x markers, but these markers do not show up over the orthophoto. To solve this problem, create a symbolspec for the markers to represent them as red filled circles. At the MATLAB command line, type: places = makesymbolspec('Point',{'Default','Marker','o', ... 'MarkerEdgeColor','r','MarkerFaceColor','r'}) The Default keyword causes the specified symbol to be applied to all point objects in a given layer unless specifically overridden by an attribute-coded symbol in the same or a different symbolspec. To activate this symbolspec, pull down the Layers menu, select boston_placenames, slide right, and select Set Symbol Spec. In the Layer Symbols dialog that appears, highlight places and click OK. The Map Viewer reads the workspace variable places; the cross marks turn into red circles. Note that a layer need not be active in order for you to apply a symbolspec to it. To see the name of a Boston place name, make boston_placenames the currently active layer (using the Active layer menu, and then select Datatip from the Tools menu. The cursor changes to a cross-hair shape. Click any red circle and the tool places a data tip annotation on the map with the name of the location. Zoom in on Beacon Hill for a closer view of the Massachusetts State House and Boston Common. Select the Zoom in tool; move the (magnifier) cursor until the X readout is approximately 774,011 and the Y readout is roughly 2,955,615; and click once to enlarge the view. The scale changes to about 1:12,500 and the map appears as below. From the Tools menu, choose Select Annotations to change from the Datatip tool back to the original cursor. Right-click any of the data tips and select Delete all datatips from the pop-up context menu. This clears the place names you added to the map. Select an area of interest to save as an image file. Click the Select area tool, and then hold the mouse button down as you draw a selection rectangle. If you do not like the selection, repeat the operation until you are satisfied. If you know what ground coordinates you want, you can use the coordinate readouts to make a precise selection. The selected area appears as a red rectangle. The Select area tool is not supported in MATLAB Online™. To view a particular region on the map, use the Zoom in, Zoom out, and Pan tools instead. In order to be able to save a file in the next step, change your working folder to a writable folder. Save your selection as an image file. From the File menu, select Save As Raster Map > Selected Area to open an Export to File dialog. In the Export to File dialog, navigate to a folder where you want to save the map image, and save the selected area's image as a .tif file, calling it central_boston.tif. (PNG and JPG formats are also available.) A world file, central_boston.tfw, is created along with the TIF. Whenever you save a raster map in this manner, two files are created: An image file ( file .tif, file .png, or file .jpg) An accompanying world file that georeferences the image ( file .tfw, file .pgw, or file .jgw) The following steps show you how to read world files and display a georeferenced image outside of mapview. Read in the saved image and its colormap with the MATLAB function imread, create a referencing matrix for it by reading in central_boston.tfw with worldfileread, and display the map with mapshow: [X cmap] = imread('central_boston.tif'); R = worldfileread('central_boston.tfw'); figure mapshow(X, cmap, R); See the documentation for mapshow for another example of displaying a georeferenced image. Experiment with other tools and menu items. For example, you can annotate the map with lines, arrows, and text; fit the map to the window; draw a bounding box for any layer; and print the current view. You can also spawn a new Map Viewer using New View from the File menu. A new view can duplicate the current view, cover the active layer's extent, cover all layer extents, or include only the selected area, if any. When you are through with a viewing session, close the Map Viewer using the window's close box or select Close from the File menu. For more information about the Map Viewer, see the mapview reference page.
https://fr.mathworks.com/help/map/tour-boston-with-the-map-viewer.html
CC-MAIN-2019-51
refinedweb
1,972
66.13
I’v noticed that dash datatables seems to break when you introduce a condition (that is met) with a filter on a column that has some special characters in the columnname: such as the swedish characters åäö, and characters such as é and ü. say you have the table: |column_ö|column_1| | test | test | and condition the table as: style_cell_conditional=[{‘if’: {‘column_id’: ‘column_ö’, ‘filter’: ‘column_ö’ eq “test”’}, ‘backgroundColor’: ‘pink’}] Then I recieve a “Error loading dependencies” in my webpage, but no error message in the console. Example code: import dash import dash_table import pandas as pd df = pd.read_csv(‘ df.rename(columns={‘State’: ‘column_ö’}, inplace=True) app = dash.Dash(name) app.layout = dash_table.DataTable( id=‘table’, columns=[{“name”: i, “id”: i} for i in df.columns], data=df.to_dict(“rows”), style_cell_conditional=[{‘if’: {‘column_id’: ‘column_ö’, ‘filter’: ‘column_ö eq “California”’}, ‘backgroundColor’: ‘pink’}] ) if name == ‘main’: app.run_server(debug=True) Would appreciate if anyone have any suggestions on how to solve it, or can point out any misstake am doing:)
https://community.plotly.com/t/dash-datatable-issue-with-special-characters-in-conditions-filter-expression/21972
CC-MAIN-2022-21
refinedweb
166
50.57
Rock Paper Scissors Solution Google Kickstart 2021 Problem You and your friend like to play Rock Paper Scissors. Each day you play exactly 6060 rounds and at the end of each day, you tally up the score from these 6060 rounds. During each round, without any knowledge of the other person’s choice, you each make your choice. Then, you both reveal the choice you made and determine your score. Rock wins over Scissors, Scissors wins over Paper, and Paper wins over Rock. Let R represent Rock, P represent Paper, and S represent Scissors. Every day you both agree on values WW and EE. If your choice wins, you get WW points. If you and your friend both pick the same choice, you get EE points. If your choice loses, you get nothing. By accident, you see your friend’s strategy written in an open notebook on a desk one day. Your friend keeps track of how many times you have chosen R, P, and S so far during one day. Let AiAi be your choice of R, P, or S on round ii, while BiBi is your friend’s choice on the same round. Let riri be the number of times Aj=Aj= R for 1≤j≤(i−1)1≤j≤(i−1). Similarly, let pipi and sisi be the total number of times you have chosen P and S, respectively, prior to round ii. On round 11 of each day, i=1i=1 and r1=s1=p1=0r1=s1=p1=0, and your friend plays randomly due to the lack of information (i.e. your friend chooses each option with probablity 1/31/3). On every subsequent round, your friend decides BiBi by choosing R with probability Pr[Pr[ R]=si/(i−1)]=si/(i−1), P with probability Pr[Pr[ P]=ri/(i−1)]=ri/(i−1), and S with probability Pr[Pr[ S]=pi/(i−1)]=pi/(i−1). This strategy is adaptive and tough to beat! You are going on vacation for the next TT days. You must leave your assistant with instructions on what choice to pick each round each day. Let integer XX be the average reward you are aiming for in this game after TT days. Given WW and EE (different values for different days), provide your instructions as a string of 6060 characters, ordered from round 11 to round 6060. Each character represents your choice for the corresponding round. Your goal is to choose your set of instructions so that the average expected value of the reward across all the days of your gameplay is at least XX. Note that you can choose different instructions for different values of WW and EE. Input The first line of the input gives the number of days, TT. The second line contains an integer XX, your targeted average reward after these TT days. Then the description of TT days follows. Each day is described as two integers WW and EE. WW is how much you get if your choice wins for each round that day. EE is how much you get for each round when your choice is the same as your friend’s choice. All the tests (except the sample test below) are generated as follows. We choose 5050 different values GG between 55 and 9595 (with uniform distribution). Then for each of these values, there will be 44 days, with WW equal to 10×G10×G and EE equal to W,W2,W10W,W2,W10, and 00. Do not assume anything about the order of these days. Output For each day, output one line containing Case #xx: A1A2…A60A1A2…A60, where xx is the day number (starting from 1) and AiAi is your choice of R, P, or S on the ii-th round of the game. There should be no spaces between the choices. The list of choices should result in an expected value that is greater than or equal to XX on average after TT days. There may be multiple solutions for a test case. If so, you may output any one of them. It is guaranteed that for given XX a solution exists. Limits Time limit: 40 seconds. Memory limit: 1 GB. T=200T=200 (for all tests except the sample where T=2T=2). 50≤W≤95050≤W≤950. 0≤E≤W0≤E≤W and EE is one of W,W2,W10W,W2,W10, or 00. Each day you play exactly 60 rounds. Test Set 1 X=14600X=14600. Test Set 2 X=15500X=15500. Test Set 3 X=16400X=16400. Sample Sample Input 2 30 60 0 60 60 Sample Output Case #1: RSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR Case #2: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP In this sample test our targeted (average) reward across all T=2T=2 days is 3030. For the first day, since W=60W=60, you can reach the total target by winning at least once. One possible strategy is to just get to that single win. - On round 11, you choose A1=A1= R. You have an equal chance of a win, a tie, or a loss, giving you an expected value of 2020. - On round 22, r2=1r2=1 and p2=s2=0p2=s2=0. Your friend’s probability of choosing Pis Pr[Pr[ P]=r2/1=1]=r2/1=1, which guarantees your friend’s choice B2=B2= P. - If you choose A2=A2= S, you are guaranteed a win, giving you a score of 6060 for round 22. - Regardless of what you choose for all following rounds in the game, your expected value after just two rounds is 20+60=8020+60=80, which is enough to reach our target. Moreover, as we already will have the average across all 2 days at least 802=40≥X=30802=40≥X=30, for the second day we can use any strategy. Note that this is not a unique solution. As long as the average expected score is ≥30≥30, other outputs would also be accepted. Also Read: - Binary Operator Solution Google Kickstart 2021 - Alien Generator Solution Google Kickstart 2021 - Smaller Strings Solution Google Kickstart 2021 Solution: #include<vector> #include<set> #include<map> #include<queue> #include<string> #include<algorithm> #include<iostream> #include<bitset> #include<functional> #include<numeric> #include<cstdio> #include<cstring> #include<cstdlib> #include<cassert> #include<cmath> #include<iomanip> #include<random> #include<ctime> #include<complex> using namespace std; typedef long long LL; typedef double D; #define all(v) (v).begin(), (v).end() mt19937 gene(233); typedef complex<double> Complex; #define fi first #define se second #define ins insert #define pb push_back inline char GET_CHAR(){ const int maxn = 131072; static char buf[maxn],*p1=buf,*p2=buf; return p1==p2&&(p2=(p1=buf)+fread(buf,1,maxn,stdin),p1==p2)?EOF:*p1++; } inline int getInt() { int res(0); char c = getchar(); while(c < '0') c = getchar(); while(c >= '0') { res = res * 10 + (c - '0'); c = getchar(); } return res; } inline LL fastpo(LL x, LL n, LL mod) { LL res(1); while(n) { if(n & 1) { res = res * (LL)x % mod; } x = x * (LL) x % mod; n /= 2; } return res; } LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } inline string itoa(int x, int width = 0) { string res; if(x == 0) res.push_back('0'); while(x) { res.push_back('0' + x % 10); x /= 10; } while((int)res.size() < width) res.push_back('0'); reverse(res.begin(), res.end()); return res; } const int _B = 131072; char buf[_B]; int _bl = 0; inline void flush() { fwrite(buf, 1, _bl, stdout); _bl = 0; } __inline void _putchar(char c) { if(_bl == _B) flush(); buf[_bl++] = c; } inline void print(LL x, char c) { static char tmp[20]; int l = 0; if(!x) tmp[l++] = '0'; else { while(x) { tmp[l++] = x % 10 + '0'; x /= 10; } } for(int i = l - 1; i >= 0; i--) _putchar(tmp[i]); _putchar(c); } struct P { D x, y; }; int w, e; const int N = 300033; const int LOG = 20; const int mod = 1e9 + 7; const int inf = 1e9 + 7; int n, m; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; D dp[63][63][63]; int u[63][63][63]; int main() { int t, x; scanf("%d%d", &t, &x); D sum = 0; for(int qq = 1; qq <= t; qq++) { scanf("%d%d", &w, &e); /*w = v[(qq - 1) / 4] * 10; sv += w / 10; cout << (qq - 1) / 4 << endl; e = qq % 4 == 1 ? w : qq % 4 == 2 ? w/ 2 : qq % 4 == 3 ? w / 10 : 0;*/ int c[3]; for(int sum = 60; sum >= 0; sum--) { for(c[0] = 0; c[0] <= sum; c[0]++) { for(c[1] = 0; c[0] + c[1] <= sum; c[1]++) { c[2] = sum - c[0] - c[1]; if(sum == 60) { dp[c[0]][c[1]][c[2]] = 0; continue; } if(sum == 0) { dp[0][0][0] = dp[1][0][0] + w / 3. + e / 3.; u[0][0][0] = 0; continue; } D mx = -1; int mxd = -1; for(int d = 0; d < 3; d++) { D tmp = 0; for(int f = 0; f < 3; f++) { if((d + 1) % 3 == f) { tmp += (c[(f + 1) % 3]) / (D)sum * w; }else if(d == f) { tmp += (c[(f + 1) % 3]) / (D)sum * e; } } int nwc[3]; memcpy(nwc, c, sizeof(c)); nwc[d]++; tmp += dp[nwc[0]][nwc[1]][nwc[2]]; if(tmp > mx) { mx = tmp; mxd = d; } } dp[c[0]][c[1]][c[2]] = mx; u[c[0]][c[1]][c[2]] = mxd; } } } memset(c, 0, sizeof(c)); printf("Case #%d: ", qq); for(int i = 1; i <= 60; i++) { printf("%c", u[c[0]][c[1]][c[2]] == 0 ? 'R' : u[c[0]][c[1]][c[2]] == 1 ? 'S' : 'P'); c[u[c[0]][c[1]][c[2]]]++; } sum += dp[0][0][0]; printf("\n"); } /*printf("%f\n", sum / 200.); printf("%f\n", sv / 200.); printf("%f\n", sum / 200 / (sv / 200) * 50);*/ } Rock Paper Scissors Solution Google Kickstart 2021
https://www.techinfodiaries.com/rock-paper-scissors-solution/
CC-MAIN-2022-27
refinedweb
1,650
79.5
This class encapsulates a general timestep solver concept to solve linear PDE in time and space. More... #include <timestepping.hh> This class encapsulates a general timestep solver concept to solve linear PDE in time and space. Any linear partial differential equation of the form where Dn, ..., D0 are space operators that not depend on time. After the discretisation it can always be brought in the form where the LHS depends only on the timestep size and the RHS can be evalated from previous steps. Therefore the new solution Yn is best obtained with an LU separation of the LHS. Definition at line 39 of file timestepping.hh. Constructor. Returns information in an output stream. Reimplemented from concepts::OutputOperator. Returns the solution of the n'th timestep. With the parameter n the actual solution is return, otherwise the specified step in the futur. A step number n before the actual step number is not possible and throws an exception Return the time of the current solution. The number of the timestep of the actual solution. Definition at line 60 of file timestepping.hh. Timestep strategy of the solver. Definition at line 62 of file timestepping.hh.
http://www.math.ethz.ch/~concepts/doxygen/html/classtimestepping_1_1TimeStepping.html
crawl-003
refinedweb
195
59.5
How to create your first app for Windows Phone 8 [ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ] This topic provides step-by-step instructions to help you create your first app for Windows Phone. You’re going to create a basic web browser. This simple app lets the user enter a URL, and then loads the web page when the user clicks the Go button. You can download the complete Mini-browser Sample in C# or in Visual Basic.NET. This topic contains the following sections. This walkthrough assumes that you’re going to test your app in the emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see How to register your phone for development for Windows Phone 8. The steps in this topic assume that you’re using Visual Studio Express 2012 for Windows Phone. You may see some variations in window layouts or menu commands if you’re using Visual Studio 2012 Professional or higher, or if you’ve already customized the layout or menus in Visual Studio. The first step in creating a Windows Phone app is to create a new project in Visual Studio. To create the project Make sure you’ve. In the New Project window, expand the installed Visual C# or Visual Basic templates, and then select the Windows Phone templates. In the list of Windows Phone templates, select the Windows Phone App template. At the bottom of the New Project window, type MiniBrowser as the project’s Name. Click OK. In the New Windows Phone Application dialog box, select Windows Phone OS 8.0 for the Target Windows Phone OS Version. When you select Windows Phone OS 8.0 as the target version, your app can only run on Windows Phone 8 devices. When you select Windows Phone OS 7.1, your app can run on both Windows Phone OS 7.1 and Windows Phone 8 devices. Click OK. The new project is created, and opens in Visual Studio. The designer displays MainPage.xaml, which contains the user interface for your app. The main Visual Studio window contains the following items: The middle pane contains the XAML markup that defines the user interface for the page. The left pane contains a skin that shows the output of the XAML markup. The right pane includes Solution Explorer, which lists the files in the project. The associated code-behind page, MainPage.xaml.cs or MainPage.xaml.vb, which contains the code to handle user interaction with the page, is not opened or displayed by default. The next step is to lay out the controls that make up the UI of the app using the Visual Studio designer. After you add the controls, the final layout will look similar to the following screenshot. To create the UI Open the Properties window in Visual Studio, if it’s not already open, by selecting the VIEW | Properties Window menu command. The Properties window opens in the lower right corner of the Visual Studio window. Change the app title. In the Visual Studio designer, click to select the MY APPLICATION TextBlock control. The properties of the control are displayed in the Properties window. In the Text property, change the name to MY FIRST APPLICATION to rename the app window title. If the properties are grouped by category in the Properties window, you can find Text in the Common category. Change the name of the page. Change the supported orientations. In the XAML code window, click the first line of the XAML code. The properties of the PhoneApplicationPage are displayed in the Properties window. Change the SupportedOrientations property to PortraitOrLandscape to add support for both portrait and landscape orientations. If the properties are grouped by category in the Properties window, you can find SupportedOrientations in the Common category. Open the Toolbox in Visual Studio, if it’s not already open, by selecting the VIEW | Toolbox menu command. The Toolbox typically opens on the left side of the Visual Studio window and displays the list of available controls for building the user interface. By default the Toolbox is collapsed when you’re not using it. Add a textbox for the URL. From the Common Windows Phone Controls group in the Toolbox, add a TextBox control to the designer surface by dragging it from the Toolbox and dropping it onto the designer surface. Place the TextBox just below the Mini Browser text. Use the mouse to size the control to the approximate width shown in the layout image above. Leave room on the right for the Go button. In the Properties window, set the following properties for the new text box. With these settings, the control can size and position itself correctly in both portrait and landscape modes. Add the Go button. Resize the text box to make room for the Go button. Then, from the Common Windows Phone Controls group in the Toolbox, add a Button control by dragging and dropping it. Place it to the right of the text box you just added. Size the button to the approximate width shown in the preceding image. In the Properties window, set the following properties for the new button. With these settings, the control can size and position itself correctly in both portrait and landscape modes. Add the WebBrowser control. From the All Windows Phone Controls group in the Toolbox, add a WebBrowser control to your app by dragging and dropping it. Place it below the two controls you added in the previous steps. Use your mouse to size the control to fill the remaining space. If you want to learn more about the WebBrowser control, see WebBrowser control for Windows Phone 8. In the Properties window, set the following properties for the new WebBrowser control. With these settings, the control can size and position itself correctly in both Portrait and Landscape modes. Your layout is now complete. In the XAML code in MainPage.xaml, look for the grid that contains your controls. It will look similar to the following. If you want the layout exactly as shown in the preceding illustration, copy the following XAML and paste it to replace the grid layout in your MainPage.xaml file. <!--ContentPanel - place additional content here--> <Grid x: <TextBox x: <Button x: <phone:WebBrowser x: </Grid> The final step before testing your app is to add the code that implements the Go button. To add the code In the designer, double-click the Go button control that you added to create an empty event handler for the button’s Click event. You will see the empty event handler in a page of C# code on the MainPage.xaml.cs tab, or in a page of Visual Basic code on the MainPage.xaml.vb tab. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using MiniBrowser.Resources; namespace MiniBrowser { public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); } private void Go_Click(object sender, RoutedEventArgs e) { } } } When you double-click the Go button, Visual Studio also updates the XAML in MainPage.xaml to connect the button’s Click event to the Go_Click event handler. In MainPage.xaml.cs or MainPage.xaml.vb, add the highlighted lines of code to the empty Go_Click event handler. This code takes the URL that the user enters in the text box and navigates to that URL in the MiniBrowser control. Now you’ve finished your first Windows Phone app! Next you’ll build, run, and debug the app. Before you test the app, make sure that your computer has Internet access to be able to test the Web browser control. To run your app in the emulator 512MB. Run the app by pressing F5 or by selecting the DEBUG | Start Debugging menu command. This opens the emulator window and launches the app. If this is the first time you’re starting the emulator, it might take a few seconds for it to start and launch your app. The Windows Phone 8 Emulator has special hardware, software, and configuration requirements. If you have any problems with the emulator, see the following topics. To test your running app, click the Go button and verify that the browser goes to the specified web site. To test the app in landscape mode, press one of the rotation controls on the emulator toolbar. Or The emulator rotates to landscape mode. The controls resize themselves to fit the landscape screen format. To stop debugging, you can select the DEBUG | Stop Debugging menu command in Visual Studio. It’s better to leave the emulator running when you end a debugging session. The next time you run your app, the app starts more quickly because the emulator is already running. Congratulations! You’ve now successfully completed your first Windows Phone app.
https://msdn.microsoft.com/en-us/library/ff402526(v=vs.105).aspx
CC-MAIN-2016-50
refinedweb
1,500
66.94
{- the 'Coroutine' monad transformer. -- -- A 'Coroutine' monadic computation can 'suspend' its execution at any time, returning control to its invoker. The -- returned coroutine suspension is a 'Functor' containing the resumption of the coroutine. Here is an example of a -- coroutine in the 'IO' monad that suspends computation using the functor 'Yield' from the -- "Control.Monad.Coroutine.SuspensionFunctors" module: -- -- @ -- producer :: Coroutine (Yield Int) IO String -- producer = do yield 1 -- lift (putStrLn \"Produced one, next is four.\") -- yield 4 -- return \"Finished\" -- @ -- -- To continue the execution of a suspended 'Coroutine', apply its 'resume' method. The easiest way to run a coroutine -- to completion is by using the 'pogoStick' function, which keeps resuming the coroutine in trampolined style until it -- completes. Here is an example of 'pogoStick' applied to the /producer/ example above: -- -- @ -- printProduce :: Show x => Coroutine (Yield x) IO r -> IO r -- printProduce producer = pogoStick (\\(Yield x cont) -> lift (print x) >> cont) producer -- @ -- -- Multiple concurrent coroutines can be run as well, and this module provides two different ways. Functions 'seesaw' -- and 'seesawSteps' can be used to run two interleaved computations. Another possible way is to use the functions -- 'couple' or 'merge' to weave together steps of different coroutines into a single coroutine, which can then be -- executed by 'pogoStick'. -- -- For other uses of trampoline-style coroutines, see -- -- > Trampolined Style - Ganz, S. E. Friedman, D. P. Wand, M, ACM SIGPLAN NOTICES, 1999, VOL 34; NUMBER 9, pages 18-27 -- -- and -- -- > The Essence of Multitasking - William L. Harrison, Proceedings of the 11th International Conference on Algebraic -- > Methodology and Software Technology, volume 4019 of Lecture Notes in Computer Science, 2006 {-# LANGUAGE ScopedTypeVariables, Rank2Types, EmptyDataDecls #-} module Control.Monad.Coroutine ( -- * Coroutine definition Coroutine(Coroutine, resume), CoroutineStepResult, suspend, -- * Coroutine operations mapMonad, mapSuspension, -- * Running Coroutine computations Naught, runCoroutine, bounce, pogoStick, foldRun, seesaw, SeesawResolver(..), seesawSteps, -- * Coupled Coroutine computations PairBinder, sequentialBinder, parallelBinder, liftBinder, SomeFunctor(..), composePair, couple, merge ) where import Control.Monad (liftM) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Class (MonadTrans(..)) import Data.Either (partitionEithers) import Data.Functor.Compose (Compose(..)) import Control.Monad.Parallel -- | Suspending, resumable monadic computations. newtype Coroutine s m r = Coroutine { -- | Run the next step of a `Coroutine` computation. The result of the step execution will be either a suspension or -- the final coroutine result. resume :: m (Either (s (Coroutine s m r)) r) } type CoroutineStepResult s m r = Either (s (Coroutine s m r)) r instance (Functor s, Monad m) => Monad (Coroutine s m) where return x = Coroutine (return (Right x)) t >>= f = Coroutine (resume t >>= apply f) where apply fc (Right x) = resume (fc x) apply fc (Left s) = return (Left (fmap (>>= fc) s)) t >> f = Coroutine (resume t >>= apply f) where apply fc (Right x) = resume fc apply fc (Left s) = return (Left (fmap (>> fc) s)) instance (Functor s, MonadParallel m) => MonadParallel (Coroutine s m) where bindM2 = liftBinder bindM2 instance Functor s => MonadTrans (Coroutine s) where lift = Coroutine . liftM Right instance (Functor s, MonadIO m) => MonadIO (Coroutine s m) where liftIO = lift . liftIO -- | The 'Naught' functor instance doesn't contain anything and cannot be constructed. Used for building non-suspendable -- coroutines. data Naught x instance Functor Naught where fmap _ _ = undefined -- | Combines two functors into one, applying either or both of them. Used for coupled coroutines. data SomeFunctor l r x = LeftSome (l x) | RightSome (r x) | Both (Compose l r x) instance (Functor l, Functor r) => Functor (SomeFunctor l r) where fmap f (LeftSome l) = LeftSome (fmap f l) fmap f (RightSome r) = RightSome (fmap f r) fmap f (Both lr) = Both (fmap f lr) -- | Combines two values under two functors into a pair of values under a single 'Compose'. composePair :: (Functor a, Functor b) => a x -> b y -> Compose a b (x, y) composePair a b = Compose $ fmap (\x-> fmap ((,) x) b) a -- | Suspend the current 'Coroutine'. suspend :: (Monad m, Functor s) => s (Coroutine s m x) -> Coroutine s m x suspend s = Coroutine (return (Left s)) -- | Change the base monad of a 'Coroutine'. mapMonad :: forall s m m' x. (Functor s, Monad m, Monad m') => (forall y. m y -> m' y) -> Coroutine s m x -> Coroutine s m' x mapMonad f cort = Coroutine {resume= liftM map' (f $ resume cort)} where map' (Right r) = Right r map' (Left s) = Left (fmap (mapMonad f) s) -- | Change the suspension functor of a 'Coroutine'. mapSuspension :: forall s s' m x. (Functor s, Monad m) => (forall y. s y -> s' y) -> Coroutine s m x -> Coroutine s' m x mapSuspension f cort = Coroutine {resume= liftM map' (resume cort)} where map' (Right r) = Right r map' (Left s) = Left (f $ fmap (mapSuspension f) s) -- | Convert a non-suspending 'Coroutine' to the base monad. runCoroutine :: Monad m => Coroutine Naught m x -> m x runCoroutine = pogoStick (error "runCoroutine can run only a non-suspending coroutine!") -- | Runs a single step of a suspendable 'Coroutine', using a function that extracts the coroutine resumption from its -- suspension functor. bounce :: (Monad m, Functor s) => (s (Coroutine s m x) -> Coroutine s m x) -> Coroutine s m x -> Coroutine s m x bounce spring c = lift (resume c) >>= either spring return -- | Runs a suspendable 'Coroutine' to its completion. pogoStick :: Monad m => (s (Coroutine s m x) -> Coroutine s m x) -> Coroutine s m x -> m x pogoStick spring c = resume c >>= either (pogoStick spring . spring) return -- | Runs a suspendable coroutine much like 'pogoStick', but allows the resumption function to thread an arbitrary -- state as well. foldRun :: Monad m => (a -> s (Coroutine s m x) -> (a, Coroutine s m x)) -> a -> Coroutine s m x -> m (a, x) foldRun f a c = resume c >>= \s-> case s of Right result -> return (a, result) Left c' -> uncurry (foldRun f) (f a c') -- | Type of functions that can bind two monadic values together; used to combine two coroutines' step results. type PairBinder m = forall x y r. (x -> y -> m r) -> m x -> m y -> m r -- | A 'PairBinder' that runs the two steps sequentially before combining their results. sequentialBinder :: Monad m => PairBinder m sequentialBinder f mx my = do {x <- mx; y <- my; f x y} -- | A 'PairBinder' that runs the two steps in parallel. parallelBinder :: MonadParallel m => PairBinder m parallelBinder = bindM2 -- | Lifting a 'PairBinder' onto a 'Coroutine' monad transformer. liftBinder :: forall s m. (Functor s, Monad m) => PairBinder m -> PairBinder (Coroutine s m) liftBinder binder f t1 t2 = Coroutine (binder combine (resume t1) (resume t2)) where combine (Right x) (Right y) = resume (f x y) combine (Left s) (Right y) = return $ Left (fmap (flip f y =<<) s) combine (Right x) (Left s) = return $ Left (fmap (f x =<<) s) combine (Left s1) (Left s2) = return $ Left (fmap (liftBinder binder f $ suspend s1) s2) -- | Weaves two coroutines into one. The two coroutines suspend and resume in lockstep. The combined coroutine suspends -- as long as either argument coroutine suspends, and it completes execution when both arguments do. couple :: forall s1 s2 m x y. (Monad m, Functor s1, Functor s2) => PairBinder m -> Coroutine s1 m x -> Coroutine s2 m y -> Coroutine (SomeFunctor s1 s2) m (x, y) couple runPair t1 t2 = Coroutine{resume= runPair proceed (resume t1) (resume t2)} where proceed :: CoroutineStepResult s1 m x -> CoroutineStepResult s2 m y -> m (CoroutineStepResult (SomeFunctor s1 s2) m (x, y)) proceed (Right x) (Right y) = return $ Right (x, y) proceed (Left s1) (Left s2) = return $ Left $ fmap (uncurry (couple runPair)) (Both $ composePair s1 s2) proceed (Right x) (Left s2) = return $ Left $ fmap (couple runPair (return x)) (RightSome s2) proceed (Left s1) (Right y) = return $ Left $ fmap (flip (couple runPair) (return y)) (LeftSome s1) -- | Weaves a list of coroutines with the same suspension functor type into a single coroutine. The coroutines suspend -- and resume in lockstep. merge :: forall s m x. (Monad m, Functor s) => (forall y. [m y] -> m [y]) -> (forall y. [s y] -> s [y]) -> [Coroutine s m x] -> Coroutine s m [x] merge sequence1 sequence2 corts = Coroutine{resume= liftM step $ sequence1 (map resume corts)} where step :: [CoroutineStepResult s m x] -> CoroutineStepResult s m [x] step list = case partitionEithers list of ([], ends) -> Right ends (suspensions, ends) -> Left $ fmap (merge sequence1 sequence2 . (map return ends ++)) $ sequence2 suspensions -- | A simple record containing the resolver functions for all possible coroutine pair suspensions. data SeesawResolver s1 s2 s1' s2' = SeesawResolver { resumeLeft :: forall m t. (Monad m) => s1 (Coroutine s1' m t) -> Coroutine s1' m t, -- ^ resolves the left suspension functor into the resumption it contains resumeRight :: forall m t. (Monad m) => s2 (Coroutine s2' m t) -> Coroutine s2' m t, -- ^ resolves the right suspension into its resumption resumeBoth :: forall m t1 t2 r. (Monad m) => (Coroutine s1' m t1 -> Coroutine s2' m t2 -> r) -- ^ continuation to resume both coroutines -> s1 (Coroutine s1' m t1) -- ^ left suspension -> s2 (Coroutine s2' m t2) -- ^ right suspension -> r -- ^ invoked when both coroutines are suspended, resolves both suspensions or either one } -- | Runs two coroutines concurrently. The first argument is used to run the next step of each coroutine, the next to -- convert the left, right, or both suspensions into the corresponding resumptions. seesaw :: (Monad m, Functor s1, Functor s2) => PairBinder m -> SeesawResolver s1 s2 s1 s2 -> Coroutine s1 m x -> Coroutine s2 m y -> m (x, y) seesaw runPair resolver t1 t2 = seesawSteps runPair proceed t1 t2 where proceed cont (Left s1) (Left s2) = resumeBoth resolver cont s1 s2 proceed _ (Right x) (Left s2) = liftM ((,) x) $ pogoStick (resumeRight resolver) (resumeRight resolver s2) proceed _ (Left s1) (Right y) = liftM (flip (,) y) $ pogoStick (resumeLeft resolver) (resumeLeft resolver s1) proceed _ (Right x) (Right y) = return (x, y) -- | Runs two coroutines concurrently. The first argument is used to run the next step of each coroutine, the next to -- convert their step results into the corresponding resumptions. seesawSteps :: (Monad m, Functor s1, Functor s2) => PairBinder m -> ((Coroutine s1 m x -> Coroutine s2 m y -> m (x, y)) -> CoroutineStepResult s1 m x -> CoroutineStepResult s2 m y -> m (x, y)) -> Coroutine s1 m x -> Coroutine s2 m y -> m (x, y) seesawSteps runPair proceed = seesaw' where seesaw' t1 t2 = runPair (proceed seesaw') (resume t1) (resume t2)
http://hackage.haskell.org/package/monad-coroutine-0.6.1/docs/src/Control-Monad-Coroutine.html
CC-MAIN-2016-50
refinedweb
1,654
54.86
Fri 10 Sep 2010 SqlAlchemy: Connecting to pre-existing databases Posted by Mike under Cross-Platform, Python, SqlAlchemy 1 Comment Accessing databases with Python is a simple process. Python even provides a sqlite database library that’s built into the main distribution (since 2.5). My favorite way to access databases with Python is to use the 3rd party package, SqlAlchemy. SqlAlchemy is an object-relational mapper (ORM), which means that it takes SQL constructs and makes them more like the target language. In this case, you end up using Python syntax to execute SQL rather than straight SQL and you can use the same code to access multiple database backends (if you’re careful). In this article, we’re going to look at how to use SqlAlchemy to connect to pre-existing databases. If my experience is any indication, you’ll probably be spending more time working with databases that you didn’t create than with ones that you did. This article will show you how to connect to them. SqlAlchemy’s autoload SqlAlchemy has two ways to define a databases columns. The first way is the long way, in which you define each and every field along with its type. The easy (or short) way is to use SqlAlchemy’s autoload functionality, which will introspect the table and pull out the field names in a rather magical way. We’ll start off with the autoload method and then show the long way in the next section. Before we begin though, it needs to be noted that there are two methods for configuring SqlAlchemy: a long-hand way and a declarative (or “shorthand” way. We will go over both ways. Let’s start out with the long version and then do it “declaratively”. from sqlalchemy import create_engine, MetaData, Table from sqlalchemy.orm import mapper, sessionmaker class Bookmarks(object): pass #---------------------------------------------------------------------- def loadSession(): """""" dbPath = 'places.sqlite' engine = create_engine('sqlite:///%s' % dbPath, echo=True) metadata = MetaData(engine) moz_bookmarks = Table('moz_bookmarks', metadata, autoload=True) mapper(Bookmarks, moz_bookmarks) Session = sessionmaker(bind=engine) session = Session() return session if __name__ == "__main__": session = loadSession() res = session.query(Bookmarks).all() res[1].title In this snippet, we import a few handy classes and utilities from sqlalchemy that allow us to define such things as an engine (a type of connection/interface to the database), metadata (a table catalog) and a session (a “handle” to the database that allows us to query it). Note that we have a “places.sqlite” file. This database comes from Mozilla Firefox. If you have it installed, go looking for it as it makes an excellent testbed for this sort of thing. On my Windows XP machine, it’s in the following location: “C:\Documents and Settings\Mike\Application Data\Mozilla\Firefox\Profiles\f7csnzvk.default”. Just copy that file into the location that you’ll be using for the scripts in this article. If you try to use it in place and you have Firefox open, you may have issues as your code may interrupt Firefox or vice-versa. In the create_engine call, we set echo to True. This causes SqlAlchemy to send all the SQL it generates to stdout, which is quite handy for debugging purposes. I would recommend setting it to False when you put your code in production. For our purposes, the most interesting line is as follows: moz_bookmarks = Table('moz_bookmarks', metadata, autoload=True) This tells SqlAlchemy to attempt to load the “moz_bookmarks” table automatically. If it’s a proper database with a primary key, this will work great. If the table doesn’t have a primary key, then you can do this to hack it: from sqlalchemy import Column, Integer moz_bookmarks = Table('moz_bookmarks', metadata, Column("id", Integer, primary_key=True), autoload=True) This adds an extra column called “id”. It’s basically monkey-patching the database. I’ve used this method successfully when I have to use poorly designed databases from vendors. SqlAlchemy will automatically increment it too, if the database supports it. The mapper will map the table object to the Bookmarks class. Then we create a session that’s bound to our engine so we can make queries. The res = session.query(Bookmarks).all() basically means SELECT * FROM moz_bookmarks and will return the result as a list of Bookmark objects. Sometimes the bad database will have a field that should obviously be the primary key. If so, you can just use that name instead of “id”. Other times, you can create a unique key by setting the primary key to two columns (i.e. fields). You do that by creating two columns and setting “primary_key” to True on both of them. This is a whole lot better than having to define an entire table if the table has several dozen fields. Let’s move on to the declarative autoload method: from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///places.sqlite', echo=True) Base = declarative_base(engine) ######################################################################## class Bookmarks(Base): """""" __tablename__ = 'moz_bookmarks' __table_args__ = {'autoload':True} #---------------------------------------------------------------------- def loadSession(): """""" metadata = Base.metadata Session = sessionmaker(bind=engine) session = Session() return session if __name__ == "__main__": session = loadSession() res = session.query(Bookmarks).all() print res[1].title The declarative method looks a little different, huh? Let’s try to unpack the new stuff. First off, we have a new import: from sqlalchemy.ext.declarative import declarative_base. We use “declarative_base” to create a class using our engine that we then create the Bookmarks subclass from. To specify the table name, we use the magic method, __tablename__ and to tell it to autoload, we create the __table_args__ dict. Then in the loadSession function, we get the metadata object like this: metadata = Base.metadata. The rest of the code is the same. Declarative syntax usually simplifies the code because it puts it all in one class rather than creating a class and a Table object separately. If you like the declarative style, you might also want to look at Elixir, a SqlAlchemy extension that did declarative before they added this style to the main package. Defining Your Databases Explicitly There are times when you can’t use autoload or you just want to have complete control over the table definition. SqlAlchemy allows you to do this almost as easily. We’ll look at the longhand version first and then look at the declarative style. from sqlalchemy import create_engine, Column, MetaData, Table from sqlalchemy import Integer, String, Text from sqlalchemy.orm import mapper, sessionmaker class Bookmarks(object): pass #---------------------------------------------------------------------- def loadSession(): """""" dbPath = 'places.sqlite' engine = create_engine('sqlite:///%s' % dbPath, echo=True) metadata = MetaData(engine) moz_bookmarks = Table('moz_bookmarks', metadata, Column('id', Integer, primary_key=True), Column('type', Integer), Column('fk', Integer), Column('parent', Integer), Column('position', Integer), Column('title', String), Column('keyword_id', Integer), Column('folder_type', Text), Column('dateAdded', Integer), Column('lastModified', Integer) ) mapper(Bookmarks, moz_bookmarks) Session = sessionmaker(bind=engine) session = Session() if __name__ == "__main__": session = loadSession() res = session.query(Bookmarks).all() print res[1].title This code really isn’t all that different from the code we’ve seen. The part we care about most is the Table definition. Here we use the keyword, Column, to define each column. The Column class accepts a name of the column, the type, whether to set it as the primary key and whether or not the column is nullable. It may accept a few other arguments, but those are the ones you’ll see the most. This example doesn’t show the nullable bit because I couldn’t figure out if the Firefox table had those constraints. Anyway, once you’ve got the columns defined, the rest of the code is the same as before. Let’s move on to the declarative style then: from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///places.sqlite', echo=True) Base = declarative_base(engine) ######################################################################## class Places(Base): """""" __tablename__ = 'moz_places' id = Column(Integer, primary_key=True) url = Column(String) title = Column(String) rev_host = Column(String) visit_count = Column(Integer) hidden = Column(Integer) typed = Column(Integer) favicon_id = Column(Integer) frecency = Column(Integer) last_visit_date = Column(Integer) #---------------------------------------------------------------------- def __init__(self, id, url, title, rev_host, visit_count, hidden, typed, favicon_id, frecency, last_visit_date): """""" self.id = id self.url = url self.title = title self.rev_host = rev_host self.visit_count = visit_count self.hidden = hidden self.typed = typed self.favicon_id = favicon_id self.frecency = frecency self.last_visit_date = last_visit_date #---------------------------------------------------------------------- def __repr__(self): """""" return "<Places - '%s': '%s' - '%s'>" % (self.id, self.title, self.url) #---------------------------------------------------------------------- def loadSession(): """""" metadata = Base.metadata Session = sessionmaker(bind=engine) session = Session() return session if __name__ == "__main__": session = loadSession() res = session.query(Places).all() print res[1].title We switched things up a bit with this example by setting it up for a different table: “moz_places”. You’ll notice that you set up the columns here by creating class variables. If you want to access the instance’s variables, you need to redefine them in the __init__. If you don’t do this, you’ll end up with some pretty confusing issues. The __repr__ is there as a “pretty print” method. When you print one of the “Places” objects, you’ll get whatever __repr__ returns. Other than that, the code is pretty similar to the other pieces that we’ve seen. Wrapping Up As you can see, using SqlAlchemy to connect to databases is a breeze. Most of the time, you will know ahead of time what the database’s design is, either from documentation, because you built it yourself, or because you have some utility that can tell you. Having that information is helpful when it comes to defining the tables in SqlAlchemy, but now you know what to try even if you don’t know the table’s configuration beforehand! Isn’t learning Python tricks fun? See you next time! Further Reading Downloads - Anonymous
http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/
CC-MAIN-2014-42
refinedweb
1,625
57.16
Hello, I am using a XamDataGrid with the datasource bound to a collection of interfaces, which are resolved to the respective classes via UnityContainer. The fields are defined with namebinding, underlying types are short, string, int?, decimal?. RecordContainerGenerationMode is not set, so judging from the blog I found click here it is set to recycle. Now to my problem: the values in cells whose types are nullable, like int? or decimal?, are sometimes horizontal aligned left sometimes right and this behavior is not coherent over the rows. Row 1 and 2 can be correctly aligned right, Row 3 is aligned left, Row 4 is right, and some are empty because of the null value. Which cells are aligned wrong is random and changes with scrolling. There is no styling on the grid. This behavior is fixed if I set RecordContainerGenerationMode to anything other than recycle, or if I change the underlying type to int eg. decimal (what I do not want). Setting the RecordContainerGenerationMode to anything other than recycle, results in a feelable performance decrease either in scrolling or on the initialization of the view. I tried to define a style for XamNumericEditor and XamCurrencyEditor to always align right and I can see these settings in Snoop, but the values are still displayed left. For the wrongfully aligned cells, if I check the settings with snoop, there is no hint on why they are displayed left. Regards <igEditors:XamDataGrid <igEditors:XamDataGrid.FieldSettings> <dataPresenter:FieldSettings </igEditors:XamDataGrid.FieldSettings> <igEditors:XamDataGrid.FieldLayouts> <dataPresenter:FieldLayout> <dataPresenter:FieldLayout.SortedFields> <dataPresenter:FieldSortDescription </dataPresenter:FieldLayout.SortedFields> Layout> </igEditors:XamDataGrid.FieldLayouts> </igEditors:XamDataGrid> MindestProduktLaufzeitInJahren and DefaultProduktLaufzeitInJahren are of type int? ProduktMindestFolgePraemie and ProduktMindestJahresPraemie are of type decimal? Hello Matthias, I have been investigating into this behavior you are reporting, and being that this behavior only happens for you when RecordContainerGenerationMode is set to “Recycle,” I would have to imagine it has something to do with the virtualization of the grid, but I cannot be sure as to what at the moment. I have put together a sample project in an attempt to reproduce this behavior, but at the moment, I cannot see the behavior you are seeing. It is also worth noting that you should be able to align the content of your Field elements in a uniform way by setting the HorizontalContentAlignment property of the Field, rather than going to the editor. I have attached 18.2.20182.186 in Infragistics for WPF 2018. XDGNullableTypeTest.zip Hello again, I got another problem with name binding. It seems that I'm unable to bind to properties that are defined on the base class of my view model. This is the same in your sample application. I get following error in vs output: A new FieldLayout is being created because none of the supplied FieldLayouts matched for the following reasons: Fieldlayout: ' - 8 Fields - index = 0' was not matched because of the following reason: There was no property found with a name of: 'IsChecked'. Note: name matching is case sensitive. Hello Andrew, I can't reproduce it in the sample project either (I just made a mistake yesterday). But I'm not able to get it to work in one view in our application. I tried to create a sample project, but I am unable to reproduce the behavior. We got the (almost) following structure in our code: public class SampleData : SampleDataBase<ISomeModelInterface>, ISampleData { public SampleData(string name, long? id, string userName, string number, decimal sum, decimal? otherSum) : base (number, sum, otherSum) { this.Name = name; this.Id = id; this.UserName = userName; } //i can bind to these public string Name { get; private set; } public long? Id { get; private set; } public string UserName { get; private set; } } public interface ISampleData : ISampleDataBase { string Name { get; } long? Id { get; } string UserName { get; } } public abstract class SampleDataBase<TModel> : SomeOtherBaseClass<TModel>, ISampleDataBase where TModel : class, ISomeModelBaseInterface { protected SampleDataBase(string number, decimal sum, decimal? otherSum) { this.Number = number; this.Sum = sum; this.OtherSum = otherSum; } // I cannot bind to these, Field Layout error Propertyname cannot be found but the values are displayed in the view. // on the grid there are 2 FieldLayout definitions one with all fields (typeof SampleData), one with 0 fields (typeof ISampleData) public string Number { get; private set; } public decimal Sum { get; private set; } public decimal? OtherSum { get; private set; } } public interface ISampleDataBase { string Number { get; } decimal Sum { get; } decimal? OtherSum { get; } } As I mentioned in the comments, I get the PropertyName not found error for all the properties in SampleDataBase. But only in our main application not in the sample. I don't get why the error is thrown and a new FieldLayout is generated but the property value is correctly displayed in the field. I am unsure why this would be happening in your application, as I have now modified the sample project such that it essentially uses the same data source that you have provided and all fields are found. I am attaching this sample project. Again, this sample project was tested against version 18.2.20182.186. As for the values being correctly displayed, I believe that I can explain this. The current FieldLayout on your end is essentially not being used as the one you have defined does not match your data item in some way. Since you have not set the FieldLayoutSettings.AutoGenerateFields property to “false,” this enables us to auto-generate a FieldLayout in the case that one is not found that is valid. I am still unsure why it is not valid in this case, though. 1172.XDGNullableTypeTest.zip I'm sorry for my late response, I tried various constellations in our application. Only sometimes, the xamdatagrid seems to be unable to bind to inherited properties, on some views it works like in your sample application. If I use alternate bindings it always works without exceptions. If I use name binding the values are correctly displayed but I get the property not found exception in the output window. I'm also curious as why I always find 2 FieldLayouts. The first, which contains all fields, is of the type of the class itself, the other which contains no fields is of the type of the corresponding interface. Edit: If I remove the inherited properties from the FieldLayout the layout type is of the Interface. If I add the Field back I get 2 FieldLayouts, one from the Interface with no Fields, one from the corresponding class with all the fields Do you have any further ideas? I think I've found the problem. In the sample applications we don't use the UnityContainer to resolve the Interface and set the data collection to items of the resolved interface. In the sample application the FieldLayout type is always the type of the class itself. Using the UnityContainer to resolve the interfaces for the items in the collection the FieldLayout is generated from the interface. Which results in the binding exception, because the Interface itself has no property with the specified name, even if it inherits an interface which has the member. If I hide the member of the base interface in the derived interface with new, it works as expected. I'm unsure on how to fix this because we heavily rely on the UnityContainer and I'm not realy a fan of adding the property to each of my interfaces and hide the base member. Thank you for your update(s). Regarding the two FieldLayouts, I think this is likely due to the error message that you are seeing that “a new FieldLayout is being created…” This will effectively keep your current FieldLayout but use the one that is being created. The one that is being created is being created because in your XAML, it does not appear that you currently have the XamDataGrid.FieldLayoutSettings.AutoGenerateFields property set to false – this defaults to true. Regarding being able to explain why this is happening in the first place though, I am really not sure as I don’t believe I completely understand what is going on with the resolution of your interfaces. As I am really unsure what is happening and I have no experience at all with UnityContainer, would it be possible for you to please modify the sample project that I sent you such that it implements these pieces and reproduces the behavior you are seeing? Alternatively, if you have an isolated sample project of your own that reproduces this, then would it be possible for you to please provide that? Hi Andrew, I was wrong with the UnityContainer but I finally found the problem. We are filling the bound collection async and at the time the grid is initialized the collection is still empty. That's why the Fieldlayout is at first created from the interface (where properties aren't inerhited if you derive from another interface). You can reproduce the behavior if you just initialize the collection with new ObeserveableCollection<ISampleData>() but don't add any items. Not sure on how we can fix this, because it's a basic implementation in our framework how/when this collection is filled with items. Thank you for your update. Using the idea of binding to an empty collection of ISampleData in the sample project, I am able to see the behavior you are referring to. Perhaps as a workaround to this, you could add a “dummy” data item to the bound collection and then mark the first DataRecord’s Visibility as Collapsed. You can access the record on the Loaded event of the XamDataGrid by accessing the grid’s Records collection. This should allow you to only generate a single FieldLayout instead of basing one on the interface. I hope this helps. Please let me know if you have any other questions or concerns on this matter. we heavily use the XamDataGrid in our application with around 50-70 views and viewmodels. Writing this dummy logic for each of them is no real option (not all of these share the same base class collection). We use a custom derived class of the XamDataGrid, let's call it CustomDataGrid, where we could implement a generic dummy logic. Which overrides would be necessary to I've played around with OnFieldLayoutChanged, OnDataSourceChanged but I wasn't able to implement the behavior I am trying to achieve. Kind regards
https://www.infragistics.com/community/forums/f/ultimate-ui-for-wpf/119566/xamdatagrid-field-binding-nullable-types-recordcontainergenerationmode/530689
CC-MAIN-2019-18
refinedweb
1,719
53.81
12 April 2012 05:13 [Source: ICIS news] By Quintella Koh SINGAPORE (ICIS)--Group I SN150 and SN500 base oils demand in the Middle East is likely to halve in July during the Muslim fasting month of Ramadan when demand drops and people work shorter hours, blenders and traders said late on Wednesday. Ramadan will start on 20 July, and will last for 30 days. During this period, blenders in the United Arab Emirates (UAE) will be lowering their plant operating rates to around 50% of capacity, the UAE-based market participants said. Employees in a blending plant usually work from 0800 to 1800 hours but during the fasting month employees work shorter hours from 0700 to 1300 hours. "This means that blending plants will have no choice but to reduce their operations," a blender said. Producers and blenders estimate that the UAE can process 2.2m tonne/year of finished lubricants, which implies that the country imports around 183,333 tonnes of base oils each month. The bulk of base oils imported by the UAE is of the Group I SN500, Group I SN150 and Group I brightstock grades. Market participants said that because of the anticipated sharp fall in demand starting from early July, they are expecting prices to remain soft sometime in early June. Group I SN150 and SN500 base oils prices have been increasing sharply since the start of March due to a regional shortage of spot material and competition for the base oils cargoes from ?xml:namespace> “Group I SN150 and SN500 base oils prices will continue to increase in the short-term, but we can expect to see the rate of price increase taper off either at the end of April or in early May,” said a second blender. Both Group I SN150 base oils prices are poised to hit 23-week highs on the back of strong demand among buyers this week, while Group I SN500 base oils prices are slated to hit a 15-week high this week. Bids for both Group I SN150 and SN500 base oils have reached $1,150/tonne (€874/tonne) CFR (cost and freight) UAE. Group I SN150 base oil prices last breached the $1,150/tonne CFR UAE level on 3 November last year, while Group I SN500 base oils prices last breached the $1,150/tonne CFR UAE level on 29 December last year.?xml:namespace> (
http://www.icis.com/Articles/2012/04/12/9549416/mideast-group-i-base-oils-demand-seen-dropping-50-in-july.html
CC-MAIN-2014-52
refinedweb
401
69.15
How to get the message from the Subscriber Function Hi, I am relatively new to ROS and have a question regarding Publisher and Subscriber. To make this easy I use the Code from the ROS Tutorial "Writing a Simple Publisher and Subscriber (C++)". I can get everything to run and I can see the published messages through the "listener" node. My question now is, how can I get the messages from the "chatterCallback" function back into my main function because I want to use it with Data from the main. I looked into the documentation of "subscribe" but I cant get it to work. Maybe I cant see the obvious solution because I didn't programmed for a while now. Used Code:... #include "ros/ros.h" #include "std_msgs/String.h" void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data.c_str()); } int main(int argc, char **argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback); //here I want access to the message from chatterCallback ros::spin(); return 0; } Thank you for the answers. Welcome! What does mean? What have you tried (post your code please)? I edited the post.
https://answers.ros.org/question/280197/how-to-get-the-message-from-the-subscriber-function/
CC-MAIN-2022-05
refinedweb
200
65.83
I am trying to do a very simple service to collect and print data from a RESTfull API, in Python. This is the code I have: import requests import json response = requests.get("url") data2 = response.json() print type(data2) data2. data2.len() PyCharm's inability to display the methods you mention indicate inability to infer the variable's type from the code alone. Which often indicates that the code might not be prepared to handle that variable's data properly in all cases (in many cases that means buggy code). The fact that your code prints the type as dict in that particular execution doesn't mean it'll always be a dict (otherwise PyCharm would have been able to infer the type). Making the code better prepared to deal with the variable's data in any situation - will make the type inferable, which will also allow PyCharm to fill in the data correctly. For example, you could write your code like this: response = requests.get("url") data2 = response.json() assert isinstance(data2, dict) print type(data2) # here data2's methods would be listed or, response = requests.get("url") data2 = response.json() if isinstance(data2, dict): print type(data2) # here data2's methods would be listed
https://codedump.io/share/VAcinAwsJMKH/1/why-doesn39t-pycharm-show-dictionary-methods-in-this-case
CC-MAIN-2017-34
refinedweb
207
65.52
Hi! How to select all Concrete Wall, Concrete Slab, Concrete Column, Concrete Beam in one DGN file using keyin? Hi, You can use the explorer to select elements based on your requirements. If you want to select multiple element types, Ctrl+Select will work. Please see the screenshot below: Hope this helps. Regards, Tathagata Tathagata Saha said:You can use the explorer The question was about using key-ins, not mouse... Jan Labyrinth Technology | dev.notes() | cad.point Yes. Using key-ins. I create C# programm for IPC mode of AECOSim. My programm send key-ins in automatic mode. namespace Bentley.IPC. contains this functional. This analog batch process for use in C#. I'm interested in using key-in, not a mouse. I'm trying to use selectby tools. For example, select only ConcreteWalls level. selectby level ConcreteWalls; selectby execute
https://communities.bentley.com/products/building/building_analysis___design/f/aecosim-speedikon-forum/174676/how-to-select-all-concrete-element-in-dgn-file-using-keyin
CC-MAIN-2019-13
refinedweb
141
62.04
Created on 2018-12-16 03:22 by satra, last changed 2018-12-16 15:16 by satra. This issue is now closed. I'm not sure if this is intended behavior or an error. I'm creating dataclasses dynamically and trying to pickle those classes or objects containing instances of those classes. This was resulting in an error, so I trimmed it down to this example. ``` import pickle as pk import dataclasses as dc @dc.dataclass class A: pass pk.dumps(A) # --> this is fine B = dc.make_dataclass('B', [], bases=(A,)) pk.dumps(B) # --> results in an error # PicklingError: Can't pickle <class 'types.B'>: attribute lookup B on types failed ``` is this expected behavior? and if so, is there a way to create a dynamic dataclass that pickles? You need to set the __module__ attribute. B.__module__ = __name__ thank you + serhiy.storchaka while that works in an interactive namespace, it fails in the following setting, which is closer to my dynamic use case. ``` class A: def __init__(self, fields=None): self.B = dc.make_dataclass('B', fields or []) self.B.__module__ = __name__ # ... self.C = self.B() ``` now pickling A() fails. Dataclasses are pickled by name, as well as other classes. Pickling classes which can not be accessed by name is not supported. Thank you.
https://bugs.python.org/issue35510
CC-MAIN-2019-43
refinedweb
215
70.5
C++ “Hello World!” Program C++ “Hello World!” program is one of the simplest C++ programs. It displays the output “Hello World!”. Example: “Hello World!” Program The output of the above program is: The above program includes the following: 1. // A Hello World program in C++: This section in the program includes the comment “A Hello World program in C++”. The compiler automatically ignores this type of comments but can be useful for the programmer. 2. #include<iostream>: In C++, all the lines starting with # are the directives that tell the compiler to include the file inside <>. <iostream> indicates the compiler to include input/output function in the program. It uses cin for input function and cout for output function. 3. using namespace std: The namespace includes all the elements of the standard C++ library. Here, std is the name of the namespace that tells the compiler to look for the elements like variables, functions. 4. int main(): It returns the data type integer. Every program must have a main() function. It is the head of the C++ program. 5. { and }: The opening braces ‘{‘ indicates the beginning of the main function and ‘}’ indicates the end of the main function. Everything written between these two is the body of the main function. 6. cout<< “Hello World!”: The cout is the function that displays the output in the screen. Everything inside the ” ” is displayed on the screen. In this program, the compiler prints the output Hello World! as shown above. 7. return 0: This statement causes the main function to finish. This statement returns the value 0 from the main() function that indicates that the execution of the main() function is successful. Recent Comments
https://www.programming-techniques.com/2019/04/cpp-hello-world-program.html
CC-MAIN-2019-47
refinedweb
281
68.57
import "golang.org/x/crypto/blowfish" Package blowfish implements Bruce Schneier's Blowfish encryption algorithm. block.go cipher.go const.go The Blowfish block size in bytes.. A Cipher is an instance of Blowfish encryption using a particular key. NewCipher creates and returns a Cipher. The key argument should be the Blowfish key, from 1 to 56 bytes. NewSaltedCipher creates a returns a Cipher that folds a salt into its key schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is sufficient and desirable. For bcrypt compatibility, the key can be over 56 bytes. BlockSize returns the Blowfish block size, 8 bytes. It is necessary to satisfy the Block interface in the package "crypto/cipher". Decrypt decrypts the 8-byte buffer src using the key k and stores the result in dst.). func (k KeySizeError) Error() string Package blowfish imports 1 packages (graph) and is imported by 41 packages. Updated 2017-11-29. Refresh now. Tools for package owners.
https://godoc.org/golang.org/x/crypto/blowfish
CC-MAIN-2017-51
refinedweb
158
51.65
I tried to run local galaxy but cannot do that upon upgrade of MacOSX to El capitan recently. Here is what I got once I type >sh run.sh I tried to run local galaxy but cannot do that upon upgrade of MacOSX to El capitan recently. Here is what I got once I type >sh run.sh Yes, we've seen the exact same error. I guess the reason is that Galaxy tries to use a slightly outdated version of amqp. amqp 1.4.7 fixes the El Capitan incompatibility and should be used instead. To fix this immediately for your current installation, this should work (though I haven't tried it yet): in the file /Users/jaeilhan/Downloads/galaxy-dev/eggs/amqp-1.4.6-py2.7.egg/amqp/five.py replace the line: libSystem = ctypes.CDLL('libSystem.dylib') with: libSystem = ctypes.CDLL(find_library('libSystem.dylib')) oh, and keep the leading whitespace as it is We are aware of this and are working on the fix. It is possibly caused by Kombu and amqp having trouble on _some_ el capitans. "Fixed libSystem import error on some OS X 10.11 (El Capitan) installations." Thanks for reporting The fix for 15.10 is here and should be merged shortly once tests pass: Older versions can simply modify eggs.ini as in that PR and should be able to use the newer eggs (however, you are strongly encouraged to update to the latest stable version, especially if developing in Galaxy). I reinstalled the galaxy and got something different. (It seemed to work at the beginning) That is still the same error. By reinstalling Galaxy you triggered a fresh download of all software it depends upon including the old version of amqp. Now try to make the change I suggested and restart (not reinstall) Galaxy. I see! However, I made the change you suggested as well but got the same error. Unfortunately, I do not have access to our El Capitan test machine right now to verify this. Can you try to change the line again and post the error message if it appears again? I would be surprised if it's the same as above. I wonder if I did something wrong. Here is the part of the five.py file including the change I made. if sys.version_info < (3, 3): import platform SYSTEM = platform.system() if SYSTEM == 'Darwin': import ctypes from ctypes.util import find_library libSystem = ctypes.CDLL(find_library('libSystem.dylib')) CoreServices = ctypes.CDLL(find_library('CoreServices'), use_errno=True) mach_absolute_time = libSystem.mach_absolute_time mach_absolute_time.restype = ctypes.c_uint64 absolute_to_nanoseconds = CoreServices.AbsoluteToNanoseconds absolute_to_nanoseconds.restype = ctypes.c_uint64 absolute_to_nanoseconds.argtypes = [ctypes.c_uint64] def _monotonic(): return absolute_to_nanoseconds(mach_absolute_time()) * 1e-9 and This is the error message I got. It seems to be same. Ah, this is *different*. The original error is gone, but that revealed a new one in /Users/jaeilhan/Downloads/galaxy-dev/eggs/kombu-3.0.24-py2.7.egg/kombu/five.py . That file suffers from the exact same problem as the previous one so modify it like you did before. Hope that is it.
https://biostar.usegalaxy.org/p/14492/
CC-MAIN-2022-05
refinedweb
512
60.21
The following two commands tell generate-mapping to log in to MySQL, look at the data dictionary of the indicated databases, and generate the mapping files that let you issue SPARQL queries against the Eudora and Outlook databases (substitute your own MySQL username and password; also note that a carriage return was added after -p in each command for readability here, but each generate-mapping command is one line): generate-mapping -o eudoraMapping.ttl -u myID -p myPassword jdbc:mysql://localhost/eudora generate-mapping -o outlookMapping.ttl -u myID -p myPassword jdbc:mysql://localhost/outlook d2r-server eudoraMapping.ttl d2r-server eudoraMapping.ttl PREFIX eud: SELECT ?p ?o WHERE { ?s eud:entries_mobile "(328) 618-8442" . ?s ?p ?o . } Each of the two mapping files you created assigns the namespace prefix map to a URL for the mapping file. To keep them straight in the combination file, change map: to emap: throughout eudoraMapping.ttl, and to omap: wherever it said map: in outlook.ttl. You don't have to do this to see the demo in action, because the resulting files are all included in the zip file, but you'll want to know about the steps I took to get there in case you do something similar with different databases. Some of the files may need to be rebuilt if one of the relevant software packages gets upgraded, because I've found that the generated URIs may evolve from one software release to another. You'll also need to change the d2rq:username and d2rq:password values in the mapping files to the username and password that you're using to log in to MySQL. Both ttl files also assigned the prefix vocab to a namespace used for vocabulary terms, so to distinguish them in the combined file, change this prefix to eud throughout eudoraMapping.ttl and to out throughout outlookMapping.ttl. It's also a good idea to change the namespace URL—which wasn't a proper one to begin with—from vocab to eudora in one and from vocab to outlook in the other. Next, combine the two files into one file named comboMapping.ttl. Move all the namespace declarations to the top and remove the redundant ones. Below is one of the mapping entries in comboMapping.ttl that you need to edit: emap:entries_email1 a d2rq:PropertyBridge; d2rq:belongsToClassMap emap:entries; d2rq:property eud:entries_email1; d2rq:column "entries.email1"; . Telling D2RQ to treat an email address such as joe@whatever.com as a URI isn't enough, because software that treats it as a URI won't like its format—it doesn't look like a URI. The value of the new d2rq:uriPattern line that replaces the commented-out d2rq:column line below inserts a mailto: prefix so that the value really is a URI. The final line of the revised version of the mapping entry tells D2RQ a condition for generating one of these mappings: that the data is not an empty string. If any address book entry is missing an email1 value, we don't want the string mailto: by itself being generated as the address book entry's entries_email1 value. emap:entries_email1 a d2rq:PropertyBridge; d2rq:belongsToClassMap emap:entries; d2rq:property eud:entries_email1; # d2rq:column "entries.email1"; d2rq:uriPattern "mailto:@@entries.email1@@"; d2rq:condition "entries.email1 <> ''"; . At this point, the combomapping.ttl mapping file is ready, and you could start up the D2RQ server as shown below, and then do queries against either database: d2r-server comboMapping.ttl dump-rdf -m comboMapping.rdf -o datadump.rdf Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/semantic/Article/38700/0/page/2
CC-MAIN-2016-26
refinedweb
623
55.54
Google Interview Question: Find the Longest Sequence in an… Google interview questions are popular since a while and it’s become a fashion to ask difficult to answer questions during interviews. Here is one question : Given an int array which might contain duplicates, find the largest subset of it which form a sequence. Eg. {1,6,10,4,7,9,5} then answer is 4,5,6,7 Sorting is an obvious solution. Can this be done in O(n) time? here is my solution. Buy I can’t understand the reason for asking such questions to be solved in a very short time. I wonder who could really solve this problem in 5 minutes time and if someone can does it really mean that s/he is a good programmer? Run the code below from here import java.util.HashMap; import java.util.Map; /** * User: uerturk */ /** * Given an int array which might contain duplicates, find the largest * subset of it which form a sequence. * Eg. {1,6,10,4,7,9,5} * then answer is 4,5,6,7 * Sorting is an obvious solution. Can this be done in O(n) time */ class FindTheLongestSequence { private int follow(int startNumber, Map<Integer, Pair<Boolean, Integer>> pairMap) { Pair<Boolean, Integer> currentPair = pairMap.get(startNumber); if (currentPair == null) { return 0; } else { if (currentPair.getFirst()) { return currentPair.getSecond(); } else { int result = follow(startNumber + 1, pairMap) + 1; currentPair.setFirst(true); currentPair.setSecond(result); return result; } } } public void longestSequence() { int[] ints = {1, 6, 10, 4, 7, 9, 5}; // in the map first is the number, in the pair first isVisited flag, second is the score Map<Integer, Pair<Boolean, Integer>> pairMap = new HashMap<Integer, Pair<Boolean, Integer>>(); for (Integer i : ints) { pairMap.put(i, new Pair<Boolean, Integer>(false, 1)); } int[] results = new int[ints.length]; for (int i = 0; i < ints.length; i++) { int result = follow(ints[i], pairMap); results[i] = result; System.out.println(ints[i] + ":" + result); } } class Pair<First, Second> { First first; Second second; public Pair(First first, Second second) { this.first = first; this.second = second; } public void setFirst(First first) { this.first = first; } public void setSecond(Second second) { this.second = second; } public First getFirst() { return first; } public Second getSecond() { return second; } public void set(First first, Second second) { setFirst(first); setSecond(second); } } public static void main(String[] args) { new FindTheLongestSequence().longestSequence(); } } Hey Umut, your code complexity is O(n^2). Worst case is: {1, 2, 3, .. n}. It can be done in O(n). Nope the solution is in O(n). Pair’s first element is also the visited flag, all the elements are traced once. What is the output of your solution? I got here 1:1 6:2 10:1 4:4 7:1 9:2 5:3 but should be this 4,5,6,7 How to print result from your solution? This code finds all the solutions; 6:2 –>6,7 4:4 –> 4,5,6,7 7:1 –> 7
http://hevi.info/uncategorized/google-interview-question-find-the-longest-sequence-in-an-unordered-set/
CC-MAIN-2022-27
refinedweb
493
58.79
Cost of painting n * m grid Given two integers n and m which are the dimensions of a grid. The task is to find the cost of painting the grid cell by cell where the cost of painting a cell is equal to the number of painted cells adjacent to it. Any cell can be painted at any time if it hasn’t been painted already, minimize the cost of painting the grid. Examples: Input: n = 1, m = 1 Output: 0 A single cell with no adjacent cells can be painted free of cost Input: n = 1, m = 2 Output: 1 1st cell will be painted free of cost but the cost of painting the second cell will be 1 as there is 1 adjacent cell to it which is painted A simple solution is to generate all possible ways of painting the grid with n * m cells and that is n * m! calculate the cost for each one of them. Time Complexity: O(n * m!) Efficient Approach: Understand the coloring process in this graph instead of the grid. The coloring of a cell is therefore equal to the coloring of a vertex of the graph. The cost obtained for the painting of a cell is equal to the number of colored neighbors of the cell. This means that the cost obtained will be the number of edges between the current cell and the adjacent colored cells. The crucial point is to note that after the end of coloring of all the cells, all the edges of the graph will be marked. An interesting fact is that the edges of the graph are marked only once. This is because an edge connects two cells. We mark the cell when both cells are painted. We are not allowed to paint a cell more than once, which ensures that we only mark each cell once. Thus, whatever the order in which you color the cells, the number of marked edges remain the same, so the cost will be the same. And for given grid the number of edge will be n * (m – 1) + m * (n – 1). This came from the fact that each row consists of m – 1 edges and each column consists of n – 1 edges. Below is the implementation of the above approach: C++ Java Python3 C# // C# implementation of the approach using System; class GFG { // Function to return the minimum cost static int getMinCost(int n, int m) { int cost = (n – 1) * m + (m – 1) * n; return cost; } // Driver code public static void Main() { int n = 4, m = 5; Console.WriteLine(getMinCost(n, m)); } } // This code is contributed // by Akanksha Rai PHP 31 Recommended Posts: - Minimum cost to cover the given positions in a N*M grid - Number of rectangles in N*M grid - Count Magic squares in a grid - Largest connected component on a grid - Count possible moves in the given direction in a grid - Minimum distance to the corner of a grid from source - Minimum number of integers required to fill the NxM grid - Unique paths covering every non-obstacle block exactly once in a grid - Minimum steps needed to cover a sequence of points on an infinite grid - Min Cost Path | DP-6 - Minimum cost to connect all cities - Minimize the cost to split a number - Minimum spanning tree cost of given Graphs - Uniform-Cost Search (Dijkstra for large Graphs) - Find the minimum cost to reach destination using a, Code_Mech, rituraj_jain, Akanksha_Rai
https://www.geeksforgeeks.org/cost-of-painting-n-m-grid/
CC-MAIN-2019-18
refinedweb
576
59.67
A few weeks ago, I demonstrated how to implement Sign in with Facebook with a REST API. Today, I will show you how to Sign-in with Google in Angular 5 with a REST API involved. We will use PHP at the backend, but this will work with any backend language you are totally comfortable with. To put it simply, your Angular App will request a token from Google OAuth Servers and then send the token to the REST API. The REST API will then validate the token against Google Servers (Never Trust Anything from the User) and if genuine, Sign-in or create account or do something that needed user to be authenticated. You will also get user profile data from Google including the profile picture which you can store for future reference. Let’s get started: The first thing we need is to create Google Project, so that we can get Access Credentials. To do this, you can head over to Google Developer Console and create an account or login with an existing account. First, click on create project button near the top left corner and enter the name for your project and click save. Wait until the project has been created. Then, select the project you just created and go to the credentials of API and Services for the project by clicking on the menu icon on the top left corner, then select API and Services, and then Credentials. If it’s a new project, you won’t have any credentials on your screen. There are a few things you need to do here. The first thing is to configure your OAuth Consent Screen. This is the screen users will see with your app name and logo as you ask for permission during the Sign in with Google Process. To configure the OAuth Consent Screen, click on the OAuth Consent Screen Tab (Refer to the image below) and fill in the requested details. The name of the App is mandatory. Next, you need to create OAuth Credentials for your project. You should see a Create Credentials button on the screen, either at the middle of the screen or on top of the Credentials tab, just beneath the toolbar of the window. Click on the Create Credential Button, and select OAuth Client Id option in the drop-down menu that follows. In the next page, select Web Application from the options under Application Type. And then provide the name of the credentials and click Create button. You might want to restrict the authorized domain names in the restriction section before creating the credentials. Here you will get the Client Id and the Client Secret, store them securely as you will need them for the steps that will follow. Assuming you have successfully created a project, let’s go on and add a Sign-in with Google button to your angular app. To achieve this, we will use angularx-social-login module. You can install it using NPM or Yarn: npm install --save angular5-social-login // Or use yarn yarn add angularx-social-login Then import the Angular Social Login module into your app module as show below: import { SocialLoginModule, AuthServiceConfig, GoogleLoginProvider } from 'angularx-social-login'; Then create a new file socialloginConfig.ts in the root of your project and add a config file for social login: import { SocialLoginModule, AuthServiceConfig, GoogleLoginProvider } from 'angularx-social-login'; export function getAuthServiceConfigs() { let config = new AuthServiceConfig([ { id: GoogleLoginProvider.PROVIDER_ID, provider: new GoogleLoginProvider()<GoogleClientIdJHere> } ]); return config; } NB: Replace the GoogleClientIdHerewith your client id from the Google Project you created in the first step. Then import getAuthServiceConfigsinto your app modules: import { getAuthServiceConfigs } from './socialloginConfig '; And finally import SocialLoginModule and add providers for SocialLoginModule as show below @NgModule({ imports: [ // ... SocialLoginModule ], providers: [ // ... SocialLoginModule.initialize(getAuthServiceConfigs) ], bootstrap: [ //... ] }) Then, on your sign in component, import the AuthService, GoogleLoginProvider as shown below: import { AuthService, GoogleLoginProvider } from 'angular5-social-login'; And Inject AuthService into your component as shown below: constructor( private socialAuthService: AuthService ) {} Then, add a method to handle Sign-in with Google and a button to your component. The method will look like this: public signinWithGoogle () { let socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID; this.socialAuthService.signIn(socialPlatformProvider) .then((userData) => { //on success //this will return user data from google. What you need is a user token which you will send it to the server this.sendToRestApiMethod(userData.idToken); }); } And then add a <button (click)="signinWithGoogle()">Sign in with Google</button> The sendToRestApiMethod is a method that will use HTTP to post the data to your REST API. The Token Id ( idToken)received from Google should be either a parameter or form data depending on the HTTP method you use to send the data to the server. Here is an example: sendToRestApiMethod(token: string) : void { this.http.post("url to google login in your rest api", { token: token } }).subscribe( onSuccess => { //login was successful //save the token that you got from your REST API in your preferred location i.e. as a Cookie or LocalStorage as you do with normal login }, onFail => { //login was unsuccessful //show an error message } ); } My REST API will be using PHP, but you can use any language you are comfortable with. For further and detailed tutorials for other language am not covering, visit the official documentation from Google here. First, install PHP Google SDK using composer as shown below (For detailed installation instruction, visit this link): composer require google/apiclient Once the installation is complete, go to your login script or method and call the Google OAuth endpoint to verify the Token Id ( idToken) and create an account or grant user access to server-side resources or something. First, initialize the Google SDK as shown below: $client = new Google_Client([ 'client_id' => '<GOOGLE CLIENT ID HERE>' ]); And then send the Token Id ( idToken) to the server for verification as shown below: $payload = $client->verifyIdToken($idToken); Then, compare the claim aud value with your google client id to ensure that the idToken you got from your app was meant for your client and its valid. If they don’t match, then the token id is not valid. The payload contains personal data from the user, here is what is included in the payload: { // These six fields are included in all Google ID Tokens. "iss": "", "sub": "110169484474386276334", //Unique Google Account Id " } Next, create an account or sign in the user if they already exist. The sub key in the payload is the Account Id and you can use to check if the user already exists. I suggest you generate your own User Id and do not rely with Google unique user id. If you liked this post and would like to help me make more like it in the future, please consider supporting me on Patreon for a dollar or more.Become a Patron!
https://codinglatte.com/posts/angular/sign-in-with-google-angular/
CC-MAIN-2019-13
refinedweb
1,129
58.42
A fast and thorough lazy object proxy. Project description A fast and thorough lazy object proxy. - Free software: BSD license Note that this is based on wrapt’s ObjectProxy with one big change: it calls a function the first time the proxy object is used, while wrapt.ObjectProxy just forwards the method calls to the target object. In other words, you use lazy-object-proxy when you only have the object way later and you use wrapt.ObjectProxy when you want to override few methods (by subclassing) and forward everything else to the target object. Example: import lazy_object_proxy def expensive_func(): from time import sleep print('starting calculation') # just as example for a very slow computation sleep(2) print('finished calculation') # return the result of the calculation return 10 obj = lazy_object_proxy.Proxy(expensive_func) # function is called only when object is actually used print(obj) # now expensive_func is called print(obj) # the result without calling the expensive_func Installation pip install lazy-object-proxy Documentation Development To run the all tests run: tox Changelog 1.4.1 (2019-05-10) - Fixed wheels being built with -coverage cflags. No more issues about bogus cext.gcda files. - Removed useless C file from wheels. - Changed setup.py to use setuptools-scm. 1.4.0 (2019-05-05) 1.3.1 (2017-05-05) - Fix broken release (sdist had a broken MANIFEST.in). 1.3.0 (2017-05-02) - Speed up arithmetic operations involving cext.Proxy subclasses. 1.2.1 (2015-08-18) 1.2.0 (2015-07-06) - Don’t instantiate the object when __repr__ is called. This aids with debugging (allows one to see exactly in what state the proxy is). 1.1.0 (2015-07-05) 1.0.2 (2015-04-11) - First release on PyPI. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/lazy-object-proxy/
CC-MAIN-2019-35
refinedweb
319
59.19
Frank Inspired by Sinatra's simplicity and ease of use, Frank lets you build static sites using your favorite libs. Frank has a built in development server for previewing work as you develop, an "export" command for compiling and saving your work out to static html and css, and a publish command for copying your exported pages to a server. Frank uses Tilt, so it comes with support for Haml & Sass, LESS, Builder, ERB, and Liquid. Overview Create a new project with: $ frank new <project_path> Then cd <project_path> and start up the server with: $ frank server ----------------------- Frank's holdin' it down... 0.0.0.0:3601 And you're ready to get to work. By default, dynamic templates are served from the dynamic folder, static files are served from the static folder, and layouts are served from the layouts folder. When you're done working: $ frank export <export_dir> to compile templates and copy them--along with static your assets--into <export_dir> (or to export/ if you don't specify an <export_dir>). Or, $ frank export --production <export_dir> to compile & copy over, but organized to work as a static website in production. (e.g. folders named after your views, with an index.html inside) You can add publish settings in setup.rb and publish directly to a server via scp. $ frank publish Upgrading As of version 0.4, Frank no longer uses settings.yml. However you can use frank upgrade in order convert your old settings.yml to the new setup.rb format. Frank Templates Frank (as of 1.0) has support for saving "templates" in ~/.frank_templates. This is very handy if find yourself wanting a custom starting point. All you have to do to use the feature is create a ~/.frank_templates folder and start putting templates in it. Once you have a few templates saved, when you run frank new <project_path> you'll be presented with a list of templates to choose from as the starting point for the project. Views & Meta Data All of your templates, less, sass &c. go into <project>/dynamic by default. You can organize them into subfolders if you've got lots. Views Writing views is simple. Say you've got a blog.haml in <project>/dynamic; just browse over to and your view will be parsed and served up as html. Meta Data Frank was designed to make controllers unnecessary. But, sometimes it's nice to have variables in your templates / layouts. This is particularly handy if you want to set the page title (in the layout) according to the view. This is simple, now, with meta data. Meta fields go at the top of any view, and are written in YAML. To mark the end of the meta section, place the meta delimeter, META---, on a blank line. You can use as many hyphens as you'd like (as long as there are 3). Meta fields are then available as local variables to all templating languages that support them--in the view & layout: view: title: My Rad Page author: My Rad Self ---------------------------------------------META %h1= title %h3= 'By ' + author layout: %title= title + '--My Rad Site' Layouts (updated in 0.3) Layouts are also simple with Frank. Create a default.haml (or .rhtml, etc.), in the layouts folder, and include a yield somewhere therein; views using the layout will be inserted there. Namespacing Layouts You can namespace your layouts using folders: - When rendering a view-- dynamic_folder/blog/a-blog-post.haml, - Frank would first look for the layout layouts/blog/default.haml, - and if not found use fall back on layouts/default.haml Multiple/No Layouts Frank also supports choosing layouts on a view-by-view basis via meta data. Just add a layout meta field: layout: my_layout.haml ---------------------------------------------META %h1 I'm using my_layout.haml instead of default.haml! or if you don't want a layout at all: layout: nil ---------------------------------------------META %h1 No layout here! Partials & Helpers Frank comes with a helper method, render_partial, for including partials in your views. You can also add your own helper methods easily. Partials To create a partial, make a new file like any of your other views, but prefix its name with an underscore. For example, if I have a partial named _footer.haml, I can include this in my Haml views like this: = render_partial 'footer' You can also send local variables to partials like this: = render_partial 'footer', :local_variable_name => 'some_value' Helpers Helper methods are also easy. Just open up helpers.rb and add your methods to the FrankHelpers module; that's it. Use them just like render_partial. Built-in Helpers Auto-Refresh Frank has a handy automatic page refreshing helper. Just include = refresh (or equivalent) in your view, and Frank will automatically refresh the page for you whenever you save a project file. This eliminates the tedium of hundreds of manual refreshes over the course of building a project. When it's time export with frank export, Frank will leave out the JavasScript bits of the refresher. Current Path Frank now has a current_path variable that you can use to set selected states on nav items. It will return the path info from the template being processed. You also, have access to the variable from layouts and from the frank export command. Placeholder Text You can easily generate dummy text like so: %p= lorem.sentences 3 This will return 3 sentences of standard Lorem Ipsum. lorem also has all of the following methods for generating dummy text: lorem.sentence # returns a single sentence lorem.words 5 # returns 5 individual words lorem.word lorem.paragraphs 10 lorem.paragraph lorem.date # accepts a strftime format argument lorem.name lorem.first_name lorem.last_name lorem.email Placeholder Images Frank now uses placehold.it for placeholder images, the lorem.image helper supports background_color, color, random_color, and text options: lorem.image('300x400') #=> lorem.image('300x400', :background_color => '333', :color => 'fff') #=> lorem.image('300x400', :random_color => true) #=> lorem.image('300x400', :text => 'blah') #=> Replacement Text All of the lorem helpers accept an optional "replacement" argument. This will be the text rendered when you frank export. For example lorem.sentence("<%= page.content %>") will generate a lorem sentence when you view the page using the frank server for development. However, when you frank export the template will render "<%= page.content %>". This is useful if you plan on moving a frank project into a framework. (e.g. rails, sinatra, django, etc) Configuration In setup.rb, you can change your folder names, and server port & host name. Check the comments there if you need help. Installation $ gem install frank Contributors (in no particular order) - railsjedi (Jacques Crocker) - asymmetric (Lorenzo Manacorda) - timmywil (timmywil) - sce (Sten Christoffer Eliesen) - btelles (Bernie Telles) - mitchellbryson (Mitchell Bryson) - nwah (Noah Burney)
http://www.rubydoc.info/gems/frank/frames
CC-MAIN-2017-30
refinedweb
1,114
67.25
hi.. vineet thank you.. I'm still having an invalidcast exception even if i follow your coding... is there any other way Can you paste the xml you are trying to parse, along with the structure of class myclass. In DetailsModel.cs: in a method: public static myclass extractmethod(string result, ServiceModel sm) myclass fd=new myclass (); { XDocument xdoc = XDocument.Parse(result); var details= from ack in xdoc.Descendants() where ack.Name =="Details" select ack; myclass fd=(myclass )details; // invalidcast exception } In myclass.cs public class myclass { private string Id { get; set; } private string Source { get; set; } public string details{ get; set; } } Hmm not sure what you are actually trying to do, is it the value of descendant 'details' tag you are trying to fetch & save it?, try pasting the xml also. The answer is actually obvious, but it's best to try and help someone figure out the answer versus just giving to them, in which case they learn nothing. An 'invalid cast exception' happens when you try to convert from one type to another and no conversion is possible. Depending on how you use Linq in this case, it's either going to return an IEnumerable<MyClass> or IEnumerable<XElement>. Either way, casting to MyClass will throw an exception because they are NOT the same type. And if you don't understand why, then I suggest you read up on programming in C# and how to use the Debugger. Note that in your new query you have not described how you get the invalid cast exception, that is why I assumed it is the same question as the previous one. Anyway I think I understand the current one. You are parsing an XML and want to populate an object. That is not done via casting. LINQ is powerful, but it can not cast a document fragment into a statically typed object/structure. You will have to create a method for your object which extracts the fields one by one from details. See for some example. If you check, its "The keyword var, object and collection initialization, and anonymous types" section shows how a "var" representing a complex structure will look like internally, it always has a type even if it is not seen in the code. And that ad-hoc type can not be casted to your myclass.
http://developer.nokia.com/community/discussion/showthread.php/243108-I-need-to-pass-the-list-values-from-1-page-to-another-page?p=927611
CC-MAIN-2014-10
refinedweb
390
63.49
How to uninstall git from Visual studio? The feature you are trying to use is on a CD-ROM error after building Setup Project Visual Studio Team Services how to publish code documentation How to use parameters for table names and field name in oledb command statement when updating a MS Access table? Clang/LLVM enabling OpenMP-Support VS2017 not showing suggestions & cannot navigate to the symbol under caret VS 2017 enable warning about missing XML comments Visual Studio extension for scripting objects with debug values Retrieve the previous record and store to text boxes How do you convert a cell value in a DataGridView into a integer if it's an integer, and a string when it's a string? Nuget returned an unexpected status code '404 Not Found' - Package on local drive When clicking "btnLogin", my forms decrease in size. How is this possible? Why does this occur? OpenQA.Selenium.DriverServiceNotFoundException MSVC Linker option debug:fastlink causing program execution slowdown Visual Studio and Nexus Integration without TFS or VSTF Given a list of named doubles, return the name of the variable with the lowest value Why does this NSubstitute Received Call Fail? xamarin.oauth /xamarin forms Facebook linkedin google authentification How do I create a SQLite database using PetaPoco? How to deploy ASP.NET MVC app via sftp VsCODE error when importing Django module How to load node.js/angular 2 project in Visual Studio? Error:(25) No resource identifier found for attribute 'tex' in package 'android' Two web project, one domain in one Visual Studio solution Need to add a key to allowed origins key in web.config file Publishing 2010 vsto word addin Visual Studio add configuration option to project when preexisting one exists sonar cs vscoveragexml imported but result not shown on SonarQube server The type or namespace name does not exist in the namespace after executing a cleanup Microsoft Visual Studio shows a message "... stopped working ..." and restarts when I compile (build) a project Visual Studio performance and build issues how to open and build my project in visual studio without .sln and .csproj file Why does commenting out the line for detection of text files' LF normalization fix weird VS line ending detection? Administrator exclusive page? Documentation for Visual Studio commands, ToolsDiffFiles and other commands Razor View is being cached in Visual Studio Visual Studio: C++\CLI wrapper assembly path dependency problems Greyed out C# preprocessor directives in Visual Studio 2017 Wrong values in Array containing Structs in C Visual studio project template replaces "$(SolutionDir)" macro in template on build VS 2017 Community - Cannont find or open the PDB file HTTP Error 502.5 - Process Failure - .net core 2.0 to AWS EB Shared react front end components -> Separate project with TypeScript -> Visual Studio 2017 Choose Visual Studio version Getting visual studio to show the same API as Unity Hololens Development How to fix error with SFML ln VS 2017? Visual Studio loads the unmodified version How Can I install mariadb and restore a mysql db using a setup project (installer) in Visual Studio Link multiple projects together VSTS Open string as new file in current VS How to find parent form name ? vb.net C# Visual Studio Add custom reference in visual studio 2017 do i have to set this in every project? How to make multy-template .vsix in SideWaffle? Gridview AutogenratedColumns Edit mode DropDownlist Control Add But Updating Time Not Available Build action Resource missing VS 2017 - Trying to Open Excel 2010 document to edit using VB.net - "No such interface supported" Cannot see the "Components" folder in Xamarin.forms /.netstandard project How do i fill combo boxes with data from mysql in visual c# Can't sign in to Visual Studio. White background Visual Studio unit test not working and not showing tests How to join two Access tables into one DataGridView? Select SQL statement from multiple database Change Strong Name in dll Properties Tracking run time values in Visual Studio How to change button.text of all the buttons you created in code (NOT the manually created buttons)? C# how to create report in visual studio using code program("aspx.cs") Closing Console Causes WPF app to close as well Unable to run Xamarin Forms project in Visual Studio 2017 Android emulator Image resampling on 3-channel thats not padded to 4 bytes? What Microsoft technology based on c# would you recommend? Trackbar value displayed in textbox C# assimp-vc140-mt.dll ASSIMP was not found Appcelerator setup on windows ContextSwitchDeadlock - why not every long task cause it? C# xamarin get resource.id in function Xamarin Forms Android emulator keeps crashing Primary key increment column not pulling through to Windows Form Custom tool window on click visual studio extension C# Xamarin Placing EditText above ListView Debug mode changing array Make a radio button check based on condition C# Xamarin LinearLayout double click C# searchbox in wpf application What happen to my VIew Folder Visual Studio 2012 Code Snippets foreach split words and datetime using regex in c# Team Target Platform Version Error: No value given for one or more required parameters. What does this mean? How do I fix? Weird memory displacement on all structures Strange Error with Vectors in C++ How to refresh user control within same form? Is there a shortcut for {End} followed by {Enter}? C# Xamarin Clickable LinearLayout Azure VM IIS Server - Web Deploy Run program in system terminal
http://codegur.com/tag/visual-studio
CC-MAIN-2018-05
refinedweb
905
50.36
Time Warner Finds AOL Email Inadequate 357 DragonMagic writes "MSNBC.com carries this article describing the woes at many of Time Warner's companies after AOL's merger, where the internet giant tried to migrate them all to AOL's email services. From crashing software and attachment limits, to missing and misdirected mail, companies such as Time Magazine had to go so far as to have hard copies rushed before deadlines by cab! Plans are now to retreat from this forced migration and return to the services previously held by each company." It's not too bad... (Score:2, Funny) Maybe they designed an anti-spam filter and went a bit too further. Obviously no one paid attention (Score:3, Insightful) Re:Obviously no one paid attention (Score:4, Informative) Obviously the person who sent out that decree has either a. never used aol mail, or b. never used email in a corporate environment. Obviously the person who wrote the above didn't even bother to understand the situation. From the particular article referenced in the Slashdot "story": Emphasis mine, smartass. Re:Obviously no one paid attention (Score:2, Insightful) Re:Obviously no one paid attention (Score:2) Re:Obviously no one paid attention (Score:3, Informative) Also, since AOL is planning on using a mozilla like system replaincing IE, and has been putting big bucks into continued Netscape browser developement, my guess is that the client software was netscape 6 based. Considering how stable NS6 is, coupled with the AOL server backend, it's no wonder the system sucked. Re:Obviously no one paid attention (Score:5, Insightful) ~my $.02 Re:Obviously no one paid attention (Score:2, Insightful) I can see some logic behind it. Rather than maintaining/supporting/upgrading X different systems across the various companies why not standardise on a single system. Now the choice of system to standardise on leaves a bit to be desired but the decision itself was, in my opinion, a sound one. Re:Obviously no one paid attention (Score:3, Insightful) I'm going to coin a phrase: This is from a company where the ultra-reliable sendmail servers were replaced with Exchange, which has been down corporate wide for up to a week at a time. All so that we could standardize on Microsoft. Hmmm, maybe it's the "Microsoft" part that really makes the CIO "incompetent"? I'll grant that there are benefits to standardization, but it seems like large corporate standardization efforts are driven top-down; nobody asks the users what they want or even what they need to get their jobs done. So the results satisfy some sort of CIO goals checklist, but the real result is that lots of time at the ground level is wasted. It's like top executives are allergic to feedback that doesn't come from Wall Street sycophants or something. Re:Obviously no one paid attention (Score:2) You make me laugh. You work at a company where the sysadmins cant' get email working and you blame the CIO? Maybe it is his fault for not firing the "incompetent" schmoes that can't figure out haw to make Exchange stay up. You know Exchange isn't inherently more or less reliable than Sendmail it's mostly up to the people who run it to make it so. I doubt the CIO was admining your servers. It seems like large corporate standardization efforts are driven top-down So? Everything in a corporation is driven top-down. The guys at the top tell you what the goals of the company are and they set the direction and tone. They give you the tools and the resources and it is your job to do it. If you don't understand that you don't have a place in an enterprise environment. Re:Obviously no one paid attention (Score:2, Interesting) I'm reasonably surprised they're not using free software, given their mozilla and their linux-client projects. Re:Obviously no one paid attention (Score:2, Insightful) If the executives at Ford don't drive Ford cars then what does it say about Ford cars? If Microsoft developers don't use Visual Studio, what does it say about Visual Studio? If AOL/TW doesn't use the email system that AOL/TW sells, then what does it say about that email system? So when one company buys another the new company has to try to use the products of both companies, regardless of the transitionary costs (e.g. Hotmail and Microsoft server OS). The (unforunately named) phrase is "eating your own dogfood". Re:Obviously no one paid attention (Score:2) Re:Obviously no one paid attention (Score:2, Informative) It says that their products are appropriate for their intended consumer audience and not necessarily for everyone. AOL markets to the low end, the new user, and their product is perfectly appropriate to that user. It is not nearly appropriate for business use. I used to work at Kraft Foods, and I assure you that at company headquarters the cafeteria does not serve Minute Rice, Stove Top stuffing, or Oscar Mayer wieners. Re:Obviously no one paid attention (Score:2) Re:Obviously no one paid attention (Score:2, Insightful) That can be answered by a) 'Our mail system is intended for home, not business use' or b) 'We have full confidence in it, but there's a system workign in place already, and there are no benefits to be gained by spending the money to switch.' Re:Unspoken factor (Score:2) So what's the old system? (Score:5, Funny) Why use AOL? (Score:3, Interesting) Perhaps some overzealous manager issued an edict that everyone *must* use AOL even though it's email software is next to useless in a work environment. Because AOL mandates it (Score:5, Interesting) I worked at Netscape and when AOL took over, they forced everyone, including Unix developers, to use the AOL client to get to HR forms, 401K info, corporate email, etc. Netscape had spent 5 years getting every sort of internal functionality on the Net. All HR, 401K, Medical stuff, email, directory, whatever, was _all_ on the Net. Then AOL came in and mandated it all go away to be replaced by the fucking pathetic AOL client. Now I'm pissed just thinking about it. (BTW, I worked for AOL for 2 weeks.) Re:Because AOL mandates it (Score:2) So this is all bullshit. No Real Suprise Here (Score:4, Insightful) Of course, now that they're in the business arena where a few hours of downtime means more than wating till tomorrow to send that email to grandma, and lo and behold they just can't cut it. MSN has the same problems. No credible business can put up with their downtimes and outages. Now the executive level is beginning to understand how important these issues are. Someone could make a nice bundle of money by creating a credible business-class isp that doesn't suck (e.g. worldcom... generation d? yeah right). Re:No Real Suprise Here (Score:2) The community thing is important now, because there starting to platue, and there are more service that have relized most people want total automation, they don't care how its done, they just want it to be simple. Click mail button, get mail, read mail, go do something else. aol is easy as in beer. (Score:2) This is a very insightful comment. I wonder when someone will put together a scaled-down linux distro that competes with AOL. You'd have to have the free dial-up numbers, but maybe netzero would be willing to make a deal in exchange for some ads or something. Imagine putting in the disk, answering a few simple questions, and getting AOL level functionality (chat would be over IRC, AIM, etc.) You might even throw in a simple word processor, spreadsheet, media player, etc. I know that $20 a month isn't much money, but I would guess that a lot of people would rather not pay it to AOL every month. Then again, who knows if NetZero is still in business.. :) Re:aol is easy as in beer. (Score:2) If you've read the AOL/RedHat stories lately, you'll see that a number of us think AOL should put out their own distro, targetted at the older PCs families are now replacing. Something to turn them into an AOL kiosk, if you will, without all the hassles of putting out your own device a la the Gateway thing. Imagine the reduction in support costs when AOL owns the OS *and* the client? Done well, I'd give it to my grandmother. Anything to stop having to explain Application Execution Errors. Also, AFAICT, all the AOL dialup numbers are now PPP. Or so Windows reports a new PPP adapter with more recent versions. They've already leaked a Linux client for internal use only, so you know they've got some skunkworks going on. Inadequate? (Score:2, Interesting) Also, from what I remember of my AOL days (back when we used the "mm[1-9]" and "server[1-9]" chat rooms for our warez), the attachment limit is 18Mb. Has this changed? Or am I just remembering wrong? attachment size (Score:2, Interesting) Re:Inadequate? (Score:2) SENDING a large attachment via AOL isn't usually a problem. RECEIVING a large attachment via AOL can be a problem -- depending primarily on the POP you use as noted above, and somewhat on the version of the AOL client you use (there are lots of subversions of each major version, which can only be identified by the date and size of the installer -- some different ones have the same filedate). A classic "suit" decision (Score:4, Interesting) Even if they had switched in the long term, they tackled this project way too quickly (it's been just over a year since the merger went through) and it's glaringly obvious that they didn't think things through very well. Messaging on that kind of scale (multiple operating companies with differing hardware/OS standards, tens of thousands of employees) is not trivial to implement or manage and the suits upstairs should have either known better or had advisors to listen to who could have told them it was a bad idea. This'll probably wind up in a business textbook someday in the "how not to integrate merged companies" chapter. :D That's funny (Score:3, Funny) MSnbc huh? (Score:2, Troll) Later in the article.... A better solution for your e-mail needs is Microsoft service called Hotmail available at, and it's FREE! Classic Problem (Score:3, Interesting) Funny. With tens of millions of consumers having to relay upon AOL email that their internal business units find it "inadequate". It reminds of the dichotomy you find between "consumer" grade and "commercial" grade items, whether it be email systems or computer hardware or even construction. Consumer grade has always been so price conscious that quality suffers, where commercial grade is always more expensive. Software shouldn't have to be subject to the rule of this dichotomy, though. AOL should clean up their act and put some efforts into adapting some open source email solutions to make them scalable to 1e7 users and to put on the shiny EZ front end that their consumers have come to expect. Re:Classic Problem (Score:2) Software shouldn't have to be subject to the rule of this dichotomy, though. Why not? There is plenty of room in the marketplace, and the demand to support it, for a wide range of software from the same category. Consider databases: You have your cheap-o MS Access, suitable for a few users. Then you have Oracle, suitable for enterprise applications. One is a consumer grade product, the other professional. Re:Classic Problem (Score:2) Why not? Well, once Oracle has been written, why not sell an Oracle-Lite to the SOHO market. Would it really cost all that much to do so compared to gaining a foothold in the low level marketplace? Maybe I'm overlooking the costs associated with bringing out such a broad product line, or intangible costs such as a perception of Oracle being a lighter weight product if a cheap version is sold. Some products seem to possess a certain cachet that is related to the fact that you must pay a threshhold price to get them, but I would figure that IT buyers would not confuse an Oracle database with a Rolex watch. Re:Classic Problem (Score:2) Because creating a cheapo lite version of an existing product costs MORE money in development costs. Once you've got your App developed, just sell it to as many people as you can. If you're only selling a "commercial grade" product, charge a high price to recoup your costs. If you're selling to consumers, greater economies of scale set in, and you can lower your price for EVERYONE while still providing the original, full-strength product. It's not like making cars, where, if you're building 20 a year they can be of the quality of a lamborghini, but if you have to build 2,000,000 a year you have to make some concessions to quality and you end up with something like a Ford Taurus. +1 Intresting but Wrong (Score:2) Re:Classic Problem (Score:2) AOL Mail is designed to be a *simple* consumer email program. AOL cut the options and kept the thing as straightforward and easy to use as possible. Most consumers are quite happy with this arrangement since it meets their needs. AOL is happy because less options means less support calls when a user screws up. I don't see any shame in Time Warner using another solution. AOL has iPlanet and Netscape software which is more than adequate for business. The challenge is getting the topography and uptime, which is more of a tech support issue. Sanity Check (Score:3, Funny) Tragic! I thought that AOL was... (Score:3, Insightful) Of course, it probably didn't help that the reputation of people with the following addresses. (You know there is that stigma about people that use AOL.) Editor_in_Chief_Time@aol.com Technology_Correspondent_Time@aol.com Enough of the fun though. This problem is not an isolated incident with AOL. This type of thing is how most large businesses are run. Someone high-up gets this hairbrained idea and then pushes it through. Regardless of how inadequete the technology is and how difficult the transition can be. I work in a situation similar to that right now. It used to be that the outlying vendors, of this major corporation, used to interact with ordering replacement units, checking on warranty status and recieving corporate memos through a satellite connection on dumb terminals. Now, someone has gotten the bright idea that they need to change from dumb terminals, to having full blown MS Windows machines running a web browser to perform those same tasks. These days, the time to perform the simplest task takes nearly three times what it used to (For both relearning and simply downloading nearly one hundred times the old amount of data.) The other major problem is, instead of dumb terminals that the end-users are unable to fiddle with. They now have MS Windows machines that they are responsible to maintain, which is the farthest thing from their mind. To them, the new stuff is hard, slow and a royal pain in the rear. Unfortunately, someone got a bug in their rear to push forward this great new technology. So, that is what is happening. I can see them going back to the way it used to be in about 5 to 10 years, after they "recoup" the losses in development and find out how much money it is going to cost them to have phone support staff handle the call volume. -- .sig seperator -- Dogfood (Score:5, Interesting) Funny thing is, this Slashdot article is the first I've heard about switching back! Mega-corporation which will be crushed under its own weight? Naaa. I was getting sick of eating my own dogfood, anyway. Re:Dogfood (Score:2) AOL/Time Warner swears they'll eat own dog food (Score:5, Funny) What I'd like to know is... (Score:3, Insightful) Mail being lost, large attachments not allowed, being classified as a 'spammer' if you BCC to too many people... that sounds like a problem with AOL's mail servers. But the article seems focused on AOL's use of their new Netscape products (presumably NS 6.x), which doesn't really jive with the complaints in the article... Re:What I'd like to know is... (Score:5, Interesting) I left AOL before most of this actually hit production. But when I was there, the problem was basically this: - Wrong tool for the job. AOL mail, as many have said, was not originally designed to be a corporate server. AOL itself, minus the Unix geeks, has used AOL e-mail via the AOL client since about 1989. But TW was using a big groupware server (Exchange or Lotus or the like), with forms, workflows, the whole bit. To change over to a text-and-attachment-based system was foolish; to do it in a few months was absurd. Many of us fought the idea vigorously, but in the end, the merger logistics team won the battle in the name of dogfood. - Worse, what TW was using *wasn't* our dog food - that was the AOL client and servers, which is incredibly reliable and instantaneous for internal mail, and pretty darn good for Internet mail in the past few years - average delivery time in the seconds. But what TW needed to use was the IMAP gateway. The developers on that are excellent, but have never been given the time to really mature the product. Some major architecture changes kept getting pushed back for more urgent matters, both real and perceived. And while the IMAP server speaks nearly perfect IMAP, no client does; we didn't have the time or cooperation to figure out how to work around bugs in OE or Outlook. - It sounds like they were trying to use the Netscape client. As we all know, that's a couple revs behind Mozilla, and even Mozilla mail doesn't feel quite ready for prime time yet to me. - Obviously, Gerald Levin didn't want to be GeraldL982341@aol.com, so we tried to graft an aliasing system on top. Sounds from the "misdirected mail" like it either didn't work out or (more likely) was prone to user error. - tswinzig mentions the spam filters; that's a good point. I can see how they might have caused trouble, and by commingling internal and customer mail, you lose the ability to have the best configuration for each task. - However, the message limits and attachment-size limits would NOT be a problem. Those haven't been actual physical limits in years; they they are business rules and can be configured as needed. (Can you imagine how many copies of Windows XP would sit in people's mailboxes if every AOL member could send arbitrarily-sized attachments?) It's a shame. The AOL core mail system is actually much faster, more reliable, and cheaper to run than sendmail (if I do say so myself). But by putting TW on before it was ready, and before the resources could be committed to make it a first-class IMAP server, they screwed both TW and any chance of getting respectability as a business e-mail solution. Jay, the ex-AOL Mail Guy Heh (Score:2) Whats next? (Score:5, Funny) Some of the employees have even decided to spend time with their children reading books printed on actual paper. One employee has decided to start up a band with some of his cube mates. "Jim here and I have been neighbors for over 3 years and we used to e-mail all the time, but now that e-mail has become unreliable I've had to actually get to know him. He's pretty groovy." Re:Whats next? (Score:2) Yes yes yes! This is offtopic, but very important: the way tech is currently being implemented is highly anti-experiential. If the trend continues, we'll all be in little boxes watching video on demand, secreting bodily fluids for the purpose of reproduction when necessary to refresh the stock. It doesn't need to be this way. Community online can become community offline. Information can activate (agit-prop) as well as pacify (television). Rock out IRL. Fine but... (Score:2) So actually they weren't forced to use AOL email. Perhaps they were forced to switch from Outlook to Netscape email or some such thing. But this isn't as moronic as they make it sound - it's not that they switched their entire business over to AOL email. They just switched mail client programs forcefully from one that works to one that didn't work well. To be perfectly honest, Netscape email has never been too great, and it doesn't have the features for the office environment that Outlook or other "groupware" email clients have (scheduling, calendaring, task management). Clearly if they were using a recent version of Mozilla, they'd probably be using a good web browser with decent email facilities. But god knows, I wouldn't force the use of Netscape anything for email in a corporate environment. So fine, they made a mistake, clearly they weren't paying attention to the needs of email systems in a corporate environment, but they weren't making people use AOL mail, for god's sake. I could have told them that. (Score:3, Informative) When I got my first computer, I signed up for AOL because one of my friends had it and it was the only ISP I had heard of. (This was about five years ago, I was 17, so cut me some slack.:) I can honestly say that of all the things that eventually irritated me about AOL, the mail has to be the absolute worst. I don't know if they'll allow you to download it with a seperate program now, but when I had it you had to get the mail in the provided portion of the AOL...um... desktop? I'm not sure what to call it, since it took up most of my screen all the time. Anyway, I'm not surprised about misdirected and deleted mail. AOL would delete old mail at its own discretion after a certain length of time, and anything I wanted to save I had to manually cut and paste as a text file because there was no good, clean way of backing anything up. The fact that AOL mail reads HTML by default is terrible; the fact that it doesn't educate the users or explain to them the concept of HTML mail is even worse -- half the things you get from other AOL members are yellow text on a hot pink background just as bad as any poorly made Geocities page (they even let you use images as backgrounds for mail). The fonts and colours may or may not show up when sending the mail to addresses outside AOL. The "unsend" feature is just a bad idea all around. I remember being frustrated with the attachment limits when trying to send ZIP files of artwork to my friends. One of the most irritating things at the time was that AOL refused to open/read many MIME types of attachments, so when someone not on AOL sent me a file, nine times out of ten I couldn't open it. I fail to see how AOL mail could be useful to anyone except the most basic internet users. I also fail to see how anyone with any amount of intelligence could think it capable of being used for anything more. I, by no means, use e-mail at any kind of a "corporate" level (I get maybe two dozen messages a day at the most), and it wasn't even adequate for my purposes. As an AOL/TW Employee (Score:5, Informative) We have actually been setting up some Sun Enterprise 280R's this week to solve this problem... The thing is, EVERYONE here knew this was going to happen, but office politics are to blame. Re:As an AOL/TW Employee (Score:2) Eat your own dogfood, but on an enterprise level. Your classic case of Executive Shielding (Score:5, Interesting) How many people here thing that Mr. Pittman ever had a problem with his AOL mail? I'd bet dollars to pesos that anyone at AOL with a capital "C" in their title has their e-mail running off their own custom-built server. This was literally the case for one fortune 500 company I contracted for. The CEO/CIO/CFO had their own Compaq Proliant server fully loaded (for the time). It was segregated from the other machines and was constantly watched by at least one Network Engineer. The rest of the company was subjected to constant crap in switching from AT&T outsourcing of e-mail service to in-house properly deployed UNIX solution, then someone falling for the Netscape sales pitch and switching to that, then Microsoft saving us from Netscape by bringing in Exchange, then ended up having Exchange do the mail but Netscape do the directory services...etc. But the top right wing with all the mahogany furniture never once had a problem with their e-mail. Because of the aforementioned dedicated server which, as far as I know, was running the original UNIX solution and never got touched. The problem is that this solution can't be applied on a large scale. I think the Steve Case and company probably have (knowingly or unknowingly) been the victims of executive shielding. The people whose jobs rely on their satisfaction would be fools not to. But then along comes some Time Warner company. The AOL brass aren't going to recommended Executive Shielding because they probably don't know about it. The AOL techies doing the shielding aren't going to tell their Time Warner opposites because they don't report to Time Warner. And the Time Warner techies are going to walk naively into the situation and get their asses blamed. But after a year of fired techies you eventually figure out that maybe the problem isn't the staff, it's the damn product. Well that's just my impression anyway. But I wouldn't be at all surprised if it were true. I wonder how many people at Time Warner lost their job because they couldn't get a square peg through a round hole for Time Warner management. They never knew the answer was to use one of those new round holes with four corners. - JoeShmoe . Re:Your classic case of Executive Shielding (Score:4, Insightful) How much you want to bet? It ain't so. They run the AOL client and read mail off the AOL servers, and have ever since AOL migrated off QuickMail around 1989. The problem is not with the AOL mail system per se, but with a total system that just doesn't fit together. See my post above. Jay "Chief Architect begins with a capital C too" Levitt. It takes a brilliant and humble executive to basically force himself not to take advantage of the special treatment offered him. At the Fortune 500 company I was talking about, the CEO would eat at the cafeteria and would even sit down and have lunch with people from the mailroom. Just a regular ol' guy. But then all it took was for his laptop to freeze up once during a presentation and all hell broke loose in the IT department. Less than a week later, we had a new Director with a sudden focus on deploying Windows NT right now even on laptops which everyone knew basically weren't built for NT (power saving, USB, port replicators, all of them threw NT for a loop). So, I don't know. I still believe that at any major corporation the executives have no idea what technology is really like in the trenches, hence Executive Shielding. - JoeShmoe .. Yeah, at my Uni there were always complaints about the campus shuttle bus service, and the clamor finally got so loud that the top adiministrators decided to "see for themselves" and arranged a date when they would all go down to a certain stop and wait for a bus. Can you believe it? A bus showed up almost instantly, and they therefore declared that there wasn't any problem. My own experience was an expected 45 minute wait for a bus scheduled to come every 7 minutes. Re:Your classic case of Executive Shielding (Score:5, Funny) Because I wrote the mail system. Jay Sorry, but.... (Score:2) DAMN!!!!!!!!! Re:Your classic case of Executive Shielding (Score:5, Informative) Are we both talking about the world's largest mail system, the one that handles over 3,000 pieces per SECOND in a single namespace, that blocks a hundred million pieces of spam a day coming FROM the net, that hardly lets any spam out TO the net, that sends intra-AOL mail, with zero loss, live bad-address feedback, and two-phase commit in under a second, that scales better and cheaper than sendmail and qmail and zmail and imapd and Critical Path and PostOffice and every other COTS server, that can route itself around nearly any kind of hardware or network or even site outage without even queueing transactions, that can manage each mailbox redundantly across multiple sites, that has been the single biggest hardware installation of any fault-tolerant platform it's run on, that allows every piece of hardware and software to be replaced with the system up, that is more tunable than a Steinway and more monitorable than a T22, that is the ONLY large mail system that's been running outage-free since 1998? The only balls it took were for me to appear to take full credit for something that I only rewrote, not wrote, that was later rewritten again by the highly talented development team I hired, and that was maintained and improved throughout by an equally talented sysadmin team reporting to my counterpart in operations. I'm sorry if it's not skinnable or buzzword-compliant or 1337 or free (as in bird). There are lots of end-user features that I wish it had, that might have made it more suitable for TW, but that the business folks prioritized below other features. And keeping a high-effectiveness, low-collateral-loss spam filter working when you're the spammers' biggest target is a 24x7 battle of impossibilities. But from an engineering perspective? Every vendor, every contractor, every partner who has seen the design of this system knows there's no other mail server that even comes close. HP once told us: "You don't push the envelope. You perforate it." You should do so well. Re:Your classic case of Executive Shielding (Score:2) Don't bet on it. Techies are easily replacable, they react in satisfying ways when you do nasty things to them (like fire them or yell at them), and they have a tendancy to say "Yes boss" when they figure out that saying "Yes boss" is a better survival skill than telling the boss exactly why his stupid idea is, well, stupid. And that's not to mention how technologically clueless many higher-ups are. (Think of Dilbert's pointy-haired boss and remember, Dilbert isn't a comic strip, it's a documentary.) Contrast that with computers that sit there and just silently, unblinkingly do what you tell them to, whether or not that was what you actually wanted them to do. They don't react at all to tantrums or threats, and besides, it has to do what the boss thinks it should be doing -- the salesman said so! They used AOL's *public* mail servers? (Score:2, Interesting) Someone mentioned that they could use iPlanet and still be eating their own; this is good, but not what they're breading their butter with... Why wouldn't they appropriate some mail servers - running the same code & on the same platforms as their public servers - but keep them for IUO? This way, they're finding - and, with hope, trouncing - any bugs or general nonsense and instability, while at the same time, not subjecting their business to all the Herbal Viagra and natural breast augmentation adverts we've come to expect in userx093jr7@aol.com inboxen. S Spammers = Corporate Executives????? (Score:5, Funny) This is BAD THING??????? This "feature" should be used as a management training tool. Re:Spammers = Corporate Executives????? (Score:2, Interesting) Actually, the quality of the information does seem inversely proportional to the cross-section of the corporation that it's distributed to. This was a big problem where I work too. Eventually we switched to a system where a weekly mail is sent out that summarizes all the various memos, with links to the full story for each, so we can avoid reading about reorganizations that we don't care about. It's not perfect, since some brass still abuse the system, but it's better than it was. Efforts to get management to understand that announcements work best via internal newsgroups rather than by email have so far been unsuccessful. Remember: "...They've struggled long and hard to be able to turn on and turn off Windows and MacOS machines." Thye did it to Compuserve (Score:3, Informative) Problem was that it never got better. Basic features of mail clients were discarded as not nessesary for the typical AOL user. And then of course they created the "IMAP" interface to their mail system. Except it was IMAP without any of the features of IMAP. Their implementation was essentialy a POP3 interface running on the IMAP ports. Re:Thye did it to Compuserve (Score:5, Informative) Actually, no. The core design of the AOL mail system is, coincidentally, a near-perfect fit to the IMAP disconnected model, with unique message IDs, per-part fetching (text vs. attachment), efficient indexes to read less-efficient messages, host-based storage, etc. It is NOTHING like POP3. In fact, as I recall, CS begged us to develop a POP3 server instead of IMAP, since CompuServe Classic had one, and we declined. The main problems were that (a) some aspects of MIME were never fully integrated into AOL mail, and (b) *every single* IMAP client is buggier (wrt protocol implementation) than you can possibly imagine, and we never had time or cooperation to work around all the bugs. I'd be curious to know which features you felt were 'discarded'. Aside from POP3, I don't remember declining any strong requests from CS while I was running the mail team. Why not use Netscape Messaging Server? (Score:2, Insightful) As an AOL/TWC employee (Score:3, Interesting) And the other giggle. When a corporate announcement is sent out to the AOL Mail, one of the admin assistant's cut-and-pastes it into an email and sends it out to our everyday email account. If it wasnt for the free cable and RR acccounts.... Re:As an AOL/TWC employee (Score:2) Hey, just like the on-call instructions. Are Sun's lawyers drooling over this one? (Score:2) Sounds like a monopolistic, anti-competitive practice to me if I've ever heard of one. Re:As an AOL/TWC employee (Score:2) May I just take this opportunity to say.... (Score:2) Everyone on the planet who has an IOTA of common computer sense knows that AOL's consumer services are below average. How did they think they could handle corporate email services? Even software like Outlook, which is specifically designed for this type of big-business structure, has trouble handling huge amounts of email (its not so much the amount of email thats the problem as much as the lack of security in the product. Oh wait, AOL doesn't do security well either.). Why on earth did AOL think it could scale up to fit business needs? The requirements of John Q. Local User are far less than those of Mr. Corporate. They should have seen it coming. Simpsons Moment! (Score:2) Xentax Do these people not have FTP? Is their IT department asleep at the wheel? Re:E-mail for magazine proofs and large files? (Score:5, Interesting) Don't blame the IT people for this. An FTP site that is easily accessible by internal prepress production and the outside designer isn't a guarantee that anyone will have a clue how to use it. I'm the "IT guy" (heh...) at a mid-sized commercial printing company. We have an easy-cheesy FTP set up that drops the files right on our proxy server. We have a link to the FTP site from the home page of our web site. (Plus our domain name is...oddly enough...the one-word name of the company.) Even the most file transfer impaired have all sorts of options to get large files to us. We're even going to go to some sort of on-line proofing system. Bet that'll be a can of worms Can people get us large file? Hell yeah! Do they? Huh? Hell no! "What's FTP?!" The problem is usually on the designer/ad agency end. I say "usually" because the folks here are *paid* to be technically savvy. If they can't retrieve a file off of our FTP site or any other, they probably should look for another job. The outside customers get scared if you tell them they have to type in a user name and password. Or if you tell them that apparently *their* firewall isn't letting them out, they drop back to a safe position like... And even that can be problematic. Things that we think are simple - compressing files, especially fonts; naming conventions that make sense; resolution issues - become a Big Deal. On the other hand, that's what we're paid to do, troubleshoot, help, smile, be happy, offer fries with that... I for one am glad AOL-Time Warner is eating their own pooch chow. Now I'll have even more ammo for my whining AOL customers. "I'm trying to send this, but YOUR email server says it's too big." MY email server can take it, baby! Re:E-mail for magazine proofs and large files? (Score:2) Re:E-mail for magazine proofs and large files? (Score:2) File transfer by email doesn't make sense when the files start to get bigger than a couple megs... Re:E-mail for magazine proofs and large files? (Score:3, Informative) I think your missing the point. Why go to the expense of developing and maintaining that solution. Why reduce yourself to a system with 3 points of failure (intranet, ftp, email). An attachment in email does the job just as well, and it's simpler and less time consuming for everyone. An ftp server is a good way to distribute the same file to many people. If you're going to send different large files to different individuals, it's not the right solution. business use (Score:2) Slashdot auto-rejects submissions? (Score:2, Offtopic) 2nd hand story (Score:2) I don't understand why AOL/TW didn't plan a little ahead, made a case study and allowed for some time to do a smooth migration. This way it had to blow up in their face and make their own service look bad. But maybe this has the positive side effect that AOL works at the quality of their service. The bad thing about this is, that in the process netscape/mozilla also looks bad, when it's really not the software at fault. Re:2nd hand story (Score:2) Maybe this explains AOL's interest in Linux? (Score:2, Insightful) Re:Maybe this explains AOL's interest in Linux? (Score:2) Sorry, Linux has what to do with mail server and client software? What really happened... (Score:2, Funny) Embarassing for AOL, but... (Score:2, Interesting) ...but every time someone slams AOL, they're essentially saying "Go MSN!". AOL has been pretty benevolent so far - vastly more so than microsoft. They deserve to be treated well until they let us down in a big way. Because AOL is our greatest hope in the battle against microsoft. They can single-handedly win the browser war against microsoft, among other things. had similar problems w exchange (Score:2, Interesting) A conflict of interest? (Score:3, Interesting) AOL is #1 in number of customers. They have the largest email system in the world. Time and AOL merge. No problem. AOL says: "Time, you gotta use our email system because we're the best. It will look good too!" Time: "Sounds great!" AOL: "We'll just take our existing consumer client and tweak it for business use. See, it is so easy, no wonder we're #1!" Time: "Uh, we can't send our large attachments which are vital to our company." AOL: "Oh, well that's because..." Time: "Our "tweaked" clients keep crashing too!" AOL: "Well, it wasn't..." Time: "2% of our emails aren't getting through" AOL: "Well, our system wasn't designed for this" Time: "How did you become #1 again?" I am pretty sure that this is going to tarnish AOL's image for being reliable. Especially since they've just gotten over the "busy-signal fiasco" of a couple years ago. If Time can't trust AOL with important emails, then how can AOL expect consumers to trust them with important emails as well? I like to think that my local ISP (or any local ISP) has better service than AOL any day. top down decision making - "going to Tahiti" (Score:2, Informative) My favorite expression for these kind of top-down decisions, that essentially come down to "because I said so!", is: "are we discussing this, or are we going to Tahiti." I picked up the expression from this John Soat column [informationweek.com] where he told a story about the GAP and their decision to replace Lotus Notes with Exchange. Note entirely AOL Email... (Score:2, Informative) According to the article:"The various types of e-mail software used by employees aren't the same as those used by America Online subscribers at home. Instead, the divisions customized AOL products, such as those from its Netscape unit". So, while this really sucks for AOL, it's not as bad as some people think. On the other hand, I work L3 tech for a web host, and we hear almost daily from AOL (l)users about messages being forwarded to AOL accounts and being lost forever, or showing up weeks later. Re:You've got mail! (Score:3, Funny) You've got mail! You've got... You've got... You've... You've... You... This program has performed an Illegal Operation and will be shut down. Re:Look who is talking... (Score:5, Informative) It says so right at the top. MSNBC generally carries Wire stories. good kneejerking, though. Re:Look who is talking... (Score:2, Insightful) Re:Look who is talking... (Score:4, Funny) Check the byline of the authors. Re:Look who is talking... (Score:2) MSNBC report system not up to grade. After several complaints to the lack of news being generated using the internal MSNBC Reporter (tm) application top executives decided to look at alternative systems for getting their news. "We've had great luck with the AP System and the WSJ System for delivering timely and interesting articles. If this trial is successful, we'll phase out the entire internal staff and use these TPNA's (Third Party News Applications) to provide all of our reporting content," quoted one anonymous executive. But seriously, using AOL mail for corporate business would be like using Hotmail for running a company. They just weren't designed for the task. Somewhere deserves a giant "what were you thinking" slap upside the head for the original decree. Re:Look who is talking... (Score:3, Insightful) 1. They not only didn't read the article (it says Wall Street Journal), the ADMITTED it in the post. 2. It's really clever to use an "$" instead of S in MS right? Huh? Get it? 3. Everyone knows MSNBC has been lauded for being a surprisingly unbiased source for news about Microsoft anyway. Much better than, say, ZDnet. Get a clue. Re:Now all they have to do (Score:2) *yawn* Re:Now all they have to do (Score:3, Funny) Ewww... don't we get enough SPAM from AOL already? Re:Bad Time Warner. (Score:3, Insightful) If you're a troll, I'm insightful. Re:Bad Time Warner. (Score:2) 2. The TW part isn't exactly going to fall over due to random *not* credible legal threats. Criticism, in general, has NOTHING to do with DMCA. Leaking proprietary information that was only obtained through breaking access controls does in order to achieve unauthorized access to copyrighted information, as does leaking information which itself facilitates breaking access controls. So, incidentally, does merely selling a service with the claim that it helps to do so. But if you believe that the DMCA is an all-purpose anti-criticism law in contravention of the First, then either a) you're an idiot for posting about it without reading it, or b) you're an idiot for posting about it without understanding it. Re:Ted Mail (Score:2) Wasn't that an IBM commercial? Man, I miss AdCritic. Re:such b.s. (Score:2) I find that owning my own domain name, even if i am the only one with that account, is the best way to secure a really permanent e-mail address. No matter what happens, I own that domain and the address. I have the e-mail hosted for a reasonable price somewhere and that mail gets forwarded to my ISP account automatically. br It works really well, costs hardly anything, and is really effective at combating this problem you speak of.
https://slashdot.org/story/02/03/22/140230/time-warner-finds-aol-email-inadequate
CC-MAIN-2017-22
refinedweb
7,777
71.14
Front-end development is one of the fastest evolving aspects of modern web development. It seems like there is a new framework or methodology every other week built to solve the issues around this relatively new technical area. In the dark ages of web development, front-end development was something either flogged off onto over-burdened designers or hacked on by exhausted software developers. Not ideal, and unfortunately many web projects are still scattered with the results of this way of thinking. This simple Venn diagram pretty much sums up the situation… Those were grim times. Fast-forward to the present day and look at the tools and resources we have available. At Raygun, we’re dedicated to producing design and code of the highest standard. This permeates into how we approach our workflow. We’ll look at: - Four key areas of a front-end workflow: - Design - HTML and CSS - JavaScript - Post-deployment maintenance - How to make front-end development accessible to all members of your team - How these tools improve code quality, help to reduce bugs in a web application, and generally result in a higher quality product Let’s dive in… 1. Design and Front-End Development At Raygun, we’ve introduced two web-oriented design tools into our workflow: Sketch and Zeplin. We won’t go into great detail about these, but we feel they are vital to our front-end development process. Here’s a brief summary of each for context: - Sketch is a digital design app built from the ground up with the web in mind - Zeplin is a collaboration tool to share designs across a team These tools are not only great for cutting down design time, they also make it easier to extract resources, ascertain dimensions and are largely web-focussed. No more pt to px conversion, inconsistent rendering of fonts, or soul-crushing frustration of building something from an out-of-date design mock-up. Sketch makes designs easier to work with, Zeplin lets you measure and extract assets from an up-to-date mock-up. 2. HTML And CSS There have been a few CSS methodologies around for a while now: - OOCSS - SMACSS - BEM When followed closely, the first two in this list have been used to great success in web design. But when it comes to building apps in a large team of engineers, BEM is by far the easiest and most scalable methodology to follow. At Raygun, we use BEM to structure our markup and our stylesheets. BEM = Block-Element-Modifier The Ground Rules Naming conventions You can essentially use any combination of dashes or underscores to split up your elements and modifiers, that’s really just a matter of preference. Here is how we name our components: - block - block__element - block__element--modifier Blocks can contain only one level of child elements JavaScript-oriented selectors are prefixed with js-, and are not referenced in the CSS That seems like a fair bit to take in, so let’s consider the following example: <!-- HTML --> <div class="module"> <div class="module__header module__header--alert"> <h2>User behavior</h2> </div> <div class="module__body"> <div class="chart"> <div class="chart__chart-container"> <div class="js-chart"></div> </div> <div class="chart__metrics"> <div class="js-chart-metrics"></div> </div> </div> </div> <div class="module__footer"> <p>...</p> </div> </div><!-- HTML --> /* CSS */ /* Block */ .module { border: 1px solid grey; font-size: 1rem; } /* Elements */ .module__header { padding: 0.5em; border-bottom: 1px solid grey; } .module__body { padding: 0.75em; } .module__footer { padding: 0.5em; border-top: 1px solid grey; } /* Modifiers */ .module__header--alert { background-color: red; color: white; } /* Block */ .chart { border: 1px solid grey; padding: 0.75em; display: flex; flex: 0 auto; flex-flow: row; } - BEM makes CSS easier to read, more modular and less ambiguous - Flat CSS means no more nested rules the length of your arm, no more ugly !important tags and, most importantly, no more inheritance wars with other developers - JavaScript DOM changes are completely independent to presentation, which follows the progressive enhancement pattern - HTML blocks can be rendered anywhere, and have no dependencies on other blocks If the rules of BEM are followed closely, every member of your team can easily make changes to your application’s front-end without fear of unexpected consequences. Bonus points: Set up KSS with Grunt or Gulp to automatically generate a living style guide as you write your CSS. This can be enormously helpful for designers and developers as a design reference for every block and component of your application. 3. JavaScript In Your Front-End Development Process JSPM Let’s continue looking at our example and add a bit of functionality with the help of this relatively new tool. The JavaScript Package Manager allows developers to easily include remotely hosted packages and plugins. Packages are loaded into your project with SystemJS (a polyfill for the ES6 module loader – coming soon). It also handles bundling for extra optimisation. JSPM simplifies your JavaScript workflow, helping developers to write better code by following modern best practices. Thanks to its flexibility, it can be introduced into a project at any point in its life-cycle. Let’s have a quick look at how it works: 1. Install jspm # Install the CLI $ npm install jspm -g # Navigate to your app $ cd ~/path/to/app # Install jspm in your app directory $ npm install jspm --save-dev # Initialize jspm (hint: If running locally, set baseURL to "./") $ jspm init 2. Add Some Code For this example, I’ve created the following files: index.html assets/css/main.css lib/main.js lib/charts.js data/dummydata.json In main.js: import {charts} from './charts'; charts(); Now we need to write a charting library… Or, maybe we should just use an existing one. For this, let’s use C3. $ jspm install c3 Note: I’ve loaded in the C3 stylesheet from a CDN Then let’s wire up our chart in charts.js: import c3 from 'c3'; export function charts() { const errorChart = c3.generate({ bindto: '.js-chart', data: { x: 'date', y: 'errors', url: './data/dummydata.json', mimeType: 'json' }, zoom: { enabled: true }, axis: { x: { label: { text: 'Date' }, type: 'timeseries', tick: { format: '%d-%m-%y', fit: true } } } }); } In the <head> element of my index.html file: <script src="./jspm_packages/system.js"></script> <script src="./config.js"></script> <script> System.import('./lib/main.js'); </script> 3. Reap the benefits Notice how everything just works? That’s all thanks to SystemJS. So that is a very simple example, and I wouldn’t say it really showcases the exciting new language features of ES6 very well. To fully understand and appreciate what we’ve accomplished here, we’ll need to look at the Chrome dev tools’ Network tab: SystemJS has done a fair bit of heavy-lifting here. - It’s worked out that we want to write some fancy ES6 flavored JavaScript and loaded in Babel to transpile it for older browsers. - It’s seen that we’re importing in the C3 library and loaded that in too plus its dependency – D3.js. - It’s doing it all asynchronously, which will cut down on page load time! I’ve barely scratched the surface on what jspm can do for your workflow, try it out for yourself. 4. Post-Deployment Maintenance So you’ve got your designers whipping up mocks in Sketch and sharing them with Zeplin, the whole engineering team are following the BEM methodology, and you’ve brought your JavaScript code-base into the 21st Century with jspm? All these workflow improvements will help your team to produce higher quality code faster. But, what about after deployment? How does any given user experience your application? How do you measure client-side performance across all pages and assets? Don’t worry, we have an answer to all these questions! Raygun Pulse is a real-time user monitoring solution to track, measure and drill down into your application’s performance. It also gives you insights into how your users are accessing your app with browser, device and location metrics to help developers ensure all users are getting a great experience. You’ll make your front-end development process a breeze! Sign up for a free 30 day trial of Pulse today! {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/a-new-workflow-for-front-end-development
CC-MAIN-2017-22
refinedweb
1,374
54.42
91 Asynchronous programming is a broad topic with many facets but its importance is hard to overstate. Even the simplest of applications often has functionality that, if not implemented asynchronously, is unusable or, at best, inefficient. For C# developers, a working knowledge of the async and await keywords is, therefore, essential. But the functionality provided by these keywords would not be possible without .NET's Task Parallel Library (TPL). For that reason, an understanding of the TPL is fundamental for anyone interested in professional asynchronous programming with C#. The TPL is a set of software APIs in the System.Threading.Tasks namespace of .NET. It was originally introduced with version 4.0 of the .NET Framework. Previous versions of .NET had a number of other APIs enabling asynchronous operations but they were inconsistent, cumbersome to use, and did not have built-in support for commonly needed features such as cancellation and progress reporting. Furthermore, the TPL enables a level of control and coordination of asynchronous operations that is difficult to achieve if developers try to implement such features themselves. First, a quick note on terminology: while asynchronous programming and multithreaded programming are often mentioned in the same context, they are not the same thing. Asynchronous programming is a bit more general in that it has to do with latency (something on which your application has to wait, for one reason or another), whereas multithreaded programming is a way to achieve parallelization (one or more things that your application has to do at the same time). That said, the two topics are closely related; an application that performs work on multiple threads in parallel will often need to wait until such work is completed in order to take some action (e.g. update the user interface). So, this idea of waiting is the more general characteristic that is referenced by the term asynchronous, regardless of thread count. What does all of this have to do with the TPL? Well, the TPL was introduced to address parallelization, hence the name Task Parallel Library, so many of its APIs deal with concepts that are specific to multithreaded programming. But, as we have learned, the requirements for multithreaded programming are very similar to that of asynchronous programming in general. The TPL took advantage of this fact and introduced a beautiful abstraction called a Task, that can be used for anything that the application needs to wait for. Need to perform some complex CPU-intensive operation on a separate thread? That is a task. Need to download something from a remote network? That is also a task. Local I/O operations such as saving files to disk can also be represented as tasks. You can even aggregate multiple disparate tasks (some involving threads and others not) and wait for them all as if they were a single task. Let's consider an example to see the TPL's Task in action. Suppose you are writing a .NET Core console application that will process a remote image. Let's say you need to download an image from the Internet, apply a blur to that image, and save it to disk. Now, normally it's fine for console applications to be synchronous, but let's say that you want to have a real time dashboard that is constantly updating with milliseconds, e.g. 1 2 3 4 5 6 while (!done) { Console.CursorLeft = 0; Console.Write(System.DateTime.Now.ToString("HH:mm:ss.fff")); Thread.Sleep(50); } For such a dashboard to stay reliably up to date, you'll need I/O and image manipulation operations to happen asynchronously. Using the TPL, you can accomplish that by performing such operations in methods that return a Task: 1 2 3 4 5 static Task<byte[]> DownloadImage(string url) { ... } static Task<byte[]> BlurImage(string imagePath) { ... } static Task SaveImage(byte[] bytes, string imagePath) { ... } Notice how Task can have a generic parameter T when you want to return something for a particular Task. In this example, for both such methods you want to return the byte array of the image downloaded or blurred. In the case of our SaveImage method, the image data is written to disk and there is nothing returned. Now for the main part of our code, where we call said functions. Assume that we're working only with JPEG images. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 bool done = false; var url = "";); SaveImage(blurredImageBytes, blurredImagePath).ContinueWith(task4 => { done = true; }); }); }); }); while (!done) { /* update the dashboard */ } Console.WriteLine("Done!"); Notice that for each Task we are adding what's called a continuation using a function called ContinueWith. The continuation is a new task and is started automatically by the TPL when the antecedent (i.e. previous) task completes. So, we've defined a chain of actions up front, and the TPL monitors and coordinates when to invoke each action. Execution of the application continues through the task definitions quickly, proceeding to the dashboard's while loop at the bottom. Since we're performing all expensive and latent operations asynchronously with a task, each of those tasks can take as long as it needs without affecting the real time updates of our dashboard. Does that mean that each Task runs on a separate thread? To truly know the answer to that question, we would need to look at the implementation of the DownloadImage, SaveImage and BlurImage methods. That said, the beauty of the Task abstraction means that, for the purpose of the calling code we've written here, we don't need to know. We can take our example one step further by doing the same thing, but for multiple images. In that case, we would want to wait until all of the images are processed before exiting the application. One way to accomplish this would be to save a reference to each of the last tasks in the chain, namely the tasks that correspond to saving each blurred image. If we maintain a list of those tasks, when we get to the last image we can use Task.WhenAll to aggregate all of them into a single task, to which we can again add a continuation via ContinueWith: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 var saveBlurImageTasks = new List<Task>(); foreach (var url in urls) {); var saveBlurImageTask = SaveImage(blurredImageBytes, blurredImagePath); saveBlurImageTasks.Add(saveBlurImageTask); if (saveBlurImageTasks.Count == urls.Count) { Task.WhenAll(saveBlurImageTasks).ContinueWith(finalTask => { done = true; }); } }); }); }); } As you can see, the TPL consists primarily of the Task class and associated functions. So far we've only scratched the surface of what is possible with the TPL. There are a number of additional static methods in the Task class, some of which provide additional operations for sets of tasks. But, even for a single task, you can customize quite a few different aspects of its behavior. For example, if you would like to perform a continuation conditionally depending on if a task failed, was canceled, or completed successfully, you can do that by providing your selection of TaskContinuationOptions to the ContinueWith method. There are a number of optimizations that can be configured with that enum as well. You can also control if, when, and how tasks correspond to threads. For example, you can create your own implementation of the TaskScheduler class and customize how tasks are queued onto threads. You can also specify if you want a continuation to run on the main application thread, even if the antecedent task ran on a thread from the thread pool. Finally, as hinted earlier, the TPL enables consistent cancellation via what's called a CancellationToken throughout its APIs and progress reporting is possible using an interface called IProgress<T> that was introduced in version 4.5 of the .NET Framework. The TPL has a very powerful set of APIs, but its extreme flexibility can have some drawbacks. As an example, let's look briefly at exception handling with the TPL. Tasks completely encapsulate their exceptions, meaning an exception that happens in a task's code does not interrupt execution of your application, so you can't just use try/ catch from the caller. Instead, you must inspect the completed task status and other properties to see if it faulted and why. In complex applications with high degrees of parallelization (i.e. many threads running simultaneously), this exception encapsulation may be exactly what you want. If the task encountered any exceptions, an exception of type AggregateException will be set. You can iterate through the InnerExceptions of the aggregate and react accordingly. 1 2 3 4 5 6 7 if (task.Status == TaskStatus.Faulted && task.Exception != null) { foreach (var ex in task.Exception.InnerExceptions) { Console.WriteLine($"Exception: {ex}"); } } Developers getting started with the TPL are often confused when their application behaves unexpectedly without any indication of an exception, so be sure to keep that in mind. You will almost always want to add some sort of logging, at a minimum. Another aspect of the TPL that is less than ideal is that, in order to get a task's result, you typically need to set a callback—a method that is called when the task completes. The continuation lambdas we set via ContinueWith above are examples of this. The callback is a tried and true pattern used in asynchronous programming but, as we saw in our example, it can be a bit hard to read since each callback is indented and marked with additional braces and parentheses. Fortunately for C# developers, the async and await keywords were created in part to alleviate that exact problem. The Task Parallel Library has proven itself to be extremely important. Not only has it made asynchronous programming more consistent, reliable and flexible for C# developers, it has also provided the foundation for a revolutionary approach to asynchronous programming at the language level, namely C#'s async and await keywords. The next guide in this series will explore how async and await built on the Task Parallel Library's success to make asynchronous programming even better. 91
https://www.pluralsight.com/guides/async-programming-task-parallel-library
CC-MAIN-2020-24
refinedweb
1,706
53.51
Code Safari: Linguistic Analysis with Lingua Free JavaScript Book! Write powerful, clean and maintainable JavaScript. RRP $11.95 Welcome to Code Safari. In this series, Xavier Shay guides you through the source code of popular gems and libraries to discover new techniques and idioms. On another blog I write for, I was curious about calculating some statistics on the readability of my writing. How does it stack up on the Flesch-Kincaid scale? How long were my articles? How did I compare to my co-author? I love this sort of problem—not necessarily that interesting, but possibly achievable within a small enough time frame to make it worthwhile. Even without a useful output, it’s a perfect training problem to flex your programming muscle on. There are two steps to the process: massaging the data into a suitable format for processing, then generating statistics from that data. I have tackled similar problems in the past, so had a good idea where to start from. This familiarity with existing libraries of your language(s) is argument alone for trying any crazy experiment that comes into your head. I use nanoc to compile the blog, and my source data was in the form of Markdown files with a YAML preamble. Here is a sample document: --- title: My Blog Post created_at: 2011-04-01 10:00 --- Indubitably I am writing a blog! puts "This is code and shouldn't be included" This is the conclusion of my fascinating blog. Ruby has a great library for parsing Markdown (actually it has a few!) called kramdown. To be able to use it though I first had to extract the meta-data (title, created at) and strip it from the document. This may not have been too hard, but why write your own parsing algorithm when someone else has done it for you? Nanoc must have some code somewhere to do this already… I unpacked the nanoc source tree and went spelunking. Nanoc doesn’t use YAML for much, so I reasoned that it might be a good thing to search for. $ gem unpack nanoc $ cd nanoc3-3.1.3 $ ack YAML lib/nanoc3/base/ordered_hash.rb 172: YAML::quick_emit(object_id, opts) {|emitter| lib/nanoc3/base/site.rb 369: @config = DEFAULT_CONFIG.merge(YAML.load_file(config_path).symbolize_keys) lib/nanoc3/cli/commands/create_site.rb 11: # Converts the given array to YAML format lib/nanoc3/data_sources/filesystem.rb 86: meta = (meta_filename && YAML.load_file(meta_filename)) || {} 233: meta = YAML.load_file(meta_filename) || {} 255: meta = YAML.load(pieces[2]) || {} lib/nanoc3/data_sources/filesystem_unified.rb 85: io.write(YAML.dump(meta).strip + "n") lib/nanoc3/data_sources/filesystem_verbose.rb 18: # or the layout’s metadata, formatted as YAML. 61: File.open(meta_filename, 'w') { |io| io.write(YAML.dump(attributes.stringify_keys)) } $ YAML.load_file(meta_filename) seems like a good candidate to me, and the file name ( data_sources/filesystem.rb) is even more promising. Cracking open the file we find a method that does exactly what we want. It’s a bit long with all the error checking, so I’ll only include an edited version here: # nanoc/lib/nanoc3/data_sources/filesystem.rb # Parses the file named `filename` and returns an array with its first # element a hash with the file's metadata, and with its second element the # file content itself. def parse(content_filename, meta_filename, kind) data = File.read(content_filename) pieces = data.split(/^(-{5}|-{3})s*$/) meta = YAML.load(pieces[2]) || {} content = pieces[4..-1].join.strip [ meta, content ] end I copied this entire method verbatim into my script, with a reference to its source location in case I needed to go back to it. For a quick prototype script like this one, my goal is to get it working as quick as possible. Any thoughts on code reuse or architecture can be suspended for the moment. Using this method, we can take the first step in constructing our parser: require 'kramdown' files = Dir["content/articles/*.md"] files.each do |file_name| meta, content = parse(file_name, nil, nil) doc = Kramdown::Document.new(content) puts doc.inspect end The inspect output, while dense, gives valuables clues as to the next step. We want to exclude any non-text elements (such as the code block) from our statistics. <KD:Document: options={:template=>"", :auto_ids=>true, :auto_id_prefix=>"", :parse_block_html=>false, :parse_span_html=>true, :html_to_native=>false, :footnote_nr=>1, :coderay_wrap=>:div, :coderay_line_numbers=>:inline, :coderay_line_number_start=>1, :coderay_tab_width=>8, :coderay_bold_every=>10, :coderay_css=>:style, :entity_output=>:as_char, :toc_levels=>[1, 2, 3, 4, 5, 6], :line_width=>72, :latex_headers=>["section", "subsection", "subsubsection", "paragraph", "subparagraph", "subparagraph"], :smart_quotes=>["lsquo", "rsquo", "ldquo", "rdquo"]} root=<kd:root nil {:encoding=>#<Encoding:UTF-8>, :abbrev_defs=>{}} [<kd:p nil [<kd:text "Indubitably I am writing a blog!" nil>]>, <kd:blank "n" nil>, <kd:codeblock "puts "This is code and shouldn't be included"n" nil>, <kd:blank "n" nil>, <kd:p nil [<kd:text "This is the conclusion of my fascinating blog." nil>]>]> warnings=[]> We can see kramdown has created different types of nodes for the content, and the only ones we are interested in are kd:text. All nodes appear to be in a tree structure descendent from kd:root, so a recursive filtering function should be sufficient to extract all of the text nodes. You can consult the kramdown documentation for the exact API of Document, but you can also get a long way just by guessing. root, type and children are common enough names for this type of tree structure, and this is no exception. def extract_text(elem) value = elem.type == :text ? [elem.value] : [] value + elem.children.map {|x| extract_text(x) }.flatten end extract_text(doc.root).join(' ') # => "Indubitably I am writing a blog! This is the conclusion of my fascinating blog." Excellent. Let’s move on to the analysis of the text. Part Two From a past project, I already knew about the Lingua library. Lingua::EN::Readabilityis a Ruby module which calculates statistics on English text. It can supply counts of words, sentences and syllables. It can also calculate several readability measures, such as a Fog Index and a Flesch-Kincaid level. It harks from a time before Rubygems, and suggests a tar.gz download to install. This isn’t so difficult, but ideally we would stay within our dependency system of choice. With many of these old projects, people have forked them so to package them properly or make them work with the latest versions of Ruby. GitHub is the best place to find these. Searching for ‘Lingua’ yields a few results, with the top one being a winner. It has a gemspec and some bug fixes on top of the original library. We can install it the same as all our other Ruby libraries. gem install lingua Usage is trivial, and completes our report: require 'lingua' require 'kramdown' files = Dir["content/articles/*.md"] def parse(content_filename, meta_filename, kind) # ... from above end files.each do |file_name| meta, content = parse(file_name, nil, nil) doc = Kramdown::Document.new(content) text = extract_text(doc.root).join(" ") report = Lingua::EN::Readability.new(text) puts "%s: %.2f" % [meta['title'], report.kincaid] end # My Blog Post: 7.37 Readable by your average seventh grader. Not too shabby! This post itself scores 8.11, which I trust is accessible to the majority of the audience. Wrapping Up Attempting small, semi-practical projects like this one are a great way to learn about your programming ecosystem, and improve your algorithmic chops. They are the programmer’s equivalent of a musician’s scales. Here are some extra problems you can try out for more practice: extract_textstrips out punctuation, meaning contractions come out incorrect in the resulting text (“I’m” becomes “I m”). This is fine for this analysis, but how would you fix it for feeding into a text to speech converter? (protip if you are on a mac: try say helloat the command line) created_atis still a text value in the meta-data. Convert it to an appropriate Timeformat. - If you keep a blog yourself, try running the above analysis over it. Let us know how you go in the comments. Tune in next week for more exciting adventures in the code jungle. Get practical advice to start your career in programming! Master complex transitions, transformations and animations in CSS!
https://www.sitepoint.com/linguistic-analysis-with-lingua/
CC-MAIN-2021-17
refinedweb
1,358
59.4
derivative() function The derivative() function computes the rate of change per unit of time between subsequent non-null records. It assumes rows are ordered by the _time column. The output table schema is the same as the input table. Output data type: Float derivative( unit: 1s, nonNegative: false, columns: ["_value"], timeColumn: "_time", ) Parameters unit The time duration used when creating the derivative. Default is 1s. nonNegative Indicates if the derivative is allowed to be negative. Default is false. When true, if a value is less than the previous value, it is assumed the previous value should have been a zero. columns The columns to use to compute the derivative. Default is ["_value"]. timeColumn The column containing time values. Default is "_time". tables Input data. Default is piped-forward data ( <-). Output tables For each input table with n rows, derivative() outputs a table with n - 1 rows. Examples The following examples use data provided by the sampledata package to show how derivative() transforms data. - Calculate the rate of change per second - Calculate the non-negative rate of change per second - Calculate the rate of change per second with null values Calculate the rate of change per second import "sampledata" sampledata.int() |> derivative() View input and output Calculate the non-negative rate of change per second import "sampledata" sampledata.int() |> derivative(nonNegative: true) View input and output Calculate the rate of change per second with null values import "sampledata" sampledata.int(includeNull: true) |> derivative() View input and output.
https://docs.influxdata.com/flux/v0.x/stdlib/universe/derivative/
CC-MAIN-2022-21
refinedweb
246
50.94
//************************************** // Name: Search a String To Another String in C // Description:A simple program that I wrote to search a string or a word to another string using C language. //************************************** #include <stdio.h> #include <conio.h> #include <string.h> #include <stdlib.h> int xstrsearch ( char *, char * ) ; void show( ) ; int main( ) { char s1[ ] = "PomperadaJake" ; char s2[ ] = "Jake" ; int pos ; system("cls"); printf("Search a String To Another String in C") printf("\n\n"); printf ( "String One: %s\n", s1 ) ; printf ( "String Two: %s\n", s2 ) ; pos = xstrsearch ( s1, s2 ) ; printf ( "\nThe pattern string is found at position: %d\n", pos ) ; getch( ) ; } int xstrsearch ( char * s1, char * s2 ) { int i, j, k ; int l1 = strlen ( s1 ) ; int l2 = strlen ( s2 ) ; for ( i = 0 ; i <= l1 - l2 ; i++ ) { j = 0 ; k = i ; while ( ( s1[k] == s2[j] ) && ( j < l2 ) ) { k++ ; j++ ; } if ( j == l2 ) return i ; } return -1 ; }.
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=13930&lngWId=3
CC-MAIN-2018-05
refinedweb
144
78.93
expression tree which gives you the AST. But I haven’t been in .NET in a while, so off to macros I went! First off, I found the documentation regarding macros to be lackluster. It’s either rudimentary with trivial examples, or the learning curve was steep and I was too lazy to read through all of it. Usually when I encounter scenarios like this I turn to exploratory programming, where I have a unit test that sets up a basic example and I leverage the debugger and intellij live REPL to poke through what I can and can’t do. Time to get set up. First, I needed to create a new submodule in my multi module maven project that would contain my macro. The reason is that you can’t use macros in the same compilation unit that they are defined in. You can however, use macros in a macros test since the compiler compiles test sources different from regular sources. That said, debugging macros is harder than normal because you aren’t debugging your running program, you are debugging the actual compiler. I found this blog post which was a life saver, even though it was missing a few minor pieces. 1. Set the main class to scala.tools.nsc.Main 2. Set the VM args to -Dscala.usejavacp=true 3. Set the program arguments to first point to the file containing the macro, then the file to compile that uses the macro: -cp types.Types macros/src/main/scala/com/devshorts/common/macros/MethodNames.scala config/src/test/scala/config/ConfigProxySpec.scala Now you can actually debug your macro! First let me show the test case class MethodNameTest(field1: Object) { def getFoo(arg: Object): Unit = {} def getFoo2(arg: Object, arg2: Object): Unit = {} } class MethodNamesMacroSpec extends FlatSpec with Matchers { "Names macro" should "extract from an function" in { methodName[MethodNameTest](_.field1) shouldEqual MethodName("field1") } it should "extract when the function contains an argument" in { methodName[MethodNameTest](_.getFoo(null)) shouldEqual MethodName("getFoo") } it should "extract when the function contains multiple argument" in { methodName[MethodNameTest](_.getFoo2(null, null)) shouldEqual MethodName("getFoo2") } it should "extract when the method is curried" in { methodName[MethodNameTest](m => m.getFoo2 _) shouldEqual MethodName("getFoo2") } } methodName here is a macro that extracts the method name from a lambda passed in of the parameterized generic type. What’s nice about how scala set up their macros is you provide an alias for your macro such that you can re-use the macro but type it however you want. object MethodNames { implicit def methodName[A](extractor: (A) => Any): MethodName = macro methodNamesMacro[A] def methodNamesMacro[A: c.WeakTypeTag](c: Context)(extractor: c.Expr[(A) => Any]): c.Expr[MethodName] = { ... } } I’ve made the methodName function take a generic and a function that uses that generic (even though no actual instance is ever passed in). The nice thing about this is I can re-use the macro typed as another function elsewhere. Imagine I want to pin [A] so people don’t have to type it. I can do exactly that! case class Configuration (foo: String) implicit def config(extractor: Configuration => Any): MethodName = macro MethodNames.methodNamesMacro[Configuration] config(_.foo) == "foo" At this point its time to build the bulk of the macro. The idea is to inspect parts of the AST and potentially walk it to find the pieces we want. Here’s what I ended up with: def methodNamesMacro[A: c.WeakTypeTag](c: Context)(extractor: c.Expr[(A) => Any]): c.Expr[MethodName] = { import c.universe._ @tailrec def resolveFunctionName(f: Function): String = { f.body match { // the function name case t: Select => t.name.decoded case t: Function => resolveFunctionName(t) // an application of a function and extracting the name case t: Apply if t.fun.isInstanceOf[Select] => t.fun.asInstanceOf[Select].name.decoded // curried lambda case t: Block if t.expr.isInstanceOf[Function] => val func = t.expr.asInstanceOf[Function] resolveFunctionName(func) case _ => { throw new RuntimeException("Unable to resolve function name for expression: " + f.body) } } } val name = resolveFunctionName(extractor.tree.asInstanceOf[Function]) val literal = c.Expr[String](Literal(Constant(name))) reify { MethodName(literal.splice) } } For more details on parts of the AST here is a great resource In the first case, when we pass in methodName[Config](_.method) it gets mangled into a function with a body that is of x$1.method. The select indicates the x$1 instance and selects the method expression of it. This is an easy case. In the block case that maps to when we call methodName[Config](c => c.thing _). In this case we have a function but its curried. In this scenario the function body is a block who’s inner expression is a function. But, the functions body of that inner function is an Apply. Apply takes two arguments — a Select or an Ident for the function and a list of arguments So that makes sense. The rest is just helper methods to recurse. The last piece of the puzzle is to create an instance of a string literal and splice it into a new expression returning the MethodName case class that contains the string literal. All in all a fun afternoons worth of code and now I get semantic string safety. A great use case here can be to type configuration values or other string semantics with a trait. You can get compile time refactoring + type safety. Other use cases are things like database configurations and drivers (the .NET mongo driver uses expression trees to type an object to its underlying mongo collection).
http://onoffswitch.net/category/code/page/2/
CC-MAIN-2018-17
refinedweb
928
58.08
Opened 6 years ago Closed 6 years ago #10933 closed defect (fixed) time of magma command fails inside function Description def foo(str): time magma(str) foo('1') fails with ERROR: An unexpected error occurred while tokenizing input The following traceback may be corrupted or invalid The error message is: ('EOF in multi-line statement', (18, 0)) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/mariah/sage/sage-4.6.2-x86_64-Linux-core2-fc/<ipython console> in <module>() /home/mariah/sage/sage-4.6.2-x86_64-Linux-core2-fc/<ipython console> in foo(str) /home/mariah/sage/sage-4.6.2-x86_64-Linux-core2-fc/local/lib/python2.6/site-packages/IPython/iplib.pyc in ipmagic(self, arg_s) 951 else: 952 magic_args = self.var_expand(magic_args,1) --> 953 return fn(magic_args) 954 955 def ipalias(self,arg_s): /home/mariah/sage/sage-4.6.2-x86_64-Linux-core2-fc/local/lib/python2.6/site-packages/IPython/Magic.pyc in magic_time(self, parameter_s) 1904 if mode=='eval': 1905 st = clk() -> 1906 out = eval(code,glob) 1907 end = clk() 1908 else: /home/mariah/sage/sage-4.6.2-x86_64-Linux-core2-fc/<timed eval> in <module>() /home/mariah/sage/sage-4.6.2-x86_64-Linux-core2-fc/local/lib/python2.6/site-packages/sage/interfaces/magma.pyc in __call__(self, x, gens) 735 pass 736 --> 737 A = Expect.__call__(self, x) 738 if has_cache: 739 x._magma_cache[self] = A /home/mariah/sage/sage-4.6.2-x86_64-Linux-core2-fc/local/lib/python2.6/site-packages/sage/interfaces/expect.pyc in __call__(self, x, name) 1110 return cls(self, str(x), name=name) 1111 except TypeError, msg2: -> 1112 raise TypeError, msg 1113 1114 def _coerce_from_special_method(self, x): TypeError: unable to coerce element into magma sage: Attachments (1) Change History (9) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by sage: def foo(s): ....: time gp(s) ....: sage: foo('1') NameError: name 's' is not defined This might also be relevant: sage: print preparse("""def foo(str):\n time gp(str)\n\nprint gp('1')""", do_time=True) def foo(str): __time__=misc.cputime(); __wall__=misc.walltime(); gp(str); print "Time: CPU %.2f s, Wall: %.2f s"%(misc.cputime(__time__), misc.walltime(__wall__)) print gp('1') sage: def foo(str): ....: __time__=misc.cputime(); __wall__=misc.walltime(); gp(str); print "Time: CPU %.2f s, Wall: %.2f s"%(misc.cputime(__time__), misc.walltime(__wall__)) ....: sage: sage: foo('1') Time: CPU 0.00 s, Wall: 0.00 s The next thing I might do is look into exactly what Python is executing... there is something funny going on with the preparser not preparsing the input as expected... comment:3 Changed 6 years ago by OK, investigated this for IPython. The issue is that it evaluates the expression gp(s) within the main user namespace, not within the function's internal namespace (where s lives). Off the top of my head, I can't think of a neat way for the time command to get the namespace from inside the function. Changed 6 years ago by comment:4 Changed 6 years ago by - Status changed from new to needs_review I fixed this by making the preparse_ipython preparse the time just as it already happens in the notebook. comment:5 Changed 6 years ago by - Reviewers set to Martin Raum - Status changed from needs_review to positive_review That's ok, but let us hope that is gets fixed in IPython soon. comment:6 Changed 6 years ago by We're looking at a way to make %time evaluate things in the correct scope, but in the current ipython trunk, auto-magics (like "time" without the %) are only used in single-line inputs. So you'd have to do: def f(x): %time gp(x) comment:7 Changed 6 years ago by I've written some simple code to make this work in IPython, if you want to test my branch here: comment:8 Changed 6 years ago by - Merged in set to sage-4.7.alpha5 - Resolution set to fixed - Status changed from positive_review to closed This isn't a magma issue per se. I get a similar issue with gp:
https://trac.sagemath.org/ticket/10933
CC-MAIN-2017-09
refinedweb
694
54.63
by Michael S. Kaplan, published on 2010/01/04 07:01 -05:00, original URI: Sometimes even when two problems are different, there are very strong similarities -- and the answer is still the same. Like the other day, when Jacques asked: Is there a standard way to determine if a given locale orders the firstname/surname as "First Last" or "Last, First"? I have looked through the Globalization namespace but haven't found anything useful. Is there a built-in way to do this or do I need to implement my own? Thanks. Now this may remind some regular readers of What's in a name? from way back when, though it was really more talking about parsing names in general (in order to find the last name), rather than the display order of names in general. However, the two problems are obviously related, and share a common heritage of the overall complexity of names - a complexity that doesn't ever seem to get any easier. So the quick answer for Jacques is that there is no such beast in the Globalization namespace. And the long answer is that not only is there no such thing but one should not try to write it oneself, for the very same reason that there is no built-in solution in the .NET Framework. Because any such solution will be incomplete across the huge variety of issues in names! Now in a way, the two problems are converse issues (one is given a display name how to parse out the constituent parts, while the other is given the constituent parts how to construct the full form of the name for display) so perhaps one could think of the problems as being merely on the other end of the telescope (pardon the oblique musical reference!). This is the kind of problem that apps like Outlook Express/Windows Mail/Windows Live Mail have had lame solutions for all along, a lameness that is pretty much mitigated by the easy way users have to notice the problems when they occur and override the program's guesses But one could take a step back and ask WHY the question is being answered in each case - what scenario leads one to have just one kind of information while needing the other - in order to come to the ideal solution for the problem. It may involve creating a localizable solution so that a localizer (someone meant to be the most knowledgeable person about users expectations in a given culture) can give the user sensible defaults that the user can then override when the code falls short. Or it may involve just making sure to ask for the information, all of the information, explicitly. And not try to be too clever in the code. If you look in not just What's in a name? but in the comments to it, there are countless examples that should tend to dissuade even the most eager developer hoping to try to add this particular feature as a pure code solution meant to solve the problem, since you can't. :-) John Cowan on 4 Jan 2010 6:45 PM: My screed "Against Structured Names And Telephone Numbers" can be found at . Michael S. Kaplan on 5 Jan 2010 11:04 AM: Yep, that lays it out nicely.... go to newer or older post, or back to index or month or day
http://archives.miloush.net/michkap/archive/2010/01/04/9943362.html
CC-MAIN-2017-13
refinedweb
568
61.8
I wrote a couple of years ago a Java application (Swing) incorporating an OpenOffice Writer component. The trick relied on some sun.awt classes from the jdk to retrieve the AWT container's handle and pass it to the OO objects: - Code: Select all Expand viewCollapse view public static long getHWnd(Component f) { ComponentPeer compPeer = f.getPeer(); if (compPeer == null) { return 0; } if (compPeer instanceof WComponentPeer) { return ((WComponentPeer) compPeer).getHWnd(); } // typically we get here if the peer is of class sun.awt.NullComponentPeer // (e.g if the Component is a Swing object - apparently these do not have a "peer") return -1; } This used to work until I moved to OpenJDK. I tested with OpenJDK 8 and 11. They don't have those old sun.awt classes, which breaks the code. Is they any new or cleaner way to integrate a OO Writer component into a Java Swing application ?
https://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=105143&p=510324&sid=148abb21d918ef2a0203fd801fa6c70f
CC-MAIN-2021-25
refinedweb
148
57.47
Today I describe how I will make data-driven charts and graphs for an intranet site I’m developing. After an hour of researching the Python graphing libraries out there, I decided to go with Matplotlib for the chart generation. It seemed like the most server friendly option because it seems to run fast and it required me to install the least amount of other programs. (Plus this guy really likes it.) Here is the chart image I’m able to make so far (code below): It’s not pretty yet, but this post is focusing on the cgi mechanics. I’ll update you when I learn the intricacies of plotting data in Matplotlib. One thing to note about using Matplotlib for this purpose is that it insists on saving its output to a file and on top of that, it requires a filename (not a file object). So that means that printing the image data directly to STDOUT like I wanted was out of the question and so was using cStringIO to make a pretend, in-memory file. Thus I was forced to use a temp file approach*. Here is the code. It makes a PNG file of a plot with two plot lines. This script should be saved in its own file, placed in a cgi-bin location and referenced via URL. You’ll need to install Matplotlib and Numeric to run this code. You’ll also want to modify it to do something useful #!/usr/bin/env python import os import tempfile matplotlib.numerix as nx def make_fig(): """ make a chart """ fig = Figure() # add an axes at left, bottom, width, height; by making the bottom # at 0.3, we save some extra room for tick labels ax = fig.add_axes([0.2, 0.3, 0.7, 0.6]) #ie set sides of chart box #now we make the plots line, = ax.plot([0,2,3,4],[100,200,230,250], 'ro--', markersize=12, markerfacecolor='g',label='Meters', linewidth=2) line, = ax.plot([0,2,4],[1.5,25,3.5], 'bv--', markersize=12, markerfacecolor='g',label='Checks', linewidth=2) ax.legend() #stick in a legend # add some text decoration ax.set_title('Sales to Blue Credit') ax.set_ylabel('$Amount') ax.set_xticks( (0,1,2,3,4) ) #set these the same as x input into plot labels = ax.set_xticklabels(('2006-01-01', '2006-01-15', '2006-02-01', '2006-03-01')) canvas = FigureCanvasAgg(fig) #now let's handle the temp file stuff and print the output tempfilenum,tempfilename=tempfile.mkstemp(suffix='.png') #function print_figure below requires a suffix canvas.print_figure(tempfilename, dpi=150) imagefile=file(tempfilename,'rb') print "Content-type: image/png\\n" imagefile.seek(0) print imagefile.read() imagefile.close() os.close(tempfilenum) #close what tempfile.mkstemp opened os.remove(tempfilename) #clean up by removing this temp file if __name__=='__main__': make_fig() So this script is a a combination of the general web server example from the Matplotlib examples and my temporary file stuff at the end in order to get my script (call it “chartgem.py”) to produce an image when called upon i.e. when browsing to it or referencing it from an <img src="chartgem.py" /> type of deal. <img src="chartgem.py" /> The next step for me is to start customizing this code further and actually make some useful dynamic charts from live company data. References: 1. Serving Dynamic Images with Python CGI was of great help. 2. so was Displaying Random Images with Simple Python CGI. 3. Python tempfile module documentation which I wish had examples *But this is a bonus for you, gentle reader as I’ve found there to be a dearth of examples of how to actually use temporary files in Python. So consider this a useful addition to the stock of temporary file usage examples in Python on the internet. (assuming I did it right ) [tags]Matplotlib, Matplotlib Python, Matplotlib Example, Matplotlib Examples, Python, Python Examples, Dynamic Charts, Data Visualization, Dynamic graphs, plots, Python plots, Data Mining, Data-Mining, tempfile, python tempfile, temporary files, tempfile example[/tags] Posted by Greg Pinero (Primary Searcher) on Jul 11th, 2006 and is filed under Python. Both comments and pings are currently closed. Add this post to Del.icio.us - Digg The line: “Content-type: image/pngn” should be: “Content-type: image/png\n” Thanks, Jenny. I updated this post with the change. © 2017, Blended Technologies LLC Entries (RSS) and Comments (RSS).
http://www.answermysearches.com/making-dynamic-charts-and-graphs-for-your-webpage/135/
CC-MAIN-2017-09
refinedweb
738
65.42
Xmonad/Using xmonad in Gnome/0.5 - Revision history 2016-02-06T10:27:00Z Revision history for this page on the wiki MediaWiki 1.19.14+dfsg-1 DonStewart at 23:26, 25 March 2008 2008-03-25T23:26:22Z <p></p> <p><b>New page</b></p><div>This is the old version of the gnome document, describing gnome support<br /> under xmonad 0.5<br /> <br /> == Introduction ==<br /> Xmonad makes a great drop-in replacement for Gnome's default window manager (metacity) giving the user a slick tiling window manager. This guide will help you get your version of gnome up and running with xmonad 0.5.<br /> <br /> === Assumptions ===<br /> For this tutorial we assume:<br /> *you're using xmonad 0.5 or newer.<br /> *you have installed the xmonad 0.5 contrib files. /> == The configuration ==<br /> All configuration is done in the ~/.xmonad/xmonad.hs file.<br /> <br /> === From scratch ===<br /> To make space for the gnome-panel/taskbar at the top, we setup the [ ManageDocks] class:<br /> <br /> import XMonad.Hooks.ManageDocks<br /> main = xmonad defaultConfig <br /> { manageHook = manageDocks<br /> , layoutHook = avoidStruts (tall ||| mirror tall ||| Full)<br /> }<br /> where tall = Tall 1 (3/100) (1/2)<br /> <br /> For gnome to know about the windows and workspaces that xmonad creates, a class called [ EwmhDesktop] exists. The configuration (from the [ EwmhDesktop] page)looks like this:<br /> import XMonad<br /> import XMonad.Hooks.EwmhDesktops<br /> <br /> myLogHook :: X ()<br /> myLogHook = do ewmhDesktopsLogHook<br /> return ()<br /> <br /> main = xmonad defaultConfig { logHook = myLogHook }<br /> <br /> Putting it all together, a simple xmonad.hs configuraton file that works with Gnome might be:<br /> import XMonad<br /> import XMonad.Hooks.ManageDocks<br /> import XMonad.Hooks.EwmhDesktops<br /> <br /> myLogHook :: X ()<br /> myLogHook = do ewmhDesktopsLogHook<br /> return ()<br /> <br /> main = xmonad $ defaultConfig<br /> { borderWidth = 2<br /> , manageHook = manageDocks<br /> , workspaces = map show [1 .. 5 :: Int]<br /> , logHook = myLogHook<br /> , layoutHook = avoidStruts (tall ||| Mirror tall ||| Full)<br /> }<br /> where tall = Tall 1 (3/100) (1/2)<br /> <br /> You also need to tell gnome that you would like xmonad to be your default window manager. If gdm is your login manager, it looks in the ~/.gnomerc file for the WINDOW_MANGER variable. Let's set that. My ~/.gnomerc file looks like this:<br /> <br /> #!/bin/bash<br /> export WINDOW_MANAGER="/usr/bin/xmonad"<br /> <br /> === From xmonad < 0.5 ===<br /> To make space for the gnome-panel on the top of the screen, xmonad had to be manually configured to make space. Prior to xmonad 0.5, this was done using the defaultGaps config option. This can now safely be taken out in favor of ManageDocks. See above.<br /> <br /> == Issues ==<br /> * Shortcuts - Be weary of the keyboard shortcuts that might conflict. For example, by default xmonad uses alt as the mod key. However, the shortcut alt-space (cycle layout) conflicts with gnome's default window management shortcut.<br /> * Nautilus - The author has had problems when Nautilus is running. To disable it do the following:<br /> *#Click System -> Preferences -> Sessions<br /> *#Select the "Current Session" tab.<br /> *#Find nautilus and select it. Set style: "Trash" and press remove.<br /> *#On the "Session Options" tab. Press "Remember currently running applications"<br /> <br /> == Old gnome tutorial from xmonad.org ==<br /> <br /> '''WARNING''': This is probably out of date. It's only here so that the static page can be deleted from xmonad.org. Someone who is knowledgeable about such things should go through and delete/incorporate into the above as appropriate.<br /> <br /> ===Introduction===<br /> <br /> As of xmonad 0.4 the procedure for replacing Metacity with xmonad under a normal GNOME/GDM session has been simplified greatly. Here you'll configure your xmonad process to be managed by gnome-session and in turn by gdm, such that logging into a GNOME session from GDM automatically launches xmonad, and logging out of GNOME in the usual manner exits both GNOME and xmonad, returning you to the GDM login screen.<br /> <br /> For this tutorial we assume:<br /> <br /> * you're using xmonad 0.4 or newer. /> ===Xmonad configuration===<br /> <br /> If you use gnome-panel or other panel/dock-style applications you'll want to create a gap space for them. Open xmonad's Config.hs in your editor and modify defaultGaps with the same height values (in pixels) your panels/docks use. For example, a single top-oriented gnome-panel instance 24 pixels in height would need:<br /> <br /> defaultGaps = [(24,0,0,0)]<br /> <br /> Once that's set recompile and reinstall xmonad. Press mod-q to make the settings take effect in a running xmonad instance.<br /> <br /> [[Image:screen-ohmega-tab-gnome-twopane-thumb.jpg|center]]<br /> <br /> ===Preparing your GNOME session===<br /> <br /> The two main approaches to changing GNOME's window manager are explained below. If you have a ~/.gnome2/session file then you should use option A, otherwise option B.<br /> <br /> # Launch GNOME as usual and back up ~/.gnome2/session in case you need to revert back to your current session configuration. Next, launch System --> Preferences --> Sessions (or at the command line, gnome-session-properties) and perform the following:<br /> ## In the Startup Programs tab click New (or Add in GNOME 2.20) and add a launcher called "xmonad" which has the command "/usr/bin/xmonad", then click OK. Make sure the new entry's box is checked so that it will be started automatically.<br /> ## In the Current Session tab select the metacity item (or whichever window manager your current GNOME session is using) from the list and set its Style to Trash. Do the same for any items which have no icon in the Style column.<br /> ## Click Apply.<br /> ## In the Session Options tab click Save the current session (or Remember currently running applications in GNOME 2.20) and then Close. This will write your modified session to ~/.gnome2/session.<br /> # In the absence of a custom ~/.gnome2/session file GDM will fall back on the default GNOME session defined in /usr/share/gnome/default.session (this path may vary according to platform). The default session launches gnome-wm which in turn launches the window manager defined by the environment variable WINDOW_MANAGER. If that variable is undefined gnome-wm defaults to Metacity. You can define it on a per-user basis by putting the following in ~/.gnomerc, ~/.xsession or ~/.xinitrc:<br /> <br /> export WINDOW_MANAGER="/usr/bin/xmonad"<br /> <br /> You can also define it system-wide. On Gentoo for example, put the following in /etc/env.d/99local then run env-update:<br /> <br /> WINDOW_MANAGER="/usr/bin/xmonad"<br /> <br /> Now that your session is ready, log out of GNOME.<br /> <br /> ===Starting GNOME with xmonad===<br /> <br /> At the GDM login screen select GNOME for a new session then log indon't just accept the default Last session option for this initial login because your previous session might be used instead of the newly-modified session. After logging in you should see the GNOME splash screen briefly, thenif all went wellyou'll be running GNOME with xmonad instead of Metacity.<br /> <br /> [[Image:gnome-thumb.png|center]]<br /> <br /> Xmonad should have your GNOME panel(s) positioned correctly by default. If not, try toggling the offending panel's Orientation property a couple of times. One reported panel fix involves adding a new manageHook rule to Config.hs; using a single top-oriented panel as an example, first add:<br /> <br /> manageHook w "Top Expanded Edge Panel" "gnome-panel" _ = reveal w >> return (W.delete w)<br /> <br /> and then remove "gnome-panel", from the following definition:<br /> <br /> manageHook w _ n _ | n `elem` ignore = reveal w >> return (W.delete w)<br /> where ignore = ["gnome-panel", "desktop_window", "kicker", "kdesktop"]<br /> <br /> If you experience applications/applets hanging during startup, you can try this: Pull up the preferences for your GNOME session again, and in the Current Session tab, find the xmonad entry and change its Order from 50 to 99, click Apply, then in the Session Options tab click Save the current session (or Remember currently running applications in GNOME 2.20) and finally Close. This helps ensure that xmonad will be started last in subsequent sessions.<br /> <br /> ===Problematic applications===<br /> <br /> * Dock mode applications Applications displaying in dock mode (GKrellM, Conky, etc.) may not behave as expected. If possible you might try setting the application to desktop window or normal window mode. Xmonad's manageHook setting provides a flexible method to make xmonad ignore the application altogether, allowing the application to sit unmanaged in a gap area (see Config.hs for more on using manageHook). Currently under development in xmonad darcs is an extension ManageDocks which aims to further improve dock management. See the comments in its source file for more information.<br /> * Window List, Window Selector, and Workspace Switcher panel applets Xmonad-managed windows and workspaces don't currently register in GNOME, so these panel applets present empty lists. Fortunately there's another extension currently under development in xmonad darcs called EwmhDesktops designed to address such deficiencies.<br /> <br /> ===Tips===<br /> <br /> * Launch gnome-terminal with mod-Shift-Enter If gnome-terminal is your preferred xterm you might want to change the key binding value for keys in Config.hs from:<br /> <br /> [ ((modMask .|. shiftMask, xK_Return), spawn "xterm") -- @@ Launch an xterm<br /> <br /> <br /> to the following:<br /> <br /> [ ((modMask .|. shiftMask, xK_Return), spawn "gnome-terminal") -- @@ Launch an xterm<br /> <br /> * Disable splash screen and Nautilus desktop Some find the Nautilus-managed desktop unhelpful when used in combination with xmonad. To disable it (while continuing to use Nautilus to manage files), you can use the command:<br /> <br /> gconftool --type boolean --set /apps/nautilus/preferences/show_desktop false<br /> <br /> <br /> The splash screen is another potential annoyance. It may also be disabled:<br /> <br /> gconftool --type boolean --set /apps/gnome-session/options/show_splash_screen false<br /> <br /> <br /> * Workspace background image The usual methods of setting the background image for the Nautilus-drawn desktop also determine the background used by xmonad's workspaces (which of course are drawn independently of Nautilus's desktop). If you need to change the workspace background programmatically (i.e. from some extension setting in xmonad's configuration file), you can use the command:<br /> <br /> gconftool --type string --set /desktop/gnome/background/picture_filename "/path/to/your/image.png"<br /> <br /> <br /> NB: On some platforms the gconftool binary is named gconftool-2 instead. <br /> <br /> [[Category:XMonad]]</div> DonStewart
https://wiki.haskell.org/index.php?title=Xmonad/Using_xmonad_in_Gnome/0.5&feed=atom&action=history
CC-MAIN-2016-07
refinedweb
1,751
56.76
/* trees.c -- output deflated data using Huffman coding Copyright (C) 1997, 1998, 1999 Free Software Foundation, Inc. Copyright (C) 1992-1993 Jean-loup Ga. */ /* * PURPOSE * * Encode various sets of source values using variable-length * binary code trees. * * DISCUSSION * * The PKZIP "deflation" process uses several Huffman trees. The more * common source values are represented by shorter bit sequences. * * Each code tree is stored in the ZIP file in a compressed form * which is itself a Huffman encoding of the lengths of * all the code strings (in ascending order by source values). * The actual code strings are reconstructed from the lengths in * the UNZIP process, as described in the "application note" * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program. * * REFERENCES * * Lynch, Thomas J. * Data Compression: Techniques and Applications, pp. 53-55. * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7. * * Storer, James A. * Data Compression: Methods and Theory, pp. 49-50. * Computer Science Press, 1988. ISBN 0-7167-8156-5. * * Sedgewick, R. * Algorithms, p290. * Addison-Wesley, 1983. ISBN 0-201-06672-6. * * INTERFACE * * void ct_init (ush *attr, int *methodp) * Allocate the match buffer, initialize the various tables and save * the location of the internal file attribute (ascii/binary) and * method (DEFLATE/STORE) * * void ct_tally (int dist, int lc); * Save the match info and tally the frequency counts. * * off_t flush_block (char *buf, ulg stored_len, int eof) * Determine the best encoding for the current block: dynamic trees, * static trees or store, and output the encoded block to the zip * file. Returns the total compressed length for the file so far. * */ #include <config.h> #include <ctype.h> #include "tailor.h" #include "gzip.h" #ifdef RCSID static char rcsid[] = "$Id: trees.c,v 1.4 2006/11/20 08:40:33 eggert Exp $"; #endif /* =========================================================================== * Constants */ #define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ #define MAX_BL_BITS 7 /* Bit length codes must not exceed MAX_BL_BITS bits */ #define LENGTH_CODES 29 /* number of length codes, not counting the special END_BLOCK code */ #define LITERALS 256 /* number of literal bytes 0..255 */ #define END_BLOCK 256 /* end of block literal code */ #define L_CODES (LITERALS+1+LENGTH_CODES) /* number of Literal or Length codes, including the END_BLOCK code */ #define D_CODES 30 /* number of distance codes */ #define BL_CODES 19 /* number of codes used to transfer the bit lengths */ local int near extra_lbits[LENGTH_CODES] /* extra bits for each length code */ = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; local int near extra_dbits[D_CODES] /* extra bits for each distance code */ = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; local int near extra_blbits[BL_CODES]/* extra bits for each bit length code */ = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; #define STORED_BLOCK 0 #define STATIC_TREES 1 #define DYN_TREES 2 /* The three kinds of block type */ #ifndef LIT_BUFSIZE # ifdef SMALL_MEM # define LIT_BUFSIZE 0x2000 # else # ifdef MEDIUM_MEM # define LIT_BUFSIZE 0x4000 # else # define LIT_BUFSIZE 0x8000 # endif # endif #endif #ifndef DIST_BUFSIZE # define DIST_BUFSIZE LIT_BUFSIZE #endif /* Sizes of match buffers for literals/lengths and distances. * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save * memory at the expense of compression). Some optimizations would be possible * if we rely on DIST_BUFSIZE == LIT_BUFSIZE. */ #if LIT_BUFSIZE > INBUFSIZ error cannot overlay l_buf and inbuf #endif #define REP_3_6 16 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ #define REPZ_3_10 17 /* repeat a zero length 3-10 times (3 bits of repeat count) */ #define REPZ_11_138 18 /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* =========================================================================== * Local data */ /* Data structure describing a single value and its code string. */ typedef struct ct_data { union { ush freq; /* frequency count */ ush code; /* bit string */ } fc; union { ush dad; /* father node in Huffman tree */ ush len; /* length of bit string */ } dl; } ct_data; #define Freq fc.freq #define Code fc.code #define Dad dl.dad #define Len dl.len #define HEAP_SIZE (2*L_CODES+1) /* maximum heap size */ local ct_data near dyn_ltree[HEAP_SIZE]; /* literal and length tree */ local ct_data near dyn_dtree[2*D_CODES+1]; /* distance tree */ local ct_data near static_ltree[L_CODES+2]; /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see ct_init * below). */ local ct_data near static_dtree[D_CODES]; /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ local ct_data near bl_tree[2*BL_CODES+1]; /* Huffman tree for the bit lengths */ typedef struct tree_desc { ct_data near *dyn_tree; /* the dynamic tree */ ct_data near *static_tree; /* corresponding static tree or NULL */ int near *extra_bits; /* extra bits for each code or NULL */ int extra_base; /* base index for extra_bits */ int elems; /* max number of elements in the tree */ int max_length; /* max bit length for the codes */ int max_code; /* largest code with non zero frequency */ } tree_desc; local tree_desc near l_desc = {dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0}; local tree_desc near d_desc = {dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0}; local tree_desc near bl_desc = {bl_tree, (ct_data near *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS, 0}; local ush near bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ local uch near bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ local int near heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ local int heap_len; /* number of elements in the heap */ local int heap_max; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ local uch near depth[2*L_CODES+1]; /* Depth of each subtree used as tie breaker for trees of equal frequency */ local uch length_code[MAX_MATCH-MIN_MATCH+1]; /* length code for each normalized match length (0 == MIN_MATCH) */ local uch dist_code[512]; /* distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ local int near base_length[LENGTH_CODES]; /* First normalized length for each code (0 = MIN_MATCH) */ local int near base_dist[D_CODES]; /* First normalized distance for each code (0 = distance of 1) */ #define l_buf inbuf /* DECLARE(uch, l_buf, LIT_BUFSIZE); buffer for literals or lengths */ /* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */ local uch near flag_buf[(LIT_BUFSIZE/8)]; /* flag_buf is a bit array distinguishing literals from lengths in * l_buf, thus indicating the presence or absence of a distance. */ local unsigned last_lit; /* running index in l_buf */ local unsigned last_dist; /* running index in d_buf */ local unsigned last_flags; /* running index in flag_buf */ local uch flags; /* current flags not yet saved in flag_buf */ local uch flag_bit; /* current bit used in flags */ /* bits are filled in flags starting at bit 0 (least significant). * Note: these flags are overkill in the current code since we don't * take advantage of DIST_BUFSIZE == LIT_BUFSIZE. */ local ulg opt_len; /* bit length of current block with optimal trees */ local ulg static_len; /* bit length of current block with static trees */ local off_t compressed_len; /* total bit length of compressed file */ local off_t input_len; /* total byte length of input file */ /* input_len is for debugging only since we can get it by other means. */ ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */ int *file_method; /* pointer to DEFLATE or STORE */ #ifdef DEBUG extern off_t bits_sent; /* bit length of the compressed data */ #endif extern long block_start; /* window offset of current block */ extern unsigned near strstart; /* window offset of current string */ /* =========================================================================== * Local (static) routines in this file. */ local void init_block OF((void)); local void pqdownheap OF((ct_data near *tree, int k)); local void gen_bitlen OF((tree_desc near *desc)); local void gen_codes OF((ct_data near *tree, int max_code)); local void build_tree OF((tree_desc near *desc)); local void scan_tree OF((ct_data near *tree, int max_code)); local void send_tree OF((ct_data near *tree, int max_code)); local int build_bl_tree OF((void)); local void send_all_trees OF((int lcodes, int dcodes, int blcodes)); local void compress_block OF((ct_data near *ltree, ct_data near *dtree)); local void set_file_type OF((void)); #ifndef DEBUG # define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len) /* Send a code of the given tree. c and tree must not have side effects */ #else /* DEBUG */ # define send_code(c, tree) \ { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \ send_bits(tree[c].Code, tree[c].Len); } #endif #define d_code(dist) \ ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)]) /* Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. dist_code[256] and dist_code[257] are never * used. */ #define MAX(a,b) (a >= b ? a : b) /* the arguments must not have side effects */ /* =========================================================================== * Allocate the match buffer, initialize the various tables and save the * location of the internal file attribute (ascii/binary) and method * (DEFLATE/STORE). */ void ct_init(attr, methodp) ush *attr; /* pointer to internal file attribute */ int *methodp; /* pointer to compression method */ { int n; /* iterates over tree elements */ int bits; /* bit counter */ int length; /* length value */ int code; /* code value */ int dist; /* distance index */ file_type = attr; file_method = methodp; compressed_len = input_len = 0L; if (static_dtree[0].Len != 0) return; /* ct_init already called */ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { length_code[length++] = (uch)code; } } Assert (length == 256, "ct_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ length_code[length-1] = (uch)code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { dist_code[dist++] = (uch)code; } } Assert (dist == 256, "ct_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for ( ; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { dist_code[256 + dist++] = (uch)code; } } Assert (dist == 256, "ct_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; n = 0; while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes((ct_data near *)static_ltree, L_CODES+1); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n].Len = 5; static_dtree[n].Code = bi_reverse(n, 5); } /* Initialize the first block of the first file: */ init_block(); } /* =========================================================================== * Initialize a new block. */ local void init_block() { int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) bl_tree[n].Freq = 0; dyn_ltree[END_BLOCK].Freq = 1; opt_len = static_len = 0L; last_lit = last_dist = last_flags = 0; flags = 0; flag_bit = 1; } #define SMALLEST 1 /* Index within the heap array of least frequent node in the Huffman tree */ /* =========================================================================== * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */ #define pqremove(tree, top) \ {\ top = heap[SMALLEST]; \ heap[SMALLEST] = heap[heap_len--]; \ pqdownheap(tree, SMALLEST); \ } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ #define smaller(tree, n, m) \ (tree[n].Freq < tree[m].Freq || \ (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ local void pqdownheap(tree, k) ct_data near *tree; /* the tree to restore */ int k; /* node to move down */ { int v = heap[k]; int j = k << 1; /* left son of k */ while (j <= heap_len) { /* Set j to the smallest of the two sons: */ if (j < heap_len && smaller(tree, heap[j+1], heap[j])) j++; /* Exit if v is smaller than both sons */ if (smaller(tree, v, heap[j])) break; /* Exchange v with the smallest son */ heap[k] = heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } heap[k] = v; } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ local void gen_bitlen(desc) tree_desc near *desc; /* the tree descriptor */ { ct_data near *tree = desc->dyn_tree; int near *extra = desc->extra_bits; int base = desc->extra_base; int max_code = desc->max_code; int max_length = desc->max_length; ct_data near *stree = desc->static_tree; int h; /* heap index */ int n, m; /* iterate over the tree elements */ int bits; /* bit length */ int xbits; /* extra bits */ ush f; /* frequency */ int overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[heap[heap_max]].Len = 0; /* root of the heap */ for (h = heap_max+1; h < HEAP_SIZE; h++) { n = heap[h]; bits = tree[tree[n].Dad].Len + 1; if (bits > max_length) bits = max_length, overflow++; tree[n].Len = (ush)bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n].Freq; opt_len += (ulg)f * (bits + xbits); if (stree) static_len += (ulg)f * (stree[n].Len + xbits); } if (overflow == 0) return; Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (bl_count[bits] == 0) bits--; bl_count[bits]--; /* move one leaf down the tree */ bl_count[bits+1] += 2; /* move one overflow item as its brother */ bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits != 0; bits--) { n = bl_count[bits]; while (n != 0) { m = heap[--h]; if (m > max_code) continue; if (tree[m].Len != (unsigned) bits) { Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); opt_len += ((long)bits-(long)tree[m].Len)*(long)tree[m].Freq; tree[m].Len = (ush)bits; }. */ local void gen_codes (tree, max_code) ct_data near *tree; /* the tree to decorate */ int max_code; /* largest code with non zero frequency */ { ush next_code[MAX_BITS+1]; /* next code value for each bit length */ ush code = 0; /* running code value */ int bits; /* bit index */ int n; /* code index */ /*<<MAX_BITS)-1, "inconsistent bit counts"); Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n].Len; if (len == 0) continue; /* Now reverse the bits */ tree[n].Code = bi_reverse(next_code[len]++, len); Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ local void build_tree(desc) tree_desc near *desc; /* the tree descriptor */ { ct_data near *tree = desc->dyn_tree; ct_data near *stree = desc->static_tree; int elems = desc->elems; int n, m; /* iterate over heap elements */ int max_code = -1; /* largest code with non zero frequency */ int node = elems; /* next internal node of the tree */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ heap_len = 0, heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n].Freq != 0) { heap[++heap_len] = max_code = n; depth[n] = 0; } else { tree[n].Len = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (heap_len < 2) { int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0); tree[new].Freq = 1; depth[new] = 0; opt_len--; if (stree) static_len -= stree[new].Len; /* new is 0 or 1 so it does not have extra bits */ } desc->max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = heap_len/2; n >= 1; n--) pqdownheap(tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ do { pqremove(tree, n); /* n = node of least frequency */ m = heap[SMALLEST]; /* m = node of next least frequency */ heap[--heap_max] = n; /* keep the nodes sorted by frequency */ heap[--heap_max] = m; /* Create a new node father of n and m */ tree[node].Freq = tree[n].Freq + tree[m].Freq; depth[node] = (uch) (MAX(depth[n], depth[m]) + 1); tree[n].Dad = tree[m].Dad = (ush)node; #ifdef DUMP_BL_TREE if (tree == bl_tree) { fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); } #endif /* and insert the new node in the heap */ heap[SMALLEST] = node++; pqdownheap(tree, SMALLEST); } while (heap_len >= 2); heap[--heap_max] = heap[SMALLEST]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen((tree_desc near *)desc); /* The field len is now set, we can generate the bit codes */ gen_codes ((ct_data near *)tree, max_code); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. Updates opt_len to take into account the repeat * counts. (The contribution of the bit length codes will be added later * during the construction of bl_tree.) */ local void scan */ if (nextlen == 0) max_count = 138, min_count = 3; tree[max_code+1].Len = (ush)0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { bl_tree[curlen].Freq += count; } else if (curlen != 0) { if (curlen != prevlen) bl_tree[curlen].Freq++; bl_tree[REP_3_6].Freq++; } else if (count <= 10) { bl_tree[REPZ_3_10].Freq++; } else { bl_tree[REPZ_11_138].Freq++; } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ local void send */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen == 0) max_count = 138, min_count = 3; for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(curlen, bl_tree); } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { send_code(curlen, bl_tree); count--; } Assert(count >= 3 && count <= 6, " 3_6?"); send_code(REP_3_6, bl_tree); send_bits(count-3, 2); } else if (count <= 10) { send_code(REPZ_3_10, bl_tree); send_bits(count-3, 3); } else { send_code(REPZ_11_138, bl_tree); send_bits(count-11, 7); } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ local int build_bl_tree() { int max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree((ct_data near *)dyn_ltree, l_desc.max_code); scan_tree((ct_data near *)dyn_dtree, d_desc.max_code); /* Build the bit length tree: */ build_tree((tree_desc near *)(&bl_desc)); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (bl_tree[bl_order[max_blindex]].Len != 0) break; } /* Update opt_len to include the bit length tree and counts */ opt_len += 3*(max_blindex+1) + 5+5+4; Tracev((stderr, "\ndyn trees: dyn %lu, stat %lu", opt_len, static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ local void send_all_trees(lcodes, dcodes, blcodes) int lcodes, dcodes, blcodes; /* number of codes for each tree */ { int rank; /* index in bl_order */ Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes"); Tracev((stderr, "\nbl counts: ")); send_bits(lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(dcodes-1, 5); send_bits(blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(bl_tree[bl_order[rank]].Len, 3); } send_tree((ct_data near *)dyn_ltree, lcodes-1); /* send the literal tree */ send_tree((ct_data near *)dyn_dtree, dcodes-1); /* send the distance tree */ } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. This function * returns the total compressed length for the file so far. */ off_t flush_block(buf, stored_len, eof) char *buf; /* input block, or NULL if too old */ ulg stored_len; /* length of input block */ int eof; /* true if this is the last block for a file */ { ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex; /* index of last bit length code of non zero freq */ flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */ /* Check if the file is ascii or binary */ if (*file_type == (ush)UNKNOWN) set_file_type(); /* Construct the literal and distance trees */ build_tree((tree_desc near *)(&l_desc)); Tracev((stderr, "\nlit data: dyn %lu, stat %lu", opt_len, static_len)); build_tree((tree_desc near *)(&d_desc)); Tracev((stderr, "\ndist data: dyn %lu, stat %lu", opt_len, static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(); /* Determine the best encoding. Compute first the block length in bytes */ opt_lenb = (opt_len+3+7)>>3; static_lenb = (static_len+3+7)>>3; input_len += stored_len; /* for debugging only */ Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ", opt_lenb, opt_len, static_lenb, static_len, stored_len, last_lit, last_dist)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; /* If compression failed and this is the first and last block, * and if the zip file can be seeked (to rewrite the local header), * the whole file is transformed into a stored file: */ #ifdef FORCE_METHOD if (level == 1 && eof && compressed_len == 0L) { /* force stored file */ #else if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) { #endif /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */ if (!buf) gzip_error ("block vanished"); copy_block(buf, (unsigned)stored_len, 0); /* without header */ compressed_len = stored_len << 3; *file_method = STORED; #ifdef FORCE_METHOD } else if (level == 2 && buf != (char*)0) { /* force stored block */ #else } else if (stored_len+4 <= opt_lenb && buf != (char*)0) { /* 4: two words for the lengths */ #endif /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ send_bits((STORED_BLOCK<<1)+eof, 3); /* send block type */ compressed_len = (compressed_len + 3 + 7) & ~7L; compressed_len += (stored_len + 4) << 3; copy_block(buf, (unsigned)stored_len, 1); /* with header */ #ifdef FORCE_METHOD } else if (level == 3) { /* force static trees */ #else } else if (static_lenb == opt_lenb) { #endif send_bits((STATIC_TREES<<1)+eof, 3); compress_block((ct_data near *)static_ltree, (ct_data near *)static_dtree); compressed_len += 3 + static_len; } else { send_bits((DYN_TREES<<1)+eof, 3); send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1); compress_block((ct_data near *)dyn_ltree, (ct_data near *)dyn_dtree); compressed_len += 3 + opt_len; } Assert (compressed_len == bits_sent, "bad compressed size"); init_block(); if (eof) { Assert (input_len == bytes_in, "bad input size"); bi_windup(); compressed_len += 7; /* align on byte boundary */ } return compressed_len >> 3; } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ int ct_tally (dist, lc) int dist; /* distance of matched string */ int lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { l_buf[last_lit++] = (uch)lc; if (dist == 0) { /* lc is the unmatched char */ dyn_ltree[lc].Freq++; } else { /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ Assert((ush)dist < (ush)MAX_DIST && (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && (ush)d_code(dist) < (ush)D_CODES, "ct_tally: bad match"); dyn_ltree[length_code[lc]+LITERALS+1].Freq++; dyn_dtree[d_code(dist)].Freq++; d_buf[last_dist++] = (ush)dist; flags |= flag_bit; } flag_bit <<= 1; /* Output the flags if they fill a byte: */ if ((last_lit & 7) == 0) { flag_buf[last_flags++] = flags; flags = 0, flag_bit = 1; } /* Try to guess if it is profitable to stop the current block here */ if (level > 2 && (last_lit & 0xfff) == 0) { /* Compute an upper bound for the compressed length */ ulg out_length = (ulg)last_lit*8L; ulg in_length = (ulg)strstart-block_start; int dcode; for (dcode = 0; dcode < D_CODES; dcode++) { out_length += (ulg)dyn_dtree[dcode].Freq*(5L+extra_dbits[dcode]); } out_length >>= 3; Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ", last_lit, last_dist, in_length, out_length, 100L - out_length*100L/in_length)); if (last_dist < last_lit/2 && out_length < in_length/2) return 1; } return (last_lit == LIT_BUFSIZE-1 || last_dist == DIST_BUFSIZE); /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } /* =========================================================================== * Send the block data compressed using the given Huffman trees */ local void compress_block(ltree, dtree) ct_data near *ltree; /* literal tree */ ct_data near *dtree; /* distance tree */ { unsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ unsigned lx = 0; /* running index in l_buf */ unsigned dx = 0; /* running index in d_buf */ unsigned fx = 0; /* running index in flag_buf */ uch flag = 0; /* current flags */ unsigned code; /* the code to send */ int extra; /* number of extra bits to send */ if (last_lit != 0) do { if ((lx & 7) == 0) flag = flag_buf[fx++]; lc = l_buf[lx++]; if ((flag & 1) == 0) { send_code(lc, ltree); /* send a literal byte */ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = length_code[lc]; send_code(code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra != 0) { lc -= base_length[code]; send_bits(lc, extra); /* send the extra length bits */ } dist = d_buf[dx++]; /* Here, dist is the match distance - 1 */ code = d_code(dist); Assert (code < D_CODES, "bad d_code"); send_code(code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra != 0) { dist -= base_dist[code]; send_bits(dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ flag >>= 1; } while (lx < last_lit); send_code(END_BLOCK, ltree); } /* =========================================================================== * Set the file type to ASCII or BINARY, using a crude approximation: * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. * IN assertion: the fields freq of dyn_ltree are set and the total of all * frequencies does not exceed 64K (to fit in an int on 16 bit machines). */ local void set_file_type() { int n = 0; unsigned ascii_freq = 0; unsigned bin_freq = 0; while (n < 7) bin_freq += dyn_ltree[n++].Freq; while (n < 128) ascii_freq += dyn_ltree[n++].Freq; while (n < LITERALS) bin_freq += dyn_ltree[n++].Freq; *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII; if (*file_type == BINARY && translate_eol) { warning ("-l used on binary file"); } }
http://opensource.apple.com/source/gnuzip/gnuzip-30/gzip/trees.c
CC-MAIN-2014-52
refinedweb
4,754
58.01
14 February 2011 11:31 [Source: ICIS news] LONDON (ICIS)--High density polyethylene (HDPE) prices, long seen as the laggard in the general polyethylene (PE) upward trend, have surged over the past few weeks, sources said on Monday. Although prices have recovered sharply, they still had some way to go before reaching the former record high level of July 2008. Net HDPE prices slumped from a high of €1,420/tonne ($1,919/tonne) FD (free delivered) NWE (northwest ?xml:namespace> Current net levels were now at €1,240-1,300/tonne, depending on the size of the customer, but there were few bargains to be had. “I have had to pay €1,250/tonne FD NWE for extra volumes,” said a large injection buyer, whose net price had been €980/tonne FD NWE in October 2010. HDPE blowmoulding buyers reported a similar picture. Both HDPE blowmoulding and injection grades were particularly strong in February, but buying sources felt the current market strength was based more on reduced output than strong demand. They were nevertheless forced to pay higher prices. Two recent cases of force majeure on HDPE, from INEOS at One major producer felt that the current tight situation would last for several months. “I can’t see availability improving before August,” it said. Buyers had been expecting relief in the form of imports from new capacities in the Middle East for many months, but delays meant that demand, particularly in fast-growing areas like China and India, had had time to catch up with output and Europe was short of imports to support the tight market. PE producers were also expected to target more increases in March as they envisaged another rise in the new ethylene momomer contract price. “We will recover anything we get on monomer,” said another HDPE producer. One producer added a note of caution, however, not just for HDPE but for all PE grades. “Demand is good, price is not an issue, but everybody is concerned. It is not a happy feeling,” it said. “We are pushing hard, but we have to because raw material prices are high, but nobody is happy.” Several buyers envisaged a similar situation to the fourth quarter of 2008 when prices collapsed along with crude oil levels, but producers argued that the situation was not the same. Inventories had been high then, whereas now they were low. Brent crude oil was trading at over $100/bbl on Monday and there was no expectation of an imminent price crash at present. HDPE blowmoulding is used widely in the manufacture of small bottles. HDPE injection is used for small household goods amongst other applications. ($1 = €0.74)
http://www.icis.com/Articles/2011/02/14/9434888/europe-hdpe-surges-on-tight-availability-higher-feedstocks.html
CC-MAIN-2014-35
refinedweb
446
60.14
As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter. The following example illustrates autoboxing and unboxing, along with generics and the for-each loop. In a mere ten lines of code, it computes and prints an alphabetized frequency table of the words appearing on the command line. import java.util.*; // Prints a frequency table of the words on the command line public class Frequency { public static void main(String[] args) { Map<String, Integer> m = new TreeMap<String, Integer>(); for (String word : args) { Integer freq = m.get(word); m.put(word, (freq == null ? 1 : freq + 1)); } System.out.println(m); } } java Frequency if it is to be it is up to me to do the watusi {be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1} The program first declares a map from String to Integer, associating the number of times a word occurs on the command line with the word. Then it iterates over each word on the command line. For each word, it looks up the word in the map. Then it puts a revised entry for the word into the map. The line that does this (highlighted in green) contains both autoboxing and unboxing. To compute the new value to associate with the word, first it looks at the current value ( freq). If it is null, this is the first occurrence of the word, so it puts 1 into the map. Otherwise, it adds 1 to the number of prior occurrences and puts that value into the map. But of course you cannot put an int into a map, nor can you add one to an Integer. What is really happening is this: In order to add 1 to freq, it is automatically unboxed, resulting in an expression of type int. Since both of the alternative expressions in the conditional expression are of type int, so too is the conditional expression itself. In order to put this int value into the map, it is automatically boxed into an Integer. The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats.. In a mere ten lines of code this method provides the full richness of the List interface atop an int array. All changes to the list write through to the array and vice-versa. The lines that use autoboxing or unboxing are highlighted in green: //; } }; } The performance of the resulting list is likely to be poor, as it boxes or unboxes on every get or set operation. It is plenty fast enough for occasional use, but it would be folly to use it in a performance critical inner loop. So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection..
http://docs.oracle.com/javase/6/docs/technotes/guides/language/autoboxing.html
CC-MAIN-2013-20
refinedweb
580
60.45
Our guest blogger is Microsoft .NET MVP and Regional Director David Yack who is the author of a number of books including the very popular CRM as a Rapid Development Platform. David blogs at. Yesterday, Microsoft released CRM SDK 4.0.12 - before you just download it and think its just another minor update – read on. This update includes what is being referred to as Advanced Developer Extensions. Before you stop reading saying “I’m not advanced” – “Advanced” I believe is marketing’s way of saying this builds on top of the strong foundation that CRM already provided – not that you need to be a “Super Advanced” developer to use it. In reality, it’s advanced because it’s going to simplify how you interact with the CRM data. More specifically, it will allow you to use the LINQ expression syntax that developers have been using since C#3/VB9 to build queries. Additionally, this introduces the idea of using the normal .NET data types instead of the CRM specific ones e.g CRMBoolean. In the past, CRM had specific types for CRM Boolean because at the time .NET didn’t support nullable types. There are other good things in the new SDK that I will try to cover in future blog posts – but wanted to make sure people didn’t gloss over this new feature. Dave’s 10 Minute Quick Start Walkthrough - (SDK download times excluded of course, I can’t help if you have a slow connection!) 1 – Download the updated CRM SDK 2 – Create a new console application in Visual Studio 2008 or 2010 – choose .NET 3.5 as your framework 3 – Create a folder in the new project called Entities – Right click Open Folder in Browser as you can see below 4 – Copy the path name from Windows Explorer – you will need it to provide to the CrmSVCUtil program so it can use it to create the generated classes 5 – From a command line – go to the SDK folder/Microsoft.xrm/Tools and run the following command line – replacing MyCrmServer with your actual server name, replace MyCrmOrg with your actual CRM Org and MyEntitiesFolder with the name you copied in step 4. Note : This assumes using integrated authentication for on-premise – support is available for many different scenarios – check the docs. crmsvcutil /server: /out:MyEntitiesFolder crmsvcutil /server: /out:MyEntitiesFolder This utility will access the server metadata and build classes for each of the entities and place them in your project folder. 6 – Right click – Add Existing Item on the entities folder, Make sure the browse dialog is in the Entities folder and select all the files and click OK 7 – Add references to the CRM SDK assemblies – using Add Reference – Browse and choosing the following 8 – Add references to the Xrm assemblies from the SDK/Microsoft.xrm/bin folder as you see in the following 9 – Add references to the following .NET assemblies 10 – Build your application you should get a clean build at this point – before we add more code 11- Open the app.config file and add the following connection string section. Modify the server name to match your server name, and the org name to match your org name - if you don’t have an app.config – just add one via add-new items: <connectionStrings> <add name="mycrm" connectionString="Authentication Type=Integrated; Server=;"/> </connectionStrings> <connectionStrings> <add name="mycrm" connectionString="Authentication Type=Integrated; Server=;"/> </connectionStrings> 12 – In the Program.cs file - Add a Using statement for your entities as you can see below: using Entities; using Entities; 13 – The new API uses a concept of a Data Context – you can think of this as the gateway to working with the CRM data – In the Main method add the following – which creates an instance and references the connection string we added to the app.config: DataContext ctx = new DataContext("mycrm"); DataContext ctx = new DataContext("mycrm"); 14 – Use LINQ to compose a query of accounts. The following defines the query but does not execute it – with LINQ expressions they get executed when used as we will see later. The following builds a query looking for all accounts that have an “a” in the name. var query = from acct in ctx.accounts where acct.name.Contains("a") select acct; var query = from acct in ctx.accounts where acct.name.Contains("a") select acct; 15 – Loop though each of the accounts and print the name – This will cause the actual execution of the query against CRM – Also notice that we can use strongly typed properties no guessing the names of magic strings: foreach (var acct in query) Console.WriteLine("Account Name :" + acct.name); foreach (var acct in query) Console.WriteLine("Account Name :" + acct.name); 17 – Run the application you should get a list of accounts 18 – See how easy it is to add ordering to a query – add the following to the LINQ query between the Where and the Select orderby acct.name 19 – Run the application again to see names sorted 20 – Let’s add a record – Adding a record is also very easy – First create an instance of the account object and set the minimum – This uses the account class that was generated by CrmSvcUtil earlier: var newAccount = new account(); newAccount.name = "test account"; var newAccount = new account(); newAccount.name = "test account"; 21 – Add the record to the Data Context – This step advises the context about the new record – but it doesn’t cause the create to happen on the server yet. This means we can do multiple adds / updates and then send them to the server when ready. ctx.AddToaccounts(newAccount); ctx.AddToaccounts(newAccount); 22 – Call the SaveChanges method on the context to cause the records to be created on the CRM server: ctx.SaveChanges(); ctx.SaveChanges(); Note : This will really add a record to your server – you have been warned! Updating is just as easy – modify a record you retrieved from a query and then call UpdateObject(account) to notify the Data Context of the changes. And of course DeleteObject(account) will make that account vanish for ever –a great way to get rid of pesky accounts :) Like Add, Update and Delete do not get sent to the server until SaveChanges is called. Cheers, David Yack Looks great! Does this pick up custom entities and attributes or does it only work on the main CRM entities? Cheers Gary Gary, the crmsvcutil.exe will easily build custom entities and customizable entities as well as the standard out of the box entities. I love the xRM piece. And Dave Yack's article is great gentle introduction. Many of us in the development community had already developed something equivalent a long time ago. The xRM implementation seems nicely done and I hope we can begin to transition to it instead of our custom classes. But I got alarmed when I saw the documentation on "Using the Web Services within a Custom Workflow Activity" where it says "It is strongly recommended that all custom workflow activities should retrieve, create, update, or delete data in Microsoft Dynamics CRM 4.0 using the DynamicEntity class. By using DynamicEntity, your code will work with out-of-the-box entity and attribute definitions and with any customizations you have made to entities or attributes. " Well, does this mean we cannot use the new xRM DTOs and DataContext classes when coding in a custom workflow situation? I guess we could use the DTOs. But would we need to make a replacement for the DataContext class and its methods that take an ICrm service? The beauty of our homemade strongly typed classes is that we have ONE shared set of classes we use whether we are coding custom workflows, custom web pages, or batch data load console applications. They can use the workflow context or plugin context or get their own context. I'm really looking for a programming model whereby we use the same techniques for coding against CRM regardless of whether it is inside the workflow context or not. Is the workflow programming model an exception to the nice, new xRM model or am I missing something? The examples are working nicely. How "realistic" is it to develop with these strongly-typed objects in a CRM deployment that changes frequently? Seems like the generated entities are using Dynamic entities (get/set props) under the covers, so as long as CRM attributes are not removed or type-changed (backward compatibility is not broken) then I can safely uses the generated classes? Thanks! Chris how do you make this work in vb.net ? I created a DLL in c# and added to asp.net site. the linq is not working and added layer is causing some error which is not being displayed. dkallen, chriss: Related to the new xRM and how it works with dynamic entities. The library exclusively uses dynamic entities internally, and it exposed both static (ie: code-genned) and dynamic mechanisms that you can use. I can speak as an ISV already using it, that we exclusively use the dynamic methods in the new SDK so that our ISV libraries can work on any customer implementation without us (the ISV) having to be aware of these customizations. Here is a page with some documentation that will show you how this can be done: HI. I need a team of experts, Microsoft Dynamics CRM 4.0, for a major project with a leading microprocessor company. Please Contact. noe.bravo(a)pounceconsulting.com Is there any chance the new Advanced Developer Extensions will ever work in a Silverlight project? Hello folks, Does any of you needed to query metadata using this xrm sdk. It has been quite useful though with some problems of caching which we managed to get around with. However, just now i have found a need to fetch some metadata and i am amazed to see that there is no support for this. Neither in xrmlinq api. May be i am wrong, but i doubt so.
http://blogs.msdn.com/b/crm/archive/2010/05/07/new-crm-sdk-new-developer-experience.aspx
CC-MAIN-2014-49
refinedweb
1,666
60.55
Summary I’ve done a lot of .Net Web APIs. APIs are the future of web programming. APIs allow you to break your system into smaller systems to give you flexibility and most importantly scalability. It can also be used to break an application into front-end and back-end systems giving you the flexibility to write multiple front-ends for one back-end. Most commonly this is used in a situation where your web application supports browsers and mobile device applications. Web API I’m going to create a very simple API to support one GET Method type of controller. My purpose is to show how to add Cross Origin Resource Sharing CORS support and how to connect all the pieces together. I’ll be using a straight HTML web page with a JQuery page to perform the AJAX command. I’ll also use JSON for the protocol. I will not be covering JSONP in this article. My final purpose in writing this article is to demonstrate how to troubleshoot problems with APIs and what tools you can use. I’m using Visual Studio 2015 Community edition. The free version. This should all work on version 2012 and beyond, though I’ve had difficulty with 2012 and CORS in the past (specifically with conflicts with Newtonsoft JSON). You’ll need to create a new Web API application. Create an empty application and select “Web API” in the check box. Then add a new controller and select “Web API 2 Controller – Empty”. Now you’ll need two NuGet packages and you can copy these two lines and paste them into your “Package Manager Console” window and execute them directly: Install-Package Newtonsoft.Json Install-Package Microsoft.AspNet.WebApi.Cors For my API Controller, I named it “HomeController” which means that the path will be: myweburl/api/Home/methodname How do I know that? It’s in the WebApiConfig.cs file. Which can be found inside the App_Start directory. Here’s what is default: config.Routes.MapHttpRoute( name: “DefaultApi“, routeTemplate: “api/{controller}/{id}“, defaults: new { id = RouteParameter.Optional } ); The word “api” is in all path names to your Web API applications, but you can change that to any word you want. If you had two different sets of APIs, you can use two routes with different patterns. I’m not going to get any deeper here. I just wanted to mention that the “routeTemplate” will control the url pattern that you will need in order to connect to your API. If you create an HTML web page and drop it inside the same URL as your API, it’ll work. However, what I’m going to do is run my HTML file from my desktop and I’m going to make up a URL for my API. This will require CORS support, otherwise the API will not respond to any requests. At this point, the CORS support is installed from the above NuGet package. All we need is to add the following using to the WebApiConfig.cs file: using System.Web.Http.Cors; Then add the following code to the top of the “Register” method: var cors = new EnableCorsAttribute(“*“, “*“, “*“); config.EnableCors(cors); I’m demonstrating support for all origins, headers and methods. However, you should narrow this down after you have completed your APIs and are going to deploy your application to a production system. This will prevent hackers from accessing your APIs. Next, is the code for the controller that you created earlier: using System.Net; using System.Net.Http; using System.Web.Http; using WebApiCorsDemo.Models; using Newtonsoft.Json; using System.Text; namespace WebApiCorsDemo.Controllers { public class HomeController : ApiController { [HttpGet] public HttpResponseMessage MyMessage() { var result = new MessageResults { Message = “It worked!“ }; var jsonData = JsonConvert.SerializeObject(result); var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new StringContent(jsonData, Encoding.UTF8, “application/json“); return resp; } } } You can see that I serialized the MessageResults object into a JSON message and returned it in the response content with a type of application/json. I always use a serializer to create my JSON if possible. You can generate the same output using a string and just building the JSON manually. It works and it’s really easy on something this tiny. However, I would discourage this practice because it becomes a programming nightmare when a program grows in size and complexity. Once you become familiar with APIs and start to build a full-scale application, you’ll be returning large complex data types and it is so easy to miss a “{” bracket and spend hours trying to fix something that you should not be wasting time on. The code for the MessageResults class is in the Models folder called MessageResults.cs: public class MessageResults { public string Message { get; set; } } Now we’ll need a JQuery file that will call this API, and then we’ll need to setup IIS. For the HTML file, I created a Home.html file and populated it with this: <!DOCTYPE html> <html> <head> <title></title> <meta charset=”utf-8” /> <script src=”jquery-2.1.4.min.js“></script> <script src=”Home.js“></script> </head> <body> </body> </html> You’ll need to download JQuery, I used version 2.1.4 in this example, but I would recommend going to the JQuery website and download the latest version and just change the script url above to reflect the version of JQuery that you’re using. You can also see that I named my js file “Home.js” to match my “Home.html” file. Inside my js file is this: $(document).ready(function () { GetMessage(); }); function GetMessage() { var url = ““; $.ajax({ crossDomain: true, type: “GET“, url: url, dataType: ‘json‘, contentType: ‘application/json‘, success: function (data, textStatus, jqXHR) { alert(data.Message); }, error: function (jqXHR, textStatus, errorThrown) { alert(formatErrorMessage(jqXHR, textStatus)); } }); } There is an additional “formatErrorMessage()” function that is not shown above, you can copy that from the full code I posted on GitHub, or just remove it from your error return. I use this function for troubleshooting AJAX calls. At this point, if you typed in all the code from above, you won’t get any results. Primarily because you don’t have a URL named “” and it doesn’t exist on the internet (unless someone goes out and claims it). You have to setup your IIS with a dummy URL for testing purposes. So open the IIS control panel, right-click on “Sites” and “Add Website”: For test sites, I always name my website the exact same URL that I’m going to bind to it. That makes it easy to find the correct website. Especially if I have 50 test sites setup. You’ll need to point the physical path to the root path of your project, not solution. This will be the subdirectory that contains the web.config file. Next, you’ll need to make sure that your web project directory has permissions for IIS to access. Once you create the website you can click on the website node and on the right side are a bunch of links to do “stuff”. You’ll see one link named “Edit Permissions”, click on it. Then click on the “Security” tab of the small window that popped up. Make sure the following users have full permissions: IUSR IIS_IUSRS (yourpcnameIIS_IUSRS) If both do not exist, then add them and give them full rights. Close your IIS window. One more step before your application will work. You’ll need to redirect the URL name to your localhost so that IIS will listen for HTTP requests. Open your hosts file located in C:WindowsSystem32driversetchosts. This is a text file and you can add as many entries into this file that you would like. At the bottom of the hosts file, I added this line: 127.0.0.1 You can use the same name, or make up your own URL. Try not to use a URL that exists on the web or you will find that you cannot get to the real address anymore. The hosts file will override DNS and reroute your request to 127.0.0.1 which is your own PC. Now, let’s do some incremental testing to make sure each piece of the puzzle is working. First, let’s make sure the hosts table is working correctly. Open up a command window. You might have to run as administrator if you are using Windows 10. You can type “CMD” in the run box and start the window up. Then execute the following command: ping You should get the following: If you don’t get a response back, then you might need to reboot your PC, or clear your DNS cache. Start with the DNS cache by typing in this command: ipconfig /flushdns Try to ping again. If it doesn’t work, reboot and then try again. After that, you’ll need to select a different URL name to get it to work. Beyond that, it’s time to google. Don’t go any further until you get this problem fixed. This is a GET method, so let’s open a browser and go directly to the path that we think our API is located. Before we do that, Rebuild the API application and make sure it builds without errors. Then open the js file and copy the URL that we’ll call and paste it into the browser URL. You should see this: If you get an error of any type, you can use a tool called Fiddler to analyze what is happening. Download and install Fiddler. You might need to change Firefox’s configuration for handling proxies (Firefox will block Fiddler, as if we needed another problem to troubleshoot). For the version of Firefox as of this writing (42.0), go to the Options, Advanced, Network, then click the “Settings” button to the right of the Connection section. Select “Use system proxy settings”. OK, now you should be able to refresh the browser with your test URL in it and see something pop up in your Fiddler screen. Obviously, if you have a 404 error, you’ll see it long before you notice it on Fiddler (it should report 404 on the web page). This just means your URL is wrong. If you get a “No HTTP resource was found that matches the request URI” message in your browser, you might have your controller named wrong in the URL. This is a 404 sent back from the program that it couldn’t route correctly. This error will also return something like “No type was found that matches the controller named [Home2]” where “Home2” was in the URL, but your controller is named “HomeController” (which means your URL should use “Home”). Time to test CORS. In your test browser setup, CORS will not refuse the connection. That’s because you are requesting your API from the website that the API is hosted on. However, we want to run this from an HTML page that might be hosted someplace else. In our test we will run it from the desktop. So navigate to where you created “Home.html” and double-click on that page. If CORS is not working you’ll get an error. You’ll need Fiddler to figure this out. In Fiddler you’ll see a 405 error. If you go to the bottom right window (this represents the response), you can switch to “raw” and see a message like this: HTTP/1.1 405 Method Not Allowed Cache-Control: no-cache Pragma: no-cache Allow: GET Content-Type: application/xml; charset=utf-8 Expires: -1 Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sun, 15 Nov 2015 00:53:34 GMT Content-Length: 96 <Error><Message>The requested resource does not support http method ‘OPTIONS’.</Message></Error> The first request from a cross origin request is the OPTIONS request. This occurs before the GET. The purpose of the OPTIONS is to determine if the end point will accept a request from your browser. For the example code, if the CORS section is working inside the WebApiConfig.cs file, then you’ll see two requests in Fiddler, one OPTIONS request followed by a GET request. Here’s the OPTIONS response: HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Expires: -1 Server: Microsoft-IIS/10.0 Access-Control-Allow-Origin: * Access-Control-Allow-Headers: content-type X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sun, 15 Nov 2015 00:58:23 GMT Content-Length: 0 And the raw GET response: HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Length: 24 Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/10.0 Access-Control-Allow-Origin: * X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sun, 15 Nov 2015 01:10:59 GMT {“Message”:”It worked!”} If you switch your response to JSON for the GET response, you should see something like this: One more thing to notice. If you open a browser and paste the URL into it and then change the name of MyMessage action, you’ll notice that it still performs a GET operation from the controller, returning the “It worked!” message. If you create two or more GET methods in the same controller one action will become the default action for all GET operations, no matter which action you specify. Modify your route inside your WebApiConfig.cs file. Add an “{action}” to the route like this: config.Routes.MapHttpRoute( name: “DefaultApi“, routeTemplate: “api/{controller}/{action}/{id}“, defaults: new { id = RouteParameter.Optional } ); Now you should see an error in your browser if the the action name in your URL does not exist in your controller: Finally, you can create two or more GET actions and they will be distinguished by the name of the action in the URL. Add the following action to your controller inside “HomeController.cs”: [HttpGet] public HttpResponseMessage MyMessageTest() { string result = “This is the second controller“; var jsonData = JsonConvert.SerializeObject(result); var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new StringContent(jsonData, Encoding.UTF8, “application/json“); return resp; } Rebuild, and test from your browser directly. First use the URL containing “MyMessage”: Then try MyMessagetest: Notice how the MyMessageTest action returns a JSON string and the MyMessage returns a JSON message object. Where to Find the Source Code You can download the full Visual Studio source code at my GitHub account by clicking here.
http://blog.frankdecaire.com/2015/11/14/web-apis-with-cors/
CC-MAIN-2018-13
refinedweb
2,423
66.23
IRC log of tagmem on 2004-04-26 Timestamps are in UTC. 18:40:57 [RRSAgent] RRSAgent has joined #tagmem 18:46:12 [DanC_] Zakim, this will be TAG 18:46:12 [Zakim] ok, DanC_; I see TAG_Weekly()2:30PM scheduled to start 16 minutes ago 18:46:51 [Stuart] Stuart has changed the topic to: 18:52:27 [Norm] Norm has joined #tagmem 18:52:59 [DanC_] I 2nd the proposal to give the okie-dokie 18:53:35 [Zakim] TAG_Weekly()2:30PM has now started 18:53:41 [DanC_] and though I didn't attend, looks OK to me too 18:53:42 [Zakim] +Norm 18:54:35 [Stuart] Ta... that will speed things up :-) 18:54:53 [Zakim] +DanC 18:55:21 [Stuart] Are my clocks wrong or are you all dialing in 5 min early? 18:55:38 [Norm] I guess I'm a couple minutes early 18:55:43 [mario] Did we already start? 18:55:44 [DanC_] we're early 18:56:01 [Stuart] In the event of Ian not attending, he sent likely regrets, I'll need a volunteer to scribe. 18:57:56 [Zakim] +??P1 18:58:34 [Stuart] Blew the dialin at the end after some ~40 digits.... starting again! 18:59:44 [Zakim] +Stuart 19:02:02 [Zakim] +TimBL 19:02:31 [Stuart] zakim who is here? 19:02:38 [Stuart] zakim, who is here? 19:02:38 [Zakim] On the phone I see Norm, DanC, MarioJ, Stuart, TimBL 19:02:39 [Zakim] On IRC I see Norm, RRSAgent, Zakim, Stuart, DanC_, mario, timbl 19:03:18 [DanC_] re "on the Web", Norm, your change seems substantial. I don't think it's helpful. I think "on the web" usually means "has an available representation". so no, tel:foo is not "on the web" 19:04:45 [DanC_] Zakim, pick a scribe 19:04:45 [Zakim] Not knowing who is chairing or who scribed recently, I propose Stuart 19:04:46 [Norm] I guess that makes a distinction between "has a URI" and "on the web" which might be meaningful 19:04:52 [DanC_] Zakim, pick a scribe 19:04:52 [Zakim] Not knowing who is chairing or who scribed recently, I propose DanC 19:04:56 [DanC_] Zakim, pick a scribe 19:04:56 [Zakim] Not knowing who is chairing or who scribed recently, I propose Stuart 19:04:57 [DanC_] Zakim, pick a scribe 19:04:57 [Zakim] Not knowing who is chairing or who scribed recently, I propose DanC 19:05:16 [Stuart] zakim, I am chairing 19:05:16 [Zakim] sorry, Stuart, I do not see a party named 'chairing' 19:05:46 [DanC_] scribe: DanC 19:05:54 [DanC_] regrets: PaulC, IanJ 19:06:05 [DanC_] Zakim, who's on the phone? 19:06:05 [Zakim] On the phone I see Norm, DanC, MarioJ, Stuart, TimBL 19:06:33 [DanC_] RESOLVED to accept 19:06:42 [DanC_] RESOLVED to accept 19:06:54 [DanC_] Stuart reviews agenda: 19:07:08 [DanC_] let's postpone 1.3 Revised TAG Charter since PaulC is not here 19:07:33 [Chris] Chris has joined #tagmem 19:07:43 [Chris] zakim, dial chris-617 19:07:43 [Zakim] ok, Chris; the call is being made 19:07:44 [Zakim] +Chris 19:07:45 [Norm] q+ 19:08:06 [DanC_] Stuart: reviewing agenda, conflicting input on whether to take 2.1 Top Level Domains used as filters up today 19:08:42 [DanC_] (let's keep it on the agenda and deal with it when we get there) 19:09:27 [Norm] q- 19:10:17 [Zakim] +Roy 19:11:23 [DanC_] Stuart: we'll keep it on the agenda; should we approach any decisions, we'll check with parties that couldn't be reached so far 19:12:29 [DanC_] next meeting: 3May? 19:12:35 [DanC_] NW on vacation 3May 19:12:40 [DanC_] SW not available 3May 19:13:06 [DanC_] TBL offers to chair 3May 19:13:41 [DanC_] RESOLVED: to meet next 3May. tbl to chair (with agend help from SW, IJ). regrets: NW, SW. 19:13:55 [DanC_] == 1.1 May TAG ftf meeting in Boston 19:14:05 [DanC_] NW: I'll get an agenda out this week before I go on vacation. 19:14:13 [DanC_] == 1.2 May AC meeting in New York 19:14:39 [DanC_] SW: except PaulC, the only TAG members planning to attend are W3C team. 19:14:56 [DanC_] SW: we need to work on our report. [sketch from agenda] 19:16:47 [DanC_] DC: you could delegate to me and CL, with input from PaulC etc. 19:16:53 [DanC_] TimBL: how about .mobile? 19:18:10 [DanC_] DC: "we've had lots of comments. upside: folks are clearly reading. downside: not easy to address quickly" 19:19:24 [DanC_] DC: I don't think we're gonna make all the commentors happy. I'm curious about input from the AC about how much consensus they want to see. 19:19:28 [DanC_] NW: yeah... that could be useful. 19:20:13 [DanC_] SW: like which? DanC: some commentors (Hayes etc.) won't likely be satisfied unless we resolve httpRange-14 19:20:26 [DanC_] CL: [oops; something about separation of presentation/content] 19:20:36 [DanC_] RF: URI spec stuff is news. 19:20:45 [DanC_] ... going to last call soon. 19:21:13 [DanC_] CL: workshop on [] seems relevant to some of our issues (13) 19:21:37 [DanC_] CL: the workshop has been brewing for a while 19:21:48 [DanC_] NW: perhaps we want a TAG position? 19:22:33 [DanC_] TBL: will the workshop presentations be good TAG reading? 19:22:49 [DanC_] CL: there will be the usual position papers 19:22:59 [Norm] Norm has joined #tagmem 19:23:31 [DanC_] ACTION DanC: prepare TAG presentation for AC 19:24:01 [DanC_] (1.3 Revised TAG Charter skipped) 19:24:33 [DanC_] (agenda+ workshop, under technical, before webarch stuff) 19:24:41 [DanC_] == 2.1 Top Level Domains used as filters (.xxx, .mobile, etc.) 19:25:10 [DanC_] re CL action "Send a draft to www-tag explaining why the .mobile proposal is misinformed. If the TAG supports the proposal, send to ICANN on the official mailing list." 19:25:46 [DanC_] CL: I've been travelling... made some progress... sent something to TimBL... 19:26:22 [DanC_] TimBL: independently, I've been working on something... 19:27:11 [DanC_] ... it turns out there are number of reasons why .mobile is harmful... mostly regarding the cost of new TLDs 19:28:16 [DanC_] TimBL: e.g. re all new TDLs: (1) there's an existing market in TLDs. You can, to a certain extent, protect your trademark by buying $tm.com, $tm.net, $tm.org ; .biz and .info bring that up to 5 ... 19:28:34 [DanC_] ... and now [the stock has split] 19:28:42 [DanC_] [no, that analogy doesn't work] 19:29:14 [DanC_] ... and with each new TLD, the market is disrupted. The speculators grab stuff first-come-first-served 19:29:18 [DanC_] [3? oops] 19:29:27 [DanC_] ... and then the market settles out. 19:30:13 [DanC_] TimBL: re .mobile in particular: after researching this, I don't see a clear description of the motivation for this domain... 19:30:45 [DanC_] ... sometimes it's put forward as a way to get the mobile phone devices on-board[?] quickly... 19:31:11 [DanC_] ... if it's for content-designed-for-mobile-devices, then it's a FLAGRANT violoation of a core principle about device independence. [?] 19:31:48 [DanC_] ... can't reuse a link to something when you use it from a different device. 19:32:16 [DanC_] ... e.g. you find a map in .mobile, email somebody a link to it, and the recipient, using a 19" display, sees a 2" map. 19:33:01 [DanC_] CL: the harm is in duplicating URIs needlessly 19:33:57 [DanC_] CL: the harm that's done is that it gives the impression that the .mobile stuff is separate from desktop stuff. 19:34:12 [DanC_] ... it warps the meaning of the rest of the web, as well as the .mobile part 19:34:56 [DanC_] CL: the best thing about .mobile is to serve as a counterpoint to W3C device indpendence work 19:35:01 [Stuart] ack Dan 19:35:01 [Zakim] DanC_, you wanted to suggest that CL and TimBL send their stuff. 19:37:23 [DanC_] [ discussion of tactics... ] 19:40:29 [DanC_] "New sTLD RFP Application .mobi" 19:41:05 [DanC_] SW: 8.5B in profit by 2008, says the application 19:41:25 [DanC_] section "Fiscal Information" 19:41:53 [DanC_] TimBL: any new ones should be non-profit. CL: yes, quite 19:42:55 [DanC_] s/8.5B/8.5 million Euro/ 19:43:11 [DanC_] discussion concludes. 19:43:19 [DanC_] == 2.2 Marking Operations Safe in WSDL 19:43:26 [Stuart] 19:44:08 [timbl] 19:46:34 [DanC_] DC: yes, what they've done so far is fine, nifty. But I'd rather the TAG reserved judgement until we see that it's actually used and such. 19:47:06 [DanC_] CL: there's a question of what happens when you take something unsafe and mark it as safe and so on 19:47:42 [DanC_] SW: PROPOSED: thank them for what they've done so far, ask them to explain a bit about what can go wrong, encourage them to put it in the test suite 19:48:06 [DanC_] so RESOLVED. ACTION SW. 19:48:40 [DanC_] == 2.3 Revised Finding "Internet Media Type registration, consistency of use" 19:48:53 [DanC_] DC: I got the impression this was an announcement of something done, not a call for review. oops. 19:49:03 [DanC_] 19:49:07 [DanC_] CL: main thing: it got shorter. 19:50:14 [DanC_] (CL, did you say that the stuff that was cut was redundant w.r.t. the webarch doc?) 19:50:52 [Chris] yes 19:50:54 [Chris] no 19:51:16 [DanC_] TBL: an aside, from an AB discussion, we could ask other folks to edit stuff. Any problem with inviting, e.g. Bray or Orchard to edit things? 19:51:17 [Chris] redundant with 19:51:20 [Zakim] +Roy_Fielding 19:51:21 [DanC_] several: no, no problem 19:51:25 [Zakim] -Roy 19:51:30 [Chris] zakim, who is here? 19:51:30 [Zakim] On the phone I see Norm, DanC, MarioJ, Stuart, TimBL, Chris, Roy_Fielding 19:51:32 [Zakim] On IRC I see Norm, Chris, RRSAgent, Zakim, Stuart, DanC_, mario, timbl 19:52:47 [Roy] Roy has joined #tagmem 19:53:44 [DanC_] DanC: if Bray's name is to remain on, I'd like to be sure he's OK with the changes 19:53:57 [DanC_] PROPOSED: to adopt the finding 19:54:03 [DanC_] so RESOLVED. 19:54:21 [DanC_] ... subject to consultation with Tim Bray to see if he wants his name to remain. 19:54:55 [DanC_] ===== workshop 19:54:57 [DanC_] 19:56:08 [DanC_] CL: workshop home says it all, pretty much 19:56:20 [DanC_] ... we've discussed compound docs... 19:56:33 [DanC_] DC: workshop home doesn't say that the TAG has discussed compound docs 19:56:38 [DanC_] CL: ah... will fix. 19:57:28 [Roy] "How are they related to Web documents, which are normally static?" -- gurk! 19:57:41 [DanC_] CL: the "web applications" stuff is what particularly motivates multi-namespace docs across the wire, as opposed to converting to .html on the server side 19:58:01 [Stuart] q? 19:58:08 [DanC_] NW: I hope to attend the workshop. 19:58:43 [DanC_] == 2.4 Web Architecture Document Last Call 19:59:00 [DanC_] NW's notes on section 3 20:01:13 [DanC_] DC: [...] 20:01:38 [DanC_] CL: I agree that POST-only things are "on the Web" 20:01:40 [Roy] I would say all it has to be is referenced from the Web to be on the Web, 20:01:50 [Roy] which also implies having a URI. 20:02:47 [Stuart] I agree with Roy 20:04:03 [Roy] A resource is on the Web when it has been assigned a URI and is referenced by some other part of the Web; hence, the Web is a graph of referenced resources. 20:05:10 [timbl] q+ 20:05:32 [Stuart] ack Dan 20:05:32 [Zakim] DanC_, you wanted to disagree re "on the web" 20:05:40 [DanC_] CL: then car:car.something is on the web? that reduces the definition of "on the web" to nothing 20:05:40 [Roy] q+ 20:05:46 [Stuart] ack timbl 20:07:15 [DanC_] TBL: I think the common parlance definition of "on the Web" means you can GET a representation of it. 20:07:37 [Stuart] ack Roy 20:08:05 [DanC_] RF: I thought we agreed to speak of the wider web, including semantic web, in this webarch document. 20:08:42 [Chris] TimBL++ 20:09:07 [DanC_] TimBL: the common use is, e.g. "W3C specs and IETF specs are on the web and ISO specs are not" 20:09:49 [Stuart] q? 20:11:24 [Norm] q+ 20:11:52 [DanC_] CL: ISO specs are "on the web" in the sense RF mentioned, since they have isbn: identifiers 20:12:21 [DanC_] RF: yes, one application may be able to get a representation of an isbn:... resource, even though the average client may not 20:12:41 [DanC_] MJ: yes, otherwise, we restrict ourselves to http... 20:13:05 [DanC_] TBL: I think it's counter-productive to go there... 20:13:10 [Roy] A resource is "on the Web" when it has been assigned a URI that makes the resource accessible to all clients that use the Web. ??? 20:13:44 [mario] Sounds like a circural definition ... 20:13:59 [DanC_] NW: hmm... maybe strike it after all? 20:14:11 [DanC_] (poll started... interrupted) 20:14:25 [timbl] A resource is "on the Web" when it has been assigned a URI that makes the resource generally accessable using standard protocols. 20:14:58 [Norm] So tel: and urn: aren't on the web? 20:15:26 [timbl] A resource is "on the Web" when it has been assigned a URI that allows one to generally obtain a representation of it using standard protocols. 20:17:23 [DanC_] RF: did you exclude POST-only things on purpose? 20:17:25 [DanC_] TimBL: yes. 20:20:23 [DanC_] ack norm 20:20:28 [Stuart] ack Norm 20:20:29 [DanC_] ack danc 20:20:29 [Zakim] DanC_, you wanted to note that we don't have a need for this definition, timbl. it can be deleted without breaking any links. 20:21:30 [Roy] /me will take the rocky road definition, two scoops please 20:22:13 [DanC_] PROPOSED: to strike the "on the web" note 20:22:38 [Roy] yes 20:22:43 [Norm] yes 20:22:56 [Stuart] yes 20:23:00 [mario] no 20:24:32 [timbl] I object 20:25:00 [timbl] Carried over my objection. 20:25:18 [DanC_] RESOLVED: to strike the "on the web" note, TimBL objecting. 20:25:35 [DanC_] ACTION NW: respond to the commentor, noting we agreed. 20:25:42 [Roy] I suggest that we remove it until someone writes an appendix that defines the several variations of "on the Web" depending upon what type of client is being used. 20:26:20 [mario] +1 to roy 20:26:55 [DanC_] NW: I think ref/identify is sufficiently clear as is. propose: no text changes. 20:26:57 [DanC_] DC: ok by me 20:27:32 [DanC_] RF: hmm... did this text come from the URI spec? 20:27:38 [DanC_] ... if so, does it need updating? 20:28:04 [DanC_] PROPOSED: to close kopecky2 without changes to webarch 20:28:14 [Norm] yes 20:28:19 [Roy] yes 20:28:19 [timbl] Tim 20:28:24 [Stuart] yes 20:28:26 [DanC_] so RESOLVED. ACTION NW 20:28:44 [DanC_] -- klyne11 20:29:36 [DanC_] PROPOSED: to add "necessarily" per klyne11 20:29:46 [Norm] yes 20:29:50 [Stuart] yes 20:29:55 [mario] yes 20:30:16 [DanC_] DanC: this looks editorial. NW: but the editor didn't mark it so. 20:30:22 [DanC_] so RESOLVED 20:30:25 [DanC_] ACTION NW 20:30:44 [DanC_] ADJOURN. 20:30:53 [Zakim] -Norm 20:30:55 [Zakim] -MarioJ 20:30:55 [Roy] Roy has left #tagmem 20:30:58 [Zakim] -Stuart 20:30:59 [Zakim] -DanC 20:31:01 [Zakim] -Roy_Fielding 20:33:00 [Zakim] -TimBL 20:34:46 [Zakim] -Chris 20:34:47 [Zakim] TAG_Weekly()2:30PM has ended 20:34:48 [Zakim] Attendees were Norm, DanC, MarioJ, Stuart, TimBL, Chris, Roy, Roy_Fielding 20:35:15 [DanC_] hmm... anybody know how "out" Ian is? is he likely to have bandwidth to finish scribe duties? 20:35:36 [DanC_] RRSAgent, make logs world-access 21:17:29 [DanC_] RRSAgent, pointer? 21:17:29 [RRSAgent] See 22:05:08 [DanC_] DanC_ has left #tagmem 22:51:46 [Zakim] Zakim has left #tagmem
http://www.w3.org/2004/04/26-tagmem-irc
CC-MAIN-2014-52
refinedweb
2,915
79.9
I'm very fond of the products developed by the Apollo team, specially the Apollo Client. It started as a simple tool to connect your frontend data requirements with a GraphQL server but, nowadays, it's a complete solution for data management on the client-side. Even though using GraphQL potentially reduces the need for local state, Apollo comes with a redux-like "global" store that you access it with a GraphQL interface. If you want to know more about how to implement client-state with Apollo, read here. I don't want to talk about local resolvers or frontend-only state, but the underlying cache that Apollo uses when you fetch GraphQL from the server, specially how you can leverage it to make your UIs more responsive and smart. Apollo docs on how to interact with cache is a good resource but, IMO, a bit far from real use cases. Simple CRUD I'll create a simple Wishlist React app (though most of what is shown is applicable to other frameworks), that is simply a CRUD of Items { title: string, price: int }. Like most real apps it has a list of resources, a delete button, a edit form and an add form.What I want to show is, basically, how to update the list after a mutation without having to refetch the list from the server. I'll be using this simple server that I've created with Codesandbox (man, aren't these guys awesome?) and the only thing to notice is that, on the edit mutation, your server should return the updated resource, you'll know why later. I'll add some mock data for us to see the results right-away. I'll assume that you already know how to setup an Apollo Client + React Apollo application. If not, check it here. So, I'll go over every letter on CRUD (for educational purposes, RUCD) and explain what you may need to do to use. Read const GET_ITEMS = gql` { items { id title price } } `; function Wishlist() { const { loading, error, data } = useQuery(GET_ITEMS); if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return data.items.map(item => { const { id, title, price } = item; return ( <div key={id}> {title} - for ${price} -{" "} </div> ); }); } This is it! Our read query is very simple: it doesn't take search parameters, pagination metadata or uses cursors. For demonstration purposes it's better this way, but I'll comment later if you need some help with more complex cases. Just with this setup, we're already prepared for our list to react to cache changes on subsequent writes. Note: Using useQuery, <Query> or even withQuery is fundamental here, since it links the data with the cache. If you use other solution like useApolloClient and, then, client.query, these solutions will not work for you. Edit We will create our Edit component and this one is the easiest case because you don't need to do anything for the list to auto update after you edit the Item. Apollo Cache, by default, uses the pair __typename + id (or _id) as a primary key to every cache object. Every time the server returns data, Apollo checks if this new data replaces something that it has on its cache, so, if your editItem mutation returns the complete updated Item object, Apollo will see that it already has that item on the cache (from when you fetched for the list), update it, and triggers the useQuery to update the data, subsequently making our Wishlist re-render. const EDIT_ITEM = gql` mutation($id: Int, $item: ItemInput) { editItem(id: $id, item: $item) { id title price } } `; const EditItem = ({ item: { title, price, id } }) => { const [editItem, { loading }] = useMutation(EDIT_ITEM); return ( <ItemForm disabled={loading} initialPrice={price} initialTitle={title} onSubmit={item => { editItem({ variables: { id, item } }); }} /> ); }; Done! When the user hit the Submit button on the edit form, the mutation will trigger, the Apollo client will receive the updated data and that item will update automatically on the list. Create Let's create our AddItem component. This time it's a bit different because when we get our response from the server (the newly created Item) Apollo doesn't "know" that the list should be updated with the new item (and, sometime, it shouldn't). For this we have to programatically add our new item to the list, and one of the parameters of the useMutation hook is the update function, that is there specifically for that purpose. The steps we need to update the cache are: - Read the data from Apollo cache (we will use the same GET_ITEMSquery) - Update the list of items pushing our new item - Write the data back to Apollo cache (also referring to the GET_ITEMSquery) After this, Apollo Client will notice that the cache for that query has changed and will also update our Wishlist on the end. const ADD_ITEM = gql` mutation($item: ItemInput) { addItem(item: $item) { id title price } } `; const AddItem = () => { const [addItem, { loading }] = useMutation(ADD_ITEM); return ( <ItemForm disabled={loading} onSubmit={item => { addItem({ variables: { item }, update: (cache, { data: { addItem } }) => { const data = cache.readQuery({ query: GET_ITEMS }); data.items = [...data.items, addItem]; cache.writeQuery({ query: GET_ITEMS }, data); } }); }} /> ); }; The delete case is very similar to the create-one. I will colocate it on the Wishlist component for simplicity, and also add some props/state for the overall functionality of the app. const DELETE_ITEM = gql` mutation($id: Int) { deleteItem(id: $id) { id title price } } `; function Wishlist({ onEdit }) { const { loading, error, data } = useQuery(GET_ITEMS); const [deleteItem] = useMutation(DELETE_ITEM); if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return data.items.map(item => { const { id, title, price } = item; return ( <div key={id}> {title} - for ${price} -{" "} <button className="dim pointer mr2" onClick={e => { onEdit(item); }} > edit </button> <button className="dim pointer" onClick={() => { deleteItem({ variables: { id }, update: cache => { const data = cache.readQuery({ query: GET_ITEMS }); data.items = data.items.filter(({id: itemId}) => itemId !== id); cache.writeQuery({ query: GET_ITEMS }, data); }}); }} > delete </button> </div> ); }); } Advanced cases It's common to have more complex lists on our apps with search, pagination and ordering and, for those, it gets a bit complicated and it heavily depends on the context of your application. For example, when deleting an item of the 4th page of items, should we delete it from the UI and show pageLength - 1 items or fetch one item from the next page and add it? These cases are also tricky because the cache.readQuery also need variables if the query provided receives it, and you might not have it globally available. One option is using something like refetch from the original query, or refetchQueries from Apollo, what makes it go on the server again. If you want to dig deeper on this problem, this issue has a lot of options for you, specially a snippet for getting a query's last used variables. The final solution The app has some state/UI quirks, I've made the minimal to demonstrate Apollo Cache Update :) The whole app developed here is on this CodeSandbox. You might need to fork this container and update the server URL. Feel free to reach me :) Discussion This is what the Apollo docs for local state should look like - much easier to follow for real use cases. It seems like it will get a bit convoluted, but not unmanageable, when paired with optimisticResponse since they both interact with the cache. Thanks :) Great post! As per the Apollo-Client docs "Do not modify the return value of readQuery. The same object might be returned to multiple components. To update data in the cache, instead create a replacement object and pass it to writeQuery." I attempted to use your solution for adding to a list of a users chats on creation and ran into "Error: Cannot assign to read only property 'edges' of object '#'" Once again, great post, just thought I'd put this here for anyone running into similar issues. You must create a new object, you cannot mutate the return value of cache.readQuery anymore and apollo will throw an error. Helpful post and thanks for sharing. here is my package npmjs.com/package/mutation-cache-u... motivated by you. Very nice, Ephrem! I've run into some issues and no one seems to respond either in the apollo community, graphql or redit. The issue is cache update but for a paginated api result. Here's the problem as I wrote it on reddit(reddit.com/r/graphql/comments/frr7...) I'm running into an issue with cache updates. I've a list of posts fetched using a query FETCH_POSTS which returns an array of type Post. I also have a CREATE_POST and UPDATE_POST mutations which return an item of type Post too. When I create a post, and use writeQuery to update the cache it works ok. The new object will be [...existingPosts, newPost]. When it comes to updating a post. When I readQuery and log the result, it seems to have updated the cache already(I'm guessing it's an auto update since the type and id are the same and exist) so writeQuery in that situation doesn't make sense. The only issue is these updates do not appear on the UI. Any idea why I may be experiencing this? This implementation works when the list of posts is not paginated. But on pagination the edit to the item in the list does not work. This is my query to fetch posts using the connection directive to ignore the pagination params. const FETCH_POSTS = gql query getPosts($params: FetchPostsParams!, $pagination: PaginationParams) { posts(params: $params, pagination: $pagination) @connection(key: "posts", filter: ["params"]) { ...PostFragment } } ${FRAGMENTS.POST_FRAGMENT} ; Things like this usually happen because the query is cached paired with the pagination variables... There was a solution I've found on Github Issues years ago where you could retrieve the "last used params" for the pagination, and, with that, your cache update would work just fine. But, I see it's a simple update, the resolutions algorithm should work just fine, it's the easiest of cases. One thing you can look into is the use of Fragments, I've never used it, so it might be the point of the problem. Hey Luciano! Will you be interested in a paid writing opportunity in your spare time? Hey Mary! How would that work? It depends on the load, I guess... sure. do you have skype or twitter? my twitter @maryvorontsov
https://dev.to/lucis/update-apollo-cache-after-a-mutation-and-get-instant-benefits-on-your-ui-1c3b
CC-MAIN-2021-04
refinedweb
1,734
61.67
Windows 2008 R2 and Windows 7 Ultimate both exhibit this behaviour... So I have directory structure like... YEAR\MONTH\file_x.ext, where YEAR goes back to 2007 and each MONTH directory contains anywhere from hundreds to thousands (2500 max right now) of files. I have a program that will randomly select a file for working with, but it only works on a single directory. So I created a new directory, and created a hardlink in there for each and every file in my structure (40,000+). Everything works peachy, except now Explorer reports that the disk only has a few MB left free and refuses to allow any more data to be written to the disk. Since they are hardlinks I figgure I should have about 40GB remaining free on the disk. Any thoughts on how to solve this? (eg, allow the single-directory application to operate properly while still retaining the organized structure, and not doubling the disk space usage) CreateHardLink() Are you sure that it’s the hard links that are filling your disk? I tested this here, but couldn’t reproduce it. Theoretically CreateHardLink should be equivalent to the mklink /h command; but just in case, I created the following AutoIt script to make sure that I was using the same function call as you. (I was far too lazy to code something in VC++…) CreateHardLink mklink /h #include <WinAPI.au3> #include <WinAPIError.au3> Local $kernel = DllOpen("kernel32.dll") If $CmdLine[0] <> 2 Then ConsoleWriteError("usage: CreateHardLink Link Target" & @CRLF) Exit EndIf Local $result = DllCall($kernel, "BOOL", "CreateHardLink", "str", $CmdLine[1], "str", $CmdLine[2], "LONG_PTR", 0) If $result[0] == 0 Then ConsoleWriteError("Windows error " & _WinAPI_GetLastError() & ": " & _WinAPI_GetLastErrorMessage()) Else ConsoleWrite("Hardlink created for " & $CmdLine[1] & " <<===>> " & $CmdLine[2] & @CRLF) EndIf Then I created a separate 2.0GB disk in VMware and attached it, so that the tests wouldn’t be on the same disk as the pagefile, etc. I put one file in the root directory and created an additional 1023 links to it (the maximum number supported) with the following batch file: @echo off dir | find "(s)" for /l %%i in (0,1,1023) do C:CreateHardLink.exe %%i %1 dir | find "(s)" Disk usage before: 1 File(s) 3,212,078 bytes 0 Dir(s) 2,089,775,104 bytes free Disk usage after: 1024 File(s) 3,289,167,872 bytes 0 Dir(s) 2,089,222,144 bytes free And Explorer says there are 1.94GB free of 1.99. I copied about 1.08GB of data (in files of various sizes, and located in various directories) to the partition, and created one hard link for each file found to a directory called HardLinks. That batch file: @echo off setlocal setlocal enabledelayedexpansion dir /s | find "(s)" set /a i=0 for /r %%a in (*) do ( C:CreateHardLink "HardLinks\!i!_%%~nxa" "%%~a" set /a i=!i!+1 ) dir /s | find "(s)" 2034 File(s) 1,109,324,978 bytes 1998 Dir(s) 975,511,552 bytes free 4246 File(s) 2,490,368,854 bytes 1998 Dir(s) 973,955,072 bytes free This would be physically impossible without hard links, since my disk is only 2.0GB. The disk space did decrease by exactly 1520K, which is ~1.46K per hard link created . At that rate, to consume 40GB in just metadata for hard links, you’d need about 29 million of them. (I imagine by that point you’d be hitting another limitation, like the number of file entries in a single directory. ;-) Apologies that this isn’t a good “answer” per se; but hopefully it gives you some reassurance that, no, hard links aren’t supposed to fill your disk. If I were you, I’d create more hard links in smaller batches and measure the disk space usage before and afterwards. It might also be worthwhile to see if something else on the same disk is using more space than it should be. I also can’t really think of an alternate solution for you; hard links seem perfect for this case, don’t they? By posting your answer, you agree to the privacy policy and terms of service. asked 2 years ago viewed 303 times active
http://serverfault.com/questions/344500/directory-of-hardlinks-on-ntfs-appears-to-be-consuming-more-space-than-it-should
CC-MAIN-2014-42
refinedweb
705
69.62
Moq Sequences Revisited A while back I wrote about mocking successive calls to the same method which returns a sequence of objects. Read that post for more context. In that post, I had written up an implementation, but quickly was won over by a better extension method implementation from Fredrik Kalseth. public static class MoqExtensions { public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup, params TResult[] results) where T : class { setup.Returns(new Queue<TResult>(results).Dequeue); } } As good as this extension method is, I was able to improve on it today during a coding session. I was writing some code where I needed the second call to the same method to throw an exception and realized this extension wouldn’t allow for that. However, it wasn’t hard to write an overload that allows for that. public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup, params object[] results) where T : class { var queue = new Queue(results); setup.Returns(() => { var result = queue.Dequeue(); if (result is Exception) { throw result as Exception; } return (TResult)result; }); } So rather than taking a parameter array of TResult, this overload accepts an array of object instances. Within the method, we create a non generic Queue and then create a lambda that captures that queue in a closure. The lambda is passed to the Returns method so that it’s called every time the mocked method is called, returning the next item in the queue. Here’s an example of the method in action: var mock = new Mock<ISomeInterface>(); mock.Setup(r => r.GetNext()) .ReturnsInOrder(1, 2, new InvalidOperationException()); Console.WriteLine(mock.Object.GetNext()); Console.WriteLine(mock.Object.GetNext()); Console.WriteLine(mock.Object.GetNext()); // Throws InvalidOperationException In this sample code, I mock an interface so that when its GetNext method is called a third time, it will throw an InvalidOperationException. I’ve found this to be a helpful and useful extension to Moq and hope you find some use for it if you’re using Moq. NOTE: As Richard Reeves pointed out to me in an email, do be careful if you mock a property using this approach. If you evaluate the property while within a debugger, you will dequeue the element potentially causing maddening debugging difficulty. 10 responses
http://haacked.com/archive/2010/11/24/moq-sequences-revisited.aspx/
CC-MAIN-2021-25
refinedweb
377
52.39
16 November 2010 15:34 [Source: ICIS news] TORONTO (ICIS)--Chemicals sales in Canada fell 0.1% in September to Canadian dollar (C$) 3.708bn ($3.671bn) from August, a government statistics agency said on Tuesday. The decline came after Statistics Canada (StatsCan) reported a 1.5% sequential increase in chemical sales in August from July. The agency added that September chemical sales in ?xml:namespace> Compared with September 2009, overall Canadian chemical sales were up 9.0%, the agency said. Canadian sales of plastics and rubber products in September 2010 fell 1.8% to C$1.73bn from August but were up 4.7% from September 2009. Overall, Canadian manufacturing sales in September totalled C$45.09bn, down 0.6% from August, with the decline mainly due to the transportation equipment industry in central Compared with September 2009, overall manufacturing sales were up 9.1%. New manufacturing orders in September totalled C$44.03bn, down 4.9% from August but up 9.2% from September 2009. Manufacturing inventory levels in September were C$60.52bn, down 0.2% from August and up 1.4% from September 2009. The overall manufacturing inventory-to-sales ratio was 1.34 in September, unchanged from August but down from 1.44 in September 2009. In related industry news, Canadian chemical railcar shipments for the year-to-date period to 6 November were up 23.4% to 637,551, from 516,765 in 2009. ($1 = C$1.01)
http://www.icis.com/Articles/2010/11/16/9411100/canadas-september-chemicals-sales-fall-0.1-from-august.html
CC-MAIN-2014-10
refinedweb
244
55.4
10 March 2009 15:07 [Source: ICIS news] LONDON (ICIS news)--Dow Chemical will shut its chlorinated solvents plant in ?xml:namespace> The source said that the exact dates of the shutdown had not been finalised, but the plant was expected to be out of action for up to two weeks. The closure will affect units that produce methylene chloride, perchloroethylene (perc), trichloroethylene (TCE) and chloroform. Dow is one of only two TCE producers in The shutdown was likely to overlap with Spolchemie’s planned maintenance at its perc unit in Market insiders said that the simultaneous closure of two of However, a source at Spolchemie doubted that the impact would be large as the outages were planned, which would allow both firms to build stocks ahead of the turnarounds. For more on methylene chloride, perc, TCE and chloro
http://www.icis.com/Articles/2009/03/10/9199109/dow-to-shut-stade-chlorinated-solvents-units-for-maintenance.html
CC-MAIN-2014-41
refinedweb
139
60.99
I'm really proud of this. I've been spending a whole day working on this, and I would really like some feedback on it. If it can be improved, please tell me in the comments. Anyway, I have created an implementation of the switch statement, seen in Java, C, and C++, using classes and decorators. I really had fun doing it, and unlike my game framework (which I have not updated in a long time), this project has proper documentation. ============================= Abstract Most traditional languages, including Visual Basic, C, C#, C++, Java, and JavaScript, include switch statements. Switch statements act very much like a light switch. Referencing a variable, a group of cases are compared, and when the comparison is true, a block of code is executed. They are a much better solution to long chains of if/elif/else statements, which are a direct violation of PEP8, and are very hard to read. With switch statements, a single condition, a value, is stated, and along with that, the block of code. Often times, switch statements point to functions. Implementation Consider the following sample code: #I'm working on a switch for Python. This is what I have so far., 6) Ignoring all the comments and fancy stuff, what we have is this:("If no case is matched") return ctx enable(mySwitch, 2) You can see a few things. I want you to focus on the @case decorator. First of all, all these methods are inside a mySwitch class. The @case decorator has one argument, representing the case's value. Example: @case(1) or... @case("bar") This is the exact same thing that the following Java code snippet does: case "bar" : //code In Java, or other languages, all you need is the case, then the code, followed by a break;. However, since this isn't officially part of Python, there are a few changes. For example, the code to be executed for each case, is a function. This should be obvious, as @case is a decorator, and decorators can only decorate function or method declarations. Consider the following code: @case("baz") def case1(ctx): print("Hello World!") return ctx As you see, there is a method, named case1(ctx). It does not matter the name of the method, but it is suggested to use case<number or code>, to avoid code confusion, as well as to make sure two cases don't have the same method name. Perhaps a more suitable course of action, would be to give the method a name, a description of what the method does in that specific case. Example: @case("printHelloWorld") def print_hello_world(ctx): print("Hello World!") return ctx As you can see, the case names also follow this construct. A coding convention, as set forth by me, is to name case conditions, if they are strings, as you would in any compiled language. Instead of using underscores, one would define a string like "stringContent" As for the definition of the method, the name does not matter on a technical level, as long as it is unique in the scope of the switch. You may notice that there is an argument, ctx, passed to the method. This acts as a reference of context, the current case. The switch goes through every case using a for loop, and checks if the case's condition matches the current index variable in memory. If it matches, the corresponding method is called. ctx is not actually passed to the method, but to @case, where it is handled, and then, it is passed to the method. You may also notice that ctx is returned. That is not to match code convention, but to allow dynamic switches, that can change the value of ctx, within a method, whilst returning it. CTX is needed, just like cls and self are needed in classes. You may also notice a special case: @case("__default__") def __default__(ctx): print("If no case is matched") return ctx This is a default case, in the event that no matching case is found, a fallback case is used, in order to prevent the program from suddenly exiting, or worse, bugs. The name of the string is "__default__", to avoid conflicts, just in case there is a case with a string, called "default". It is also a convention to name the function __default__, for the same reason the condition must be named that, however, it is not required to do so. And now, we've reached the end. As you know, states, in Python, using this implementation, are actually classes. Therefore, they cannot be executed on their own. What is nice about Python, is that there is a function that does that for us. Remember that enable that was imported? We're gonna use that. enable(mySwitch, "fdk") The first argument shall be the switch itself, aka the class, and the second argument is the value to be compared to by the switch. And putting it all together, this is the code:, "fdk") When we run this code, the following is outputted: Out[1]:Default case. That is because we have our passed switch variable, as a case which doesn't exist. If we change the enable() call to this: enable(mySwitch, 2) , we get the following: Out[1]:Second case, where you put the integer two. Creating a Finite State Machine using Switches So that's the gist of it all. Now, let's briefly talk about making a finite state machine with this. A finite state machine, is very different from a pure switch, in that it repeats, and that the value of the reference, may change. Here is an example: class stateMachine: @case("idle") def idle(ctx): print("Idle state. About to change that (=") ctx = "attack" return ctx @case("attack") def attack(ctx): print("Attack state. Awaiting next state.") ctx = "sleep" return ctx @case("sleep") def sleep(ctx): print("Sleep state. Loop has been finished.") ctx = "__finish__" return ctx ctx = "idle" while ctx != "__finish__": ctx = enable(stateMachine, ctx) I'll just leave you with that. If there are any bugs, go ahead and tell me via Reddit, or GitHub. And as always, have a great day. @MrEconomical Thank you. I spent a whole day working on it, I'm already making a game with this... Nice work! class a: @how(do="You", dot="his") question(): print("confused.") votes += 1 Enlighten me on the prospect of the @ operator. @Coder100 The @ operator is called a decorator. More info here: Cool! 2 things you should add though: You should make the case decorator not have to take a keyword argument, so people could do something like @case(5) def case1(ctx): ... As well, you should add support for multiple cases with 1 decorator, like: @case(5, 6) def case2(ctx): ... @sugarfi It is impossible to do, because the decorator is a class, I already tried implementing it. The least I could do about it, was being able to use any keyword argument. I'll try adding support for multiple cases, I'm in class right now. It would have to be a different decorator though, since any object value can be used as a case. @eidhernan ? just change the decorator from def case(function=None, **kwargs): to def case(function=None, *args):. Classes can take non-keyword args. @sugarfi It's because *args doesn't work, the function isn't passed to the decorator, instead, the function argument is what is put in @case({...}). That's why I can't do that, it's a limitation of Python itself. I've experienced this problem before, but I've accepted that there is no way to solve it. @eidhernan nevermind, I was wrong. However, I forked your repl and was able to fix it - you were simply using decorators wrong. @Thecrowbar1234 Not at all! Just make sure to credit me. I updated the post to include the license info. Nice! I like how you made it so smooth and Pythonic!
https://repl.it/talk/share/Switch-Case-in-Python/29952
CC-MAIN-2020-24
refinedweb
1,330
73.47
Popup Dialogs as Modules Recently, it was pointed out that there were bugs in the PopUpDialogAsModule example. The dialog would not center and was not draggable. The reason was that the thing being popped up was a Module that parented a TitleWindow and not the TitleWindow tiself. After thinking about that for a bit, I decided to create a subclass of TitleWindow that can be a Module's top level MXML tag. The source is available at this link: Download source Of course, the usual caveats apply. I could have certainly missed something again. In theory, any component can be made into a module's top-level tag by adding the [frame] metadata. Hope this helps. I've been seeing this issue a lot recently. Also, sorry for the errors in the older example. Very Interesting, But, you have try to make the popup not modal as: PopUpManager.addPopUp(loginDialog, Application.application as DisplayObject,false); And try to make more popups!.... then IExplorer process are bigger, you kill popups, and memory not free. ¿Is a bug?. To big applications that´s could be a big problem. In this week i must decide if i develop a proyect with this or not... 70% no, 30% yes... :( Sorry for my poor english!. Best!. --------- My testing does not how any memory leaks. Make sure you read my blog on garbage collection/memory management because memory statistics can be misleading. Good luck, -Alex Posted by: Angel | August 7, 2007 7:27 AM HI, When i try to run this app by moving the module specific files into a package/folder say testpackage then i am getting the following Error 1 Error found. Error /MyTests/testpackage/MyApp.mxml A file found in a source-path must have the same package structure '', as the definition's package, 'testpackage'. I added the package testpackage for the two ActionScript Files and Added xmlns:> in the LoginDialog.mxml Not sure what went wrong.. Thanks Sateesh ----------------- Your directory structure must match the package structure. Modules do not like being in subdirectories so build them in their own project directory. Posted by: sateesh | August 16, 2007 2:47 PM Hi Alex, Also when i try to run the Module it self i am getting the Error: Error /MyTests/testpackage/LoginDialog.mxml Unable to locate specified base class 'testpackage.ModuleTitleWindow' for component class 'LoginDialog'. I am sure this is a simple namespace issue but some how i cannot figure it out.. could u pls let me know.. Thanks a lot for your help.. Regards Kumar -------------- same problem. Put everything in its own project directory. Posted by: sateesh | August 16, 2007 2:53 PM Very nice, this cleans up a messy workaround I was using before. Also, I have successfully used the modules in subdirectories of my larger project. It takes a little work with namespace but it seems to work fine. However, making it runnable is a bit of a hack as you have to edit the .actionScriptProperties file by hand to make it runnable, clean your project, close your project, then reopen your project, and possibly clean your project again. Posted by: Daryl Ducharme | August 24, 2007 9:23 AM Hi Alex, I have an example of using Modules which works but only by hard linking to the loaded module. For best practice I'd like to use and interface but I can't cast the loaded module to the interface because it must be typed DisplayObject: Note: I need to use ModuleManager because I'm loading multiple modules dynamically, many of which may be duplicates. Code: import mx.modules.ModuleLoader; import mx.modules.ModuleManager; import mx.modules.IModuleInfo; import mx.events.ModuleEvent; import ModuleIFace; import QuestionModule; public var readyCount:int; public var info:IModuleInfo; public var myModInfos:Array = []; public var myMods:Array = []; public var myModChilds: Array = []; public var modUrlArr: Array = ["] public function onCreationComplete():void{ readyCount = 0; var i:int; for (i=0; i { info = ModuleManager.getModule(modUrlArr[i]); info.addEventListener(ModuleEvent.READY, modEventHandler); if(!info.loaded){ info.load(); } // Add the ModuleInfos to an Array myModInfos.push(info); } } private function modEventHandler(e:ModuleEvent):void { // count the number of Ready Events. When all URLs are ready call initModule readyCount ++; if(readyCount >= modUrlArr.length) { initModule(); } } public function initModule():void{ var i:int; for (i=0; i var moddy:DisplayObject = myModInfos[i].factory.create() as DisplayObject ; myMods.push(moddy); myV.addChild(moddy); } } public function popModules():void{ var i:int; for (i=0; i myMods[i].popDump("gog"); } } ]]> I have an Interface for the module but don't know how to use it in this scenario. Thanks for any help. Gerard ------------- You should be able to cast from the interface to DisplayObject. Posted by: Gerard | September 24, 2007 3:02 AM Many thanks for share the "Download Source"... Very usefully.... Posted by: Webdesign Agentur | December 24, 2007 8:16 AM hi Alex, I´ve got the same Problem like saatesh. Error /MyTests/testpackage/MyApp.mxml Please replay... Or write an email please (admin@medienstern.de) Thanks -------------------------- Try it without putting the module in a package. Modules are like sub-apps and should be in the default package. Posted by: Werbeagentur | December 28, 2007 12:40 PM it works excellent. many thanks again Posted by: Webdesign Agentur | January 24, 2008 7:15 AM Thanks for the Great Informations and the Download... A usefully Blog. I could learn very usefully things here... Thanks Posted by: Werbeagentur | February 14, 2008 8:55 AM D:\flexTestProjects>mxmlc test\Person.as K 2\frameworks\flex-config.xml D:\flexTestProjects\test\Person.as: Error: A file found in a source-path must ha ve the same package structure '', as the definition's package, 'test'. what went wrong here? I have the code inside package test{ } And as you can see, i have the file inside the test folder. Do flex having something like CLASSPATH in java? --------------------- Alex responds: Generally, an application or module cannot be in a package. I think someone has made it work, but in general I don't do that. You can set source-path options to try to compile something in a subdirectory Posted by: Sebin | July 22, 2008 6:24 AM Thanks for such a nice example. I have following error while running this. first, If I use ModuleEvent.READY it does not work anything, and when I change it to ModuleEvent.SETUP, it gives me following error TypeError: Error #1009: Cannot access a property or method of a null object reference. at mx.managers::PopUpManagerImpl/addPopUp()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:229] at mx.managers::PopUpManager$/addPopUp()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\PopUpManager.as:169] at ()[D:\kaushal\download\flex3\example_tutorial\PopUpDialogAsModule2\src\MyApp.mxml:19] ----------------------------- Alex responds: The example I posted works in Flex 3. You should be getting and using the READY event. SETUP might be at the wrong time. Posted by: Kaushal Shah | August 4, 2008 4:35 AM Nice example, I have change folder structure and find it is not working. You can view source from (right click > view source) Please run on debugger version which shows you error. I am using flex 3.0 (build 3.0.164161). I have temporary solution for that is to change as below in MyModule.mxml private var loginDialog:*; loginDialog = m.factory.create(); Anyone can help me, how to avoid that error? Thanks ----------------------- Alex responds: Please post this question on FlexCoders. Posted by: Kaushal Shah | August 5, 2008 12:31 AM
http://blogs.adobe.com/aharui/2007/08/popup_dialogs_as_modules.html
crawl-002
refinedweb
1,251
59.6
Starting with Spark 1.0.0, the Spark project will follow the semantic versioning guidelines with a few deviations. These small differences account for Spark’s nature as a multi-module project. Each Spark release will be versioned: [MAJOR].[FEATURE].[MAINTENANCE] When new components are added to Spark, they may initially be marked as “alpha”. Alpha components do not have to abide by the above guidelines, however, to the maximum extent possible, they should try to. Once they are marked “stable” they have to follow these guidelines. An API is any public class or interface exposed in Spark that is not marked as “developer API” or “experimental”. Release A is API compatible with release B if code compiled against release A compiles cleanly against B. Currently, does not guarantee that a compiled application that is linked against version A will link cleanly against version B without re-compiling. Link-level compatibility is something we’ll try to guarantee in future releases. Note, however, that even for features “developer API” and “experimental”, we strive to maintain maximum compatibility. Code should not be merged into the project as “experimental” if there is a plan to change the API later, because users expect the maximum compatibility from all available APIs. From.
http://spark.apache.org/versioning-policy.html
CC-MAIN-2017-13
refinedweb
208
55.95
To from stack overflow, the uncompressed file would not fit on the disk of this machine so I'll work with the compressed files directly (more on that here). Reading xml without taking up a lot of memory As this article explains, extra care is needed when using python's xml.etree module to avoid loading too many references into memory. The key is to access the root element outside of the loop, then clear() it within the loop to avoid building up a tree. Here I read through the file and create a dictionary of dates to number of posts on that date, using pandas to output the data in csv format. import bz2 import pandas as pd from collections import defaultdict from xml.etree import cElementTree def parse_file(filename): """Count the number of posts on each day for stack exchange xml data""" date_counts = defaultdict(int) with bz2.BZ2File(filename) as f: iterparser = cElementTree.iterparse(f, events=('start', )) _, root = iterparser.next() for _, element in iterparser: if element.tag == 'row': date_str = element.get('CreationDate', '').split('T')[0] date_counts[date_str] += 1 root.clear() return date_counts date_counts = parse_file('stackoverflow.com-Posts.bz2') date_counts_df = pd.DataFrame.from_dict(date_counts, orient='index') date_counts_df.columns = ['num_posts'] date_counts_df.to_csv('stackex_by_date.csv') Similar Posts - SF Python meetup talk, Score: 0.933 - Using sed to make specific text lowercase in place, Score: 0.847 - Using topic modeling to find related blog posts, Score: 0.824 - Saving time and space by working with gzip and bzip2 compressed files in python, Score: 0.818 - Pandas date parsing performance, Score: 0.816
https://www.datasciencebytes.com/bytes/2015/03/19/analyzing-large-xml-files-in-python/
CC-MAIN-2018-39
refinedweb
262
60.51
- No gems fetched from Git repositories - License compliance - GitLab-created gems - Upgrade Rails - Upgrading dependencies because of vulnerabilities Gemfile guidelines When adding a new entry to Gemfile or upgrading an existing dependency pay attention to the following rules. No gems fetched from Git repositories We do not allow gems that are fetched from Git repositories. All gems have to be available in the RubyGems index. We want to minimize external build dependencies and build times. License compliance Refer to licensing guidelines for ensuring license compliance. GitLab-created gems Sometimes we create libraries within our codebase that we want to extract, either because we want to use them in other applications ourselves, or because we think it would benefit the wider community. Extracting code to a gem also means that we can be sure that the gem does not contain any hidden dependencies on our application code. In general, we want to think carefully before doing this as there are also disadvantages: - Gems - even those maintained by GitLab - do not necessarily go through the same code review process as the main Rails application. - Extracting the code into a separate project means that we need a minimum of two merge requests to change functionality: one in the gem to make the functional change, and one in the Rails app to bump the version. - Our needs for our own usage of the gem may not align with the wider community’s needs. In general, if we are not using the latest version of our own gem, that might be a warning sign. In the case where we do want to extract some library code we’ve written to a gem, go through these steps: - Start with the code in the Rails application. Here it’s fine to have the code in lib/and loaded automatically. We can skip this step if the step below makes more sense initially. - Before extracting to its own project, move the gem to vendor/gemsand load it in the Gemfileusing the pathoption. This gives us a gem that can be published to RubyGems.org, with its own test suite and isolated set of dependencies, that is still in our main code tree and goes through the standard code review process. - For an example, see the merge request !57805. - Once the gem is stable - we have been using it in production for a while with few, if any, changes - extract to its own project under the gitlab-orgnamespace. 1. When creating the project, follow the instructions for new projects. 1. Follow the instructions for setting up a CI/CD configuration. 1. Follow the instructions for publishing a project. - See issue #325463 for an example. In some cases we may want to move a gem to its own namespace. Some examples might be that it will naturally have more than one project (say, something that has plugins as separate libraries), or that we expect non-GitLab-team-members to be maintainers on this project as well as GitLab team members. The latter situation (maintainers from outside GitLab) could also apply if someone who currently works at GitLab wants to maintain the gem beyond their time working at GitLab. When publishing a gem to RubyGems.org, also note the section on gem owners in the handbook.. Similarly,.
https://docs.gitlab.com/ee/development/gemfile.html
CC-MAIN-2021-31
refinedweb
546
60.65
Invoke the code completion for <bean id="foo" | The p-namespace property items pop up, among them, "p:cacheSeconds". But when I invoke the code completion for <bean id="foo" p:cache| I expect the "p:cacheSeconds" and "p:cacheSeconds-ref" items to pop up, which doesn't happen. This isn't a problem in the code completion, but in the XML infrastructure. Given <bean id="foo" p:cache| the XML lexer returns an error token starting at the class attribute. The corresponding Element doesn't contain a class attribute, so the code completion can't resolve the bean class name. Filed issue 129165. This would have low impact, since users usually put p-namespace properties after the class name. But, unfortunately, for <bean id="foo" class="FooAbstractController" p: /> <bean id="bar" class="SomeOtherClass"/> the attribute computation seems to "leak" into the bar bean, so the foo bean appears to have the SomeOtherClass class. Filed issue 129272 for the attribute computation. Hopefully it will be fixed for 6.1. moving opened issues from TM <= 6.1 to TM=Dev Andrei, Now that 129272 is fixed, can you close this ? No, since issue 129165 still needs to be fixed. The original scenario is still reproducible. Target milestone revised to future in accordance with the milestone of its dependency issue # 129165. Taking over Alexey's JSF and Spring issues. Issue #129165 is still valid and blocking this issue and I'm afraid that it will not be fixed in nb71 as well. Changing the target milestone to Next and let see what about XML issue then. Blocking issue #129165 still valid so I'm targeting this one to the next release. This old bug may not be relevant anymore. If you can still reproduce it in 8.2 development builds please reopen this issue. Thanks for your cooperation, NetBeans IDE 8.2 Release Boss
https://netbeans.org/bugzilla/show_bug.cgi?id=129027
CC-MAIN-2018-34
refinedweb
312
67.86
In a large code base, I am using np.broadcast_to In [1]: x = np.array([1,2,3]) In [2]: y = np.broadcast_to(x, (2,1,3)) In [3]: y.shape Out[3]: (2, 1, 3) y vectorize for unbroadcast In [4]: z = unbroadcast(y) In [5]: z.shape Out[5]: (1, 1, 3) z y.shape unbroadcast This is probably equivalent to your own solution, only a bit more built-in. It uses as_strided in numpy.lib.stride_tricks: import numpy as np from numpy.lib.stride_tricks import as_strided x = np.arange(16).reshape(2,1,8,1) # shape (2,1,8,1) y = np.broadcast_to(x,(2,3,8,5)) # shape (2,3,8,5) broadcast def unbroadcast(arr): #determine unbroadcast shape newshape = np.where(np.array(arr.strides) == 0,1,arr.shape) # [2,1,8,1], thanks to @Divakar return as_strided(arr,shape=newshape) # strides are automatically set here z = unbroadcast(x) np.all(z==x) # is True Note that in my original answer I didn't define a function, and the resulting z array had (64,0,8,0) as strides, whereas the input has (64,64,8,8). In the current version the returned z array has identical strides to x, I guess passing and returning the array forces a creation of a copy. Anyway, we could always set the strides manually in as_strided to get identical arrays under all circumstances, but this doesn't seem necessary in the above setup.
https://codedump.io/share/xo0UMs8DjP2f/1/un-broadcasting-numpy-arrays
CC-MAIN-2016-50
refinedweb
245
68.57
In this user guide, we will learn how to log DS18B20 temperature sensor readings along with timestamps to a microSD card using ESP32 and Arduino IDE. Furthermore, the current date and time will also be logged with each temperature sensor reading. We will use the ESP32 NTP server to request updated time stamps. In order to save battery, ESP32 will remain in sleep mode for most of the time and wake up from deep sleep after every 5 minutes. After wake up from deep sleep, ESP32 will take sensor reading, updated time from the NTP server, and logged the values to the MicroSD card. Any preferred sensor, such as BME280, BME680, LM35, and MPU6050, can be used but for this article, we will use a ds18b20 sensor which will be used to measure the ambient temperature. The sensor readings will be accessed from the ds18b20 sensor connected with the ESP32 module. These readings will get updated on microSD card connected via the microSD card module to the ESP32 after every few minutes. For a getting started guide to microSD card with ESP32, read the article: MicroSD Card Module with ESP32 using Arduino IDE This article is divided into these sub-topics: - Project Overview - Introduction to ds18b20 sensor and connecting it with the ESP32 and the microSD card module - Formatting the microSD card - Setting up Arduino IDE for data logging temperature readings to microSD card (installing libraries, Arduino sketch and demonstration) ESP32 Temperature Logging with SD Card Overview The DS18B20 sensor will be connected to the ESP32 board through the GPIO pins which we will specify later. When the ESP32 development board boots, the DS18B20 sensor will get DS18B20 temperature readings. After that, a request will be made to the NTP server to access the current and date. The temperature reading along with its timestamp will then get logged to the microSD card and ESP32 goes to deep sleep for 5 minutes. You can read more about ESP32 deep sleep here: ESP32 Deep Sleep Mode and Wake Up Sources using Arduino IDE After every 5 minutes, new sensor readings will get logged on the microSD card with its respective date and time. The rest of the time the ESP32 board will remain in deep sleep mode. This process will repeat indefinitely. For this project we will require the following components: Required Components - ESP32 development board - MicroSD card module - MicroSD card - DS18B20 temperature sensor - 10k ohm resistor - Connecting wires - Breadboard: - Single and Multiple DS18B20 with ESP32: Display Readings on OLED - Interfacing Multiple DS18B20 with Arduino: Display Readings on OLED - MicroPython: DS18B20 Web Server with ESP32/ESP8266(Weather Station) Interfacing DS18B20 and microSD card module with ESP32 board The connection of DS18B20 with the ESP32 board is very simple. The DS18B20 sensor can be powered in two different modes. Normal Mode: The sensor is powered through an external source through the VDD pin and a pull-up resistor. Parasite Mode: The sensor obtains power from its own data line. Hence, no external power supply is required. For this article, we will power the sensor in the normal mode. Thus, we have to connect the VCC terminal with Vin, ground with the ground (common ground), and the data pin of the sensor with an appropriate GPIO pin of ESP32 via a pull-up resistor. We are using GPIO4 for this project. Additionally,. The table below shows the connections between the two modules: The schematic diagram shows the connections between the ESP32 board, the DS18B20 sensor and the microSD card module. Formatting the_10<< Installing NTPClient Library by Taranais To request the current date and time from the NTP server we will use the NTPClient library by taranais available at Github. Follow the link:() to download it. Click the Code button and go to the Download Zip option as highlighted in the figure. Your zip file will get downloaded to your computer right away. After the download is complete, extract the .zip file to the Arduino library folder. Make sure you rename the extracted file as ‘NTPClient.’ You can also go to Sketch > Include Library > Add .zip Library inside the IDE to add the library as well. After installation of the libraries, restart your IDE. Arduino Sketch – ESP32 Data Logging Readings to microSD card Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file. This sketch will acquire temperature readings from DS18B20 sensor after every 5 minutes. Likewise, the time stamp will also be requested through the NTP server. This data will get displayed in the serial monitor as well as get saved in a .txt file on the microSD card. Additionally, we will put the ESP32 board in deep sleep mode after each set of data is acquired. This will led to a more efficient project. #include "FS.h" #include "SD.h" #include <SPI.h> #include <OneWire.h> #include <DallasTemperature.h> #include <WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> uint64_t uS_TO_S_FACTOR = 1000000; uint64_t TIME_TO_SLEEP = 300; const char* ssid = "Your_SSID"; const char* password = "Your_Password"; RTC_DATA_ATTR int sensor_data = 0; String Data; #define sensor_data_pin 4 OneWire oneWire(sensor_data_pin); DallasTemperature sensors(&oneWire); float temperature; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); String Date; String day; String Time; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected."); timeClient.begin(); timeClient.setTimeOffset(18000); if(!SD.begin()) { Serial.println("Card Mount Failed"); return; } uint8_t cardType = SD.cardType(); if(cardType == CARD_NONE) { Serial.println("No SD card attached"); return; } Serial.println("Initializing SD card..."); if (!SD.begin()) { Serial.println("SD card initialization failed!"); return; } File file = SD.open("/temperature_readings.txt"); if(!file) { Serial.println("File does not exist"); Serial.println("Creating file..."); writeFile(SD, "/temperature_readings.txt", "Reading Number, Date, Hour, Temperature \r\n"); } else { Serial.println("File exists"); } file.close(); esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); sensors.begin(); obtainReadings(); obtain_Date_Time(); data_logging(); sensor_data++; Serial.println("Sensor data logged successfully! Going to sleep"); esp_deep_sleep_start(); } void loop() { } void obtainReadings(){ sensors.requestTemperatures(); temperature = sensors.getTempCByIndex(0); Serial.print("Temperature: "); Serial.println(temperature); }() { Data = String(sensor_data) + "," + String(day) + "," + String(Time) + "," + String(temperature) + "\r\n"; Serial.print("Save data: "); Serial.println(Data); appendFile(SD, "/temperature_readings.txt", Data.c_str()); }? Now let us understand how each part of the code works. Installing Libraries The first step is to include all the libraries that are necessary for this project. The FS library will be used for handling files, the SD library will be used for the microSD card functionality and the SPI library will be used as we are using SPI communication protocol between the ESP32 board and the microSD card module. Then, we will be including the OneWire and DallasTemperature libraries which we previously installed for the functionality of the DS18B20 sensor. The WiFi.h will help the ESP32 board to connect to the local network whose credentials that we will provide in the program code. Additionally, we will also include the NTPClient library which we previously installed so that we will be able to request the timestamp from the NTP server. #include "FS.h" #include "SD.h" #include <SPI.h> #include <OneWire.h> #include <DallasTemperature.h> #include <WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> Adding the sleep time We want our ESP32 module to go to deep sleep whenever we will not be accessing the sensor readings. As we are logging sensor readings after every 5 minutes thus, the module will go to sleep during that time. This will make our project very efficient. Specify the time in seconds. We have set it to 300 which means 300/60=5 minutes. Also, a micro second to second conversion factor is also defined which will be used later on in the program code. uint64_t uS_TO_S_FACTOR = 1000000; uint64_t TIME_TO_SLEEP = 300; Defining Variables Next, we will define several variables. First, we will define an integer data type named ‘sensor_data.’ This will indicate the number of data (count) being logged in the microSD card e.g.(0,1,2…) This will be saved in the RTC memory of the ESP32 board so we will add ‘RTC_DATA_ATTR’ before defining it. RTC_DATA_ATTR int sensor_data = 0; Next, is the string variable named ‘Data.’ This will hold the data that will get logged on the microSD card after every 5 minutes. String Data; Additionally, we will create three more string variables named ‘Date’, ‘day’ and ‘Time.’ This will hold the current day and time. String Date; String day; String Time; The float variable named ‘temperature’ will hold the sensor reading obtained from the DS18B20. This will get updated to a new value after every 5 minutes. float temperature; Additionally, we will use the following lines of code to request the current timestamp from the NTP server. WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); Defining sensor’s data pin We will create a variable to store the GPIO pin through which the DS18B20 sensor’s data pin will be connected. We have used GPIO4 in this example. #define sensor_data_pin 4 Creating Instances for sensor We will require the following instances as well to access the temperature readings. First, we will create a oneWire instance and use the sensor_data_pin as an argument inside it. Then we will call the DallasTemperature sensor and pass the oneWire reference which we created as an argument inside it. OneWire oneWire(sensor_data_pin); DallasTemperature sensors(&oneWire); setup() Inside the setup() function, we will open a serial connection at a baud rate of 115200. Serial.begin(115200); The following section of code will connect the ESP32 module with the local network. We will call WiFi.begin() and pass the SSID and password variables inside it which we defined before. After a successful connection has been established, the serial monitor will display the message “WiFi connected”. WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected."); Next, we will initialize the NTP server by using begin() method on timeClient. We will also set the time offset so that we obtain the correct time according to our country. We have specified the offset for Pakistan but you can change them according to your time zone to obtain the correct time. For the GMT offset, click here to check for your time zone and add the offset in the program code by converting it in seconds. For Pakistan, the UTC offset is +05:00 so in our code, we have specified the GMT offset which is the same as the UTC offset in seconds as 18000 (5*60*60). timeClient.begin(); timeClient.setTimeOffset(18000); //Replace with your GMT offset (seconds) Initializing microSD card The following lines of code will initialize the microSD card using the begin() function on the SD filesystem. The begin() function takes in no argument. Thus, it will start the SPI communication using the default SPI CS pin that is GPIO5. To change the SPI CS pin you can pass the pin number as an argument inside the begin() function. if(!SD.begin()) { Serial.println("Card Mount Failed"); return; } uint8_t cardType = SD.cardType(); if(cardType == CARD_NONE) { Serial.println("No SD card attached"); return; } Serial.println("Initializing SD card..."); if (!SD.begin()) { Serial.println("SD card initialization failed!"); return; } Creating .txt file Next, we will open the temperature_readings.txt file on the microSD card using SD.open(). If the file does not exist, the message will get displayed in the serial monitor. The file will be created and its heading will be ” Reading Number, Date, Hour, Temperature”. This will be achieved by using the writeFile() function. After that, we will close the file using file.close(). File file = SD.open("/temperature_readings.txt"); if(!file) { Serial.println("File does not exist"); Serial.println("Creating file..."); writeFile(SD, "/temperature_readings.txt", "Reading Number, Date, Hour, Temperature \r\n"); } else { Serial.println("File exists"); } file.close(); Enabling Timer Wake up Next, we will enable the timer wake up. Using the following function, the ESP32 board will wake up from deep sleep mode. This function will take in the time in micro seconds as a parameter. Thus, we will pass TIME_TO_SLEEP (which is 5 minutes)* the conversion factor to insure that the argument inside the function is in micro seconds. esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); Initializing DS18B20 sensor We will call sensors.begin() to initialize the DS18B20 sensor. sensors.begin(); Next, we will call three functions that we will shortly explain. These will acquire the sensor readings and timestamp and log them on the microSD card. obtainReadings(); obtain_Date_Time(); data_logging(); Increment the ‘sensor_data’ variable which denotes the count of the sensor readings. sensor_data++; On the serial monitor, you will view that the sensor data was successfully logged and now the ESP32 board will go into deep sleep mode. The ESP32 board goes to deep sleep when esp_deep_sleep_start() function is called. Serial.println("Sensor data logged successfully! Going to sleep"); esp_deep_sleep_start(); loop() The loop() function is empty because it never reaches this part of the program code. The ESP32 goes into deep sleep. void obtainReadings() The obtainReadings() function takes in no parameter. It will access the temperature reading from the DS18B20 sensor and save it in the variable ‘temperature’ which we defined earlier. We will call the requestTemperatures() method. Then we will use the getTempCByIndex() function to retrieve the temperature in degree Celsius. Notice that we are passing 0 as a parameter inside the function. This is because we are using a single DS18B20 sensor. When using multiple sensors this value will increment for each additional sensor. We will display the temperature readings on the serial monitor after every 5 minutes. void obtainReadings(){ sensors.requestTemperatures(); temperature = sensors.getTempCByIndex(0); Serial.print("Temperature: "); Serial.println(temperature); } void obtain_Date_Time() The obtain_Date_Time() fuction also takes in no parameter. It will request the current date and time from the NTP server and save this value in ‘Date.’ This will be achieved by using timeClient.getFormattedDate(). In the serial monitor you will be able to view this timestamp. It will of the kind: 2021-08-23T22:15:35Z Thus, we will have to split the date and the time. To do that we will first create an integer variable named ‘split.’ Then, save the date in the variable ‘day’ and the time in the variable ‘Time.’ These will be displayed in the serial monitor.() The data_logging() function will log the data received from the DS18B20 sensor and the timestamp on the microSD card. This will be saved in the variable ‘Data.’ Data will consist of the sensor readings count (sensor_data), the current date (day), the current time (Time) and the sensor reading( temperature). This will get displayed in the serial monitor. To add this ‘Data’ at the end of our .txt in the microSD card, we will use the appendFile() function. This takes in the SD filesystem, the file path and the content which has to be added. void data_logging() { Data = String(sensor_data) + "," + String(day) + "," + String(Time) + "," + String(temperature) + "\r\n"; Serial.print("Save data: "); Serial.println(Data); appendFile(SD, "/temperature_readings.txt", Data.c_str()); } writeFile() This is the default writeFile() function that takes in three parameters. The first is the SD filesystem, the second is the file path and the third is the content which we want to write in the file.File() To add some content at the end of a file, we will use the appendFile() function. This takes in the SD filesystem, the file path and the content which has to be<< Open your serial monitor. You will be able to view the different messages. After a few minutes, take the microSD card out of the module and insert it in your system to view the temperature_readings.txt file. Open the .txt file. Inside it you will be able to view the temperature readings with their timestamps. We took readings for 25 minutes. Thus, we have a set of 6 readings after every 5 minutes. Conclusion In conclusion, we learned how to create a data logger to log sensor readings to MicroSD card using ESP32 and Arduino IDE. We used a DS18B20 sensor to access the current temperature readings that we logged on our microSD card. Additionally, we requested the current date and time as well through the NTP server for each sensor reading. In the next tutorial, we will show you how to create an ESP32 web server with files that will be saved on the microSD card.
https://microcontrollerslab.com/esp32-data-logging-temperature-sensor-readings-to-microsd-card-arduino-ide/
CC-MAIN-2021-39
refinedweb
2,718
57.87
Mohd Tariq wrote: > Hi Senthil, > > I am building a C++ Application with HP aCC 6.10 compiler. During build it > gave error about iterators "#2135" and later we found that iterators are > not supported by HP aCC6.10.'s STL. > > So now I have been trying to use third party STL that we got from >. I have build that library > successfully. > I am using "+nostl" option to link it to 3rd party STL. > > To check we have written a small cpp program which prints "Hello". The > following are the compiler options that we gave to compile this file: > > aCC -v +DD64 +W829,641 -D_RWSTD_USE_CONFIG -D_RWSTDDEBUG +z -mt > -Wc,-ansi_for_scope,on I don't think you need the ansi_for_scope option, it's on by default. +nostl -I/opt/aCC/include_std > -I/opt/aCC/include_std/iostream_compat -I/home/stdcxx-4.1.3/include > -I/home/build1/nls -I/usr/include -I/usr -L/usr/lib/hpux64 > -L/home/build1/lib -L/opt/langtools/lib/hpux64 -L/opt/aCC/lib/hpux64 > -L/home/build1/rwtest -l:librwtest11D.a -l:libstd11D.so -l: You don't need to link with librwtest unless you're building the stdcxx test suite. Also, you shouln't be linking with the versioned library below. Use the link instead. > libstd11D.so.4.1.3 test.cpp You're compiling and linking in the same step (which is okay). When compiling and linking in two steps, dependent libraries must be listed after the object file on the link line. I suspect the same is going to be true when doing both in one step. > > We are using +nostl option as mentioned in the acc programming guide which > would suppress all default -L and -I options. The options mentioned > above in > bold are to include and link the third party libraries. > > The sample program is: > > #include<iostream> > using namespace std; > int main(){ > cout<<"Hello"; > return 0; > } > > > We are getting errors during the linking stage. The errors are: > > ld: Unsatisfied symbol "std::__rw_std_streams" in file test.o > ld: Unsatisfied symbol "std::ios_base::_C_unsafe_clear(int,int)" in file > test.o > ld: Unsatisfied symbol "_HPMutexWrapper::lock(void*)" in file test.o This suggests that you have a dependency on the HP C++ Standard Library. That would be bad (you can't mix two implementations of the same library in the same program). Martin > ld: Unsatisfied symbol "virtual table of __rw::__rw_thread_error" in file > test.o > ld: Unsatisfied symbol "type info of __rw::__rw_thread_error" in file > test.o > ld: Unsatisfied symbol "_HPMutexWrapper::unlock(void*)" in file test.o > > And when i compiled a sample program which contails templates it gave the > same error as before. > Please anyone help me in this regard, > Thanks and Regards >
http://mail-archives.apache.org/mod_mbox/incubator-stdcxx-dev/200612.mbox/%3C45802B3C.9030800@roguewave.com%3E
CC-MAIN-2014-42
refinedweb
450
57.98
Various ways of Initializing an Array in C++ Hello Everyone! In this tutorial, we will learn about the various ways of initializing an Array,> using namespace std; int main() { cout << "\n\nWelcome to Studytonight :-)\n\n\n"; cout << " ===== Program to demonstrate various ways to Initialize an Array ===== \n\n"; // No intitialization only declaration and hence, each of the array element contains a garbage value float arr[1000]; //To initialize an array to all zeros, initialize only the first value to 0. All 1000 values automatically gets initialized to zero. float zeros[1000] = {0.0}; //If the size is not mentioned, the compiler uses the number of values to be the size of the array int no_of_days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Initial values of pressure(variable) undefined. Only declaration and hence all the elements store a garbage value initially. float pressure[10]; // Only the initial elements contain the characters of the string. Remaining characters gets initialized to zero. char website_name[100] = "Studytonight"; // Array size is 6 (last character is the String end delimeter '\0' ). char greeting[] = "Hello"; return 0; } We hope that this post helped you develop better understanding of the various ways to initialize an array in C++. For any query, feel free to reach out to us via the comments section down below. Keep Learning : )
https://studytonight.com/cpp-programs/various-ways-of-initializing-an-array-in-cpp
CC-MAIN-2021-04
refinedweb
225
51.68
HsOpenSSL is a (part of) OpenSSL binding for Haskell. It can generate RSA keys, read and write PEM files, generate message digests, sign and verify messages, encrypt and decrypt messages. But since OpenSSL is a very large library, it is uneasy to cover everything in it. Features that aren't (yet) supported: So if you find out some features you want aren't supported, you must write your own patch. Happy hacking. Computation of withOpenSSL action initializes the OpenSSL library and computes action. Every applications that use OpenSSL must wrap any other operations related to OpenSSL or they might crash. module Main where import OpenSSL main :: IO () main = withOpenSSL $ do ...
http://hackage.haskell.org/package/HsOpenSSL-0.1/docs/OpenSSL.html
CC-MAIN-2016-22
refinedweb
110
64.3
, 2005-09-23 at 18:18 +0200, Thomas Vander Stichele wrote: > Hi Stefan, > > did you know that documenting args for function-like defines does not > work inline with gtk-doc 1.4 or older ? This breaks the build. Any > solution you know of ? And when I said "args", I meant to say "Returns:" values :) Thomas Dave/Dina : future TV today ! - <-*- thomas (dot) apestaart (dot) org -*-> "You don't need a girlfriend, you need a maid !" "Isn't that the same thing ?" "Uh uh, baby, you're in the wrong century." <-*- thomas (at) apestaart (dot) org -*-> URGent, best radio on the net - 24/7 ! - Hi Stefan, did you know that documenting args for function-like defines does not work inline with gtk-doc 1.4 or older ? This breaks the build. Any solution you know of ? Thomas On Fri, 2005-09-23 at 07:31 -0700, Stefan Kost wrote: > CVS Root: /cvs/gstreamer > Module: gstreamer > Changes by: ensonic > Date: Fri Sep 23 2005 07:31:33 PDT > > Log message: > * > > Modified files: > . : ChangeLog > docs/gst : gstreamer-sections.txt > docs/gst/tmpl : .cvsignore > gst : gstelement.c gstelement.h gstinfo.c gstinfo.h > gstobject.c gstobject.h > Removed files: > docs/gst/tmpl : gstelement.sgml gstinfo.sgml gstobject.sgml > > Links: > > > > > > > > > > > > > > ====Begin Diffs==== > Index: ChangeLog > =================================================================== > RCS file: /cvs/gstreamer/gstreamer/ChangeLog,v > retrieving revision 1.1552 > retrieving revision 1.1553 > diff -u -d -r1.1552 -r1.1553 > --- ChangeLog 23 Sep 2005 11:41:29 -0000 1.1552 > +++ ChangeLog 23 Sep 2005 14:31:21 -0000 1.1553 > @@ -1,3 +1,18 @@ > +2005-09-23 Stefan Kost <ensonic@...> > + > + * > 2005-09-23 Thomas Vander Stichele <thomas at apestaart dot org> > > * check/gst/.cvsignore: > Index: gstreamer-sections.txt > RCS file: /cvs/gstreamer/gstreamer/docs/gst/gstreamer-sections.txt,v > retrieving revision 1.176 > retrieving revision 1.177 > diff -u -d -r1.176 -r1.177 > --- gstreamer-sections.txt 22 Sep 2005 15:08:01 -0000 1.176 > +++ gstreamer-sections.txt 23 Sep 2005 14:31:21 -0000 1.177 > @@ -437,10 +437,10 @@ > GST_STATE_WAIT > GST_ELEMENT_NAME > GST_ELEMENT_PARENT > +GST_ELEMENT_BUS > GST_ELEMENT_CLOCK > GST_ELEMENT_PADS > GST_ELEMENT_ERROR > -GST_ELEMENT_BUS > GST_ELEMENT_WARNING > GST_ELEMENT_IS_LOCKED_STATE > Index: .cvsignore > RCS file: /cvs/gstreamer/gstreamer/docs/gst/tmpl/.cvsignore,v > retrieving revision 1.21 > retrieving revision 1.22 > diff -u -d -r1.21 -r1.22 > --- .cvsignore 21 Sep 2005 09:48:40 -0000 1.21 > +++ .cvsignore 23 Sep 2005 14:31:21 -0000 1.22 > @@ -15,6 +15,7 @@ > gstcollectpads.sgml > gstcompat.sgml > gstconfig.sgml > +gstelement.sgml > gstelementdetails.sgml > gstelementfactory.sgml > gstenumtypes.sgml > @@ -30,11 +31,13 @@ > gstimplementsinterface.sgml > gstindex.sgml > gstindexfactory.sgml > +gstinfo.sgml > gstiterator.sgml > gstmacros.sgml > gstmemchunk.sgml > gstmessage.sgml > gstminiobject.sgml > +gstobject.sgml > gstparse.sgml > gstpluginfeature.sgml > gstpushsrc.sgml > --- gstelement.sgml DELETED --- > --- gstinfo.sgml DELETED --- > --- gstobject.sgml DELETED --- > Index: gstelement.c > RCS file: /cvs/gstreamer/gstreamer/gst/gstelement.c,v > retrieving revision 1.363 > retrieving revision 1.364 > diff -u -d -r1.363 -r1.364 > --- gstelement.c 22 Sep 2005 18:07:22 -0000 1.363 > +++ gstelement.c 23 Sep 2005 14:31:21 -0000 1.364 > @@ -19,7 +19,52 @@ > * Free Software Foundation, Inc., 59 Temple Place - Suite 330, > * Boston, MA 02111-1307, USA. > */ > - > +/** > + * SECTION:gstelement > + * @short_description: Abstract base class for all pipeline elements > + * @see_also: #GstElementFactory, #GstPad > + * > + * GstElement is the base class needed to construct an element that can be > + * used in a GStreamer pipeline. As such, it is not a functional entity, and > + * cannot do anything when placed in a pipeline. > + * > + * The name of a GstElement can be get with gst_element_get_name() and set with > + * gst_element_set_name(). For speed, GST_ELEMENT_NAME() can be used in the > + * core. Do not use this in plug-ins or applications in order to retain ABI > + * compatibility. > + * All elements have pads (of the type #GstPad). These pads link to pads on > + * other elements. Buffers(). > + * Application writers can manipulate ghost pads (copies of real pads inside a bin) > + * with gst_element_add_ghost_pad() and gst_element_remove_ghost_pad(). > + * A pad of an element can be retrieved by name with gst_element_get_pad(). > + * A GList of all pads can be retrieved with gst_element_get_pad_list(). > + *(). > + * You can wait for an element to change it's state with gst_element_wait_state_change(). > + * To get a string representation of a #GstState, use > + * gst_element_state_get_name(). > + * You can get and set a #GstClock on an element using gst_element_get_clock() > + * and gst_element_set_clock(). You can wait for the clock to reach a given > + * #GstClockTime using gst_element_clock_wait(). > + */ > #include "gst_private.h" > #include <glib.h> > #include <stdarg.h> > Index: gstelement.h > RCS file: /cvs/gstreamer/gstreamer/gst/gstelement.h,v > retrieving revision 1.206 > retrieving revision 1.207 > diff -u -d -r1.206 -r1.207 > --- gstelement.h 22 Sep 2005 16:51:27 -0000 1.206 > +++ gstelement.h 23 Sep 2005 14:31:21 -0000 1.207 > @@ -82,7 +82,21 @@ > /* NOTE: this probably should be done with an #ifdef to decide > * whether to safe-cast or to just do the non-checking cast. > + * GST_STATE: > + * @obj: Element to return state for. > + * This macro returns the current state of the element. > #define GST_STATE(obj) (GST_ELEMENT(obj)->current_state) > + * GST_STATE_PENDING: > + * @obj: Element to return the pending state for. > + * This macro returns the currently pending state of the element. > #define GST_STATE_PENDING(obj) (GST_ELEMENT(obj)->pending_state) > #define GST_STATE_FINAL(obj) (GST_ELEMENT(obj)->final_state) > #define GST_STATE_ERROR(obj) (GST_ELEMENT(obj)->state_error) > @@ -125,28 +139,72 @@ > GST_STATE_CHANGE_READY_TO_NULL = 1<<(GST_STATE_READY+8) | 1<<GST_STATE_NULL > } GstStateChange; > + * GstElementFlags: > + * @GST_ELEMENT_LOCKED_STATE: ignore state changes from parent > + * @GST_ELEMENT_IS_SINK: the element is a sink > + * @GST_ELEMENT_UNPARENTING: Child is being removed from the parent bin. > + * gst_bin_remove() on a child already being removed immediately returns FALSE > + * @GST_ELEMENT_FLAG_LAST: offset to define more flags > + * The standard flags that an element may have. > typedef enum > { > - /* ignore state changes from parent */ > GST_ELEMENT_LOCKED_STATE = GST_OBJECT_FLAG_LAST, > - > - /* the element is a sink */ > GST_ELEMENT_IS_SINK, > - /* Child is being removed from the parent bin. gst_bin_remove on a > - * child already being removed immediately returns FALSE */ > GST_ELEMENT_UNPARENTING, > - /* use some padding for future expansion */ > GST_ELEMENT_FLAG_LAST = GST_OBJECT_FLAG_LAST + 16 > } GstElementFlags; > + * GST_ELEMENT_IS_LOCKED_STATE: > + * @obj: A #GstElement to query > + * Check if the element is in the loacked state and therefore will ignore state > + * changes from its parent object. > #define GST_ELEMENT_IS_LOCKED_STATE(obj) (GST_FLAG_IS_SET(obj,GST_ELEMENT_LOCKED_STATE)) > + * GST_ELEMENT_NAME: > + * Gets the name of this element. Use only in core as this is not > + * ABI-compatible. Others use gst_element_get_name() > #define GST_ELEMENT_NAME(obj) (GST_OBJECT_NAME(obj)) > + * GST_ELEMENT_PARENT: > + * Get the parent object of this element. > #define GST_ELEMENT_PARENT(obj) (GST_ELEMENT_CAST(GST_OBJECT_PARENT(obj))) > + * GST_ELEMENT_BUS: > + * Get the message bus of this element. > #define GST_ELEMENT_BUS(obj) (GST_ELEMENT_CAST(obj)->bus) > + * GST_ELEMENT_CLOCK: > + * Get the clock of this element > #define GST_ELEMENT_CLOCK(obj) (GST_ELEMENT_CAST(obj)->clock) > + * GST_ELEMENT_PADS: > + * Get the pads of this elements. > #define GST_ELEMENT_PADS(obj) (GST_ELEMENT_CAST(obj)->pads) > /** > @@ -176,7 +234,20 @@ > __txt, __dbg, __FILE__, GST_FUNCTION, __LINE__); \ > } G_STMT_END > -/* log a (non-fatal) warning message and post it on the bus */ > + * GST_ELEMENT_WARNING: > + * @el: the element that throws the error > + * @domain: like CORE, LIBRARY, RESOURCE or STREAM (see #GstError) > + * @code: error code defined for that domain (see #GstError) > + * @text: the message to display (format string and args enclosed in > + parentheses) > + * @debug: debugging information for the message (format string and args > + enclosed in parentheses) > + * Utility function that elements can use in case they encountered a non-fatal > + * data processing problem. The pipeline will throw a warning signal and the > + * application will be informed. > #define GST_ELEMENT_WARNING(el, domain, code, text, debug) \ > G_STMT_START { \ > gchar *__txt = _gst_element_error_printf text; \ > @@ -304,9 +375,43 @@ > GType gst_element_get_type (void); > /* basic name and parentage stuff from GstObject */ > + * gst_element_get_name: > + * @elem: a #GstElement to set the name of. > + * @name: the new name of the element. > + * Gets the name of the element. > #define gst_element_get_name(elem) gst_object_get_name(GST_OBJECT(elem)) > + * gst_element_set_name: > + * Sets the name of the element, getting rid of the old name if there was one. > + * Returns: the name of the element. > #define gst_element_set_name(elem,name) gst_object_set_name(GST_OBJECT(elem),name) > + * gst_element_get_parent: > + * @elem: a #GstElement to get the parent of. > + * Gets the parent of an element. > + * Returns: the #GstObject parent of the element. > #define gst_element_get_parent(elem) gst_object_get_parent(GST_OBJECT(elem)) > + * gst_element_set_parent: > + * @elem: a #GstElement to set the parent of. > + * @name: the new parent #GstObject of the element. > + * Sets the parent of an element. > #define gst_element_set_parent(elem,parent) gst_object_set_parent(GST_OBJECT(elem),parent) > /* clocking */ > Index: gstinfo.c > RCS file: /cvs/gstreamer/gstreamer/gst/gstinfo.c,v > retrieving revision 1.105 > retrieving revision 1.106 > diff -u -d -r1.105 -r1.106 > --- gstinfo.c 21 Sep 2005 21:39:06 -0000 1.105 > +++ gstinfo.c 23 Sep 2005 14:31:21 -0000 1.106 > @@ -20,6 +20,64 @@ > + * SECTION:gstinfo > + * @short_description: Debugging and logging facillities > + * @see_also: #GstConfig, #Gst for command line parameters > + * and environment variables that affect the debugging output. > + * GStreamer's debugging subsystem is an easy way to get information about what > + * the application is doing. > + * It is not meant for programming errors. Use GLibs methods (g_warning and so > + * on for that. > + * The debugging subsystem works only after GStreamer has been initilized > + * - for example by calling gst_init(). > + * The debugging subsystem is used to log informational messages while the > + * application runs. > + * Each messages has some properties attached to it. Among these properties > + * are the debugging category, the severity (called "level" here) and an obtional > + * #GObject it belongs to. Each of these messages is sent to all registered > + * debugging handlers, which then handle the messages. GStreamer attaches a > + * default handler on startup, which outputs requested messages to stderr. > + * Messages are output by using shortcut macros like #GST_DEBUG, > + * #GST_CAT_ERROR_OBJECT or similar. These all expand to calling gst_debug_log() > + * with the right parameters. > + * The only thing a developer will probably want to do is define his own > + * categories. This is easily done with 3 lines. At the top of your code, declare > + * the variables and set the default category. > + * <informalexample> > + * <programlisting> > + * GST_DEBUG_CATEGORY (my_category); // define category > + * &hash;define GST_CAT_DEFAULT my_category // set as default > + * </programlisting> > + * </informalexample> > + * After that you only need to initialize the category. > + * GST_DEBUG_CATEGORY_INIT (my_category, "my category", 0, "This is my very own"); > + * Initialization must be done before the category is used first. Plugins do this > + * in their plugin_init function, libraries and applications should do that > + * during their initialization. > + * The whole debugging subsystem can be disabled at build time with passing the > + * --disable-gst-debug switch to configure. If this is done, every function, macro > + * and even structs described in this file evaluate to default values or nothing > + * at all. So don't take addresses of these functions or use other tricks. > + * If you must do that for some reason, there is still an option. If the debugging > + * subsystem was compiled out, #GST_DISABLE_GST_DEBUG is defined in <gst/gst.h>, > + * so you can check that before doing your trick. > + * Disabling the debugging subsystem will give you a slight (read: unnoticable) > + * speed increase and will reduce the size of your compiled code. The GStreamer > + * library itself becomes around 10% smaller. > + * Please note that there are naming conventions for the names of debugging > + * categories. These are explained at GST_DEBUG_CATEGORY_INIT(). > #include "gstinfo.h" > Index: gstinfo.h > RCS file: /cvs/gstreamer/gstreamer/gst/gstinfo.h,v > retrieving revision 1.85 > retrieving revision 1.86 > diff -u -d -r1.85 -r1.86 > --- gstinfo.h 20 Jul 2005 16:20:39 -0000 1.85 > +++ gstinfo.h 23 Sep 2005 14:31:21 -0000 1.86 > @@ -30,14 +30,36 @@ > G_BEGIN_DECLS > -/* > - * GStreamer's debugging subsystem is an easy way to get information about what > - * the application is doing. > - * It is not meant for programming errors. Use GLibs methods (g_warning and so > - * on for that. > + * GstDebugLevel: > + * @GST_LEVEL_NONE: No debugging level specified or desired. Used to deactivate > + * debugging output. > + * @GST_LEVEL_ERROR: Error messages are to be used only when an error occured > + * that stops the application from keeping working correctly. > + * An examples is gst_element_error, which outputs a message with this priority. > + * It does not mean that the application is terminating as with g_errror. > + * @GST_LEVEL_WARNING: Warning messages are to inform about abnormal behaviour > + * that could lead to problems or weird behaviour later on. An example of this > + * would be clocking issues ("your computer is pretty slow") or broken input > + * data ("Can't synchronize to stream.") > + * @GST_LEVEL_INFO: Informational messages should be used to keep the developer > + * updated about what is happening. > + * Examples where this should be used are when a typefind function has > + * successfully determined the type of the stream or when an mp3 plugin detects > + * the format to be used. ("This file has mono sound.") > + * @GST_LEVEL_DEBUG: Debugging messages should be used when something common > + * happens that is not the expected default behavior. > + * An example would be notifications about state changes or receiving/sending of > + * events. > + * @GST_LEVEL_LOG: Log messages are messages that are very common but might be > + * useful to know. As a rule of thumb a pipeline that is iterating as expected > + * should never output anzthing else but LOG messages. > + * Examples for this are referencing/dereferencing of objects or cothread switches. > + * @GST_LEVEL_COUNT: The number of defined debugging levels. > + * The level defines the importance of a debugging message. The more important a > + * message is, the greater the probability that the debugging system outputs it. > -/* log levels */ > typedef enum { > GST_LEVEL_NONE = 0, > GST_LEVEL_ERROR, > @@ -49,8 +71,16 @@ > GST_LEVEL_COUNT > } GstDebugLevel; > -/* we can now override this to be more general in maintainer builds > - * or cvs checkouts */ > + * GST_LEVEL_DEFAULT: > + * Defines the default debugging level to be used with GStreamer. It is normally > + * set to #GST_LEVEL_NONE so nothing get printed. > + * As it can be configured at compile time, developer builds may chose to > + * override that though. > + * You can use this as an argument to gst_debug_set_default_threshold() to > + * reset the debugging output to default behaviour. > #ifndef GST_LEVEL_DEFAULT > #define GST_LEVEL_DEFAULT GST_LEVEL_NONE > #endif > @@ -64,6 +94,30 @@ > * Background color codes: > * 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white > + * GstDebugColorFlags: > + * @GST_DEBUG_FG_BLACK: Use black as foreground color. > + * @GST_DEBUG_FG_RED: Use red as foreground color. > + * @GST_DEBUG_FG_GREEN: Use green as foreground color. > + * @GST_DEBUG_FG_YELLOW: Use yellow as foreground color. > + * @GST_DEBUG_FG_BLUE: Use blue as foreground color. > + * @GST_DEBUG_FG_MAGENTA: Use magenta as foreground color. > + * @GST_DEBUG_FG_CYAN: Use cyan as foreground color. > + * @GST_DEBUG_FG_WHITE: Use white as foreground color. > + * @GST_DEBUG_BG_BLACK: Use black as background color. > + * @GST_DEBUG_BG_RED: Use red as background color. > + * @GST_DEBUG_BG_GREEN: Use green as background color. > + * @GST_DEBUG_BG_YELLOW: Use yellow as background color. > + * @GST_DEBUG_BG_BLUE: Use blue as background color. > + * @GST_DEBUG_BG_MAGENTA: Use magenta as background color. > + * @GST_DEBUG_BG_CYAN: Use cyan as background color. > + * @GST_DEBUG_BG_WHITE: Use white as background color. > + * @GST_DEBUG_BOLD: Make the output bold. > + * @GST_DEBUG_UNDERLINE: Underline the output. > + * These are some terminal style flags you can use when creating your > + * debugging categories to make them stand out in debugging output. > /* colors */ > GST_DEBUG_FG_BLACK = 0x0000, > @@ -93,6 +147,12 @@ > #define GST_DEBUG_FORMAT_MASK (0xFF00) > typedef struct _GstDebugCategory GstDebugCategory; > + * GstDebugCategory: > + * This is the struct that describes the categories. Once initialized with > + * #GST_DEBUG_CATEGORY_INIT, its values can't be changed anymore. > struct _GstDebugCategory { > /*< private >*/ > gint threshold; > @@ -104,17 +164,39 @@ > /********** some convenience macros for debugging **********/ > -/* This is needed in printf's if a char* might be NULL. Solaris crashes then. */ > + * GST_STR_NULL: > + * @str: The string to check. > + * Macro to use when a string must not be NULL, but may be NULL. If the string > + * is NULL, "(NULL)" is printed instead. > + * In GStreamer printf string arguments may not be NULL, because on some > + * platforms (ie Solaris) the libc crashes in that case. This includes debugging > + * strings. > #define GST_STR_NULL(str) ((str) ? (str) : "(NULL)") > -/* easier debugging for pad names */ > /* FIXME, not MT safe */ > + * GST_DEBUG_PAD_NAME: > + * @pad: The pad to debug. > + * Evaluates to 2 strings, that describe the pad. Often used in debugging > + * statements. > #define GST_DEBUG_PAD_NAME(pad) \ > (GST_OBJECT_PARENT(pad) != NULL) ? \ > GST_STR_NULL (GST_OBJECT_NAME (GST_OBJECT_PARENT(pad))) : \ > "''", GST_OBJECT_NAME (pad) > -/* You might want to define GST_FUNCTION in apps' configure script. */ > + * GST_FUNCTION: > + * This macro should evaluate to the name of the current function and be should > + * be defined when configuring your project, as it is compiler dependant. If it > + * is not defined, some default value is used. It is used to provide debugging > + * output with the function name of the message. > #ifndef GST_FUNCTION > #if defined (__GNUC__) > # define GST_FUNCTION ((const char*) (__PRETTY_FUNCTION__)) > @@ -275,10 +357,26 @@ > gchar * gst_debug_construct_term_color (guint colorinfo); > + * GST_CAT_DEFAULT: > + * Default gstreamer core debug log category. Please define your own. > GST_EXPORT GstDebugCategory * GST_CAT_DEFAULT; > /* this symbol may not be used */ > extern gboolean __gst_debug_enabled; > + * GST_CAT_LEVEL_LOG: > + * @cat: category to use > + * @level: the severity of the message > + * @object: the #GObject the message belongs to or NULL if none > + * @...: A printf-style message to output > + * Outputs a debugging message. This is the most general macro for outputting > + * debugging messages. You will probably want to use one of the ones described > + * below. > #ifdef G_HAVE_ISO_VARARGS > #define GST_CAT_LEVEL_LOG(cat,level,object,...) G_STMT_START{ \ > if (__gst_debug_enabled) { \ > @@ -318,6 +416,156 @@ > #endif /* G_HAVE_ISO_VARARGS */ > + * GST_CAT_ERROR_OBJECT: > + * @obj: the #GObject the message belongs to > + * @...: printf-style message to output > + * Output an error message belonging to the given object in the given category. > + * GST_CAT_WARNING_OBJECT: > + * Output a warning message belonging to the given object in the given category. > + * GST_CAT_INFO_OBJECT: > + * Output an informational message belonging to the given object in the given > + * category. > + * GST_CAT_DEBUG_OBJECT: > + * Output an debugging message belonging to the given object in the given category. > + * GST_CAT_LOG_OBJECT: > + * Output an logging message belonging to the given object in the given category. > + * GST_CAT_ERROR: > + * Output an error message in the given category. > + * GST_CAT_WARNING: > + * Output an warning message in the given category. > + * GST_CAT_INFO: > + * Output an informational message in the given category. > + * GST_CAT_DEBUG: > + * Output an debugging message in the given category. > + * GST_CAT_LOG: > + * Output an logging message in the given category. > + * GST_ERROR_OBJECT: > + * Output an error message belonging to the given object in the default category. > + * GST_WARNING_OBJECT: > + * Output a warning message belonging to the given object in the default category. > + * GST_INFO_OBJECT: > + * Output an informational message belonging to the given object in the default > + * GST_DEBUG_OBJECT: > + * Output a debugging message belonging to the given object in the default > + * GST_LOG_OBJECT: > + * Output a logging message belonging to the given object in the default category. > + > + * GST_ERROR: > + * Output an error message in the default category. > + * GST_WARNING: > + * Output a warning message in the default category. > + * GST_INFO: > + * Output an informational message in the default category. > + * GST_DEBUG: > + * Output a debugging message in the default category. > + * GST_LOG: > + * Output a logging message in the default category. > #define GST_CAT_ERROR_OBJECT(cat,obj,...) GST_CAT_LEVEL_LOG (cat, GST_LEVEL_ERROR, obj, __VA_ARGS__) > @@ -592,14 +840,36 @@ > /********** function pointer stuff **********/ > typedef void (* GstDebugFuncPtr) (void); > void _gst_debug_register_funcptr (GstDebugFuncPtr func, > gchar * ptrname); > G_CONST_RETURN gchar * > _gst_debug_nameof_funcptr (GstDebugFuncPtr func); > + * GST_DEBUG_FUNCPTR: > + * @ptr: pointer to the function to register > + * Register a pointer to a function with its name, so it can later be used by > + * GST_DEBUG_FUNCPTR_NAME(). > + * Returns: The ptr to the function > #define GST_DEBUG_FUNCPTR(ptr) \ > (_gst_debug_register_funcptr((GstDebugFuncPtr)(ptr), #ptr) , ptr) > + * GST_DEBUG_FUNCPTR_NAME: > + * @ptr: pointer to the function to look up the name > + * Retrieves the name of the function, if it was previously registered with > + * GST_DEBUG_FUNCPTR(). If not, it returns a description of the pointer. > + * Make sure you free the string after use. > + * Returns: The name of the function > #define GST_DEBUG_FUNCPTR_NAME(ptr) \ > _gst_debug_nameof_funcptr((GstDebugFuncPtr)ptr) > Index: gstobject.c > RCS file: /cvs/gstreamer/gstreamer/gst/gstobject.c,v > retrieving revision 1.96 > retrieving revision 1.97 > diff -u -d -r1.96 -r1.97 > --- gstobject.c 20 Sep 2005 11:09:50 -0000 1.96 > +++ gstobject.c 23 Sep 2005 14:31:21 -0000 1.97 > @@ -20,6 +20,60 @@ > + * SECTION:gstobject > + * @short_description: Base class for the GStreamer object hierarchy > + * GstObject provides a root for the object hierarchy tree filed in by the > + * G; calling gst_object_unref() on the newly-created GtkObject is incorrect. > + *(). > + * In contrast to GObject instances GstObject add a name property. The functions > + * gst_object_set_name() and gst_object_get_name() are used to set/get the name > + * of the object. > @@ -44,7 +98,7 @@ > * we use our own atomic refcounting to do proper MT safe refcounting. > * > * The hack has several side-effect. At first you should use > - * gst_object_ref/unref() whenever you can. Next When using g_value_set/get_object(); > + * gst_object_ref/unref() whenever you can. Next when using g_value_set/get_object(); > * you need to manually fix the refcount. > * A proper fix is of course to make the glib refcounting threadsafe which is > @@ -168,16 +222,42 @@ > g_param_spec_string ("name", "Name", "The name of the object", > NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT)); > + /** > + * GstObject::parent-set: > + * @gstobject: the object which received the signal. > + * @parent: the new parent > + * > + * Is emitted when the parent of an object is set. > + */ > gst_object_signals[PARENT_SET] = > g_signal_new ("parent-set", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, > G_STRUCT_OFFSET (GstObjectClass, parent_set), NULL, NULL, > g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_OBJECT); > + * GstObject::parent-unset: > + * @parent: the old parent > + * Is emitted when the parent of an object is unset. > gst_object_signals[PARENT_UNSET] = > g_signal_new ("parent-unset", G_TYPE_FROM_CLASS (klass), > G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstObjectClass, parent_unset), NULL, > NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_OBJECT); > #ifndef GST_DISABLE_LOADSAVE_REGISTRY > - /* FIXME This should be the GType of xmlNodePtr instead of G_TYPE_POINTER */ > + * GstObject::object-saved: > + * @xml_node: the xmlNodePtr of the parent node > + * Is trigered whenever a new object is saved to XML. You can connect to this > + * signal to insert custom XML tags into the core XML. > + /* FIXME This should be the GType of xmlNodePtr instead of G_TYPE_POINTER > + * (if libxml would use GObject) > gst_object_signals[OBJECT_SAVED] = > g_signal_new ("object-saved", G_TYPE_FROM_CLASS (klass), > G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstObjectClass, object_saved), NULL, > @@ -185,6 +265,17 @@ > klass->restore_thyself = gst_object_real_restore_thyself; > + * GstObject::deep-notify: > + * @prop_object: the object that originated the signal > + * @prop: the property that changed > + * The deep notify signal is used to be notified of property changes. It is > + * typically attached to the toplevel bin to receive notifications from all > + * the elements contained in that bin. > gst_object_signals[DEEP_NOTIFY] = > g_signal_new ("deep-notify", G_TYPE_FROM_CLASS (klass), > G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | > Index: gstobject.h > RCS file: /cvs/gstreamer/gstreamer/gst/gstobject.h,v > retrieving revision 1.58 > retrieving revision 1.59 > diff -u -d -r1.58 -r1.59 > --- gstobject.h 20 Sep 2005 11:09:50 -0000 1.58 > +++ gstobject.h 23 Sep 2005 14:31:21 -0000 1.59 > @@ -41,12 +41,20 @@ > #define GST_OBJECT_CAST(obj) ((GstObject*)(obj)) > #define GST_OBJECT_CLASS_CAST(klass) ((GstObjectClass*)(klass)) > -/* make sure we don't change the object size but stil make it compile > +/* make sure we don't change the object size but still make it compile > * without libxml */ > #ifdef GST_DISABLE_LOADSAVE_REGISTRY > #define xmlNodePtr gpointer > + * GstObjectFlags: > + * @GST_OBJECT_DISPOSING: the object is been destroyed, do use it anymore > + * @GST_OBJECT_FLOATING: the object has a floating reference count (e.g. its > + * not assigned to a bin) > + * @GST_OBJECT_FLAG_LAST: subclasses can add additional flags starting from this flag > GST_OBJECT_DISPOSING = 0, > @@ -65,26 +73,112 @@ > /* we do a GST_OBJECT_CAST to avoid type checking, better call these > * function with a valid object! */ > + * GST_LOCK: > + * @obj: Object to lock. > + * This macro will obtain a lock on the object, making serialization possible. > + * It block until the lock can be obtained. > #define GST_LOCK(obj) g_mutex_lock(GST_OBJECT_CAST(obj)->lock) > + * GST_TRYLOCK: > + * @obj: Object to try to get a lock on. > + * This macro will try to obtain a lock on the object, but will return with > + * FALSE if it can't get it immediately. > #define GST_TRYLOCK(obj) g_mutex_trylock(GST_OBJECT_CAST(obj)->lock) > + * @obj: Object to unlock. > + * This macro releases a lock on the object. > #define GST_UNLOCK(obj) g_mutex_unlock(GST_OBJECT_CAST(obj)->lock) > + * @obj: Object to get the mutex of. > + * Acquire a reference to the mutex of this object. > #define GST_GET_LOCK(obj) (GST_OBJECT_CAST(obj)->lock) > + * GST_OBJECT_NAME: > + * @obj: Object to get the name of. > + * Get the name of this object > #define GST_OBJECT_NAME(obj) (GST_OBJECT_CAST(obj)->name) > + * GST_OBJECT_PARENT: > + * @obj: Object to get the parent of. > + * Get the parent of this object > #define GST_OBJECT_PARENT(obj) (GST_OBJECT_CAST(obj)->parent) > -/* for the flags we double-not to make them comparable to TRUE and FALSE */ > + * GST_FLAGS: > + * @obj: Object to return flags for. > + * This macro returns the entire set of flags for the object. > #define GST_FLAGS(obj) (GST_OBJECT_CAST (obj)->flags) > +/* for the flags we double-not to make them comparable to TRUE and FALSE */ > + * GST_FLAG_IS_SET: > + * @obj: Object to check for flags. > + * @flag: Flag to check for, must be a single bit in guint32. > + * This macro checks to see if the given flag is set. > #define GST_FLAG_IS_SET(obj,flag) (!!(GST_FLAGS (obj) & (1<<(flag)))) > + * GST_FLAG_SET: > + * @obj: Object to set flag in. > + * @flag: Flag to set, can by any number of bits in guint32. > + * This macro sets the given bits. > #define GST_FLAG_SET(obj,flag) G_STMT_START{ (GST_FLAGS (obj) |= (1<<(flag))); }G_STMT_END > + * GST_FLAG_UNSET: > + * @obj: Object to unset flag in. > + * @flag: Flag to set, must be a single bit in guint32. > + * This macro usets the given bits. > #define GST_FLAG_UNSET(obj,flag) G_STMT_START{ (GST_FLAGS (obj) &= ~(1<<(flag))); }G_STMT_END > + * GST_OBJECT_IS_DISPOSING: > + * @obj: Object to check > + * Check if the given object is beeing destroyed. > #define GST_OBJECT_IS_DISPOSING(obj) (GST_FLAG_IS_SET (obj, GST_OBJECT_DISPOSING)) > + * GST_OBJECT_IS_FLOATING: > + * @obj:Object to check > + * Check if the given object is floating (has no owner). > #define GST_OBJECT_IS_FLOATING(obj) (GST_FLAG_IS_SET (obj, GST_OBJECT_FLOATING)) > typedef struct _GstObject GstObject; > typedef struct _GstObjectClass GstObjectClass; > + * GstObject: > + * @name: The name of the object > struct _GstObject { > GObject object; > > > ------------------------------------------------------- > SF.Net email is sponsored by: > Tame your development challenges with Apache's Geronimo App Server. > Download it for free - -and be entered to win a 42" plasma tv or your very > own Sony(tm)PSP. Click here to play: > _______________________________________________ > gstreamer-cvs-verbose mailing list > gstreamer-cvs-verbose@... > Dave/Dina : future TV today ! - <-*- thomas (dot) apestaart (dot) org -*-> What should I tell her She's going to ask If I ignore it it gets uncomfortable She'll want to argue about the past <-*- thomas (at) apestaart (dot) org -*-> URGent, best radio on the net - 24/7 ! - Benjamin > I've recently gotten a bluetooth headset and had wondered about using it > on Linux and seeing how bluetooth headsets are handled in Linux left me > extremely unimpressed. And that was architecturally, not the fact that it > didn't work ;) I'm glad you can see how messy and incomplete it is. What we have now is a prototype. We need to move the audio drivers out of the kernel with a decent alsa and/or gstreamer plugin. The alsa plugin api has been changing... it was rewritten and I think they recently added an api for clients to discover alsa-lib plugins but no clients are using it yet. > I had expected that when I connect a bluetooth headset to my computer it > automatically creates a sound card device Some of what you want needs to be hooked into the desktop bluetooth helper app(s) > So a GStreamer-only solution, while probably easier to code, would have > lots of apps unable to use the headset. Ok, that sounds reasonable. I guess gstreamer could make use of an alsa-lib plugin indirectly, eh? > PS: Are you bluetooth-alsa guys on IRC smewhere? I'd like some > hand-holding while digging through the Bluetooth and kernel code - which > is even less documented than ALSA, who'd have thought. At least the 1250 > pages Bluetooth core protocol docs are available ;) Not really but it's a good idea. If there's a good place on irc to discuss alsa-lib plugin work you might see me there since I am struggling with this stage. Brad On Fri, 2005-09-23 at 10:18 +0200, Stefan Kost wrote: > My systems use gentoo and suse and neither one has glib-2.8 packages > in their > stable versions yet. You're wrong here, I'm running Gentoo with Gnome2.12, gtk+2.8 (and glib2.8 with it) fine, glib2.8 is ~x86, but updating from 2.6 (even only glib) was easy and didn't break things. echo "=dev-libs/glib-2.8* ~x86" >> /etc/portage/package.keywords :) Ikke Even though I am not counted as core-dev and thus have no vote here my pov: if gst-0.9 would require glib-2.8 right now, I would not be able to contribute anymore. My systems use gentoo and suse and neither one has glib-2.8 packages in their stable versions yet. Stefan David Schleef wrote: > On Thu, Sep 22, 2005 at 04:00:58PM -0400, Ronald S. Bultje wrote: > >>>heh :) that's a bit silly isn't it ? You haven't even given any reason >>>to need 2.8 for any of the work you've done on the 0.9 branch. >> >>We've had that discussion, it's recurring. Let's just vote, decide and >>be done with it. > > > I'm leaning toward having a policy that development versions of > gstreamer should not rely on package versions that are not in > the latest release of popular 6-month-cycle distros. This gives > us a much lower barrier to entry of both testers and developers, > which I like. > > Thus, on the day that FC5 and Breezy are released, I think we > should bump the requirement to glib-2.8. > > > > dave... > I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/gstreamer/mailman/gstreamer-devel/?viewmonth=200509&viewday=23
CC-MAIN-2016-36
refinedweb
4,652
50.53
Ora Lassila (Nokia) is a long-time W3C participant and member of the W3C Advisory Board. He also is one of the early proponents of the Semantic Web. I spoke with him about getting the best that Web apps and linked data have to offer — together. IJ: I read your CIDOC 2012 keynote “Love Thy Data (or: Apps Considered Harmful).” I would paraphrase the thesis as “Data have longevity; the life of code is short.” Why do your portray data and apps as being in conflict? OL: I am not hostile to software per se. But you get the feeling that everything today is about apps! It’s like a curse. To me, it borders on the profane to say you need a specific app for some narrow activity. IJ: What do you mean? OL: I see two categories of apps. The first lets you use features of your device, such as your camera. These apps are necessary. The second kind packages and insulates content from the rest of the Web. Every organization seems to feel it has content that warrants being packaged as an app. But when they insulate their content from the rest of the Web, bad things happen. We lose all the web goodness. Many of the original principles that underlie the web are really good ones, and give us linking, bookmarking, sharing bookmarks, and so on. We lose that when people create islands of content. This is a step backwards to life before the Web. IJ: Why do you think people do this? OL: One reason is that some people think that apps are the predominant way to monetize content in the mobile world. A lot of people talk about mobile ads. I’m not entirely convinced that monetization through mobile ads in native apps is happening at a large scale. On the other hand, I do see that advertising on the Web is highly lucrative for some companies. IJ: And yet native apps have done well. OL: Apps don’t serve users, they serve publishers of software. They provide a way to package and deploy content. What’s more, I don’t think users care. Users care about good content. And good content is that which integrates with the larger web. Installation and delivery are side issues. In a sense, the whole notion of an app is an antiquated idea. IJ: Do you see particular obstacles to HTML5 becoming dominant? OL: I think early on there was a need to create native apps for various reasons such as performance or to achieve a particular required user experience. But things have changed —very rapidly— and now we can provide users with that functionality using web technology. Performance may still be an issue if we are talking about accessing a particular hardware capability. But it’s certainly not an issue in the case of delivering a newspaper article. The Financial Times has a Web app that is more popular than their native app. Amazon has been building their Kindle cloud reader, their app for consuming Kindle content not on a Kindle. It’s built with HTML5 to replace the native app they had built earlier. That means the content is delivered through the web and not through a native app that has to be installed through an app store. When you are just talking about delivering content, we have crossed the threshold and it’s now possible to do so using Web technology on mobile devices. As a bonus, you get to integrate your content with other parts of the Web. And I think it’s great that W3C is getting more involved in games. I think that when we truly get to the point where games can be delivered as web apps we’ll have made huge progress. IJ: Web APIs are proliferating. How does this relate to your ideas for data integration? OL: I see the Open Web Platform and Linked Data together offering a solution. Good APIs are a step in the right direction. They give apps access to same functionality and data. But eventually things will become very complex because you have a large number of APIs that you need to take into account. The challenge in API-based integration is: what do you do about use cases you did not anticipate? In the longer term we must provide integration between silos. I want to have data that can move freely, that has been engineered to integrate easily with other data. Linked data standards are a very good candidate solution for achieving this. Other options may come along, but today linked data is the top contender. IJ: How would that improve integration? OL: There are 3 parts to an app: data, logic, presentation. In many apps, there is little logic, and it is possible to use Web technology for both the data and presentation. But the way apps are built today in general, all three are insulated from the rest of the world. This makes it harder to learn about and reuse the data. Native platforms do not really support (let alone encourage) integration with other applications. Where you do see native app integration, it is because OS vendors have packaged them. IJ: So why aren’t the world’s app developers already slurping up masses of linked data to reap the benefits? OL: Good question. I think the biggest stumbling block for Linked Open Data (LOD) is: what’s the business model? People understand the indirect benefits of linked data, but few people have a handle on how to monetize it directly. For example, because data is often consumed by software agents, attaching advertising to the data is unlikely to be effective. It is also the case that people hesitate to give up their data. For instance, museums may be interested in opening up catalogs and in people being able to combine slices of catalogs. But they may be worried that by opening their catalog they are giving away something. There’s also a cost issue. Publishing data is great, but not free. For example, there is a cost to running servers capable of handling complex SPARQL queries. IJ: But people sell data all the time. Why is this more of a challenge with linked data? Do you think the openness of the format plays a role? OL: Most definitely. But you are correct, people do sell data. This should be possible, but it’s harder a question than it first seems. I think we need to do more work in this area. IJ: You said that people hesitate to share data. Is there a place for digital rights management here? OL: Digital rights management with linked data can be tricky because linked data lets you make use of fine-grained data. Current DRM technology is well-suited for much larger chunks. Semantic Web technology allows us to track the provenance (and potentially ownership) of small pieces of data, even after those pieces have been combined with data from many other sources into something bigger. This is absolutely one of the most attractive things about the technologies we’ve defined: fine-grained integration is possible, and you can take apart the data later with reliable provenance information. Provenance information is important in a world of aggregation since we may prefer some sources more than others for various social reasons. IJ: What else do you think makes linked data technology attractive? OL: I work in a big data analytics team. We’ve noticed that having descriptions of data —of what the data means, what you can do with it, and so on— adds tremendous value to the data. We want to describe the bits so that others can make use of them. That’s where Semantic Web technology is so attractive. Data silos arise even within a single organization when people don’t describe their data. The better the description, the greater the chances you or anyone else will reuse your data. Ontologies make data semantics accessible. IJ: What can we do to promote this vision of linked-data driven apps? OL: W3C has done a good job creating a set of specifications that can be used to build good things. Now I think we need more education to help people make the best use of what we’ve got. For instance, we’ve just started the Linked Data Platform Working Group on the application of these linked data technologies. We also need to help developers reap these benefits through talks and sharing good practices. I’m pleased to see more and more conferences geared to the industrial use of linked data technology. We need to hear the success stories. IJ: Does JSON give you what you need for data-driven apps? OL: JSON is easy to use for some situations. Developers like it, the data are easy to use. But JSON doesn’t solve the difficult problems we set out to solve with the Semantic Web. IJ: Such as? OL: While there are discussions about improving JSON, the ones I have seen are focused on syntax —like whether JSON parsers should allow the trailing comma. Please let’s elevate the discussion above syntax. All problems with syntax have already been solved. There is no need to define another syntax, ever. Minimally, I am interested in questions like namespaces to facilitate global sharing. Schema.org is a commendable effort on the data model front, and will help people reuse models and avoid incompatibilities. However, schema.org does not clearly state how to extend their models. When people see data they think they know what it means. They have a hard time discerning what they know from what is actually embodied in the data itself. People end up writing software the encapsulates some of the data semantics, keeping them implicit, and thus limiting reuse. We solved this problem in the early days of the semantic web. I fear that with schema.org we are in the same situation we were in with microformats, where the lack of extensibility of microformats became an issue. With each new format, you had to write new software, which doesn’t scale. The more software you write the more complex your system becomes. There are questions we should be able to solve once and then move up the stack to solve more interesting problems. IJ: What do you think is missing from the developer toolkit to build linked data powered apps? OL: There’s plenty of software already. The obstacle is more mindset than tools. We have some exciting technology to solve these problems. We’ve got some remaining issues but for me the real obstacle remains the business model. I encourage readers to think about solving that problem. IJ: What mindset would you encourage? OL: People need to think about engineering for serendipity. It no longer suffices to design for a well-defined and finite set of requirements. You need to design for change and unanticipated reuse. IJ: What about designing for mobile? OL: Several years ago Tim Berners-Lee made the case at Nokia for “One Web,” including on mobile. Tim argued that if you separate mobile devices from the web, that you are not creating a utopia for mobile devices, but rather a mobile ghetto. That remark resonated within the company. Since then, Nokia has become a big proponent for making standard Web technologies applicable on mobile devices. This is an area where W3C had a strong impact on Nokia’s activities. When I joined Nokia in 1996, nobody knew what W3C was or what we should do about the Web. I would argue that W3C is now one of the most important standards organizations that we work with. And has been for a while. IJ: Any other notes on W3C given your experience? OL: W3C has come a long way with respect to how the standards-making machinery works. In the early years, we discovered ways of working together (both within W3C and between Nokia and W3C). Over the years —thanks significantly to Art Barstow’s contribution— the W3C/Nokia relation has become more clearly defined. The W3C Patent Policy also had a big impact. IJ: Ora, thanks for your time! Photo credit: Grace Lassila 3 thoughts on “Interview: Ora Lassila on Web Apps Powered by Linked Data” This interview makes some good points. But I disagree with the following two sentences: I agree that the syntactic issues for developing efficient compilers for mapping one notation to another were mostly solved in the 1960s. But there are still a huge number of human factors issues and efficiency issues about developing good notations for different purposes on different platforms and devices. By that, I would include graphic notations as well as linear notations. UML, for example, has proved to be much more readable and humanly usable than any of the Semantic Web notations. Much more R & D is required to develop notations and tools that the average programmer can use (and the average teacher can teach). I agree that JSON is primarily a syntactic notation. I call it “LISP with curly braces”. I also agree that focusing on syntactic tweaks for JSON is a trivial matter. For human factors, however, JSON is an immense improvement over the XML-based notations. I would recommend JSON as the primary notation for publishing RDF resources and OWL ontologies. If you adopt JSON as primary, there is no need for auxiliary notations such as N3 and Turtle. The XML-based notation should be limited to applications that require short XML snippets intermixed with text. As for the second sentence, I would say that there is very little need to define a new logic-based semantics. Instead, all the logics used for the Semantic Web should be based on a very general, highly expressive common semantics. RDF, RDFS, OWL, SPARQL, RIF, and many other useful logics could then be defined as restricted syntaxes for expressing different subsets of the common semantics. I suggest UML as an example of a family of different graphic syntaxes that are specialized for different purposes. Unfortunately, the UML designers made the same mistake as the W3C: They did not define a common logic-based semantics for all the notations. Recommendation: The W3C should focus on a common semantics for all logic-based components. The semantics for each notation, graphic or linear, would be specified by its mapping to the common semantics. Notations such as JSON and UML can be incorporated into the Semantic Web toolkit just by defining a mapping to the common semantics. The Object Management Group (OMG) has a great deal of experience in integrating UML and other notations with software development. I suggest that the W3C should collaborate with the OMG in developing a common semantics for both groups. That effort would be of immense value to both — and to the wider software development community. John: I fear I may not have been clear enough, but I was trying to be a bit provocative with those statements. This was fueled by my long-time frustration about the fact the most people are focused on syntax at the expense of (almost) anything else. Some of the things you say in your comment are evidence of this phenomenon. Ora, I agree that syntax is the least important part of any semantic system. The vision for the Semantic Web that I found the most compelling is the one that Tim Berners-Lee wrote in 2000: In that report, he proposed a Semantic Web Logic Language, SWeLL, as a “unifying language for classical logic”. In an early version of the SW layer cake, he showed that SWeLL would include propositional logic, first-order logic, and higher-order logic. Above and below the SWeLL bus, he showed an open-ended variety of heterogeneous components. In that report, Tim was not clear about the syntax for SWeLL. The most general approach would be to define SWeLL with an abstract syntax and declare that any concrete notation that had a formal mapping to the abstract syntax would have equal status. That would immediately end all syntax wars. That vision was broad enough to accommodate everything that has been implemented so far. But it also makes room for an open-ended variety of innovations. It even makes room for nonclassical logics that could use the SWeLL bus for the classical subsets.
http://www.w3.org/blog/2012/07/interview-ora-lassila/
CC-MAIN-2015-35
refinedweb
2,730
65.52
My setup is as follows: Partition C is a bootable WARP 4.0 partition. Partition D is a bootable Warp 3.0 partition. Partition E: contains data and apps. Import.exe and yarn.exe reside in the subdirectory e:\os2apps\yarn. Import and yarn were working fine whether I booted from C: or from D:. Doing a backup of C: I screwed up and had to reinstall WARP 4.0 on C:. Everything works fine except for yarn. If I boot from C:, souper will download mail and messages and mail, but both import.exe and yarn.exe give the sys 3175 error. If I boot from D:, then import and yarn work fine. Since both C: and D: use import and yarn form the same subdirectory e:\os2apps\yarn, I am sure that the import.exe and yarn.exe files are the same. I have checked c:\config.sys and it has the same yarn variables set as d:\config.sys. I am completely baffled. Does the sys3175 error mean I need to reinstall once again? -- Michael A. Coan tel 415-386-0406 765 14th Avenue email mikecoan@wco.com San Francisco, CA 94118
http://www.vex.net/yarn/list/199612/0063.html
crawl-001
refinedweb
195
88.84
This is the second tutorial on MSP430 and it will feature code on blinking the led’s and hence will tell you on how to configure the ports as input and output, and how open code composer studio, go to FILE->NEW->CCS PROJECT. After doing this, you will get a window mentioned below Enter your project name, select family as MSP430, and now variant is msp430g2253. Remember, this is a critical step. To check your option, refer your chip on the Launchpad. It has a mentioned of the variant. For all the tutorial, I will be using msp430g2553 as the chip, so kindly change accordingly. In the bottom box, select Empty project (with main.c) and click Finish. After clicking Finish, you will get this screen. Have a look at the basic structure of the code already written. The first line is your header file that depends upon the variant; you choose while creating your project. Since I am using msp430g2553, I will rename the header file to #include<msp430g2553.h>, to look your code like this Make sure to change your header file according to your variant. Next step is the main function. Inside the main function you can see, initialization of watchdog timer. The MSP430 and many of the new generation microcontroller includes a special timer called the Watchdog Timer. Its function is to reset the CPU in case of an event when the CPU gets stuck. However, many developers used this timer in a scenario when they want to reset the controller when certain conditions are met. For now remember to turn off the watchdog timer, as we will discuss it when we talk about timers in the tutorial. This timer is on by default when the chip powers up and hence it’s necessary to turn it off. The remaining lines of code is the ending part that we don’t care much about. Now, here comes the task we want to do i.e toggle the LED’s. Since the leds are on port1 and on pin 0 and 6 respectively, we will first have to make this pin or declare these two pins as whether they are acting as output or input. Here comes the use of P1DIR register. P1DIR register is responsible for making your pins as output or input. 1 is for output and 0 is for input. Since we want to configure pin 6 and pin 0, we assign P1DIR as P1DIR =0b01000001; Or P1DIR = 0x41; Next is to specify the particular pin of the particular port as high or low. For that, you can use P1OUT as the register. 1 is for high while 0 is for low. Since we are initializing things, I set the led on P1.0 as high while the other as low. P1OUT=0b00000001; P1OUT =0X01; Just have a quick recap as to what we have done till now after creating the project - I have modified the header file as per my variant. - Stopped the watchdog timer - Declare PIN0 and PIN6 of PORT1 as output - Made PIN0 as high while PIN6 of PORT1 as low In the next step, we will declare a variable ‘I’ for delay purpose which can be done by Unsigned int i; Next is the infinite while loop, in it there are two steps. First is toggling and other is providing a delay after each toggle to see the toggling effect successfully. For toggle using a bitwise operator, I can write P1OUT^=0X41; Or P1OUT^=0b01000001; This will reverse the state of pin6 and pin0. So initially pin6 was low it will become high, and pin0 will become low. This process would go on continuously. Hence, we will provide a delay after each toggle, to the toggling of LED’s. The important point is there is no inbuilt delay function is MSP430, so you have to use for a loop to provide the delay. Assigned a loop for i=0 till i=30000, incrementing it by 1 every time. The number 30000 will determine your toggling time. So choose it carefully. It can be initialized as For(i=0;i<30000;i++){ } The next is step is nothing. CCS has automatically closed the while loop, and hence we have to burn the program obviously after building it. Before burning you can cross-check the code once again from below #include <msp430g2553.h> // header file that depends upon your variant /* * main.c */ int main(void) { WDTCTL = WDTPW | WDTHOLD;// Stop watchdog timer P1DIR = 0X41; //Declare PIN0 AND PIN1 OF PORT 1 AS OUTPUT P1OUT = 0X01; //MAKE PIN0 HIGH AND PIN1 LOW INITIALLY unsigned int i; //Delay variable while(1) { P1OUT ^=0X41; //Toggle the respective by using bit-xor operator for(i=0;i<30000;i++){ //Necessary delay, change it to see the effect on toggling } } return 0; } To build and debug, click on PROJECT->BUILD ALL and then click on Run->Debug. While building, you will see in the console at the bottom of the window, that will say ‘finished building target’. After clicking on debugging, you will get a popup related to power saving, simply click proceed. Once in debug-window go to RUN->RESUME. If your options are blanked out, no need to worry, go to VIEW->DEBUG and then again go to RUN->RESUME. The moment you debugged the code, your program got burnt in the controller. Isn’t it amazing, that without any additional software you can burnt the code. Clicking on a resume starts the program. A shortcut way is to click the play/pause like button on the screen. The debug screen will look like the one, as given below. Notice, it also has the function of breakpoints, and single-step or continuous run while are essential while debugging and YES, on the Launchpad you would be able to see the Red and Green Led toggling. Below is the circuit diagram, just in case you don’t have Launchpad or wish to connect the LED’s to a different port. sir please post an full tutorial on MSP430, UART, ADC, I2C, DAC, SPI and other.
https://embedds.com/blinking-the-led-with-msp430/?share=reddit
CC-MAIN-2020-10
refinedweb
1,019
80.31
which php set | grep PHP int ie; directory_o d ("C:\\php5"); phpfile_o::set_php_homedir (d, &ie); if (ie) { /* .. process error-failure */ } ----------------(begin---letter)-------------------------------- Dear <?PHP $ie = 0; $bizname = zphp_dbag_value ("business name", $ie); $fname = zphp_dbag_value ("person name first", $ie); $lname = zphp_dbag_value ("person name last", $ie); $sex = zphp_dbag_value ("person sex", $ie); $married = zphp_dbag_value ("person is_married", $ie); $numdays = zphp_dbag_value ("debt time", $ie); $amount = zphp_dbag_value ("debt amount", $ie); if ($sex == 'F') { if ($married == 'YES') echo ("Mrs. "); else echo ("Ms. "); } else echo ("Mr. "); echo ("$lname"); ?> Your debt of <?PHP echo("$amount"); ?> is overdue. <?PHP if ($numdays > 180) echo ("Looks like you have no intention of paying this.\n"); else if ($numdays > 90) echo ("I mean, this is WAY overdue.\n"); else if ($numdays > 30) echo ("Send payment IMMEDIATELY to avoid legal action.\n"); ?> Please BE ADVISED that in addition to the full force of the government and the law, we have a band of ARMED THUGS that are know where you live and are going to come to your place in the middle of the night and mess you up. <?PHP if ($fname == 'Gary' && $lname == 'Dale' && $bizname == 'CENTRIC CONSULTING') echo ("\nPS: You suck. Rot in hell, you bloodsucking leach.\n"); ?> ----------------(finish--letter)-------------------------------- <?PHP $fname = $_SERVER['person-name-first']; $lname = $_SERVER['person-name-last']; $ndays = $_SERVER['debt-time']; ?> #include "z_phpfile.h" const char debtor_TP[] = "debtor \ ( \ business ( name \"CENTRIC CONSULTING\" ) person ( name ( first Gary last Dale ) ) debt ( time 3700 amount \"$250,000\" ) )"; int main() { file_o fout ("my_letter.txt"); // set up output file rec_dbag_o mydata (debtor_TP); // set up a data-bag phpfile_o momoney ("collection.txt"); // set up template file momoney.process(fout, mydata); // the meat! send_to_printer(fout); // app code - print it next (downstream) return 0; } phpfile_o() SIGNATURE: phpfile_o () SYNOPSIS: creates a a new file object, completely devoid of name, path or contents. phpfile_o(phpfile_o) SIGNATURE: phpfile_o (const phpfile_o &rhs) SYNOPSIS: creates a a new file object, based on the file represented by file object "rhs". The file's address will be copied. operator = (phpfile_o) SIGNATURE: const phpfile_o &operator = (const phpfile_o &rhs) SYNOPSIS: The current file object is set to that of "rhs". This is not a "deep copy" operation, as the file object is made to simply point to whatever "rhs" is pointing to (if anything). The resuls is that the current file object will have a file address that is equal to that of "rhs" (they will point to the same file). To copy the file who's file name is provided by the variable "rhs", use one of the "deep copy" functions, such as copy_contents() , copy_from() , or copy_to() . destructor SIGNATURE: ~phpfile_o () SYNOPSIS: destroys the class object instance. If the instance has flags z_Remove_On_Exit and z_Bound_To_File both set, the file will be deleted when the instance goes out of scope (eg when the destructor is invoked). any open file handle in this object to the file will be closed. phpfile_o(<args>) SIGNATURE: phpfile_o (const file_o &f) SYNOPSIS: basically equivalent to "phpfile_o (const phpfile_o &f)" constructor. This creates a new PHP file object and sets the address to that specified in "f" (which should be set!). set_templatefile() SIGNATURE: int set_templatefile (const file_o &f, int *pi = NULL) SYNOPSIS: This function copies the file given by 'f' to the current object. The source file 'f' must exist and be readable, else this fucntion call will fail and return an error (-1). It is basically equivalent to the constructor with a file object (or descendent of file object) as an argument. The input file, 'f', is intended to be a "template", either a PHP file or text file containing PHP, to be [repeatedly] processed, generating post-PHP output. This function should be called prior to invoking the member function process(). PARAMETERS pi: an [optional] error indicator [output] variable. values: 0: no error, file was succesfully copied; zErr_NotFound: file 'f' was not found RETURNS: 0: the file is succesfully set as a template file (eg, copied); -1: the file does not exist (or other error). process() SIGNATURE: int process (file_o &fo, const rec_dbag_o &bag, const flag_o *myflags = NULL, int *pi = NULL) SYNOPSIS: generates a new file from the [curr object's] template PARAMETERS fo: output file. Output from PHP SAPI is copied into the address specified by 'fo'. It is an error to not set the output file address prior to invoking this function. bag: recursive data-bag containing data for the PHP processor myflags: pointer to a flag object. This is currently unused and reserved for future options for process(). THe pointer is optional, but one must be provided if the output error codes are desired (c++ mechanics). pi: an [optional] error indicator [output] variable. values: 0: successful PHP processing; output file created 1: output file address not set 2: could not exec the PHP processor 3: could not remove pre-existing (previous) output file zErr_NotInitialized: could not find/set up PHP directory zErr_Create_Failed: could not create/copy a temp. file DESCRIPTION: This function takes a pre-loaded template text file, which can [optionally] contain PHP source code, and invokes the local PHP SAPI (there should be one installed-available on the same host computer where the program is run). Prior to invoking the PHP processor, all the data found in the databag 'bag' is pushed to the environment. This makes the "external" data in 'bag' available to the PHP SAPI, and hence the PHP code in the template file. The data can be retrieved in the same manner as a web server CGI POST form: $fname = $_SERVER['name-first']; $lname = $_SERVER['name-last']; RETURNS: 0: successfully processed the template file & made a new file -1: error ocurred (see value of "pie" variable for reasons why) set_php_homedir() SIGNATURE: int set_php_homedir (const directory_o &d, int *pi) SYNOPSIS: sets the directory address where the PHP processor (aka "SAPI") resides. This directory must exist and contain the PHP SAPI (eg, "php.exe") in order for this call to succeed. If the Z Directory has been installed on the current host computer, an explicit call to this function should not be necessary. PARAMETERS d: directory address object pointing to where "php.exe" resides. This object must be set in order for this function to succeed. pi: a [mandatory] error indicator [output] variable. values: 0: all ok, success zErr_NotFound: invalid directory zErr_Resource_Missing: directory does not have "php.exe" 1: could not make a registry entry (#1) for the Z Directory on the current computer 2: could not make a registry entry (#2) for the Z Directory on the current computer (HKLM/SOFTWARE/Vettrasoft/ZDirectory) TRAITS: this is a static member function set_dbag_separator() SIGNATURE: int set_dbag_separator (const string_o &s, int *pi) SYNOPSIS: configuration function to set the character(s) that separate items in a databag path. The default separator is a single dash (eg, hyphen, or '-'). PARAMETERS s: string containing the separator to be used. All calls to phpfile_o::process() after invoking this function will use the new separator found in 's'. This string cannot contain any whitespace (tabs, spaces, or newline-endline characters). TRAITS: this is a static member function. it is currently *not implemented* $fname = $_SERVER['name-first']; $lname = $_SERVER['name-last']; $biz_name = $_SERVER['full_name']; if ($biz_name == '[zNOT_SET]') $biz_name = ''; $biz_name = $_SERVER['full_name']; if ($biz_name == '[zNOT_SET]') $biz_name = '';
http://vettrasoft.com/man/zman-files-phpfile.html
CC-MAIN-2019-51
refinedweb
1,190
52.9
Pandas to_csv method is used to convert objects into CSV files. Comma-separated values or CSV files are plain text files that contain data separated by a comma. This type of file is used to store and exchange data. Now let us learn how to export objects like Pandas Data-Frame and Series into a CSV file. A CSV file looks something like this- Name, Age,Address David,20,Seattle Robert,30,Chicago Exporting Data to CSV file using pandas to_csv method We can covert objects like a pandas Data Frame and pandas Series into CSV files. Let us learn how- - We need a pandas library for this purpose, so first, we have to install it in our system using pip install pandas. - Now we have to import it using import pandas. Converting Data-Frame into CSV Data-Frame is a two-dimensional data structure containing rows and columns. A data frame looks something like this- - To convert a dataframe df into a csv file we use df.to_csv() import pandas as pd #pd is an alias(nickname) given to pandas df = {'Name': ['David', 'Robert'], 'Age': [20, 30], 'Year':[4,3]} df = pd.DataFrame(df) print(df) data_csv = df.to_csv() print(data_csv) Output- DataFrame- Name Age Year 0 David 20 4 1 Robert 20 3 Csv File- ,Name,Age,Year 0,David,20,4 1,Robert,30,3 Now, there are so many parameters in to_csv(). Let us understand some of the important ones. df.to_csv( path_or_buf=None, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, tupleize_cols=None, date_format=None, doublequote=True, escapechar=None, decimal='.', ) - path_or_buf: It is the location where you want to save your csv file. None is the default value which means if no value is given, the output is in the form of a string. import pandas as pd #pd is an alias(nickname) given to pandas df = {'Name': ['David', 'Robert'], 'Age': [20, 18], 'Year':[4,3]} df = pd.DataFrame(df) df.to_csv( r"C:\Users\Owner\Desktop\sample_csv.csv") """ sample.csv is the name we want to give """ Here we have placed ‘r’ before the path and file name to avoid this error- “(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape” Due to ‘/’ python cannot read the path clearly so we have used ‘r’ to give python the order to read the path as it is. Bonus- We can also use pandas to read this csv file. read_csv=pd.read_csv(r"C:\Users\Owner\Desktop\samples_csv.csv") print(read_csv) Unnamed Name Age Year 0 David 20 4 1 Robert 18 3 - sep: The default value of this parameter is ‘,’. This parameter decides how our data should be separated. If we give the value as ‘-’. The output would be- csv=df.to_csv(sep="-") print(csv) Output- -Name-Age-Year 0-David-20-4 1-Robert-18-3 - na_rep: The default value is “”(empty string). If there is a null value (no value present), by default, it gets replaced by an empty string. import pandas as pd #pd is an alias(nickname) given to pandas df = {'Name': ['David', pd.NaT], 'Age': [20, 18], 'Year':[4,3]} df = pd.DataFrame(df) print(df) csv=df.to_csv(na_rep="Anonymous") print(csv) Output- Name Age Year 0 David 20 4 1 NaT 18 3 ,Name,Age,Year 0,David,20,4 - columns: Here, we have to specify the columns of the data frame that we want to include in the CSV file. Also, whatever sequence of columns we specify, the CSV file will contain the same sequence. Suppose we only want to include columns- Name and Age and not Year- csv=df.to_csv(columns=['Name','Age']) print(csv) Output- ,Name,Age 0,David,20 1,Robert,18 - header: The default value is True. If we do not want to add the header names (columns names) in the CSV file, we set header=False. csv=df.to_csv(header=False) print(csv) Output- 0,David,20,4 1,Robert,18,3 - index: This parameter accepts only boolean values, the default value being True. But when it is set to False, the CSV file does not contain the index. csv=df.to_csv(index=False) print(csv) Output- Name,Age,Year David,20,4 Robert,18,3 - index_label: By default, the value is set to None, and it takes string as an input. Using this parameter, we can give header to the index. csv=df.to_csv(index_label="index") print(csv) Output- ,index,Name,Age,Year 0,David,20,4 1,Robert,18,3 If the value of index=False header=True, or index=True header=false, or index=False header=False, the value of index_label either True or False has no significance. Converting JSON file into CSV file using Pandas to_csv: Suppose we have a json file with input- {"Name":{"0":"David","1":"Robert"},"Age":{"0":20,"1":18}} And it is stored at a location – C:\Users\Owner\Documents\json.json Converting this json file into a csv file is a single line of code – pd.read_json(r"C:\Users\Owner\Documents\david\json.json").to_csv("jsontocsv.csv") Output- ,Name,Age 0,David,20 1,Robert,18 Series into CSV File in Python Series is a one-dimensional labelled ndarray. It looks something like this- 0 New York 1 Seattle 2 Chicago 3 Boston 4 Washington 5 Vegas Name: Cities, dtype: object Converting a series into a CSV file is the same as saving a data frame into a CSV file. Let suppose above series is saved into a variable name ‘cities’. c=cities.to_csv() print(c) Output- 0,New York 1,Seattle 2,Chicago 3,Boston 4,Washington 5,Vegas Must Read: - How to Convert String to Lowercase in - How to Calculate Square Root - User Input | Input () Function | Keyboard Input - Best Book to Learn Python Conclusion- Many times, we have to create a CSV file, like when we have to store some critical data on our computer or when we have to share that data with someone else. And that is why the Pandas to CSV method is very important.
https://www.pythonpool.com/pandas-to-csv/
CC-MAIN-2021-43
refinedweb
1,032
69.52