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
(For more resources related to this topic, see here.) To start from, cross-validation is a common validation technique that can be used to evaluate machine learning models. Cross-validation essentially measures how well the estimated model will generalize some given data. This data is different from the training data supplied to our model, and is called the cross-validation set, or simply validation set, of our model. Cross-validation of a given model is also called rotation estimation. If an estimated model performs well during cross-validation, we can assume that the model can understand the relationship between its various independent and dependent variables. The goal of cross-validation is to provide a test to determine if a formulated model is overfit on the training data. In the perspective of implementation, cross-validation is a kind of unit test for a machine learning system. A single round of cross-validation generally involves partitioning all the available sample data into two subsets and then performing training on one subset and validation and/or testing on the other subset. Several such rounds, or folds, of cross-validation must be performed using different sets of data to reduce the variance of the overall cross-validation error of the given model. Any particular measure of the cross-validation error should be calculated as the average of this error over the different folds in cross-validation. There are several types of cross-validation we can implement as a diagnostic for a given machine learning model or system. Let's briefly explore a few of them as follows: - A common type is k-fold cross-validation, in which we partition the cross-validation data into k equal subsets. The training of the model is then performed on subsets of the data and the cross-validation is performed on a single subset. - A simple variation of k-fold cross-validation is 2-fold cross-validation, which is also called the holdout method. In 2-fold cross-validation, the training and cross-validation subsets of data will be almost equal in proportion. - Repeated random subsampling is another simple variant of cross-validation in which the sample data is first randomized or shuffled and then used as training and cross-validation data. This method is notably not dependent on the number of folds used for cross-validation. - Another form of k-fold cross-validation is leave-one-out cross-validation, in which only a single record from the available sample data is used for cross-validation. Leave-one-out cross-validation is essentially k-fold cross-validation in which k is equal to the number of samples or observations in the sample data. Cross-validation basically treats the estimated model as a black box, that is, it makes no assumptions about the implementation of the model. We can also use cross-validation to select features in a given model by using cross-validation to determine the feature set that produces the best fit model over the given sample data. Of course, there are a couple of limitations of classification, which can be summarized as follows: - If a given model is needed to perform feature selection internally, we must perform cross-validation for each selected feature set in the given model. This can be computationally expensive depending on the amount of available sample data. - Cross-validation is not very useful if the sample data comprises exactly or nearly equal samples. In summary, it's a good practice to implement cross-validation for any machine learning system that we build. Also, we can choose an appropriate cross-validation technique depending on the problem we are trying to model as well as the nature of the collected sample data. For the example that will follow, the namespace declaration should look similar to the following declaration: (ns my-namespace (:use [clj-ml classifiers data])) We can use the clj-ml library to cross-validate the classifier we built for the fish packaging plant. Essentially, we built a classifier to determine whether a fish is a salmon or a sea bass using the clj-ml library. To recap, a fish is represented as a vector containing the category of the fish and values for the various features of the fish. The attributes of a fish are its length, width, and lightness of skin. We also described a template for a sample fish, which is defined as follows: (def fish-template [{:category [:salmon :sea-bass]} :length :width :lightness]) The fish-template vector defined in the preceding code can be used to train a classifier with some sample data. For now, we will not bother about which classification algorithm we have used to model the given training data. We can only assume that the classifier was created using the make-classifier function from the clj-ml library. This classifier is stored in the *classifier* variable as follows: (def *classifier* (make-classifier ...)) Suppose the classifier was trained with some sample data. We must now evaluate this trained classification model. To do this, we must first create some sample data to cross-validate. For the sake of simplicity, we will use randomly generated data in this example. We can generate this data using the make-sample-fish function. This function simply creates a new vector of some random values representing a fish. Of course, we must not forget the fact that the make-sample-fish function has an in-built partiality, so we create a meaningful pattern in a number of samples created using this function as follows: (def fish-cv-data (for [i (range 3000)] (make-sample-fish))) We will need to use a dataset from the clj-ml library, and we can create one using the make-dataset function, as shown in the following code: (def fish-cv-dataset (make-dataset "fish-cv" fish-template fish-cv-data)) To cross-validate the classifier, we must use the classifier-evaluate function from the clj-ml.classifiers namespace. This function essentially performs k-fold cross-validation on the given data. Other than the classifier and the cross-validation dataset, this function requires the number of folds that we must perform on the data to be specified as the last parameter. Also, we will first need to set the class field of the records in fish-cv-dataset using the dataset-set-class function. We can define a single function to perform these operations as follows: (defn cv-classifier [folds] (dataset-set-class fish-cv-dataset 0) (classifier-evaluate *classifier* :cross-validation fish-cv-dataset folds)) We will use 10 folds of cross-validation on the classifier. Since the classifier-evaluate function returns a map, we bind this return value to a variable for further use, as follows: user> (def cv (cv-classifier 10)) #'user/cv We can fetch and print the summary of the preceding cross-validation using the :summary keyword as follows: user> (print (:summary cv)) Correctly Classified Instances 2986 99.5333 % Incorrectly Classified Instances 14 0.4667 % Kappa statistic 0.9888 Mean absolute error 0.0093 Root mean squared error 0.0681 Relative absolute error 2.2248 % Root relative squared error 14.9238 % Total Number of Instances 3000 nil As shown in the preceding code, we can view several statistical measures of performance for our trained classifier. Apart from the correctly and incorrectly classified records, this summary also describes the Root Mean Squared Error (RMSE) and several other measures of error in our classifier. For a more detailed view of the correctly and incorrectly classified instances in the classifier, we can print the confusion matrix of the cross-validation using the :confusion-matrix keyword, as shown in the following code: user> (print (:confusion-matrix cv)) === Confusion Matrix === a b <-- classified as 2129 0 | a = salmon 9 862 | b = sea-bass nil As shown in the preceding example, we can use the clj-ml library's classifier-evaluate function to perform a k-fold cross-validation on any given classifier. Although we are restricted to using classifiers from the clj-ml library when using the classifier-evaluate function, we must strive to implement similar diagnostics in any machine learning system we build. Building a spam classifier Now that we are familiar with cross-validation, we will build a working machine learning system that incorporates cross-validation. The problem at hand will be that of spam classification, in which we will have to determine the likelihood of a given e-mail being a spam e-mail. Essentially, the problem boils down to binary classification with a few tweaks to make the machine learning system more sensitive to spam. Note that we will not be implementing a classification engine that is integrated with an e-mail server, but rather we will be concentrating on the aspects of training the engine with some data and classifying a given e-mail. The way this would be used in practice can be briefly explained as follows. A user will receive and read a new e-mail, and will decide whether to mark the e-mail as spam or not. Depending on the user's decision, we must train the e-mail service's spam engine using the new e-mail as data. In order to train our spam classifier in a more automated manner, we'll have to simply gather data to feed into the classifier. We will need a large amount of data to effectively train a classifier with the English language. Luckily for us, sample data for spam classification can be found easily on the Web. For this implementation, we will use data from the Apache SpamAssassin project. The Apache SpamAssassin project is an open source implementation of a spam classification engine in Perl. For our implementation, we will use the sample data from this project. You can download this data from. For our example, we have used the spam_2 and easy_ham_2 datasets. A Clojure Leiningen project housing our spam classifier implementation will require that these datasets be extracted and placed in the ham/ and spam/ subdirectories of the corpus/ folder. The corpus/ folder should be placed in the root directory of the Leiningen project that is the same folder of the project.clj file. The features of our spam classifier will be the number of occurrences of all previously encountered words in spam and ham e-mails. By the term ham, we mean "not spam". Thus, there are effectively two independent variables in our model. Also, each word has an associated probability of occurrence in e-mails, which can be calculated from the number of times it's found in spam and ham e-mails and the total number of e-mails processed by the classifier. A new e-mail would be classified by finding all known words in the e-mail's header and body, and then somehow combining the probabilities of occurrences of these words in spam and ham e-mails. For a given word feature in our classifier, we must calculate the total probability of occurrence of the word by taking into account the total number of e-mails analyzed by the classifier. Also, an unseen term is neutral in the sense that it is neither spam nor ham. Thus, the initial probability of occurrence of any word in the untrained classifier is 0.5. Hence, we use a Bayesian probability function to model the occurrence of a particular word. In order to classify a new e-mail, we also need to combine the probabilities of occurrences of all the known words found in it. For this implementation, we will use Fisher's method, or Fisher's combined probability test, to combine the calculated probabilities. Although the mathematical proof of this test is beyond the scope of this article, it's important to know that this method essentially estimates the probabilities of several independent probabilities in a given model as a (pronounced as chi-squared) distribution. Such a distribution has an associated number of degrees of freedom. It can be shown that an distribution with degrees of freedom equal to twice the number of combined probabilities k can be formally expressed as follows: This means that using an distribution with degrees of freedom, the Cumulative Distribution Function (CDF), of the probabilities of the e-mail being a spam or a ham can be combined to reflect a total probability that is high when there are a large number of probabilities with values close to 1.0. Thus, an e-mail is classified as spam only when most of the words in the e-mail have been previously found in spam e-mails. Similarly, a large number of ham keywords would indicate the e-mail is in fact a ham e-mail. On the other hand, a low number of occurrences of spam keywords in an e-mail would have a probability closer to 0.5, in which case the classifier will be unsure of whether the e-mail is spam or ham. For the example that will follow, we will require the file and cdf-chisq functions from the clojure.java.io and Incanter libraries, respectively. The namespace declaration of the example should look similar to the following declaration: (ns my-namespace (:use [clojure.java.io :only [file]] [incanter.stats :only [cdf-chisq]]) A classifier trained using Fisher's method, as described earlier, will be very sensitive to new spam e-mails. We represent the dependent variable of our model by the probability of a given e-mail being spam. This probability is also termed as the spam score of the e-mail. A low score indicates that an e-mail is ham, while a high score indicates that the e-mail is spam. Of course, we must also include a third class to represent an unknown value in our model. We can define some reasonable limits for the scores of these categories as follows: (def min-spam-score 0.7) (def max-ham-score 0.4) (defn classify-score [score] [(cond (<= score max-ham-score) :ham (>= score min-spam-score) :spam :else :unsure) score]) As defined earlier, if an e-mail has a score of 0.7 or more, it's a spam e-mail. And a score of 0.5 or less indicates that the e-mail is ham. Also, if the score lies between these two values, we can't effectively decide whether the e-mail is spam or not. We represent these three categories using the keywords :ham, :spam, and :unsure. The spam classifier must read several e-mails, determine all the words, or tokens, in the e-mails' text and header, and store this information as empirical knowledge to use later. We need to store the number of occurrences a particular word is found in spam and ham e-mails. Thus, every word that the classifier has encountered represents a feature. To represent this information for a single word, we will use a record with three fields as shown in the following code: (defrecord TokenFeature [token spam ham]) (defn new-token [token] (TokenFeature. token 0 0)) (defn inc-count [token-feature type] (update-in token-feature [type] inc)) The record TokenFeature defined in the preceding code can be used to store the needed information for our spam classifier. The new-token function simply creates a new record for a given token by invoking the record's constructor. Obviously, a word is initially seen zero times in both spam and ham e-mails. We will also need to update these values, and we define the inc-count function to perform an update on the record using the update-in function. Note that the update-in function expects a function to apply to a particular field in the record as the last parameter. We are already dealing with a small amount of a mutable state in our implementation, so let's delegate access to this state through an agent. We would also like to keep track of the total number of ham and spam e-mails; so, we'll wrap these values with agents as well, as shown in the following code: (def feature-db (agent {} :error-handler #(println "Error: " %2))) (def total-ham (agent 0)) (def total-spam (agent 0)) The feature-db agent defined in the preceding code will be used to store all word features. We define a simple error handler for this agent using the :error-handler keyword parameter. The agent's total-ham and total-spam functions will keep track of the total number of ham and spam e-mails, respectively. We will now define a couple of functions to access these agents as follows: (defn clear-db [] (send feature-db (constantly {})) (send total-ham (constantly 0)) (send total-spam (constantly 0))) (defn update-feature! "Looks up a TokenFeature record in the database and creates it if it doesn't exist, or updates it." [token f & args] (send feature-db update-in [token] #(apply f (if %1 %1 (new-token token)) args))) In case you are not familiar with agents in Clojure, we can use the send function to alter the value contained in an agent. This function expects a single argument, that is, the function to apply to its encapsulated value. The agent applies this function on its contained value and updates it if there are no errors. The clear-db function simply initializes all the agents we've defined with an initial value. This is done by using the constantly function that wraps a value in a function that returns the same value. The update-feature! function modifies the value of a given token in the feature-db map and creates a new token if the supplied token is not present in the map of feature-db. Since we will only be incrementing the number of occurrences of a given token, we will pass the inc-count function as a parameter to the update-feature! function. Now, let's define how the classifier will extract words from a given e-mail. We'll use regular expressions to do this. If we want to extract all the words from a given string, we can use the regular expression [a-zA-Z]{3,}. We can define this regular expression using a literal syntax in Clojure, as shown in the following code. Note that we could also use the re-pattern function to create a regular expression. We will also define all the MIME header fields from which we should also extract tokens. We will do all this with the help of the following code: (def token-regex #"[a-zA-Z]{3,}") (def header-fields ["To:" "From:" "Subject:" "Return-Path:"]) To match tokens with the regular expression defined by token-regex, we will use the re-seq function, which returns all matching tokens in a given string as a sequence of strings. For the MIME headers of an e-mail, we need to use a different regular expression to extract tokens. For example, we can extract tokens from the "From" MIME header as follows: user> (re-seq #"From:(.*)\n" "From: someone@host.org\n") (["From: someone@host.org\n" " someone@host.org"]) Note the use of the newline character at the end of the regular expression, which is used to indicate the end of a MIME header in an e-mail. We can then proceed to extract words from the values returned by matching the regular expression defined in the preceding code. Let's define the following few functions to extract tokens from a given e-mail's headers and body using this logic: (defn header-token-regex [f] (re-pattern (str f "(.*)\n"))) (defn extract-tokens-from-headers [text] (for [field header-fields] (map #(str field %1) ; prepends field to each word from line (mapcat (fn [x] (->> x second (re-seq token-regex))) (re-seq (header-token-regex field) text))))) (defn extract-tokens [text] (apply concat (re-seq token-regex text) (extract-tokens-from-headers text))) The header-token-regex function defined in the preceding code returns a regular expression for a given header, such as From:(.*)\n for the "From" header. The extract-tokens-from-headers function uses this regular expression to determine all words in the various header fields of an e-mail and appends the header name to all the tokens found in the header text. The extract-tokens function applies the regular expression over the text and headers of an e-mail and then flattens the resulting lists into a single list using the apply and concat functions. Note that the extract-tokens-from-headers function returns empty lists for the headers defined in header-fields, which are not present in the supplied e-mail header. Let's try this function out in the REPL with the help of the following code: User≫ (Def Sample-Text "From: 12A1Mailbot1@Web.De Return-Path: ≪12A1Mailbot1@Web.De≫ Mime-Version: 1.0") User≫ (Extract-Tokens-From-Headers Sample-Text) (() ("From:Mailbot" "From:Web") () ("Return-Path:Mailbot" "Return-Path:Web")) Using the extract-tokens-from-headers function and the regular expression defined by token-regex, we can extract all words comprising of three or more characters from an e-mail's header and text. Now, let's define a function to apply the extract-tokens function on a given e-mail and update the feature map using the update-feature! function with all the words found in the e-mail. We will do all this with the help of the following code: (defn update-features! "Updates or creates a TokenFeature in database for each token in text." [text f & args] (doseq [token (extract-tokens text)] (apply update-feature! token f args))) Using the update-features! function in the preceding code, we can train our spam classifier with a given e-mail. In order to keep track of the total number of spam and ham e-mails, we will have to send the inc function to the total-spam or total-ham agents depending on whether a given e-mail is spam or ham. We will do this with the help of the following code: (defn inc-total-count! [type] (send (case type :spam total-spam :ham total-ham) inc)) (defn train! [text type] (update-features! text inc-count type) (inc-total-count! type)) The inc-total-count! function defined in the preceding code updates the total number of spam and ham e-mails in our feature database. The train! function simply calls the update-features! and inc-total-count! functions to train our spam classifier with a given e-mail and its type. Note that we pass the inc-count function to the update-features! function. Now, in order to classify a new e-mail as spam or ham, we must first define how to extract the known features from a given e-mail using our trained feature database. We will do this with the help of the following code: (defn extract-features "Extracts all known tokens from text" [text] (keep identity (map #(@feature-db %1) (extract-tokens text)))) The extract-features function defined in the preceding code looks up all known features in a given e-mail by dereferencing the map stored in feature-db and applying it as a function to all the values returned by the extract-tokens function. As mapping the closure #(@feature-db %1) can return () or nil for all tokens that are not present in a feature-db agent, we will need to remove all empty values from the list of extracted features. To do this, we will use the keep function, which expects a function to apply to the non-nil values in a collection and the collection from which all nil values must be filtered out. Since we do not intend to transform the known features from the e-mail, we will pass the identity function, which returns its argument itself as the first parameter to the keep function. Now that we have extracted all known features from a given e-mail, we must calculate all the probabilities of these features occurring in a spam e-mail. We must then combine these probabilities using Fisher's method we described earlier to determine the spam score of a new e-mail. Let's define the following functions to implement the Bayesian probability and Fisher's method: (defn spam-probability [feature] (let [s (/ (:spam feature) (max 1 @total-spam)) h (/ (:ham feature) (max 1 @total-ham))] (/ s (+ s h)))) (defn bayesian-spam-probability "Calculates probability a feature is spam on a prior probability assumed-probability for each feature, and weight is the weight to be given to the prior assumed (i.e. the number of data points)." [feature & {:keys [assumed-probability weight] :or {assumed-probability 1/2 weight 1}}] (let [basic-prob (spam-probability feature) total-count (+ (:spam feature) (:ham feature))] (/ (+ (* weight assumed-probability) (* total-count basic-prob)) (+ weight total-count)))) The spam-probability function defined in the preceding code calculates the probability of occurrence of a given word feature in a spam e-mail using the number of occurrences of the word in spam and ham e-mails and the total number of spam and ham e-mails processed by the classifier. To avoid division-by-zero errors, we ensure that the value of the number of spam and ham e-mails is at least 1 before performing division. The bayesian-spam-probability function uses this probability returned by the spam-probability function to calculate a weighted average with the initial probability of 0.5 or 1/2. We will now implement Fisher's method of combining the probabilities returned by the bayesian-spam-probability function for all the known features found in an e-mail. We will do this with the help of the following code: (defn fisher "Combines several probabilities with Fisher's method." [probs] (- 1 (cdf-chisq (* -2 (reduce + (map #(Math/log %1) probs))) :df (* 2 (count probs))))) The fisher function defined in the preceding code uses the cdf-chisq function from the Incanter library to calculate the CDF of the several probabilities transformed by the expression . We specify the number of degrees of freedom to this function using the :df optional parameter. We now need to apply the fisher function to the combined Bayesian probabilities of an e-mail being spam or ham, and combine these values into a final spam score. These two probabilities must be combined such that only a high number of occurrences of high probabilities indicate a strong probability of spam or ham. It has been shown that the simplest way to do this is to average the probability of a spam e-mail and the negative probability of a ham e-mail (or 1 minus the probability of a ham e-mail). We will do this with the help of the following code: (defn score [features] (let [spam-probs (map bayesian-spam-probability features) ham-probs (map #(- 1 %1) spam-probs) h (- 1 (fisher spam-probs)) s (- 1 (fisher ham-probs))] (/ (+ (- 1 h) s) 2))) Hence, the score function will return the final spam score of a given e-mail. Let's define a function to extract the known word features from a given e-mail, combine the probabilities of occurrences of these features to produce the e-mail's spam score, and finally classify this spam score as a ham or spam e-mail, represented by the keywords :ham and :spam respectively, as shown in the following code: (defn classify "Returns a vector of the form [classification score]" [text] (-> text extract-features score classify-score)) So far, we have implemented how we train our spam classifier and use it to classify a new e-mail. Now, let's define some functions to load the sample data from the project's corpus/ folder and use this data to train and cross-validate our classifier, as follows: (defn populate-emails "Returns a sequence of vectors of the form [filename type]" [] (letfn [(get-email-files [type] (map (fn [f] [(.toString f) (keyword type)]) (rest (file-seq (file (str "corpus/" type))))))] (mapcat get-email-files ["ham" "spam"]))) The populate-emails function defined in the preceding code returns a sequence of vectors to represent all the ham e-mails from the ham/ folder and the spam e-mails from the spam/ folder in our sample data. Each vector in this returned sequence has two elements. The first element in this vector is a given e-mail's relative file path and the second element is either :spam or :ham depending on whether the e-mail is spam or ham. Note the use of the file-seq function to read the files in a directory as a sequence. We will now use the train! function to feed the content of all e-mails into our spam classifier. To do this, we can use the slurp function to read the content of a file as a string. For cross-validation, we will classify each e-mail in the supplied cross-validation data using the classify function and return a list of maps representing the test result of the cross-validation. We will do this with the help of the following code: (defn train-from-corpus! [corpus] (doseq [v corpus] (let [[filename type] v] (train! (slurp filename) type)))) (defn cv-from-corpus [corpus] (for [v corpus] (let [[filename type] v [classification score] (classify (slurp filename))] {:filename filename :type type :classification classification :score score}))) The train-from-corpus! function defined in the preceding code will train our spam classifier with all e-mails found in the corpus/ folder. The cv-from-corpus function classifies the supplied e-mails as spam or ham using the trained classifier and returns a sequence of maps indicating the results of the cross-validation process. Each map in the sequence returned by the cv-from-corpus function contains the file of the e-mail, the actual type (spam or ham) of the e-mail, the predicted type of the e-mail, and the spam score of the e-mail. Now, we need to call these two functions on two appropriately partitioned subsets of the sample data as follows: (defn test-classifier! [corpus cv-fraction] "Trains and cross-validates the classifier with the sample data in corpus, using cv-fraction for cross-validation. Returns a sequence of maps representing the results of the cross-validation." (clear-db) (let [shuffled (shuffle corpus) size (count corpus) training-num (* size (- 1 cv-fraction)) training-set (take training-num shuffled) cv-set (nthrest shuffled training-num)] (train-from-corpus! training-set) (await feature-db) (cv-from-corpus cv-set))) The test-classifier! function defined in the preceding code will randomly shuffle the sample data and select a specified fraction of this randomized data as the cross-validation set for our classifier. The test-classifier! function then calls the train-from-corpus! and cv-from-corpus functions to train and cross-validate the data. Note that the use of the await function is to wait until the feature-db agent has finished applying all functions that have been sent to it via the send function. Now we need to analyze the results of cross-validation. We must first determine the number of incorrectly classified and missed e-mails from the actual and expected class of a given e-mail as returned by the cv-from-corpus function. We will do this with the help of the following code: (defn result-type [{:keys [filename type classification score]}] (case type :ham (case classification :ham :correct :spam :false-positive :unsure :missed-ham) :spam (case classification :spam :correct :ham :false-negative :unsure :missed-spam))) The result-type function will determine the number of incorrectly classified and missed e-mails in the cross-validation process. We can now apply the result-type function to all the maps in the results returned by the cv-from-corpus function and print a summary of the cross-validation results with the help of the following code: (defn analyze-results [results] (reduce (fn [map result] (let [type (result-type result)] (update-in map [type] inc))) {:total (count results) :correct 0 :false-positive 0 :false-negative 0 :missed-ham 0 :missed-spam 0} results)) (defn print-result [result] (let [total (:total result)] (doseq [[key num] result] (printf "%15s : %-6d%6.2f %%%n" (name key) num (float (* 100 (/ num total))))))) The analyze-results function defined in the preceding code simply applies the result-type function to all the map values in the sequence returned by the cv-from-corpus function, while maintaining the total number of incorrectly classified and missed e-mails. The print-result function simply prints the analyzed result as a string. Finally, let's define a function to load all the e-mails using the populate-emails function and then use this data to train and cross-validate our spam classifier. Since the populate-emails function will return an empty list, or nil when there are no e-mails, we will check this condition to avoid failing at a later stage in our program: (defn train-and-cv-classifier [cv-frac] (if-let [emails (seq (populate-emails))] (-> emails (test-classifier! cv-frac) analyze-results print-result) (throw (Error. "No mails found!")))) In the train-and-cv-classifier function shown in the preceding code, we first call the populate-emails function and convert the result to a sequence using the seq function. If the sequence has any elements, we train and cross-validate the classifier. If there are no e-mails found, we simply throw an error. Note that the if-let function is used to check whether the sequence returned by the seq function has any elements. We have all the parts needed to create and train a spam classifier. Initially, as the classifier hasn't seen any e-mails, the probability of any e-mail or text being spam is 0.5. This can be verified by using the classify function, as shown in the following code, which initially classifies any text as the :unsure type: user> (classify "Make money fast") [:unsure 0.5] user> (classify "Job interview today! Programmer job position for GNU project") [:unsure 0.5] We now train the classifier and cross-validate it using the train-and-cv-classifier function. We will use one-fifth of all the available sample data as our cross-validation set. This is shown in the following code: user> (train-and-cv-classifier 1/5) total : 600 100.00 % correct : 585 97.50 % false-positive : 1 0.17 % false-negative : 1 0.17 % missed-ham : 9 1.50 % missed-spam : 4 0.67 % nil Cross-validating our spam classifier asserts that it's appropriately classifying e-mails. Of course, there is still a small amount of error, which can be corrected by using more training data. Now, let's try to classify some text using our trained spam classifier, as follows: user> (classify "Make money fast") [:spam 0.9720416490829515] user> (classify "Job interview today! Programmer job position for GNU project") [:ham 0.19095646757667556] Interestingly, the text "Make money fast" is classified as spam and the text "Job interview … GNU project" is classified as ham, as shown in the preceding code. Let's have a look at how the trained classifier extracts features from some text using the extract-features function. Since the classifier will initially have read no tokens, this function will obviously return an empty list or nil when the classifier is untrained, as follows: user> (extract-features "some text to extract") (#clj_ml5.spam.TokenFeature{:token "some", :spam 91, :ham 837} #clj_ml5.spam.TokenFeature{:token "text", :spam 907, :ham 1975} #clj_ml5.spam.TokenFeature{:token "extract", :spam 3, :ham 5}) As shown in the preceding code, each TokenFeature record will contain the number of times a given word is seen in spam and ham e-mails. Also, the word "to" is not recognized as a feature since we only consider words comprising of three or more characters. Now, let's check how sensitive to spam e-mail our spam classifier actually is. We'll first have to select some text or a particular term that is classified as neither spam nor ham. For the training data selected for this example, the word "Job" fits this requirement, as shown in the following code. Let's train the classifier with the word "Job" while specifying the type of the text as ham. We can do this using the train! function, as follows: user> (classify "Job") [:unsure 0.6871002132196162] user> (train! "Job" :ham) #<Agent@1f7817e: 1993> user> (classify "Job") [:unsure 0.6592140921409213] After training the classifier with the given text as ham, the probability of the term being spam is observed to decrease by a small amount. If the term "Job" occurred in several more e-mails that were ham, the classifier would eventually classify this word as ham. Thus, the classifier doesn't show much of a reaction to a new ham e-mail. On the contrary, the classifier is observed to be very sensitive to spam e-mails, as shown in the following code: user> (train! "Job" :spam) #<Agent@1f7817e: 1994> user> (classify "Job") [:spam 0.7445135045480734] An occurrence of a particular word in a single spam e-mail is observed to greatly increase a classifier's predicted probability of the given term belonging to a spam e-mail. The term "Job" will subsequently be classified as spam by our classifier, at least until it's seen to appear in a sufficiently large number of ham e-mails. This is due to the nature of the chi-squared distribution that we are modeling. We can also improve the overall error of our spam classifier by supplying it with more training data. To demonstrate this, let's cross-validate the classifier with only one-tenth of the sample data. Thus, the classifier would be effectively trained with nine-tenths of the available data, as follows: User≫ (Train-And-Cv-Classifier 1/10) Total : 300 100.00 % Correct : 294 98.00 % False-Positive : 0 0.00 % False-Negative : 1 0.33 % Missed-Ham : 3 1.00 % Missed-Spam : 2 0.67 % Nil As shown in the preceding code, the number of misses and wrongly classified e-mails is observed to reduce when we use more training data. Of course, this is only shown as an example, and we should instead collect more e-mails to feed into the classifier as training data. Using a significant amount of the sample data for cross-validation is a good practice. In summary, we have effectively built a spam classifier that is trained using Fisher's method. We have also implemented a cross-validation diagnostic, which serves as a kind of unit test for our classifier. Note that the exact values produced by the train-and-cv-classifier function will vary depending on the spam and ham emails used as training data. Summary In this article, we've explored the tools provided by the clj-ml library to cross-validate a given classifier. Later, we've built an operational spam classifier that incorporates cross-validation to determine whether the classifier is appropriately classifying e-mails as spam. Resources for Article: Further resources on this subject: - Clojure for Domain-specific Languages - Design Concepts with Clojure [Article] - Application Performance [Article] - Improving Performance with Parallel Programming [Article]
https://www.packtpub.com/books/content/using-cross-validation
CC-MAIN-2015-11
refinedweb
6,539
50.77
or Kubernetes or Mesos or anything like that - Running containers has a bunch of advantages even with no Docker - If you’re going to move to Docker/k8s eventually, you need to containerize anyway. You can separate out this work into a smaller project! - so this might be a good migration plan if you want to eventually move to Kubernetes or something As usual I am not a container expert. I am just trying to figure out how to use them. Maybe this will be useful to you too! I’m writing this because I think having more ideas for migration plans on the internet to think about and compare is a good thing. vertical change vs horizontal change If you’re trying to make a big infrastructure change (like migrate to Kubernetes), there are basically two ways to do it. You could make a new small Kubernetes cluster which contains all your hopes and dreams, and slowly migrate things into the new cluster. The second way is to incrementally roll out small changes. So you start out making a bunch of changes horizontally across your infrastructure, and move everything a little towards Kubernetes, and a little more, and a little more, and a little more, and then finally hopefully you have what you want. Right now making changes horizontally feels less risky to me, because it means you can check that your changes will actually work everywhere and there’s less danger of “we have this cool new world but a bunch of our software can’t actually use any of it right now”. But there are also good things about building the Cool New World first! You can start to learn how to operate your Cool New World by deploying less critical applications there. what does “use containers without Docker” mean (and why you might want to start without Docker) I mean a pretty specific thing by “just use containers”. We learned a while back that Docker has a daemon. This daemon does a bunch of stuff for you, like - supervising your containers and restarting them when they stop - redirecting your programs’ logs - letting you run commands like docker psto see what you have running on the box - I don’t even know what else Lots of cool orchestration features like with Kubernetes or Mesos or Docker Swarm mean that I need to learn how the software works and how it operates and exactly how it can fail in production. Which I am okay with doing, eventually! But in the short term, if I want to deploy changes that I can confidently run in production, using all kinds of exciting features like this just slows me down. So, what’s the minimal way to use containers, where you use as few features as possible but still get some advantages? Right now I think it’s: - build a container image. Use whatever you want to do this (a Dockerfile, packer, whatever). You can use as many fancy tools as you want to build your containers. - run that container with rkt. rkt just runs containers, the same way you run a program. I know how to run programs! This is awesome. - run the container in your host network namespace (same place as before) so you don’t need to worry about any fancy networking business - supervise it the same way you supervise things currently - run the container in its own pid namespace And rkt is mostly just responsible for starting up my process in a reasonable environment and passing on any signals it gets to my process. It seems like it would be hard to screw that up too much. (though, as usual with software, who knows what will happen until you try) rkt actually does a bit more than I’ve described – it keeps a local store of containers on your machine, it does a bunch of security checks at runtime, and it runs systemd as an init process inside your container. There’s probably more that I don’t understand yet, too. what just containers can do for me Three things I would really like: - have less lines of puppet configuration that I am scared of changing - stop thinking in terms of how to provision specific computers (“I need to put this file at /etc/awesome/blah.xml on this computer”), and worry more about services (“this program always needs /etc/awesome/blah.xml to exist”) - have better standards around how we run services (less special snowflakes) I think that just using containers by itself will force us to be disciplined about how we package and run services (you have to install all the stuff the service needs inside the container, otherwise the service will not work!). There’s no way for it to silently depend on the host configuration, because its filesystem is totally separate from the host’s filesystem. To get these advantages, you don’t need to run Docker or Kubernetes or Mesos or anything! You just need to have a container that is isolated from the rest of your operating system. To be clear, I don’t necessarily think it makes sense to stop at “just use containers”. This is just about separating work into smaller useful chunks. migrating to using containers without docker might be really easy! The exciting thing to me about “use containers without docker” is that I don’t need to learn how to operate any new programs in production. I’m hoping that if we do this, we can get it done pretty quickly, and then move on to the business of deciding how to manage the containers. And you’ll have to do all this “make your programs work with containers” work anyway to use any containerization magic! So you’re just doing work that you’d have to do anyway. cautiously optimistic I used to be really annoyed about containers because it seemed like a buzzword. But it seems like right now a lot of the thinking & software being built around “make it easy for developers to run code” is happening in the context of containers. So it seems like it’s worth it for me to learn what’s happening in containerland! So I’m going to try this stuff out, but I think we’re going to start slowly and introduce as little new software into our production environments at a time as I can :) thanks to Kamal for reading this and being the best. Also to Greg my coworker who is the best for telling me many things about containers.
https://jvns.ca/blog/2016/10/26/running-container-without-docker/
CC-MAIN-2017-51
refinedweb
1,096
65.86
I'm having the same problem as this guy and possibly this guy, but I am around to share some code and respond to questions! I have some code in a batch job that reads fields from a Microsoft Access database via pyodbc and prepares the output for display. Here is a snippet. Note the assert. def format_currency(amount): if amount is None: return "" else: result = "$%.2f" % amount assert ":" not in result, ( "That's weird. The value %r of class %s is represented as %s" % (amount, amount.__class__, result)) return result AssertionError: That's weird. The value Decimal('54871.0000') of class <class 'decimal.Decimal'> is represented as $54870.:0 from decimal import Decimal print "$%.2f" % Decimal('54871.0000') $54871.00 ':' is '9' + 1 in ASCII decimal _exp _int _sign _is_special _exp: -4 _int: 548710000 _sign: 0 _is_special: False decimal __float__ def __float__(self): """Float representation.""" return float(str(self)) print "Str", str(amount) print "Float", float(amount) Str 54871.0000 Float 54870.: I was able to reproduce the error. I created an Access table [pyData]... ID - AutoNumber Amount - Currency (2 decimal places) ...and filled it with a million rows of random values between 50,000 and 60,000. When I ran my test script it failed here 30815 : $50638.91 30816 : $52423.28 30817 : Traceback (most recent call last): File "C:\__tmp\pyOdbcTest.py", line 20, in <module> print row.ID, ":", format_currency(row.Amount) File "C:\__tmp\pyOdbcTest.py", line 10, in format_currency (amount, amount.__class__, result)) AssertionError: That's weird. The value Decimal('58510.0000') of class <class 'decimal.Decimal'> is represented as $5850:.00 I also tested that value (58510.00) and the one that failed for you (54871.00) as single rows in a separate table with the same structure, and they both failed. So we know that it's not a function of some leftover "junk" from an earlier ODBC call. Thinking that it might be related to the number having a '1' followed by zeroes to the end of the number, I tried 55871.00, but that worked fine. 53871.00 worked fine, too. Changing the number back to 54871.00 revived the error. I tried the same test using pypyodbc and got the same error. I was somewhat optimistic because pypyodbc includes a number of Access-specific features, so I thought that one of its users may have encountered this problem before, but apparently not. Finally, I upsized my test table to SQL Server 2008 R2 Express and tried the same test using the {SQL Server Native Client 10.0} driver. The numbers that failed when read from Access ("Currency" column type) did not fail when read from the SQL Server table ("money" column type). So, the best I can offer for an "answer" at the moment is: It looks like it's either: a bug in pyodbc (and pypyodbc, which appears to be quite closely related to pyodbc), or a bug in the Microsoft Access ODBC Driver, or an "unfortunate interaction" between the two (if the ODBC spec is loose enough that neither component is technically "wrong"). In any case it looks like you'll need to work around it, at least for now. Since I had that big batch of numbers I decided to let the script keep running and see what other numbers might get formatted with a colon in them. The resulting list all seemed to be whole numbers (no pennies), so I ran another test with whole numbers between 1 and 100,000. I found 260 numbers that wound up with a colon in the formatted string: 1451.0000 -> $1450.:0 1701.0000 -> $1700.:0 1821.0000 -> $1820.:0 1951.0000 -> $1950.:0 2091.0000 -> $2090.:0 ... 98621.0000 -> $98620.:0 98710.0000 -> $9870:.00 99871.0000 -> $99870.:0 I pasted the entire list here. Perhaps that might be helpful. My previous tests were run under Python version 2.7.3. I just upgraded Python to version 2.7.5 (Win 32-bit) with pyodbc still at version 3.0.6 and the problem seems to have gone away.
https://codedump.io/share/DsutumvkVGJV/1/python-inserts-a-colon-in-a-decimal-number-from-access-via-pyodbc
CC-MAIN-2017-39
refinedweb
681
76.72
Hi, 1. Create an app in web2py admin panel 2. In models/db.py define a table named entries Entries = db.define_table("entries", Field("entry", "text")) 3. Register a new user in 4. Go to appadmin and Add a couple of entries. 5. now add the RESTful services to the default.py controller as described in ('parse_as_rest') or here: ) def PUT(table_name,record_id,**vars): return db(db[table_name]._id==record_id).update(**vars) def DELETE(table_name,record_id): return db(db[table_name]._id==record_id).delete() return dict(GET=GET, POST=POST, PUT=PUT, DELETE=DELETE) 6. In the browser: you get all entries with 7. you get the just the second entry with 8. you get all auto-generated patterns with That's as far as we get with GET in a browser. 9. To make things more realistic, we add basic user authentication and try some POSTs with curl. - Add auth.settings.allow_basic_login = True @auth.requires_login() above @request.restful. Authentification now is mandatory for the REST interface. 10. get the first entry curl --user user:pass default/api/entries/id/1.json 11. post a new entry curl --user user:pass -d "f_entry=something" default/api/entries.json 12. delete the first entry curl -X DELETE --user user:pass default/api/entries/1.json 13. Same thing from python: import requests from requests.auth import HTTPBasicAuth payload = {'f_entry': 'somevalue'} auth=HTTPBasicAuth('user', 'pass') r = requests.post("", data=payload, auth=auth) r = requests.delete("", data=payload, auth=auth) 0 raj-chinna-11798 6 years ago Hi, I know it's beginner question, but still am struggling to find a answer for it. Currently am building a restful service with my web2py app to get log files from my mobile application, so I need to know how to handle file uploading (server & client side [java]) in the web2py restful services. Thanks in advance, 0 dirkk0 7 years ago
http://www.web2pyslices.com/slice/show/1533/restful-api-with-web2py
CC-MAIN-2020-34
refinedweb
315
52.66
On Tuesday, June 4, 2002, at 12:38 PM, Stephan Michels wrote: > > > On Tue, 4 Jun 2002, Stefano Mazzocchi wrote: > >> Stephan Michels wrote: >> >>> I think what be useful for the first time is an projection of >>> a loaction >>> in a repository on a url. My first initial stage was: >>> >>> slide://<namespace>/<uri of the >>> resource>?username=<principal>&revision=<revision> >> >> If you make this a WriteableSource, I'm sure many will start to use it >> right away instead of writing stuff on the file system. > > It is a WriteableSource ;-) > Top man! One innocent question (sorry, I am completely new to Slide). Say you were going to make a file-based repository to be managed by Slide. Say you wanted to access this repository via Slide for editing purposes only, but publish files to actual users via the (faster?) FileGenerator, does Slide leave you with a coherent file hierarchy to read directly? Or, once you use Slide as your repository, every access MUST go through Slide? thanks for any help I liked Stefano's (?) idea, a repository that is accessed through Slide for version management, but via Xindice for user access, taking advantage of XPath queries on whole collections. regards Jeremy --------------------------------------------------------------------- To unsubscribe, e-mail: cocoon-dev-unsubscribe@xml.apache.org For additional commands, email: cocoon-dev-help@xml.apache.org
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200206.mbox/%3C60C71A7C-77B8-11D6-9CD6-0003935AD2EE@mac.com%3E
CC-MAIN-2017-34
refinedweb
219
56.05
Surprisingly, even advanced Python coders don’t know the details of the copy() method of Python lists. Time to change that! Definition and Usage: The list.copy() method copies all list elements into a new list. The new list is the return value of the method. It’s a shallow copy—you copy only the object references to the list elements and not the objects themselves. Here’s a short example: >>> lst = [1, 2, 3] >>> lst.copy() [1, 2, 3] In the first line, you create the list lst consisting of three integers. You then create a new list by copying all elements. Syntax: You can call this method on each list object in Python. Here’s the syntax: list.copy() Arguments: The method doesn’t take any argument. Return value: The method list.clear() returns a list object by copying references to all objects in the original list. Video: Related articles: Here’s your free PDF cheat sheet showing you all Python list methods on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall: Python List Copy Shallow Before you can truly understand the copy() method in Python, you must understand the concept of a “shallow copy”. In object-oriented languages such as Python, everything is an object. The list is an object and the elements in the list are objects, too. A shallow copy of the list creates a new list object—the copy—but it doesn’t create new list elements but simply copies the references to these objects. You can see that the list below is only a shallow copy pointing to the same elements as the original list. In Python, the list.copy() method only produces a shallow copy which has much faster runtime complexity. Here’s an example showing exact this scenario: >>> lst = [6, 7, [1, 2], "hello"] >>> lst_2 = lst.copy() >>> lst_2[2].append(42) >>> lst[2] [1, 2, 42] Changing the third list element of the copied list impacts the third list element of the original list. Python List Copy Deep Having understood the concept of a shallow copy, it’s now easy to understand the concept of a deep copy. A shallow copy only copies the references of the list elements. A deep copy copies the list elements themselves which can lead to a highly recursive behavior because the list elements may be lists themselves that need to be copied deeply and so on. Here’s a simple deep copy of the same list as shown previously: In contrast to the shallow copy, the list [1, 2] is copied separately for the deep copy list. If one changes this nested list in the original list, the change would not be visible at the deep copy. (Because the nested list of the deep copy list is an independent object in memory.) Note that in a deep copy, the string object must not be copied. Why? Because strings are immutable so you cannot change them (and, thus, there will be no dirty “side effects” seen by other copies of the list pointing to the same object in memory. To get a deep copy in Python, use the copy module and use the deepcopy() method: >>> import copy >>> lst = [6, 7, [1, 2], "hello"] >>> lst_2 = copy.deepcopy(lst) >>> lst_2[2].append(42) >>> lst[2] [1, 2] How to Copy a Python List (Alternatives)? Say, you want to copy the list. What options are there? Slicing belongs to the fastest methods (very dirty benchmark here). If you need to refresh your Python slicing skills, here’s a tutorial on the Finxter blog: Related Articles: Python List Copy Not Working The main reason why the list.copy() method may not work for you is because you assume that it creates a deep copy when, in reality, it only creates a shallow copy of the list. To create a deep copy where the list elements themselves are copied (e.g. for multi-dimensional lists), simply import the copy module and use its method deepcopy(x) to copy list x. >>> import copy >>> lst = [[1, 2], 3, 4] >>> lst_2 = copy.deepcopy(lst) Python List Copy And Append How to copy a list and append an element in one line of Python code? Simply use slicing to copy the list and the list concatenation operator + to add the list of a single element [x] to the result. But there are other nice ways, too. Check out the following ways to append element x to a given list lst and return the result as a copy: - lst[:] + [x] - lst.copy() + [x] - [*lst, x] The third way to copy a list and append a new element is my personal favorite because it’s fast, easy-to-read, and concise. It uses the asterisk operator to unpack the elements of the original list into a new list. Python List Copy By Value Do you want to copy all elements in your list “by value”? In other words, you want not only the list object to be copied (shallow copy) but also the list elements (deep copy). This can be done with the deepcopy() method of Python’s copy library. Here’s an example: >>> import copy >>> lst = [6, 7, [1, 2], "hello"] >>> lst_2 = copy.deepcopy(lst) >>> lst_2[2].append(42) >>> lst[2] [1, 2] The element 42 was not appended to the nested list of lst. Python List Copy With Slice You can simply copy a list lst by using the slice operation lst[:] with default start and stop indices so that all elements are copied in the list. This creates a shallow copy of the list lst. Related Articles: Python List Copy Without First Element To copy a list without its first element, simply use slicing list[1:]. By setting the start index to 1 all elements with index larger or equal to 1 are copied into the new list. Here’s an example: >>> lst = [1, 2, 3, 4] >>> lst[1:] [2, 3, 4] Python List Copy Without Last Element To copy a list without its last element, simply use slicing list[:-1]. By setting the start index to -1 (the right-most list element) all elements but the last one are copied into the new list. Here’s an example: >>> lst = [1, 2, 3, 4] >>> lst[:-1] [1, 2, 3] Python List Copy Time Complexity The time complexity of shallow list copying—examples are list.copy() or slicing list[:]—is linear to the number of elements in the list. For n list elements, the time complexity is O(n). Why? Because Python goes over all elements in the list and adds a copy of the object reference to the new list (copy by reference). I wrote a quick script to evaluate that the time complexity of copying a list is, in fact, linear in the number of list elements: import matplotlib.pyplot as plt import time y = [] for i in [100000 * j for j in range(10)]: lst = list(range(i)) t0 = time.time() lst_2 = lst[:] t1 = time.time() y.append(t1-t0) plt.plot(y) plt.xlabel("List elements (10**5)") plt.ylabel("Time (sec)") plt.show() Here’s the result: The runtime grows linearly in the number of list elements. Python List Copy Partially How to copy a list partially? To copy only the elements between start index (included) and stop index (excluded), use slicing like this: list[start:stop]. This results in a new list that contains only parts of the list. Python List Copy Multi-Dimensional List To copy a multi-dimensional list (a list of lists), you need to create a deep copy. You can accomplish this with the copy library’s deepcopy() method as follows: >>> import copy >>> lst = [[1, 2, 3], [4, 5, 6]] >>> lst_2 = copy.deepcopy(lst) >>> lst_2 [[1, 2, 3], [4, 5, 6]] Now check if the copy is really deep by clearing the first list element in the copy: >>> lst_2[0].clear() >>> lst [[1, 2, 3], [4, 5, 6]] >>> lst_2 [[], [4, 5, 6]] You can see that the copy was really deep because the first element of the lst was not affected by the clear() method that removed all elements for the deep copy lst_2. Python List copy() Thread Safe Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as copy()) are actually thread safe. In other words: can you call the copy().copy() method creates a shallow copy of the list. The copy.deepcopy(list) method creates a deep copy.
https://blog.finxter.com/python-list-copy/
CC-MAIN-2021-43
refinedweb
1,435
71.55
Test.Framework.Tutorial.) Suppose you are writing a function for reversing lists: myReverse :: [a] -> [a] myReverse [] = [] myReverse [x] = [x] myReverse (x:xs) = myReverse xs To test this function using the HTF, you statements are also needed: import System.Environment ( getArgs ) with name allHTFTests of type TestSuite. Definitions starting with test_ denote unit tests and must be of type Assertion. Definitions starting with prop_ denote QuickCheck properties and must be of type T such that T is an instance of the type class Testable. To run the tests, use the runTestWithArgs function, which takes a list of strings and the test. main = do args <- getArgs runTestWithArgs args reverseTests Here is the skeleton of a .cabal file which you may want to use to compile the tests. Name: HTF-tutorial Version: 0.1 Cabal-Version: >= 1.6 Build-type: Simple Executable tutorial Main-is: Tutorial.hs Build-depends: base, HTF Compiling the program just shown (you must include the code for myReverse as well), and then running the resulting program with no further commandline arguments yields the following output: Main:nonEmpty (Tutorial.hs:17) *** Failed! assertEqual failed at Tutorial.hs:18 expected: [3,2,1] but got: [3] Main:empty (Tutorial.hs:19) +++ OK Main:reverse (Tutorial.hs:22) *** Failed! Falsifiable (after 3 tests and 1 shrink): [0,0] Replay argument: "Just (847701486 2147483396,2)" * Tests: 3 * Passed: 1 * Failures: 2 * Errors: 0 . Moreover, for the QuickCheck property Main.reverse, the HTF also tutorial, we now give a correct definition for myReverse: myReverse :: [a] -> [a] myReverse [] = [] myReverse (x:xs) = myReverse xs ++ [x] Running our tests again on the fixed definition then yields the desired result: Main:nonEmpty (Tutorial.hs:17) +++ OK Main:empty (Tutorial.hs:19) +++ OK Main:reverse (Tutorial.hs:22) +++ OK, passed 100 tests. Main:reverseReplay (Tutorial.hs:24) +++ OK, passed 100 tests. * Tests: 4 * Passed: 4 * Failures: 0 * Errors: 0 The HTF also allows the definition of black box tests. See the documentation of the Test.Framework.BlackBoxTest module for further information.
http://hackage.haskell.org/package/HTF-0.3.1/docs/Test-Framework-Tutorial.html
CC-MAIN-2015-18
refinedweb
333
50.73
#include <thread.h> int cond_timedwait(cond_t *cv, mutex_t *mp, timestruct_t abstime) Use cond_timedwait(3T) as you would use cond_wait(), except that cond_timedwait() does not block past the time of day specified by abstime. (For POSIX threads, see "pthread_cond_timedwait(3T)".) cond_timedwait() always returns with the mutex locked and owned by the calling thread even when returning an error. The cond_timedwait() function blocks until the condition is signaled or until the time of day specified by the last argument has passed. The time-out is specified as a time of day so the condition can be retested efficiently without recomputing the time-out value.
http://docs.oracle.com/cd/E19620-01/805-5080/sthreads-43512/index.html
CC-MAIN-2014-35
refinedweb
102
51.99
Summary When the information you need already exists, but it's scattered here and there around the web, you have an option. You can create a small, super-lightweight web app to put it together--a mashup. It's not quite as easy as falling off a log, but it's gotten to the point that end users can create their own applications. Contents - What's a Mashup? - The Long Tail - Structure of a Mashup - Mashup Builders: Google Gadgets, Yahoo Pipes, Teqlo, QEDWiki - Mashup Enablers: Microformats & Web Scrapers (OpenKapow, Kapow, Dapper) - - Mashup Technologies - - Web page GUI components and GUI Builders: GWT, Xap, NetBeans - Data Formats: Microformats, RSS, Atom, JSON, JSONP - Communication Mechanisms: REST, APP - Data Sources and Repositories - Coding Libraries: JSR 311, ROME, ROME Propono - Service-Building Strategies - Security Considerations - Resources Mashups are super-lightweight web apps that are created in minimum time, with minimum code, from information and services that already exist on the web. You want your email, RSS feeds, and calendar all in one page? Smash the pieces into a web page that has the interface you want. Have a web-accessible GPS locator in your company's delivery trucks? Combine that feed with a a map service like Google maps to display the truck's location in real time, The possibilities are cool, and the prospect of doing them with very little work is even cooler. so it was great to get an overview of the technologies that make it all work. Andreas Krohn of Kapow Technologies gave a great survey of the tchnology landscape. This post summarizes his talk, mashing it together with a talk given by Sean Brydon, Greg Murray, and Mark Basier of Sun Microsystems, as well as one given by Dave Johnson (also from Sun). (The latter talks went deeper into the technologies and provided useful insights into security considerations. But mostly they introduced the most important buzzwords to know.) Software development tends to be an expensive, time-consuming process. So only the most critical projects get implemented. There are a limited number of them, but since they are used by many people, they justify the investment in a system that enhances reliability and scalability, like the Service-Oriented Architecture (SOA)--even if it is more complex and harder to use. On the other hand, many people have a need for small, single-purpose applications that may not do much more than put information together for their purposes. Those small apps rarely get developed, because coding resources are scarce. There are a very small number of users for those apps, but there are a large number of applications. When plotted on a curve, there the number of possible applications continues to infinity as the number of users diminishes to one: | * ^ | * | | * Users | * | * | * | * | * | * | * | * | * | * * * +-------------------------------------------- Applications --> Andreas pointed out that mashups help to address that "long tail" at the end of the graph. All development enhancements do that to some degree, of course. But the goal of mashup technology is to get to the point that users can do it for themselves. Let's say you want to put your hotel reservations, map of their locations, and a calender with your travel dates, all on one page. The goal is to see the information you need, all in one place, gathering it from whereever it happens to exist. To create a mashup, you need: - Web page GUI components and a GUI Builder - A communication mechanism and a data format - One or more data sources you can access - Optionally, a data repository you can interact with The GUI components display data and give you a way to provide selection. The coommunication mechanism goes out to the web, delivering a package of information in a given data format. The data sources deliver one-way information, while the optional repository gives you a way to store information you want to save. In a moment, We'll look at The most common technologies used in each area. First, let's take a look at some all-in-one mashup builders that let you create a mashup without writing a line of code. You can also configure your mashup to publish the information it gathers, delivering information in other formats such as Atom and JSON. The Pipes system is limited to RSS feeds, so if you want to access additional data sources, or perhaps add special functionality (like dragging items to the calendar), then you'll need to add some code. If you want to start playing with these technologies and see what kind of mashups you can construct, head over to the Resources section now. To find out how to turn normal web pages into data sources you can use in your mashups, read the next section. Following that, you'll find more information on the underlying technologies. When the information you is on the web, but it isn't in a form a mashup can, there is a solution: Use a Mashup Enabler to convert the information into usable form. - Download and run openkapow - Tell it to build a new service - Specify the URL the data comes from - Tell it what to search for in the page - Tell it which items to include in the output - Do an initial search - Specify a loop to output multiple items - Use menu items to extract pieces The risk with web scraping, of course, is that the data format you're scraping could change. But the reward is that you get the app you want. The risk/reward ratio depends on the time required to create such an app. With the all-in-one mashup build systems that serve "the long tail", the ratio becomes favorable to the point that it's worth setting up a web scraper to access critical bits of data, even if it has to change once in a while. Note: Other services in the web scraping category include Dapper, Google Data, and the Java Mozilla HTML parser. What follows is a whirlwind tour of the technology buzzwords mentioned in the talks. My notes are sketchy at points, but should serve as a decent guide to the process. In the old days, you did a lot of programming to create a GUI. But in the web era, you assemble pre-built components, wiring them to data feeds. The code you write--if any--is minimal. The components themselves are built using AJAX, of course. That means Javascript. But the tricky bit is the differences in the document object structure (DOM) that different browsers create for their web pages. AJAX component libraries attempt to account for those differences. The degree to which they're successful determines how robust and reliable they are. Libraries built of AJAX components include: - prototype - scrip.aculo.us - Dojo - jMaki, where the "j" stands for JavaScript, and "Maki" is Japanese for "wrapper", or "container". But even when you have the best of libraries, it takes a fair amount of work to wire them up and lay them out. That's where GUI builders come in. For a serious enterprise app that will have many users on different browsers, one of the commercial mashup builders may make sense, for the sake of increased reliability and timely support: - BackBase - NexaWeb On the other hand, when you're creating something for yourself, one of the open source builders may work well enough to do what you need on the browser you use regularly: - Google web Toolkit (GWT): Java classes that generate Javascript, so you can write cleaner code and use the compiler to help detect errors. With GWT you can browse the libraries, take advantage of code completion, refactor with the IDE, do unit testing, and rapidly cycle between coding and testing. Perhaps more importantly, the GWT libraries were designed to optimize the end user experience and only then, where possible, optimize the developer experience. - XAP: The open source version of NexaWeb - NetBeans: for jMaki A client that expects JSON format data uses tbe following URL convention to express that preference: The structure that comes back consists of: "id": 5 "name": "Bob" {"id": 5, "name": "bob" } [ {...}, {.... } ] When delivering JSON, the server sets the MIME type with a call like this one: response.setContentTye("appication/json;charset=UTF-8") Within strings, special characters like quotes, backslashes, slash characters, and control chars need to be escaped. In an interesting augmentation of basic JSON functionality, the client can append a callback name as parameter: When the server sees that command, it surrounds the JSON data with a call to the function, returning: someFunction(...JSON data...) So instead of doing an XMLHttpRequest, the client can use JSONP. <span onmouseover='alert(document.cookie);'>Data</span> The standard communication mechansims are REST, the Atom Publishing Protocol (APP) to publish Atom, RSS, JSON, and microformats, as well as straight HTTP requests to get such data. Really Easy System for Transmitting (web data) All REST is, in the end, is standard HTTP requests. The HTTP requests have been around for a long time, in fact. But someone finally decided to use them. With REST, you always specify a resource with a URI. You then implement standard CRUD functions (create, read, update, delete) with the equivalent HTTP requests: - Http POST - Http GET - Http PUT - Http DELETE When you combine REST with Javascript callback functions and JSON data, you get a lot of power at very low cost, even if the server is just pushing data to your client. But when the server is ready to listen to post, put, and delete requests, as well as GETs, you get even more power. And that is the basis of the Atom Publishing Protocol. Atom Publishing Protocol (APP) The APP is a REST-based publishing mechanism for Atom format data. In additon to providing CRUD functions with post, get, put, and delete, APP provides for user authentication, which is critical in any such scenario. Atom is a generic data format, of course. It's not just for blogs. But in addition to allowing any kind of data in an entry, Atom also allows for CRUD operations on collections of entries. In fact, it even includes next/previous links in its collections. To publish an entry, you post to a collection URI. To read one, you use GET. Then you edit and use PUT to replace it. Libraries that support APP include: - ROME: A strong Java library that handles RSS and Atom (discussed below) - Abdera: STAX-based Atom-only parser in Java - Google Data API: Google's library. Note: Other entries in this category include the Universal Feed Parser (Python) and the Windows-only Windows RSS Platform built into IE7. Now that you've see the choices for data formats and communication mechanisms, the possibilities for a data source are fairly easy to understand (any of which could be generated by masup enabler: - RESTful service - RSS or Atom feed (RSSBus, Grazr, Java ROME) The choices for a data repository are equally simple: - RESTful service (especially one that supports APP) - Local storage (for a rich client implementation) The libraries that make the most sense for coders on the Java platform include JSR 311, ROME, and ROME Propono. To consume an arbitrary feed with ROME, create a SynFeed object, read the data, and then convert it to Atom (or RSS, if you must). The command to create a new SynFeed looks something like this: Synfeed feed = input.build(new InputStreamReader(inputStream)); When polling, take the following steps to maximize performance and minimize network traffic: To publish with ROME: application/rss+xml application/atom+xml In general, you want to think syndication, not coordination. In other words, provide a RESTful feed, and let others mash it up the way they want to. (Instead of having long meetings where you make sure the provider and consumer interfaces match up.) You want to provide one or more of: - APIs - A RESTful web service - Atom or RSS feeds But to make sure that clients can make use of your service, you also want to provide: - Client-side javascript libraries - A client-side widget - Client-side CSS - Documentation for the API - An example showing how it all fits together You also want to set up a server-side proxy-style service, where: - The browser gets a web page from the host server - The web page gets Javascript file and CSS from the mashup server - The javascript gets data from the mashup database server (The client can also use cross-site scripting to pull together data from multiple sources.) Ideally, the server should also be prepared to deliver data in mulitple formats, including JSON, JSONP, and XML: if ("jsonp".equals(format) ... response.write("callback" + jsonp_value + content) else if ("json".equals(format) ... response.setContentType("text/json") else response.setContentType "text/xml") write ... For performance, you'll also want to do as much caching as you can: - Client-side cache via HTTP Conditional GET - Proxy server cache via HTTP headers - Server side cache using your favorite cache technology And you'll also want to set things up so that applications and browsers like Firefox, Safari, and IE can auto-discover your feeds, using HTML that looks roughly like this: <link rel="alternate", "title ="My Feed (RSS)", You'll also want to ensure that you're generating a valid feed, with properly escaped HTML and well-formed XML: - feedvalidator.org (works on all formats) Other service-building strategies include: - DWR: A combination of servlets on the server and Javascript on client--good for a tightly integrated application - JavaServer Faces to wrap Ajax components In summary, - Consider json for data interchanges - Strive for RESTful design - Access the server using a server-side proxy stragegy - Build a RESTful service so others can mashup your site The information in this section came from the Java Blueprints folks-Sean Brydon, Greg Murray, and Mark Basier--who turn out to have a fair amount of expertise on the subject. Any inaccuracies here resulted from my limitations, not theirs. To start with, use the data format that is appropriate for your level of exposure: - JSON: When you're in the same domain as the data provider. (You could get arbitrary Javascript, and that Javascript will execute, so you want to be inside your firewall.) - JSONP: When you are inside or outside of your domain. (You're specifying the javascript to execute with this format, so it's safer. That makes this the easiest and most portable option.) - XML: When you're getting data from outside your domain, or when the client isn't using Javascript, which would let it easily parse JSON data. When using JSON, any javascript could be coming your way, so you need a certain level of trust in your data source, or added levels of security protection: - Use a namespace for your javascript commands - Use CSS for customization - Don't add to the prototype of common objects Securing your services: - Create a token: - Create a file with apikey (It's secure because it can't be edited with javascript.) - Use a session-based hash to make sure that a session has been established (so the request isn't coming in at random): - Create an API key generated from the URL, using a one-way hash - The user registers to get the API key (a very long string) - The key is attached to the GET request - The host name is mapped against the hash for access. Other security notes: - Don't change state with HTTP GET - Add a security token to your forms - Don't just use cookies to validate the user - When rendering query string data, verify it All-in-one mashup builders: - BackBase: (Unfortunately, this page has a redirect that defeats the back button.) - NexaWeb: - QEDWiki (IBM): - Pipes (Yahoo): - Teqlo: Mashup Enablers - Dapper: - Google Gadgets: - Kapow Technologies: - Microformats: - OpenKapow: GUI-building technologies: - Dojo: - DWR: - Google Web Tookkit (GWT): - Java Server Faces: - jMaki: - XAP: Communications and data formats: - Abdera (Apache): - Atom: - Spec: - Overview: - Google Data: - JSON / JSONP: - REST: - ROME / Propono: - - - RSS 1.0: - RSS 2.0: Feed Validator: - Have an opinion? Readers have already posted 2 comments about this weblog entry. Why not add yours? If you'd like to be notified whenever Eric Armstrong adds a new entry to his weblog, subscribe to his RSS feed.
http://www.artima.com/weblogs/viewpost.jsp?thread=205160
CC-MAIN-2014-42
refinedweb
2,702
56.29
29 May 2012 12:07 [Source: ICIS news] LONDON (ICIS)--Ciech has appointed Dariusz Krawczyk as its new CEO, after deciding he was the best candidate to complete its restructuring prior to a fresh attempt at privatisation, the Polish chemical group said on Tuesday. Krawczyk, who served as CEO of Poland's Synthos, ?xml:namespace> Kunicki was dismissed from Ciech, An initial task for Krawczyk is to decide on the fate of Ciech's lossmaking toluene di-isocyanate (TDI), epichlorohydrin (ECH) and epoxy resins subsidiary, Zachem. One possibility is that Ciech will attempt to divest Zachem. In late April, Ciech said it had received a concrete offer for the unit, while last week an investment bank said that there was growing anticipation on the Newly installed treasury minister, Mikolaj Budzanowski, has said he wants to see the Polish state exit the chemical sector before the end
http://www.icis.com/Articles/2012/05/29/9564768/MOVES-Ex-Synthos-CEO-made-head-of-Polands-Ciech.html
CC-MAIN-2013-48
refinedweb
146
51.52
On 2009-04-07, Scott David Daniels <Scott.Daniels at Acm.Org> wrote: > Grant! Doh! > I also dislike the trailing backslashes and over-parenthesizing. > So, I'd do it like this (using the pare to avoid the backslash): The paren to avoid the backslashes is a good tip. > def controlEqual(self,other): > return (self.type == other.type > and self.name == other.name > and self.value == other.value > and self.disabled == other.disabled > and self.readonly == self.readonly) I don't really like to rely on my memory of operator precidence, but that's a personal problem. > ... >> problem is that my app never instanciates either the Control or the HTMLForm class: that's all done by module functions that the app calls, and they don't know about the new classes without some trickery (e.g. below) > The latter could be insured by monkey-patching: > ... > ClientForm.Control = FancyControl > ClientForm.HTMLForm = FancyHTMLForm > > But substituting monkey-patching :) How did I not know that phrase until today? > for class method insertion seems like you are going from one > quick and dirty technique to a slightly nicer quick and dirty > technique. I think like your monkey-patching solution better. It feels a bit cleaner. -- Grant Edwards grante Yow! ! Up ahead! It's a at DONUT HUT!! visi.com
https://mail.python.org/pipermail/python-list/2009-April/532191.html
CC-MAIN-2014-15
refinedweb
213
62.14
change screen orientation snippet shows how to change the screen's orientation in PySymbian. Preconditions This method is only available for some S60 3rd Edition devices. The orientation attribute of the application can be read and written and can be one of the following values: 'automatic' (this is the default value), 'portrait' or 'landscape'. Note: This method only changes the orientation of the application in which it is used. Other applications are not affected. In other words, once the application has been closed the screen's orientation is set back to the previous orientation. Source code import appuifw appuifw.app.orientation = 'landscape' Postconditions The application's orientation is set to landscape mode. 28 Sep 2009
http://developer.nokia.com/community/wiki/Archived:How_to_change_screen_orientation_using_PySymbian
CC-MAIN-2014-52
refinedweb
115
50.63
from thinkbayes2 import Pmf, Cdf, Suite import thinkplot Different species of flea beetle can be distinguished by the width and angle of the aedeagus. The data below includes measurements and know species classification for 74 specimens. Suppose you discover a new specimen under conditions where it is equally likely to be any of the three species. You measure the aedeagus and width 140 microns and angle 15 (in multiples of 7.5 degrees). What is the probability that it belongs to each species? This problem is based on this data story on DASL Datafile Name: Flea Beetles Datafile Subjects: Biology Story Names: Flea Beetles Reference: Lubischew, A.A. (1962) On the use of discriminant functions in taxonomy. Biometrics, 18, 455-477. Also found in: Hand, D.J., et al. (1994) A Handbook of Small Data Sets, London: Chapman & Hall, 254-255. Authorization: Contact Authors Description: Data were collected on the genus of flea beetle Chaetocnema, which contains three species: concinna (Con), heikertingeri (Hei), and heptapotamica (Hep). Measurements were made on the width and angle of the aedeagus of each beetle. The goal of the original study was to form a classification rule to distinguish the three species. Number of cases: 74 Variable Names: Width: The maximal width of aedeagus in the forpart (in microns) Angle: The front angle of the aedeagus (1 unit = 7.5 degrees) Species: Species of flea beetle from the genus Chaetocnema We can read the data from this file: import pandas as pd df = pd.read_csv('../data/flea_beetles.csv', delimiter='\t') df.head() Here's what the distributions of width look like. def plot_cdfs(df, col): for name, group in df.groupby('Species'): cdf = Cdf(group[col], label=name) thinkplot.Cdf(cdf) thinkplot.decorate(xlabel=col, ylabel='CDF', loc='lower right') plot_cdfs(df, 'Width') And the distributions of angle. plot_cdfs(df, 'Angle') I'll group the data by species and compute summary statistics. grouped = df.groupby('Species') <pandas.core.groupby.groupby.DataFrameGroupBy object at 0x7f33a1dd59b0> Here are the means. means = grouped.mean() And the standard deviations. stddevs = grouped.std() And the correlations. for name, group in grouped: corr = group.Width.corr(group.Angle) print(name, corr) Con -0.193701151757636 Hei -0.06420611481268008 Hep -0.12478515405529574 Those correlations are small enough that we can get an acceptable approximation by ignoring them, but we might want to come back later and write a complete solution that takes them into account. To support the likelihood function, I'll make a dictionary for each attribute that contains a norm object for each species. from scipy.stats import norm dist_width = {} dist_angle = {} for name, group in grouped: dist_width[name] = norm(group.Width.mean(), group.Width.std()) dist_angle[name] = norm(group.Angle.mean(), group.Angle.std()) Now we can write the likelihood function concisely. class Beetle(Suite): def Likelihood(self, data, hypo): """ data: sequence of width, height hypo: name of species """ width, angle = data name = hypo like = dist_width[name].pdf(width) like *= dist_angle[name].pdf(angle) return like The hypotheses are the species names: hypos = grouped.groups.keys() dict_keys(['Con', 'Hei', 'Hep']) We'll start with equal priors suite = Beetle(hypos) suite.Print() Con 0.3333333333333333 Hei 0.3333333333333333 Hep 0.3333333333333333 Now we can update with the data and print the posterior. suite.Update((140, 15)) suite.Print() Con 0.9902199258865487 Hei 0.009770186966082915 Hep 9.887147368342703e-06 Based on these measurements, the specimen is very likely to be an example of Chaetocnema concinna.
https://nbviewer.jupyter.org/github/AllenDowney/ThinkBayes2/blob/master/examples/flea_beetle_soln.ipynb
CC-MAIN-2021-10
refinedweb
572
60.72
In languages like C and C++ strings are character arrays and end with a null character. The null character is used to process the string and it is useful in many situations. The sequences of characters are stored in an array. But in Java, the string is an object that represents a sequence of characters. The java.lang.String class is used to create string class objects. Things to note about Java strings: - Java strings are objects of String class. - Java strings are stored on a separate memory location called "String constant pool". - There are also null-terminated strings in java, but they are extensively used in Internet applications. - There are two types of java strings: Mutable and immutable. How to Declare strings in Hava? There are two ways to create a String object: 1. By string literal 2. By new keyword 1.Java String literal is created by using double quotes. For Example: String s="welcome";. For example String s1="Welcome"; String s2="Welcome";//It doesn't create a new instance In the above example, only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in a string constant pool that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance. string constant pool is a separate block of memory where the strings are stored by JVM. 2. String s=new String("Welcome"); In such a case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non pool). Java String class methods: The String class defines a number of methods that allow us to accomplish a variety of string manipulation tasks. a) Java String length(): The Java String length() method tells the length of the string. It returns the count of total number of characters present in the String. b) Java String compareTo(): The Java String compareTo() method compares the given string with the current string. It either returns a positive number, negative number or 0. c) Java String concat(): The Java String concat() method combines a specific string at the end of another string and ultimately returns a combined string. It is like appending another string. d) Java String Trim(): The java string trim() method removes white spaces at the beginning and ending. e) Java String toLowerCase(): The java string toLowerCase() method converts all the characters of the String to lower case f) Java String toUpper(): The Java String toUpperCase() method converts all the characters of the String to upper case g) Java String ValueOf(): This method converts different types of values into a string. h) Java String replace(‘x’,’y’): Replace all appearances of X with Y i) Java String equals(): The Java String equals() method compares the two given strings on the basis of content of the string. j)Java ChartAt(n): Gives the nth character of the string. Java Example Program for all string methods import java.util.Scanner; public class Alphabetical_Order { public static void main(String[] args) { int n; String temp; Scanner s = new Scanner(System.in); System.out.print("Enter number of names you want to enter:"); n = s.nextInt(); String names[ ] = new String[n]; Scanner s1 = new Scanner(System.in); System.out.println("Enter all the names:"); for(int i = 0; i < n; i++) { names[i] = s1.nextLine(); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (names[i].compareTo(names[j])>0) { temp = names[i]; names[i] = names[j]; names[j] = temp; } } } System.out.print("Names in Sorted Order:"); for (int i = 0; i < n - 1; i++) { System.out.print(names[i] + ","); } System.out.print(names[n - 1]); } } Note: only a member of this blog may post a comment.
http://www.tutorialtpoint.net/2020/06/java-strings-and-string-methods.html
CC-MAIN-2022-05
refinedweb
668
64.71
Build your own back links with free blogs (don’t go overboard on linking to your stuff, mix in other authority links out) Put a couple of articles on each free blog so you look legit. Vary your link text, don’t use the same one over and over. One post immediately, one more in two weeks. One more each month is all that is needed and they can be short 500 word articles. - livejournal.com high traffic 78 million visits monthly free blog - tumblr.com high traffic 300 million visits monthly images mostly- look at what others in your niche are posting use hashtags - medium.com high traffic 161 million visits a month free blog long form content - blogger.com 53 million visits free blog owned by Google can be deleted if too spammy free blog integrates with evernote free website free website - substack.com 23 million visits free newsletters, podcasts, monetize your content a blog but with email, powerful search free website - wordpress.com 300 million visits a month free blog , has a search engine, very good extra website for links and traffic Be consistent - flipgrid.com 7 million visits a month video discussions + can build a community Create a group “discovery” search for other groups only 2 results can get in early keto link to google docs/youtube videos/ advice and teaching get your content up there submit to search console discovery when you publish something good be consistent - onlinegeniuses.com Must apply to use for marketers seo and digital marketers slack community Here is one of the biggest online communities that provides direct access to thousands of marketers and content creators, spanning across hundreds of niches. So not only can you use this to drive traffic to your website, but you can also use it for: Self promotion Guest blogging opportunities Outreach and link building Collaborations and joint ventures Find work and to hire people - clubhouse app 10 million users add your bio start an open room good topic – specific topic give great information ask the questions how they feel what they think share those emotions answer questions welcome questions clear call to action tattler feed post update switch to public not just logged in users Use Groups and create a group use keywords in your group name and descriptions publish content that helps others out cover image that represents your group find less competitive hashtags trendsmap.com to find better hashtags see what the most popular hashtags are around the world in the last 7 days ritetag.com use search bar and enter keyword can see tweet data - torial.com 65k visits a month change language to english topic magazines – niches find topics search apply to be an expert share your thoughts groups you can join and post to health group with english speakers thousands of users library, groups - medium.com republish your blog posts import a story add image link out to a optinpage - tumblr.com free blog tons of traffic blog directory directory for blogs and businesses - ten press release sites 2 free press releases/month hidden nav bar login signup now powerful 1 pr a day PR framework - For Immediate Release and contact info at top - short and snappy interesting headline - add your location and news peg(hook) in first paragraph - write just 2 or 3 paragraphs who what when where and why and 5. bullet points facts and figures - company description at the bottom - add 3 hash signs at end - make powerful listicles google love list posts and they are sharable need to have an end goal for this article.. lead, traffic, sales next logical step to solve the problem CTA social media links outreach – how are you going to get it out there Simplify the solution to a problem simple and easy = value step by step research at buzzsumo.com seed keywords gives you a loose idea of what the people like the most they have your target market already at those top sites semrush keyword research Great Tool to find keyword questions asked recently 5 free documents a month outline builder create master list then do a listicle for each subheading/topic 10 best ways to x = master article next do 10 articles for each way all linked from master article SILO Problem –step 1, step 2 step 3 —– all the way to the solution. Deep dive on each step separately look for more questions to solve all the articles link to each other Add images to your articles Strong images help sharability. freepik.com pexels.com unsplash.com Outreach get involved in discussions and offer your articles for them to share. market your content to get it shared. - Get converting traffic to your website with buyer intent keyword lists 3 types of buyer intent keywords content that matches buyer intent 4 stages of buying 1 frustration 2 interest 3 consideration 4 procurement 3 types of keywords informational How to __ ,History of __ , Ways to __ , What is____ , ________tutorials , ___guides Why____? investigational Top 10___ Reviews for _____, ____ vs. ____ , ___ compatibility transactional Buy ___, Free Shipping for ____, ____ deals, ____ coupon code keyword modifiers Best, cheap find, top, location, scam men, women, price serp intent keyword planner tool seed keyword yoast google suggest planner seed keyword look for questions comparisons find search intent change visualization to data download csv and study it - little known social sites to use for traffic - wt.social - friendica - mastodon - nextdoor.com list your business - steemit.com communities create a community - diaspora.com - ello.com for artists What’s my source for most of these traffic tips? Mick Meany @profitcopilot he has some great Youtube videos for traffic. Check him out. But I know for a fact free blogs can help you look better on Google. I have been using them for years now. Spread your content web far and wide, it can only help if you post quality helpful articles that relate to your niche. Start using these effective traffic growing tools.
https://michaeljohnsonbiz.com/25-amazingly-effective-traffic-growing-tools/
CC-MAIN-2022-05
refinedweb
1,001
53.24
13.6. Finding Synonyms and Analogies¶ In the “Implementation of Word2vec” section, we trained a word2vec word embedding model on a small-scale data set and searched for synonyms using the cosine similarity of word vectors. In practice, word vectors pre-trained on a large-scale corpus can often be applied to downstream natural language processing tasks. This section will demonstrate how to use these pre-trained word vectors to find synonyms and analogies. We will continue to apply pre-trained word vectors in subsequent sections. 13.6.1. Using Pre-trained Word Vectors¶ MXNet’s contrib.text package provides functions and classes related to natural language processing (see the GluonNLP tool package[1] for more details). Next, let us check out names of the provided pre-trained word embeddings. In [1]: from mxnet import nd from mxnet.contrib import text text.embedding.get_pretrained_file_names().keys() Out[1]: dict_keys(['glove', 'fasttext']) Given the name of the word embedding, we can see which pre-trained models are provided by the word embedding. The word vector dimensions of each model may be different or obtained by pre-training on different data sets. In [2]: print(text.embedding.get_pretrained_file_names('glove')) ['glove.42B.300d.txt', 'glove.6B.50d.txt', 'glove.6B.100d.txt', 'glove.6B.200d.txt', 'glove.6B.300d.txt', 'glove.840B.300d.txt', 'glove.twitter.27B.25d.txt', 'glove.twitter.27B.50d.txt', 'glove.twitter.27B.100d.txt', 'glove.twitter.27B.200d.txt'] The general naming conventions for pre-trained GloVe models are “model.(data set.)number of words in data set.word vector dimension.txt”. For more information, please refer to the GloVe and fastText project sites [2,3]. Below, we use a 50-dimensional GloVe word vector based on Wikipedia subset pre-training. The corresponding word vector is automatically downloaded the first time we create a pre-trained word vector instance. In [3]: glove_6b50d = text.embedding.create( 'glove', pretrained_file_name='glove.6B.50d.txt') Print the dictionary size. The dictionary contains 400,000 words and a special unknown token. In [4]: len(glove_6b50d) Out[4]: 400001 We can use a word to get its index in the dictionary, or we can get the word from its index. In [5]: glove_6b50d.token_to_idx['beautiful'], glove_6b50d.idx_to_token[3367] Out[5]: (3367, 'beautiful') 13.6.2. Applying Pre-trained Word Vectors¶ Below, we demonstrate the application of pre-trained word vectors, using GloVe as an example. 13.6.2.1. Finding Synonyms¶ Here, we re-implement the algorithm used to search for synonyms by cosine similarity introduced in the “Implementation of Word2vec” section. In order to reuse the logic for seeking the \(k\) nearest neighbors when seeking analogies, we encapsulate this part of the logic separately in the knn (\(k\)-nearest neighbors) function. In [6]: def knn(W, x, k): # The added 1e-9 is for numerical stability cos = nd.dot(W, x.reshape((-1,))) / ( (nd.sum(W * W, axis=1) + 1e-9).sqrt() * nd.sum(x * x).sqrt()) topk = nd.topk(cos, k=k, ret_typ='indices').asnumpy().astype('int32') return topk, [cos[i].asscalar() for i in topk] Then, we search for synonyms by pre-training the word vector instance embed. In [7]: def get_similar_tokens(query_token, k, embed): topk, cos = knn(embed.idx_to_vec, embed.get_vecs_by_tokens([query_token]), k+1) for i, c in zip(topk[1:], cos[1:]): # Remove input words print('cosine sim=%.3f: %s' % (c, (embed.idx_to_token[i]))) The dictionary of pre-trained word vector instance glove_6b50d already created contains 400,000 words and a special unknown token. Excluding input words and unknown words, we search for the three words that are the most similar in meaning to “chip”. In [8]: get_similar_tokens('chip', 3, glove_6b50d) cosine sim=0.856: chips cosine sim=0.749: intel cosine sim=0.749: electronics Next, we search for the synonyms of “baby” and “beautiful”. In [9]: get_similar_tokens('baby', 3, glove_6b50d) cosine sim=0.839: babies cosine sim=0.800: boy cosine sim=0.792: girl In [10]: get_similar_tokens('beautiful', 3, glove_6b50d) cosine sim=0.921: lovely cosine sim=0.893: gorgeous cosine sim=0.830: wonderful 13.6.2.2. Finding Analogies¶ In addition to seeking synonyms, we can also use the pre-trained)\). In [11]: def get_analogy(token_a, token_b, token_c, embed): vecs = embed.get_vecs_by_tokens([token_a, token_b, token_c]) x = vecs[1] - vecs[0] + vecs[2] topk, cos = knn(embed.idx_to_vec, x, 1) return embed.idx_to_token[topk[0]] # Remove unknown words Verify the “male-female” analogy. In [12]: get_analogy('man', 'woman', 'son', glove_6b50d) Out[12]: 'daughter' “Capital-country” analogy: “beijing” is to “china” as “tokyo” is to what? The answer should be “japan”. In [13]: get_analogy('beijing', 'china', 'tokyo', glove_6b50d) Out[13]: 'japan' “Adjective-superlative adjective” analogy: “bad” is to “worst” as “big” is to what? The answer should be “biggest”. In [14]: get_analogy('bad', 'worst', 'big', glove_6b50d) Out[14]: 'biggest' “Present tense verb-past tense verb” analogy: “do” is to “did” as “go” is to what? The answer should be “went”. In [15]: get_analogy('do', 'did', 'go', glove_6b50d) Out[15]: 'went' 13.6.3. Summary¶ - Word vectors pre-trained on a large-scale corpus can often be applied to downstream natural language processing tasks. - We can use pre-trained word vectors to seek synonyms and analogies. 13.6.4. Exercises¶ - Test the fastText results. - If the dictionary is extremely large, how can we accelerate finding synonyms and analogies? 13.6.5. Reference¶ [1] GluonNLP tool package. [2] GloVe project website. [3] fastText project website.
http://d2l.ai/chapter_natural-language-processing/similarity-analogy.html
CC-MAIN-2019-18
refinedweb
906
52.46
Free text analytics seems a fashionable pastime at present. The most commonly seen form in the wild might be the very basic text visualisation known as the “word cloud”. Here, for instance is the New York Times’ “most searched for terms” represented in such a cloud. When confronted with a body of human-written text, one of the first steps for many text-related analytical techniques is tokenisation. This is the process where one decomposes the lengthy scrawlings received from a human into suitable units for data mining; for example sentences, paragraphs or words. Here we will consider splitting text up into individual words with a view to later processing. My (trivial) sample data is: Let’s imagine I want to know how many times each word occurs. For instance, “Alteryx” appears in there twice. Just to complicate things marginally, I’d also like to : - remove all the “common” words that tend to dominate such analysis whilst adding little insight – “I”, “You” etc. - ignore capitalisation: the word ALTERYX should be considered the same as Alteryx for example. Alteryx has the tools to do a basic version of this in just a few seconds. Here’s a summary of one possible approach. First I used an Input tool to connect to my datasource which contained the free text for parsing. Then use a formula tool to pull all the free text fields into one single field, delimited by a delimiter of my choice. The formula is simply a concatenation: [Free text 1] + "," + [Free text 2] + "," + [Free text 3] The key manipulation was then done using the “Text To Columns” tool. Two configuration options were particularly helpful here. - Despite its name, it has a configuration option to split your text to rows, rather than columns.This is great for this type of thing because each field might contains a different, and unknown amount of words in in – and for most analytic techniques it is often easier to handle a table of unknown length than one of unknown width. You will still be able to track which record each row originally came from as Alteryx preserves the fields that you do not split on each record, similar to how the “Transpose” tool works. - You can enter several delimiters – and it will consider any of them independently. The list I used was ', !;:.?"', meaning I wanted to consider that a new word started or ended whenever I saw a comma, space, full stop, question mark and so on. You can add as many as you like, according to how your data is formatted. Note also the advanced options at the bottom if you want to ignore delimiters in certain circumstances. When one runs the tool, if there are several delimiters next to each other, this will (correctly) cause rows with blank “words” to be generated. These are easily removed with a Filter tool, set to exclude any record where the text IsEmpty(). Next I wanted to remove the most common basic words, such that I don’t end up with a frequency table filled with “and” or “I” for instance. These are often called stopwords. But how to choose them? In reality, stopwords are best defined by language and domain. Google will find you plenty based on language but you may need to edit them to suit your specific project. Here, I simply leveraged the work of the clever developers of the famous Python Natural Language Toolkit This toolkit contains a corpus of default stopwords in several languages. The English ones can be extracted via: from nltk.corpus import stopwords stopwords.words('english') which results in a list of 127 such words – I, me, my, myself etc. You can see the full current list on my spreadsheet: NLTK stopwords. I loaded these into an Alteryx text input tool, and used a Join tool to connect the words my previous text generated (on the left side) to the words in this stopword corpus (on the right side), and took the left-hand output of the join tool. The overall effect of this is what relational database fans might call a LEFT JOIN: an output that gives me all of the records from my processed text that do not match those in the stopword corpus. (Alteryx has a nice “translate from SQL to Alteryx” page in the knowledgebase for people looking to recreate something they did in SQL in this new-fangled Alteryx tool). The output of that Join tool is therefore the end result; 1 record for each word in your original text, tokenised, that is not in the list of common words. This is a useful format for carrying on to analyse in Alteryx or most other relevant tools. If you wanted to do a quick frequency count within Alteryx for instance, you can do this in seconds by dropping in a Summarise tool that counts each record, grouping by the word itself. You can download the full workflow shown above here.
https://dabblingwithdata.wordpress.com/2015/06/
CC-MAIN-2019-09
refinedweb
827
69.11
On 07/11/2012 07:35 Don't you mean 'gcc impl' here? > though, we don't expect anyone to seriously use the pthread.h > impl, so this downside is not significant. Agree that the majority of compilation is currently done with gcc, even though we try hard to allow other compilers. > +++ b/configure.ac > @@ -157,7 +157,64 @@ dnl Availability of various common headers (non-fatal if missing). > AC_CHECK_HEADERS([pwd.h paths.h regex.h sys/un.h \ > sys/poll.h syslog.h mntent.h net/ethernet.h linux/magic.h \ > sys/un.h sys/syscall.h netinet/tcp.h ifaddrs.h libtasn1.h \ > - net/if.h execinfo.h]) > + net/if.h execinfo.h pthread.h]) NACK to this change. We already check for pthread.h via gnulib. > + > +dnl We need to decide at configure time if libvirt will use real atomic > +dnl operations ("lock free") or emulated ones with a mutex. > + > ;],[ > + atomic_ops=gcc > +],[]) > + > +if test "$atomic_ops" = "" ; then > + + + AC_TRY_COMPILE([], > + [__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4;], > + [AC_MSG_ERROR([Libvirt must be build with -march=i486 or later.])], > + []) > + + > + case "$host" in > + *-*-mingw* | *-*-cygwin* | *-*-msvc* ) > + atomic_ops=win32 Okay for mingw and msvc, but looks wrong for cygwin. Cygwin prides itself in having the same interface as Linux, and mucking with win32 internals violates that. But that means you are inheriting a glib bug, not something you are introducing yourself. On the other hand, cygwin cannot be compiled unless you use gcc, so the extent of the glib bug is a dead arm of the case statement, and not something that will ever trigger in reality. I suppose I can live with it, on the grounds that it was copy and paste; but I'd really like it if we isolated this into a separate file under m4/virt-...m4, and attributed it back to the glib sources, so that if glib enhances their tests, then we can more easily stay in sync with those enhancements. > @@ -714,7 +712,7 @@ virNWFilterSnoopReqPut(virNWFilterSnoopReqPtr req) > > virNWFilterSnoopLock(); > > - if (virAtomicIntDec(&req->refctr) == 0) { > + if (virAtomicIntDecAndTest(&req->refctr)) { The old code checked for 0, the new code checks for non-zero... > /* > * delete the request: > * - if we don't find req on the global list anymore > @@ -896,7 +894,7 @@ virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req, > skip_instantiate: > VIR_FREE(ipl); > > - virAtomicIntDec(&virNWFilterSnoopState.nLeases); > + virAtomicIntDecAndTest(&virNWFilterSnoopState.nLeases); ...but here, the old and new code both test for non-zero. Did you introduce a logic bug? > > - if (virAtomicIntInc(&virNWFilterSnoopState.wLeases) >= > - virAtomicIntRead(&virNWFilterSnoopState.nLeases) * 20) > + if (virAtomicIntAdd(&virNWFilterSnoopState.wLeases, 1) >= > + virAtomicIntGet(&virNWFilterSnoopState.nLeases) * 20) Did you mean to use virAtomicIntInc(&virNWFilterSnoopState.wLeases) instead of virAtomicIntAdd(&virNWFilterSnoopState.wLeases, 1)? ... > -# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ > 4) > -# undef __VIR_ATOMIC_USES_LOCK > -# endif > +/** > + * virAtomicIntInc: > + * Increments the value of atomic by 1. > + * > + * Think of this operation as an atomic version of { *atomic += 1; } > + * > + * This call acts as a full compiler and hardware memory barrier. > + */ > +void virAtomicIntInc(volatile int *atomic) > + ATTRIBUTE_NONNULL(1); ...Oh, I guess you can't, since this returns void instead of the old value. Then again, you have a subtle bug due to change of semantics. The old virAtomicIntAdd returns the NEW value; the new virAtomicIntAdd returns the OLD value. Since you are adding one, you have thus introduced an off-by-one. Or is this an instance where our existing code has the different logic under gcc than under pthread? Good thing you're adding a unit test for semantics, but that still means we need to inspect our usage for correct logic. > +/** > + * virAtomicIntCompareExchange: > + * Compares atomic to oldval and, if equal, sets it to newval. If > + * atomic was not equal to oldval then no change occurs. > + * > + * This compare and exchange is done atomically. > + * > + * Think of this operation as an atomic version of > + * { if (*atomic == oldval) { *atomic = newval; return TRUE; } > + * else return FALSE; } Can we s/TRUE/true/ to match the fact that we use the real <stdbool.h>? > + > +# define virAtomicIntGet(atomic) \ > + virAtomicIntGet((int *)atomic) What are these macro casts for? You are not properly parenthesizing things, and didn't the glib definition already check that the right size was being passed in? > +++ b/src/util/virfile.c > @@ -622,12 +622,12 @@ cleanup: > #else /* __linux__ */ > > int virFileLoopDeviceAssociate(const char *file, > - char **dev) > + char **dev ATTRIBUTE_UNUSED) > { > virReportSystemError(ENOSYS, > _("Unable to associate file %s with loop device"), > file); > - return -1;m > + return -1; > } This hunk is stale (commit 56f34e5). > +++ b/tests/Makefile.am > @@ -89,6 +89,7 @@ test_programs = virshtest sockettest \ > nodeinfotest virbuftest \ > commandtest seclabeltest \ > virhashtest virnetmessagetest virnetsockettest \ > + viratomictest \ TAB vs. space. > +static void > +thread_func(void *data) > +{ > + int idx = (int)(long)data; > + int i; > + int d; > + > + for(i = 0; i < ROUNDS; i++) { Space after 'for' > + d = virRandomBits(7); > + bucket[idx] += d; > + virAtomicIntAdd(&atomic, d); > +#ifdef WIN32 > + SleepEx (0,0); No space after SleepEx. > +static int > +testThreads(const void *data ATTRIBUTE_UNUSED) > +{ > + int sum; > + int i; Make this a long... > + virThread threads[THREADS]; > + > + atomic = 0; > + for(i = 0; i < THREADS; i++) > + bucket[i] = 0; > + > + for(i = 0; i < THREADS; i++) { Space after 'for' (twice) > + if (virThreadCreate(&(threads[i]), true, thread_func, (void*)(long)i) < 0) ...and you can avoid one of the casts here. > + return -1; > + } > + > + for(i = 0; i < THREADS; i++) > + virThreadJoin(&threads[i]); > + > + sum = 0; > + for(i = 0; i < THREADS; i++) (twice more) Enough problems that I'll need to see a v2. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library Attachment: signature.asc Description: OpenPGP digital signature
https://www.redhat.com/archives/libvir-list/2012-July/msg00624.html
CC-MAIN-2017-09
refinedweb
883
55.54
Communities [ REGRESSION / BUG ] getNSHScriptParamValues doesn't work anymoreClement BARRET Jun 30, 2014 5:20 AM Hi, I used to call the getNSHScriptParamValues method from the NSHScriptJob namespace. It worked flawlessly on our previous BMC BladeLogic environments (on our 7.6 and our 8.2 SP4 versions). Now, we migrated to the 8.3 SP2 and this method doesn't work anymore : blcli_execute "NSHScriptJob" "getDBKeyByGroupAndName" "/Workspace/ENG_BladeLogic/CBA" "NSH_SCRIPT_JOB_TEST" blcli_storeenv NSHSJ_DBKEY echo $NSHSJ_DBKEY DBKey:SJobModelKeyImpl:2029742-1-2226560 blcli_execute Job findByDBKey $NSHSJ_DBKEY blcli_execute Utility setTargetObject blcli_execute NSHScriptJob getName NSH_SCRIPT_JOB_TEST blcli_execute NSHScriptJob getType 111 blcli_execute NSHScriptJob getNSHScriptParamValues java.lang.NullPointerException I really don't want to rewrite much of my existing code just because of the poor QA process of the the BMC BladeLogic development team. So, we (ORANGE BUSINESS SERVICES / FRANCE) need this to be fixed ASAP. Best regards. PS : Please don't ask me what I need this method for and how to do without it, it was working on the previous BladeLogic versions, it's still there in the undocumented API, I just need it to work as it used to. 1. Re: [ REGRESSION / BUG ] getNSHScriptParamValues doesn't work anymoreJim Wilson Jun 30, 2014 5:39 AM (in response to Clement BARRET) Discussion successfully moved from BMC Bladelogic to Server Automation 2. Re: [ REGRESSION / BUG ] getNSHScriptParamValues doesn't work anymoreBill Robinson Jun 30, 2014 6:05 AM (in response to Clement BARRET) ‘getNSHScriptParamValues’ is, and has always been an ‘unreleased’ command, so it is not guaranteed to work. there is no qa or support done directly on the ‘unreleased commands’. so there is no issue of ‘poor QA process’. I would suggest that you open a ticket w/ support on this if you have no already. 3. Re: [ REGRESSION / BUG ] getNSHScriptParamValues doesn't work anymoreClement BARRET Jun 30, 2014 7:51 AM (in response to Bill Robinson) Hi @Bill Robinson, Well, let me tell you something, without this blcli command, much of your own "provided code" dispatched here and there on this community forum is not working at all/anymore. (mostly regarding NSHScriptJob parameters handling). Very well done, nice move from the BMC designers to have decided to remove this method ! (I suppose -- since there is no flaw in the QA process -- that's actually the case) What's quite "fun" though is that it's still listed in the unreleased commands (auto-generated by a command you start on the application server) even though it's not usable at all/anymore. May be those who decided to do that were too lazy to completely remove the method from the NSHScriptJob namespace and let a broken piece in its place ? No matter the reason, the "official" API is way too poor to be sufficient enough... when you really need to develop things around the BMC BladeLogic services... So, will you update/fix all of your messages (with code examples) that include this call ? I guess not... So you shouldn't in the first place have given us some code that would be broken in the next release... I know you're the community manager here and you're most often very successful and quite efficient to provide us with applicable answers -- and I appreciate that --, but that one is unacceptable. I've already opened a ticket and I hope to get some more useful answer than a "It's an unreleased command, don't cry me a river." one... Our BMC customer relationship partner once told us "If you need an undocumented blcli to become a officially supported one, just ask us and we will include it". I will in this case, for sure. PS : I've already proven in the past your QA process is broken in multiple ways so there's no point discussing that with you. That's a fact and nobody can deny it. 4. Re: [ REGRESSION / BUG ] getNSHScriptParamValues doesn't work anymoreBill Robinson Jun 30, 2014 8:05 AM (in response to Clement BARRET) We have not removed anything. this ‘getNSHScriptParamValues’ has never been a published or released command. what was the ticket # that you opened for this issue ? If this command is not used by any of the released commands (which it does not seem to be) then no testing of the released/published blcli commands would ever test it. that is why the ‘unreleased’ commands are always ‘use at your own risk’ which is noted: Did you submit a rfe / idea to have this command flagged as released ? if so do you have the QM # ? I don’t see anything like this in our tracking system after a quick search. 5. Re: [ REGRESSION / BUG ] getNSHScriptParamValues doesn't work anymoreClement BARRET Jun 30, 2014 8:43 AM (in response to Bill Robinson) @Bill Robinson : Bill Robinson a écrit: We have not removed anything. this ‘getNSHScriptParamValues’ has never been a published or released command. what was the ticket # that you opened for this issue ? [...] Did you submit a rfe / idea to have this command flagged as released ? if so do you have the QM # ? I don’t see anything like this in our tracking system after a quick search. - The customer support is already handling the ticket I opened. - I've not opened a "RFE/IDEA" yet because I didn't expect such an answer. I will soon though, once I've found the original email telling us we could do so. Welll, since I also found this call in one of your own script (which was quite nicely written imho), I will ask you something : How would you replace/modify one or more parameters's values of a NSHScriptJob without this call ? (here is the link to your own script : ) I used to follow almost the same process as the one described in your script. Now... I'm really stuck. Regards 6. Re: [ REGRESSION / BUG ] getNSHScriptParamValues doesn't work anymoreBill Robinson Jun 30, 2014 9:08 AM (in response to Clement BARRET)1 of 1 people found this helpful right - in that case it looks like the npe makes the script fail - so i think there should be a couple things here: 1 - an idea/rfe for a command that spits out all the values of the nsh parameters based on the job path or something like that. 2 - a defect for the npe. the issue w/ the 'unreleased' commands is that not all of the unreleased commands get used by 'released' commands, and in that case (as is the case here) the underlying commands would never get tested. that's why these have always been 'use at your own risk'. i talked to the support engineer for your case and we'll open a defect for the npe and see about scheduling - we'll follow up there.
https://communities.bmc.com/thread/109915
CC-MAIN-2017-51
refinedweb
1,125
59.94
Micron’s New Heavy Hitter NVMe devices have taken off these past few years, but adoption is accelerating in 2019. They now surpass both SAS and SATA as the preferred interface and are getting faster with each generation. That's a trend that won’t go away any time soon because we are currently creating over 2.5 exabytes of data a day, and by 2025, the global datasphere is predicted to hit upwards of 175 zettabytes. We once made data lakes; we are now making data oceans. In fact, that brings us to today’s review. Micron has updated its 9300 series of enterprise-class NVMe SSDs to boost capacity and performance to help handle the explosion of data. Micron's main goal was to improve the drive's write speed and achieve balanced sequential throughput by tweaking the firmware for the monstrous Microsemi NVMe controller under the hood. As a result, the new 9300 series SSDs hit 3.5 GB/s in both sequential reads and writes over its PCIe 3.0 x4 U.2 connection. Micron also reduced power consumption by 28% on average over the previous-gen model, and the drives are less expensive per gigabyte of storage than the prior-gen models, too. Finding Balance Why did Micron focus on achieving a balanced read and write speed? It is what today’s workloads demand, and it enables more efficient utilization of resources. In today’s markets, data-driven decision making is increasingly important. The 9300 series devices will usually find themselves used as caching devices in AI, machine learning, deep learning servers, or similar database or block- and object-acceleration scenarios. In many of these workloads, the applications need high-performance storage so that they can ingest the data from huge data lakes and then export back out as fast as possible. That allows GPUs and other accelerators to read the data as fast as possible to process and extract any valuable data. But it’s not just about sheer speed – efficiency is a big factor in enterprise storage. The 9300 series comes in capacities of up to 15.36TB, which a 40% increase over the previous generation and essentially ties with the most capacious HDDs. But these SSDs come in a compact U.2 form factor so you can fit many more into the same space, or use fewer racks and save on overall power consumption. The 9300 drives also support 16 power states ranging from 10W up to 25W. (We tested ours at the stock 25W mode) Micron's flex capacity feature allows IT admins to configure capacity to match their application’s workloads and requirements. Some users demand a cost-sensitive approach for upgrading their infrastructure for their workloads, while others need the fastest drive they can get. No one solution can satisfy every need, but a flexible one might be able to satisfy most. Customers are demanding storage tuned just for their needs. That’s where Flex Capacity comes into play. It gives the customer cost flexibility and the ability to adjust write endurance, performance, and consistency, along with capacity, for their applications. In fact, both the Micron 9300 PRO and MAX have the same hardware through and through. The MAX is simply preconfigured with more over-provisioning. We don’t have official pricing from Micron, but the PRO sells from ~$0.19 -$0.20 per GB online, while the MAX sells for ~$0.24 - $0.26 per GB depending on the capacity point. This gives customers the option to save a few bucks by buying the PRO, but remember, while it won’t be an upfront cost, it will take some time to reconfigure the drives in the field, if needed. Furthermore, Micron enabled the option to define up to 32 namespaces on a drive. This allows the drives to accommodate multitenancy deployments in hyperscale data centers and cloud infrastructure and enables more parallel sessions for single storage devices, which improves elasticity and application utilization. But while these features are awesome in their own way, note that Micron states that Flex Capacity and manual Namespace Management are not intended to be configured together and should be implemented independently. Specifications While Micron’s 9300 series puts out sequential performance of up to 3.5 GBps read/write, its no slouch in random workloads. These SSDs are rated to deliver up to 850,000/310,000 random 4K read/write IOPS and have average read/write latency ratings of 86/11us. The 9300 MAX and PRO comes with a 5-year warranty, and endurance figures are variable based on the model and capacity. Designed for read-intensive tasks (one drive write per day), the 9300 PRO’s endurance ranges from 8.4 to 33.6 petabytes (PB) written. While these figures by themselves are quite impressive, the MAX, with its greater over-provisioning, withstands anywhere from 18.6PB of writes at the smallest capacity, and up to a staggering 74.7PB at the highest. The MAX is only rated for three drive writes per day, but its huge capacity helps it to scale endurance to ultra-high levels. Furthermore, the drive comes with crypto erase support, power loss protection for data in-flight and data-at-rest, and enterprise data path protection (user & metadata). The Uncorrectable Bit Error Rate (UBER) is less than 1 sector per 10^17 bits read, and the Mean Time to Failure rating comes in at 2 million device hours. Software and Management Micron supports the 9300 series with its Storage Executive Software. It is compatible with both Windows and Linux. With it, you can monitor and manage the SSD. Micron’s 9300 series can also be updated from a single secure signed firmware file without the need to reset the system, helping prevent downtime. A Closer Look As mentioned earlier, the 9300 series SSDs come in a U.2 15mm form factor, unlike the 9200 series that has models in the HH-HL AIC form factor, too. Stuffing this compact enclosure with so much NAND and such a big controller can heat it up under load when consuming upwards of 21W at the highest capacity. That is why Micron opted to etch fins and cooling vents into the case to aid cooling. Once cracked open, we see that the PCB in all its glory. The 9300 series is powered by Microsemi's Flashtec 2nd generation NVMe controller, the PM8607 NVMe2016. It features 32 independent flash channels, each supporting up to 8 chip enables for high performance and capacity, but Micron may not be taking advantage of all of them. In Micron’s literature on the drive, it states that it only has 16 channels. Regardless of specifics, it is still quite impressive to open up our 7.68TB sample and see 32 of Micron’s 64L 3D TLC NAND packages jammed in there. Additionally, the controller supports the nine 1GB DDR4 2666MHz CL19 DRAM chips configured in an ECC arrangement for FTL caching and is backed by a large supercapacitor to improve reliability. MORE: How We Test HDDs And SSDs MORE: Best External Hard Drives and SSDs
https://www.tomshardware.com/uk/reviews/micron-9300-nvme-ssd-review,6256.html
CC-MAIN-2020-50
refinedweb
1,190
63.09
Accordingly to the C++ standard, no one knows. It is one of those undefined behavior that should worry you so much to be very careful in writing C++ code. If you are developing on Visual Studio, and you application is built in debug mode, the disaster is shielded by an assertion failure that pops up a window with some debug information that should help you to find the offending line (just press the retry button, and debug your code). If you want to see what happens in these cases, you could try this code: #include <queue> // ... void f() { // ... std::queue<int> qi; // qi.front(); // deque iterator not dereferencable // qi.pop(); // deque empty before pop // ... }1. If you uncomment this line, you would get a "deque iterator not dereferencable" assertion, since you are trying to dereference an iterator to an empty queue. 2. Trying to popping an empty queue results in a "deque empty before pop" assertion. [edit: Jon commented on google plus to this post, adding information for g++ and STLport. It is a very long time since the last time I have used the latter, but g++ is everyday matter, and Jon is right, I'd better complete the discussion with some words on the behavior of the Free Software Foundation compiler] To check what happens on g++, compile the code in debug mode, defining the constant _GLIBCXX_DEBUG, and run the resulting application. For both call you will get the same error message, "attempt to access an element in an empty container.", the execution will be aborted, and you will get some information on the objects involved in the operation.
http://thisthread.blogspot.com/2013_02_01_archive.html
CC-MAIN-2017-51
refinedweb
271
59.13
Current Situation ATS currently supports SSDs, however it does not take the best advantage of their special characteristics. In particular, SSDs could be used as an addition level in the cache (between RAM and traditional platter-based hard drives (HDDs)), and SSDs could benefit from reducing writes. Currently we write all misses to disk but we could write only (for example) on seeing the second miss to a particular URL. Use Cases - large working set, few HDDs, low RAM reverse proxy - large working set, many HDDs, probably forward proxy, but perhaps shard CDN - no moving parts forward or reverse proxy, 0 HDDs NOTE: situations with a small working set and adequate RAM fall will not benefit performance-wise from an SSD, however because of the relatively limited number of write cycles supported by SSDs currently, specialized SSD support might improve longevity and reliability. Features - support for re-writing warm content to an SSD if read from spinning media - this is uses the SSD as an additional level in the hierarchy between RAM and HDD - support for only writing the second miss in an SSD-only environment The Interim Caching Layer From V6.0.0, the interim caching feature is removed, please consider other options. When we thinking about the storage of ATS, the original desigin is to support many disks, with the same size(best work with block devices without raid), and build up the volumes(partitions), then assign each of the volumes to some domain(hostname), we find out that if we don't make big change in the storage design, we don't have a easy way to archive the multi-tiered caching storage, then we come to the following INTERIM solution: - we think that if your deployed mixed storage, the fast device is less. IE, 1/10 of the slow devices, in size or in counts. - we assume that in most case, 8 fast disks is fairly many. - we assume your slow disk should not go beyond 32TB per disk. - the slow devices holding all the data, should not loss them when fast disk fails. - compare to the storage percent, ie 10%, the fast devices may loss data during the server restart. - the fast disks should balance to all the slow disks, in size and even in IOPS. the volumes is building upon the slow disks, with slices from every disks, we should spread the load on each fast disk too. we make a design with balance: - a interim cache of the cache, which is lived on the fast disks(SSD in most case), will loss the data if you restart the server process. make the data on interim caching device a real interim. - we support 8 fast disks at most - we make a block level interim cache, which does not contains any index info what we have done: - we steal 4bit from the Dir struct, to identify each of the fast disks - we cut down the up limit of the disk in size to 32TB - we split each fast disks into volumes confiured in the volume.config, and bind them. - we store the interim data in the dir on the slow storages - write data from the origin server on the slow disks - we setup a interal LRU list, limited in size(1M bucket), and bump the busy blocks into fast device - we do hot data evocation on the interim caching devices, to make it more efficent, we do compare the blocks with the LRU list - the interim cache device(fast disks), works with RRD writing too. coins and pins: - coins: - we make a solid solution without big change in the storage architecture - the LUR help us get the hot blocks, it is efficent - the block layer interim caching can help on small objects and big ones too - pins: - loss data if the server process crash Fixed in TS-2275 - limited in block device only for used as interim caching device - the interim caching device space is not a add-on, but a copy of the hot data on the slow devices - we set lower the max disk size of the storage from 0.5PB to 32TB. - the interim caching function is not enabled by default configuration codes & structs: the change of Dir: @@ -155,15 +157,42 @@ struct FreeDir unsigned int reserved:8; unsigned int prev:16; // (2) unsigned int next:16; // (3) +#if TS_USE_INTERIM_CACHE == 1 + unsigned int offset_high:12; // 8GB * 4K = 32TB + unsigned int index:3; // interim index + unsigned int ininterim:1; // in interim or not +#else inku16 offset_high; // 0: empty +#endif #else uint16_t w[5]; FreeDir() { dir_clear(this); } we split the stat of read_success into disk, interim and ram: @@ -2633,6 +2888,11 @@ register_cache_stats(RecRawStatBlock *rsb, const char *prefix) REG_INT("read.active", cache_read_active_stat); REG_INT("read.success", cache_read_success_stat); REG_INT("read.failure", cache_read_failure_stat); + REG_INT("interim.read.success", cache_interim_read_success_stat); + REG_INT("disk.read.success", cache_disk_read_success_stat); + REG_INT("ram.read.success", cache_ram_read_success_stat); REG_INT("write.active", cache_write_active_stat); REG_INT("write.success", cache_write_success_stat); REG_INT("write.failure", cache_write_failure_stat); how to enable interim caching: configure to enable the interim caching function: add '--enable-interim-cache' option. we introduced two record config: - proxy.config.cache.interim.storage: disk device(s) for the interim cache, we only support block devices in full path, multipule disks may seperate by SPACE. example: LOCAL proxy.config.cache.interim.storage STRING /dev/sdb /dev/sdc1 - proxy.config.cache.interim.migrate_threshold: controls how many times one content should be migrate to the interim cache from the storage, which will control the writing on the interim disk. default to '2', which means it should be seen in the LRU list two times before we thinking of migrate it to the interim caching device. some of the result: we have a system with 160G SSD + 3 * 500G SAS, 16G RAM, 4 cores, here is the result of tsar and iostat -x: ``` Time --------------------ts------------------ -------------ts_cache----------- Time qps cons Bps rt rpc hit ramhit band ssdhit 24/06/13-10:30 901.83 18.89 22.6M 17.36 47.74 87.30 68.08 88.90 22.49 24/06/13-10:35 934.12 18.88 22.0M 14.34 49.47 87.60 68.53 90.70 22.21 24/06/13-10:40 938.14 18.92 21.7M 15.36 49.58 87.70 68.02 89.50 22.45 avg-cpu: %user %nice %system %iowait %steal %idle 5.47 0.00 15.62 25.09 0.00 53.82 Device: rrqm/s wrqm/s r/s w/s rsec/s wsec/s avgrq-sz avgqu-sz await svctm %util sda 0.00 7.33 25.67 3.33 1600.00 1438.00 104.76 0.45 15.46 12.17 35.30 sdb 0.00 0.00 28.67 11.33 1461.00 8723.00 254.60 0.74 18.47 11.21 44.83 sdc 0.00 0.00 25.67 2.00 2178.00 1373.33 128.36 0.40 14.05 11.04 30.53 sdd 0.00 0.00 196.00 4.00 14790.00 2823.00 88.06 0.13 0.66 0.41 8.30 ```
https://cwiki.apache.org/confluence/display/TS/SSDSupport
CC-MAIN-2019-18
refinedweb
1,180
57.1
Hi guys, i'm working on trying to pass commands from the console from one program to another program by using pipes() and the execve() system calls. I'm pretty much stuck right now, because I can't seem to determine what i'm doing wrong. Here are my code listings #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #define BUFLEN 100 #define MESSAGE "shit" int main(int argc, char *argv[]) { extern int errno; char buffer[BUFLEN]; char result[BUFLEN+1]; char *param[3]; float *fnum; int toServer[2]; int fromServer[2]; int pid; int err; char input[BUFLEN]; /*scanf("%s,%s\n",mpg, input);//fix this to call mpg function*/ /* Create a pipe */ err=pipe(toServer); /*For reading*/ err=pipe(fromServer); /*For writing*/ if(err==-1) { printf("Error on pipe creation: %d\n",errno); exit(1); } pid=fork(); if(pid==0) { /* Child process */ close(fromServer[1]); /*Close output*/ err=read(fromServer[0], buffer, BUFLEN);/*store from fromServer[0] into buffer*/ if(err==-1) { printf("Error on read from pipe: %d\n", errno); exit(2); } sscanf(buffer, "%f", &fnum);//convert buffer to float printf("response: Average MPG = %f\n", fnum);/*print from sprintf*/ exit(0); } else if (pid>0) { /* Parent process */ close(toServer[0]);/*Close input*/ err=write(toServer[1],result,strlen(result)+1);/*write char[] to fd[1]*/ if(err==-1) { printf("Error on write to pipe: %d\n", errno); exit(3); } sprintf(result, "%f", *fnum); param[0]=result; err = execve ("./server.c", param,0); if (err == -1) printf ("error on execve: %d\n", errno); exit(0); } else exit(4); } That is the first program that handles taking in the input from the console. This next one is the program that processes the command that is passed through the pipe. #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> typedef struct { char id[8]; int odometer; float gallons; }Records; int main(int argc, char *argv[]) { FILE *finput; int i, n; //extern int errno; //char buffer[BUFLEN]; //char result[100]; Records r[20]; finput = fopen("proj3.txt", "r"); for (i = 0; i < 13; i++ ) { fscanf(finput, "%s %d %f", &r[i].id, &r[i].odometer, &r[i].gallons); if (feof(finput)) { printf("end-of-file detected on file proj3.txt\n"); exit (1); } printf("element = %d, id = %s,odometer = %d, gallons = %f\n", i, r[i].id, r[i].odometer, r[i].gallons); } /*parameters passed to Server program via execve call, take in arguments as console, and calculate them using the mpg<id> function that calculates the avg use fromServer[], toServer[] to pass response back to Interface program to print create text file that stores in all the values listed in the project 3 description just numbers. use fprintf(), fscanf() to read and write from files must use fopen() and fclose() to handle open and close of files */ } Also, the text file which contains the inputs : 987654 201200 4.000000 red 89114 0.000000 red 89712 13.500000 red 90229 15.300000 987654 201001 0.000000 987654 201111 5.200000 987654 201612 25.299999 red 89300 7.100000 green 16 0.000000 green 216 20.000000 green 518 61.000000 green 879 50.000000 Both codes are incomplete at the moment because I am still trying to figure out how to fix it part by part. My question is, what am I doing wrong? How do I take in input from the console and pass it through the pipes to invoke a function in the "server.c" program. I understand that you can only pass strings, hence my sscanf() and sprintf() functions. Also am I utilizing execve() the right way? I understand that the community does not generally solve people's homework for them, and yes this is a project for a class, but I am not asking for an actual program, I just need some help in figuring out where i'm going wrong and what it is I should look at. It'd be great if someone could guide me in the right direction. Thank you
https://www.daniweb.com/programming/software-development/threads/177094/pipe-and-execve-problem
CC-MAIN-2016-50
refinedweb
685
73.98
Dart wrapper library for the new Firebase This is an unofficial Dart wrapper library for the new Firebase. You can find more information on how to use Firebase on Getting started page. Don't forget to setup correct rules for your realtime database and/or storage in Firebase console. Auth has to be also set in the Firebase console if you want to use it. Usage Installation Install the library from the pub or Github. Include Firebase source You must include the original Firebase JavaScript source into your .html file to be able to use the library. <script src=""></script> Use it import 'package:firebase3/firebase.dart' as firebase; import 'package:firebase3/database.dart'; }); ... } Examples You can find more examples on realtime database, auth and storage in the example folder. Bugs This is the first version of the library, the bugs may appear. If you find a bug, please create an issue. Libraries - firebase3.app - - firebase3.auth - - firebase3.database - - firebase3.firebase Firebase is a global namespace from which all the Firebase services are accessed. - firebase3.storage -
https://www.dartdocs.org/documentation/firebase3/0.1.0/index.html
CC-MAIN-2017-17
refinedweb
176
67.25
Arduino GPS Speedometer With a Ks0108 - 128x64 GLCD (display) Introduction: positioned in a more convenient position - right in front of me. And as I did not want to mess with my car's electronic parts in order to tap in and read the "speed" signal straight from the car's computer, I opted for the GPS version. Components needed: 1. Arduino Uno (Nano or other Arduino boards might be fine as well) 2. GPS module, I got this one (if the link is not working when clicked, just copy and paste it into your browser's address bar) 3. Graphic LCD (...) 4. 10k trimpot for adjusting the contrast of the LCD 5. 4.7k potentiometer for adjusting the brightness of the LCD 6. 100 ohm resistor to limit the current for the LCD brightness 7. Wires, suction cup, self-adhesive velcro, kitchen aluminium foil (or similar), soldering iron, pliers, hot glue gun, etc. Optionally: 8. USB cable for powering the Arduino board (and LCD) and separately the GPS module 9. 2 x USB (5V) car power adapters (at least 1A each) 10. Plastic enclosure (or you could build one) 11. and of course, a car with a battery to power the whole stuff Step 1: PLEASE NOTE: I would advise that you build a prototype version first, and only when tested and working start the actual building of the enclosure. In order to be able to upload sketches to the Arduino board, the GPS module will have to be disconnected, as it uses the same RX and TX pins to communicate with the Arduino board as the Arduino IDE. While the GPS module was left connected, attempts to upload sketches failed in my case. PS. As YukselV suggested, you could use SoftwareSerial instead of the "simple" Serial, in case you want to test other features which means uploading the sketch multiple times - you won't have to disconnect the GPS module in this case. Thanks YukselV! () Similarly, the LCD power will have to be disconnected while uploading sketches to the Arduino board. This is due to the RESET pin being connected to the LCD, which interferes with the Arduino IDE. I read that one could simply connect the RESET pin of the LCD to +5V on the Arduino (permanently), or simply temporarily disconnect the RESET wire while uploading the sketch to the Arduino board. I simply disconnected the power supply when required. *********************************************************************************** First, because my LCD order would take a while to arrive, I started by testing the GPS module using a LED display. *********** UPDATE 31.10.2016 ******************** I have attached the .INO sketch for using with a 4-Digit-7-Segment-LED-Display *********** end of UPDATE 31.10.2016 ******************** When the LCD finally arrived, it took me a while finding out the correct wiring for the LCD. I found a tutorial in Italian (...) that shows the wiring (...). That however was not working properly for me, so I had to change some stuff around: - I had to change some wiring around the 10k trimpot (controlling the LCD contrast) - I added another 4.7k potentiometer in series with a 100 ohm resistor, that will allow me to control the LCD brightness as well. EDIT: Thanks to ibenkos for pointing out that the +5v engine in my original wiring image was connected to ground rail on the breadboard. It should of course be connected to the positive rail - updated picture uploaded. Then I wanted for the speed to be displayed instantly after starting my car engine and moving off. However I didn't want to leave the whole stuff powered up all the time and risk for the car battery to go dead. Therefore I would power the Arduino board and the LCD only when I start the engine, while the GPS module would be powered all the time, even when the engine is off (so that it won't take "I don't care how many seconds to lock onto the positioning satellites for required data to be sent to Arduino for processing"). It's up to you however to locate the appropriate points where to get power from the fuse board. Using one USB car power adapter I would get continuous 5V to power the GPS module, while the second USB car power adapter would give me 5V to power the Arduino and the LCD only when I start the car engine. One more thing to note: I used fused wires to connect to both car power adapters, so that they will blow in case of a short circuit, and not some other car electronics. Step 2: Here I was testing the LCD wiring - note the resistors I was using instead of the trimpot, which I did not have at the time. Step 3: I cut a whole in the plastic enclosure (that I bought from a local shop) that will allow the LCD display to fit in, and then I hot-glued the LCD in place. I've cut a piece of plastic sheet and placed it on the back of the LCD then I added some aluminium foil on top. I also added aluminium foil all around the plastic enclosure, including the back cover, and connected everything to ground. The idea is: try to enclose the Arduino board inside an improvised Faraday cage () in order to prevent any interference from other electronic devices that could affect the functionality of the Arduino board. That's the idea, anyway :-) Is this really necessary? I don't know. However, make sure that you are not shorting any contacts on either the LCD or Arduino. Step 4: Because I needed two different 5V power supplies (one for Arduino and LCD, the other for the GPS module), and another wire that will connect to the potentiometer controlling the LCD brightness - four wires in total, if we account for the ground as well - I decided that I will use an USB cable, which is conveniently screened. I took the USB connector off the Arduino board (I didn't have another one at that time, and having uploaded and tested the whole thing before), I cut another hole in the plastic enclosure, and there I had my required power connection. You could use an additional USB connector, if you think you might need to upload updated sketches to the Arduino board. Or of course, you could use another type of an electrical connector altogether if you wish. The idea is to get those four wires inside the box connected to the appropriate power source - continuous 5V, engine on 5V, LCD brightness signal coming from the potentiometer, and ground. Step 5: I happened to have a suction cup from an old sat nav, which I wasn't using anymore. This will hold the whole box onto the windscreen of the car. The GPS module is attached using some self-adhesive velcro, with a small hole allowing the four wires (5v, ground, TX, RX) to go and connect inside the box. Step 6: And there it is, the final product located onto the dashboard, connected by the USB cable to the power supply and the potentiometer conveniently located beside the steering wheel (please note, I have a left hand driving car, the steering wheel is located therefore on the right hand side of the car) And you can watch it working here: Sorry for the video going in and out of focus - I was using a compact camera, with no option for a fixed focus. Step 7: Now for the code... First, you need to download two libraries (in case you don't have them already in your Arduino's library folder): 1. OpenGLCD -... (more information can be found here: and here) 2. TinyGPS - Unzip and copy them in your Arduino's library folder (normally C:\Program Files (x86)\Arduino\libraries\). If the Arduino IDE is open, you have to close and re-open it, to allow for the new libraries to be loaded. Step 8: Then I found it very awkward to generate new fonts (as high as the screen height) that will be displayed onto my LCD. Therefore what I did was to create bitmaps (numbers 0 to 9 plus a blank) that will be displayed on my LCD. After "installing" the openGLCD library, look for the file name called "glcdMakeBitmap.pde", normally located here C:\Program Files (x86)\Arduino\libraries\openGLCD\bitmaps\utils\glcdMakeBitmap\ EDIT - April 12th, 2016!!!! Added OpenGLCD library, which already has the .h (header) files. You need to copy and unzip where your Arduino IDE is located - normally C:\Program Files (x86)\Arduino\libraries\ EDIT - April 12th, 2016!!!! [ends] To run this file you will need to download and install an additional piece of free software, called Processing, which is very similar to Arduino IDE. EDIT - March 14th, 2016!!!! Thanks ab710 for pointing out that using some newer Processing versions will give an error while trying to run the code. Please use the link below to download Processing 2.2.1 which in my case allows for properly running of the code.?... () EDIT - March 14th, 2016!!!! [ends] Open "glcdMakeBitmap.pde" in Processing and click Run, in the top-left corner. The purpose of "glcdMakeBitmap.pde" application is to allow you to "feed" it with image files (gif, jpg, bmp, tga, png), and then some .h (header) files will automatically be created within the "bitmaps" folder of the openGLCD library. They will eventually be used to display your numbers (as images) onto the LCD. I have attached an archive file named "numbers.zip" which you can download, unzip, and then drag each one of those .BMP files onto the running "glcdMakeBitmap.pde" in order to create the 11 header files (0 to 9, plus blank). But if you wish, you can design your own numbers, using different fonts, save them as BMP or other supported image file extension, and use them to create the header files which will be displayed onto the LCD. PS. In case you're wondering why did I not upload the header (.h) files instead of the .BMP files, and save you the trouble of downloading and installing Processing, and running "glcdMakeBitmap.pde": It's not enough to simply copy the .h files into "bitmaps" folder, as the files named "allBitmaps.h" will be automatically updated as well (by the Processing application) to refer to the new files. Plus, in case you don't like my numbers, you now know how to create your own :-) Step 9: And finally the sketch, which is not very complicated, and should be self-explanatory. I have also attached the .ino sketch for your convenience. ******************************************************************** #include //math library to use for round function #include "TinyGPS.h" //GPS module library #include // LCD library TinyGPS gps; //create a gps object float fLat, fLong; //floats for longitude and latitude; will be used to determine whether the GPS data is up to date or not unsigned long fix_age; // returns +- latitude/longitude in degrees int digit1, digit2, digit3; //integers to hold the three digits making up the speed int iSpeed; //integer to hold the speed value from the GPS module void setup() { Serial.begin(9600); //start the serial communication // initialise the library, non inverted writes pixels onto a clear screen GLCD.Init(NON_INVERTED); } void loop() { while (Serial.available()) { //incoming serial data from GPS int c = Serial.read(); if (gps.encode(c)) { // process new gps info here, in case you want to display more details } } gps.f_get_position(&fLat, &fLong, &fix_age); //get longitude and latitude, used to find if data is up to date if (fix_age == TinyGPS::GPS_INVALID_AGE || fix_age > 2000) { //data was not updated for some time, assume that GPS connection is lost iSpeed = 0; } else { //GPS connection is up to date, get the speed information, and round it to closest integer value iSpeed = round(gps.f_speed_kmph()); // speed in km/h } //when not moving, the GPS module will still read some "speed" value, not necessarily zero //in that case assume the car is not moving; only display values greater than 2 if (iSpeed == 1) iSpeed = 0; displaySpeed(iSpeed); //call function to display the speed, digit by digit } void displaySpeed(int iSpeed) { //"simple" maths to extract each digit value digit1 = iSpeed / 100; iSpeed = iSpeed - (digit1 * 100); digit2 = iSpeed / 10; digit3 = iSpeed - (digit2 *10); //display "blank" bitmap when necessary, instead of number zero if (digit2 == 0 && digit1 == 0) digit2 = -1; //digit 2 is blank if (digit1 == 0) digit1 = -1; //digit 1 is blank //call function to display each digit, at their required position drawDigit(digit1, 0); drawDigit(digit2, 45); drawDigit(digit3, 90); } void drawDigit(int digit, int pos) { switch (digit) { case 0: GLCD.DrawBitmap(Number0, pos, 0); break; case 1: GLCD.DrawBitmap(Number1, pos, 0); break; case 2: GLCD.DrawBitmap(Number2, pos, 0); break; case 3: GLCD.DrawBitmap(Number3, pos, 0); break; case 4: GLCD.DrawBitmap(Number4, pos, 0); break; case 5: GLCD.DrawBitmap(Number5, pos, 0); break; case 6: GLCD.DrawBitmap(Number6, pos, 0); break; case 7: GLCD.DrawBitmap(Number7, pos, 0); break; case 8: GLCD.DrawBitmap(Number8, pos, 0); break; case 9: GLCD.DrawBitmap(Number9, pos, 0); break; default: GLCD.DrawBitmap(NumberBlank, pos, 0); break; } } Step 10: If you have any comments, questions or ideas, please let me know. And I hope you'll enjoy (as much as I did) building your own Arduino based GPS speedometer. Finished at last. I placed an LED on the front to show when I had a GPS signal. The two holes on the front were going to be for the pots, but they would have got in the way of the screen. great little project. Thanks for sharing. That's great, I'm glad that you found this useful. Hello, Good day. I badly need some help, hehe. my goal is to warn the driver of a vehicle with a voice message when the speed reached 80 km/hr, and also sends information like latitude and longitude via text message to a mobile phone. Initially, I did not put the voice alert function, just the text message function. There was no problem with the GPS module getting a fix information when it was connected to the Arduino UNO and GSM module, I did not use a library for the GSM module. It was working fine by then. The values from the GPS module are updated. But when I wired the mp3 player module and included the DFPlayer_Mini_Mp3.h library and its commands to my sketch, the voice alert was fine, the GSM module sends a message to my phone, but values from the GPS module is not updated, just zero values. ex. LAT: 000000, LONG: 000000. here is my sketch, i just badly need help right now, hehe: #include <TinyGPS++.h> #include <DFPlayer_Mini_Mp3.h> #include <SoftwareSerial.h> SoftwareSerial mySerialGPS(2, 3); SoftwareSerial mySerialGSM(7, 8); SoftwareSerial mySerial_mp3(10, 11); //Arduino pin 10 to DFPlayer TX, //Arduino pin 11 to DFPlayer RX TinyGPSPlus gps; void setup() { mySerialGSM.begin(2400); // Setting the baud rate of GSM Module mySerialGPS.begin(9600); mySerial_mp3.begin (9600); mp3_set_serial (mySerial_mp3); //set softwareSerial for DFPlayer-mini mp3 //module mp3_set_volume (15); SendMessage(); smartDelay(1000); } void loop() { if (gps.speed.kmph() > 80) { //play file 0080.mp3 mp3_play(80); smartDelay(3000); speed_alert_80(); smartDelay(1000); } pinMode(13, OUTPUT); digitalWrite(13, LOW); smartDelay(1000); } void speed_alert_80() { mySerialGSM.println(“AT+CMGF=1″); //Sets the GSM Module in Text Mode smartDelay(500); // Delay of 500 milli seconds or 1 second mySerialGSM.println(“AT+CMGS=\”+63xxxxxxxxxx\”\r”); // Replace x with mobile //number smartDelay(500); mySerialGSM.println(“Alert! there was a speed offender!”);// The SMS text you //want to send mySerialGSM.println(“The vehicle’s speed has reached 80 km/hr.”); mySerialGSM.print(“SPEED(kmph): “); mySerialGSM.println(gps.speed.kmph()); mySerialGSM.print(“LAT: “); mySerialGSM.println(gps.location.lat(),6); mySerialGSM.print(“LONG: “); mySerialGSM.println(gps.location.lng(),6); smartDelay(100); mySerialGSM.println((char)26);// ASCII code of CTRL+Z smartDelay(1000); } void SendMessage() { //play file 0101.mp3 mp3_play(101); smartDelay(2618); mySerialGSM.println(“AT+CMGF=1″); //Sets the GSM Module in Text Mode smartDelay(500); // Delay of 500 milli seconds or 1 second mySerialGSM.println(“AT+CMGS=\”+639487567571\”\r”); // Replace x with mobile //number smartDelay(500); mySerialGSM.println(“GPS module’s current state.\n”);// The SMS text you want //to send mySerialGSM.print(“LAT: “); mySerialGSM.println(gps.location.lat(),6); mySerialGSM.print(“LONG: “); mySerialGSM.println(gps.location.lng(),6); mySerialGSM.print(“DATE(ddmmyy): “); mySerialGSM.println(gps.date.value()); mySerialGSM.print(“SPEED(kmph): “); mySerialGSM.println(gps.speed.kmph()); mySerialGSM.print(“# of Sat. in use: “); mySerialGSM.println(gps.satellites.value()); smartDelay(100); mySerialGSM.println((char)26);// ASCII code of CTRL+Z smartDelay(1000); //play file 0102.mp3 mp3_play(102); smartDelay(3459); } static void smartDelay(unsigned long ms) { unsigned long start = millis(); do { while (mySerialGPS.available()) gps.encode(mySerialGPS.read()); } while (millis() – start < ms); } Hi, in your code you're only calling the function SendMessage() in the Setup, but not when a speed over 80 km/h was read. Try adding a call to SendMessage() within the body if (gps.speed.kmph() > 80) { .......................... } and see if that's working. I can't test it for real, for I don't have the necessary parts. PS. why are you calling the function SendMessage() in the Setup? Hello Studvio, thanks for the reply. yes i did not call SendMessage() within the body, but I did call speed_alert_80() within the body if (gps.speed.kmph() > 80) { //play file 0080.mp3 mp3_play(80); smartDelay(3000); speed_alert_80(); smartDelay(1000); } and for your question: why are you calling the function SendMessage() in the Setup? -- I just wanna check first at home if the system can get reliable values from the GPS module before testing it on the road. -- Initially, without the mp3 player module and the DFPlayer_Mini_Mp3.h library, every time I reset the arduino UNO, I receive a message like this: GPS module’s current state. LAT: 8.241666 LONG: 126.025932 DATE(ddmmyy): 151116 SPEED(kmph): 0.00 # of Sat. in use: 11 --but when I added the mp3 player module and its libary, its like this: LAT: 0.000000 LONG: 0.000000 DATE(ddmmyy): 000000 SPEED(kmph): 0.00 # of Sat. in use: 0 -- what do you think was the culprit? bmb, thanks in advance. Hi, yes, you are right about that call, I wasn't sure why you want to have the speed_alert_80() though. I know that you can not transmit data over the Software Serial to more than one device at a time. I also notice that you have the 3 second delay between sending data to the mp3 player module and sending data to the GSM module. I reckon that this could be the problem, whereas for some reason the communication is messed up somehow. Again, I don't have the required parts and I can not test it myself, but what I would suggest you to try: 1. Under if (gps.speed.kmph() > 80), comment out the call to play the file, mp3_play(80). You already mentioned that without the MP3 module it works properly, but I'm note sure whether you removed the whole library altogether, or you simply didn't make the call. Does it work now? I mean, the SMS text has all the data you need? 2. If the above is working now, try swapping the calls around like this if (gps.speed.kmph() > 80) { speed_alert_80(); smartDelay(3000); //play file 0080.mp3 mp3_play(80); smartDelay(3000); } so that you are sending the SMS first, and then play the MP3 file. (I see that you are doing that in this order in SendMessage(). Does the mp3 file plays the first time, when you reset the Arduino board?) If step 1 doesn't work, try also commenting the line SoftwareSerial mySerial_mp3(10, 11); but allow for the mp3 library to be included. If still doesn't work, then it may be that the DFPlayer_Mini_Mp3.h library is creating the problems. 3. Try something like if (mySerialGPS.available()) { speed_alert_80(); } I hope any of this helps, but let me know in either case please. Hello sir. I already got mine working just fine. hehe. thank you so much for your ideas. -- the culprit was this lines, particularly the order: mySerialGSM.begin(2400); mySerialGPS.begin(9600); mySerial_mp3.begin (9600); -- I changed it into this: mySerialGSM.begin(2400); mySerial_mp3.begin (9600); mySerialGPS.begin(9600); //the baud rate of the GPS module should //be set last. I dont no why but at least it //works for me. hehe -- do you have any idea why it worked properly in that order of setting baud rates? bmb, tnx in advance .. Hi! very nice project, but my LCD display is quite different from yours and does't work!! So.. it is possible having the project with the led display? I think is more easy and quite retro.. Hi there, in step one I've added the required .INO sketch. I hope it will work for you. Hi Studio, this is excellent. Thanks so much for sharing. I've rigged it up as a prototype and I can see the GPS is powered and receiving data (green LED is flashing). My display however is showing zero all the time. I've stripped the wiring out and redone it, but still the same result. I must be missing something with the unit. From the GPS, I'm not connecting the EN (yellow) and PPS (white) wires. I do not see them connected on the wiring diagram. Any ideas, friends? How are you? I am assuming that you are moving about with the prototype powered on, so that your speed would be higher than 2km/h. Then if at all possible, connect the stuff to a laptop / netbook, start the serial monitor and watch for incoming values from the GPS unit (iSpeed). You will need to add the necessary lines of code for that, of course, and use the Softserial method. Hi Studvio. It was a schoolboy error on my part: I hadn't stripped any extra insulation from the Rx and Tx on the GPS module. Once I did that, the data was passing into the Arduino. :o) I'll post a picture when it's all up and running. Take care :o) Hi, glad to hear that you were able to fix it, and thanks for your appreciation. Thanks, I'll give that a try :) Thank you very much.. It helped me alot Thanks for a well documented instructable. I saved $960 by making one of these. The speedo on our engine died, this was an awesome replacement. THANK YOU. Glad to hear that you managed to build one, and thanks for your kind comment. Installed and DONE! This vehicle is a backup, so it doesn't get used much. More for PR than anything. Because its not used much, the batteries have been dead a few times because flashlights, radios, and other tools are charging all the time. So I added a voltage divider to the 12v from the batteries of the fire engine to drop it down to a 5v input on pin A5. When the input value gets to 4v (10.5v on the engine, I tested to find that it won't start below 10.3) a REALLY annoying piezo buzzer goes off on pin 13. The only way to shut it up is to charge the batteries. This might be my favorite part. The other change I made was to use a photocell to drive the LED back light instead of a manual pot. The brighter the sun, the brighter the back light. The only issue I had was a night when it was dark.....no backlight. SO, I paralleled a 500 ohm resister to keep a minimal value for night time. It is has been working great. Finally, I pushed it all down on a mini Arduino pro. I jammed it all together, soldered a micro pot directly to the screen for contrast, used a few pieces of double sided tape, a 5v regulator.....and done! Again, thanks for sharing your code! That's fantastic! You're welcome (about the code), and thanks for your tips and improvements.! Hi, just confirming that you're using Arduino IDE version 1.6.5, Processing 2.2.1, and the correct GLCD library... as I understand these could potentially generate troubles. I have updated the tutorial and at step 8 I included the GLCD library I am using (again, an older version), which is working for me, and it already has the necessary header (.h) files. Please give it a try and let me know.! Hi, in this case I would reckon that some connections are loose. I had this exact problem myself, where I was able to adjust the contrast / brightness, but nothing was displayed. Are you using the correct values for the (trim) pots and the resistor? Also, make sure that your GLCD's pinout is the same as in my schematics, as there are different models that one can buy, and the pins' order might be slightly different. The GLCD library comes with a testing app that will display different info on the display. Try that as well, and see if the problem is in the GPS code or with the wiring. Awsome. Easy, good tutorial. Thanks Great project, been thinking of making something like this for a while now, and you saved me a lot of research with this instructable! Thanks for the nice work. Thank you so much sir....... you really helped me do it.....its such a nice project...:) :) Glad to hear that you've made it. Was the Arduino IDE at fault? Only asking so that other people might be aware of that, if such a case. Thanks for your appreciation and good luck with your future projects. yes sir, it was that i chose the new version of arduino ide and i downloaded wrong glcd library file actually it had to be openglcd library file...thanks for all the support you provided me sir.... exit status 1 'Number0' was not declared in this scope why am i getting this error in speedometrer.ino.....pls can u reply Hi, did you install the GLCD driver? And did you copy and unzipped the numbers.zip file attached, containing the Number0.bmp to Number9.bmp, plus NumberBlank.bmp? i have attached glcd to libraries of arduino........where shud i attach it other dan dat....pls can u reply sir... Hi, could you also confirm that you unzipped "numbers.zip", and that the .BMP files (letters from 0 to 9, plus a "blank") can also be found in your project folder, so that the code can access those? yes sir , i have done all those, numbes header file is created and processing is working but only problem im facing with simple code......... can i know which version of arduino ide have u used for running the code?.... sir one more doubt .........wat did u mean project folder ......where shud i attach the" numbers.zip" after unzipping it........please do reply sir.... Hi, you actually guessed what my next question would be, and that was in relation to Arduino IDE version. I am using v 1.6.5. And the BMP files should be located in the same folder as the INO project file. And as you can see in the attached images, the code is compiling without a problem. You can download v1.6.5 here, if you wish to give it a try () C:\Users\Megha Acharya\Downloads\speedometerLCD\speedometerLCD.ino: In function 'void drawDigit(int, int)': speedometerLCD:76: error: 'Number0' was not declared in this scope GLCD.DrawBitmap(Number0, pos, 0); this is the proper error im facing while compiling........ Hello, I am having issues with the glcdMakeBitmap code in processing. When I go to run the code, lines 197 through 239 all light up red and it displays an error that says "The constructor 'dnd.DropTarget(glcdMakeBitmap, DropTargetListener(){})' does not exist". I cant seem to get it to work, if you could get back to me with any tips that would be great. Thanks. Great project btw. Hi, I can confirm that I could "still" get it working on my PC (Windows7 64 bit). However, I was able to identify and hopefully solve your problem in running the code :-) I am running Processing version 2.2.1, and as I said - no problems with running the code. I went to the link I provided in my original post (which should be updated by the time you are reading this) and I downloaded the latest version of Processing, version 3.0.2. When trying to run the same code the error message you mentioned is there. So I could advise to get Processing 2.2.1 for your operating system (I tried newer versions, but they output the same error message), and see whether it's working. A list of Processing releases are to be found at this link?... () PS. To quote from the link above for the latest version, PROCESSING 3.0.2 (REV 0248) - 13 February 2016: "Nothing says "I LOVE YOU" like a bouquet of bug fixes." They've "fixed" it all right :-) It works now. Thanks! Thats a very nice project, just want to ask would it be possible to put a tattle-tail function on it, a button that tell you the highest speed for the day. Thought it might be useful for when someone borrows my car, as they got a speeding ticket but they swear they weren't speeding.... I never thought of that option to be honest with you (I'm the only person driving my car hopefuly), but I'm sure it can be done, and I'm thinking of two options: 1. Adding a variable in the code that will hold the highest speed value. Two buttons - one to display hgat value, and the other to reset it. Of course, you will have to power the Arduino all the time for the value to be remembered. (In my project, the power is disconnected when the engine is swithed off). 2. Adding a SD card slot, and saving in a file - let's say every 2 seconds - the current speed value. You won't need any extra buttons for this, as you can remove the SD card from the slot for reading the file externally. The Arduino won't have to be powered all the time in this case, although you should make sure that the file on the card doesn't get corrupted due to lost of power during the writing process. You could also add a RTC (real time clock) module and save the current time / date as well along with the speed value on the CD card. You will need to add at least one button in this case allowing you to adjust the time / date, if such a case. Or option 3... You could get a dashcam and position it in a way that it records the road ahead and the speedometer on the dashboard of the car at the same time. I know I'm doing this :-), so that I keep the speedometer as small and simple as possible. Thanks that sounds cool, It was my wife that got the speeding ticket an Im pretty sure she wasn't speeding as she was in a long line of cars all doing the same speed. It would of been good to tell the cop, my GPS speedo says no I wasn't speeding. Not sure whether you could use this Arduino project as evidence in any court, but at least you can have some fun :-) Good evening sir, is the GPS module you have used also good and accurate in obtaining location and velocity of any vehicle anywhere in the Philippines? I badly need some help for my final project, because i'm an ECE student here in our country, thanks a lot. Hi, the module will provide such information if needed. Please have a look at the sample code here... () on how to get the longitude and latititude, no matter where you're on the Globe. As for accuracy, I can only say that the speed it returns is very accurate (as per my project above); I don't know about the positioning (lat, long), but I assume that would be accurate as well. Nice project, I saw that you make the speedometer with a led display in a breadboard and I also want to make it with a led display because I want to put it in a karting, and I want to make it as small as possible so can you share me the code. Regards, Tomas Mercado. Here is my email: tomas.mercado07@gmail.com Hi Tomas, I sent you the code by email, I hope it will work for you. Very nice idea and well done. Only tweak I could see doing would be to use an illuminated display and display upside down so that the display could be laid flat on the dashboard and would show up as a heads up display when reflected off the inside surface of the windshield. My initial idea was actually something similar to this, using some kind of laser projector, like the ones found in projection clocks, to display the speed onto the windshield. However I am not so sure how that would be visible during daylight or with direct sunlight. You will find that a dark and light display will reflect fairly clearly off the winshield and illuminated against dark will show up very well after dark. You will likely have to dim the illumination to maintain good visibility through the windshield.
http://www.instructables.com/id/Arduino-GPS-speedometer-with-a-ks0108-128x64-GLCD-/
CC-MAIN-2017-30
refinedweb
5,609
73.17
Building High Performance HTML Pages Note As of December 2011, this topic has been archived and is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Windows Internet Explorer, see Internet Explorer Developer Center.. - Reuse HTML Components and External Scripts - DEFER Your Scripts - Author Hyperlinks Consistently - Use Fixed-Size Tables - Optimize Your Scripts - Scope Your Object References Wisely - Close Your Tags - Use the HTTP Expires Header - Use Cache-Control Extensions - Related topics Reuse HTML Components and External Scripts Microsoft Internet Explorer 3.02. By using this feature, the client only has to download the .js file the first time a page containing a reference to that .js file is requested. When. Dynamic HTML (DHTML) behaviors, introduced in Microsoft Internet Explorer 5, are the next logical step in the direction of code reuse. Like .js files, Dynamic HTML : By designing behaviors carefully to capture events and associating those behaviors with elements using the STYLE and CLASS attributes, it is possible to enhance the user experience safely and efficiently. For more information, see Using HTML Components to Implement DHTML Behaviors in Script. DEFER Your Scripts are typically executed immediately as the page is loading. In addition, you shouldn't defer any global variables or functions that are accessed by immediately executing script. Author Hyperlinks Consistently The Internet Explorer cache is case-sensitive. That means that you should author your hyperlinks with case-sensitivity in mind. Take the following example.. Use Fixed-Size Tables CSS attribute to achieve optimal performance out of Internet Explorer 5 or later. By doing the following, you'll allow Internet Explorer to start rendering the table before it has received all the data. - Set the table-layout CSS attribute to fixed on the table. - Explicitly define col objects for each column. - Set the WIDTH attribute on each col. See Enhancing Table Presentation for more information on this feature. Optimize Your Scripts Not enough can be said about writing solid code regardless of the platform or language. When targeting Internet Explorer 4.0 or later, a thorough understanding of the features provided by the Dynamic HTML : What's wrong with the previous code? The code contains three calls through the all collection of the document. During each iteration through the loop, the scripting engine will: - Get the length of the collection. - Get the tagName of the current object in the collection. - Get the innerText of the current object in the collection. That's not particularly efficient. The overhead amounts to numerous unnecessary calls to the DHTML Object Model for information that we already know about. Here's version two: This version assumes the overhead of creating two local variables to cache the all collection as well as the length of that collection. We can do better: Using the tags method of the all collection puts the burden on the DHTML Object Model to do the filtering and allows for the elimination of the if condition on every iteration of the scripted loop. Note Beware the ramifications of caching DHTML collections. DHTML collections are truly dynamic, and any code you author that creates new elements and inserts them into the document may cause the collection to grow or shrink. Scope Your Object References Wisely JScript and VBScript are interpreted languages. Because all the work is done at execution time, relative to compiled languages, these languages are slow. Within a script, every reference to an object amounts to two calls from the scripting engine to the DHTML Object Model. For those unfamiliar with or interested in the intimate details of Automation, refer to the documentation on IDispatch::GetIDsOfNames and IDispatch::Invoke in the Microsoft Platform software development kit (SDK). The following example defines a div with an ID of div1. When Internet Explorer parses a page it accounts for all the objects on the page for which ID attributes have been explicitly specified. It adds them to the global namespace of the scripting engine, allowing you to refer to them directly. That means that the following is excessive. In addition to the extra bytes that are passed across the network and parsed by the scripting engine, four extra calls are made by the script engine back to Internet Explorer in order to retrieve the innerText property of the div. The following is all that's required to retrieve the innerText of the div. Notable exceptions to this minimalist approach include the following: - Accessing elements contained within a form. - Accessing properties of an iframe. - Accessing properties of the window object. Elements contained within a form are hidden within the form's namespace. For example: For cross-frame security reasons, iframe properties must be fully scoped as shown in the following example. When a scripting engine encounters a scoped object model reference in your code, the engine needs to resolve the reference by looking up the left-most piece of that reference in a look-up table. Two factors influence the scripting engine's ability to perform the look-up: - The number of entries in the look-up table. - The scope of the reference. The number of entries in the table corresponds to the number of global variables, named objects, and functions that you have defined on your page. Thus, you should only declare the ID attribute on those elements that you explicitly wish to manipulate through script. As mentioned above, there's a right way and a wrong way to scope references. When you've assigned an ID attribute to an element, there's no reason to access the corresponding object through document.all. Armed with this information, you might think that you should minimize your object model references in all cases. Let's look at another common example where this rule doesn't apply: The code works. It stores the HTTP_USER_AGENT string in the variable sUA. In order for the scripting engine to resolve this reference, however, it first attempts to find an object named navigator in the global look-up table. After looking through the entire table and not finding such a named item, the engine has to walk through the table again asking each of the global objects if it supports the navigator object. When it finally encounters the global window object, the object that exposes the navigator property, it can then retrieve the userAgent property. A better way to handle this situation, especially on a page containing many globally named items, is to fully scope the reference as follows: If all this talk about look-up tables and global objects has your head spinning, just remember this simple rule: fully scope your references to members of the window object. A list of these members is provided in the DHTML Reference. Close Your Tags. But the following will be parsed more quickly because it is well-formed and Internet Explorer doesn't need to look ahead to decide where the paragraph or list items end. Use—including Internet Explorer 4.0. For more information on the expires header see RFC2068: Hypertext Transfer Protocol -- HTTP/1.1. For specific information on how to specify the expires header for a resource on your HTTP server, see your HTTP server documentation. Use Cache-Control Extensions: - post-check - Defines an interval in seconds after which an entity must be checked for freshness. The check may happen after the user is shown the resource but ensures that on the next roundtrip the cached copy will be up-to-date. - pre-check - Defines an interval in seconds after which an entity must be checked for freshness prior to showing the user the resource.. - If the post-check interval has not yet elapsed, simply retrieve the page from the cache. - If the elapsed time since the last request is between the post-check and the pre-check intervals, display the page from the cache, and in the background, ask the HTTP server if the page has been modified since it was last requested by the browser. If the page has been modified, fetch the updated page and store it in the cache. - If the pre-check interval has elapsed by the time the user next requests the page, first ask the HTTP server if the page has been modified since it was last requested by the browser. If the page has been modified, fetch and display the updated page.. Try this: - On a machine running Microsoft Internet Information Server (IIS) 4.0 or later, create a file containing the following content. This feature is language-independent and works in both JScript and VBScript. - Save the content to a file, call it check.pl, in a directory in which Internet Information Server has permissions to execute scripts. - Launch Internet Explorer 5, and load the page using the HTTP protocol. You should see the string "Hello, world!" render in the browser. Close the browser. - On the server, modify the .asp file by changing the content contained within the H1 to "Adios, mundo!". Save the file. - Relaunch the browser, and reenter the URL corresponding to the .asp file. When the page renders, you should see the original text, "Hello, world!". - Two minutes after having first retrieved the file you should still see the same content. The next time you load the page, however, Internet Explorer will have downloaded the page in the background, and you will see the updates. If four minutes had passed since you last requested the page, Internet Explorer would have sent an if-modified-since request to the server and, upon receiving a response that the page had changed, would have fetched the latest version and would have rendered it in the browser.. Related topics
http://msdn.microsoft.com/en-us/library/ie/ms533020(v=vs.85).aspx
CC-MAIN-2014-52
refinedweb
1,611
54.63
I used local galaxy to run data. However I deleted the current library. but I think this still occupied my disk volume. I want to clean them totally, how I can do it? Thank you very much in advance! I used local galaxy to run data. However I deleted the current library. but I think this still occupied my disk volume. I want to clean them totally, how I can do it? Thank you very much in advance! Hi, please have a look at the following script: python ./scripts/cleanup_datasets/cleanup_datasets.py --help Hope this helps, Bjoern Hi Bjoern, First I added the following sentences in cleanup_datasets.py from" ./ scripts/cleanup_datasets/cleanup_datasets.py" GALAXY_LIB="/Users/biowzmailustceducn/galaxy/lib" if [ "$GALAXY_LIB" != "/Users/biowzmailustceducn/galaxy/lib" ]: then if [ -n "$PYTHONPATH" ]: then export PYTHONPATH="$GALAXY_LIB:$PYTHONPATH" else export PYTHONPATH="$GALAXY_LIB" fi fi And next python /Users/biowzmailustceducn/galaxy/scripts/cleanup_datasets/cleanup_datasets.py The error occurs as following File "/Users/biowzmailustceducn/galaxy/scripts/cleanup_datasets/cleanup_datasets.py", line 6 if [ -n "$PYTHONPATH" ]: then ^ IndentationError: unexpected indent Would you like to help me solve this problem? Thank you very much for your help! Best wishes Hil Why do you need this? If I just run this code, the errors like this as following: Traceback (most recent call last): File "/Users/biowzmailustceducn/galaxy/scripts/cleanup_datasets/cleanup_datasets.py", line 14, in <module> from galaxy import eggs ImportError: No module named galaxy Would you like to help us about this? Are you running it inside your galaxy root dir? Thank you very much! I pasted this file under galaxy root dir, but I met another question,as follow: Traceback (most recent call last): File "./cleanup_datasets.py", line 531, in <module> if __name__ == "__main__": main() File "./cleanup_datasets.py", line 101, in main for key, value in config_parser.items( "app:main" ): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 642, in items raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'app:main'
https://biostar.usegalaxy.org/p/13878/
CC-MAIN-2021-21
refinedweb
327
61.63
[AdWords API] Keyword Search Volume fetching -- 2 Budget $50-100 USD What I need is a function or class that connects with the AdWords API and retrieves exact search volume for a specific keyword, optionally in a specific country or language(Japan/Japanese). It should do the same thing what this tool does: [url removed, login to view] For example, I have a list of 10 keywords in PHP, I would like to be able to call a function with optional parameters for country and language that will return (a list of) volume value(s) for the keyword. It should return the exact volume (option in the tool as well). *v201409 of the AdWords API is required to use. *It should return AVERAGE search volume in Japan. I have MCC and access token key for adwords api. Application will _only_ be taken into account if you provide the following information with your application: - API documentation pages / API functions you will be using for the script. Do provide this information, as it will prove that you researched the topic before applying. In case of questions, don't hesitate to contact me. 5 freelancers are bidding on average $151 for this job I can do this project perfectly. I have experience in this field from long time. I will be waiting for your positive reply thanks.
https://www.freelancer.com.au/projects/php/adwords-api-keyword-search-volume/
CC-MAIN-2019-39
refinedweb
224
61.36
On Tue, Jun 22, 2010 at 10:57:08PM +0100, M?ns Rullg?rd wrote: > Michael Niedermayer <michaelni at gmx.at> writes: > > > On Tue, Jun 22, 2010 at 09:46:35PM +0100, M?ns Rullg?rd wrote: > >> Michael Niedermayer <michaelni at gmx.at> writes: [...] > >> >> Index: libavcodec/h264.h > >> >> =================================================================== > >> >> --- libavcodec/h264.h (revision 23459) > >> >> +++ libavcodec/h264.h (working copy) > >> >> @@ -735,22 +735,6 @@ > >> >> 1+5*8, 2+5*8, > >> >> }; > >> >> > >> >> -static av_always_inline uint32_t pack16to32(int a, int b){ > >> >> -#if HAVE_BIGENDIAN > >> >> - return (b&0xFFFF) + (a<<16); > >> >> -#else > >> >> - return (a&0xFFFF) + (b<<16); > >> >> -#endif > >> >> -} > >> >> - > >> >> -static av_always_inline uint16_t pack8to16(int a, int b){ > >> >> -#if HAVE_BIGENDIAN > >> >> - return (b&0xFF) + (a<<8); > >> >> -#else > >> >> - return (a&0xFF) + (b<<8); > >> >> -#endif > >> >> -} > >> >> - > >> > > >> > moving these or anything else to a common place is ok of course > >> > >> I suggest alongside the 8x4 Ronald added today. > > > > just keep track which of these work with negative numbers and which not > > Maybe we should have one of each to avoid needless masking: > > PACK_2S8 > PACK_2U8 > PACK_4S8 > PACK_4U8 > PACK_2S16 > PACK_2U16 fine with: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2010-June/092216.html
CC-MAIN-2017-04
refinedweb
165
60.65
The purpose of this section is to review and recall the basic terms in the measurement of returns and statistics which are used in valuations. Net Present Value (NPV) NPV is the sum of all discounted flows (both positive and negative) from a project. NPV is used as a gauge for measuring the advisability of an investment; an investment is only worthwhile if NPV>0. Example: We are contemplating investing $100 in the present (C0) and expect the investment to yield (Cn) $110 one year from now (n=1). We shall assume that the investment is "risky" and that the appropriate interest rate (k) is therefore 15%. Inserting these values in the formula reveals a negative NPV i.e., the investment is not worthwhile. NPV = (-100) + 110/ (1 + 15%) = -4.348 NPV = (-100) + 110/ (1 + 15%) = -4.348 Rate of return The rate of return on an investment is the profit or loss made on the investment over the period of the investment, as a percentage of the initial amount invested. The rate of return is measured by dividing the sum of the cash flows (both positive and negative) by the amount of the investment. The rule is that an investment is worthwhile only when y>k, i.e., when the rate of return on the investment (y) is greater than the market return on such investment (k). y = (C0 + Cn)/-C0 y = (C0 + Cn)/-C0 In the case of an initial investment (C0) of $100 and a return (Cn) of $110, the rate of return is: y = (-100 + 110)/100 = 10% y = (-100 + 110)/100 = 10% If the appropriate interest rate (k) for an investment with such a risk profile is 15%, then the investment is not worthwhile. Internal Rate of Return (IRR) IRR is defined as the discount rate at which the NPV of the investment is zero. IRR = (Cn/C0)1/n - 1 IRR = (Cn/C0)1/n - 1 For example, in an investment of $100 now which is expected to yield $200 five years from now (n=5), IRR = (200/100)1/5 - 1 = 14.9% IRR = (200/100)1/5 - 1 = 14.9%
https://flylib.com/books/en/2.488.1.69/1/
CC-MAIN-2018-22
refinedweb
358
68.6
(* Find recently modified entries in the Address Book Input: a time interval (backwards from today) in the variable "daysBeforeToday" Output: a string on the clipboard, format: YYYY-MM-DD (tab) Name (return) ©2009, Michael Bach, <> *) set daysBeforeToday to 7 -- <<< change as desired or read from a dialog tell application "Address Book" copy (current date) - daysBeforeToday * 24 * minutes * 60 to referenceDate copy (every person whose (modification date > referenceDate)) to modifiedPersons set s to "" repeat with aPerson in modifiedPersons set d to ((modification date) of aPerson) -- now change to international format and forget the hours set dateString to (year of d as string) & "-" & (my twoDigits((month of d) as number)) & "-" & (my twoDigits(day of d) as string) set s to s & dateString & tab & (name of aPerson) & return end repeat set the clipboard to s --for pasting into other applications s -- to view immediately in the script editor end tell on twoDigits(aNumber) -- trivial utility for formatting if aNumber < 10 then return "0" & (aNumber as string) return (aNumber as string) end twoDigits I may be missing something here, but can't you use a smart group to pick up all of the contacts that have changed in the last day? Michael, Why not just make a group called 'Family'? then, in Mail, in the 'To' field, simply type 'Family' and all of the email addresses spring right on over. Very clean. I use project numbers and do this for all my client contacts. I agree. Using smart groups is probably the tool to solve that issue. Generally, there are usually ways to do what you want to do that you may not be familiar with. The nice thing is that once you learn it for address book, you'll learn it for other apps at the same time because most everything is designed using the same organizational and functional concepts. However, I agree, more export options would be nice. I'd like to generate a tab-delimited file. I've done this before, but using some perl hacking. However, one tip to discover more hidden "export" options is to hit print, which allows you to "export" to PDF. The format is somewhat customizable. Yes, I believe you can just use a smart group--I just did it myself. I didn't know this was possible. Smart Group in Address Book works for me... Card : has changed in : 7 : days I'm curious about these "limitations". I've only ever used Address Book. What functionality/features am I missing out on? What I'd like is a smart folder, or at least a script to figure out which ones of my contacts have a picture. Nicer still - which one have a large iPhone picture and which ones have the small icon. --this returns the names of people who don't have pix... tell application "Address Book" to return name of people whose image is missing value --this returns the names of people who do have pix... tell application "Address Book" to return name of people whose image is not missing value Hope this helps! If. Visit other IDG sites:
http://hints.macworld.com/article.php?story=20090218052324712
CC-MAIN-2016-50
refinedweb
515
67.28
2018-03-05 Announcing Dotty 0.6.0 and 0.7.0-RC1 Today, we are excited to release Dotty versions 0.6.0 and 0.7.0-RC1. These releases serve as a technology preview that demonstrates new language features and the compiler supporting them. If you’re not familiar with Dotty, it's a platform to try out new language concepts and compiler technologies for Scala. The focus is mainly on simplification. We remove extraneous syntax (e.g. no XML literals), and try to boil down Scala’s types into a smaller set of more fundamental constructs. The theory behind these constructs is researched in DOT, a calculus for dependent object types. You can learn more about Dotty on our website. This is our seventh scheduled release according to our 6-week release schedule. The previous technology preview focussed on bug fixes and stability work. What’s new in the 0.7.0-RC1 technology preview? Enum Simplification #4003 The previously introduced syntax and rules for enum were arguably too complex. We can considerably simplify them by taking away one capability: that cases can have bodies which can define members. Arguably, if we choose an ADT decomposition of a problem, it's good style to write all methods using pattern matching instead of overriding individual cases. So this removes an unnecessary choice. We now treat enums unequivocally as classes. They can have methods and other statements just like other classes can. Cases in enums are seen as a form of constructors. We do not need a distinction between enum class and enum object anymore. Enums can have companion objects just like normal classes can, of course. Let's consider how Option can be represented as an enum. Previously using an enum class: enum class Option[+T] { def isDefined: Boolean } object Option { case Some[+T](x: T) { def isDefined = true } case None { def isDefined = false } def apply[T](x: T): Option[T] = if (x == null) None else Some(x) } And now: enum Option[+T] { case Some(x: T) case None def isDefined: Boolean = this match { case None => false case Some(_) => true } } object Option { def apply[T](x: T): Option[T] = if (x == null) None else Some(x) } For more information about Enumerations and how to use them to model Algebraic Data Types, visit the respective sections in our documentation. Erased terms #3342 The erased modifier can be used on parameters, val and def to enforce that no reference to those terms is ever used. As they are never used, they can safely be removed during compilation. One particular use case is to add implicit type constraints that are only relevant at compilation time. For example, let's consider the following implementation of flatten. class List[X] { def flatten[Y](implicit erased ev: X <:< List[Y]): List[Y] = { val buffer = new mutable.ListBuffer[Y] this.foreach(e => buffer ++= e.asInstanceOf[List[Y]]) buffer.toList } } List(List(1, 2), List(3)).flatten // List(1, 2, 3) List(1, 2, 3).flatten // error: Cannot prove that Int <:< List[Y] The implicit evidence ev is only used to constrain the type parameter X of List such that we can safely cast from X to List[_]. The usage of the erased modifier ensures that the evidence is not used and can be safely removed at compilation time. For more information, visit the Erased Terms section of our documentation. Note: Erased terms replace phantom types: they have similar semantics, but with the added advantage that any type can be an erased parameter. See #3410. Improved IDE support #3960 The Dotty language server now supports context sensitive IDE completions. Completions now include local and imported definitions. Members completions take possible implicit conversions into account. We also improved the find references functionality. It is more robust and much faster! Try it out in Visual Studio Code! Better and safer types in pattern matching (improved GADT support) Consider the following implementation of an evaluator for a very simple language containing only integer literals ( Lit) and pairs ( Pair): sealed trait Exp case class Lit(value: Int) extends Exp case class Pair(fst: Exp, snd: Exp) extends Exp object Evaluator { def eval(e: Exp): Any = e match { case Lit(x) => x case Pair(a, b) => (eval(a), eval(b)) } eval(Lit(1)) // 1: Any eval(Pair(Pair(Lit(1), Lit(2)), Lit(3))) // ((1, 2), 3) : Any } This code is correct but it's not very type-safe since eval returns a value of type Any, we can do better by adding a type parameter to Exp that represents the result type of evaluating the expression: sealed trait Exp[T] case class Lit(value: Int) extends Exp[Int] case class Pair[A, B](fst: Exp[A], snd: Exp[B]) extends Exp[(A, B)] object Evaluator { def eval[T](e: Exp[T]): T = e match { case Lit(x) => // In this case, T = Int x case Pair(a, b) => // In this case, T = (A, B) where A is the type of a and B is the type of b (eval(a), eval(b)) } eval(Lit(1)) // 1: Int eval(Pair(Pair(Lit(1), Lit(2)), Lit(3))) // ((1, 2), 3) : ((Int, Int), Int) } Now the expression Pair(Pair(Lit(1), Lit(2)), Lit(3))) has type Exp[((Int, Int), Int)] and calling eval on it will return a value of type ((Int, Int), Int) instead of Any. Something subtle is going on in the definition of eval here: its result type is T which is a type parameter that could be instantiated to anything, and yet in the Lit case we are able to return a value of type Int, and in the Pair case a value of a tuple type. In each case the typechecker has been able to constrain the type of T through unification (e.g. if e matches Lit(x) then Lit is a subtype of Exp[T], so T must be equal to Int). This is usually referred to as GADT support in Scala since it closely mirrors the behavior of Generalized Algebraic Data Types in Haskell and other languages. GADTs have been a part of Scala for a long time, but in Dotty 0.7.0-RC1 we significantly improved their implementation to catch more issues at compile-time. For example, writing (eval(a), eval(a)) instead of (eval(a), eval(b)) in the example above should be an error, but it was not caught by Scala 2 or previous versions of Dotty, whereas we now get a type mismatch error as expected. More work remains to be done to fix the remaining GADT-related issues, but so far no show-stopper has been found. Trying out Dotty Scastie Scastie, the online Scala playground, supports Dotty. This is an easy way to try Dotty without installing anything. sbt Using sbt 0.13.13 or newer, do: sbt new lampepfl/dotty.g8 This will setup a new sbt project with Dotty as compiler. For more details on using Dotty with sbt, see the example project. IDE support It is very easy to.6.0..0.7.0-RC1 these are: 182 Martin Odersky 94 Nicolas Stucki 48 Olivier Blanvillain 38 liu fengyun 16 Allan Renucci 15 Guillaume Martres 11 Aggelos Biboudis 5 Abel Nieto 5 Paolo G. Giarrusso 4 Fengyun Liu 2 Georg Schmid 1 Jonathan Skowera 1 Fedor Shiriaev 1 Alexander Slesarenko 1 benkobalog 1 Jimin Hsieh.
http://dotty.epfl.ch/blog/2018/03/05/seventh-dotty-milestone-release.html
CC-MAIN-2019-04
refinedweb
1,233
61.87
Solaris, the actual name for the library file on disk is libmyRenderingLib.so . Here torun Java 2 SDK. Solaris, against the jre/lib/sparc/libjawt.so library. (For Windows, link against the jre/bin/jawt.dll library.) Solaris X11-based drawing environment and a Java VM where the AWT Native Interface is present:/* * Copyright 1999 Sun Microsystems, Inc., * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * */ _1_3; Solar Windows platform would be structured similarly, but would include the version of jawt_md.h for Windows 32 and the structure located in the platformInfo field of drawing surface info would be cast as a JAWT_Win32DrawingSurfaceInfo* . And, of course, the actual drawing operations would need to be changed to those appropriate for the Windows platform.. */ /* * Win32 and Solaris support the existing structures in jawt_md.h. * ******************* * EXAMPLE OF USAGE: ******************* * * In Win32, Windows or a * JAWT_X11DrawingSurfaceInfo on Solaris.() */ jint version; /* * Return a drawing surface from a target jobject. This value * may be cached. * Returns NULL if an error has occurred. * Target must be a java.awt.Canvas. *); } #include (Windows 32 "jawt.h" #ifdef __cplusplus extern "C" { #endif /* * Win32_ */
http://java.sun.com/j2se/1.3/docs/guide/awt/AWT_Native_Interface.html
crawl-002
refinedweb
189
61.73
If. public class CalculatorTester { public void TestAdd() { var calculator = new Calculator(); if (calculator.Add(2, 2) == 4) Console.WriteLine("Success"); else Console.WriteLine("Failure"); } }. What Are Unit Test Frameworks? Well, as you can imagine, having this sort of unit testing across your entire codebase could prove cumbersome. You’d write lots of classes just like this one and then… what? You’d look at all of the console output for failures, only to discover that failure proved pretty inscrutable. Most likely you would then have the clever idea to include the name of the test in the output so that you could see what had failed. From there, you might start to add some sort of GUI-like feedback to the results, to present them in a more readable fashion. From there, who knows? Maybe you write a Visual Studio plugin or maybe you find a way to incorporate this test suite into your build? Well, it turns out that if you did all that stuff, you would have built yourself a unit testing framework. Let’s take a look now at what some code written for an actual unit test framework (MS Test) looks like. [TestClass] public class CalculatorTests { [TestMethod] public void TestMethod1() { var calculator = new Calculator(); Assert.AreEqual(4, calculator.Add(2, 2)); } } Unlike the last snippet, we have a bit of magic here. Notice the attributes, TestClass and TestMethod. Those exist simply to tell the unit test framework to pay attention to them when executing the unit test suite. When you want to get results, you invoke the unit test runner, and it executes all methods decorated like this, compiling the results into a visually pleasing report that you can view. So, with that background established, let’s take a look at your top 3 unit test framework options for C#. 1. MSTest/Visual Studio First, since I’ve already mentioned it, I’ll lead with MSTest. MSTest was actually the name of a command line tool for executing tests, so we’re really talking about something called the “Visual Studio Unit Testing Framework.” But veterans will colloquially call it MSTest, so let’s use that here. MSTest ships with Visual Studio, so you have it right out of the box, in your IDE, without doing anything. This lack of friction to getting started is arguably its killer feature. The preferred .NET pattern for unit tests is to have a test project for each production (regular) project in your codebase. With MSTest, getting that setup is as easy as File->New Project. Then, when you write a test, you can right click on it and execute, having your result displayed in the IDE. Pretty neat, huh? And you can also see code coverage without installing any other tools. On the con side, one of the most frequent knocks on MSTest is that of performance. People find the experience can be sluggish. On top of that, many people struggle with interoperability. After all, Microsoft makes it so you can integrate with other Microsoft/Visual Studio stuff, so making it work with third party things would probably not rate as a priority. 2. NUnit Next up, I’ll talk about NUnit. Unit test frameworks have a history dating back almost 30 years, so they long predated .NET. NUnit started out as a port from Java’s JUnit, but the authors eventually redid it to be more C# idiomatic. So the tool has the rich history of unit testing behind it, but with an appropriately C# flavor. Because of its independent history, NUnit also has the distinction of interoperating nicely with other tools, such as non-Microsoft build platforms and custom test runners. On top of that, NUnit also has a reputation for fast testing running, and it has some nice additional features as well, including test annotations allowing easy specification of multiple inputs to a given test. The main downside here is that it doesn’t integrate into Visual Studio the way that MSTest does. Using it means doing extra work, and installing extra tools, regardless of how easy those tools’ authors may make the process. 3. xUnit.NET The last option that I’ll cover is xUnit.NET (I’ll just call it xUnit for brevity, not to be confused with the xUnit category of test tools). One of the creators of the idiomatic version of NUnit went on to create xUnit. xUnit has a relatively innovative for users to reason about their tests, dividing tests into “facts” and “theories” to distinguish between “always true” and “true for the right data,” respectively. xUnit earns points for creating extremely intuitive terminology and ways to reason about the language of tests. On top of that, the tool has a reputation for excellent extensibility. Another awesome feature of xUnit is actually not a feature of the software, but a feature of the authors. They have a reputation for commitment, responsiveness, and evangelism. On the con side, some users seem to wish the tool had more documentation. Beyond that, the community seems pretty enthusiastic and it’s hard to find a lot of detractors. This may speak to an implicit con, however. It has a small but loyal core of users because it requires a different way of thinking about some things and perhaps a bit more learning. Just Get Started I’ll close here by stating something emphatically. If you’re looking to start your unit testing journey, do NOT get bogged down in trying to pick one of these frameworks. Just pick one — roll some dice, flip a few coins — whatever. They have their pros and cons, their detractors and supporters. But every one of them is better, by far, than continuing not to write unit tests. You can always re-evaluate and switch later if you need to. I’ve used a lot of different unit test frameworks in my career and never felt locked in or concerned about it. So get started as quickly as you can. And before you know it, you’ll suffer the curse of knowledge with unit testing and not be able to conceive of someone not versed in the pros and cons of their favorite unit testing framework. -
https://stackify.com/unit-test-frameworks-csharp/
CC-MAIN-2018-09
refinedweb
1,035
63.59
On Oct 12, 2006, at 1:42 PM, Derk-Jan Hartman wrote: > >. Thanks Derk, I had figured that out. My code allows you to specify if you want to precede it with length bytes (then it will fill in the extradata with avcc block), or start sequence (in which case it will fill it in with sps/pps). This appears to work currently. It's interesting though, as I was not filling SPS/PPS nals with 0001, only 001.? > [...] >> I'm also having to get the rtsp rtcp packet (receiver reports) >> working, because that's why the server is cutting me off after two >> minutes. > > great I have this working, but I can't send on the url_port. I was opening it RDWR (I changed it back for the patches), and it was still giving me the -2 error. Something must be closing the connection, or they must be half open (for tcp)... >> Finally, I can give a Blocksize parameter to the server on RTSP >> initial handshake. With this, I could specify a maximum packet size, >> which would allow me to preallocate all of my internal packets (using >> around 2k buffers each, since MTU is 1500 by default). This would >> basically mean that there would be initial memory allocation for >> packets until I had enough in the packet pool, and I could retire >> them to another linked list and pull them from there. So there would >> be no malloc's after an initial startup period. I think this would >> be a good thing, but I'm not sure how the rest of FFMPEG feels about >> memory allocation. Is this a better approach? > > yes, less *malloc() and *free() is better This is not done yet; but I still plan on doing it. >> >> /* ---------------- code */ >> void *new_h264_extradata() > > non static functions need some av_ or ff_ prefix to avoid namespace > clashes All my functions are static (and made available through a parameter block). I tried to keep the other naming conventions the same for other visible functions (rtsp_ or rtp_ if I had to add some for those). I'm not happy with rtsp_get_word and rtsp_get_word_sep, but i needed them in two places.. >> >> // fprintf(stderr, "Buf: %p Length: %d\n", buf, len); > > this should be av_log or removed (and that of course applies to all > these > // *printf lines I left a few fprintf's in, but they are all commented out. this was just since it's still a work in progress. (old habits) >. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: patch.txt URL: <> -------------- next part -------------- A non-text attachment was scrubbed... Name: rtp_h264.c Type: application/octet-stream Size: 39493 bytes Desc: not available URL: <> -------------- next part -------------- A non-text attachment was scrubbed... Name: rtp_h264.h Type: application/octet-stream Size: 955 bytes Desc: not available URL: <> -------------- next part -------------- A non-text attachment was scrubbed... Name: rtp_internal.h Type: application/octet-stream Size: 4438 bytes Desc: not available URL: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2006-October/018187.html
CC-MAIN-2017-30
refinedweb
490
70.43
Sven K=C3=B6hler <skoehler@...> writes: > > The 2.6.0 UML patch is available at > > >=20 > Disable CONFIG_HIGHMEM, then it does build. I have a few more questions: * what is the status of kernel modules in 2.6 kernels? It doesn't build without patching the kernel: One issue is some elf relocation defines being missing (R_386_32, R_386_PC32), making apply_relocate() fail to build. The other issue is apply_alternatives() not being defined, making the final link fail. Trying to fix that, booting and trying to load modules leads to kernel panic. * Any known issues with 2.6.1 kernels? Tried to apply the 2.6.0 patch to 2.6.1 and fixup the one reject in arch/um/kernel/irq.c manually and the fs/proc/task_mmu.c build failure with a patch fished from this list. But the resulting kernel fails to boot up the system. I see the init start banner, then it stops. Looking whats up with gdb shows that the fork syscall seems to hang in a endless loop, pagefaulting at the same address over and over ... Gerd --=20 You have a new virus in /var/mail/kraxel? Certainly (this is from 2.4.23-1um). Seems like something goes weird with procfs, but I've no idea why this only happens with slirp (and newer gcc for that matter). (gdb) bt #0 panic (fmt=0x0) at panic.c:58 #1 0xa00d769b in segv (address=8, ip=2685922193, is_write=0, is_user=0, sc=0x0) at trap_kern.c:144 #2 0xa00d7af5 in segv_handler (sig=11, regs=0xa0350274) at trap_user.c:67 #3 0xa00df411 in sig_handler_common_skas (sig=11, sc_ptr=0x58) at trap_user.c:33 #4 0xa00d7c05 in sig_handler (sig=0, sc= {gs = 0, __gsh = 0, fs = 0, __fsh = 0, es = 43, __esh = 0, ds = 43, __dsh = 0, edi = 2687843188, esi = 2688540673, ebp = 2687843100, esp = 2687843028, ebx = 2687843188, edx = 2687843188, ecx = 2687827968, eax = 0, trapno = 14, err = 4, eip = 2684641864, cs = 35, __csh = 0, eflags = 2163202, esp_at_signal = 2687843028, ss = 43, __ssh = 0, fpstate = 0x0, oldmask = 0, cr2 = 8}) at trap_user.c:103 #5 <signal handler called> #6 0xa0046248 in link_path_walk (name=0xa03fe001 "dev", nd=0xa0353b74) at namei.c:462 #7 0xa004674e in path_walk (name=0x0, nd=0xa0353b74) at namei.c:659 #8 0xa0046919 in path_lookup (path=0xa03fe000 "/dev", flags=2687843188, nd=0xa0353b74) at namei.c:748 #9 0xa0047754 in sys_mkdir (pathname=0x0, mode=448) at namei.c:1345 #10 0xa000eafa in prepare_namespace () at init/do_mounts.c:917 #11 0xa000e613 in init (unused=0x0) at init/main.c:580 #12 0xa00d22f9 in run_kernel_thread (fn=0xa000e600 <init>, arg=0x0, #13 0xa00de930 in new_thread_handler (sig=10) at process_kern.c:70 #14 <signal handler called> (gdb) i sym 2685922193 kill + 17 in section .text (gdb) i line *2685922193 Line 155 of "proc_fs.h" starts at address 0xa0178e94 <svc_proc_register+68> and ends at 0xa01c3913. (gdb) up 6 #6 0xa0046248 in link_path_walk (name=0xa03fe001 "dev", nd=0xa0353b74) at namei.c:462 462 inode = nd->dentry->d_inode; (gdb) print *nd $1 = {dentry = 0x0, mnt = 0x0, last = { name = 0x8124 <Address 0x8124 out of bounds>, len = 1, hash = 2686526256}, flags = 16, last_type = 1} -- - mdz Alle 00:04, luned=EC 12 gennaio 2004, Jeff Chua ha scritto: > On Sun, 11 Jan 2004, BlaisorBlade wrote: > > Also, Jeff, when you compiled LVM, did you compile it as module(as you > > speak about initrd) or statically? > > LVM dm-mod (device mapper) is module. > > If I don't load this and not start vgscan, mount lvm devices, I don't see > klog segmentation fault. Probably building into the kernel that module would work-around your proble= m.=20 LVM is loaded at startup before klog, I guess, right? In fact the bug is likely to be with handling of modules, as they go in a=20 different kernel memory area; *maybe* they are in vmalloc'ed memory. Bye =2D-=20 cat <<EOSIGN Paolo Giarrusso, aka Blaisorblade Linux Kernel 2.4.23/2.6.0 on an i686; Linux registered user n. 292729 EOSIGN On 2004-01-13 22:40+1100, Tim Barbour wrote: > ? > I have used an 32bit UML in my AMD64 (pure 64bit system). So it is doable. I can't remember any hiccups and installation was really straightforward. BR, Jani -- Jani Averbach? Here what I get: NET4: Unix domain sockets 1.0/SMP for Linux NET4.0. Program received signal SIGSEGV, Segmentation fault. walk_init_root (name=0xf4a33ee8 <Address 0xf4a33ee8 out of bounds>, nd=0xa08f7b74) at atomic.h:107 107 __asm__ __volatile__( (gdb) bt #0 walk_init_root (name=0xf4a33ee8 <Address 0xf4a33ee8 out of bounds>, nd=0xa08f7b74) at atomic.h:107 (gdb) c Continuing. Breakpoint 1, segv (address=4104339216, ip=2685837537, is_write=2, is_user=0, sc=0xf4a33f10) at trap_kern.c:124 124 if(!is_user && (address >= start_vm) && (address < end_vm)){ (gdb) bt #0 segv (address=4104339216, ip=2685837537, is_write=2, is_user=0, sc=0xf4a33f10) at trap_kern.c:124 (gdb) bt #0 segv (address=4104339216, ip=2685837537, is_write=2, is_user=0, sc=0xf4a33f10) at trap_kern.c:124 (gdb) c Continuing. Breakpoint 2, panic (fmt=0xa08f4000 "") at panic.c:58 58 machine_paniced = 1; (gdb) bt #0 panic (fmt=0xa08f4000 "") at panic.c:58 (gdb) c Continuing. Kernel panic: Segfault with no mm Program exited normally. Cheers, -- Bill. <ballombe@...> Imagine a large red swirl here. Moin Jeff Dike, > > Is there any possibility of running a 64-bit UML virtual machine on an > > AMD-64 ? > It is, and I'm working on it. i'm thinking about upgrading my oldest UML system to either a BiAthlon, which is known to work with SKAS, or to wait a few month more a dual Opteron system to become cheap. I remember the TT problems of UML running on duals, leading me to install SKAS. Are there any experiences about running UML on an 64bit NUMA system ? Bye Michael -- mailto:kraehe@... UNA:+.? 'CED+2+:::Linux:2.4.22'UNZ+1' CETERUM CENSEO WINDOWS ESSE DELENDAM allomber@... said: > Kernel panic: Segfault with no mm > Without the eth0=slirp parameter, there are no kernel panic. Can someone get a stack trace from this? Jeff On Mon, Jan 12, 2004 at 10:36:23AM -0800, Matt Zimmerman wrote: > By the way, the original reason why I started building UML with gcc-2.95 was > because building with 3.x broke the slirp transport like so: > > Kernel panic: read of switch_pipe failed, errno = 9 > > errno 9 is EBADF. I never did find the real cause of that bug, but it has > resurfaced now that I am building with gcc 3.3 again to fix the other, worse > bug. I would be interested to know if anyone else has run into it. More > information is here: For what it worth with the current Debian UML package I get $ linux ubd0=uml root=/dev/ubd0 eth0=slirp|& less ... Netdevice 0 : SLIRP backend - command line: 'slirp' mconsole (version 2) initialized on /home/bill/.uml/wksNEk/mconsole Partition check: ubda: unknown partition table Initializing stdio console driver NET4: Linux TCP/IP 1.0 for NET4.0 IP: routing cache hash table of 512 buckets, 4Kbytes TCP: Hash tables configured (established 2048 bind 4096) Linux IP multicast router 0.06 plus PIM-SM NET4: Unix domain sockets 1.0/SMP for Linux NET4.0. Kernel panic: Segfault with no mm Without the eth0=slirp parameter, there are no kernel panic. So at least the error message has changed. The host kernel has the skas patch from the Debian package applied. Cheers, -- Bill. <ballombe@...> Imagine a large red swirl here. trb@... said: > Is there any possibility of running a 64-bit UML virtual machine on an > AMD-64 ? It is, and I'm working on it. Jeff ? The UML website has no mention of an AMD-64 port of UML, but I have heard a claim that it is possible to host a 64-bit UML on an AMD-64. If anyone can shed light on this I would appreciate it. Tim > The 2.6.0 UML patch is available at > i get this error: i applied this patch to clean 2.6.0 sources from kernel.org. if you need more information just ask. i'm running gentoo 1.4 with a 2.6.1 host kernel. linux 2.4.19 headers are installed in /usr/include, just in case it matters. > This patch updates UML to 2.6.0 and pulls in all the changes that have > accumulated in my 2.4 tree. I forgot to mention that newer libcs won't boot on 2.6 UMLs until I get [gs]et_thread_area implemented. Older libcs are fine, as are new libcs on 2.4 UMLs. Jeff
https://sourceforge.net/p/user-mode-linux/mailman/user-mode-linux-devel/?viewmonth=200401&viewday=13
CC-MAIN-2017-09
refinedweb
1,424
76.82
Text::Template - Expand template text with embedded Perl version 1.53 use Text::Template; $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'filename.tmpl'); $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] ); $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh ); $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' ); $template = Text::Template->new(PREPEND => q{use strict;}, ...); # Use a different template file syntax: $template = Text::Template->new(DELIMITERS => [$open, $close], ...); $recipient = 'King'; $text = $template->fill_in(); # Replaces `{$recipient}' with `King' print $text; $T::recipient = 'Josh'; $text = $template->fill_in(PACKAGE => T); # Pass many variables explicitly $hash = { recipient => 'Abed-Nego', friends => [ 'me', 'you' ], enemies => { loathsome => 'Saruman', fearsome => 'Sauron' }, }; $text = $template->fill_in(HASH => $hash, ...); # $recipient is Abed-Nego, # @friends is ( 'me', 'you' ), # %enemies is ( loathsome => ..., fearsome => ... ) # Call &callback in case of programming errors in template $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...); # Evaluate program fragments in Safe compartment with restricted permissions $text = $template->fill_in(SAFE => $compartment, ...); # Print result text instead of returning it $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...); # Parse template with different template file syntax: $text = $template->fill_in(DELIMITERS => [$open, $close], ...); # Note that this is *faster* than using the default delimiters # Prepend specified perl code to each fragment before evaluating: $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...); use Text::Template 'fill_in_string'; $text = fill_in_string( <<EOM, PACKAGE => 'T', ...); Dear {$recipient}, Pay me at once. Love, G.V. EOM use Text::Template 'fill_in_file'; $text = fill_in_file($filename, ...); # All templates will always have `use strict vars' attached to all fragments Text::Template->always_prepend(q{use strict 'vars';});. Here's an example of a template, which we'll suppose is stored in the file formletter.tmpl: Dear {$title} {$lastname}, It has come to our attention that you are delinquent in your {$monthname[$last_paid_month]} payment. Please remit ${sprintf("%.2f", $amount)} immediately, or your patellae may be needlessly endangered. Love, Mark "Vizopteryx" Dominus The result of filling in this template is a string, which might look something like this: Dear Mr. Smith, It has come to our attention that you are delinquent in your February payment. Please remit $392.12 immediately, or your patellae may be needlessly endangered. Love, Mark "Vizopteryx" Dominus Here is a complete program that transforms the example template into the example result, and prints it out: use Text::Template; my $template = Text::Template->new(SOURCE => 'formletter.tmpl') or die "Couldn't construct template: $Text::Template::ERROR"; my @monthname = qw(January February March April May June July August September October November December); my %vars = (title => 'Mr.', firstname => 'John', lastname => 'Smith', last_paid_month => 1, # February amount => 392.12, monthname => \@monthname); my $result = $template->fill_in(HASH => \%vars); if (defined $result) { print $result } else { die "Couldn't fill in template: $Text::Template::ERROR" }? Text::Template templates are programmed in Perl. You embed Perl code in your template, with { at the beginning and } at the end. If you want a variable interpolated, you write it the way you would in Perl. If you need to make a loop, you can use any of the Perl loop constructions. All the Perl built-in functions are available. The Text::Template module scans the template source. An open brace { begins a program fragment, which continues until the matching close brace }. When the template is filled in, the program fragments are evaluated, and each one is replaced with the resulting value to yield the text that is returned. A backslash \ in front of a brace (or another backslash that is in front of a brace) escapes its special meaning. The result of filling out this template: \{ The sum of 1 and 2 is {1+2} \} is { The sum of 1 and 2 is 3 } If you have an unmatched brace, Text::Template will return a failure code and a warning about where the problem is. Backslashes that do not precede a brace are passed through unchanged. If you have a template like this: { "String that ends in a newline.\n" } The backslash inside the string is passed through to Perl unchanged, so the \n really does turn into a newline. See the note at the end for details about the way backslashes work. Backslash processing is not done when you specify alternative delimiters with the DELIMITERS option. (See "Alternative Delimiters", below.) Each program fragment should be a sequence of Perl statements, which are evaluated the usual way. The result of the last statement executed will be evaluated in scalar context; the result of this statement is a string, which is interpolated into the template in place of the program fragment itself. The fragments are evaluated in order, and side effects from earlier fragments will persist into later fragments: {$x = @things; ''}The Lord High Chamberlain has gotten {$x} things for me this year. { $diff = $x - 17; $more = 'more' if ($diff == 0) { $diff = 'no'; } elsif ($diff < 0) { $more = 'fewer'; } ''; } That is {$diff} {$more} than he gave me last year. The value of $x set in the first line will persist into the next fragment that begins on the third line, and the values of $diff and $more set in the second fragment will persist and be interpolated into the last line. The output will look something like this: The Lord High Chamberlain has gotten 42 things for me this year. That is 25 more than he gave me last year. That is all the syntax there is. $OUTvariable There is one special trick you can play in a template. Here is the motivation for it: Suppose you are going to pass an array, @items, into the template, and you want the template to generate a bulleted list with a header, like this: Here is a list of the things I have got for you since 1907: * Ivory * Apes * Peacocks * ... One way to do it is with a template like this: Here is a list of the things I have got for you since 1907: { my $blist = ''; foreach $i (@items) { $blist .= qq{ * $i\n}; } $blist; } Here we construct the list in a variable called $blist, which we return at the end. This is a little cumbersome. There is a shortcut. Inside of templates, there is a special variable called $OUT. Anything you append to this variable will appear in the output of the template. Also, if you use $OUT in a program fragment, the normal behavior, of replacing the fragment with its return value, is disabled; instead the fragment is replaced with the value of $OUT. This means that you can write the template above like this: Here is a list of the things I have got for you since 1907: { foreach $i (@items) { $OUT .= " * $i\n"; } } $OUT is reinitialized to the empty string at the start of each program fragment. It is private to Text::Template, so you can't use a variable named $OUT in your template without invoking the special behavior. All Text::Template functions return undef on failure, and set the variable $Text::Template::ERROR to contain an explanation of what went wrong. For example, if you try to create a template from a file that does not exist, $Text::Template::ERROR will contain something like: Couldn't open file xyz.tmpl: No such file or directory new $template = Text::Template->new( TYPE => ..., SOURCE => ... ); This creates and returns a new template object. new returns undef and sets $Text::Template::ERROR if it can't create the template object. SOURCE says where the template source code will come from. TYPE says what kind of object the source is. The most common type of source is a file: Text::Template->new( TYPE => 'FILE', SOURCE => $filename ); This reads the template from the specified file. The filename is opened with the Perl open command, so it can be a pipe or anything else that makes sense with open. The TYPE can also be STRING, in which case the SOURCE should be a string: Text::Template->new( TYPE => 'STRING', SOURCE => "This is the actual template!" ); The TYPE can be ARRAY, in which case the source should be a reference to an array of strings. The concatenation of these strings is the template: Text::Template->new( TYPE => 'ARRAY', SOURCE => [ "This is ", "the actual", " template!", ] ); The TYPE can be FILEHANDLE, in which case the source should be an open filehandle (such as you got from the FileHandle or IO::* packages, or a glob, or a reference to a glob). In this case Text::Template will read the text from the filehandle up to end-of-file, and that text is the template: # Read template source code from STDIN: Text::Template->new ( TYPE => 'FILEHANDLE', SOURCE => \*STDIN ); If you omit the TYPE attribute, it's taken to be FILE. SOURCE is required. If you omit it, the program will abort. The words TYPE and SOURCE can be spelled any of the following ways: TYPE SOURCE Type Source type source -TYPE -SOURCE -Type -Source -type -source Pick a style you like and stick with it. DELIMITERS You may also add a DELIMITERS option. If this option is present, its value should be a reference to an array of two strings. The first string is the string that signals the beginning of each program fragment, and the second string is the string that signals the end of each program fragment. See "Alternative Delimiters", below. ENCODING You may also add a ENCODING option. If this option is present, and the SOURCE is a FILE, then the data will be decoded from the given encoding using the Encode module. You can use any encoding that Encode recognizes. E.g.: Text::Template->new( TYPE => 'FILE', ENCODING => 'UTF-8', SOURCE => 'xyz.tmpl'); UNTAINT If your program is running in taint mode, you may have problems if your templates are stored in files. Data read from files is considered 'untrustworthy', and taint mode will not allow you to evaluate the Perl code in the file. (It is afraid that a malicious person might have tampered with the file.) In some environments, however, local files are trustworthy. You can tell Text::Template that a certain file is trustworthy by supplying UNTAINT => 1 in the call to new. This will tell Text::Template to disable taint checks on template code that has come from a file, as long as the filename itself is considered trustworthy. It will also disable taint checks on template code that comes from a filehandle. When used with TYPE => 'string' or TYPE => 'array', it has no effect. See perlsec for more complete information about tainting. Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph Baehr for help with this feature. PREPEND This option is passed along to the fill_in call unless it is overridden in the arguments to fill_in. See " PREPEND feature and using strict in templates" below. BROKEN This option is passed along to the fill_in call unless it is overridden in the arguments to fill_in. See BROKEN below. compile $template->compile() Loads all the template text from the template's source, parses and compiles it. If successful, returns true; otherwise returns false and sets $Text::Template::ERROR. If the template is already compiled, it returns true and does nothing. You don't usually need to invoke this function, because fill_in (see below) compiles the template if it isn't compiled already. If there is an argument to this function, it must be a reference to an array containing alternative delimiter strings. See "Alternative Delimiters", below. fill_in $template->fill_in(OPTIONS); Fills in a template. Returns the resulting text if successful. Otherwise, returns undef and sets $Text::Template::ERROR. The OPTIONS are a hash, or a list of key-value pairs. You can write the key names in any of the six usual styles as above; this means that where this manual says PACKAGE (for example) you can actually use any of PACKAGE Package package -PACKAGE -Package -package Pick a style you like and stick with it. The all-lowercase versions may yield spurious warnings about Ambiguous use of package => resolved to "package" so you might like to avoid them and use the capitalized versions. At present, there are eight legal options: PACKAGE, BROKEN, BROKEN_ARG, FILENAME, SAFE, HASH, OUTPUT, and DELIMITERS. PACKAGE PACKAGE specifies the name of a package in which the program fragments should be evaluated. The default is to use the package from which fill_in was called. For example, consider this template: The value of the variable x is {$x}. If you use $template->fill_in(PACKAGE => 'R') , then the $x in the template is actually replaced with the value of $R::x. If you omit the PACKAGE option, $x will be replaced with the value of the $x variable in the package that actually called fill_in. You should almost always use PACKAGE. If you don't, and your template makes changes to variables, those changes will be propagated back into the main program. Evaluating the template in a private package helps prevent this. The template can still modify variables in your program if it wants to, but it will have to do so explicitly. See the section at the end on `Security'. Here's an example of using PACKAGE: Your Royal Highness, Enclosed please find a list of things I have gotten for you since 1907: { foreach $item (@items) { $item_no++; $OUT .= " $item_no. \u$item\n"; } } Signed, Lord High Chamberlain We want to pass in an array which will be assigned to the array @items. Here's how to do that: @items = ('ivory', 'apes', 'peacocks', ); $template->fill_in(); This is not very safe. The reason this isn't as safe is that if you had a variable named $item_no in scope in your program at the point you called fill_in, its value would be clobbered by the act of filling out the template. The problem is the same as if you had written a subroutine that used those variables in the same way that the template does. ( $OUT is special in templates and is always safe.) One solution to this is to make the $item_no variable private to the template by declaring it with my. If the template does this, you are safe. But if you use the PACKAGE option, you will probably be safe even if the template does not declare its variables with my: @Q::items = ('ivory', 'apes', 'peacocks', ); $template->fill_in(PACKAGE => 'Q'); In this case the template will clobber the variable $Q::item_no, which is not related to the one your program was using. Templates cannot affect variables in the main program that are declared with my, unless you give the template references to those variables. HASH You may not want to put the template variables into a package. Packages can be hard to manage: You can't copy them, for example. HASH provides an alternative. The value for HASH should be a reference to a hash that maps variable names to values. For example, $template->fill_in( HASH => { recipient => "The King", items => ['gold', 'frankincense', 'myrrh'], object => \$self, } ); will fill out the template and use "The King" as the value of $recipient and the list of items as the value of @items. Note that we pass an array reference, but inside the template it appears as an array. In general, anything other than a simple string or number should be passed by reference. We also want to pass an object, which is in $self; note that we pass a reference to the object, \$self instead. Since we've passed a reference to a scalar, inside the template the object appears as $object. The full details of how it works are a little involved, so you might want to skip to the next section. Suppose the key in the hash is key and the value is value. undef, then any variables named $key, @key, %key, etc., are undefined. $keyis set to that value in the template. If the value is a reference to an array, then @key is set to that array. If the value is a reference to a hash, then %key is set to that hash. Similarly if value is any other kind of reference. This means that var => "foo" and var => \"foo" have almost exactly the same effect. (The difference is that in the former case, the value is copied, and in the latter case it is aliased.) $template->fill_in(HASH => { database_handle => \$dbh, ... }); If you do this, the template will have a variable $database_handle which is the database handle object. If you leave out the \, the template will have a hash %database_handle, which exposes the internal structure of the database handle object; you don't want that. Normally, the way this works is by allocating a private package, loading all the variables into the package, and then filling out the template as if you had specified that package. A new package is allocated each time. However, if you also use the PACKAGE option, Text::Template loads the variables into the package you specified, and they stay there after the call returns. Subsequent calls to fill_in that use the same package will pick up the values you loaded in. If the argument of HASH is a reference to an array instead of a reference to a hash, then the array should contain a list of hashes whose contents are loaded into the template package one after the other. You can use this feature if you want to combine several sets of variables. For example, one set of variables might be the defaults for a fill-in form, and the second set might be the user inputs, which override the defaults when they are present: $template->fill_in(HASH => [\%defaults, \%user_input]); You can also use this to set two variables with the same name: $template->fill_in( HASH => [ { v => "The King" }, { v => [1,2,3] } ] ); This sets $v to "The King" and @v to (1,2,3). BROKEN If any of the program fragments fails to compile or aborts for any reason, and you have set the BROKEN option to a function reference, Text::Template will invoke the function. This function is called the BROKEN function. The BROKEN function will tell Text::Template what to do next. If the BROKEN function returns undef, Text::Template will immediately abort processing the template and return the text that it has accumulated so far. If your function does this, it should set a flag that you can examine after fill_in returns so that you can tell whether there was a premature return or not. If the BROKEN function returns any other value, that value will be interpolated into the template as if that value had been the return value of the program fragment to begin with. For example, if the BROKEN function returns an error string, the error string will be interpolated into the output of the template in place of the program fragment that cased the error. If you don't specify a BROKEN function, Text::Template supplies a default one that returns something like Program fragment delivered error ``Illegal division by 0 at template line 37'' (Note that the format of this message has changed slightly since version 1.31.) The return value of the BROKEN function is interpolated into the template at the place the error occurred, so that this template: (3+4)*5 = { 3+4)*5 } yields this result: (3+4)*5 = Program fragment delivered error ``syntax error at template line 1'' If you specify a value for the BROKEN attribute, it should be a reference to a function that fill_in can call instead of the default function. fill_in will pass a hash to the broken function. The hash will have at least these three members: text The source code of the program fragment that failed error The text of the error message ( $@) generated by eval. The text has been modified to omit the trailing newline and to include the name of the template file (if there was one). The line number counts from the beginning of the template, not from the beginning of the failed program fragment. lineno The line number of the template at which the program fragment began. There may also be an arg member. See BROKEN_ARG, below BROKEN_ARG If you supply the BROKEN_ARG option to fill_in, the value of the option is passed to the BROKEN function whenever it is called. The default BROKEN function ignores the BROKEN_ARG, but you can write a custom BROKEN function that uses the BROKEN_ARG to get more information about what went wrong. The BROKEN function could also use the BROKEN_ARG as a reference to store an error message or some other information that it wants to communicate back to the caller. For example: $error = ''; sub my_broken { my %args = @_; my $err_ref = $args{arg}; ... $$err_ref = "Some error message"; return undef; } $template->fill_in( BROKEN => \&my_broken, BROKEN_ARG => \$error ); if ($error) { die "It didn't work: $error"; } If one of the program fragments in the template fails, it will call the BROKEN function, my_broken, and pass it the BROKEN_ARG, which is a reference to $error. my_broken can store an error message into $error this way. Then the function that called fill_in can see if my_broken has left an error message for it to find, and proceed accordingly. FILENAME If you give fill_in a FILENAME option, then this is the file name that you loaded the template source from. This only affects the error message that is given for template errors. If you loaded the template from foo.txt for example, and pass foo.txt as the FILENAME parameter, errors will look like ... at foo.txt line N rather than ... at template line N. Note that this does NOT have anything to do with loading a template from the given filename. See fill_in_file() for that. For example: my $template = Text::Template->new( TYPE => 'string', SOURCE => 'The value is {1/0}'); $template->fill_in(FILENAME => 'foo.txt') or die $Text::Template::ERROR; will die with an error that contains Illegal division by zero at at foo.txt line 1 SAFE If you give fill_in a SAFE option, its value should be a safe compartment object from the Safe package. All evaluation of program fragments will be performed in this compartment. See Safe for full details about such compartments and how to restrict the operations that can be performed in them. If you use the PACKAGE option with SAFE, the package you specify will be placed into the safe compartment and evaluation will take place in that package as usual. If not, SAFE operation is a little different from the default. Usually, if you don't specify a package, evaluation of program fragments occurs in the package from which the template was invoked. But in SAFE mode the evaluation occurs inside the safe compartment and cannot affect the calling package. Normally, if you use HASH without PACKAGE, the hash variables are imported into a private, one-use-only package. But if you use HASH and SAFE together without PACKAGE, the hash variables will just be loaded into the root namespace of the Safe compartment. OUTPUT If your template is going to generate a lot of text that you are just going to print out again anyway, you can save memory by having Text::Template print out the text as it is generated instead of making it into a big string and returning the string. If you supply the OUTPUT option to fill_in, the value should be a filehandle. The generated text will be printed to this filehandle as it is constructed. For example: $template->fill_in(OUTPUT => \*STDOUT, ...); fills in the $template as usual, but the results are immediately printed to STDOUT. This may result in the output appearing more quickly than it would have otherwise. If you use OUTPUT, the return value from fill_in is still true on success and false on failure, but the complete text is not returned to the caller. PREPEND You can have some Perl code prepended automatically to the beginning of every program fragment. See " PREPEND feature and using strict in templates" below. DELIMITERS If this option is present, its value should be a reference to a list of two strings. The first string is the string that signals the beginning of each program fragment, and the second string is the string that signals the end of each program fragment. See "Alternative Delimiters", below. If you specify DELIMITERS in the call to fill_in, they override any delimiters you set when you created the template object with new. fill_this_in The basic way to fill in a template is to create a template object and then call fill_in on it. This is useful if you want to fill in the same template more than once. In some programs, this can be cumbersome. fill_this_in accepts a string, which contains the template, and a list of options, which are passed to fill_in as above. It constructs the template object for you, fills it in as specified, and returns the results. It returns undef and sets $Text::Template::ERROR if it couldn't generate any results. An example: $Q::name = 'Donald'; $Q::amount = 141.61; $Q::part = 'hyoid bone'; $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q); Dear {$name}, You owe me \\${sprintf('%.2f', $amount)}. Pay or I will break your {$part}. Love, Grand Vizopteryx of Irkutsk. EOM Notice how we included the template in-line in the program by using a `here document' with the << notation. fill_this_in is a deprecated feature. It is only here for backwards compatibility, and may be removed in some far-future version in Text::Template. You should use fill_in_string instead. It is described in the next section. fill_in_string It is stupid that fill_this_in is a class method. It should have been just an imported function, so that you could omit the Text::Template-> in the example above. But I made the mistake four years ago and it is too late to change it. fill_in_string is exactly like fill_this_in except that it is not a method and you can omit the Text::Template-> and just say print fill_in_string(<<'EOM', ...); Dear {$name}, ... EOM To use fill_in_string, you need to say use Text::Template 'fill_in_string'; at the top of your program. You should probably use fill_in_string instead of fill_this_in. fill_in_file If you import fill_in_file, you can say $text = fill_in_file(filename, ...); The ... are passed to fill_in as above. The filename is the name of the file that contains the template you want to fill in. It returns the result text. or undef, as usual. If you are going to fill in the same file more than once in the same program you should use the longer new / fill_in sequence instead. It will be a lot faster because it only has to read and parse the file once. People always ask for this. ``Why don't you have an include function?'' they want to know. The short answer is this is Perl, and Perl already has an include function. If you want it, you can just put {qx{cat filename}} into your template. Voilà. If you don't want to use cat, you can write a little four-line function that opens a file and dumps out its contents, and call it from the template. I wrote one for you. In the template, you can say {Text::Template::_load_text(filename)} If that is too verbose, here is a trick. Suppose the template package that you are going to be mentioning in the fill_in call is package Q. Then in the main program, write *Q::include = \&Text::Template::_load_text; This imports the _load_text function into package Q with the name include. From then on, any template that you fill in with package Q can say {include(filename)} to insert the text from the named file at that point. If you are using the HASH option instead, just put include => \&Text::Template::_load_text into the hash instead of importing it explicitly. Suppose you don't want to insert a plain text file, but rather you want to include one template within another? Just use fill_in_file in the template itself: {Text::Template::fill_in_file(filename)} You can do the same importing trick if this is too much to type. myvariables People are frequently surprised when this doesn't work: my $recipient = 'The King'; my $text = fill_in_file('formletter.tmpl'); The text The King doesn't get into the form letter. Why not? Because $recipient is a my variable, and the whole point of my variables is that they're private and inaccessible except in the scope in which they're declared. The template is not part of that scope, so the template can't see $recipient. If that's not the behavior you want, don't use my. my means a private variable, and in this case you don't want the variable to be private. Put the variables into package variables in some other package, and use the PACKAGE option to fill_in: $Q::recipient = $recipient; my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q'); or pass the names and values in a hash with the HASH option: my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient }); All variables are evaluated in the package you specify with the PACKAGE option of fill_in. if you use this option, and if your templates don't do anything egregiously stupid, you won't have to worry that evaluation of the little programs will creep out into the rest of your program and wreck something. Nevertheless, there's really no way (except with Safe) to protect against a template that says { $Important::Secret::Security::Enable = 0; # Disable security checks in this program } or { $/ = "ho ho ho"; # Sabotage future uses of <FH>. # $/ is always a global variable } or even { system("rm -rf /") } so don't go filling in templates unless you're sure you know what's in them. If you're worried, or you can't trust the person who wrote the template, use the SAFE option. A final warning: program fragments run a small risk of accidentally clobbering local variables in the fill_in function itself. These variables all have names that begin with $fi_, so if you stay away from those names you'll be safe. (Of course, if you're a real wizard you can tamper with them deliberately for exciting effects; this is actually how $OUT works.) I can fix this, but it will make the package slower to do it, so I would prefer not to. If you are worried about this, send me mail and I will show you what to do about it. Lorenzo Valdettaro pointed out that if you are using Text::Template to generate TeX output, the choice of braces as the program fragment delimiters makes you suffer suffer suffer. Starting in version 1.20, you can change the choice of delimiters to something other than curly braces. In either the new() call or the fill_in() call, you can specify an alternative set of delimiters with the DELIMITERS option. For example, if you would like code fragments to be delimited by [@-- and --@] instead of { and }, use ... DELIMITERS => [ '[@--', '--@]' ], ... Note that these delimiters are literal strings, not regexes. (I tried for regexes, but it complicates the lexical analysis too much.) Note also that DELIMITERS disables the special meaning of the backslash, so if you want to include the delimiters in the literal text of your template file, you are out of luck---it is up to you to choose delimiters that do not conflict with what you are doing. The delimiter strings may still appear inside of program fragments as long as they nest properly. This means that if for some reason you absolutely must have a program fragment that mentions one of the delimiters, like this: [@-- print "Oh no, a delimiter: --@]\n" --@] you may be able to make it work by doing this instead: [@-- # Fake matching delimiter in a comment: [@-- print "Oh no, a delimiter: --@]\n" --@] It may be safer to choose delimiters that begin with a newline character. Because the parsing of templates is simplified by the absence of backslash escapes, using alternative DELIMITERS may speed up the parsing process by 20-25%. This shows that my original choice of { and } was very bad. PREPENDfeature and using strictin templates Suppose you would like to use strict in your templates to detect undeclared variables and the like. But each code fragment is a separate lexical scope, so you have to turn on strict at the top of each and every code fragment: { use strict; use vars '$foo'; $foo = 14; ... } ... { # we forgot to put `use strict' here my $result = $boo + 12; # $boo is misspelled and should be $foo # No error is raised on `$boo' } Because we didn't put use strict at the top of the second fragment, it was only active in the first fragment, and we didn't get any strict checking in the second fragment. Then we misspelled $foo and the error wasn't caught. Text::Template version 1.22 and higher has a new feature to make this easier. You can specify that any text at all be automatically added to the beginning of each program fragment. When you make a call to fill_in, you can specify a PREPEND => 'some perl statements here' option; the statements will be prepended to each program fragment for that one call only. Suppose that the fill_in call included a PREPEND => 'use strict;' option, and that the template looked like this: { use vars '$foo'; $foo = 14; ... } ... { my $result = $boo + 12; # $boo is misspelled and should be $foo ... } The code in the second fragment would fail, because $boo has not been declared. use strict was implied, even though you did not write it explicitly, because the PREPEND option added it for you automatically. There are three other ways to do this. At the time you create the template object with new, you can also supply a PREPEND option, in which case the statements will be prepended each time you fill in that template. If the fill_in call has its own PREPEND option, this overrides the one specified at the time you created the template. Finally, you can make the class method call Text::Template->always_prepend('perl statements'); If you do this, then call calls to fill_in for any template will attach the perl statements to the beginning of each program fragment, except where overridden by PREPEND options to new or fill_in. An alternative to adding "use strict;" to the PREPEND option, you can pass STRICT => 1 to fill_in when also passing the HASH option. Suppose that the fill_in call included both HASH => {$foo => ''} and STRICT => 1 options, and that the template looked like this: { $foo = 14; ... } ... { my $result = $boo + 12; # $boo is misspelled and should be $foo ... } The code in the second fragment would fail, because $boo has not been declared. use strict was implied, even though you did not write it explicitly, because the STRICT option added it for you automatically. Any variable referenced in the template that is not in the HASH option will be an error. This section is technical, and you should skip it on the first few readings. Normally there are three places that prepended text could come from. It could come from the PREPEND option in the fill_in call, from the PREPEND option in the new call that created the template object, or from the argument of the always_prepend call. Text::Template looks for these three things in order and takes the first one that it finds. In a subclass of Text::Template, this last possibility is ambiguous. Suppose S is a subclass of Text::Template. Should Text::Template->always_prepend(...); affect objects in class Derived? The answer is that you can have it either way. The always_prepend value for Text::Template is normally stored in a hash variable named %GLOBAL_PREPEND under the key Text::Template. When Text::Template looks to see what text to prepend, it first looks in the template object itself, and if not, it looks in $GLOBAL_PREPEND{class} where class is the class to which the template object belongs. If it doesn't find any value, it looks in $GLOBAL_PREPEND{'Text::Template'}. This means that objects in class Derived will be affected by Text::Template->always_prepend(...); unless there is also a call to Derived->always_prepend(...); So when you're designing your derived class, you can arrange to have your objects ignore Text::Template::always_prepend calls by simply putting Derived->always_prepend('') at the top of your module. Of course, there is also a final escape hatch: Templates support a prepend_text that is used to look up the appropriate text to be prepended at fill_in time. Your derived class can override this method to get an arbitrary effect. Jennifer D. St Clair asks: > Most of my pages contain JavaScript and Stylesheets. > How do I change the template identifier? Jennifer is worried about the braces in the JavaScript being taken as the delimiters of the Perl program fragments. Of course, disaster will ensue when perl tries to evaluate these as if they were Perl programs. The best choice is to find some unambiguous delimiter strings that you can use in your template instead of curly braces, and then use the DELIMITERS option. However, if you can't do this for some reason, there are two easy workarounds: 1. You can put \ in front of {, }, or \ to remove its special meaning. So, for example, instead of if (br== "n3") { // etc. } you can put if (br== "n3") \{ // etc. \} and it'll come out of the template engine the way you want. But here is another method that is probably better. To see how it works, first consider what happens if you put this into a template: { 'foo' } Since it's in braces, it gets evaluated, and obviously, this is going to turn into foo So now here's the trick: In Perl, q{...} is the same as '...'. So if we wrote {q{foo}} it would turn into foo So for your JavaScript, just write {q{if (br== "n3") { // etc. }} } and it'll come out as if (br== "n3") { // etc. } which is what you want. head2 Shut Up! People sometimes try to put an initialization section at the top of their templates, like this: { ... $var = 17; } Then they complain because there is a 17 at the top of the output that they didn't want to have there. Remember that a program fragment is replaced with its own return value, and that in Perl the return value of a code block is the value of the last expression that was evaluated, which in this case is 17. If it didn't do that, you wouldn't be able to write {$recipient} and have the recipient filled in. To prevent the 17 from appearing in the output is very simple: { ... $var = 17; ''; } Now the last expression evaluated yields the empty string, which is invisible. If you don't like the way this looks, use { ... $var = 17; ($SILENTLY); } instead. Presumably, $SILENTLY has no value, so nothing will be interpolated. This is what is known as a `trick'. Every effort has been made to make this module compatible with older versions. The only known exceptions follow: The output format of the default BROKEN subroutine has changed twice, most recently between versions 1.31 and 1.40. Starting in version 1.10, the $OUT variable is arrogated for a special meaning. If you had templates before version 1.10 that happened to use a variable named $OUT, you will have to change them to use some other variable or all sorts of strangeness will result. Between versions 0.1b and 1.00 the behavior of the \ metacharacter changed. In 0.1b, \\ was special everywhere, and the template processor always replaced it with a single backslash before passing the code to Perl for evaluation. The rule now is more complicated but probably more convenient. See the section on backslash processing, below, for a full discussion. In Text::Template beta versions, the backslash was special whenever it appeared before a brace or another backslash. That meant that while {"\n"} did indeed generate a newline, {"\\"} did not generate a backslash, because the code passed to Perl for evaluation was "\" which is a syntax error. If you wanted a backslash, you would have had to write {"\\\\"}. In Text::Template versions 1.00 through 1.10, there was a bug: Backslash was special everywhere. In these versions, {"\n"} generated the letter n. The bug has been corrected in version 1.11, but I did not go back to exactly the old rule, because I did not like the idea of having to write {"\\\\"} to get one backslash. The rule is now more complicated to remember, but probably easier to use. The rule is now: Backslashes are always passed to Perl unchanged unless they occur as part of a sequence like \\\\\\{ or \\\\\\}. In these contexts, they are special; \\ is replaced with \, and \{ and \} signal a literal brace. Examples: \{ foo \} is not evaluated, because the \ before the braces signals that they should be taken literally. The result in the output looks like this: { foo } This is a syntax error: { "foo}" } because Text::Template thinks that the code ends at the first }, and then gets upset when it sees the second one. To make this work correctly, use { "foo\}" } This passes "foo}" to Perl for evaluation. Note there's no \ in the evaluated code. If you really want a \ in the evaluated code, use { "foo\\\}" } This passes "foo\}" to Perl for evaluation. Starting with Text::Template version 1.20, backslash processing is disabled if you use the DELIMITERS option to specify alternative delimiter strings. $Text::Template::ERROR In the past some people have fretted about `violating the package boundary' by examining a variable inside the Text::Template package. Don't feel this way. $Text::Template::ERROR is part of the published, official interface to this package. It is perfectly OK to inspect this variable. The interface is not going to change. If it really, really bothers you, you can import a function called TTerror that returns the current value of the $ERROR variable. So you can say: use Text::Template 'TTerror'; my $template = Text::Template->new(SOURCE => $filename); unless ($template) { my $err = TTerror; die "Couldn't make template: $err; aborting"; } I don't see what benefit this has over just doing this: use Text::Template; my $template = Text::Template->new(SOURCE => $filename) or die "Couldn't make template: $Text::Template::ERROR; aborting"; But if it makes you happy to do it that way, go ahead. The CGI module provides functions for `sticky widgets', which are form input controls that retain their values from one page to the next. Sometimes people want to know how to include these widgets into their template output. It's totally straightforward. Just call the CGI functions from inside the template: { $q->checkbox_group(NAME => 'toppings', LINEBREAK => true, COLUMNS => 3, VALUES => \@toppings, ); } It may be useful to preprocess the program fragments before they are evaluated. See Text::Template::Preprocess for more details. It may be useful to process hunks of output before they are appended to the result text. For this, subclass and replace the append_text_to_result method. It is passed a list of pairs with these entries: handle - a filehandle to which to print the desired output out - a ref to a string to which to append, to use if handle is not given text - the text that will be appended type - where the text came from: TEXT for literal text, PROG for code Originally written by Mark Jason Dominus, Plover Systems (versions 0.01 - 1.46) Maintainership transferred to Michael Schout <mschout@cpan.org> in version 1.47 Many thanks to the following people for offering support, encouragement, advice, bug reports, and all the other good stuff. Special thanks to: for telling me how to do the Safe support (I spent two years worrying about it, and then Jonathan pointed out that it was trivial.) for demanding less verbose fragments like they have in ASP, for helping me figure out the Right Thing, and, especially, for talking me out of adding any new syntax. These discussions resulted in the $OUT feature. my variables in fill_in are still susceptible to being clobbered by template evaluation. They all begin with fi_, so avoid those names in your templates. The line number information will be wrong if the template's lines are not terminated by "\n". You should let me know if this is a problem. If you do, I will fix it. The $OUT variable has a special meaning in templates, so you cannot use it as if it were a regular variable. There are not quite enough tests in the test suite.. Michael Schout <mschout@cpan.org> This software is copyright (c) 2013 by Mark Jason Dominus <mjd@cpan.org>. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
http://search.cpan.org/~mschout/Text-Template-1.53/lib/Text/Template.pm
CC-MAIN-2018-22
refinedweb
7,429
71.34
Let's continue with previous 'orbit' tutorial. In order to create new 'planetary system' just add single orbit function call: orbit(planetMovieClip, satelliteMovieClip, _distance, _speed); This will make satelliteMovieClip orbit around planetMovieClip at distance _distance with speed _speed. Further you can create another smaller satellite to orbit around satelliteMovieClip, etc ... This system doesn't have any gravity variables, just plain circular movement. Now, to create simple trails, insert new movie clip, any image will do, but for start, make something simple, like 4 pixels radius white circle. Enter 'trailMC' as linkage name and add next code: // create trail movie clip var mc:trailMC = new trailMC(); mc.x = sat.x; mc.y = sat.y; addChild(mc); This code should go at the bottom of doEveryFrame function. Take a look at result file image: As you can see, if you make star, planets and moons movie clips have alpha = zero, then you get easy to use shapes generator ... or something like that. Since trails movie clip can be anything you think of, you can see how powerful this technique can be. If drawing shapes it's not your goal and rather you need just trails, you can make them disappear after a while. One way to do it is to use next code inside trailMC (or use Timer class): import flash.events.Event; this.addEventListener(Event.ENTER_FRAME, onFrame); function onFrame(evt:Event):void { if (alpha > 0) { alpha -= 0.05; } else { this.removeEventListener(Event.ENTER_FRAME, onFrame); } } In next post I'll show you how to use drawing API instead of movie clips for making orbit trails. Thanks for reading. *_*
http://flanture.blogspot.com/2011/03/making-orbit-trails-in-flash.html
CC-MAIN-2014-35
refinedweb
267
72.87
Dear experts, I have a class which contains, a std::vector of vectors. I don’t want to store this class in a tree or draw it, or anything, I just want to use this class as a container in my program, which elsewhere requires root libraries. If I comment out everything in my code which doesn’t use std::vector< std::vector> > the compilation is fine. Do I need to add something into my LinkDef file to compile my class correctly? The error occurs when generating the dictionary: Syntax error prec_stl/memory:56: … A test with a simple class: #include <vector> class test { public: test() {}; typedef std::vector< std::vector<int> > dvec; private: ClassDef(test,0) } Throws the same error. Thanks, Rob
https://root-forum.cern.ch/t/std-vector-std-vector-in-root-class/8069
CC-MAIN-2022-27
refinedweb
123
57.4
Continuing on my series discussing the language I wrote, this next post is going to talk about the basics of static typing and scope rules. So far my language implementation follows very closely to Parr’s examples in his book Language Implementation Patterns, which is what gave me the inspiration to do this project. However, starting here, I began to get confused with Parr’s examples. I didn’t really see how to translate his examples into real code. On top of that some of his diagrams weren’t matching my mental model of what was going on, so that didn’t help either. In general, I understood what he was doing, but I didn’t want to follow his examples anymore – Parr switched over to using ANTLR for everything which didn’t help me: I wanted to know how to do this without a generator. So I just jumped in and took a stab at it. For the scope builder (and later the interpreter) I did what I thought made sense. Like I’ve mentioned before, I haven’t formally studied compiler/language design, so if a solution seems naive or egregiously wrong take it with a grain of salt (but leave a comment so I can learn how to do it better). Anyways, this is where the project started to take off because I got to make real language decisions. The first two things I decided on was that this language would have static typing and forward reference support. I, personally, prefer static typed languages to dynamic typed languages because I like compile time checking. I’m not going to deny that dynamic typing isn’t helpful in some situations, in fact my interpreter leverages the dynamic data type heavily. For fun I did build in some runtime typing into the language (which I’ll cover in a later post). The type system I implemented also supports type inference. However, my language is pretty rudimentary and I don’t support type promotion, though it wouldn’t be hard to add. For scoping, I wanted to allow forward references for methods and class internals, but not for internal statements. I like forward references because it lets you structure your code by ideas and locality of reference, and not strictly by bottom up execution. I like the freedom that forward references gives you. Also I knew that solving forward references would be more difficult so I decided to tackle the problem. For the remaining post, I’m going to discuss the groundwork required to dig into more complex parts of the scope builder. As always, if you are curious check out the github project for full source, examples, tests, and comments. Let’s get started. Iterating over the syntax tree In the last post we built a parser that generates an abstract syntax tree representing the execution of our program. Now, we need to iterate over that tree and do meaningful work. However, we’re going to be going over this tree a bunch of different times and we want to do different work over it. We could put the tree iteration into the syntax tree, but thats nasty. Instead, I used the visitor pattern to iterate over the tree. I defined two interfaces. The first, is the definition for the actual visitor. public interface IAstVisitor { void Visit(Conditional ast); void Visit(Expr ast); void Visit(FuncInvoke ast); void Visit(VarDeclrAst ast); void Visit(MethodDeclr ast); void Visit(WhileLoop ast); void Visit(ScopeDeclr ast); void Visit(ForLoop ast); void Visit(ReturnAst ast); void Visit(PrintAst ast); void Visit(ClassAst ast); void Visit(ClassReference ast); void Visit(NewAst ast); void Visit(TryCatchAst ast); void Start(Ast ast); } This interface will accept different syntax trees and depending on which overloaded Visit function is called, the visitor will know how to iterate (and do work) on that particular syntax tree. The next interface is applied to the abstract base class Ast, which means that all syntax tree classes have to implement it. This interface forces the ast classes to “accept” a visitor. interface IAcceptVisitor { void Visit(IAstVisitor visitor); } Below is the class used to represent an expression. Notice its visit method. All the classes have exactly the same visit method. You have to do it this way because if the visit method was in the base class, the visitor wouldn’t be able to figure out which class was trying to be visited (since they all inherit from Ast). public class Expr : Ast { public Ast Left { get; private set; } public Ast Right { get; private set; } public Expr(Token token) : base(token) { } public Expr(Ast left, Token token, Ast right) : base(token) { Left = left; Right = right; } public override void Visit(IAstVisitor visitor) { visitor.Visit(this); } public override AstTypes AstType { get { return AstTypes.Expression; } } } Now all we need to do to iterate over the tree is create an actual visitor. As an example, here is the function invoke overloaded visit method on a visitor called PrintAstVisitor that iterates the syntax tree and writes the tree representation to the console. To iterate over other parts of the tree we tell the tree to visit itself using this visitor (with this). public class PrintAstVisitor : IAstVisitor { // ... other functions .... public void Visit(FuncInvoke ast) { Console.WriteLine("Function invoke AST"); ast.FunctionName.Visit(this); ast.Arguments.ForEach(arg => arg.Visit(this)); } // ... other functions .... When we are ready to actually iterate over the full tree, we need to hand off the root of the syntax tree to the visitor and tell it to start. var program = @"int x = 1;"; var ast = new LanguageParser(new Lexer(program)).Parse(); new PrintAstVisitor().Start(ast); Symbols, Types, and Scopes? The goal of the scope builder visitor is to associate types to symbols and make sure that they are visible in the right scope. We all intuitively know what symbols are, we work with them all the time. int x = 1 x, here, is a symbol. It also has a type of int. Some types are built into the language, like int, string, void, etc. Some types are user defined (like classes or structs). The scope builder is going to figure out which expressions are which types and tag each syntax tree node with its type. The builder also starts to do some syntax validation for us. It’s responsible for making sure our assignments, declarations, and invocations all make sense. One of the builders job is to make sure we can’t reference undefined values. For example, this is invalid: int x = y int y = 0; This is because x uses y before y is defined. The scope builder is also responsible for validating static typing: we want invalid type assignment to be prevented void x = 1; If we defined x to be a void then we certainly shouldn’t be able to assign 1 to a void. The scope builder should throw an exception and prevent us from doing this. By preventing us from doing this we eliminate having to find out at runtime that our code is bogus. Though, as the language “designer” here, if we wanted to let this happen we totally could! It’s really up to your language implementation as to how you deal with what this means. On top of all of this, like mentioned above, the scope builder is responsible for validating that symbols are visible only where they should be. The code below should be invalid because y is declared in an inner scope not visible to the print statement. Some languages don’t do it this way (javascript/actionscript), but this drives me nuts, so I made sure to do it for my own language. int x = 1; { int y = 2; } print y; The scope builder sounds like it does a lot of work (and it does), but most of these things are intertwined and the underlying code is short and sweet so there isn’t too much overlapping of concerns in the same class. Scopes Scopes are easily represented by a stack. Each time you encounter a new scope block (like the inner scoped y above) all you need to do is push a new scope onto your scope stack. Symbols below the current scope on the stack are visible if you are in that scope, so x would be visible to y, but symbols are not allowed to be visible up the stack from the bottom. To support classes I had one scope stack for the global space. This scoped items in what I considered “main”, or really any inline code that is not within a class. I also had a scope stack for each class I encountered. This is because you don’t want classes to be able to see symbols in the global scope. Imagine this scenario: class foo{ int value = x; } int x = 0; This should be invalid because foo shouldn’t be able to see x. [Note: classes get a little weird, because you need to define the class declaration in the global scope (so you can instantiate the class), but everything inside the class is in its own scope. There are also other issues with classes that I’ll talk about in a later post.] A scope, then, is nothing more than a bag of symbols and a reference to its parent scope (below it in the scope stack). For example, a basic Scope object in my language looks like this. Notice that a scope contains a reference to its parents scope (line 5). This will get set automatically by the ScopeStack I’ll show next. It’s important to understand that a scope will have access to all elements below it via its parent. You can see that logic in the Resolve function which checks if a symbol is in the current scopes dictionary, and if not, tries the parent scope. public class Scope : IScopeable<Scope> { public Dictionary<string, Symbol> Symbols { get; set; } public Scope EnclosingScope { get; private set; } public List<IScopeable<Scope>> ChildScopes { get; private set; } public Scope() { Symbols = new Dictionary<string, Symbol>(); ChildScopes = new List<IScopeable<Scope>>(64); } public void SetParentScope(Scope scope) { EnclosingScope = scope; } public void Define(Symbol symbol) { Symbols[symbol.Name] = symbol; } public Symbol Resolve(String name) { Symbol o; if (Symbols.TryGetValue(name, out o)) { return o; } if (EnclosingScope == null) { return null; } return EnclosingScope.Resolve(name); } } To help with setting the parent scope each time we pushed a new scope onto the stack, I created a generic scope stack that facilitated pushing and popping scopes, as well as auto-linked scope references. This way when I access a scope reference I can go down its stack: public class ScopeStack<T> where T : class, IScopeable<T>, new() { private Stack<T> Stack { get; set; } public T Current { get; set; } public ScopeStack() { Stack = new Stack<T>(); } public void CreateScope() { var parentScope = Current; if (Current != null) { Stack.Push(Current); } Current = new T(); Current.SetParentScope(parentScope); if (parentScope != null) { parentScope.ChildScopes.Add(Current); } } public void PopScope() { if (Stack.Count > 0) { Current = Stack.Pop(); } } } And IScopeable is public interface IScopeable<T> where T : class, new() { void SetParentScope(T scope); List<IScopeable<T>> ChildScopes { get; } } The concept of a stack based symbol visibility control will get re-used again when we discuss memory spaces (i.e. where a value is in memory). Memory and scope are very similar, but not the same. You’ll see why later, but needless to say the scope container class gets re-used a few times in different contexts. Types Every symbol has a type. Let me show you what my type definition looks like: public interface IType { String TypeName { get; } ExpressionTypes ExpressionType { get; } Ast Src { get; set; } } ExpressionTypes is an enum of expression types. I use this for type checking later. The Src property holds a reference to the syntax tree that generated this type. For example, if I have a class called foo I will create a type whose TypeName is foo and it’s Src property will point to its ClassAst reference. Later I can get info about the source syntax tree just from the type. I only have two kinds of types in the entire system. - Built in types. These are types like int, string, etc. They all share the same class, and the only thing that is different about them is the ExpressionTypeenum they hold indicating which built in type they are. - User defined types. These are classes that the user defines. To make a symbol is easy. Depending on the syntax tree type I can create the proper symbol type based on its token type. public static IType CreateSymbolType(Ast astType) { if (astType == null) { return null; } Func<IType> op = () => { switch (astType.Token.TokenType) { case TokenType.Int: return new BuiltInType(ExpressionTypes.Int); case TokenType.Float: return new BuiltInType(ExpressionTypes.Float); case TokenType.Void: return new BuiltInType(ExpressionTypes.Void); case TokenType.Infer: return new BuiltInType(ExpressionTypes.Inferred); case TokenType.QuotedString: case TokenType.String: return new BuiltInType(ExpressionTypes.String); case TokenType.Word: return new UserDefinedType(astType.Token.TokenValue); case TokenType.True: case TokenType.False: return new BuiltInType(ExpressionTypes.Boolean); case TokenType.Method: return new BuiltInType(ExpressionTypes.Method); } return null; }; var type = op(); if (type != null) { type.Src = astType; } return type; } Symbols A symbol is a pairing of a symbol name and a symbol type. This means a variable named x declared as type int now gets those two values paired together: public class Symbol : Scope { public String Name { get; private set; } public IType Type { get; private set; } public Symbol(String name, IType type) { Name = name; Type = type; } public Symbol(String name) { Name = name; } } But wait, symbols are also scopes? They can be. A class symbol is also a scope and when we’re within a class we’ll want to define it’s symbols within it’s own personal space (like I mentioned earlier with the separate scope stacks). Having a symbol also be a scope makes life really easy when you try and figure out where things are. The scope builder is complicated, but it follows the same basic pattern - If the current symbol is being declared (variable declaration, method declaration argument definitions, etc) then define the symbol in the appropriate scope. - If we are referencing the symbol, resolve it and make sure it’s been declared and is visible in the scope we expect Defining a symbol A simplified version of the variable declration visit function looks like this: [Note: it’s simplified because we need to handle variables that are declared without values, as well as type inferred values, and method assignments, and partial functions, and validating left and right hand side type assignments, etc. There is a lot to it, to be covered later. If you’re curious check the github] public void Visit(VarDeclrAst ast) { if (ast.DeclarationType != null) { var symbol = ScopeUtil.DefineUserSymbol(ast.DeclarationType, ast.VariableName); DefineToScope(symbol); ast.AstSymbolType = symbol.Type; } } The declaration type is a syntax tree representing the declaration of the variable (int, string, user defined, whatever), and the name is an expression representing a word that the variable is called. Then we create symbol type and the actual symbol public static Symbol DefineUserSymbol(Ast ast, Ast name) { IType type = CreateSymbolType(ast); return new Symbol(name.Token.TokenValue, type); } Then we define the symbol in the current scope private void DefineToScope(Symbol symbol) { Current.Define(symbol); } And finally, we assign the current ast node it’s expression type ast.AstSymbolType = symbol.Type; This way each syntax tree can track what type it is. We can use this information to do static type checking later (basically validate that the left hand side and right hand side have the same, or promotable, types). Resolving a symbol Resolving is the other way around. Here is a simplified version of the visitor for an expression. It first visits the left, then the right. If the left and right are null then we have a leaf in our syntax tree and we need to resolve what it is. If it’s a built in type, like an integer, it’ll get defined as a symbol, otherwise if it’s a word (a user defined variable) it’ll get resolved: public void Visit(Expr ast) { if (ast.Left != null) { ast.Left.Visit(this); } if (ast.Right != null) { ast.Right.Visit(this); } SetScope(ast); if (ast.Left == null && ast.Right == null) { ast.AstSymbolType = ResolveOrDefine(ast); } } Which calls /// <summary> /// Creates a type for built in types or resolves user defined types /// </summary> /// <param name="ast"></param> /// <returns></returns> private IType ResolveOrDefine(Expr ast) { if (ast == null) { return null; } switch (ast.Token.TokenType) { case TokenType.Word: return ResolveType(ast); } return ScopeUtil.CreateSymbolType(ast); } We’ve already seen ScopeUtil.CreateSymbolType. Here is a simplified version of ResolveType private IType ResolveType(Ast ast) { Symbol symbol = Current.Resolve(ast); if(symbol != null){ return symbol.Type; } throw new InvalidSyntax("Cannot resolve {0}", ast.Token.TokenValue); } It’s a simplified version because it doesn’t handle forward references. I’ll discuss that in a later post. Remember the scope rules above. If a variable isn’t visible in a scope, either because it’s undefined, or because it’s not visible, resolving the type will fail. You’ll notice the SetScope function. Every syntax tree gets assigned a reference to the scope they came from. This way everyone knows who can see what. Conclusion At this point we have a very basic way of defining symbols, types, and scopes. We’ve also gone over a way to validate simple scoping rules. There is a lot more to the scope builder. Now that there is some infrastructure in the next post I’ll dig deeper into the scope builder and discuss how we can fix the forward reference problem and do type inference. Still to come in the scope builder is determining return types and handling how to build partial functions. 1 thought on “Adding static typing and scope validation into the language, part 1”
https://onoffswitch.net/2013/03/04/adding-static-typing-and-scope-validation-into-the-language-part-1/
CC-MAIN-2020-16
refinedweb
2,986
64.2
When a URL points at a specific piece of a document, it can be difficult to ascertain. Find out how you can use some simple CSS to draw attention to the target of a URL and improve the user's experience. As an aid to identifying the destination of a link that points to a specific portion of a document, CSS3 Selectors introduces the :target pseudo-class. Netscape 7.1 introduced support for this pseudo-class into the Netscape family, giving authors a new way to assist users keep oriented within large documents.pseudo-class. Netscape 7.1 introduced support for this pseudo-class into the Netscape family, giving authors a new way to assist users keep oriented within large documents. Picking a Target The pseudo-class :target contains the fragment identifier #Example. In HTML, identifiers are found as the values of either id or name attributes, since the two share the same namespace. Thus, the example URI would point to the heading "Example" in this document. is used to style the target element of a URI containing a fragment identifier. For example, the URIis used to style the target element of a URI containing a fragment identifier. For example, the URI Suppose you wish to style any h2 element that is the target of a URI,. Related Links Original Document Information - Author(s): Eric Meyer, Standards Evangelist, Netscape Communications - Last Updated Date: Published 30 Jun 2003 - Note: This reprinted article was originally part of the DevEdge site.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_the_:target_selector
CC-MAIN-2015-18
refinedweb
248
51.38
ifStatement Like most languages, C++ provides an if statement that supports conditional execution. We can use an if to write a program to count how many consecutive times each distinct value appears in the input: #include <iostream>int main(){ // currVal is the number we're counting; we'll read new values into val int currVal = 0, val = 0; // read first number and ensure that we have data to process if (std::cin >> currVal) { int cnt = 1; // store the count for the current value we're processing while (std::cin >> val) { // read the remaining numbers if (val == currVal) // if the values are the same ++cnt; // add 1 to cnt else { // otherwise, print the count ... No credit card required
https://www.safaribooksonline.com/library/view/c-primer-fifth/9780133053043/ch01lev2sec13.html
CC-MAIN-2018-13
refinedweb
117
50.84
Asynchronous Versus Parallel Programming The. Before we begin it would help to review a key difference in Asynchronous and Parallel programming. The two perform similar tasks and functions in most modern languages, but they have conceptual differences. Asynchronous calls are used to prevent “blocking” within an application. For instance, if you need to run a query against a database or pull a file from a local disk you will want to use an asynchronous call. This call will spin-off in an already existing thread (such as an I/O thread) and do its task when it can. Asynchronous calls can occur on the same machine or be used on another machine somewhere else (such as a computer in the LAN or a webserver exposing an API on the internet). This is used to keep the user interface from appearing to “freeze” or act unresponsively. In parallel programming you still break up work or tasks, but the key differences is that you spin up new threads for each chunk of work and each thread can reach a common variable pool. In most cases parallel programming only takes place on the local machine, and is never sent out to other computers. Again, this is because each call to a parallel task spins up a brand new thread for execution. Parallel programming can also be used to keep an interface snappy and not feel “frozen” when running a challenging task on the CPU. So you might ask yourself “Well these sound like the same deal!” In reality they are not by any means. With an asynchronous call you have no control over threads or a thread pool (which is a collection of threads) and are dependent on the system to handle the requests. With parallel programming you have much more control over the tasks chunks, and can even create a number of threads to be handled by a given number of cores in a processor. However each call to spin up or tear down a thread is very system intensive so extra care must be taken into account when creating your programming. Imagine this use case: I have an array of 1,000,000 int values. I have requested that you, the programmer, make an addition to each of these people objects to contain an internal id equal to the object’s array index. I also tell you about how the latest buzzword on the street is “multi-core processing” so I want to see patterns on that used for this assignment. Assuming you have already defined the original “person” class and wrote a “NewPerson” class with the added dimension, which pattern (asynchronous or parallel) would be preferred to break the work up and why? The correct answer of course would be the parallel pattern. Since each object is not dependent on another object from somewhere else (from something like a remote API) we can split the million objects into smaller chunks and perform the object copy and addition of the new parameter. We can then break send those chunks to different processors to conduct the execution of our code. Our code can even be designed to account for n processors in any computer, and evenly spread the work across CPU cores. Now here at Mercer I am working on a .NET web product. Our tech leads and developers have created a “Commons” library that contains factories and objects that are useful to all the sub-projects that exist in this very large .NET product. Exposed services or factories are hosted via IIS and are accessible by other projects in the product by simply referring to the “Commons” namespace. Basically the “Commons” library prevents all developers from re-inventing the wheel if they need things such as a log writer, methods to extract objects from a MSSQL database, or even methods for interoperability between projects. When it comes to the “Commons” library we are using Asynchronous calls between the server and client. We do this since a user could potentially hit one server in the cluster, then make another request that is picked up by a separate server in the cluster. It would not be helpful if we spun up a processing thread on Server A, only for the client to hit Server B (which then would have to spin up its own thread) if the cluster load balancer redirects them to Server B. Since our services are built to be asynchronous calls, all the client end has to do is pass in some session information to the server and the server can pull up the requested objects or data. If we were to use parallel processing in regards to the .NET pattern, we would be creating a ton of overhead with the constant setup and tear-down of threads within the webserver. There is also a chance the client might be redirected to another server completely by the forward facing load balancer. For our “Commons” it makes much, much more sense to just let the operating system handle sending off and receiving asynchronous calls. So this should have served as a basic compare and contrast of asynchronous and parallel programming. If you remember anything, remember this: While both patterns are used to prevent blocking within, say a User Interface, keep in mind that an asynchronous calls will use threads already in use by the system and parallel programming requires the developer to break the work up, spinup, and teardown threads needed.
https://urda.com/blog/2010/10/04/asynchronous-versus-parallel-programming
CC-MAIN-2022-21
refinedweb
910
65.56
On Display: XML Web Pages with Opera 4.0On Display: XML Web Pages with Opera 4.0 In the second article in his series examining next-generation browser XML support, Simon St.Laurent examines the Opera 4 browser, comparing its XML support with that of Mozilla, reviewed previously. If you haven't read the Mozilla article yet, I suggest you read it in tandem with this piece. - E.D. Opera 4.0 beta 2 renders XML content using an overlapping, but somewhat different, set of tools from those used by Mozilla. While much of the core is the same, some of the details, especially linking, are different. Both browsers are still pre-release, so it's probably too much to expect interoperable implementations. XML browsers are also still in uncharted territory - XLink isn't finished, the rules for using HTML with XML are still developing, and there's an enormous amount of integration work yet to be done. Opera 4.0 is built on the same combination of XML and Cascading Style Sheets (CSS) that the Mozilla project has used as its base. The core set of tools described in the previous article, including the stylesheet processing instruction and the display property of CSS2 work the same way in both Mozilla and Opera 4.0. Loading the Mozilla display property example into Opera 4.0 beta 2, shown below in Figure 1, shows that the basics work the same way. The block and inline elements are rendered properly. The lists are rendered correctly as lists, though there is a problem in Opera with the numbering of the ordered list. (There was a related issue with Opera's rendering of HTML OL lists that has supposedly been fixed - see). The table renders properly as well. Similarly, the table of books displays just as it did in Mozilla. This shared foundation means that it's now quite simple to use Mozilla and Opera as viewers for various kinds of XML documents, from documents filled with formatting to tables that need a "boxy" presentation. In the common browser role of passive viewer, these two tools can do an excellent and highly compatible job of presenting XML as the stylesheets demand. (Full compliance testing with CSS1 and CSS2 is another issue, still to be resolved - that evaluation may have to wait until a production release.) Opera does very well, if not perfectly, on lots of XML+CSS tests. The foundations are there, and seem solid. Aspects of XML browsing beyond the core of XML and CSS presentation are still difficult, yet fixable. Opening the more sophisticated book catalog that we built for Mozilla in the previous article brings up a page without displaying the expected images, and with marked links that don't work, as shown in Figure 3 below. To a considerable extent, this isn't Opera's fault. The World Wide Web Consortium hasn't issued any guidelines on what an "XML browser" would look like, or much suggestion as to how to process XML and HTML when the two are mixed together in a single document. Amaya, the W3C's own browser, provides some implementation examples, but doesn't itself support generic XML and CSS presentation. The links we created for Mozilla probably shouldn't work in Opera - they are, after all, built using a draft of XLink that's been out of date for nearly nine months. The W3C has a number of specifications in development that may change the rules yet further, notably Extensible Style Sheets and XHTML. The infrastructure needs a substantial cleanup as more and more pieces have become attached. To support linking through this time of uncertainty, Opera's designers have taken an undocumented step, which should make it easier for them to support a variety of linking approaches in XML languages in the near future. It isn't XLink, but it opens the way to describing linking semantics within Cascading Style Sheets. Perhaps best of all, it provides a way to support whatever flavor of simple links emerge from the XLink process without needing to change code. The code needed for this example was dredged from the CSS file Opera 4 uses to support WML, so it may well not be something they're encouraging developers to use in general. It would be wise for Opera to submit a more detailed explanation of what they're doing here to the W3C, and contribute to the on-and-off discussions about the relationship between stylesheets and linking. While the Opera approach is intriguing, its non-standard and undocumented (though non-damaging) nature could be improved substantially with some political work to complement the technical work they've done. Making the linking from the more sophisticated book presentation example work in Opera requires only the addition of two lines to the stylesheet. The original stylesheet looked like: catalog {display:table;} book {display:table-row;} book *{display:table-cell; padding:5px;} title {color:blue; text-decoration:underline;} The new style sheet is identical, except for the title element: catalog {display:table;} book {display:table-row;} book *{display:table-cell; padding:5px;} title {color:blue; text-decoration:underline; set-link-source:attr(href); use-link-source:current;} The two new CSS properties identify the source of the linking target information ( set-link-source), and tell the browser to use that information on the current element ( use-link-source). We've told the browser to use the href attribute as the source of the linking target, and to make that a link to the current ( title) element. The pictures still won't display, but Opera will now connect the links specified by the title elements, as shown in Figure 4. The use-link-source property does accept another value, next, in the stylesheet Opera uses for rendering Wireless Markup Language, but in this case it shuffles the links around to make the title links point to the books following them. (The link on XML Elements of Style would point to the XML Bible, and so on). The image display issues are harder to resolve, though Opera has taken the same guess that Netscape has regarding how to integrate HTML with XML, using a namespace identifying HTML elements as coming from the HTML 4.0 recommendation. Elements from the HTML vocabulary that use the namespace will be rendered as HTML. It appears that a bug in the rendering somewhere is keeping the book jackets from appearing in the table above, but hopefully this will be fixed. (In some of my experiments with images and CSS2 tables I was able to crash the Opera 4 beta 2 browser, a reminder of the perils of software that isn't quite finished.) Since the table example doesn't work, we'll try some a simpler stylesheet to demonstrate mixing HTML with XML. We'll start with a slightly modified version of the books document, adding an HTML h1 headline to it and pointing to a different style sheet: <?xml version="1.0"?> <?xml-stylesheet <html:h1>XML Books</html:h1> > ... In the new stylesheet, books4.css, we'll use block and inline elements instead of table structures to contain our images and links. We'll also tell Opera to note the link in the cover element as well as the one in the title element. catalog {display:block;} book {display:block; padding:5px;} book *{display:block;} title {color:blue; text-decoration:underline; set-link-source:attr(href); use-link-source:current;} cover {set-link-source:attr(href); use-link-source:current;} The result is shown in Figure 5 below. Opera notes the HTML origin of the h1 element, and renders it using its built-in expectations for HTML - note that we didn't specify anything in the style sheet regarding h1. Oddly, the images don't load immediately, but can be brought in - right-clicking on the word IMAGE will produce a pop-up menu that lets you load the image, presenting the scene shown in Figure 6. Clicking on either the cover (whether the image loaded or not) or the book title will activate the link and navigate to the relevant Amazon.com page. As Figure 7 shows, the same document and style sheet work well in the Netscape 6 preview release (built on Mozilla.) We've effectively built a cross-browser XML document!. Browsing XML is getting tantalizingly close! XML.com Copyright © 1998-2006 O'Reilly Media, Inc.
http://www.xml.com/lpt/a/412
crawl-001
refinedweb
1,406
58.42
I want to read two points in a picture. Most pixel values will be (0,0,0). I don't know how to take the flatted data and separate it into x,y coordinates. I use the Image library and VideoCaputre. I want to read two points in a picture. Most pixel values will be (0,0,0). I don't know how to take the flatted data and separate it into x,y coordinates. I use the Image library and VideoCaputre. i don't know much about Image library, but it's quite easy todo with pygame: # import pygame import pygame from pygame.locals import * # import our picture image = pygame.image.load('picture.bmp') for x in image.get_width(): for y in image.get_height(): # for each pixel in the image, print out it's RGB format, or RGBX (rgb and then transparency, I believe) print('%s' % str(image.get_at((x,y)) ) This is the code I have so far. I decided to go with the Image module for reading the picture instances. I use pygame to display what everything is doing. Its working well, except when I bring one dot1 higher than dot2 then bring dot2 higher than dot1 the program reverses the d.bmp and d2.bmp. I don't know if I explained it well enough to understand what's happening. You can test it for yourself to see. You'll need PIL, Pysco, VideoCaputre, and pygame I filter all light except IR. I do this with a negative from a film strip placed over the lens of the web cam. I use three layers. It eats about half of my CPU Usage. I have an intel Centrino Due Core Vista Home 64bit 4 gig RAM #hopeit with two IR points #mouse control proto #K.B. Carte # d.bmp and d2.bmp are two 7X5 images to show the two #seprate points. one is red the other is blue. import VideoCapture from VideoCapture import Device import Image, sys, pygame, time from pygame.locals import * from psyco import full full() cam = Device() pygame.init() screen = pygame.display.set_mode((640,480)) font = pygame.font.SysFont("Curier",26) d = pygame.image.load('d.bmp') dT = pygame.image.load('d2.bmp') def xy(im): imxy = [] x = 0 y = 0 while x*y <= 307200: if im.getpixel((x,y)) >= (200,200,200): imxy.append((x,y)) x += 1 if x == 640: x = 0 y += 1 if y == 480: return imxy while 1: try: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() imc = cam.getImage() bg = pygame.Surface(screen.get_size()) bg = bg.convert() bg.fill((0,0,0)) dots = xy(imc) if dots: dOne = dots[0] dTwo = dots[1] imc = pygame.image.frombuffer(imc.tostring(), (640,480), "RGB") bg.blit(imc, (0,0)) bg.blit(d, dOne) bg.blit(dT, dTwo) screen.blit(bg, (0,0)) pygame.draw.line(screen, (255,255,255), dOne, dTwo) pygame.display.flip() else: pass except IndexError: pass Don't you think you could save some CPU usage if you replaced the "while 1" by a timer which would run the loop at a certain frequency ? loop: def main(): print('in main..') if '__name__' == '__main__': main() that should work
https://www.daniweb.com/programming/software-development/threads/240812/reading-pixels
CC-MAIN-2018-47
refinedweb
536
79.77
I've been writing servlets for a better part of two years, last week I started looking at ejb. I have a good idea of how it's supposed to work and have converted one of my simpler servlets to ejb. The problem I'm having is that the client servlet is not able to create an ejb object. I dont get any exceptions, but the lookup call returns a null. I'm using jdk 1.4.0, j2ee 1.3.1, resin 2.1.9 I think it's some sort of a configuration problem in the .ear file, but things look fine to me, I'm using the sun deploy tool. thanks for your help Discussions EJB programming & troubleshooting: beginner's ejb deployment question beginner's ejb deployment question (4 messages) Threaded Messages (4) - beginner's ejb deployment question by Chetans on May 21 2003 00:15 EDT - code by Mike - on May 21 2003 14:45 EDT - beginner's ejb deployment question by Mike - on May 21 2003 14:49 EDT - beginner's ejb deployment question by Chetans on May 22 2003 12:36 EDT beginner's ejb deployment question[ Go to top ] Mike, - Posted by: Chetans - Posted on: May 21 2003 00:15 EDT - in response to Mike - There are few things you might want to check for your problem. 1. Check your entries in ejb-jar file, make sure that you have proper bean name and same is being used in your code. 2. For startars you can check documentation on JNDI and make sure you are using proper classes for finding the bean. 3. Have you generated your bean stub classes ? if you are connecting across the machine, i guess you will need these classes. Can you put your code snippet on the board so we can take look at it ? Happy working Chetan code[ Go to top ] This is the code, I can email you my .ear file if you'll look at it. - Posted by: Mike - - Posted on: May 21 2003 14:45 EDT - in response to Chetans thanx mike ----- public class Servlet extends baseServlet{ ... private static ResumeCreatorHome resumeCreatorHome = null; public void init(ServletConfig config) throws ServletException { ... try{ InitialContext ic = new InitialContext(); resumeCreatorHome = (ResumeCreatorHome)PortableRemoteObject.narrow(ic.lookup("ResumeCreator"), ResumeCreatorHome.class); }catch(Exception e){ System.err.println("exception occured\nmessage: " + e.getMessage() + "\ncause: " + e.getCause() + "\ntostring: " + e.toString()); } return; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{ ... ResumeCreator resumeCreator = null; try{ resumeCreator = resumeCreatorHome.create(); // this throws NullPointerException }catch(Exception e){ System.err.println("exception occured\nmessage: " + e.getMessage() + "\ncause: " + e.getCause() + "\ntostring: " + e.toString()); } ... return; } ... } beginner's ejb deployment question[ Go to top ] 1. The names match everywhere. - Posted by: Mike - - Posted on: May 21 2003 14:49 EDT - in response to Chetans 2. I'm not sure what you mean. 3. The client servlet and the EJB are in one archive. beginner's ejb deployment question[ Go to top ] mike !!!!!!!!!! - Posted by: Chetans - Posted on: May 22 2003 00:36 EDT - in response to Mike - why do u want your home interface to be static !!!!!!!!!! .... remember that everyting you connect to the container to get the handle for the bean, the container will pickup any bean from the pool and give handle to you. The problem with static is that somehow you want to keep live connection to this bean handle and later keep on using it for some other kind of implementation. I will sugget you not to make this stuff static. that will be the first suggestion.
http://www.theserverside.com/discussions/thread.tss?thread_id=19439
CC-MAIN-2014-35
refinedweb
589
66.74
The Developer's Challenge Existing Windows applications need not be ported to Metro, and you can keep on writing classic Windows applications using the same tools and libraries you're using the .NET Framework and .NET languages. Metro applications will require a new type of development, API, and runtime system, but nearly the same languages and programming tools that you already use. You can write them using HTML5 plus a mix of JavaScript and CSS 3. You can also use C++, Visual Basic, and C#. In all cases, XAML remains the language of choice to express the user interface. In terms of functionality, the API for native Metro applications is nearly the same as the API for .NET applications: Some namespaces have been renamed and some classes have been moved around. It's important to note, however, that Metro applications run on top of a new runtime system that wraps up the Windows kernel services in a way similar to Win32. The .NET Framework runs on top of Win32 and must use P/Invoke to call native operating system services. With WinRT the Metro runtime access to native services is more direct, and it encapsulates services differently (see Figure1). Metro applications follow the logic of mobile applications. They never run indefinitely and are subject to suspension. Likewise, Metro applications are distributed through an ad hoc marketplace, moving the burden of app certification, trial, and antipiracy measures to Microsoft. They're licensed per user and not per machine, with application settings automatically roamed via the cloud. Finally, Metro applications must declare the hardware they intend to use. Overall, writing a Metro application is similar to writing a mobile application such as one for Windows Phone 7. The nature and structure of the application is also different from traditional .NET applications, as most Metro applications tend to be simpler, more interactive, and content focused. So, is Windows 8 a big change for users and developers? Are Windows 8 and Metro applications something you must look into immediately to avoid putting your company and business at risk? Honestly, on both counts, I don't think so. Windows 8 is about continuity, but it also introduces some new approaches with Metro. As a developer, you just have one more target platform to consider, but with plenty of opportunities to leverage your existing skills to code for it. Dino Esposito has written several programming books about Microsoft technology. He will begin exploring the various facets of Windows 8 in a series of articles starting in December.
http://www.drdobbs.com/windows/what-exactly-is-windows-8/231902075?pgno=2
CC-MAIN-2016-22
refinedweb
421
55.24
The busy Java developer's guide to Scala Implementation inheritance Objects meet functions in Scala's inheritance Content series: This content is part # of # in the series: The busy Java developer's guide to Scala This content is part of the series:The busy Java developer's guide to Scala Stay tuned for additional content in this series. For the better part of 20 years, a staple of object-oriented language design has been the notion of inheritance. Languages that do not support inheritance, such as Visual Basic, are derided for being "toy languages," unsuited to real work. Meanwhile, languages that do support inheritance do so differently, leading to many hours of debate. Is multiple inheritance really necessary (as the maker of C++ decided), or is it gratuitous and ugly (as determined by the makers of C# and the Java language)? Ruby and Scala are two newer languages that have taken the middle course on multiple inheritance — as I discussed last month when introducing Scala's traits (see Related topics). Like all the cool languages, Scala also supports implementation inheritance (see Related topics). In the Java language, a single-implementation-inheritance model allows you to extend base classes and add new methods and fields, and so on. Despite some syntactic changes, Scala's implementation inheritance looks and feels much the same as it does in the Java language. The differences have to do with the ways that Scala fuses object and functional language design, and they're well worth exploring this month. Plain Old Scala Object As I've done in previous articles in this series, I'll use the Person class as a starting point for exploring Scala's inheritance system. Listing 1 shows the Person class definition: Listing 1. Hey, I'm a Person // This is Scala class Person(val firstName:String, val lastName:String, val age:Int) { def toString = "[Person: firstName="+firstName+" lastName="+lastName+ " age="+age+"]" } Person is a fairly simple POSO (Plain Old Scala Object), with three read-only fields. You might recall that to make them read-write, you need only change the values to variables in the declaration of the primary constructor. Anyway, using the Person type is also pretty trivial, as demonstrated in Listing 2: Listing 2. PersonApp // This is Scala object PersonApp { def main(args : Array[String]) : Unit = { val bindi = new Person("Tabinda", "Khan", 38) System.out.println(bindi) } } Hardly earth-shattering code, but it gives us a starting point. Abstract methods in Scala As this system develops, it becomes apparent that the Person class lacks a fairly important piece to being a Person, which is the act of doing something. Many of us define ourselves by what we do with our lives, rather than just existing and taking up space. So, I'll add a new method, shown in Listing 3, which gives Person some purpose: Listing 3. Well, doSomething! // This is Scala class Person(val firstName:String, val lastName:String, val age:Int) { override def toString = "[Person: firstName="+firstName+" lastName="+lastName+ " age="+age+"]" def doSomething = // uh.... what? } Which raises a problem: what, exactly, do Persons do? Some Persons paint, some sing, some write code, some play video games, and some don't do much of anything at all (ask any teenager's parents about that). So I need to create subclasses of Person, rather than trying to incorporate these activities directly into the Person itself, as shown in Listing 4: Listing 4. This Person does little // This is Scala class Person(val firstName:String, val lastName:String, val age:Int) { override def toString = "[Person: firstName="+firstName+" lastName="+lastName+ " age="+age+"]" def doSomething = // uh.... what? } class Student(firstName:String, lastName:String, age:Int) extends Person(firstName, lastName, age) { def doSomething = { System.out.println("I'm studying hard, Ma, I swear! (Pass the beer, guys!)") } } When I try to compile my code, I discover that it won't compile. This is because the definition for the Person.doSomething method doesn't work yet; either the method needs a full body (perhaps throwing an exception to indicate that it should be overridden in a derived class), or else it needs to have no body, similar to how an abstract method works in Java code. I try the abstract route in Listing 5: Listing 5. abstract class Person // This is Scala abstract class Person(val firstName:String, val lastName:String, val age:Int) { override def toString = "[Person: firstName="+firstName+" lastName="+lastName+ " age="+age+"]" def doSomething; // note the semicolon, which is still optional // but stylistically I like having it here } class Student(firstName:String, lastName:String, age:Int) extends Person(firstName, lastName, age) { def doSomething = { System.out.println("I'm studying hard, Ma, I swear! (Pass the beer, guys!)") } } Note how I adorned the Person class with the abstract keyword. abstract indicates to the compiler that, yes, this class is supposed to be abstract. In this regard, Scala is no different from the Java language. Objects, meet functions Due to Scala's fusing of objects and functional-language styles, I could actually model my Person, as described above, but without creating subtypes. It's a bit of a mind-warp, but it really does underscore Scala's integration of these two design styles and the very interesting ideas that come of it. Recall from previous articles that Scala treats functions as values, just as it does any other value in the language, like Int, Float, or Double. I can leverage that in this case by modeling my Person to have doSomething not as a method to be overridden in a derived class, but as a function value to be invoked, replaced, and extended. Listing 6 shows this approach: Listing 6. A hard-working Person // This is Scala class Person(val firstName:String, val lastName:String, val age:Int) { var doSomething : (Person) => Unit = (p:Person) => System.out.println("I'm " + p + " and I don't do anything yet!"); def work() = doSomething(this) override def toString = "[Person: firstName="+firstName+" lastName="+lastName+ " age="+age+"]" } object App { def main(args : Array[String]) = { val bindi = new Person("Tabinda", "Khan", 38) System.out.println(bindi) bindi.work() bindi.doSomething = (p:Person) => System.out.println("I edit textbooks") bindi.work() bindi.doSomething = (p:Person) => System.out.println("I write HTML books") bindi.work() } } This idea of using functions as first-class modeling tools is quite a common trick in dynamic languages such as Ruby, Groovy, and ECMAScript (aka JavaScript), as well as many functional languages. While it's possible to do in other languages (C++ through pointers-to-functions and/or pointers-to-member-functions, or in Java code through anonymous inner class implementations of an interface reference), it's far more work than what Scala (and Ruby, Groovy, ECMAScript, and others) demands. This is an extension of the "higher order functions" concept that functional programmers toss around. (See Related topics for more about higher order functions.) Thanks to Scala's view of functions as values, you can employ function values anywhere you might need to switch around functionality at runtime. You might recognize this approach as the Role pattern, a variation on the Gang of Four Strategy pattern where object roles (such as Person's current employment status) are better represented as runtime values than in the static type hierarchy. Constructors up the hierarchy Recall, if you will, from your days writing Java code, that sometimes a derived class needs to pass parameters from its constructor up to its base class constructor, in order to allow base class fields to be initialized. In Scala, because the primary constructor appears on the class declaration, instead of as a "traditional" member of the class, passing parameters up to the base takes on a whole new dimension. In Scala, primary constructor parameters are passed on the class line, but you can also use the val modifier on these parameters in order to easily introduce accessors (and mutators, in the case of var) on the class itself. So, the Scala class Person from Listing 5 turns into the Java class in Listing 7, as viewed by javap: Listing 7. Translation, please? // This is javap C:\Projects\scala-inheritance\code>javap -classpath classes Person Compiled from "person.scala" public abstract class Person extends java.lang.Object implements scala.ScalaObje ct{ public Person(java.lang.String, java.lang.String, int); public java.lang.String toString(); public abstract void doSomething(); public int age(); public java.lang.String lastName(); public java.lang.String firstName(); public int $tag(); } The basic rules of the JVM are still at work: derived classes of Person have to pass something up to the base class when constructed, regardless of what the language insists. (Actually, this isn't entirely true, but the JVM gets a tad grumpy when languages try to bypass this rule, so most continue to support it in one way or another.) Scala, of course, needs to adhere to this rule, not only because it wants to keep the JVM happy, but also because it wants to keep the Java base classes happy as well. So that means that, somehow, Scala has to enable a syntax allowing derived classes to call up to the base, all the while preserving the syntax that allows us to introduce those accessors and mutators on the base class. To put this into a more concrete context, let's assume I've written the Student class from Listing 5 like so: Listing 8. Bad Student! // This is Scala // This WILL NOT compile class Student(val firstName:String, val lastName:String, val age:Int) extends Person(firstName, lastName, age) { def doSomething = { System.out.println("I'm studying hard, Ma, I swear! (Pass the beer, guys!)") } } The compiler in this case will bark loud and long because I've tried to introduce a new set of methods ( lastName, and age) onto my Student class. Those methods will clash with the similarly named methods on my Person, and the Scala compiler won't necessarily know if I'm trying to override the base class methods (which would be bad because I'd be hiding the implementation and field behind those base class methods), or introduce new methods of the same name (which would be bad because I'd be hiding the implementation and field behind those base class methods). In a bit, you'll see how to successfully override methods from the base class, but that's not what we're after at the moment. You should also note that in Scala the parameters to Person's constructor don't have to line up one-to-one with the parameters passed to Student's; the rules here are exactly like those of Java's constructors. We do this just for easy reading. Also, Student can demand additional constructor parameters, as it could in the Java language, as shown in Listing 9: Listing 9. Demanding Student! // This is Scala class Student(firstName:String, lastName:String, age:Int, val subject:String) extends Person(firstName, lastName, age) { def doSomething = { System.out.println("I'm studying hard, Ma, I swear! (Pass the beer, guys!)") } } Yet again, you see how similar Scala code is to Java code, at least when it comes to inheritance and class relationships. Differences in syntax You may be wondering about the subtleties of the syntax so far. After all, Scala doesn't differentiate fields from methods the way that the Java language does. This is actually a deliberate design decision that allows Scala programmers to "hide" the distinction between fields and methods quite easily from those who use the base class. Consider Listing 10: Listing 10. What am I? // This is Scala abstract class Person(val firstName:String, val lastName:String, val age:Int) { def doSomething def weight : Int override def toString = "[Person: firstName="+firstName+" lastName="+lastName+ " age="+age+"]" } class Student(firstName:String, lastName:String, age:Int, val subject:String) extends Person(firstName, lastName, age) { def weight : Int = age // students are notoriously skinny def doSomething = { System.out.println("I'm studying hard, Ma, I swear! (Pass the beer, guys!)") } } class Employee(firstName:String, lastName:String, age:Int) extends Person(firstName, lastName, age) { val weight : Int = age * 4 // Employees are not skinny at all def doSomething = { System.out.println("I'm working hard, hon, I swear! (Pass the beer, guys!)") } } Notice how weight is defined to take no parameters and return Int? This is a "parameterless method." Because it looks strongly similar to what a "property" method looks like in the Java language, Scala will actually permit the definition of weight as either a method (as in Student) or as a field/accessor (as in Employee). This syntactical decision gives you a degree of flexibility in the implementation of abstract-class derivatives. Note that in Java, you could have the same flexibility only if every field were accessed through its get/set methods, even when being accessed from within the same class. Right or wrong, not many Java programmers write their code this way, so the flexibility isn't often used. What's more, Scala's approach works just as easily with hidden/private members as it does with public ones. From @Override to override Frequently, a derived class wants to change the behavior of a method defined in one of its base classes; in Java code, we handle this simply by adding a new method of the same name and signature to the derived class. The downside of this approach is the possibility that a typo or slight ambiguity in the signature will silently fail, which means the code will compile but "do the wrong thing" at runtime. To address this, the Java 5 compiler introduced the @Override annotation. @Override verifies for javac that a method introduced in a derived class has, in fact, overridden a base class method. In Scala, override has become part of the language, and forgetting it will generate a compiler error. Thus, a derived toString() method should look as shown in Listing 11: Listing 11. That's derivative // This is Scala class Student(firstName:String, lastName:String, age:Int, val subject:String) extends Person(firstName, lastName, age) { def weight : Int = age // students are notoriously skinny def doSomething = { System.out.println("I'm studying hard, Ma, I swear! (Pass the beer, guys!)") } override def toString = "[Student: firstName="+firstName+ " lastName="+lastName+" age="+age+ " subject="+subject+"]" } Pretty straightforward. Making it final The flip side of permitting derived overrides, of course, is the act of preventing it: Sometimes, a base class wants to forbid a child class from changing its base-class behavior, or from even having any sort of derived class whatsoever. In the Java language, we do this by applying the modifier final to the method, ensuring that it will not be overridden. Or, we might apply final to the class as a whole to prevent derivation. Implementation hierarchy works the same way in Scala: We can apply final to the method to prevent a child class from overriding it or to the class declaration itself to prevent derivatives. Bear in mind that all of this discussion about abstract and final and override applies equally to "methods with funny names" (what Java or C# or C++ programmers would call operators) as it does to routinely named methods. So it's common to define a base class or trait that sets a certain expectation for mathematical functionality (call it "Mathable," if you will) that defines abstract member functions "+", "-", "*" and "/", along with any other mathematical operations that should be supported, such as pow or abs. Then other programmers can create additional types — perhaps a Matrix class — that can implement or extend "Mathable," define those members, and look like any other built-in arithmetic type Scala provides "out of the box." The difference is in the ... If Scala maps to the Java inheritance model so easily, as you've seen so far, it should be possible to have Scala classes inherit from the Java language, and vice versa. In fact, it absolutely has to be possible because Scala, like any language that compiles to Java bytecode, has to produce objects that inherit from java.lang.Object. Note that Scala classes might also inherit from other things, too, such as traits, so how the actual inheritance resolution and code-generation works can be different, but in the end, we have to be able to inherit from Java base classes in some fashion. (Remember, traits are something like interfaces with behavior, and the Scala compiler gets this to work by splitting the trait into an interface and dropping the implementation into the class the trait is compiled into.) As it turns out, however, Scala's type hierarchy is slightly and subtly different from that of the Java language; technically, the base class from which all Scala classes inherit, including types like Int, Float, Double, and the other numeric types, is the scala.Any type, which defines a core set of methods available on any type in Scala: ==, !=, equals, hashCode, toString, isInstanceOf, and asInstanceOf, most of which are pretty easily understood by their names alone. From there, Scala splits into two major branches, where the "primitive types" inherit from scala.AnyVal, and the "class types" inherit from scala.AnyRef. ( scala.ScalaObject in turn inherits from scala.AnyRef.) Normally, this isn't something you need to worry about directly, but it can have some rare interesting side-effects when considering inheritance across the two languages. For example, consider the ScalaJavaPerson in Listing 12: Listing 12. It's a hybrid! // This is Scala class ScalaJavaPerson(firstName:String, lastName:String, age:Int) extends JavaPerson(firstName, lastName, age) { val weight : Int = age * 2 // Who knows what Scala/Java people weigh? override def toString = "[SJPerson: firstName="+firstName+ " lastName="+lastName+" age="+age+"]" } ... which inherits from this JavaPerson: Listing 13. Look familiar? // This is Java public class JavaPerson { public JavaPerson(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return this.firstName; } public void setFirstName(String value) { this.firstName = value; } public String getLastName() { return this.lastName; } public void setLastName(String value) { this.lastName = value; } public int getAge() { return this.age; } public void setAge(int value) { this.age = value; } public String toString() { return "[Person: firstName" + firstName + " lastName:" + lastName + " age:" + age + " ]"; } private String firstName; private String lastName; private int age; } When ScalaJavaPerson compiles, it will extend JavaPerson as normal, but again, as demanded by Scala, it will also implement the ScalaObject interface. It will also support the methods inherited from JavaPerson as usual. Note that because ScalaJavaPerson is a Scala type, we can expect it to support assignment into an Any reference, as per Scala's rules: Listing 14. Using ScalaJavaPerson // This is Scala val richard = new ScalaJavaPerson("Richard", "Campbell", 45) System.out.println(richard) val host : Any = richard System.out.println(host) But what happens when I create a JavaPerson in Scala and attempt to assign it to an Any reference as well? Listing 15. Using JavaPerson // This is Scala val carl = new JavaPerson("Carl", "Franklin", 35) System.out.println(carl) val host2 : Any = carl System.out.println(host2) As it turns out, this code compiles and works as expected because Scala can silently ensure that the JavaPerson "does the right thing," thanks to the similarities of the Any type to the java.lang.Object type. In fact, it's almost fair to say that anything that extends java.lang.Object also supports being stored into an Any reference. (There are a few edge cases, I'm told, but I've never run into any myself thus far.) Net result? For all practical purposes, we can mix and match inheritance across both the Java language and Scala without too much concern. (The big headache will be trying to figure out how to override a Scala "method with a funny name" like " ^=!#" or something similar.) In conclusion As I've shown you this month, the close fidelity between Scala code and Java code means that Scala's inheritance model is easy for Java developers to pick up and understand. Method overriding works the same, member visibility works the same, and so on. Of all the functionality in Scala, inheritance is probably the most similar to what you've seen in your own Java development. The only tricky part is Scala syntax, which is markedly different. Being comfortable with the overlap (and slight differences) in how the two languages approach inheritance means you can begin to comfortably write your own Scala implementations of Java programs. For example, consider Scala implementations of popular Java base classes and frameworks like JUnit, Servlets, Swing, or SWT. In fact, the Scala team produced a Swing application, called OOPScala (see Related topics), that used JTable to provide simple spreadsheet functionality in a ridiculously small number of lines of code (easily an order of magnitude less than a traditional Java equivalent). So, if you've been wondering how Scala applies to your production code, you should now be ready to take your first steps to finding out. Just think about writing certain pieces of your next program in Scala. As you've learned this month, you'll have no trouble inheriting from the appropriate base classes and providing overrides just the way you would in your Java programs. Downloadable resources Related topics - The busy Java developer's guide to Scala (Ted Neward, IBM developerWorks, 2008): Read the complete series. - "Scala for Java refugees Part 5: Traits and types" (Daniel Spiewak, Code Commit, February 2008): Another pass at the topic of inheritance in Scala. - "Implementation Inheritance with Mixins - Some Thoughts" (Debasish Ghosh, Ruminations of a Programmer, February 2008): Discusses the "workable compromises" that define Java language inheritance to date. - "A Tour of Scala: Higher-Order Functions" (Scala-lang.org): A short example of a higher order function in Scala. - "OOPScala: A Swing application written in Scala. - "Functional programming in the Java language" (Abhijit Belapurkar, developerWorks, July 2004): Understand the benefits and uses of functional programming from a Java developer's perspective. - "Scala by Example" (Martin Odersky, May 2008):. - Download Scala: Currently in version 2.7.0-final.
https://www.ibm.com/developerworks/java/library/j-scala05298/index.html
CC-MAIN-2018-30
refinedweb
3,666
52.49
On Fri, Nov 27, 2020 at 12:28 AM Steven D'Aprano steve@pearwood.info wrote: Block scoping adds semantic and implementation complexity and annoyance, while giving very little benefit. No thank you. def foo(): let x = 1 if bar: let x = 2 ... # x is 1 again here, you don't like it, don't want it, and see no value in it. I use lexical scoping all the time, and it doesn't lead to the stupidities you're implying that it does; in fact, it can be used to make code much clearer and easier to reason about, because - quite the contrary to what you're saying here - you can use distinct variable names, and have a guarantee that the variable can't be misused outside of its intended scope. This wouldn't really apply as cleanly to Python, since the rest of the function could potentially use a global with the same name, but please, stop assuming and asserting that block scoping must inherently be both useless and confusing. .) ChrisA
https://mail.python.org/archives/list/python-ideas@python.org/message/OP3TJGHYGMNQXCIC3SCV7I6DQSZJTMIE/
CC-MAIN-2021-17
refinedweb
173
64.95
It looks like you're new here. If you want to get involved, click one of these buttons! import streams import socket # import the wifi interface from wireless import wifi # uncomment the following line to use the BCM43362 driver (Particle Photon) from broadcom.bcm43362 import bcm43362 as wifi_driver streams.serial() # init the wifi driver sleep(2000) print("Init...") wifi_driver.auto_init() # a list of security strings wifi_sec=["Open","WEP","WPA","WPA2"] sleep(2000) print("Scanning for 15 seconds...") try: # start scanning for 15000 milliseconds res = wifi.scan(15000) # if everything goes well, res is a sequence of tuples # each tuple contains: # -ssid: the name of the network # -sec: the security type of the network, from 0 to 3 # -rssi: the strength of the signal, from 0 to 127 # -bssid: the mac address of the access point for ssid,sec,rssi,bssid in res: print(ssid,"::",wifi_sec[sec],":: strength ",rssi*100/127) except Exception as e: print. We hope you understand the issue and you appreciate our effort in supporting the Zerynth community, thanks for being part of it. Matteo the photon works fine on my machine with Win 10 (see image below just captured). Do you have the Zerynth libraries updated to the last versions? You can check it via Zerynth Package Manager. click the circle icon on top right corner of the ZPM column for updating the packages DB. You will se an orange icon on the top bar of the ZPM if some package is out of date. The CC3000 is a known issue we are working on it. @Giacomo should have a driver update almost ready to be released. we'll keep you posted. We are very sorry for this issue Best Daniele Zerynth Chief System Architect I still cannot get the WiFi Scan example to work on either a Arduino Due + Adafruit CC3300 or a Photon with the BCM Driver. Is this still an issue to be resolved shortly or is it me? Ken Sorry I have had issues regarding WiFi on various devices since joining via Kickstarter many months ago. Any chance of an answer to this point? There appears to be a lack of resources or intent at Zerynth to resolve issues quickly. If Zerynth is to become a significant player in the IOT space it will have to speed up development and rectification of issues otherwise it will miss the opportunity. Ken Unfortunately, the cc3000 wifi chip, as described in the official texas instruments wiki (link), is a discontinued product and Texas Instruments itself recommends CC3200 & CC3100 chip (not supported yet in Zerynth) for all new and existing embedded Wi-Fi & Internet of Things applications. In our internal tests the cc3000 chip works most of the time but we detect from time to time problems regarding signal level, scanned nets, and lost connections. Instead the BCM43362 chip mounted on the Particle Photon works well in all of our tests and we don't detect any problems; we load the wi-fi scan example on 2 different Particle Photon uncommenting the "import library" row (from broadcom.bcm43362 import bcm43362 as wifi_driver) and everything works. If you don't see anything in the serial console you should put a sleep instruction before the start of the scan because the Particle Photon is very quick and maybe it has already printed the informations when you open the serial. Another advice is that if you call other library function (like set_antenna(), etc.) you must put them in the script after the auto_init() function. Here a script that should resolve the problem: I hope that this can help you. Let me know Zerynth Support Team Have tested your code with the Photon and NodeMcu v2 and both work fine. The sensitivity of the Photon is much less than I normally get with Particle firmware. Moving on now to the HTTP Time example to see if I can get either device to connect to my WiFi network. Still cannot get result with the Due+CC3000. Does Giacomo's previous comment still apply or has the driver been updated yet? Ken The site "/" appears to no longer exist, therefore the example fails. I have tried testing with the HTTP Weather example which appears to work fine, proving connectivity. It is a pity that Zerynth examples which do not work have not been either fixed or removed. It is also a pity that the examples have not been updated to reflect the growing number of platforms Zerynth works on. For example the ZerynthApp Basic example does not include many WiFi drivers. If new users are to grasp the value of Zerynth quickly, good working examples give a great start-up experience. Ken Ken thanks for your very helpful feedback and suggestions. We are working hard day by day to improve the Zerynth usability and user experience but keeping track of all the changes happening on the web is a big challenge... this is why we have a community Thanks again for your support! Zerynth Chief System Architect The Arduino Due plus CC3000 work fine using Arduino code. Can you confirm .... 1. the CC3000 drivers should work with r2.0.5 and the Due? 2. if not when is it anticipated that this will be resolved? 3. or is it the example code? For information, the Due Programming Port seems to be unavailable for uploading after the WiFiScan has been run until I reconnect the Due. Situation with CC3000 as before, still not working with Zerynth but OK with PlatformIO and Arduino IDE. Been discussing this issue for a long time without success. Do you intend to fix the library for the CC3000 Or are you not intending to support it going forward? K.Zerynth libraries for Microchip MCW1001A, Microchip WINC1500, and STM SPWF01SA wi-fi chips are now available and we invite you choosing the most suitable for your projects. Other new wi-fi chips libraries will arrive in the early future. We hope you understand the issue and you appreciate our effort in supporting the Zerynth community, thanks for being part of it. Matteo Zerynth Support Team
https://community.zerynth.com/discussion/380/wifi-drivers-for-cc3000-and-bcm43362-cannot-get-working
CC-MAIN-2017-26
refinedweb
1,016
71.55
Each Answer to this Q is separated by one/two green lines. I use Jupyter Notebook to make analysis of datasets. There are a lot of plots in the notebook, and some of them are 3d plots. I’m wondering if it is possible to make the 3d plot interactive, so I can later play with it in more details? Maybe we can add a button on it? Clicking it can pop out a 3d plot and people can zoom, pan, rotate etc. My thougths: 1. matplotlib, %qt This does not fit my case, because I need to continue plot after the 3d plot. %qt will interfere with later plots. 2. mpld3 mpld3 is almost ideal in my case, no need to rewrite anything, compatible with matplotlib. However, it only support 2D plot. And I didn’t see any plan working on 3D (). 3. bokeh + visjs Didn’t find any actualy example of 3d plot in bokeh gallery. I only find, which uses visjs. 4. Javascript 3D plot? Since what I need is just line and surce, is it possible to pass the data to js plot using js in the browser to make it interacive? (Then we may need to add 3d axis as well.) This may be similar to visjs, and mpld3. try: %matplotlib notebook EDIT for JupyterLab users: Follow the instructions to install jupyter-matplotlib Then the magic command above is no longer needed, as in the example: # Enabling the `widget` backend. # This requires jupyter-matplotlib a.k.a. ipympl. # ipympl can be install via pip or conda. %matplotlib widget # aka import ipympl import matplotlib.pyplot as plt plt.plot([0, 1, 2, 2]) plt.show() Finally, note Maarten Breddels’ reply; IMHO ipyvolume is indeed very impressive (and useful!). There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn’t do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I’m the author) You may go with Plotly library. It can render interactive 3D plots directly in Jupyter Notebooks. To do so you first need to install Plotly by running: pip install plotly You might also want to upgrade the library by running: pip install plotly --upgrade After that in you Jupyter Notebook you may write something like: # Import dependencies import plotly import plotly.graph_objs as go # Configure Plotly to be rendered inline in the notebook. plotly.offline.init_notebook_mode() # Configure the trace. trace = go.Scatter3d( x=[1, 2, 3], # <-- Put your data instead y=[4, 5, 6], # <-- Put your data instead z=[7, 8, 9], # <-- Put your data instead mode="markers", marker={ 'size': 10, 'opacity': 0.8, } ) # Configure the layout. layout = go.Layout( margin={'l': 0, 'r': 0, 'b': 0, 't': 0} ) data = [trace] plot_figure = go.Figure(data=data, layout=layout) # Render the plot. plotly.offline.iplot(plot_figure) As a result the following chart will be plotted for you in Jupyter Notebook and you’ll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one. A solution I came up with is to use a vis.js instance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page A small notebook to illustrate this: demo The code itself: from IPython.core.display import display, HTML import json def plot3D(X, Y, Z, height=600, <script src=""></script> <div id="pos" style="top:0px;left:0px;position:absolute;"></div> <div id="visualization"></div> <script type="text/javascript"> var data = new vis.DataSet(); data.add(""" + json.dumps(data) + """); var </iframe>" display(HTML(htmlCode)) For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless. A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D
https://techstalking.com/programming/python/python-matplotlib-make-3d-plot-interactive-in-jupyter-notebook/
CC-MAIN-2022-40
refinedweb
681
66.23
The busy Java developer's guide to db4o Queries, updates, and identity Count the ways to query in db4o Content series: This content is part # of # in the series: The busy Java developer's guide to db4o This content is part of the series:The busy Java developer's guide to db4o Stay tuned for additional content in this series. In the first article in this series I discussed the failure of the RDBMS as a solution for Java™ object storage. As I explained, an object database like db4o simply has more to offer to object-oriented developers, in today's object-oriented world, than its relational cousins. 1: Listing 1. The Person class; } As POJOs go, Person is hardly a complex beast.." This style of query uses a prototype object (the one passed in to the get() call) to decide if objects in the database match and returns an ObjectSet (essentially a collection) of those objects that match the criteria. Listing 2. Query by Example()); } finally { if (db != null) db.close(); } } } Rules of query. In a table, this call would roughly correspond to an SQL query of SELECT * FROM Person WHERE firstName = "Brian". (Be careful, though, about trying to map OODBMS queries to SQL: the analogy isn't perfect and can lead to misunderstanding about the nature and performance of particular queries.) The returned object from a query is an ObjectSet, which is similar to a JDBC ResultSet in that it's a simple container of objects. Walking the results is a simple exercise in using the Iterator interface implemented by ObjectSet. Using the particular methods of Person would require a downcast on the objects returned by Updates and identity. The simple example in Listing 3 demonstrates this differing notion of identity: Listing 3. The three Brians()); Person brian2 = new Person("Brian", "Goetz", 39);db.set(brian2);db.commit(); // Find all the Brians ObjectSet brians = db.get(new Person("Brian", null, 0)); while (brians.hasNext()) System.out.println(brians.next()); } finally { if (db != null) db.close(); } } } When you run the query in Listing 3, the database reports three Brians, two of them Brian Goetz. (A similar effect would occur if the persons.data file already existed in the current directory -- all of the Persons created would be stored into the persons.data file, and all the Brians stored there would be returned by the query.) Clearly, the old rules regarding primary keys aren't in force here; so how does an object database deal with notions of uniqueness? Embrace the OID When an object is stored into an object database, a unique key is created, called an Object identifier or OID (pronounced similarly to the last syllable of avoid), which uniquely identifies that object. The OID, like the this pointer/reference found in C# and Java programming, is silent unless explicitly requested. In db4o, the OID for a given object can be found through a call to db.ext().getID(). (You can also use the db.ext().getByID() method to retrieve objects by OID. 4: Listing 4. Query before inserting // ... as before ObjectContainer db = null; try { db = Db4o.openFile("persons.data"); ... // We want to add Brian Goetz to the database; is he already there? if (db.get(new Person("Brian", "Goetz", 0).hasNext() == false) { // Nope, no Brian Goetz here, go ahead and add him db.set(new Person("Brian", "Goetz", 39)); db.commit(); } } 39.) If you want to modify the object in the database, it's simple to take the object retrieved from the container, modify it in some way, and then store it back, as shown in Listing 5: Listing 5. Updating an object // ... as before ObjectContainer db = null; try { db = Db4o.openFile("persons.data"); ... // Happy Birthday, David Geary! if ((ObjectSet set = db.get(new Person("David", "Geary", 0))).hasNext()) { Person davidG = (Person)set.next();davidG.setAge(davidG.getAge() + 1);db.set(davidG);db.commit(); } else throw new MissingPersonsException( "David Geary doesn't seem to be in the database"); }. A search utility method.set() to poke that value into my template object. Once that's all done, I call get() on the db4o database and check to see if the ObjectSet returned contains any objects. This gives me a basic method outline that looks like the one shown in Listing 6: Listing 6. A utility method for doing QBE identity searches import java.lang.reflect.*; import com.db4o.*; public class Util { public static boolean identitySearch(ObjectContainer db, Class type, String[] fields, Object[] values) throws InstantiationException, IllegalAccessException, NoSuchFieldException { // Create an instance of our type Object template = type.newInstance(); // Populate its fields with the passed-in template values for (int i=0; i<fields.length; i++) { Field f = type.getDeclaredField(fields[i]); if (f == null) throw new IllegalArgumentException("Field " + fields[i] + " not found on type " + type); if (Modifier.isStatic(f.getModifiers())) throw new IllegalArgumentException("Field " + fields[i] + " is a static field and cannot be used in a QBE query"); f.setAccessible(true); f.set(template, values[i]); } // Do the query ObjectSet set = db.get(template); if (set.hasNext()) return true; else return false; } } Obviously a great deal could be done to tune this method to taste, such as catching all of the exception types and rethrowing them as runtime exceptions instead, or returning the ObjectSet itself instead of true/false, or even returning an array of objects containing the contents of the ObjectSet (which would then make it easy to check the length of the returned array). What is apparent from Listing 7, however, is that its usage is arguably not much simpler than the basic QBE version shown already: Listing 7. The utility method at work // Is Brian already in the database? if (Util.identitySearch( db, Person.class, {"firstName", "lastName"}, {"Brian", "Goetz"}) == false) { db.set(new Person("Brian", "Goetz", 39)); db.commit(); } Actually, much of the utility method's utility become apparent when placed onto the stored class itself, as shown in Listing 8: Listing 8. Using the utility method from within Person public class Person { // ... as before public static boolean exists(ObjectContainer db, Person instance) { return (Util.identitySearch(db, Person.class, {"firstName", "lastName"}, {instance.getFirstName(), instance.getLastName()}); } }. Advanced queries So far you've seen how to query for individual objects, or objects that meet a particular criteria. Although this makes for a fairly easy way to issue queries, it also makes for somewhat limited options; for example, what if you needed to retrieve all Persons whose last name started with G, or all Persons of an age greater than 21? A QBE approach would fail pretty badly for these types of queries because QBE does equality matches, not comparison. Historically, even moderately complex comparison has been a weakness of the OODBMS and a strength of the relational model and SQL. Issuing a comparison query in SQL is trivial, but to do the same in the OODBMS required one of several unappealing approaches: - Fetch all the objects and do the relative comparison yourself. - Extend the QBE API to include predicates. - Create a query language to be translated into a query against your object model. Weak on comparison. (This is not an indictment of the OODBMS, by the way -- fetching a million rows across a network connection may be within the RDBMS server's capabilities, but it will still crush the network it's on.) The second option pollutes the simplicity of the QBE approach and leads to monstrosities like the one shown in Listing 9: Listing 9. A QBE call with predicates Query q = new Query(); q.setClass(Person.class); q.setPredicate(new Predicate( new And( new Equals(new Field("firstName"), "David"), new GreaterThan(new Field("age"), 21) ))); q.Execute();. In the past, the OODBMS folks created a standard query language, Object Query Language, or OQL, which looked something like what you see in Listing 10: Listing 10. A snippet of OQL SELECT p FROM Person WHERE p.firstName = "David" AND p.age > 21 On the surface, OQL seems remarkably similar to SQL, and thus supposedly just as powerful and easy to use. The drawback of OQL is that it wants to return ... what?. Native queries in db4o Rather than force a complex query API onto developers or introduce a new "something-QL," db4o offers a facility called native queries, which is both powerful and remarkably easy to use, as you can begin to see in Listing 11. (A query API for db4o is available in the form of SODA queries, which are used principally for fine-grained query control. As you'll see in a second, however, SODA is generally only necessary for hand-optimizing queries.) Listing 11. A db4o native query // ... as before ObjectContainer db = null; try { db = Db4o.openFile("persons.data"); ... // Who wants to get a beer? List<Person> drinkers = db.query(new Predicate<Person>() { public boolean match(Person candidate) { return person.getAge() > 21; } } for (Person drinker : drinkers) System.out.println("Here's your beer, " + person.getFirstName()); }. Either a source preprocessor has to be used to translate the source file with the query in it into something the database engine understands (a la SQL/J or other embedded preprocessors of note), or the database is sending all the Person objects back to the client where the predicate is executed against the complete set (in other words, exactly the approach rejected earlier).. (Sort of a "JQL" -- Java Query Language -- if you will. But please don't repeat that name to the db4o developers; you'll get me in trouble.) Let db4o tell you ....out.println in your Java code, or System.Console 12: Listing 12. DiagnosticListener // ... as before ObjectContainer db = null; try { db = Db4o.openFile("persons.data"); db.ext().configure().diagnostic().addListener(new DiagnosticListener() { public void onDiagnostic(Diagnostic d) { if (d instanceof NativeQueryNotOptimized) { // could display information here, but for simplicity // let's just fail loudly throw new RuntimeException("Native query failed optimization!"); } } }); } Obviously, this would only be desirable during development -- at runtime it would be preferable to log this failure to a log4j error stream or something equally less distracting to the user. In conclusion In this second article in The busy Java developer's guide to db4o, I used the OODBMS notion of identity as a launching point for explaining how db4o stores and retrieves objects, as well as introducing its native query facility. QBE is the preferred mechanism for simple query situations because it's an easier API to work with, but it does require that your domain objects permit any or all of the fields containing data to be set to null, which may violate some of your domain rules. For example, it would be nice to be able to enforce both a first name and a last name for Person objects. Using Person in a QBE query for just last name, however, mandates that the first name be allowed to be null, which effectively means we either have to choose the domain constraint or the query capability, neither of which is entirely acceptable. Native queries provide a powerful way to execute complex queries without having to learn a new query language or resort to complicated object structures to model a predicate. And for those situations where db4o's native query facility fails to meet the need, the SODA API (which originally appeared as a standalone query system for any object system, and still lives on SourceForge) allows you to tune the query down to its tiniest detail, at the expense of simplicity. This multi-faceted approach to querying databases may strike you as complex and confusing and entirely different from how an RDBMS works. In truth, this isn't quite the case: Most large-scale databases translate SQL text into a bytecode format that is analyzed and optimized and then executed against the data stored on disk, assembled back into text, and returned. The db4o native query approach puts the compilation into bytecode back into the hands of the Java (or C#) compiler, thus allowing for type safety and earlier detection of incorrect query syntax. (Type safety is sadly missing from JDBC's approach to accessing SQL, by the way, because it is a call-level interface and is thus restricted to strings that can only be checked at runtime. This is true of any CLI, not just JDBC; ODBC and .NET's ADO.NET suffer from the same limitation.) Optimization is still done inside the database, but instead of text being returned real objects are sent back, ready for use. This is in marked contrast to the SQL/Hibernate or other ORM approach, which Esther Dyson famously described as follows: Using tables to store objects is like driving your car home and then disassembling it to put it into the garage. It can be assembled again in the morning, but one eventually asks whether this is the most efficient way to park a car. Indeed. See you next time. Downloadable resources Related topics - The busy Java developer's guide to db4o (Ted Neward, developerWorks, March 2007): Read the other parts in this series. - "Object Databases: Not Just for CAD/CAM Anymore" (Gregory Meinke, 1996): Makes the case for the object database. - "The Vietnam of Computer Science" (Ted Neward, The Blog Ride, June 2006): A point-by-point examination of the weaknesses of object-relational mapping. - ODBMS.Org: An excellent collection of free materials on object database technology. - Simple Object Database Access (SODA): An object API to communicate with databases.
https://www.ibm.com/developerworks/java/library/j-db4o2/index.html
CC-MAIN-2017-26
refinedweb
2,227
54.42
What is a Component Components are the most basic building blocks of an Angular application. A Real-world angular application will have tens to a few hundreds of components. Some of them are reusable and some of them or not. But what actually is a component? We can define a component as a small block or part of a page that has its own template, style, selector and properties. An Angular app should have at least one component. Take this site as an example. The homepage of this site has a navigation bar, sidebar, and an area to display the most recent posts. We can call these three sections as three different components. Every Angular app is a tree of components. Starting with the app component as the base. A component usually has four files. - <name>.component.ts – This is where we write the logic. - <name>.component.html – Holds HTML markup of the component. - <name>.component.css – Defines styles (CSS) for the component. - <name>.component.spec.ts – The .spec.ts files are for unit tests for individual components. The app component As we have seen earlier, App component is the root of an Angular application. You might have noticed that the home page has some content in it. Where did it come from? Let’s find out. Open the app.component.html file. This is the HTML markup of our app component. Replace its contents with this code. <h1>Welcome to my first Angular app</h1> Now come back to the browser. You will notice that the default content of our home page is replaced with our welcome message. So, what we saw in the home page was from app.component.html. Let’s add some style Now, let us add some style to our app component. To style the app component, open app.component.css and replace its content with this. h1{ color: dodgerblue; text-align: center; } Open your browser to see the output. Exploring app.component.ts Let’s have a look at the code of app.component.ts. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'LearnAngular'; } From this code, it is clear that every component is a class. Here the name of our class is AppComponent. But what are these @Component, selector, templateUrl, and styleUrls? @Component All components including AppComponent is basically a typescript class. To mark this class as a component, we should add some metadata to it using @Component decorator. This metadata helps Angular to decide how the component should be processed. Properties / metadata selector – This is a unique string that Angular uses to decide where the component should be displayed. Whenever angular finds an HTML tag with the name of a selector, it displays the corresponding component is displayed within the tags. To see this in action, open index.html in src folder. You will see these lines in the markup. <body> <app-root></app-root> </body> We saw that app-root was the selector of appComponent. So, Angular will automatically place the content of appComponent within these tags. Here’s the final output from the browser’s console. <body data- <app-root <div _ngcontent- <!-- Code removed for brevity --> </div> <router-outlet</router-outlet> </app-root> <!-- Code removed for brevity --> </body> - templateUrl – This is the reference to the HTML Markup of our component. - styleUrls – A list that contains references to the style sheets of our component. Create a new component Fortunately, Angular CLI allows us to create new components with a single-line command. Open a new terminal in the project folder and run ng g c <component_name>. This will create a new component and register it in app.module.ts. 💡We should register every component in the app_name.module.tsfile before using it. ng g c employees You will get an output similar to this. PS C:\Users\Username\Desktop\Angular\LearnAngular> ng g c employees CREATE src/app/employees/employees.component.html (24 bytes) CREATE src/app/employees/employees.component.spec.ts (649 bytes) CREATE src/app/employees/employees.component.ts (281 bytes) CREATE src/app/employees/employees.component.css (0 bytes) UPDATE src/app/app.module.ts (487 bytes) The last line tells that our new component is registered in app.module.ts. Registering components manually To register a component in app’s module.ts file, add reference to the component and specify it in the declerations list. import { EmployeesComponent } from './employees/employees.component'; @NgModule({ declarations: [ AppComponent, EmployeesComponent ], imports: [ // Code removed for brevity ], // Code removed for bevity }) Replace EmployeeComponent with the name of your component. Displaying the component To display the component, replace the content of app.component.htmlwith this markup. <app-employees></app-employees> Save the file and open the browser and verify the output. In the next post, we’ll learn how to display a list of employees in the component.
https://www.geekinsta.com/angular-tutorial-working-with-components/
CC-MAIN-2020-40
refinedweb
816
52.56
sc_ProcThreadGrp - Man Page The ProcThreadGrp class privides a concrete thread group appropriate for an environment where there is only one thread. Synopsis #include <thread.h> Inherits sc::ThreadGrp. Public Member Functions ProcThreadGrp (const Ref< KeyVal > &) int start_threads () Starts the threads running. int wait_threads () Wait for all the threads to complete. Ref< ThreadLock > new_lock () Return a local object. ThreadGrp * clone (int nthread=-1) Create a ThreadGrp like the current one. Additional Inherited Members Detailed Description The ProcThreadGrp class privides a concrete thread group appropriate for an environment where there is only one thread. Member Function Documentation ThreadGrp* sc::ProcThreadGrp::clone (int nthread = -1) [virtual] Create a ThreadGrp like the current one. If nthread is given, the new ThreadGrp will attempt to support that number of threads, but the actual number supported may be less. If nthread is -1, the number of threads in the current group will be used. Reimplemented from sc::ThreadGrp. int sc::ProcThreadGrp::start_threads () [virtual] Starts the threads running. Thread 0 will be run by the thread that calls start_threads. Implements sc::ThreadGrp. int sc::ProcThreadGrp::wait_threads () [virtual] Wait for all the threads to complete. This must be called before start_threads is called again or the object is destroyed. Implements sc::ThreadGrp. Author Generated automatically by Doxygen for MPQC from the source code.
https://www.mankier.com/3/sc_ProcThreadGrp
CC-MAIN-2021-21
refinedweb
215
59.4
No way to create slice objects I tried to slice a numpy array but this doesn't work since Ruby doesn't understand Python's slice syntax. If I could create a slice object using the Python built-in slice function, I could get around this by passing a slice object to Numpy's getslice method, but afaik there's no way to access this. Perhaps RubyPython could provide a built-in for this? Access to other Python built-ins would be nice as well, though less necessary. Specifically, access to len and type would be handy. You can accomplish what I wanted by writing a python module such as the one below. I suggest updating the rubypython intro to suggest this. If a module with all the built-ins can come standard (or maybe it already does?) even better. Thanks! --- python module --- import builtin def slice(a=None,b=None,c=None): return builtin.slice(a,b,c) The RubyPython::PyMain object should provide access to python builtins. Does this not work to create a slice? Thanks, I didn't know that was there. I suggest updating the main page: and RDoc to alert users of the ability to access built-ins this way. RubyPython::PyMain.slice(2,3,4) works fine. Thanks very much Cloned as. Please follow the issue there.
https://bitbucket.org/raineszm/rubypython/issues/22/no-way-to-create-slice-objects
CC-MAIN-2017-26
refinedweb
223
84.37
The in the following example: [DllImport("avifil32.dll")] private static extern void AVIFileInit(); The extern keyword also can define an external assembly alias, making it possible to reference different versions of the same component from within a single assembly. For more information, see extern alias (C# Reference).. The extern keyword is more limited in use than in C++. To compare with the C++ keyword, see Using extern to Specify Linkage in the C++ Language Reference.. // cmdll.c // compile with: /LD int __declspec(dllexport) SampleMethod(int i) { return i*10; } This example uses two files, CM.cs and Cmdll.c, to demonstrate extern. The C file is the external DLL created in Example 2 that is invoked from within the C# program. // cm.cs using System; using System.Runtime.InteropServices; public class MainClass { [DllImport("Cmdll.dll")] public static extern int SampleMethod(int x); static void Main() { Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5)); } } SampleMethod() returns 50. To build the project: Compile Cmdll.c to a D
http://msdn.microsoft.com/en-us/library/e59b22c5(VS.80).aspx
crawl-002
refinedweb
165
53.68
Details Description Currently the InteractiveShell (aka. groovysh) class is written in Java... and well, AFAICT there is no good reason for that. So re-write it in Groovy Activity Any hints on how to get the underlying GroovyShell instance to remember things? Seems like it doesn't do that at all right now. Perhaps the SourceUnit needs to be inspected and then use that information to pull out bits from the compiled script... er something? As you'll evaluate new scripts with GroovyShell, you can pass a binding containing variables. So in this binding, you can put MethodClosures wrapping methods defined in previous scripts. Okay, and I'm guessing that previously defined classes should already stick na? What about things like: def foo = "bar" And more so... how does one figure out what methods (and or simple defs like above) were defined? Seems that the binding does not capture those (unfortunately IMO), so I'm probably going to have to use the SourceUnit to track those down? def foo = "bar" is a local variable, so we won't be able to capture it and put into the binding, but: foo = "bar" will go in the binding of the script by default. For methods, as if you evaluate this script: def err(msg) { System.err.println(msg) } you will have to introspect the Script class that is compiled to retrieve the methods that have been defined on it. Then, you wrap that in a MethodClosure that you keep inside the binding as 'err' (for the key), and the method closure for the value, so that later on, people can call err('hi') (in fact, the script will retrieve the err property in the binding, and as it's a closure, will call it) The trickier thing is probably how to memorize the imports :-/ An idea could be to "catch" the imports as if they were shell commands, then you keep them somewhere in memory. You could append them to the script evaluated, but you'd loose the right line number information. So a better approach, ideally, would be to use the GroovyClassLoader and add imports transparentely when the script is compiled. See blackdrag's blog for some ideas: This is also a technique that Alexandru Popescu used to add TestNG imports automatically in his Test'N'Groove project: Look at the end of this file to see how to do that: The last thing also that would be needed would be to remember class definitions, so that you can define a class in a first script: class A {} and then in another script execution being able to create new instances: new A() There might be some tricks with classloaders to make that possible though, and I'm not sure yet how to best do that. Perhaps Jochen can give some perspective on this. This is done, enable with NEWSHELL=t ./bin/groovysh atm. Requirements:
http://jira.codehaus.org/browse/GROOVY-2053?focusedCommentId=104945&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2014-42
refinedweb
483
65.96
The homepage for OsmSharp brags about having documentation, but it is minimal and horribly out of date! I was using version 4.2.0.723, but recently updated to 5.0.6. I thought that maybe I was the one who was out of date, but even after the update the documentation is incorrect and does not help. The only change was that all the namespaces were changed and some classes were removed or added. I still don't have a single clue how to filter the data! I would like to filter using a bounding box. Any help would be much appreciated! asked 30 Jan '17, 09:29 Kapten-N 41●2●2●6 accept rate: 0% Have you tried to contact the developer of OsmSharp by email or similar? What is the result? Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown This is the support site for OpenStreetMap. Question tags: filter ×47 filtering ×15 documentation ×4 osmsharp ×4 question asked: 30 Jan '17, 09:29 question was seen: 841 times last updated: 30 Jan '17, 19:22 Isolating buildings (and all member ways) using the Filter objects tool How to filter tags Filtering footprints to given bounding box Edit certain subsets of objects in JOSM It is possible hide Hotels And Restaurants? (on extracted maps) Filter relation by member tag How can I download a subset of the data for a large area? Is there any documentation ready to be read in a ebook reader? Relation Filtering issue Highway Filtering First time here? Check out the FAQ!
https://help.openstreetmap.org/questions/54349/how-do-i-filter-with-osmsharp
CC-MAIN-2020-45
refinedweb
275
71.75
Today marks a big milestone: V-Play is now called Felgo and got a new facelift. In this article you will learn: - Why we did the rebranding from V-Play to Felgo - Why this will benefit you - What the Felgo roadmap looks like - How to update to the latest Felgo release Reasons for Rebranding V-Play to Felgo The first official version of V-Play was released 2012. We started to work on the first alpha versions in 2009. Back in these days, the main focus area was games. Thus the first APIs were tailored for making cross-platform game development simple and fast to develop. Interestingly, we saw that many customers used the V-Play APIs and the underlying Qt framework to develop mobile business apps, not only for games. Because many of the APIs we provided were also useful for apps. In addition, a new trend in app development emerged: business apps started to have custom UI and many animations, similar as they are used in games. This led to a first release of V-Play Apps in 2015. This release contained a specialized set of APIs as part of the V-Play framework to make development easier for software engineers targeting mobile apps, in addition to the already available game APIs. Features like abstracting the different native navigation paradigms of iOS + Android to a single Navigation component, or the native style for Android Material design or Apple Cupertino design made these APIs popular and increased the growth of V-Play developers. Since this release, the most common question we got was: “But V-Play is only for games, right?” The answer to this question is and always has been: NO. It is perfectly suited for mobile app development. And it allows a lot more things like: - Develop for desktop platforms with a single code base - Develop for embedded & IoT platforms - Develop for the web (see the roadmap section below) - Cloud services for user authentication, data storage, chat, gamification services and more In addition, we provide - App Development Services to create a mobile app for you or together with your dev team - Qt Trainings - Qt Consulting services With such a wide field of use cases and services, the initial name held us back and caused a wrong first impression. This is going to change today. V-Play is now called Felgo All products and tools, website content, social pages and dev accounts like our Github page are now called Felgo. What does Felgo mean? Felgo is an acronym for the 2 V-Play founders names, Christian FELdbacher and Alex LeutGOeb. It is a short & catchy name, easy to type and remember. It allows to become more independent of the actual product and services and provides flexibility for all the new features to come. What does the Felgo Rebranding Mean for Me as a developer? Most importantly, all your existing apps work without modification – you do not need to change your existing code after updating to today’s Felgo 3.0 release. New features, however, will only be available with the new Felgo import. The new import makes it easier to develop with Felgo. See the upgrade guide below how to change it. You can reach the new website on. All previous links to the v-play.net domain still work and are redirected to this new domain. The new name allows us to grow even faster than before, because there is no wrong first impression that Felgo is a games-only framework. Felgo is for games, apps, and many more use cases. Accelerated growth means even more features you can expect. And as a bonus, you will have an easier time telling your co-workers and friends about Felgo and what you can use it for. 🙂 Felgo Roadmap We have been working on several bigger additions for Felgo that will be available in the coming months. You can expect these new features: - Felgo Cloud Build: you will be able to let your app or game build in the cloud, either on our servers or on-premise. You can connect your Git repository or upload a zip file to perform all steps needed in the development process of apps: build, sign, upload for testing or release to the app stores. This service will be available for mobile, Desktop, embedded and Web. It will also allow you to distribute an app to the iOS App store without a Mac, and build for all platforms in parallel. - Web Platform Support: You will be able to publish your existing app to the Web with a single code base. - Felgo Cloud IDE: Setting up a working development environment for many target platforms can be tricky and time-consuming. With our new cloud-based development IDE, you can develop and even publish any app to all target platforms, without any development setup. You will be able to connect your Git repository and test, debug, and preview your app in the browser, and deploy it to mobile, desktop, embedded and web platforms. Combined with the Cloud Build service, you can distribute your app or build updates from within your browser. - Felgo Hot Reload: We have seen great development satisfaction after the Felgo Live Code Reloading feature, which allows you to see changes in your code instantly on all connected devices, for iOS, Android, embedded & Web. With the upcoming Hot Reload feature, you will be able to iterate and develop even faster, because also the state of the app is preserved at a live reload. - Native App Integration: it will become a lot easier to integrate native iOS & Android code to your Felgo apps. You will also be able to integrate a Felgo app or single pages easily into an existing native app. - Embedded & IoT: We will make development for Raspberry Pi, Arduino, i.MX and other popular embedded platforms easier. If you’d like to get early access to any of these topics, just contact us. What’s New in the Felgo 3.0 Release – Upgrade Guide 1. Apps, Games and Plugins Combined in Felgo You no longer need to use different import statements when working with Felgo. The components of the Felgo Apps, Felgo Games and Felgo Plugins API modules are all available with a single import Felgo 3.0 statement: import Felgo 3.0 // old: // import VPlay 2.0 // import VPlayApps 1.0 // import VPlayPlugins 1.0 import QtQuick 2.0 App { // Storage, required import VPlay 2.0 before Storage { } // NavigationStack, required import VPlayApps 1.0 before NavigationStack { Page { title: "AdMob Page" // AdMob Plugin, required import VPlayPlugins 1.0 before AdMobBanner { adUnitId: "ca-app-pub-3940256099942544/6300978111" // banner test ad by AdMob testDeviceIds: [ "" ], without any changes. But we suggest to update your projects for the Felgo import. 2. Improved Component Names Especially for the Felgo // old: SpriteSequenceVPlay SpriteSequence { id: spriteseq defaultSource: "spritesheet.png" // old: SpriteVPlay Sprite { name: "walk" frameWidth: 32 frameHeight: 32 frameCount: 4 startFrameColumn: 1 frameRate: 20 to: {"jump":0, "walk": 1} } // old: with a removed ‘VPlay’ suffix in their name: - Scene3DVPlay → Scene3D - CameraVPlay → Camera - AnimatedSpriteVPlay → AnimatedSprite - SpriteVPlay → Sprite - SpriteSequenceVPlay → SpriteSequence - TexturePackerAnimatedSpriteVPlay → TexturePackerAnimatedSprite - TexturePackerSpriteVPlay → TexturePackerSprite - TexturePackerSpriteSequenceVPlay → TexturePackerSpriteSequence - SoundEffectVPlay → SoundEffect - ParticleVPlay → Particle When you update your project to the new Felgo 3.0 import, please also make sure to use the new names for these components if you use them. The name changes only apply for the Felgo module import. Your existing project with V-Play imports is not affected and can still use the old names. 3. Renamed FelgoGameNetwork, FelgoMultiplayer and SocialView } } 4. Felgo Project Configuration and FelgoApplication To integrate the Felgo SDK in your project, set CONFIG += felgo in your *.pro configuration: # allows to add DEPLOYMENTFOLDERS and links to the Felgo library and QtCreator auto-completion CONFIG += felgo # old: CONFIG += vplay # uncomment this line to add the Live Client Module and use live reloading with your custom C++ code # for the remaining steps to build a custom Live Code Reload app see here: # CONFIG += felgo-live # old: CONFIG += vplay-live The previous CONFIG += v-play setting is still supported. For live reloading with custom C++ code, the CONFIG += v-play # old: VPLAY_PLUGINS += admob } In your main.cpp, the Felgo application and Live Client class names also got renamed: #include <QApplication> #include <QQmlApplicationEngine> #include <FelgoApplication> // old: #include <VPApplication> // uncomment this line to add the Live Client Module and use live reloading with your custom C++ code //#include <FelgoLiveClient> // old: #include <VPLiveClient> int main(int argc, char *argv[]) { QApplication app(argc, argv); FelgoApplication felgo; // old: VPApplication vplay; // ... // to start your project as Live Client, comment (remove) the lines "felgo.setMainQmlFileName ..." & "engine.load ...", and uncomment the line below //FelgoLiveClient client (&engine); // old: VPLiveClient client (&engine); return app.exec(); } Similar to other changes of this update, the previous class names and includes are still supported as well. 5. Deprecated Components With the power of Felgo Apps at hand, there’s no need to use outdated controls that were part of the Games module. You can take advantage of Felgo Apps Controls and Qt Quick Controls 2 for your games instead. To make the difference clear and match the name pattern of Felgo app controls like AppButton, those game controls now prepend ‘Game’. In case a ‘VPlay’ suffix was used, it is removed: - ButtonVPlay → GameButton - SliderVPlay → GameSlider - SwitchVPlay → GameSwitch - TextFieldVPlay → GameTextField - ScrollViewVPlay → GameScrollView Those types are also marked deprecated and won’t receive updates anymore. We advise to not use these types in future projects. You can read more about the latest changes and previous additions in the! We are looking forward to exciting times ahead and to many more great apps developed by you, powered by Felgo! Happy coding.
https://blog.felgo.com/updates/felgo-release-and-roadmap
CC-MAIN-2022-33
refinedweb
1,604
61.26
The day has finally come. Today we’ll take a look at the noteworthy monads. A monad, just like a monoid, may seem to be a concept taken from the deepest hell. It seems almost impossible to understand. Nothing could be further from the truth. Let’s try to shed light on this concept. There are many definitions of what a monad is. Some are complicated, others are easier. As we are really fond of simple definitions, in this first contact with monads we’ll say that they are algebraic structures that have a constructor and a flatMap method which, as we already saw in previous posts, is a concatenation of a map method and a flatten. What do we need to create a monad? As we have already said, we need basically two methods: a constructor (commonly called apply) and a flatMap method. In addition, there are some monadic laws to comply with. Those laws require that certain relations exist between the abovementioned functions. However, for better or worse, we are not going to analyse them in this post in order not to complicate it unnecessarily. Case: Option type Option type, as already mentioned in some other posts, is a monad. Let’s get into the insides of Scala to see how it’s defined: def apply[A](x: A): Option[A] = if (x == null) None else Some(x) def flatMap[B](f: A => Option[B]): Option[B] = if (isEmpty) None else f(this.get) As can be appreciated, Option type has a constructor (apply) and a flatMap method. Thanks to these two methods (and to the compliance with monadic laws), we can say that Option type is a monad. However, in Scala’s basic library, the Monad type is not defined. This is where Scalaz comes in. Let’s see how Scalaz defines the Option type as a monad: def point[A](a: => A) = Some(a) def bind[A, B](fa: Option[A])(f: A => Option[B]) = fa flatMap f As can be seen, in Scalaz, the flatMap method is called bind. In turn, the point method calls a constructor and therefore, the apply method is called. Henceforth, if we define these two methods for our own types (them complying with monadic laws too), we’ll be able to create our own monads. And, as they’ll have a flatMap and an apply methods (or same thing, a bind and a point methods), we’ll be able to use the for comprehension structure to make our code more readable, as we learned two weeks ago: for { x <- Some(1) y <- Some(2) } yield x + y //Some(3) Conclusion Monads are much more than we have described in this post. It’s a whole new world to explore. Apart from the abovementioned monadic laws, there are some predefined monads, such as the Reader one. Furthermore, the use of monads is geared towards avoiding side effects, which is quite important in pure functional programming. But all in due time 🙂 2 thoughts on “Abstract alge… what? Monads” […] losing our fear of monads, a whole new world of possibilities has opened up. Today we’ll take a look at one specific […] Me gustaMe gusta […] afraid we don’t. Would we like to? Very likely. In previous posts we spoke about monoids and monads, but now it’s functor’s time. Functors are everywhere and we can prove it. Before […] Me gustaMe gusta
https://scalerablog.wordpress.com/2015/10/12/abstract-alge-what-monads/
CC-MAIN-2017-39
refinedweb
570
72.46
JTextArea Before discussing TextArea let us know the difference between TextField and TextArea, The difference between these two components,are as follows. "A TextField is an input box where we can only enter single line of text whereas a TextArea allows you to enter multiple line of texts". " If the text is more than the display area of the Field a TextField will never grow but the TextArea will grow". Creating a TextArea A TextArea can be created by using the JTextArea class of the Swing package as follows, JTextArea area=new JTextArea(height,width); Here 'height' and 'width' specifies the number of rows and columns of text that should be supported respectively. Following program explains you how to create and add TextArea into a container, TextAreaDemo.java import javax.swing.*; import java.awt.*; class TextAreaDemo extends JFrame { public TextAreaDemo() { setTitle("TextAreaDemo"); setSize(400,400); setLocationByPlatform(true); JPanel p=new JPanel(); JLabel lb=new JLabel("TextArea"); p.add(lb); JPanel p1=new JPanel(); JTextArea area=new JTextArea(10,25);//Text Area of height 10 rows and width 25 Columns area.setLineWrap(true); p1.add(area); add(p,BorderLayout.NORTH); add(p1,BorderLayout.CENTER); } } TextAreaMain.java import javax.swing.*; import java.util.*; class TextAreaMain { public static void main(String args[]) { TextAreaDemo Areademo=new TextAreaDemo(); Areademo.setVisible(true); Areademo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } OUTPUT: As you see the above program it is very simple to create and add a textarea into a panel,but there are some important things that should be noted here, they are, 1. If you see this line area.setLineWrap(true); you can identify that Line Wrap is not supported in TextArea by default. So you have to invoke this method explicitly to include this feature into TextArea. 2. As i have said before, if the text to be displayed is more than the display size then the TextArea will grow until it reaches the window size and after that text would be clipped. 3. Like TextField, it also supports setText() and getText() methods to set and retrieve the text to/from the TextArea...
http://craftingjava.blogspot.com/2012/10/
CC-MAIN-2017-51
refinedweb
345
60.85
Blog Post Secure your container-based system So you're interested in securing a container-based system? Then this blog post is for you. You'll learn about some techniques to improve the architecture, design,… So you’re interested in securing a container-based system? Then this blog post is for you. Read about some of my techniques to improve the architecture, design, and practices of your containerized application. VMs versus containers First, I think it’s important for you to understand the difference between using a container versus a Virtual Machine (VM). Basically, when you use a Virtual Machine there is a necessity to run an entire Operating System (OS) to get your application operational. VMs will typically have potential security surface areas of attack, like open ports (or starting sshd). This means that you need to take care of all the OS vulnerabilities first, close all unnecessarily opened ports before you expose a VM-based application to the users (for both the Internet and an Intranet). In addition, you need to limit the availability of standard applications that you don’t need in the OS, like sshd, to decrease the surface of the potential attack. Going forward, you need to update the OS with the latest security and functionality fixes. When using containers, you might slim down the OS to only the files, libraries, daemons, and parts of the system that you’re going to use in your application. This limits the amount of the exposures of your system in comparison to VMs that support your application. In some cases it might be possible to start from the scratch image (an empty, non-OS image), and add the libraries that are necessary for your executable. Let’s use Docker as an example of a container for the purposes of this blog. Most Dockerfiles start from a parent image. If you need to completely control the contents of your image, you might start from scratch by creating a base image. One more good practice that I suggest: don’t run your services as root and avoid using privileged mode, just in case there’s a security hole. You might want to put limits on the resources that can be used by the container to prevent noisy neighbor effects. Reference Docker best practices on how to do so. Use the Kubernetes secret file instead of environment variables As you probably realize, storing sensitive data in the environment variables it is not too good idea for production systems. The environment variables can be easily discoverable via system process examination. Therefore I’d suggest that you add a secret to the cluster (the file including passwords to your system or sensitive info, like API keys, tokens, usernames and passwords) rather than in environment variables. Here’s an example of the secret file I’m referring to from the jpetstore demo: kubectl create secret generic mms-secret --from-file=mms-secrets=./mms-secrets.json The mms-secrets.json file holds the API keys, tokens, and user numbers: { "jpetstoreurl": ".<Ingress Subdomain>", "watson": { "url": "", "note": "It may take up to 5 minutes for this key to become active", "api_key": "123123123123123123"}, "twilio": { "sid": "", "token": "", "number": "+1XXXXXXXXXX" } } } The best practice of storing secrets to your cluster suggests that implementing the repeatable CI/CD pipeline includes fixes, security patches, the use of capabilities, and use secrets for sensitive information. And thanks to CI/CD pipeline all the fixes, security patches will be applied when they need to be quickly and easily, and not as one-offs/hacks. The above mentioned jPetStore Modernization Demo example implements such a toolchain. You can refer to this article for more information on the CI/CD-based security implementation for containers. Scanning and signing of the container images When you build your own image repository, you should start from performing overall vulnerability scans of your container images. There are automated mechanisms implemented in the enterprise grade repositories, like the one that is based in the IBM Cloud®. Find more information on securing Docker containers with Vulnerability Advisor. The Vulnerability Scanner provides developers with the instant feedback on security policies and package vulnerabilities. The IBM Cloud repository provides the image scan feature. See all the vulnerabilities that were detected with some suggested resolutions: See the full security evaluation for the MySQL db image in the example above. Another thing you can do when dealing with security issues is to sign your images for your containerized applications with IBM Cloud Container Registry. Then you can enforce the policy to use only signed images from the enterprise registry. See the example of the policy with the enforced signed images (at the time of this blogpost the functionality is in the BETA): apiVersion: securityenforcement.admission.cloud.ibm.com/v1beta1 kind: ClusterImagePolicy metadata: name: ibmcloud-default-cluster-image-policy spec: repositories: # This enforces that all images deployed to this cluster pass trust and VA # To override, set an ImagePolicy for a specific Kubernetes namespace or modify this policy - name: "*" policy: trust: enabled: true va: enabled: true I also want to mention this useful tool, IBM Image Scanner Tool, which allows you to scan container images even if they’re not hosted in the IBM enterprise-grade registry. It might be a good idea for you to add it to a CI/CD pipeline since there’s a REST API to access the tool. Container security in the runtime Yet another aspect of container security is in the runtime, where monitoring and securing containers are already in production. For any size of the system you should make sure all of the connections between the various microservices are actually needed, in an attempt to reduce the complexity or reduce risk of rogue services causing havoc. One of the known systems doing exactly this task is the monitoring system designed by NeuVector. You can see the complex view on the system below: “I’d recommend that you take a serious look at what’s running inside your container network.” Jon Deeming, VP at Experian The subject of container security is a vast field, and each section is only the tip of an iceberg. I will try to uncover those concepts that I barely scratched here and the new ones in the follow-up posts. If you want to hear more, please clap for it! Or, you know, tweet me @blumareks.
https://developer.ibm.com/blogs/securing-your-containers/
CC-MAIN-2020-29
refinedweb
1,059
50.57
imar2 wrote:because in this forum topic every one said that they did it "ctrl-c ctrl-v style" and the time limit would suggest it as well. but I guess I'll have to look into it.. Imar2 Automated submission is the way to go. I used: import urllib import urllib2 import re I logged on to hts and then set my cookie in my code with strSession=" " instead of trying to make my code log me in and then go to the mission page, it's easier that way. Also since the answer is a POST form it requires adding 'submitbutton' & a value to urlencode, if you decide to go that route.
http://www.hackthissite.org/forums/viewtopic.php?p=35855
CC-MAIN-2015-35
refinedweb
114
74.73
Using OpenGL in a SFML window Introduction This tutorial is not about OpenGL itself, but rather how to use SFML as an environment for OpenGL, and how to mix them together. As you know, one of the most important features of OpenGL is portability. But OpenGL alone won't be enough to create complete programs: you need a window, a rendering context, user input, etc. You would have no choice but to write OS-specific code to handle this stuff on your own. That's where the sfml-window module comes into play. Let's see how it allows you to play with OpenGL. Including and linking OpenGL to your application OpenGL headers are not the same on every OS. Therefore, SFML provides an "abstract" header that takes care of including the right file for you. #include <SFML/OpenGL.hpp> This header includes OpenGL and GLU functions, and nothing else. People sometimes think that SFML automatically includes GLEW (a library which manages OpenGL extensions) because SFML uses GLEW internally, but it's only an implementation detail. From the user's point of view, GLEW must be handled like any other external library. You will then need to link your program to the OpenGL library. Unlike what it does with the headers, SFML can't provide a unified way of linking OpenGL. Therefore, you need to know which library to link to according to what operating system you're using ("opengl32" on Windows, "GL" on Linux, etc.). The same applies for GLU as well in case you plan on using it too: "glu32" on Windows, "GLU" on Linux, etc. OpenGL functions start with the "gl" prefix, GLU functions start with the "glu" prefix. Remember this when you get linker errors, this will help you find which library you forgot to link. Creating an OpenGL window Since SFML is based on OpenGL, its windows are ready for OpenGL calls without any extra effort. sf::Window window(sf::VideoMode(800, 600), "OpenGL"); // it works out of the box glEnable(GL_TEXTURE_2D); ... In case you think it is too automatic, sf::Window's constructor has an extra argument that allows you to change the settings of the underlying OpenGL context. This argument is an instance of the sf::ContextSettings structure, it provides access to the following settings: depthBitsis the number of bits per pixel to use for the depth buffer (0 to disable it) stencilBitsis the number of bits per pixel to use for the stencil buffer (0 to disable it) antialiasingLevelis the multisampling level majorVersionand minorVersioncomprise the requested version of OpenGL sf::ContextSettings settings; settings.depthBits = 24; settings.stencilBits = 8; settings.antialiasingLevel = 4; settings.majorVersion = 3; settings.minorVersion = 0; sf::Window window(sf::VideoMode(800, 600), "OpenGL", sf::Style::Default, settings); If any of these settings is not supported by the graphics card, SFML tries to find the closest valid match. For example, if 4x anti-aliasing is too high, it tries 2x and then falls back to 0. In any case, you can check what settings SFML actually used with the getSettings function: sf::ContextSettings settings = window.getSettings(); std::cout << "depth bits:" << settings.depthBits << std::endl; std::cout << "stencil bits:" << settings.stencilBits << std::endl; std::cout << "antialiasing level:" << settings.antialiasingLevel << std::endl; std::cout << "version:" << settings.majorVersion << "." << settings.minorVersion << std::endl; OpenGL versions above 3.0 are supported by SFML (as long as your graphics driver can handle them), but you can't set flags for now. This means that you can't create debug or forward compatible contexts; in fact SFML automatically creates contexts with the "compatibility" flag, because it uses deprecated functions internally. This should be improved soon, and flags will then be exposed in the public API. A typical OpenGL-with-SFML program Here is what a complete OpenGL program would look like with SFML: #include <SFML/Window.hpp> #include <SFML/OpenGL.hpp> int main() { // create the window sf::Window window(sf::VideoMode(800, 600), "OpenGL", sf::Style::Default, sf::ContextSettings(32)); window.setVerticalSyncEnabled(true); // load resources, initialize the OpenGL states, ... // run the main loop bool running = true; while (running) { // handle events sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { // end the program running = false; } else if (event.type == sf::Event::Resized) { // adjust the viewport when the window is resized glViewport(0, 0, event.size.width, event.size.height); } } // clear the buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw... // end the current frame (internally swaps the front and back buffers) window.display(); } // release resources... return 0; } Here we don't use window.isOpen() as the condition of the main loop, because we need the window to remain open until the program ends, so that we still have a valid OpenGL context for the last iteration of the loop and the cleanup code. Don't hesitate to have a look at the "OpenGL" and "Window" examples in the SFML SDK if you have further problems, they are more complete and most likely contain solutions to your problems. Managing multiple OpenGL windows Managing multiple OpenGL windows is not more complicated than managing one, there are just a few things to keep in mind. OpenGL calls are made on the active context (thus the active window). Therefore if you want to draw to two different windows within the same program, you have to select which window is active before drawing something. This can be done with the setActive function: // activate the first window window1.setActive(true); // draw to the first window... // activate the second window window2.setActive(true); // draw to the second window... Only one context (window) can be active in a thread, so you don't need to deactivate a window before activating another one, it is deactivated automatically. This is how OpenGL works. Another thing to know is that all the OpenGL contexts created by SFML share their resources. This means that you can create a texture or vertex buffer with any context active, and use it with any other. This also means that you don't have to reload all your OpenGL resources when you recreate your window. Only shareable OpenGL resources can be shared among contexts. An example of an unshareable resource is a vertex array object. OpenGL without a window Sometimes it might be necessary to call OpenGL functions without an active window, and thus no OpenGL context. For example, when you load textures from a separate thread, or before the first window is created. SFML allows you to create window-less contexts with the sf::Context class. All you have to do is instantiate it to get a valid context. int main() { sf::Context context; // load OpenGL resources... sf::Window window(sf::VideoMode(800, 600), "OpenGL"); ... return 0; } Rendering from threads A typical configuration for a multi-threaded program is to handle the window and its events in one thread (the main one), and rendering in another one. If you do so, there's an important rule to keep in mind: you can't activate a context (window) if it's active in another thread. This means that you have to deactivate your window before launching the rendering thread. void renderingThread(sf::Window* window) { // activate the window's context window->setActive(true); // the rendering loop while (window->isOpen()) { // draw... // end the current frame -- this is a rendering function (it requires the context to be active) window->display(); } } int main() { // create the window (remember: it's safer to create it in the main thread due to OS limitations) sf::Window window(sf::VideoMode(800, 600), "OpenGL"); // deactivate its OpenGL context window.setActive(false); // launch the rendering thread sf::Thread thread(&renderingThread, &window); thread.Launch(); // the event/logic/whatever loop while (window.isOpen()) { ... } return 0; } Using OpenGL together with the graphics module This tutorial was about mixing OpenGL with sfml-window, which is fairly easy since it's the only purpose of this module. Mixing with the graphics module is a little more complicated: sfml-graphics uses OpenGL too, so extra care must be taken so that SFML and user states don't conflict with each other. If you don't know the graphics module yet, all you have to know is that the sf::Window class is replaced with sf::RenderWindow, which inherits all its functions and adds features to draw SFML specific entities. The only way to avoid conflicts between SFML and your own OpenGL states, is to save/restore them every time you switch from OpenGL to SFML. - draw with OpenGL - save OpenGL states - draw with SFML - restore OpenGL states - draw with OpenGL ... The easiest solution is to let SFML do it for you, with the pushGLStates/ popGLStates functions : glDraw... window.pushGLStates(); window.draw(...); window.popGLStates(); glDraw... Since it has no knowledge about your OpenGL code, SFML can't optimize these steps and as a result it saves/restores all available OpenGL states and matrices. This may be acceptable for small projects, but it might also be too slow for bigger programs that require maximum performance. In this case, you can handle saving and restoring the OpenGL states yourself, with glPushAttrib/ glPopAttrib, glPushMatrix/ glPopMatrix, etc. If you do this, you'll still need to restore SFML's own states before drawing. This is done with the resetGLStates function. glDraw... glPush... window.resetGLStates(); window.draw(...); glPop... glDraw... By saving and restoring OpenGL states yourself, you can manage only the ones that you really need which leads to reducing the number of unnecessary driver calls.
http://www.sfml-dev.org/tutorials/2.0/window-opengl.php
CC-MAIN-2016-26
refinedweb
1,569
63.59
Create Dart + React apps with no build configuration. pub global activate dart_create_react_app export PATH=$PATH:~/.pub-cache/bin dart_create_react_app my_app cd my_app/ pub serve Then open to see your app. When you’re ready to deploy to production, create a minified bundle with pub build. You don’t need to install or configure any extra tooling. They are preconfigured so that you can focus on the code. Just create a project, and you’re good to go. If you don't already have Dart installed, you can install using Homebrew on macOS. $ brew tap dart-lang/dart $ brew install dart --with-content-shell --with-dartium Then, you can install dart_create_react_app globally. pub global activate dart_create_react_app export PATH=$PATH:~/.pub-cache/bin To create a new app, run: dart_create_react_app my_app cd my_app/ It will create a directory called my_app inside the current folder. Inside that directory, it will generate the initial project structure and install the transitive dependencies: my_app/ ├── lib/ │ └── src/ │ | └── my_app │ | | └── app.dart │ └── my_app.dart ├── tool/ ├── test/ │ └── unit/ │ | └── my_app │ | | └── my_app_test.dart ├── web/ │ └── main.dart │ └── index.css │ └── index.html │ └── logo.svg ├── .gitignore ├── pubspec.lock ├── pubspec.yaml └── README.md No configuration or complicated folder structures, just the files you need to build your app. Once the installation is done, you can run some commands inside the project folder: pub serve Runs the app in development mode. pub run dart_dev test Runs all tests located in the /test folder. pub build Builds the app for production to the build folder. It correctly bundles React in production mode and optimizes the build for the best performance. You can install the package from the command line: $ pub global activate dart_create_react_app The package has the following executables: $ dart_create_react_app Add this to your package's pubspec.yaml file: dependencies: dart_create_react_app: ^1.0.0 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:dart_create_react_app/dart_create_react.
https://pub.dartlang.org/packages/dart_create_react_app
CC-MAIN-2018-51
refinedweb
336
58.69
An introduction to the Java 2D API How to compile and run JDK 1.2 code JDK 1.2 is not yet supported from within popular browsers such as Netscape and Internet Explorer. To compile the example code provided below, please use: javac Test2D.java To run the compiled class, use: java Test2D where is a number between 1 and 4. Java 2D basics Most of the java2d classes are located in the java.awt.geom package. It is therefore typical to include: import java.awt.geom.*; in your applets and applications that use the java2d API. In order to draw lines and text using older versions of the JDK, you write: public void paint(Graphics g) { g.setColor(Color.black); g.drawLine(x1, y1, x2, y2); }The setColor method sets variables within the Graphics object instance pertaining to graphics "state," and the drawLine method performs the graphics operation in screen space -- i.e., coordinates are specified in terms of pixels. In the java2d API, much of the code is similar, except that a Graphics2D object is used instead of a Graphics object, and the drawing operations are usually specified in object space. You can think of this as representing your graphical objects in a coordinate system that's relevant to the application domain. An AffineTransform object then translates from these coordinates to the actual pixel values needed for drawing -- but, we'll get to that later. Here's how the above mentioned code would look using java2d operations: public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHints(Graphics2D.ANTIALIASING, Graphics2D.ANTIALIAS_ON); // Create the line path object GeneralPath p = new GeneralPath(1); p.moveTo(x1, y1); p.lineTo(x2, y2); g2.setColor(Color.black); g2.draw(p); } Introducing GeneralPath The greatest change from past practice in the java2d API is that rather than calling drawLine as before, we are calling the draw method on the Graphics2D object with a GeneralPath as its argument. A GeneralPath instance represents a graphical object that can be composed of multiple lines, quadratic and cubic curves. For example, to create two rectangles, one within the other, you can write: // makes a box out of two rectangular pieces one inside the other // centered at x,y with the specified width and height. The inner // rectangle is half as wide and tall as the outer one. GeneralPath makeBox(int x, int y, int width, int height) { GeneralPath p = new GeneralPath(); p.moveTo(x + (width/2), y - (height/2)); p.lineTo(x + (width/2), y + (height/2)); p.lineTo(x - (width/2), y + (height/2)); p.lineTo(x - (width/2), y - (height/2)); p.closePath(); p.moveTo(x + (width/4), y - (height/4)); p.lineTo(x + (width/4), y + (height/4)); p.lineTo(x - (width/4), y + (height/4)); p.lineTo(x - (width/4), y - (height/4)); p.closePath(); return p; } Note the important process involved in creating a GeneralPath. You typically move to a point, and then use one of the methods defined in the GeneralPath class to create a line or curve from this point (quadratic curves are created with the quadTo method, and Bezier curves with the curveTo method). Once you have created the path, you can "draw" it on a Graphics2D instance (which uses stroking operations), or "fill" it. Our first test illustrates both operations with the makeBox function: public void test); GeneralPath p = makeBox(sz.width/4, sz.height/4, 100, 100); p.setWindingRule(GeneralPath.NON_ZERO); g2.setColor(Color.blue); g2.fill(p); p = makeBox((3 * sz.width)/4, sz.height/4, 100, 100); p.setWindingRule(GeneralPath.EVEN_ODD); g2.setColor(Color.blue); g2.fill(p); } Note that since Graphics2D is a descendant of Graphics, you can still perform the AWT Graphics operations with which you may be familiar. The code above will draw two GeneralPaths side by side on the screen. In the code above, setRenderingHints enables the ANTIALIASING hint. This indicates to the Graphics2D object that stroking and other drawing operations should attempt to avoid jaggies in the output they produce; you can set the second argument to be ANTIALIAS_OFF for slightly faster performance but lower quality output. The other property that you can set with the setRenderingHints method is the RENDERING hint. The value can be one of RENDER_SPEED, RENDER_QUALITY or RENDER_DEFAULT. The first value sacrifices quality for speed while the second does the reverse. An important GeneralPath property that you can set is the winding rule, which is to be used during fill operations. As indicated by the code above, the second draw operation uses the EVEN_ODD winding rule which specifies that the inside and outside of a geometric shape alternate as you move inward. Hence, when the path is filled, it looks like a rectangle with a hole in the middle. Specifying NON_ZERO as the winding rule, however, results in a completely filled rectangle. The filling operation in this case depends on counting how many times a given path intersects a ray to infinity from a specified point in order to determine whether that point is inside or outside the given path. If that sounds complicated, don't worry -- as long as you are dealing with a convex single-loop path that doesn't cross itself, you shouldn't have to worry about the distinction. The java2d API can draw lines of varying thicknesses and dash patterns. The basic support for such operations is provided through the Stroke class and the setStroke method in the Graphics2D class. Our second example (remember to use "java Test2D 2" to run it), uses the draw method rather than fills and draws the two paths created above with lines that are 5 and 15 pixels wide. g2.setStroke(new BasicStroke(5.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f, null, 0.0f)); The second argument specifies that the stroke should extend unclosed subpaths with a square projection that extends beyond the end of the segment to a distance equal to half the line width. The third argument specifies that line segments should be stroked by extending their outer edges until they meet. The fourth argument specifies the miter limit. The last two arguments specify dash patterns (which we are not using in this example). What is an AffineTransform Our next example (use "java Test2D 3" to run it) deals with transforming objects before drawing them. Typically, two-dimensional objects can be scaled, rotated, reflected and skewed before being drawn. Such operations are usually represented by a 3x3 matrix (a translation can be denoted by T(x, y), a rotation by R(theta) and so on). The best way to understand the AffineTransform class is as follows: Think of the coordinates of points in your objects to be drawn as relative to some coordinate system B. (i.e., when you say a point is at [x=5, y=15] you are really saying that it is relative to some origin [x_B, y_B] and that the coordinate system is at some angle relative to the screen coordinate system). Rather than thinking of translating and rotating points in your geometric object, it makes sense to think of the coordinate systems being moved around. For example, translating your object along the x axis by 10 units is equivalent to translating the origin of the coordinate system relative to which your object is represented by -10 units. (In either case, the newly transformed object has all of its x coordinates increased by 10 units). AffineTransforms, in essense, represent the 3x3 matrices that represent operations such as translations, rotations, etc. Another important point to remember about AffineTransforms is that operations "compose" rather intuitively. For example, if you translate a coordinate system A, by x,y and then rotate it by an angle theta to get to a new co-ordinate system B, the resulting affine transform can be represented as the matrix multiplication: T' = T(x,y) . R(theta) This composed transform, however, translates points expressed in the B coordinate system to points in the A coordinate system. Note that as you move left-to-right, the rotations, scaling and subsequent translations, etc., occur relative to the transformed coordinate system until that point. (In the above example, the rotation happens about the origin of the "translated" coordinate system.) Typically, the way it works is that you have an object expressed about some coordinate system B. You would like to draw it about some coordinate system A. In order to do this, you just write out the coordinate transformations you need to do, in order to go from A to B. The order is important! Now we are ready to examine the code: public void test); // make the box at 125, 125 that's 200 x 100 pixels GeneralPath p = makeBox(sz.width/4, sz.height/4, 200, 100); p.setWindingRule(GeneralPath.EVEN_ODD); AffineTransform tfm = new AffineTransform(); // now translate it by 125, 125 so it appears at the center tfm.translate(sz.width/4, sz.width/4); g2.setTransform(tfm); g2.setColor(Color.blue); g2.fill(p);); }We first create a path as before, and then: AffineTransform tfm = new AffineTransform(); // now translate it by 125, 125 so it appears at the center tfm.translate(sz.width/4, sz.width/4); g2.setTransform(tfm); These lines create a transformation that represents a translation of 125 pixels along each axis (our frame is 500 x 500 pixels). Note that in screen space, the x-axis increases to the right, and the y-axis increases downward. The setTransform method on the Graphics2D class affects all subsequent draw and fill operations. In the above example, how did we know to specify a positive translation to make the rectangle appear at the center of the screen? This illustrates that sometimes you know where your picture or object needs to end up, but need to compute the extent of the transformation. By comparing the original B (in the previous examples) to the transformed picture we desire, we can see that the B->A transform needs to be negative, which indicates that the A->B transform must be a positive translation. One further note (and a few lines of code) to nail these concepts down further:);Note that a negative translation moves the object near the origin. The next line transforms the shape with the given transform. This converts the coordinates to be centered around the origin. //); The next few lines create a transform that represents a translation to the center of the screen and then a rotation of 30 degrees about that point. If you replace s in the call to draw with p, you will see that the result is not what you expected. This is because the original GeneralPath was not centered at the origin. Translating and then rotating the offset shape will result in a shape that is also offset. In general, it is always a good idea to describe your shapes relative to the origin. Then, translations and rotations are easier to understand. If you are still confused about AffineTransforms, please consult one of the standard computer graphics texts indicated below. This class provides several useful methods having to do with various types of graphics transformations. Do we really understand AffineTransforms yet? This last example is provided as a teaser to those of you who are interested in playing more with the AffineTransform class. In science and engineering, it is customary to use an x coordinate that increases to the right and a y coordinate that increases toward the top. In all the examples thus far, we have used a coordinate system that had x increasing to the right and y increasing toward the bottom of the screen. The origin (0,0) was at the top left-hand corner of the screen. It is sometimes useful to create drawings with the origin at the center of the screen and the axes aligned as they are in engineering plots. The following code computes and sets up an AffineTransform to do exactly that (it basically translates the origin to the center of the screen and flips the y-axis). Note that the drawing operations subsequent to that are in an object space -- i.e., we draw the axes, and a cross at the two points indicated, but the coordinates we use are not screen or pixel coordinates. public void test); // create the magic transform :) AffineTransform tfm = new AffineTransform(1.0, 0.0, 0.0, -1.0, (float)sz.width/2, (float)sz.height/2); AffineTransform tfm1 = new AffineTransform(); g2.setTransform(tfm); g2.setColor(Color.red); GeneralPath p = makeCross(25, 25, 8); g2.draw(p); p = makeCross(-100, 25, 8); g2.draw(p); p = makeLine(0, 0, 200, 0); g2.draw(p); p = makeLine(0, 0, 0, 200); g2.draw(p); Point2D pt1 = new Point2D.Double(30.0, 25.0); Point2D pttfm1 = tfm.transform(pt1, null); Point2D pt2 = new Point2D.Double(-105.0, 25.0); Point2D pttfm2 = tfm.transform(pt2, null); // If you comment out the following four lines, and uncomment // the lines below, you'll see slower and really funny drawString // operation. (i.e. since the original transform is in effect // you'll see the text drawn flipped along the y-axis as well!) g2.setTransform(tfm1); g2.setColor(Color.black); g.drawString("25,25", (int) pttfm1.getX(), (int) pttfm1.getY()); g.drawString("-100,25", (int) pttfm2.getX(), (int) pttfm2.getY()); // This is much slower // g2.drawString("25,25",(float) pttfm1.getX(), (float) pttfm1.getY()); // g2.drawString("-100,25",(float)pttfm2.getX(),(float) pttfm2.getY()); } The comments indicate the curious interaction between text drawing operations and other graphics operations. The java2d API also contains points and lines that can be at different degrees of precision. The code below indicates, for example, how to create a two-dimensional point the coordinates of which are represented with double-precision floating point numbers: Point2D pt1 = new Point2D.Double(30.0, 25.0); Similar classes exist in the Line2D class. By default, the java2d operations support all three (float, double and integer) while the Graphics class supports only integer coordinates. Conclusion This article introduced the java2d API and provided brief examples illustrating some of its interesting classes. Of course, there's a lot more to the API than what has been described here. With this API, the Java platform's graphics capabilities get a much-needed shot in the arm. If you have shied away from Java in the past because all you could see was spinning logos, it is time to take a serious look at java2d. Pretty soon, this API may be decorating a lot of pages on the Web! For further information, see: - Complete source code for this article. - Javasoft's Web site - Documentation on java2d - Java2D Home Page - Introductory article on java2d color - Another introduction to the java2d API - Introductory graphics texts: 3D Computer Graphics -- Alan Watt Introduction to Computer Graphics -- James D. Foley, Andries van Dam, Steven K. Feiner Sundar Narasimhan got his Ph.D. from MIT in '94, and is now Chief Scientist at Ascent Technology Inc., where he works on real-time resource allocation and database mining systems. You can reach Sundar Narasimhan at: sundar@ascent.com Page 1 of 2
http://www.developer.com/java/other/article.php/601851/An-introduction-to-the-Java-2D-API.htm
CC-MAIN-2014-15
refinedweb
2,521
55.44
in reply to How do you manage module deployment? In order to make a CPAN shell solution plausible in my environment, I use CPAN::Mini to maintain a local mini-CPAN mirror. That mirror weighs in somewhere in the area of 450MB. Then, as I create new or update existing modules I use CPAN::Mini::Inject to add them into the mini-CPAN mirror. Although I currently do this manually, it seems trivial to script it and run out of cron or some other scheduler. I serve the entire mini-CPAN mirror up over anonymous FTP. I've configured the CPAN module on each build machine to use it as its only CPAN mirror. Then I can pull down the entire project, dependencies and all, to a clean machine with zero hassle. Updates are similarly a breeze, so long as I'm disciplined about maintaining the dependency list. Some caveats are that the mini-CPAN mirror will only contain the latest-and-greatest CPAN modules each time it updates (though this might be configurable, I'm not sure). That works well for my environment, but may not be so hot for yours. Also, I don't do any updating of modules that I can get from the CPAN. If I were to do so, I imagine that it may require pulling it into a different CPAN namespace than that of the original author. --jwest -><- -><- -><- -><- -><- All things are Perfect To every last Flaw And bound in accord With Eris's Law - HBT; The Book of Advice, 1:7 Used as intended The most useful key on my keyboard Used only on CAPS LOCK DAY Never used (intentionally) Remapped Pried off I don't use a keyboard Results (441 votes), past polls
http://www.perlmonks.org/index.pl?node_id=474529
CC-MAIN-2015-11
refinedweb
290
68.5
Dijkstra’s Algorithm January 4, 2011 We follow the implementation given in Section 24.3 of the third edition, published in 2009, of Introduction to Algorithms by Thomas Cormen, Charles Leiserson, Ronald Rivest and Clifford Stein. (hereafter referred to as CLRS). In it, vertices are given a number of attributes; we begin with a simple vertex class to collect them all in one spot: class Vertex(object): def __init__(self, adj={}, dist=float("inf"), name=None, pred=None): self.adj = adj self.dist = dist self.name = name self.pred = pred return def __cmp__(self, other): return cmp(self.dist, other.dist) def __repr__(self): return self.name A vertex has a distance parameter, a name, and a predecessor. In CLRS, vertices also have an adjacency list and edge weights are recorded in an external structure. We instead opt to have each vertex’s adj attribute be a Python dictionary, where each key is an adjacent vertex and each value is the weight of the edge between them. We also give vertices a __cmp__ method to compare vertices by distance and a __repr__ method is included to give human readable print out. The implementation of Dijkstra’s Algorithm in CLRS requires a min-priority queue; interestingly, this queue determines the speed of the algorithm as a whole, because we need to constantly retrieve the vertex of minimum distance and update the key of a node in the queue whenever a vertex’s distance estimate changes. While CLRS recommends a Fibonacci heap, we’ll use pairing-heaps which we studied in a previous exercise. Pairing heaps have most of the efficiency of Fibonacci heaps, while being easier to implement. We’ll represent a digraph with a Python dictionary of string –> vertex pairs. First off, we have two procedures to build our digraph D out of edges: def add_edge(D, u, v, weight): if u not in D: D[u] = Vertex(name=u, adj={}) if v not in D: D[v] = Vertex(name=v, adj={}) D[u].adj[v] = weight return def add_edges(D, edges): for edge in edges: add_edge(D, *edge) return When adding an edge, we first ensure both vertices are in the graph. Then the head vertex’s adjacency list is updated with tail vertex and the weight of the edge between them. The add_edges procedure is included for convenience’s sake, so we don’t have to build the digraph one edge at a time. Next, our two helper functions: init_single_source and relax. The first readies the digraph for work on the single source shortest path problem, while the latter updates each vertex when a shorter path is found to it: def init_single_source(D, s): for v in D: D[v].dist = float("inf") D[v].pred = None D[s].dist = 0 return def relax(D, u, v): d = D[u].dist + D[u].adj[v] if D[v].dist > d: D[v].dist = d D[v].pred = u return The main procedure is dijkstra. First, we add each vertex ( D.values() is a list of all the vertices in D) to the priority queue. Next we iteratively step through all the vertices of the digraph (indexed by distance from the source), relaxing each outward edge. We also clean up the queue with merge_pairs so that the queue is again ordered by distance after relaxing edges. def dijkstra(D, s): init_single_source(D, s) Q = make_heap() for v in D.values(): Q = insert(v, Q) while Q: u, Q = find_min(Q), delete_min(Q) for v in u.adj: relax(D, u.name, v) Q = merge_pairs(Q) return Finally, we build the shortest path by traversing backwards through the predecessor subtree created by the algorithm. We record the path with a list, appending on the right, and then reverse the list to get the path in order: def find_shortest_path(D, s, f): dijkstra(D, s) path, v = [f], D[f].pred while v is not None: path.append(v) v = D[v].pred path.reverse() return path Testing on the digraph given in our picture: if __name__ == "__main__": D = {} add_edges(D, [('a', 'c', 2), ('a', 'd', 6), ('b', 'a', 3), ('b', 'd', 8), ('c', 'd', 7), ('c', 'e', 5), ('d', 'e', 10)]) print find_shortest_path(D, 'a', 'e') # Output: ['a', 'c', 'e'] The code including the priority-queue is available on. […])
http://programmingpraxis.com/2011/01/04/dijkstras-algorithm/2/
CC-MAIN-2015-22
refinedweb
719
64.61
Building Block: Queries and Views Last modified: April 05, 2010 Applies to: SharePoint Foundation 2010 In this article Object Model for Queries and Views XML Used for Queries and Views Object Model for LINQ to SharePoint Provider XML Used for SPMetal Areas Related to Queries and Views Development More Information about Queries and Views In Microsoft SharePoint Foundation 2010, a query determines what site data or list data is returned, while a view determines how that data is displayed within the page. A view always contains a query, but a query is not always associated with a view, because a query can be used independently of a view in a managed code context. Views can be shared as view styles across lists in a Web site. Collaborative Application Markup Language (CAML) has traditionally served as the principal means for defining queries and views in SharePoint Foundation. You can use a CAML string to define a query within the context of the server object model or the new client object model. However, SharePoint Foundation 2010 introduces an alternative method to define queries that does not require using CAML. Instead, you can now query SharePoint data directly by using the new LINQ to SharePoint provider, which allows you to query lists from server code that uses Language Integrated Query (LINQ) syntax. SPMetal is a command-line tool you can use to generate entity classes, which in turn provide an object oriented interface to the SharePoint Foundation content databases. When working with server code that uses the Microsoft.SharePoint namespace, you define a query by instantiating an SPQuery object, and assigning a string containing CAML that defines the query to the Query property. You then pass the SPQuery object as parameter in the GetItems() method of the SPList object to return specified list items. Client code that uses the new Microsoft.SharePoint.Client namespace (JavaScript: SP Namespace) works in a similar way. In client code, you can define a query by instantiating a CamlQuery object (JavaScript: CamlQuery) and assigning a CAML query string to the ViewXml property (JavaScript: viewXml). You then pass the CamlQuery as parameter in the GetItems(CamlQuery) method (JavaScript: getItems) of List (JavaScript: List) to return specified list items. The most important classes to use when working with views and queries in the server and client object models include the following: SPQuery - Defines a query. Client object model: CamlQuery (JavaScript: CamlQuery) SPView – Represents a view of list data. A view contains a query. The Views property of SPList provides access to the list's SPViewCollection. Client object model: View (JavaScript: View) SPViewFieldCollection – Represents the collection of fields that are returned in a view. Client object model: ViewFieldCollection (JavaScript: ViewFieldCollection) SPViewStyle - Represents a view style. The ViewStyles property of SPWeb provides access to the SPViewStyleCollection for a Web site. For information about using queries in the server object model, see How to: Return Items from a List. For information about using queries in the client object model, see Data Retrieval Overview and How to: Retrieve List Items. The CAML View schema contains a CAML query, although the Query schema is often used in contexts outside of the View schema. A view is contained within the Schema.xml file for a list, which is located in the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\FEATURE folder for a list definition. In SharePoint Foundation 2010, much of the view is defined through XSLT in .xsl files located in %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\XSL. For information about XSLT views, see List Views. SharePoint Foundation 2010 introduces new Joins and ProjectFields elements that the View element can contain, which allows a list view to include fields from other lists that have been joined to the primary list. For information about the structure of the View and Query schemas and their elements, see View Schema and Query Schema. The Microsoft.SharePoint.Linq namespace provides the following important classes that are used to implement the LINQ to SharePoint provider. DataContext - Main gateway class that provides access to SharePoint Foundation and the functionality for LINQ querying, writing to the content databases, and object change management. GetList<T>(String) returns an EntityList<TEntity> object that represents a list that can be queried, and SubmitChanges() writes changes to the content database. EntityList<TEntity> – Represents a list that can be queried by using LINQ. Together with a set of other "entity classes" that represent list items and field values, this list provides an object-relational mapping and interface between object-oriented .NET code and the relational structure of content databases. EntityRef<TEntity> – Entity class that provides for deferred loading and relationship maintenance for the singleton side of a one-to-many relationship. EntitySet<TEntity> - Entity class that provides for deferred loading and relationship maintenance for the "many" side of one-to-many and many-to-many relationships. LookupList<T> - Entity class that represents the values of a lookup field (column) that allows multiple values. For information about other important classes that can be used with the LINQ to SharePoint provider, see Microsoft.SharePoint.Linq. For overviews and programming tasks that describe the provider, see Managing Data with LINQ to SharePoint. SPMetal Parameters XML Schema is used to override certain aspects of the default behavior of SPMetal, determining in particular which content database entities are included in the entity classes that the tool generates. For more information about how the tool and its schema are used, see SPMetal.
http://msdn.microsoft.com/en-us/library/office/ee535714(v=office.14)
CC-MAIN-2014-41
refinedweb
916
51.68
Matrix dot multiplication slowness and BLAS versions Hello everyone! Is there a way to increase a performance of matrix multiplication in Sage? Right now I am relying on numpy's dot function like this: import numpy as np N = 768 P = 1024 A = np.random.random((P, N)) A.T.dot(A) Timing dot product in Sage now gives me a time about second and a half: >>>>> timeit.repeat('A.T.dot(A)', setup=setup, number=10, repeat=3) [18.736198902130127, 18.66787099838257, 17.36500310897827] Yet the same multiplication in Matlab takes less than 100 ms. I heard that numpy internally relying on BLAS and it can be replaced with OpenBLAS /ATLAS/IntelMKL or something like that for the better performance. So I am looking for some kind of manual or info about that is going on with the performance in regard with underlying numpy's components and when one should consider replacing one with another and is there a simple way to do that? Which version of Sage are you using ? Which binaries did you use ? Which hardware ? Which distribution ?
https://ask.sagemath.org/question/26507/matrix-dot-multiplication-slowness-and-blas-versions/?answer=26511
CC-MAIN-2019-09
refinedweb
181
65.12
Connecting to Objects Microsoft® Windows® 2000 Scripting Guide Before you can do anything with the data in a database, you must first make a connection of some kind to that database. Likewise, before you can do anything with the methods or properties of an Automation object, you must first make a connection to that object, a process known as binding. Binding to objects can be confusing, because VBScript and WSH both provide a GetObject and a CreateObject method for accessing objects. Furthermore, although the implementations are similar, there are some subtle differences that grow in importance as you become more proficient in scripting. These differences are discussed in more detail later in this chapter. For now, use the following rules-of-thumb without worrying about whether you are using the VBScript or the WSH method (although in most cases you will use the VBScript implementation): Use GetObject to bind to either WMI or ADSI. Both WMI and ADSI allow you to use a moniker when binding from VBScript. A moniker (discussed later in this chapter) is an intermediary object that makes it easy to bind to objects that do not exist in the file system namespace. ADSI exists in the Active Directory namespace, while WMI exists in its own namespace. Although it is possible (and sometimes required) to bind to WMI or ADSI using CreateObject, using GetObject and a moniker is typically faster and easier. Use CreateObject to bind to all objects other than WMI or ADSI. In general, CreateObject will be required to create new instances of such elements as the FileSystem object, the Dictionary object, and Internet Explorer. This is not a hard-and-fast rule, however. For example, you will often need to use CreateObject to create WMI objects other than SWbemServices (such as SWbemLocator). Connecting to WSH In line 1 of the script in Listing 2.2, the script binds to WMI by using the following code statement: This connects the script to the WMI SWbemServices object. No similar binding string is used to connect to WSH. Instead, the Echo method is called without first binding to WSH. You are already connected to WSH because WSH is required to run a script written in VBScript.
https://technet.microsoft.com/library/ee198857.aspx
CC-MAIN-2017-43
refinedweb
369
60.45
when i'm pressing the "start program" button it starts a 5 sec task and block the GUI. as i understand i need to use Threading so each button will work independently from the GUI. I'm stuck for almost a month already, can someone show me how can execute def start_Button(self): function using threading? from tkinter import * import time class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.var = IntVar() self.master.title("GUI") self.pack(fill=BOTH, expand=1) quitButton = Button(self, text="Exit", command=self.client_exit) startButton = Button(self, text="Start Program", command=self.start_Button) quitButton.grid(row=0,column=0) startButton.grid(row=0, column=2) def client_exit(self): exit() def start_Button(self): print('Program is starting') for i in range (5): print(i) time.sleep(1) root = Tk() root.geometry("200x50") app = Window(root) root.title("My Program") root.mainloop() There are a lot of important questions to ask before you jump into threading for the first time, but by and large the most important question is "how do I want to communicate between my threads?" In your minimal example you don't require any communication at all, however in your real code start_Button may be doing some Work and returning data back to the GUI. If that's the case, you have more work to do. Please clarify that as a comment if that's the case. For the minimal example, it's actually quite easy. class Window(tkinter.Frame): # the rest of your GUI class as written, but change... def start_Button(self): def f(): # this is the actual function to run print('Program is starting') for i in range (5): print(i) time.sleep(1) t = threading.Thread(target=f) t.start()
https://codedump.io/share/cVtJb4agDAWz/1/tkinter-gui-stuck-till-end-of-the-task-when-pressing-a-button
CC-MAIN-2018-05
refinedweb
302
51.95
In this three-part series, we’ve taken an in-depth look at Kotlin, a modern programming language for Android apps that runs in the Java Virtual Machine (JVM). While Kotlin is far from the only alternative programming language that’s designed to run on the JVM, it does have a lot to offer Android developers. So if you’ve recently been feeling frustrated with the Java part of Android development, then you'll want to consider giving Kotlin a go. In the first two instalments, we covered the following: Java vs. Kotlin: Should You Be Using Kotlin for Android Development? In this introductory article, we looked at what Kotlin has to offer Android developers, as well as some potential drawbacks you need to be aware of before deciding whether Kotlin is right for you. Coding Functional Android Apps in Kotlin: Getting Started. In this post, we looked at how to configure Android Studio to support Kotlin code, created an Android app written entirely in Kotlin, familiarised ourselves with Kotlin's basic syntax, and even saw how switching to Kotlin can mean you never have to write another findViewByIdagain. Now that you’re in a position where you can replace the Java portions of your projects with Kotlin code that has the same end result, let’s move on and look at some areas where Kotlin has the advantage over Java. In this final installment, we’re going to explore some of the more advanced Kotlin features that allow you to perform tasks that would either be much more verbose in Java, or not achievable with Java alone. By the end of this article, you’ll know how to use Kotlin to trim a ton of boilerplate code from your projects, extend existing classes with new functionality, and make those frustrating NullPointerExceptions a thing of the past. No More Nulls How many times have you run into a NullPointerException while testing your code? Today, it’s pretty clear that allowing developers to assign null to an object reference wasn’t the best design choice! Attempting to use an object reference that has a null value is a huge source of bugs across many different programming languages, including Java. In fact, NullPointerException has been such a huge source of annoyance that Java 8 added the @NonNull annotation specifically to try and fix this flaw in its type system. The problem lies in the fact that Java allows you to set any variable of a reference type to null—but if at any point you try to use a reference that points to null, then the variable won’t know where to look because the object doesn’t actually exist. At this point, the JVM can’t continue the normal path of execution—your application will crash, and you’ll encounter a NullPointerException. Trying to call a method on a null reference or attempting to access a field of a null reference will both trigger a NullPointerException. If you’ve experienced the pain of NullPointerExceptions (and haven’t we all at some point?) then there’s good news: null safety is integrated into the Kotlin language. The Kotlin compiler doesn’t allow you to assign a null value to an object reference, as it specifically checks your code for the presence of possible null objects during compilation. If the Kotlin compiler detects that a NullPointerException may be thrown at runtime, then your code will fail at compile-time. Kotlin’s null-safe design means you’ll (almost) never encounter null situations and NullPointerExceptions originating from Kotlin code. The only exception is if you trigger a NullPointerException by incorrectly using one of Kotlin’s special operators, or if you use one of these operators to deliberately trigger a NullPointerException (we’ll explore operators in more detail later in this article). Null Safety in Practice In Kotlin, all variables are considered non-nullable by default, so attempting to assign a null value to a variable will result in a compilation error. For example, the following won’t compile: var example: String = null If you do want a variable to accept a null value, then you’ll need to explicitly mark that variable as nullable. This is the exact opposite of Java, where every object is considered nullable by default, which is a huge part of why NullPointerExceptions are so common in Java. If you do want to explicitly declare that a variable can accept a null value, then you’ll need to append a ? to the variable type. For example, the following will compile: var example: String? = null When the compiler sees this kind of declaration, it recognises that this is a nullable variable and will treat it a bit differently, most notably preventing you from calling a method or accessing a property on this nullable reference, once again helping you avoid those pesky NullPointerExceptions. For example, the following won’t compile: var example : String? = null example.size Although Kotlin’s design means that it’s difficult to encounter NullPointerExceptions originating from Kotlin code, if your project features a mixture of Kotlin and Java then the Java portions of your project can still be a source of NullPointerExceptions. If you’re working with a blend of Kotlin and Java files (or perhaps you specifically need to introduce null values into your Kotlin code) then Kotlin includes a range of special operations that are designed to help you gracefully handle any null values you do encounter. 1. The Safe Call Operator The Safe Call operator ?. gives you a way of dealing with references that might potentially contain a null value, while ensuring that any call to this reference won’t result in a NullPointerException. When you add a Safe Call operator to a reference, that reference will be tested for a null value. If the value is null, then null is returned, otherwise the object reference will be used as you originally intended. While you could achieve the same effect using an if statement, the Safe Call operator allows you to perform the same work in much less code. For example, the following will return a.size only if a is not null—otherwise, it’ll return null: a?.size You can also chain Safe Call operators together: val number = person?.address?.street?.number If any of the expressions in this series is null, then the result will be null, otherwise the result will be the requested value. 2. The Elvis Operator Sometimes you’ll have an expression that could potentially contain a null value, but you don’t want to throw a NullPointerException even if this value does turn out to be null. In these situations, you can use Kotlin’s Elvis operator ?: to provide an alternate value that will be used whenever the value turns out to be null, which is also a good way of preventing the propagation of null values in your code. Let’s look at an example of the Elvis operator in action: fun setName(name: String?) { username = name ?: "N/A" Here, if the value to the left of the Elvis operator is not null then the value of the left-hand side is returned ( name). But if the value to the left of the Elvis operator is null then the expression on the right will be returned, which in this instance is N/A. 3. The !! Operator If you ever want to force your Kotlin code to throw a Java-style NullPointerException, then you can use the !! operator. For example: val number = firstName!!.length Here, we’re using the !! operator to assert that the firstName variable is not null. As long as firstName contains a valid reference, then the variable number is set to the length of the string. If firstName doesn’t contain a valid reference, then Kotlin will throw a NullPointerException. Lambda Expressions A lambda expression represents an anonymous function. Lambdas are a great way of reducing the amount of code needed to perform some tasks that come up all the time in Android developmment—for example, writing listeners and callbacks. Java 8 has introduced native lambda expressions, and these are now supported in Android Nougat. Although this feature isn’t something that’s unique to Kotlin, it’s still worth taking a look at them. Plus, if you’re working on a project that contains both Kotlin and Java code, then you can now use lambda expressions across your entire project! A lambda expression comprises a set of parameters, a lambda operator ( ->) and a function body, arranged in the following format: { x: Int, y: Int -> x + y } When constructing lambda expressions in Kotlin, you need to bear the following rules in mind: The lambda expression should be surrounded by curly braces. If the expression contains any parameters, then you need to declare them before the ->arrow symbol. If you’re working with multiple parameters, then you should separate them with commas. The body goes after the ->sign. The main benefit of lambda expressions is that they allow you to define anonymous functions and then pass these functions immediately on as an expression. This allows you to perform many common development tasks more succinctly than you could in Java 7 and earlier, as you no longer need to write the specification of the function in an abstract class or interface. In fact, the lack of lambdas in Java 7 and earlier is a big part of why writing listeners and callbacks has traditionally been so clunky in Android. Let’s look at a common example: adding a click listener to a button. In Java 7 and earlier, this would typically require the following code: button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(this, "Button clicked", Toast.LENGTH_LONG).show(); } }); However, Kotlin lambda functions allow you to set a click listener using a single line of code: button.setOnClickListener({ view -> toast("Button clicked") }) Already, this is much more succinct and easier to read, but we can go further—if a function takes another function as the last parameter, then you can pass it outside of the parentheses list: button.setOnClickListener() { toast("Button clicked") } And if the function only has one parameter that’s a function, you can remove the parentheses completely: button.setOnClickListener { toast("Button clicked") } Extension Functions Similar to C#, Kotlin allows you to add new functionality to existing classes that you wouldn’t otherwise be able to modify. So if you think a class is missing a useful method then why not add it yourself, via an extension function? You create an extension function by prefixing the name of the class you want to extend to the name of the function you’re creating. For example: fun AppCompatActivity.toast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show() } Note that the this keyword inside the extension function corresponds to the AppCompatActivity instance which .toast is called on. In this example, you just need to import the AppComptActivity and Toast classes into your .kt file and then you’re ready to call the . notation on instances of the extended class. When it comes to Android development, you may find extension functions particularly useful for giving ViewGroups the ability to inflate themselves, for example: fun ViewGroup.inflate( @LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View { return LayoutInflater .from(context) .inflate(layoutRes, this, attachToRoot) } So instead of having to write the following: val view = LayoutInflater .from(parent) .inflate(R.layout.activity_main, parent, false) You can simply use your extension function: val view = parent.inflate(R.layout.activity_main) Singleton Objects In Java, creating singletons has typically been pretty verbose, requiring you to create a class with a private constructor and then create that instance as a private attribute. The end result is usually something like this: public class Singleton { private static Singleton singleton = new Singleton( ); private Singleton() { } public static Singleton getInstance( ) { return singleton; } Rather than declaring a class, Kotlin allows you to define a single object, which is semantically the same as a singleton, in one line of code: object KotlinSingleton {} You can then use this singleton right away, for example: object KotlinSingleton { fun myFunction() { [...] } } KotlinSingleton.myFunction() Conclusion In this article, we took an in-depth look at Kotlin’s null-safe design, and saw how you can ensure your Android projects remain null safe even when they contain a mix of Java and Kotlin code by using a range of special operators. We also took a look at how you can use lambda expressions to simplify some common development tasks in Android, and how to add new functionality to existing classes. Combined with what we learnt in Part 1: Java vs. Kotlin and Part 2: Getting Started, you now have everything you need to start building effective Android apps using the Kotlin programming language. Have fun with the Kotlin language, and why not check out some of our other courses and tutorials on Android programming? Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/articles/coding-functional-android-apps-in-kotlin-lambdas-null-safety-more--cms-27964
CC-MAIN-2019-22
refinedweb
2,170
50.06
Hello there, A little bit of preliminary infos. I've installed the v2 sdk and followed the tutorial on how to compile the library for python3 (I'm on python3.7.7, configured for 64bit). For now I'm able to get the coordinates in the reference frame that the sensor uses for the palm position and that's good, this means that the compiled files works as expected. Now I'm implementing gesture recognition in one of my projects (swipe in particular) but I've encountered a problem...It seems that the function frame.gestures() returns always something even if no gesture is performed (even if no hand is inframe).An example of the output using print(frame.gestures()): <Leap.GestureList; proxy of <Swig Object of type 'Leap::GestureList *' at 0x0000000003344150> > frame.gestures() print(frame.gestures()) <Leap.GestureList; proxy of <Swig Object of type 'Leap::GestureList *' at 0x0000000003344150> > I've crosschecked with another pc with python2 and sdk 2 configured and I receive this kind of output only when an actual gesture is performed. It seems that the sensor signals a gesture even if no hand or movement is present...very strange, and nonsense to me. Have anyone had the same issue as me with Python3? I know that is not natively supported but I really need to stay on P3. Thanks in advance for the help. Do you still have the guide to recompiling for Python 3? I'm trying to make a Blender addon for the Leap (so I'm stuck with Python 3.7) but the link in the Leap documentation for the Python 3 compiling guide isn't valid any more Yeah, when they moved to the v4 sdk a proper migration of old url wasn't put in place....Here's the link: Recompile for P3 Note that the newer version of SWIG will have complains about indentation and other stuff with the input file. Just use the 2.0.9 version that is still downloadable. For the rest the guide in the above link worked well for me (64bit, python 3.7.7). Feel free to dm me if you have problems with the compilation. Thanks so much! Got it working and (sloppily) hooked into Blender. Taking a poke at your problem (I'm not using gestures myself but I felt guilty for hijacking your thread), I'm sort of scraping at the edges of what I understand here but it looks like maybe the swig-generated dll isn't properly passing along Python's attempts to address an array- I get the same output as you're getting (different memory address of course), also regardless of whether a hand is in frame. I noticed that code copied and pasted from the documentation verbatim throws an error (this is from the keytap gesture page): for gesture in frame.gestures(): if gesture.type is Leap.Gesture.TYPE_KEY_TAP: key_tap = Leap.KeyTapGesture(gesture) the first line gives me StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "[my horrifying folder structure redacted]\Leap.py", line 26, in LeapControl_Handler fp.close() SystemError: <built-in function delete_GestureList> returned a result with an error set Yeah, I got the same sensation about the swig. After some digging and debug this code works well for the detection: from Leap import SwipeGesture #STUFF class SampleListener(Leap.Listener): # State of gesture names state_names = ['STATE_INVALID', 'STATE_START', 'STATE_UPDATE', 'STATE_END'] # STUFF def on_frame(self, controller): # Get the most recent frame frame = controller.frame() # Get gesture as list gestures = list(frame.gestures()) # Count gestures numGestures = len(gestures) if numGestures >= 1: for gesture in gestures: if gesture.type == Leap.Gesture.TYPE_SWIPE: swipe = SwipeGesture(gesture) Swipe_direction = swipe.direction if(self.state_names[gesture.state] == 'STATE_START'): print("Swipe start") if(self.state_names[gesture.state] == 'STATE_UPDATE'): print("Swipe update") if(self.state_names[gesture.state] == 'STATE_END'): print("Swipe end") if(Swipe_direction[0] > 0): print("RIGHT SWIPE") elif(Swipe_direction[0] < 0): print("LEFT SWIPE")
https://forums.leapmotion.com/t/gesture-recognition-on-python3/8762
CC-MAIN-2020-45
refinedweb
660
65.62
At last Microsoft has released an early build new AJAX libraries based around version 2 of their .NET Framework. Skip this next section if you are already familiar with what AJAX is and don't want to read my lame ass description of it. The most basic intro to AJAX… Essentially AJAX is Asynchronous JavaScript and XML. At the core of it all what you get is the ability to use JavaScript to talk to the server asynchronously (meaning behind the scene in your pages, without tying up the interface). A practical example would be if you had two Combo boxes. Country and State. You drop down Country and State automagically populates with the appropriate states for the chosen country, of course this happens without pre-loading JavaScript on the client, nor doing a post back to the server directly. Typically at the core of any AJAX library we see something along the lines of first creating an instance of the ActiveXObject "Msxml2.XMLHTTP", and then using it to make the calls back to the server, asynchronously. Don't be afraid when you see "MSXML", see this post regarding cross platform support. Once the call has been completely the library usually bubbles the event back up to the method you state. For more details and a 100x better description see this doc. So now you know what AJAX is, what do I have to say about it... I have taken the time to quickly review the QuickStart and the core Atlas Documentation. I don't want to cover everything that is stated in both those documents you can read them if you like. I intend to just cover the highlights and give my thoughts on what I'm seeing. OOP: So the first thing we see is the fact that Microsoft has put allot of thought into the OOP aspect of programming (thank god!). We see that we get some tools for allowing Namespaces, Inheritance and Interfaces. You can literally register namespaces with the Type system on the client setup a class hierarchy and even implement interfaces. The syntax looks a bit strange but I'm sure we can adapt. ASMX Support: Next we see that they have enabled the whole ASMX Web Services goop to be easily accessible for us. Simply create your ASMX Web Services as you normally do, and then use <atlas:Script> blocks to include the common JavaScript libraries including the AtlasRuntime.js. I'm sure those includes will be cut down to one prior to RTM. I cant see any reason why we would need to have 3 JavaScript "include" blocks just for Web Services support or for simple AJAX support on the client, let the server determine and control exactly what support JavaScript it needs to pump out.. I immediately notice that their default library script is approx. 137KB, not sure if that is a very reasonable size but time will tell. What's cool is this next line: <script language="JavaScript" src="SimpleService.asmx/js"> Notice we simply need to point it to our same old ASMX service with the /js modifier on the URL. Here is the full URL in their help doc for the output of the "SimpleService.aspx/js". Notice it is simply emitting JavaScript out of the service. It would seem logical that the src attribute of the script tag above can be any sort of fully qualified URL, including offsite url's, but I don't see that stated anywhere in the help. Also, it would be nice to see some sort of a wrapper for non .NET services, to automatgically wrap up a simple WSDL with the appropriate JavaScript. Maybe they could add a /out:js parameter to the WSDL.exe command itself? We then could simply include that script as our source instead of the .asmx/js directly. If they don't enhance the wsdl.exe tool directly I would be willing to put money down that someone in the community will have a tool publish in the coming months prior to actual RTM. Serialization: As we expected, we can send and receive complex types via this toolkit. I wonder what serializer is used. The SOAP Serializer seems obvious for those calls to an actual Web Service endpoint, but what about non-Web Service endpoints? I hope we can just use typical/raw XML with out the SOAP bloat (envelope, body, etc). For SOAP Envelope's do we also get header support? Oh, I don't see any example of getting nor setting data with a DataSet. I bet you that this will be baked in as well. I personally limit my use of DS's but MSFT has pushed them onto us so much that most people do use them and you can expect support for them. Caching data received from an ASMX's seems pretty obvious. Do it on the server as we normally have done in the past. DataSource: Exposing a DataSource for Atlas to consume is as easy as pie. Take a look at the examples, some really amazing stuff going on there. Setup your service to inherit from "DataServer", implement the required methods; add the atlas:DataSource control to your page, point it to your DataService (asmx); add some control (for example a atlas:ListView control) and point it to your DataSource then wire up the events like click and such. A simple three step process to wire it all up, now that is what I like to see. ASP.NET Atlas Controls: This is where things start to go downhill. It would appear that the Atlas team has invested in an extensive library for markup of our client sided forms. The sections of code marked under "<script type="text/xml-atlas">" and "<script type="text/xml-script">". I personally don't like this direction. What are they thinking!? Currently, we have an object model for markup and event handling for controls on the server and now they want to add a completely new model for the client?! Why could we simply not take advantage of this "runat" attribute on our server sided controls and let the framework put it all together for us? runat="client" I understand that this stuff is (probably) not going to be included directly in the framework, v2, and will be shipped as a separate install, but come on guys! Another completely separate Object Model? Is that really necessary? How many will actually use this? Is there plans to actually include it in v3 of the framework? With the coming of XAML we will see yet another object model. That brings up my next point… My style of Adaptive Rendering… I have a great idea, which I stated many times already. Let's leverage this whole .NET Framework thing and create rendering engines. That is, this now called "adaptive rendering" we see in v2 for Web and Mobile controls, let's extend that right out. Have a single set of controls which us hard working developers need to learn and Microsoft, you build us rendering engines for each platform: Web, Web+AJAX, Mobile, Windows Forms, etc. If someone hits our URL with a XAML browser (essentially a Windows Forms client) render for that request. If they hit with Netscape 2, render old school Web, etc. I hit with IE7, render for it. Let's avoid tacking yet another object model into the mix. Server Class Library: First thing that stands out is the Microsoft.Web.Services.Converters.DataSetConverter. As I suspected it looks like they will be baking in some support for DataSets. Along with that it appears that we will be able to create our own Converters, just based on the Microsoft.Web.Services.JavsScriptConverter. Nice to know. Here we get to see all of the control classes which are currently exposed to the client. Nice big list, unfortunately its an entire new set of controls we will have to learn. Boo! Browser Support: What I would like to see as another final deliverable is a cross browser support matrix. I want to know exactly which feature is and is not supported on each and every (semi)popular browser on the market today, their versions and on alternative OS's. Scroll down on this page to get an idea of what I would expect. I think if MSFT really wants the industry to adapt this technology they will need to prove that it has a wide support base in the industry. Given this matrix it would allow us to really narrow down our browser/OS targets and enable us to make a more educated decision. I still haven't managed to find time to get some resources from Tech.Ed up - hopefully by this weekend.
http://weblogs.asp.net/rchartier/archive/2005/09/13/425039.aspx
crawl-002
refinedweb
1,460
72.05
Need help on decrypting/not sure how to start.Am I doing this right? This is the input file and I already created the output file. [code]#includ... Need help on decrypting/not sure how to start.Assignment: Write a C++ program to decrypt a 12 character message located in a file named “encr... Need help with Programming statistics[code]include <cmath> include <iostream> using namespace std; int main() { int a, b, c, d, e; cout <... Need help with Programming statistics Thanks. Need help with Programming statistics[code] #include <iostream> #include <cmath> using namespace std; int main() { AM = (a+b+c+d+e... This user does not accept Private Messages
http://www.cplusplus.com/user/abba901/
CC-MAIN-2013-48
refinedweb
110
68.87
: pointer_c: Function-pointer-based style for C. It is the most widely compatible, comparable to GLEW. It has variables to test whether an extension was loaded (and how many of its functions were loaded). Like GLEW, it requires calling an initialization function to set it up. This is best used for C or C++ users who need to be able to share the headers with other tools (note: usually, you don't need to do this). pointer_cpp: Function-pointer-based style for C++. It wraps all function pointers, extension variables, and enumerators in a namespace (not the typedefs). It requires calling an initialization function to set it up. This is best used for C++ users who don't need compatibility, but would like OpenGL stuff to not pollute the global namespace so much. func_cpp: Inline-function-based style for C++. This means that the header contains actual inline functions, which forward their parameters to the actual function pointers internally. Like pointer_cpp, most of OpenGL is in a namespace. This is best used for C++ users who want the best possible autocompletion from their IDE or coding tool of choice. noload_c: Automatic loading style for C. This is similar to the old loading tool GLee. Unlike the other styles, it does not require an initialization function; you simply call whatever function you want to use. The first time a call is encountered, it will load that function. This is best used for C or C++ users who don't want to do explicit initialization, and also want header compatibility like pointer_c. noload_cpp: Automatic loading style for C++. This is similar to the old loading tool GLee. Unlike the other styles, it does not require an initialization function; you simply call whatever function you want to use. The first time a call is encountered, it will load that function. It will wrap most of OpenGL in a namespace. This is best used for C++ users who don't want to do explicit initialization.
https://bitbucket.org/alfonse/glloadgen/wiki/Styles?_escaped_fragment_=user-created-styles
CC-MAIN-2016-30
refinedweb
331
66.33
We are back in Beta2 with a bunch of new stuff in Coded UI test for UI automation testers. First up, the code generation in Coded UI test has been changed to structure the code in a much more usable and intuitive way: 1. All the UI elements you interact with, whether part of recording or added from the UI control locator, all go into a single UI Map – a single collection of all the UI objects in your test. So, you can now edit objects from a single store 2. Every assertion you add is now a method in itself which takes parameters where you can define the expected value to assert on. So, you can now separate the test into logical actions and assertions 3. The recorded methods also have input parameters defined on them that help make data driving easier to do. So, you can now data drive the method by changing the values of the input parameters that go into the recorded method. For example, if you were testing the new user sign up in hotmail.com and checking if a certain id’s availability is displayed correctly, you can record steps to open hotmail.com, go to sign up page, enter a particular id and press “check availability” button. The coded UI test project generated has 4 files – the coded UI test .cs file (TestHotmail.cs) containing the test method, UIMap.uitest file which is an XML representation of all the UI elements and actions/assertions performed on each UI object, the UImap.designer.cs file which is the code-behind for the .uitest file containing code for the objects and actions, the UIMap.cs is a file containing a partial definition of the UImap class to help preserve user customizations to the test code. TestHotmail.cs – contains the actual test method and invocations to recorded methods and assertions [CodedUITest] public class TestHotmail { [TestMethod]public void TestNewUserSignUp(){ this.UIMap.GotoSignUpPage(); this.UIMap.CheckAvailabilityOfId(); this.UIMap.VerifyIdAvailable(); }} UIMap.designer.cs – contains the definitions of the recorded methods, assertions and UI objects. Plus also contains the parameter class definitions passed into each class public partial class UIMap { public void GotoSignUpPage() { HtmlInputButton signupButton = this.SignInWindowsInterneWindow.HttploginlivecomlogiClient.SignInDocument.SignupButton; // Click 'Sign up' button Mouse.Click(signupButton, new Point(47, 11)); } public void CheckAvailabilityOfId() { HtmlEdit imembernameliveEdit = this.SignupWindowsLiveWinWindow.HttpssignuplivecomsiClient.SignupWindowsLiveDocument.ImembernameliveEdit; // Type 'anutthar' in 'imembernamelive' text box imembernameliveEdit.Text = this.CheckAvailabilityOfIdParams.ImembernameliveEditText; // Click 'Check availability' button Mouse.Click(checkavailabilityButton, new Point(88, 15)); }} // Input parameter into the CheckAvailabilityOfId recorded method public class CheckAvailabilityOfIdParams { public string ImembernameliveEditText = "anutthar"; } Other than that, the CUIT builder has gone through a major redesign and morphed into a stack bar at the bottom of your screen with pop up dialogs for the control locator, actions viewer, generate code etc. More on that in the next post We’ve also added support for virtualized controls in WPF. You will need to wait until the UI Automation 3.0 APIs are available to get this working though. But this should certainly help WPF programmers trying to write tests on their UI apps. Go ahead, give CUIT a spin and tell us what you think… You mentioned for support of virtualized controls in WPF, UI Automation 3.0 APIs are needed. What is the schedule for that? Thanks. It’s out. Here you go: When running these tests automatically on a Test Environment in Test Center it seems like the test infrastructure is giving up before the last page load. I see the test agent pop up then "PRXY0007: The request or the response message was incomplete or malformed. An existing connection was forcibly closed by the remote host" shows up in the web browser. Manual tests work fine. [Anu] Hmm – no idea. Can you post it on to the forums and ping me if you don't get a response? I'll pursue it internally then Did you find a solution for this issue? [Anu] What issue? Hi, Any updates on the "PRXY0007: The request or the response message was incomplete or malformed." issue? I think it has something to do with the VSTS proxy server that is used for interacting with the AUT. [Anu] Pankaj – yes, sounds like it. Have you filed a bug on? Regards, Pankaj I just came across this issue when testing a webpage. I was getting the error "PRXY0007: The request or the response message was incomplete or malformed." about every second time i accessed the website. I thought it might be an Browser compatibility issue with the webpage so i tried IE and it works. The i googled the message and found this site. Its not a compatibility issue with the webpage its a compatibility issue with MTM and Chrome. If i start a test case, pause it and then try accessing the webpage i get the issue every time. If MTM is recording your actions it happens about every 2 times, i think this might be time boxed so if it happens 2 times in a short amount of time. If i then stop MTM it works fine [Anu] Ryan – could you please post this on with the appropriate logs I requested for? Thanks
https://blogs.msdn.microsoft.com/anutthara/2009/10/25/whats-new-for-testers-doing-ui-automation-in-vs-2010-beta2/
CC-MAIN-2017-47
refinedweb
864
56.05
#include <switch_arg.hpp> A simple switch argument. If the switch is set on the command line, then the getValue method will return the opposite of the default value for the switch. Definition at line 31 of file switch_arg.hpp. Definition at line 108 of file switch_arg.hpp. Definition at line 117 of file switch_arg.hpp. Checks a string to see if any of the chars in the string match the flag for this Switch. Definition at line 131 of file switch_arg.hpp. Returns bool, whether or not the switch has been set. Definition at line 129 of file switch_arg.hpp. Handles the processing of the argument. This re-implements the Arg version of this method to set the _value of the argument appropriately. Reimplemented in ecl::MultiSwitchArg. Definition at line 160 of file switch_arg.hpp. The value of the switch. Definition at line 38 of file switch_arg.hpp.
http://docs.ros.org/kinetic/api/ecl_command_line/html/classecl_1_1SwitchArg.html
CC-MAIN-2020-24
refinedweb
148
70.6
bigfloat man page math::bigfloat — Arbitrary precision floating-point numbers Synopsis package require Tcl 8.5 package require math::bigfloat ?2.0.1? fromstr number ?trailingZeros? tostr ?-nosci? number fromdouble double ?decimals? todouble number isInt number isFloat number int2float integer ?decimals? add x y sub x y mul x y div x y mod x y abs x opp x pow x n iszero x equal x y compare x y sqrt x log x exp x cos x sin x tan x cotan x acos x asin x atan x cosh x sinh x tanh x pi n rad2deg radians deg2rad degrees round x ceil x floor x Description The bigfloat package provides arbitrary precision floating-point math capabilities to the Tcl language. It is designed to work with Tcl 8.5, but for Tcl 8.4 is provided an earlier version of this package. See What About Tcl 8.4 ? for more explanations. By convention, we will talk about the numbers treated in this library as : - BigFloat for floating-point numbers of arbitrary length. - integers for arbitrary length signed integers, just as basic integers since Tcl 8.5. Each BigFloat is an interval, namely [m-d, m+d], where m is the mantissa and d the uncertainty, representing the limitation of that number's precision. This is why we call such mathematics interval computations. Just take an example in physics : when you measure a temperature, not all digits you read are significant. Sometimes you just cannot trust all digits - not to mention if doubles (f.p. numbers) can handle all these digits. BigFloat can handle this problem - trusting the digits you get - plus the ability to store numbers with an arbitrary precision. BigFloats are internally represented at Tcl lists: this package provides a set of procedures operating against the internal representation in order to : - perform math operations on BigFloats and (optionnaly) with integers. - convert BigFloats from their internal representations to strings, and vice versa. Introduction - fromstr number ?trailingZeros? Converts number into a BigFloat. Its precision is at least the number of digits provided by number. If the number contains only digits and eventually a minus sign, it is considered as an integer. Subsequently, no conversion is done at all. trailingZeros - the number of zeros to append at the end of the floating-point number to get more precision. It cannot be applied to an integer. # x and y are BigFloats : the first string contained a dot, and the second an e sign set x [fromstr -1.000000] set y [fromstr 2000e30] # let's see how we get integers set t 20000000000000 # the old way (package 1.2) is still supported for backwards compatibility : set m [fromstr 10000000000] # but we do not need fromstr for integers anymore set n -39 # t, m and n are integers The number's last digit is considered by the procedure to be true at +/-1, For example, 1.00 is the interval [0.99, 1.01], and 0.43 the interval [0.42, 0.44]. The Pi constant may be approximated by the number "3.1415". This string could be considered as the interval [3.1414 , 3.1416] by fromstr. So, when you mean 1.0 as a double, you may have to write 1.000000 to get enough precision. To learn more about this subject, see Precision. For example : set x [fromstr 1.0000000000] # the next line does the same, but smarter set y [fromstr 1. 10] - tostr ?-nosci? number Returns a string form of a BigFloat, in which all digits are exacts. All exact digits means a rounding may occur, for example to zero, if the uncertainty interval does not clearly show the true digits. number may be an integer, causing the command to return exactly the input argument. With the -nosci option, the number returned is never shown in scientific notation, i.e. not like '3.4523e+5' but like '345230.'. puts [tostr [fromstr 0.99999]] ;# 1.0000 puts [tostr [fromstr 1.00001]] ;# 1.0000 puts [tostr [fromstr 0.002]] ;# 0.e-2 See Precision for that matter. See also iszero for how to detect zeros, which is useful when performing a division. - fromdouble double ?decimals? Converts a double (a simple floating-point value) to a BigFloat, with exactly decimals digits. Without the decimals argument, it behaves like fromstr. Here, the only important feature you might care of is the ability to create BigFloats with a fixed number of decimals. tostr [fromstr 1.111 4] # returns : 1.111000 (3 zeros) tostr [fromdouble 1.111 4] # returns : 1.111 - todouble number Returns a double, that may be used in expr, from a BigFloat. - isInt number Returns 1 if number is an integer, 0 otherwise. - isFloat number Returns 1 if number is a BigFloat, 0 otherwise. - int2float integer ?decimals? Converts an integer to a BigFloat with decimals trailing zeros. The default, and minimal, number of decimals is 1. When converting back to string, one decimal is lost: set n 10 set x [int2float $n]; # like fromstr 10.0 puts [tostr $x]; # prints "10." set x [int2float $n 3]; # like fromstr 10.000 puts [tostr $x]; # prints "10.00" Arithmetics - add x y - sub x y - mul x y Return the sum, difference and product of x by y. x - may be either a BigFloat or an integer y - may be either a BigFloat or an integer When both are integers, these commands behave like expr. - div x y - mod x y Return the quotient and the rest of x divided by y. Each argument (x and y) can be either a BigFloat or an integer, but you cannot divide an integer by a BigFloat Divide by zero throws an error. - abs x Returns the absolute value of x - opp x Returns the opposite of x - pow x n Returns x taken to the nth power. It only works if n is an integer. x might be a BigFloat or an integer. Comparisons - iszero x Returns 1 if x is : - a BigFloat close enough to zero to raise "divide by zero". - the integer 0. See here how numbers that are close to zero are converted to strings: tostr [fromstr 0.001] ; # -> 0.e-2 tostr [fromstr 0.000000] ; # -> 0.e-5 tostr [fromstr -0.000001] ; # -> 0.e-5 tostr [fromstr 0.0] ; # -> 0. tostr [fromstr 0.002] ; # -> 0.e-2 set a [fromstr 0.002] ; # uncertainty interval : 0.001, 0.003 tostr $a ; # 0.e-2 iszero $a ; # false set a [fromstr 0.001] ; # uncertainty interval : 0.000, 0.002 tostr $a ; # 0.e-2 iszero $a ; # true - equal x y Returns 1 if x and y are equal, 0 elsewhere. - compare x y Returns 0 if both BigFloat arguments are equal, 1 if x is greater than y, and -1 if x is lower than y. You would not be able to compare an integer to a BigFloat : the operands should be both BigFloats, or both integers. Analysis - sqrt x - log x - exp x - cos x - sin x - tan x - cotan x - acos x - asin x - atan x - cosh x - sinh x - tanh x The above functions return, respectively, the following : square root, logarithm, exponential, cosine, sine, tangent, cotangent, arc cosine, arc sine, arc tangent, hyperbolic cosine, hyperbolic sine, hyperbolic tangent, of a BigFloat named x. - pi n Returns a BigFloat representing the Pi constant with n digits after the dot. n is a positive integer. - rad2deg radians - deg2rad degrees radians - angle expressed in radians (BigFloat) degrees - angle expressed in degrees (BigFloat) Convert an angle from radians to degrees, and vice versa. Rounding - round x - ceil x - floor x The above functions return the x BigFloat, rounded like with the same mathematical function in expr, and returns it as an integer. Precision How do conversions work with precision ? - When a BigFloat is converted from string, the internal representation holds its uncertainty as 1 at the level of the last digit. - During computations, the uncertainty of each result is internally computed the closest to the reality, thus saving the memory used. - When converting back to string, the digits that are printed are not subject to uncertainty. However, some rounding is done, as not doing so causes severe problems. Uncertainties are kept in the internal representation of the number ; it is recommended to use tostr only for outputting data (on the screen or in a file), and NEVER call fromstr with the result of tostr. It is better to always keep operands in their internal representation. Due to the internals of this library, the uncertainty interval may be slightly wider than expected, but this should not cause false digits. Now you may ask this question : What precision am I going to get after calling add, sub, mul or div? First you set a number from the string representation and, by the way, its uncertainty is set: set a [fromstr 1.230] # $a belongs to [1.229, 1.231] set a [fromstr 1.000] # $a belongs to [0.999, 1.001] # $a has a relative uncertainty of 0.1% : 0.001(the uncertainty)/1.000(the medium value) The uncertainty of the sum, or the difference, of two numbers, is the sum of their respective uncertainties. set a [fromstr 1.230] set b [fromstr 2.340] set sum [add $a $b]] # the result is : [3.568, 3.572] (the last digit is known with an uncertainty of 2) tostr $sum ; # 3.57 But when, for example, we add or substract an integer to a BigFloat, the relative uncertainty of the result is unchanged. So it is desirable not to convert integers to BigFloats: set a [fromstr 0.999999999] # now something dangerous set b [fromstr 2.000] # the result has only 3 digits tostr [add $a $b] # how to keep precision at its maximum puts [tostr [add $a 2]] For multiplication and division, the relative uncertainties of the product or the quotient, is the sum of the relative uncertainties of the operands. Take care of division by zero : check each divider with iszero. set num [fromstr 4.00] set denom [fromstr 0.01] puts [iszero $denom];# true set quotient [div $num $denom];# error : divide by zero # opposites of our operands puts [compare $num [opp $num]]; # 1 puts [compare $denom [opp $denom]]; # 0 !!! # No suprise ! 0 and its opposite are the same... Effects of the precision of a number considered equal to zero to the cos function: puts [tostr [cos [fromstr 0. 10]]]; # -> 1.000000000 puts [tostr [cos [fromstr 0. 5]]]; # -> 1.0000 puts [tostr [cos [fromstr 0e-10]]]; # -> 1.000000000 puts [tostr [cos [fromstr 1e-10]]]; # -> 1.000000000 BigFloats with different internal representations may be converted to the same string. For most analysis functions (cosine, square root, logarithm, etc.), determining the precision of the result is difficult. It seems however that in many cases, the loss of precision in the result is of one or two digits. There are some exceptions : for example, tostr [exp [fromstr 100.0 10]] # returns : 2.688117142e+43 which has only 10 digits of precision, although the entry # has 14 digits of precision. What About Tcl 8.4 ? If your setup do not provide Tcl 8.5 but supports 8.4, the package can still be loaded, switching back to math::bigfloat 1.2. Indeed, an important function introduced in Tcl 8.5 is required - the ability to handle bignums, that we can do with expr. Before 8.5, this ability was provided by several packages, including the pure-Tcl math::bignum package provided by tcllib. In this case, all you need to know, is that arguments to the commands explained here, are expected to be in their internal representation. So even with integers, you will need to call fromstr and tostr in order to convert them between string and internal representations. # # with Tcl 8.5 # ============ set a [pi 20] # round returns an integer and 'everything is a string' applies to integers # whatever big they are puts [round [mul $a 10000000000]] # # the same with Tcl 8.4 # ===================== set a [pi 20] # bignums (arbitrary length integers) need a conversion hook set b [fromstr 10000000000] # round returns a bignum: # before printing it, we need to convert it with 'tostr' puts [tostr [round [mul $a $b]]] Namespaces and Other Packages We have not yet discussed about namespaces because we assumed that you had imported public commands into the global namespace, like this: namespace import ::math::bigfloat::* If you matter much about avoiding names conflicts, I considere it should be resolved by the following : package require math::bigfloat # beware: namespace ensembles are not available in Tcl 8.4 namespace eval ::math::bigfloat {namespace ensemble create -command ::bigfloat} # from now, the bigfloat command takes as subcommands all original math::bigfloat::* commands set a [bigfloat sub [bigfloat fromstr 2.000] [bigfloat fromstr 0.530]] puts [bigfloat tostr $a] Examples Guess what happens when you are doing some astronomy. Here is an example : # convert acurrate angles with a millisecond-rated accuracy proc degree-angle {degrees minutes seconds milliseconds} { set result 0 set div 1 foreach factor {1 1000 60 60} var [list $milliseconds $seconds $minutes $degrees] { # we convert each entry var into milliseconds set div [expr {$div*$factor}] incr result [expr {$var*$div}] } return [div [int2float $result] $div] } # load the package package require math::bigfloat namespace import ::math::bigfloat::* # work with angles : a standard formula for navigation (taking bearings) set angle1 [deg2rad [degree-angle 20 30 40 0]] set angle2 [deg2rad [degree-angle 21 0 50 500]] set opposite3 [deg2rad [degree-angle 51 0 50 500]] set sinProduct [mul [sin $angle1] [sin $angle2]] set cosProduct [mul [cos $angle1] [cos $angle2]] set angle3 [asin [add [mul $sinProduct [cos $opposite3]] $cosProduct]] puts "angle3 : [tostr [rad2deg $angle3]]" Bugs, Ideas, Feedback This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category math :: bignum :: float of the Tcllib Trackers []. Please also report any ideas for enhancements you may have for either package and/or documentation. Keywords computations, floating-point, interval, math, multiprecision, tcl Category Mathematics Copyright (c) 2004-2008, by Stephane Arnold <stephanearnold at yahoo dot fr>
https://www.mankier.com/n/bigfloat
CC-MAIN-2017-22
refinedweb
2,344
65.42
srec_mos_tech - MOS Technology file format The MOS Technology | CRLF | +--+--------+---------+------+----------+------+ Length The record length field is a 2 character (1 byte) field that specifies the number of data bytes in the record. Typically this is 24 or less. Address This is a 2‐byte address that specifies where the data in the record is to be loaded into memory, big‐endian. Data The data field contains the executable code, memory‐loadable data or descriptive information to be transferred. Checksum The checksum is an 2‐byte field that represents the least significant two bytes of the the sum of the values represented by the pairs of characters making up the record’s length, address, and data fields, big‐endian. End of File The final line should have a data length of zero, and the data line count in the address field. The checksum is not the usual checksum, it is instead a repeat of the data line count. Size Multiplier In general, binary data will expand in sized by approximately 2.54 times when represented with this format. Here is an example MOS Technology format file. It contains the data “Hello, World” to be loaded at address 0. ;0C000048656C6C6F2C20576F726C640454 ;0000010001. Peter Miller E‐Mail: pmiller@opensource.org.au /\/\* WWW: KIM‐1 User Manual - Appendix F - Paper Tape Format (The following information is reproduced from just in case it vanishes from the Web.) The paper tape LOAD and DUMP routines store and retrieve data in a specific format designed to insure error free recovery. Each byte of data to be stored is converted to two half bytes. The half bytes (whose possible values are 0 to F HEX) are translated into their ASCII equivalents and written out onto paper tape in this form. Each record outputted begins with a “;” character (ASCII 3B) to mark the start of a valid record. The next byte transmitted (18HEX) or (24 decimal) is the number of data bytes contained in the record. The record’s starting address High (1 byte, 2 characters), starting address Lo (1 byte, 2 characters), and data (24 bytes, 48 characters) follow. Each record is terminated by the record’s check‐sum (2 bytes, 4 characters), a carriage return (ASCII 0D), line feed (ASCII 0A), and six “NULL”‐sum digits. An “XOFF” character ends the transmission. ;180000FFEEDDCCBBAA0099887766554433221122334455667788990AFC ;0000010001 During a “LOAD” all incoming data is ignored until a “;” character is received. The receipt of non ASCII data or a mismatch between a records calculated check‐sum and the check‐sum read from tape will cause an error condition to be recognized by KIM. The check‐sum is calculated by adding all data in the record except the “;” character. The paper tape format described is compatible with all other MOS Technology, Inc. software support programs.
http://huge-man-linux.net/man5/srec_mos_tech.html
CC-MAIN-2017-30
refinedweb
461
62.68
Created on 2010-04-03 10:27 by kristjan.jonsson, last changed 2010-08-06 16:50 by terry.reedy. This issue is now closed. This patch does several things: 1) Creates a separate lock type PyThread_type_gil and locking functions for that. This allows tweaking of the GIL without affecting regular lock behaviour. 2) Creates a uniform implementation of the GIL on windows/pthreads using macros, with emulated condition variables on windows (Lifted Antoine's code from py3k, adding own improvements to the slightly problematic windows implementation). This makes the GIL behave the same on windows and pthreads platforms, if we so choose, and allows cross-platform development. 3) provide three GIL implementations: a) legacy gil, which is the same as the one used on pthreads b) a roundrobin gil, which fixes the multicore problem on pthreads and exhibits the same behaviour as the legacy GIL on windows did (no jumping the gil queue) c) a priority based gil, with n given priority levels, and optionally, the ability to request immediate GIL drop by the ceval.c loop. See thread_gil.h for details of the three modes. In my experiments using David Beazley's scripts from, implementation "b" fixed the performance problems encountered on multicore machines. This is, I believe, the original impetus for Antoine Pitrou's work on the new GIL. Implementation "c" improved data transfer still, by allowing faster wakeup of completed IO. Please note that I was not able to test this patch on a pthreads machine, I can only hope that it compiles :) I think this is too late for 2.7. 2.7b1 will be released RSN, and we should not implement such a change after the first beta release. Without looking at this patch, I think it would wise to proceed with caution on incorporating any kind of GIL patch into 2.X. If there is anything to be taken away from my own working studying the GIL, it's that the problem is far more tricky than it looks and that any kind of fix has the potential to adversely affect something that you might not expect. That said, I would only suggest that any kind of "new gil" incorporated in 2.X be disabled by default and enabled with special configuration options for those who want to try it out. Martin: Well, this patch was originally conceived more as a demonstration of the GIL problem and an alternative fix proposal. However, it is possible to configure it so that there is no change from existing functionality, simply by not including thread_gil.h in thread_pthread.h and thread_nt.h. The only change would then be the presence of the new PyThread_type_gil and associating locking functions which delegate directly to the old PyThread_type_lock functions. Antoine: Please take a look, the change is really simple, particularly the ROUNDROBIN_GIL variant which fixes the originally observed problem. the GIL is still a lock, implemented using a mutex and a semaphore. It is modified to work exactly as the lock always has done on windows (which is why the original problem isn't present on that platform). The simplicity of the change stems from the fact that the gil is still just a mutex-type object, which is aqcuired and released just as it has always been. The change is in the internal rules of the mutex, making sure that threads queue up properly and (optionally) that they are released in a priority based order. I'm not sure where you're getting your information, but the original GIL problem *DEFINITELY* exists on multicore Windows machines. I've had numerous participants try it in training classes and workshops they've all observed severely degraded performance for CPU-bound threads on Windows (XP, Vista, and Windows 7). Just ran the CPU-bound GIL test on my wife's dual core Windows Vista machine. The code runs twice as slow using two threads as it does using no threads (original observed behavior in my GIL talk). Kristjan, I agree with Martin, it's probably too late to make such changes for 2.7. Additionally, your "round-robin" scheme only seems round-robin when there are two threads competing. Otherwise, you could have three threads A, B and C, and the GIL bouncing between A and B. I would advocate opening a separate issue to improve the Windows condition variable code under 3.x. Silly question, I know, but why isn't the GIL just implemented as a lock of the host operating system? After all, we want mutual exclusion, I don't see why condition variables are required for this. I have to admin that I did not look at the source, so the reason might be documented there. It's not a simple mutex because if you did that, you would have performance problems much worse than those described in issue 7946. Sorry, what I meant with the "original problem" was the phenomenon observed by Antoine (IIRC) that the same CPU thread tends to hog the gil, even when releaseing it in ceval.c. What I have been looking at up to now is chiefly IO performance using David's iotest.py, and improving the poor performance of IO. IO will not suffer as badly on windows because the IO thread will get its fair slice of execution time. Promted by you, I added this bit of code to the iotest.py: spins = 0 laststat = 0 def spin(): global spins, laststat task,args = task_pidigits() while True: r= task(*args) spins += 1 t = time.clock() if t-laststat > 1: print spins/(t-laststat) spins = 0 laststat = t You are right, however that cpu throughput of multiple cpu bound thread suffers. And in fact, on windows, it appears to suffer the least using the LEGACY_GIL implementation. This is, I conjecture, because there are far fewer context switches (because relinqushing the GIL fails). My conjecture is that context switches between threads on two cores are so expensive as to dramatically affect performance. Normal multithreaded programs don't suffer from this because the threads are kept busy. But in our case, we are stopping one thread on one core, and starting another on a separate core, and this causes latency. Now, I've improved my patch somewhat. First off, I fixed some minor errors in the PRIORITY_GIL implementation. But more importantly, I added something called FIFOCOND. It is a condition variable that guarantees the FIFO property. This was prompted by my observation that even Windows' Semaphore doesn't do that, rather the windows scheduler may allow the currently executing thread to jump ahead in the semaphore queue. The FIFOCOND condition variable fixes that using explicit scheduling, and is intended as a diagnostic tool. (Antoine, your comment from 13:04 about "roundrobin" inasfar as that we don't know anything about the condition variable behaviour. I was assuming FIFO behaviour for the sake of argument, and I thought I´ put it in to the comments that we assume a general 'fairness' there. Put in the FIFOCOND and you will have that fairness guaranteed.) At any rate, I believe my patch provides a useful platform for further experimentation. 1) Factoring out the gil as a separate type of lock (which it must be) 2) allowing for different implementation of the GIL 3) shoring up the Condition variable implementation on Windows 4) Providing a FIFOCOND_T type to enforce a particular scheduling order, and demonstrating how we can be explicit about thread scheduling. I have already demonstrated that using the PRIORITY_GIL method fixes the problem with IO threads in the presence of CPU bound threads. Your iotest.py script is perfect for this, using 2 worker threads. On windows, the problem with IO wasn't so grave as I have explained (windows by default works as the ROUNDROBIN_GIL implementation, not the LEGACY_GIL mode used on pthreads). The PRIORITY_GIL solution is particularly effective with multicore on Windows, but it also improves IO throughput if cpu affinity of the server is fixed to one CPU, i.e. on singlecore. I have no fix for CPU bound threads, and I honestly don't think such a fix exists, except by causing switches to happen far less frequently, e.g. by raising the checkinterval, and so mitigating the problem (which is what the new gil in py3k does with its timeout implementation) But the IO fix for pthreads To summarise then: 1) The GIL has two problems on multicore machines a) performance of CPU threads goes down b) performance of IO in the presence of CPU threads is abysmal, but not on Windows 2) We can fix problem b) on pthreads with the ROUNDROBIN_GIL implementation. 3) We can improve IO performance in the presence of CPU threads on pthreads and Windows using the PRIORITY_GIL implementation, even to become faster than on a single core. 4) We cannot do anything about decreased performance of co-operatively switching CPU threads on multicore except switching less frequently. But this is quite feasible now with the PRIORITY_GIL implementation because it can request an immediate gil drop when IO is ready. So raising the checkinterval will not affect IO performance in a negative way. Please have a look at the latest patch with IO thread performance in mind. It is currently configured to enable the PRIORITY_GIL implementation without the FIFOCOND on windows and pthreads. I just did some profiling. I´m using visual studio team edition which has some fancy built in profiling. I decided to compare the performance of the iotest.py script with two cpu threads, running for 10 seconds with processor affinity enabled and disabled. I added this code to the script: if affinity: import ctypes i = ctypes.c_int() i.value = 1 ctypes.windll.kernel32.SetProcessAffinityMask(-1, 1) Regular instruction counter sampling showed no differences. There were no indications of excessive time being used in the GIL or any strangeness with the locking primitives. So, I decided to sample on cpu performance counters. Following up on my conjecture from yesterday, that this was due to inefficiencies in switching between cpus, I settled on sampling the instruction fetch stall cycles from the instruction fetch unit. I sample every 1000000 stalls. I get interesting results. With affinity: Functions Causing Most Work Name Samples % _PyObject_Call 403 99,02 _PyEval_EvalFrameEx 402 98,77 _PyEval_EvalCodeEx 402 98,77 _PyEval_CallObjectWithKeywords 400 98,28 call_function 395 97,05 affinity off: Functions Causing Most Work Name Samples % _PyEval_EvalFrameEx 1.937 99,28 _PyEval_EvalCodeEx 1.937 99,28 _PyEval_CallObjectWithKeywords 1.936 99,23 _PyObject_Call 1.936 99,23 _threadstartex 1.934 99,13 When we run on both cores, we get four times as many L1 instruction cache hits! So, what appears to be happening is that each time that a switch occurs the L1 instruction cache for each core must be repopulated with the python evaluation loop, it having been evacuated on that core during the hiatus. Note that for this effect to kick in we need a large piece of code excercising the cache, such as the evaluation loop. Earlier today, I wrote a simple (python free) C program to do similar testing, using a GIL, and found no performance degradation due to multi core, but that program only had a very simple "work" function. So, this confirms my hypothesis: The downgrading of the performance of python cpu bound threads on multicore machines stems from the shuttling about of the python evaluation loop between the instruction caches of the individual cores. How best to combat this? I'll do some experiments on Windows. Perhaps we can identify cpu-bound threads and group them on a single core. [...] > _PyObject_Call 403 99,02 [...] > affinity off: > Functions Causing Most Work > Name Samples % [...] > _PyObject_Call 1.936 99,23 [...] > _threadstartex 1.934 99,13 > > When we run on both cores, we get four times as many L1 instruction cache hits! You mean we get 4x the number of cache /misses/, right? This analysis is gratuitous if you can't evaluate/measure/calculate the actual cost (in proportion of total elapsed or CPU time) of the instruction cache misses. Perhaps it is actually negligible and the slowdown is caused by something else. > How best to combat this? I'll do some experiments on Windows. > Perhaps we can identify cpu-bound threads and group them on a single > core. IMHO, the OS should handle this. I don't think ad-hoc platform-specific CPU affinity tweaks belong in the Python core.. The analysis of instruction cache behavior is interesting---I could definitely see that coming into play given the heavy penalty that one sees going to multiple cores (it's a side effect in addition everything else that goes wrong such as a huge increase in the number of system calls). I will only point out that messing around with processor affinities is going to be problematic. There are C/C++ extensions to Python that intentionally release the GIL and want to run fully multithreaded across as many cores as might be available. Setting a processor affinities is going to be the exact opposite of what you want for code like that. > The counter is "stall cycles". > During the 10 second run on my 2.4Ghz cpu, we had instruction cache > miss stalls for 2 billion cycles (2000 samples of 1000000 cycles per > sample). That does account for around 10% of the availible cpu. Ok, thanks. > 2) The poor performance of competing CPU threads on multicore machines > is due to the instruction cache behaviour of non-overlapping thread > execution on different cores. Have you tried your measurement approach with ccbench? > We can fix 1) easily, even with a much less invasive patch than the > ones I have put in here. I'm a bit surprised at the apparent > disinterest in such an obvious bug / fix. As already said, it's too late for 2.7. And the fix in 3.2 is most probably better. David, yes messing about with processor affinities is certainly not nice. Especially since the issue is cross-platform. The pthreads api doesn't offer much. There is pthreadd_setschedparam(), and pthreads_setconcurrency(). Unfortunately I don't have a pthreads machine to test that with. On windows, one possibility would be to switch to fibers, in the case of a yielding thread. I don't know if that would change anything, or if the thread-to-fiber and vice versa conversion is lightweight enough to be used dynamically. Antoine: I'm not familiar with ccbench. I´ll look into it. As for my FIFO fix, py3k is trying to do more, namely get rid of the checkinterval. It is most certainly a more complex solution and with it its own set of problems. The only thing that needs fixing is to add "fairness" to the GIL. I know that this is coming a bit late for 2.7 and I'm not pushing it as such for 2.7. But after 2.7 comes 2.8 (and so on ad infinitum) But I'm also pointing out the obvious problem and an obvious simple fix which doesn't involve inventing a whole new system. I would have thought that this should at least spark some enthusiasm. It's unfortunate, maybe, that I only realized so late that the pythread GIL was implemented using a homebrew condition variable mechanism. I always thougth (being a windows guy) that it were simply using the pthread_mutex() and thus the greedy behaviour of the GIL could be ascribed to that. Anyway, I´ll continue giving this patch some love. I wouldn't be surprised if it, and especially the "priority" variant, would be appealing to people doing e.g. webservers with 2.x technology. Another thing that the "priority" patch has done is convince me that I really need to implement this scheduling mode in stackless, since it does appear to help network latency when using FIFO scheduling of threads / tasklets. Cheers! If it really improves multicore performance and none of our test fail (even in memory/resource/time survival tests) then I'd give it a try even after a beta. 2.x is still the best practical version out there. I looked at ccbench. It's a great tool. I've added two features to it (see the attached patch) -y option to turn off the "do_yield" option in throughput, and so measure thread scheduling without assistance, and the throughput option now also computes "balance", which is the standard deviation of the throughput of each thread normalized by the average. I give you three results for throughput, to demonstrate the ROUNDROBIN_GIL implementation: 1) LEGACY_GIL, no forced switching C:\pydev\python\trunk\PCbuild>python.exe ..\Tools\ccbench\ccbench.py -y -t == CPython 2.7a4+.0 (trunk) == == AMD64 Windows on 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' == --- Throughput --- Pi calculation (Python) threads= 1: 672 iterations/s. balance threads= 2: 597 ( 88%) 0.4243 threads= 3: 603 ( 89%) 0.2475 threads= 4: 596 ( 88%) 0.4776 regular expression (C) threads= 1: 571 iterations/s. balance threads= 2: 565 ( 98%) 0.6203 threads= 3: 567 ( 99%) 1.6867 threads= 4: 570 ( 99%) 1.1670 SHA1 hashing (C) threads= 1: 1269 iterations/s. balance threads= 2: 1268 ( 99%) 1.1470 threads= 3: 1270 (100%) 0.6024 threads= 4: 1263 ( 99%) 0.7419 LEGACY_GIL, with forced switching C:\pydev\python\trunk\PCbuild>python.exe ..\Tools\ccbench\ccbench.py -t == CPython 2.7a4+.0 (trunk) == == AMD64 Windows on 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' == --- Throughput --- Pi calculation (Python) threads= 1: 663 iterations/s. balance threads= 2: 605 ( 91%) 0.0232 threads= 3: 599 ( 90%) 0.1988 threads= 4: 601 ( 90%) 0.4648 regular expression (C) threads= 1: 568 iterations/s. balance threads= 2: 562 ( 99%) 0.1737 threads= 3: 571 (100%) 0.3950 threads= 4: 566 ( 99%) 0.3158. Now, for ROUNDROBIN_GIL, and no forced switching: C:\pydev\python\trunk\PCbuild>python.exe ..\Tools\ccbench\ccbench.py -t -y == CPython 2.7a4+.0 (trunk) == == AMD64 Windows on 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' == --- Throughput --- Pi calculation (Python) threads= 1: 672 iterations/s. balance threads= 2: 485 ( 72%) 0.0289 threads= 3: 448 ( 66%) 0.0737 threads= 4: 476 ( 70%) 0.0408 regular expression (C) threads= 1: 569 iterations/s. balance threads= 2: 551 ( 96%) 0.0505 threads= 3: 551 ( 96%) 0.1637 threads= 4: 551 ( 96%) 0.2020 SHA1 hashing (C) threads= 1: 1271 iterations/s. balance threads= 2: 1262 ( 99%) 0.0111 threads= 3: 1207 ( 94%) 0.0143 threads= 4: 1202 ( 94%) 0.0317 Notice the much better balance value, and this is without the forced sleep. Also note a lower througput when computing pi with threads. This is because yielding every 100 opcodes now actually works, and the aforementioned instruction cache problem kicks in. Increasing the checkinterval to 1000 solves this: C:\pydev\python\trunk\PCbuild>python.exe ..\Tools\ccbench\ccbench.py -t -y -i100 0 == CPython 2.7a4+.0 (trunk) == == AMD64 Windows on 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' == --- Throughput --- Pi calculation (Python) threads= 1: 673 iterations/s. balance threads= 2: 628 ( 93%) 0.0000 threads= 3: 603 ( 89%) 0.0284 threads= 4: 606 ( 90%) 0.0328 regular expression (C) threads= 1: 570 iterations/s. balance threads= 2: 569 ( 99%) 0.2729 threads= 3: 562 ( 98%) 0.6595 threads= 4: 560 ( 98%) 1.2440 SHA1 hashing (C) threads= 1: 1265 iterations/s. balance threads= 2: 1256 ( 99%) 0.0000 threads= 3: 1264 ( 99%) 0.0759 threads= 4: 1255 ( 99%) 0.1309 If no one objects, I'd like to submit this changed ccbench.py to the trunk. Fyi, here is the output using the unmodified Windows GIL, i.e. without my patch being active: C:\pydev\python\trunk\PCbuild>python.exe ..\Tools\ccbench\ccbench.py -t -y == CPython 2.7a4+.0 (trunk) == == AMD64 Windows on 'Intel64 Family 6 Model 23 Stepping 6, GenuineIntel' == --- Throughput --- Pi calculation (Python) threads= 1: 623 iterations/s. balance threads= 2: 489 ( 78%) 0.0289 threads= 3: 461 ( 74%) 0.0369 threads= 4: 460 ( 73%) 0.0426 regular expression (C) threads= 1: 515 iterations/s. balance threads= 2: 548 (106%) 0.0771 threads= 3: 532 (103%) 0.0556 threads= 4: 523 (101%) 0.1132 SHA1 hashing (C) threads= 1: 1188 iterations/s. balance threads= 2: 1212 (102%) 0.0232 threads= 3: 1198 (100%) 0.0250 threads= 4: 1215 (102%) 0.0163 You see results virtually identical to the ROUNDROBIN_GIL implementation. This is just do demonstrate that Windows has had the ROUNDROBIN_GIL behaviour all along. I must be missing something, but why, exactly would you want multiple CPU-bound threads to yield every 100 ticks? Frankly, that sounds like a horrible idea that is going to hammer your system with excessive context switching overhead and cache performance problems---an effect that you, yourself have actually observed. The results of ccbench also show worse performance for the round-robin GIL because of this. Although the legacy GIL signals every 100 ticks, threads do not context switch that rapidly. In fact, on single CPU systems, they context switch at about the same rate as the system time-slice (5-10 milliseconds on most systems). The new GIL implemented by Antoine also does not rapidly switch CPU-bound threads. Again, I must be missing something, but I don't see how this round-robin GIL and all of this forced thread switching is anything that you would ever want--especially for CPU-bound threads. It seems to go against just about every design goal that people usually have for schedulers (especially the goal of minimizing context switching overhead). Again, maybe I'm just being dense and missing something. Sorry, but I don't see how you can say that the round-robin GIL and the legacy GIL have the same behavior based solely on the result of a performance benchmark. Do you have any kind of thread scheduling trace that proves they are scheduling threads in exactly the same manner? Maybe they both have lousy performance, but for different reasons. >. Which is not unreasonable, since SHA1 releases the GIL. The unbalance would be produced by the Windows scheduler, not by Python. Note: "do_yield" is not meant to "balance" things as much as to make measurements meaningful at all. Without switching at all during say 2 seconds, the numbers become totally worthless. > If no one objects, I'd like to submit this changed ccbench.py to the trunk. Please let me take a look. David, I don't necessarily think it is reasonable to yield every 100 opcodes, but that is the _intent_ of the current code base. Checkinterval is set to 100. If you don't want that, then set it higher. Your statement is like saying: "Why would you want to have your windows fit tightly, it sounds like a horrible thing for the air quality indoors" (I actually got this when living in Germany). The answer is, of course, that a snugly fitting window can still be opened if you want, but more importantly, you _can_ close it properly. And because the condition variable isn't strictly FIFO, it actually doesn't switch every time (an observation. The scheduler may decide o do its own things inside the condition variable / semaphore). What the ROUNDROBIN_GIL ensures, however, is that the condition variable is _entered_ every checkinterval. What I'm trying to demonsrate to you is the brokenness of the legacy GIL (as observed by Antoine long ago) and how it is not broken on windows. It is broken because the currently running thread is biased to reaquire the GIL immediately in an unpredictable fashion that is not being managed by the (OS) thread scheduler. Because it doesn't enter the condition variable wait when others are competing for it, the scheduler has no means of providing "fairness" to the application. So, to summarise this: I'm not proposing that we context switch every 100 opcodes, but I am proposing that we context switch consistently according to whatever checkinterval is put in place. Antoine, in case you misunderstood: I´m saying that the ROUNDROBIN_GIL and the Windows GIL are the same. If you don't believe me, take a look at the NonRecursiveLock implementation for windows. I'm also starting to think that you didn't actually bother to look at the patch. Please compare PyLock_gil_acquire() for LEGACY_GIL and ROUNDROBIN_GIL and see if you can spot the difference. Really, it's just two lines of code. Maybe it needs restating. The bug is this (python pseudocode) with gil.cond: while not gil.locked: #this line is the bug gil.cond.wait() gil.locked = True vs. with gil.cond: if gil.n_waiting or gil.locked: gil.n_waiting += 1 while True: gil.cond.wait() #always wait at least once if not gil.locked: break gil.n_waiting -= 1 gil.locked = True The cond.wait() is where fairness ensues, where the OS can decide to serve threads roughly on a first come, first serve basis. If you are biased towards not entering it at all (when yielding the GIL), then you have taken away the OS' chance of scheduling. Antoine (2): The need to have do_yield is a symptom of the brokenness of the GIL. You have a checkinterval of 100, which elapses some 1000 times per second, and yet you have to put in place special fudge code to ensure that we do get switches every few seconds? The whole point of the checkinterval is for you _not_ to have to dot the code with sleep() calls. Surely you don't expect the average application developer to do that if he wants his two cpu bound threads to compete fairly for the GIL? This is why I added the -y switch: To emulate normal application code. Also, the 0.7 imbalance observed in the SHA1 disappears on windows, (and using ROUNDROBIN_GIL). It is not due to the windows scheduler, it is due to the broken legacy_gil. This last slew of comments has been about the ROUNDROBIN_GIL only. I haven't dazzled you yet with PRIORITY_GIL, but that solves both problems because it is _fair_, and it allows us to increase the checkinterval to 10000, thus elimintating the rapid switching overhead, and yet gives fast response to IO. > Antoine (2): The need to have do_yield is a symptom of the brokenness > of the GIL. Of course it is. But the point of the benchmark is to give valid results even with the old broken GIL. I could remove do_yield and still have it give valid results, but that would mean running each step for 30 seconds instead of 2. I don't like having to wait several minutes for benchmark numbers :-) I'm sorry, I still don't get the supposed benefits of this round-robin patch over the legacy GIL. Given that using interpreter ticks as a basis for thread scheduling is problematic to begin with (mostly due to the fact that ticks have totally unpredictable execution times), I'd much rather see further GIL work continue to build upon the time-based scheduler that's been implemented in Python 3.2. For instance, I think being able to specify a thread-switching interval in seconds (sys.setswitchinternal) makes much more sense than continuing to fool around with check intervals and all of this tick business. The new GIL implementation is by no means perfect, but people are working on it. I'd much rather know if anything that you've worked out with this patch can be applied to that version of the GIL.. The GIL on windows, (and the poorly named ROUNDROBIN_GIL) is a "fair" synchronization primitive. Unfair mutexes have their place, and such is the behaviour of the windows condition variable (and the pthreads mutex, I suspect). But they are not useful if you want to provide fair access to a resource that is held all the time. Until after that GIL business at PyCon I wasn't aware of this fundamental difference between the GIL on windows and pthreads platforms in 2.x. It is astonishing to me that no one appears to have noticed the difference, or made much of it. CPU threads are scheduled fairly on windows, and incredibly unfairly on pthreads. with the ROUNDROBIN_GIL I'm not proposing anything radical, I'm just suggesting that we adopt the superior behaviour that has been on windows all along. Yes, people actually do use windows. Antoine, I understand that your point about do_yield, yet the results for 3 seconds without it are telling on their own, and worthy of being studied, which is why I suggested disabling it. Also, I think you will find that he imbalance in the throughput of the threads won't go away even after 30 seconds. Unfortunately, the unfairness is such that it may actually diverge. I've improved my patch some more. I'll upload it soon. In particular, I've addea a PyThread_gil_yield() method to enable whatever underlying gil there is to possible deal with this particular locking case differently, if possible, perhaps suggesting to the OS not to switch cores. I´ve also created a simple program in visual studio to examine a GIL outside the context of python. I'll put it here tomorrow too, for those interested. It allows for simpler experimentation, although because the loop is small, you won't see the effect of the instruction cache problems. David, I actually think that the checkinterval is a perfectly good mechanism, especially if augmented with an interrupt mechanism What does it matter if some opcodes are slower than others? when we are checking every 100 or 1000 (or 10000 as I am proposing) that hardly matters. We just need to have an order of magnitude thing there. But there are other ways to do it. You can use a timer on windows, and on pthreads too, I think. But the whole point of this patch is to take a step back, and to see if there is a way to fix the "gil problem" in a simpler way by first trying to understand it fully, and then apply minimal changes to solve it. Kristjan, > Maybe the state of this discussion is my fault for not being clear enough. It's quite a bit simpler. The first 2.7 beta has been released and there's IMO no way such patches will be accepted. It doesn't seem to be a pressing enough issue to be considered a real bug. As you said yourself, most people actually aren't really affected, or not enough. > CPU threads are scheduled fairly on windows, and incredibly unfairly > on pthreads. pthreads doesn't schedule anything. The kernel does. I'm sure that on non-tiny periods (>= 5s) they are scheduled quite fairly. It's just that switching occurs less often and less regularly than you'd might hope. > Antoine, I understand that your point about do_yield, yet the results > for 3 seconds without it are telling on their own, and worthy of being > studied, which is why I suggested disabling it. As I said, they will render 2.x results completely wrong (at least under Linux). > Also, I think you will find that he imbalance in the throughput of the > threads won't go away even after 30 seconds. I'm actually not really interested in confirming this, but as I said there's no reason to think that the Linux kernel does a bad job. (the one reputed to do a bad job at scheduling, especially for desktop environments, is the Windows kernel) > I've improved my patch some more. I'll upload it soon. If you are interested in taking it further, I would recommend publishing your patch (and prebuilt binaries, if you care) somewhere else as well, because as I said there's probably no way it gets integrated during what remains of the 2.x timeline. Of course, other developers might disagree with me, in which case your patch /can/ be integrated. But I don't see a lot of interest showing honestly. > We just need to have an order of magnitude thing there. Duration of opcodes can vary by more than an order of magnitude. ccbench includes such testing by the way (different CPU-bound workloads) >. That's not really true. The Linux condition variable (from glibc linuxthreads), for example, implements "fair" synchronization. Other implementations may do the same. What bothers me most about this discussion is that the Windows implementation (legacy GIL) is being held up as an example of what we should be doing on posix. Yet, if I go run the same thread tests that I presented in my GIL talks on a multicore Windows machine, the performance is every bit as bad, if not worse, than what I reported in my talk. Therefore, why would we want that? I just don't get it. Here is yet another point:? if so, then this entire rant about a broken lock on pthreads is nonsense. Please note that the "emulated" semaphore is unfair, as I've pointed out, whereas a posix_sem object strives to be fair. So this "emulation" is not working.. Martin, you are right that some mutexes are indeed fair. There has been a move towards using unfair mutexes, particularly on multicore machines. This is because they reduce the "lock convoying" problem. A fair mutex hands off the lock to a waiting thread. That thread is then made runnable. But on a busy system, it may take a while for that thread to actually start running and use the locked resource. The reesult is that the locked resource is unavailable for a longer time. An unfair mutex will wake up a waiting thread, yet have that thread compete for the mutex with any interloper that might arrive and claim it. See e.g. and >? Yes, it does. Actually, I find it unlikely that any modern Unix would fall back on the non-semaphore version. All this code is (mostly) very old. Oh dear. I was assuming that the mutex+condition variable were the actual implementation mostly in use on pthreads. This is because of David's GIL open talk at pycon, where we were looking at the source and bickering about the placement of "pthread_cond_signal()" being after the "pthread_mutex_unlock()" call. In which case, more than half of this thread is invalid. I could, perhaps, start a new defect: "semaphore emulation using condition variable is broken". However, I just asked a colleague with a os X to compile python 2.7 and _POSIX_SEMAPHORES isn't defined, and so, it is running using the emulation. Why, I wonder? Isn't it defined in unistd.h?. > However, I just asked a colleague with a os X to compile python 2.7 > and _POSIX_SEMAPHORES isn't defined, and so, it is running using the > emulation. Why, I wonder? Isn't it defined in unistd.h? Perhaps a bad combination of defines. Has he checked that the semaphore path isn't used at all? (just put a #error in the other path) If so, opening an issue would be good. I would hope we can drop the emulation path one day. Yes, we put #error in both places (defining and undefining USE_SEMAPHORES). The colleague in question is Christian Tismer, he is unlikely to have gotten it wrong. I am also curious why David Beazley kept talking about the "binary semaphore" when it is apparent that that is supposed to be a "hack" to use on platforms that don't have posix semaphores. This gets curiouser and curiouser. > Yes, we put #error in both places (defining and undefining > USE_SEMAPHORES). The colleague in question is Christian Tismer, he is > unlikely to have gotten it wrong. Ok, so can you or Christian open an issue about it? We should try to fix it. > I am also curious why David Beazley kept talking about the "binary > semaphore" when it is apparent that that is supposed to be a "hack" to > use on platforms that don't have posix semaphores. I think David often uses technical terms (such as "semaphore" or "signal") in more generic meanings than what you might expect :) You do realize, that if we enable the USE_SEMAPHORE, we get the GIL behaviour as seen on windows and with my ROUNDROBIN_GIL implementation, right? Also, at the GIL open space talk on PyCon, David did show us the "emulation" source code as if it were _the_ gil. Well, maybe he can explain it. > You do realize, that if we enable the USE_SEMAPHORE, we get the GIL > behaviour as seen on windows and with my ROUNDROBIN_GIL > implementation, right? I haven't studied this argument, but I don't see how that contradicts anything. The main issue witnessed with the 2.x GIL -- and the point of Dave Beazley's original talk -- is CPU inefficiency (due to far too many lock operations). My understanding is that David noticed the problem originally on MacOS. If the emulation is indeed being used on that platform (and a little googling indicates the MacOS posix semaphore implementation is considered at least slightly broken, and FreeBSD didn't support it until 7.2), then perhaps that is why he was looking at that code. Also note that his results were much worse on MacOS than anyone was seeing on Linux, which may support this theory :) I hope everyone realizes that all of this bike-shedding about emulated semaphores versus "real" semaphores is mostly a non-issue. For one thing, go look at how a "real" semaphore is implemented by reading the source code to pthreads or some other thread library. You'll find that semaphores are implemented using the exact same mechanisms that underly condition variables and in some cases, are actually implemented using a mutex lock and a condition variable exactly as Python is doing. Second, the performance of using "real" semaphores still sucks. So, all of the arguing about "fairness" and whatnot seems to be a total waste of time in my opinion because it doesn't address the underlying problem. David, I urge you to reconsider: The "emulated" semaphore is broken because it is unfair. It is clearly a programming error, born out of naivete about how to implement such primitives. Proper semaphores therefore cannot be implemented using the "exact same mechanism" because proper semaphores are fair, this one isn't. You do understand why exactly it is unfair, don't you? Second, with a fair GIL you still get poor performance on multicore with low values of "tickinterval" but at least you get predictable scheduling. The emulated semaphore is bad in two ways: Unpredictable scheduling with thread starvation _and_ poor multicore performance. I don't understand why you prefer having two problems to one. I also think it is worth investigating when exactly the "emulaton" semaphore became the "standard". Did something break in the config script at some point? Googling a bit gave me this: It would appear that mac os X was at least lacking full posix semaphore support in 2005. > Googling a bit gave me this: > > It would appear that mac os X was at least lacking full posix semaphore support in 2005. Hmm. OS X really sucks. I'm sorry, but even in the presence of fair locking, I still don't like this patch. The main problem is that it confuses fair locking with fair CPU use---something that this patch does not and can not achieve on any platform. The main problem is that everything is still based on the execution of interpreter ticks. However, interpreter ticks have wildly varying execution times dependent upon the code that's running. Thus, executing 1000 ticks might take significantly longer in one thread than another. Under a FIFO scheduler based on "fair" locking, the thread with the longer-running ticks is going to unfairly hog the GIL and the CPU. For example, if thread 1 takes 95 usec to execute 1000 ticks and thread 2 takes 5 usec to execute 1000 ticks, then thread 1 is going to end up hogging about 95% of the CPU cycles, starving thread 2. To me, that doesn't sound especially "fair." It would be much better to have fairness where threads are guaranteed to get an equal time slice of CPU cycles regardless of how many ticks they're executing. In other words, it would be much better if the two threads above each got 50% of the CPU cycles. The only way you're ever going to be able to do that is to base thread scheduling on timing. The new GIL in Python 3 makes an effort to do this even though some issues are still being worked out with it. On a slightly unrelated note, I just tried some experiments on Linux with the GIL implemented as condition variables and with semaphores. I honestly didn't see any noticeable performance difference between the two versions. I also didn't see any kind of purported "fair" scheduling of threads using the semaphore version. Both versions exhibit the same performance problems as described in my GIL talk (albeit not to the same extreme as on OS-X). Based on my own reading of the pthreads source code (yes, I have looked), I can't really draw any conclusion about the fairness of semaphores. Under the covers, it's all based on futex locks (the "f" in futex referring to "fast", not "fair" by the way). I know that the original paper on futexes has some experiments with fair lock scheduling, but I honestly don't know if that is being used in the Linux kernel or by pthreads. My understanding is that by default, futexes do not guarantee fairness. To know for certain with semaphores, much more low-level investigation would be required. I've attached a test "fair.py" that gives an example of the fair CPU scheduling issue. In this test, there are two threads, one of which has fast-running ticks, one of which has slow-running ticks. Here is their sequential performance (OS-X, Python 2.6): slow: 5.71 fast: 0.32 Here is their threaded performance (OS-X, Python 2.6.4): slow : 5.99 fast : 6.04 (Notice : Huge jump in execution, unfair CPU) Here is their threaded performance using the Py3K New GIL: slow : 5.96 fast : 0.67 (Notice : Fair CPU use--time only doubled) Using Linux with semaphores gives no benefit here. The fast code is stalled in the same way. For example: here are my Linux results (Ubuntu 8.10, Python-2.6.4, dual-core, using semaphores): Sequential: slow : 6.24 fast : 0.59 Threaded: slow : 6.40 fast : 6.69 (even slower than the slow code!) What your fair.py is doing is demonstrating the superior behaviour of a time-based GIL interrupt to a bytecode based one. I have no quibbles with that and I agree that it is superior. But I also think that your example is a very artificial one. On average the duration of the bytecodes evens out between threads and so they should give a fair first approximation. But this is not what I was talking about when considering fairness. Your test only measures each thread end to end, and it demonstrates how a bytecode based gil yilelding system wil let the two threads work in lockstep, even though each loop in one thread is cheaper than the other. Fair enough. But fair scheduling between threads doesn't show up here. To demonstrate fair / unfair, I've modified fair.py to add two more runs, where three threads of the "fast" variety are run for identical number of rounds. This is when you will se a difference between the linux and the mac based GIL implementations. For your info, on my windows dual core office box, with regular windows gil: D:\pydev\python\trunk\PCbuild>python.exe d:\pyscript\fair.py Sequential execution slow: 3.384000 (0 left) fast: 0.177000 (0 left) Threaded execution slow: 3.435000 (0 left) fast: 3.568000 (0 left) Treaded, balanced execution: fast A: 0.973000 (0 left) fast C: 0.992000 (0 left) fast B: 1.013000 (0 left) Treaded, balanced execution, with quickstop: fast A: 0.977000 (0 left) fast C: 0.976000 (252 left) fast B: 0.978000 (17601 left) And now, same box, with the unfair GIL: D:\pydev\python\trunk\PCbuild>python.exe d:\pyscript\fair.py Sequential execution slow: 3.338000 (0 left) fast: 0.177000 (0 left) Threaded execution fast: 0.382000 (0 left) slow: 3.539000 (0 left) Treaded, balanced execution: fast A: 0.362000 (0 left) fast B: 0.464000 (0 left) fast C: 0.549000 (0 left) Treaded, balanced execution, with quickstop: fast B: 0.389000 (0 left) fast A: 0.447000 (240480 left) fast C: 0.360000 (613098 left) The two last cases are the interesting ones. With unfair scheduling, one thread takes almost twice as long to complete its 1000000 inserts than another. And if they are all stopped when the quickest one finishes, one thread has more than 600000 iterations to go. This is what I mean by fair/unfair scheduling. Cheers, Kristján p.s. Yes, I agree that time based GIL yielding is better. I intentionally didn't want to confuse the matter with that in 2.x. I wanted to address the other issues that are wrong.? One other comment. Running the modified fair.py file on my Linux system using Python compiled with semaphores shows they they are *definitely* not fair. Here's the relevant part of your test: Treaded, balanced execution, with quickstop: fast C: 1.580815 (0 left) fast B: 1.636923 (158919 left) fast A: 1.788634 (310323 left) >I'm not trying to be a pain here, but do you have any explanation as to >why, with fair scheduling, the observed execution time of multiple CPU->bound threads is substantially worse than with unfair scheduling? Yes. This is because the GIL yield now actually succeeds most of the time, every 100 opcodes (the default). Profiling indicates that on multicore machines this causes significant instruction cache misses as the new thread is scheduled on the other core. Try raising the sys.checkinterval to 1000 and watch the performance difference fall away. >If so, why would I want fair locking? Wouldn't I want the solution >that offers the fastest overall execution time? Because of IO latency. Your IO thread, waiting to wake up when somethin happen also has to compete unfairly with the CPU threads. "a fair" lock allows you to balance the cost of switching (on multicore) vs thread latency using sys.checkinterval (if we are based on opcodes). The unfair lock all but disables this control. >One other comment. Running the modified fair.py file on my Linux >system using Python compiled with semaphores shows they they are >*definitely* not fair. Here's the relevant part of your test: Interesting. let me stress that I am using windows and making assumptions about how something like sem_wait() behaves. And the posix standard does not require "fair" behaviour of the semaphore functions according to. The kernel-based windows synchronization functions achieve an amount of "fairness" through WaitForSingleObject() and friends: Are you absolutely sure that USE_SEMAPHORES is defined? There could be a latent config problem somewhere. I'm definitely sure that semaphores were being used in my test---I stuck a print statement inside the code that creates locks just to make sure it was using the semaphore version :-). Unfortunately, at this point I think most of this discussion is academic since no change is likely to be incorporated into Python 2.7. I can definitely see where fairness might help I/O performance if there is only 1 CPU bound thread. I just don't know for other situations. For example, if you have a server where it's all I/O-bound threads, but it suddenly comes under extreme load (e.g., slashdot effect), does a fair GIL help or hurt with that? I just don't know. In the big picture, all of the issues raised here should be on the minds of people fixing the GIL in py3k though. It's just one more aspect of why fixing the GIL is hard. As a followup, since I'm not sure anyone actually here actually tried a fair GIL on Linux, I incorporated your suggested fairness patch to the condition-variable version of the GIL (using this pseudocode you wrote as a guide): with gil.cond: if gil.n_waiting or gil.locked: gil.n_waiting += 1 while True: gil.cond.wait() #always wait at least once if not gil.locked: break gil.n_waiting -= 1 gil.locked = True I did some tests on this and it does appear to exhibit fairness. Here are the results of running the 'fair.py' test with a fair GIL on my Linux system: [ Fair GIL Linux ] Sequential execution slow: 6.246764 (0 left) fast: 0.465102 (0 left) Threaded execution slow: 7.534725 (0 left) fast: 7.674448 (0 left) Treaded, balanced execution: fast A: 10.415756 (0 left) fast B: 10.456502 (0 left) fast C: 10.520457 (0 left) Treaded, balanced execution, with quickstop: fast B: 8.423304 (0 left) fast A: 8.409794 (16016 left) fast C: 8.381977 (9162 left) beazley@ubuntu:~/Desktop/Python-2.6.4$ If I switch back to the unfair GIL, this is the result: [ Unfair GIL, original implementation, Linux] Sequential execution slow: 6.164739 (0 left) fast: 0.422626 (0 left) Threaded execution slow: 6.570084 (0 left) fast: 6.690927 (0 left) Treaded, balanced execution: fast A: 1.994143 (0 left) fast C: 2.014925 (0 left) fast B: 2.073212 (0 left) Treaded, balanced execution, with quickstop: fast A: 1.614533 (0 left) fast C: 1.607324 (377323 left) fast B: 1.625987 (111451 left) Probably the main thing to notice is the huge increase in performance over the fair GIL. For instance, the balance execution test runs about 5 times faster. Here are the two tests repeated with checkinterval = 1000. [ Fair GIL, checkinterval = 1000] Sequential execution slow: 6.175320 (0 left) fast: 0.424410 (0 left) Threaded execution slow: 6.505094 (0 left) fast: 6.746649 (0 left) Treaded, balanced execution: fast A: 2.243123 (0 left) fast B: 2.416043 (0 left) fast C: 2.442475 (0 left) Treaded, balanced execution, with quickstop: fast A: 1.565914 (0 left) fast C: 1.514024 (81254 left) fast B: 1.531937 (63740 left) [ Unfair GIL, checkinterval = 1000] Sequential execution slow: 6.258882 (0 left) fast: 0.411590 (0 left) Threaded execution slow: 6.255027 (0 left) fast: 0.409412 (0 left) Treaded, balanced execution: fast A: 1.291007 (0 left) fast C: 1.135373 (0 left) fast B: 1.437205 (0 left) Treaded, balanced execution, with quickstop: fast C: 1.331775 (0 left) fast A: 1.418670 (54841 left) fast B: 1.403853 (208732 left) Here, the unfair GIL is still quite a bit faster on raw performance. I tried kicking the check interval up to 10000 and the unfair GIL still won by a pretty significant margin on raw speed of completing the different tasks. I've attached a copy of the thread_pthread.h file I modified for this test. It's from Python-2.6.4. >. Exactly so. I still don't see why you then infer that the GIL is unfair. It is not IF THE CONDITION VARIABLE IS FAIR. As I said, some implementations of condition variables *are* fair, e.g. the Linux one (which in itself isn't really relevant here, because Linux uses the semaphore GIL, anyway). However, it remains unclear why you think that the GIL is not fair in pthreads. Martin, I´ve explained it in my other dissue, issue 8411, with a step by step example. It is unfair because a thread can _bypass_ the condition variable. A thread just woken up from the condition variable has to race to get the lock, and it is a race that it will invariably loose if the other thread is doing a release/acquire (yielding the GIL as happens in ceval.py) The ConditionVariable can only endow the lock with its fairness property if all the threads play by the same rules. This was a design decision made by Tim (according to the comment) but a misguided one. It is a good stragegy for resources that are held for a short time to avoid lock convoying, but not appropriate in this case. You also don't have to take my word for it. Just try it out. Notice that 99% of all yields between threads fail, causing starvation of a thread which is the definition of "unfairness." Anyway, this is the last time I explain why the "emulated" semaphore is unfair. I think I´ve done so on at least four or five different occasions and it would be helpful if people would actually bother to read my comments. > Martin, I´ve explained it in my other dissue, issue 8411, with a step by step example. Hmm. Can't find it there. What message or file should I be looking at?. Sorry Martin, I meant issue 8410. I have so many of these going on :) It is interesting to see, David, the difference in the behaviour of the semaphore based and condition variable based lock on linux. It is clear that the semaphore and the condition varable have different queuing characteristics. I wouldn't be surprised if the semaphore were "fair" on average, but that it somehow colludes with the scheduler allow the current thread to cut in early based on, perhaps, timeslices or something. The condition variable seems to be much more FIFO. It is odd to me that you don't seem to be able to shake the performance hit even with a checkinterval of 10000. In the end, the performance hit is because of successful switches during the GIL yield in ceval.c. You ought to be able to raise the checkinterval up to the same level as the 'effective' one with the unfair condition variable approach and have the same sort of behaviour (inclusive IO latency). I'll do some modifcations locally to gather stats on successful yields vs unsuccessful ones. As for this being academic, yes it is. As I stated early on, I never intended this to be checked in as is. My aim was to take a step back from the radical GIL rewrite in 3.x. Provide a simple platform for GIL experiments in the know and trusted 2.x series. See if we could achieve the desired features without the added unknowns of the new GIL. And in fact, I also didn't want to expend this amount of ammunition on the "ROUNDROBIN_GIL" implementation. It was included merely as an example of one thing that was wrong with the old one and why it was so unpredictable. What I really wanted to look at was to combine the benefit of a large checkinterval (100000, say) with a priority based mechanism giving us a low IO latency. I've gotten so sidetracked with this whole fair/unfair business that I have neglected to provide useful performance benchmark of the PRIORITY_GIL implementation. The fact that I had to expend so much effort explaining exactly how the gil on mac (LEGACY_GIL) was not fair, also shows how tricky working with synchronization primitives and threads can be, even using such relatively modern primitives as mutexes and condition variables. There are many pitfalls for the unwary, and in my experience, only a lot of exposure will bend your brain into taking all those pesky race conditions into acccount. This is why I think it is important to _understand_ the problem completely before trying to fix it, and why fixing it stepwise, with a full understanding of each step along the way, is necessary for robust behaviour. As for missing the boat on 2.7, well, there is always 2.8 isn't there :) David, trying to get some more realistic IO benchmarks I did some more tests. The idea is to have a threaded socket server, serving requests that take different amounts of time to process, and see how io response measures up for two classes of requests being serviced simultaneously. Please see the evalsrv.rar for the client and server scripts. The client uses multiprocessing to distance itself from the GIL issue. The results on my dual core windows box are as follows (LEGACY_GIL is the mac, unfair GIL, ROUNDROBIN_GIL is the same with the fairness fix. "with affinity" means that the server process is restricted to running on one core. label time avg time std.dev) (total time, sum of individual classes)) (for each test, you get the indvidual timing for each request class, and then a sum of total time and sum of individual times.) Please don't read too much into small differences, this is a roughly one-off test here and likely contains noise. A few things become apparent: 1) with LEGACY_GIL, affinity appears not to matter. The 300 fast requests take longer to complete than the 30 slow requests if done in parallel, even though their serial execution time is roughly 1/5th. 2) With ROUNDROBIN_GIL, serial performance appears not to be affected, but simultaneous performance is much better: end-to-end time is the same, but the sum of individual classes is lower. That means that the client had to wait less for their IO results. 3) With ROUNDROBIN_GIL, if we put affinity on, we get the same kind of performance as with the LEGACY_GIL. The most important points here are the two last ones, I think. The fact that the sum of the individual request waits goes down is significant, and it is by no small amount that it drops. But equally perplexing is the fact that forcing the server to one cpu, removes the "fairness" again. It would appear that the behaviour of the synchronization object (an windows Semaphore in this case) changes depending on the number of cores, just as you had previously mentioned. This is, however, a windows only effect, I think. I must try to find out what is going on. Sorry, all the benchmarks were missing from my last comment. Here they are: total time avg time/request stddev LEGACY_GIL serial ((30, 500), (2.6908777512225717, 0.08968708313486773, 0.0015164644061278888)) ((300, 10), (0.4470272758129874, 0.0014862882945551276, 0.00024585959927491124)) 3.30s (3.14s) [end-to-end time, ( sum of total times) simultaneous ((30, 500), (2.876280574765787, 0.09586895587753937, 0.0011848842024515473)) ((300, 10), (3.2645357161315194, 0.010877886016239504, 0.027372366395914234)) 3.27s (6.14s) LEGACY_GIL, affinity on serial ((30, 500), (2.8003825905247735, 0.09333925587376796, 0.013360667457052446)) ((300, 10), (0.45636945477707364, 0.001517769716542185, 0.00020067298808990378)) 3.43s (3.26s) simultaneous ((30, 500), (2.8963266281049687, 0.09653735553913509, 0.0096323348697044)) ((300, 10), (3.212417639672081, 0.010703065845891957, 0.014433573531885001)) 3.21s (6.11s) ROUNDROBIN_GIL serial ((30, 500), (2.703059536896449, 0.09009326837163198, 0.0020036630273102198)) ((300, 10), (0.4539455433581643, 0.0015096094615377107, 0.00041274624690973134)) 3.32s (3.16s) simultaneous ((30, 500), (3.2613636649350686, 0.10870530565570016, 0.02613516235517462)) ((300, 10), (1.4737764855589188, 0.004908413639163637, 0.002818028070766402)) 3.26s (4.74s) ROUNDROBIN_GIL, affinity on) ROUNDROBIN_GIL, USE_FIFO_COND serial ((30, 500), (2.7050386292112547, 0.09016071176643957, 0.0017078174777967025)) ((300, 10), (0.4478294727402505, 0.001488698051474884, 0.00012887034661806298)) 3.31s (3.15s) simultaneous ((30, 500), (3.262343957123042, 0.10873750248518549, 0.02640198429431565)) ((300, 10), (1.5242242379967286, 0.005076519036171731, 0.0033917786033315026)) 3.26s (4.79s) For better or worse, this did not make it into 2.7. Is it the sort of thing that could still go into a bug-fix release, without alpha/beta testing? Or should this be closes as out-of-date? That question should probably raised on python-dev, not the bug tracker. Although I did finally manage to explain the point of this patch (after a long, long discussion), I think the issue is still too controversial. We did, for example, see some strange behaviour in my last comment (Date: 2010-04-21 23:22) regarding affinity fixing of the process! What I hope comes out of this is that I think I have put my point across that with multithreading, a lock is not a lock. While a mutex may be indeed a mutex, its behaviour towards the threads that want to claim it can be different and can affect program behaviour and performance. This also goes for "emulated" or "constructed" entities, built out of something more primitive such as condition variables. Since 2.x is now frozen, and everyone seems happy (I think) with the more complicated 3.x method (although, being more complex, probably has more surprises in store), we should probably just let this fade away. OK. I would probably be better to expend energy on the 3.x new GIL, should issues arise.
http://bugs.python.org/issue8299
CC-MAIN-2014-15
refinedweb
10,146
65.93
Major Bitcoin Exchange Ceases Operation 208 First time accepted submitter Sabbetus writes "On Monday the CEO of prominent Bitcoin exchange Tradehill announced that they are shutting down. Ars Technica ran a story on this stating that 'After Monday's news, the currency's value fell from $5.50 to $4.40, a decline of 20 percent.' Tradehill is returning all funds and meanwhile their competitors are fighting over who gets Tradehill's customers." Bizarre and Confusing Summary (Score:5, Informative) Not sure where that came from, didn't find it in the Ars article. At the end they mention Mt. Gox being the only other exchange ... so there's one competitor. They didn't mention anything about fighting over customers. Furthermore the third sentence in the Ars article was suspiciously absent from the summary: He has pledged to open a new site once these issues have been resolved. As well as the explanation of why all this happened (lack of proper money transmission licensing). I've asked this many times before but how do you track illegal purchases on BitCoin [slashdot.org] when, by definition, it claims to be an anonymous payment solution? Quite simply put, no BitCoin exchange -- neither Tradehill nor Mt. Gox -- is going to be able to comply with the Bank Secrecy Act [wikipedia.org]. Re:Bizarre and Confusing Summary (Score:4, Funny) Re:Bizarre and Confusing Summary (Score:4, Insightful) Re: (Score:2) No. In todays industry, those "to big to fail", don't. Their losses are replaced by printing more money so they can pay their bonuses, and have another shot at craps. Re: (Score:3) Like this one? [amazon.com] Re: (Score:3) Re: (Score:2) There are any number of valuable things that your landlord would be unlikely to accept as payment. Carbon nanotubes, for instance. So, Bitcoin is not (yet? ever?) a viable currency, but that doesn't mean it doesn't have value. Re: (Score:3) Are you saying there's a short supply of idiots? Because my experience says otherwise. Re: (Score:3) By your definition, idiots can successfully use bitcoin as a currency, but only because they don't realize how "silly" it is. When you think about it, that's a *really* odd thing to state. If you mean that bitcoins have no intrinsic value, then you'd be right. But that's true of currencies in general these days. No one uses gold coins as currency any more. If you actually have a specific criticism if bitcoin other than "silly", I'd be interested to hear it. Re: (Score:3) I'm surprised they didn't get a federal bailout. Re:Bizarre and Confusing Summary (Score:4, Insightful) The Act only applies to the US though. Many places you can host an exchange. Never heard of tradehill though, so can't tell where they were based. One of the nice things about bitcoin is that there are no real borders for it. You can trade on any exchange in the world, and use the currencty anywhere without restrictions (so a bit like cash, but without limits on how much you can take out the country, or currency conversion fees, etc...). Re: (Score:3) Also we're not talking about a Bitcoins to seashells exchange here; we're talking about a Bitcoins to USD exchange. Any such exchange must perform transactions with other banks that operate with USD. Guess where a majority of those USD-handling banks are located? Re: (Score:2) Really? The government controls *.co.uk? No, I didn't think they did. All they 'control' are the silly generic domains that are too overpopulated to be useful anymore anyway. The rest of the world could rather quickly tell the US to go fuck themselves are far as DNS is concerned. Other countries run root servers too. Re: (Score:2) While many of the root servers are operated outside the US, it is ARIN that assigns them the space in the root server namespace, and delegates the root server cache. And ARIN is as American as apfelstrudel. Nothing except it (a) being incredibly stupid to do so, and (b) the politicians being unaware prevents the US from retracting root servers they don't like from the rest of the world. There were a couple of attempts at creating a parallel DNS world not touchable (remember alternic, anyone?), but they neve Re: (Score:3) TOR is an http packet router The Onion Router) [wikipedia.org] and therefore is unrelated to DNS. You could argue that DNS is irrelevant bu then you would be forced to remember 50.17.218.130 instead of example.co.bs and imagine how fun that would be. Also an only IP solution would still be scrutinized by the IANA (and regional entities) since IP isn't decentralized. One more thing: if DNS would go down hosting costs for your blog would go up (as in sky high) because you would need a dedicated IP for it instead of a shared on Re:Bizarre and Confusing Summary (Score:5, Insightful) Technically true but in practice any institution that touches dollars ends up being bound to obey US law if it wants access to the international financial system. Re:Bizarre and Confusing Summary (Score:5, Insightful) I disagree. As long as an exchange keeps identity records for all of its business and for all of the address endpoints it creates, it'd probably be able to comply with US Treasury Department regulations. Bitcoin isn't anonymous. Things only start to get murky once you are moving bitcoins around off an exchange, but that's not the exchange's problem. Re: (Score:2) I mine one block of 50 BitCoins. I use that that block to get 50 $5 Sears gift certificates (redeemable in-store) through BTCBuy. I redeem them (CA, ME, MA, and MO all require stores to cash out gift certificates with $5 or less on them) in-store for cash. More realistically (and less likely to arouse suspicion from a salesdrone), I would just take a $250 gift cert and actually buy something I needed at Sears; but the protest-of-last-resort from the naysayers always runs along Re:Bizarre and Confusing Summary (Score:5, Informative) Quite simply put, no BitCoin exchange -- neither Tradehill nor Mt. Gox -- is going to be able to comply with the Bank Secrecy Act [wikipedia.org]. Totally not true. They have to record cash transactions for negotiable instruments. They have to report cash transactions over $10,000. Most of them did not deal in cash at all, but in credit or debit cards and paypal, all of which is easily recorded. The act makes no mention of tracking the negotiable instruments (bitcoin) after they are sold. Re: (Score:2) Re:Bizarre and Confusing Summary (Score:5, Interesting) Mt. Gox being the only other exchange MtGox is the only exchange bigger than TradeHill, but there are lots of smaller exchanges: [bitcoin.it] Quite simply put, no BitCoin exchange -- neither Tradehill nor Mt. Gox -- is going to be able to comply with the Bank Secrecy Act. First, Bitcoin is pseudonymous, not anonymous. Second, the important part: while it's very difficult to positively identify who sent you some Bitcoins, the exchanges know exactly who receives them, trades them back and forth to fiat currencies, and then sends them back out. They have names and bank account numbers, or they're using fiat payment services that have bank account numbers. Know Your Customer is not a problem for most exchanges. Re: (Score:2) Bitcoin is perfectly anonymous. Bitcoin exchanges like Tradehill and MtGox are not anyonymous. Re: (Score:2) Bitcoin is as anonymous as an advertiser clickstream. It's quite possible to correlate individuals from their transactions [blogspot.com], and the transactions are out in the open for all to see. Re: (Score:2) I can send Bitcoins to people from a random address and all they will only know how much, when, and from what address. You'd have to trace transactions backward to the originating address to find out where the money truly came from, and the ultimate originating source is always the miners. For you to track anyone on Bitcoin you'd have to know their address. But anyone can generate a new address whenever they want. I myself had dozens back when I was mining Bitcoins. You can trace all transactions to addresses Re: (Score:3) You can trace mined coins to specific IP addresses if you are careful with how you listen to the packets and try to find out which computer gave you the packet first. If you had several computers tracking this information, it would be possible to identify down to a small number of users who actually mined some Bitcoins, and from that if any Bitcoins were co-mingled with those mined coins to be able to further identify what other addresses might be used by that person who also is mining coins. Still, attempting to do that is a real technical challenge and you would need the resources of something like the U.S. federal government to pull that off, plus a whole bunch of data mining and active participation in the Bitcoin network... and it still gives wiggle room for plausible deniability on the surface. If there was a particular set of transactions that such data mining was looking for, you can still be tracked. On the other hand, if you were very paranoid about such things you could set up manual connections for routing Bitcoin data to only trusted nodes (by your own definition... not some random list in other words), and hopefully even they are being just as paranoid about random connections "to the outside world". IF you control all nodes, AND you KNOW you control all the nodes, then you can track the transaction to the IP ADDRESS of the MINER or TRANSACTION INITIATOR. You cannot track the transaction to an individual person. An IP address is not a person. A Bitcoin address is not a person. Furthermore, it's laughable to think that anyone can control all of the nodes to make this possible. And if that scenario ever did occur, you could just avoid routing directly to those nodes (as you mentioned). If the government wan Re: (Score:2) Re: (Score:3) Except to use cash, you have to go out in public. You know, where there are often cameras. And most stores don't take kindly to people walking in wearing ski masks and gloves to conceal their faces and fingerprints. Re: (Score:2) Hmm. I thought Trade Hill was going down, and the company behind it was putting up a new, compliant website by the end of the month... Re: (Score:2, Funny) AHA! Proof that you actually read the article AND Jered's original post to the bitcointalk forum announcing the change. Tradehill is closing so that a new platform can be built from the developer team. You actually read the article and its source material. You are an embarrassment to the Slashdot community. :-) Re: (Score:3) Bitcoin never claimed to be an anonymous payment solution. In fact every single payment (along with sender and recipient address) ever made is visible in the very public block chain. People who don't understand bitcoin claimed it was an anonymous payment solution. Re: (Score:2) As I understand it all you needed was a swapping service, you put a coin in and get a different coin back. It's a little more complicated to avoid correlation and timing attacks and such, but that's the basic idea. Re: (Score:2) So that everyone clea Re: (Score:2) After Silk Road started picking up steam the currency jumped to its bubble peak of $30+ USD. I'm sure I wasn't the only one who noticed the timeline there. I think the $30 spike was more likely caused by an influx of noobs who found out that their GPU could print money. Re:Bizarre and Confusing Summary (Score:4, Funny) Nope. Because Bitcoin is not a scheme whereby people use newcomers money to pay people who have been in the scheme longer. In fact, Bitcoin does not ask people for money at all. Re: (Score:2) Re: (Score:2) Then every successful corporation is a pyramid scheme. Bitcoin's still around? (Score:5, Funny) I thought that Bitcoin must have ceased operating when there stopped being a slashdot story about them every day. Re: (Score:3) Re: (Score:2) We stopped getting bitcoin articles when Taco left. Yeah, yeah, correlation is not causation ... but it sure is sufficient cause to suspect causation. Re:Bitcoin's still around? (Score:4, Funny) You think that Taco left because of a lack of bitcoin articles? Whatever editor was in to them sold them (Score:2, Insightful) That's my bet. One (or maybe more) of the Slashdot staff was in to bitcoins. They mined them, bought them, whatever. So they had an interest in getting people in to them so the value would go up and they could make money. Now they are out of it so they don't give a shit, no reason to pimp it anymore. Plus it was a fad, and its time has come and gone. While it isn't dead, the days of "big money" are gone. It lost a shit ton of value, the miners aren't making much, etc, etc. The virtual gold rush is over, so i Re: (Score:2) Wow (Score:2) Who didn't see that coming? /snark Oh well. (Score:2, Redundant) Major? (Score:4, Interesting) Tradehill was never a major Bitcoin exchange. MtGox is the only one anyone ever used. Tradehill was started by some guy who got mad that MtGox was raking in the cash. He started throwing out accusations about security holes, the owner (of MtGox) not actually having all of the BitCoins backing his market, etc. Then he threw up Tradehill and it was shit. All Bitcoin exchanges are shit. They're for speculators. Bitcoin as a currency is fine, and it will be fine if every exchange dies off. Re: (Score:2) "and it will be fine if every exchange dies off." Except for the fact that there will be no way to acquire bitcoins? Re: (Score:2) Re: (Score:3) "and it will be fine if every exchange dies off." Except for the fact that there will be no way to acquire bitcoins? By that logic there would be no way of acquiring US dollars either. Without exchanges, you acquire Bitcoins in exchange for goods and services. It's money. Earn it. But there are exchanges (Score:5, Insightful) Many of them. The US dollar is traded on all international currency markets and for a small scale, any bank will convert them. If it weren't, it wouldn't be very useful. If I pay someone in Europe in US dollars they are ok with that because they can convert them to Euros, which is what they need to do their business. If they couldn't, if US dollars were non-convertible, they'd be non-useful. Also you have the problem that next to nobody accepts and deals in bitcoins directly. It isn't a functional currency. The US Dollar, the Euro, the Yen, these are all functional currencies because a lot of people will accept them as such. You can buy goods with them, pay taxes with them, etc. I cannot name a single thing I'd want to buy, a single place I shop at, that takes bitcoins. As such if they aren't convertible, they are worthless. Re: (Score:2) Sure, it would only be used by a tiny niche of enthusiasts. So what? It has to start somewhere, and even if it didn't grow from there it could live on as a functional niche currency. Speculation is all the Bitcoin has (Score:2, Insightful) -- something which there is never any guarantee of (compare to private currencies that are backed by national currencies). This is in stark contrast to national currencies like dollars, which people must have if they intend to pay their taxes (which they must do if they intend to legally own property, hold a j Re: (Score:2) How can I short this currency? Re:Speculation is all the Bitcoin has (Score:5, Informative) How can I short this currency? Right over here: [bitcoinica.com] Be careful. Volatility cuts both ways. Re: (Score:2) I believe MtGox was working on options trading for BitCoin and one would assume they might allowed short trading. If not, then just buy a Put option at the current price (that ought to be cheap right?) and then at some later date come in and cover your Put at the presumably lower price, or sell your Put, which is usually a better deal than exercising it. However, I wouldn't recommend shorting it at this point. Once the dump story dujour moves on, it will probably move back to Re: (Score:2) The only reason anyone has ever accepted Bitcoin as payment for anything is because they believe they can redeem Bitcoin for some other currency later on This is demonstrably false. There's a considerable demographic in the Bitcoin community who don't like that the speculators have eclipsed the commerce side, and who would very much prefer if they could trade it back and forth as an isolated currency rather than having everyone think of it as a proxy for dollars. Re: (Score:2) There's a considerable demographic in the Bitcoin community...who would very much prefer if they could trade it back and forth as an isolated currency Unless they live outside the jurisdiction of any effective government, they will have to find at least enough of some nation's currency to pay their taxes (which in some nations includes taxes on transactions made using Bitcoin, which cannot themselves be paid using Bitcoin). I sincerely doubt that these users live under such circumstances, and even if they did, they would also have to find a way to generate electricity and connect to the Internet without incurring any costs other than Bitcoin, which is Re: (Score:2) they will have to find at least enough of some nation's currency to pay their taxes Just because you're using Bitcoins doesn't mean you have to use ONLY Bitcoins. There's no reason it can't exist as a niche currency. Re: (Score:3) There's no reason it can't exist as a niche currency OK, I'll grant that -- Bitcoin might live on as an obscure, niche currency with extremely limited utility. Not even the black market users will stick with it in that case, and perhaps people will realize that there are more effective digital cash systems out there that could be deployed in a way that benefits society (not just the black market). Re: (Score:2) On the other hand I think it will be exchangeable to dollars for the foreseeable future, regardless of what the island-currency niche wants. As long as there's another group that DOES want it exchangeable, they'll find a way. Re: (Score:2) Re: (Score:2) and so over the long term we should expect Bitcoin's value to decline. That too is speculation. It's just speculating on the downside. :) Bitcoin's value is almost entirely due to speculation. I agree, but I want to contrast it with your earlier statement... Without speculation, Bitcoin is worthless. ... which which I disagree. Re: (Score:2) Wrong. People accept Bitcoin because they believe they can also use it for goods and services. Just like every other currency in existence. Re: (Score:2) Re: (Score:2) NYSE was never a major stock exchange. ... Then he threw up NASDAQ and it was shit. NYSE is the only one anyone ever used. NASDAQ was started by some guy who got mad that NYSE was raking in the cash. All stock exchanges are shit. They're for speculators. FTFY. :) what an exchange actually means (Score:2) A real exchange (e.g. like the CME) has the following important property: all participants have the exchange as an economic counterparty, not each other. That is you take on the credit risk of the exchange, which is presumably better than any individual participant. This means that if X trades with Y on the CME, and X (as a broker) goes bankrupt before the money settles, the CME will pay Y, and then attempt to get money back from X. This actually matters sometime (cf MF Global). The exchange then has stand Re: (Score:2) On most of the Bitcoin exchanges, X and Y deposit their respective funds (say, USD for X and BTC for Y) into their account on the exchange. During a trade the exchange immediately transfers X's USD to Y's account and Y's BTC to X's account, less fees on both sides. IE, trades are settled instantly and withdraws may be performed immediately (though the usual banking delays exist on the fiat side, and received BTC take about an hour to confirm). Legally the exchange happens between X and Y, and the exchange i But the protocols are still intact (Score:5, Insightful). Why Bitcoin is doomed (Score:4, Insightful) Useful digital cash systems involve a central issuing authority like a bank or government, that can accept old tokens and produce "fresh" tokens of equal value. Having such a central authority is not a bad thing: It is a good thing that nobody is obligated to use BItcoin to pay their debts, because: So there you have it. Re: (Score:2) Re:Why Bitcoin is doomed (Score:4, Insightful) they have already begun by taking the mining out of the default client This makes the scalability problem even worse, since it forces you to reuse older tokens, which have already grown because of their use in previous transactions. This is not a problem that you can just hack your way around, it is a fundamental limitation of digital cash systems. Note that on the very page you linked to, they attempt to sidestep this problem by claiming that hard drive sizes will grow to accommodate their needs, which I seriously doubt unless Bitcoin remains an obscure payment system. The black market already holds its own to the deman for national currency and the black market is growing with time - it is very likely that within the next decade or two it may outpace the regulated one. With half the world's population already employed in the black market it is not much of a stretch to think that you don't need a government to back a currency, if the incentives are right for the market to protect it itself. It is very much a stretch to think that money can exist without government backing. If the black market stopped using national currencies, they would be forced to switch to a currency backed by some other large, powerful organization to enforce payments, and that organization would be a de facto government. Money is only valuable within some enforcement structure, which is the role that a government plays; even when banks issue currency, they rely on governments to enforce debt payments. And you could say by the same metric that trade in physical goods, whether coins or paper bills have been a 'necessary' component ...until the digital banking started to take over in the 80's or so. Just because something has always been part of the economy does not mean that it is necessary. That is a correlation vs. causation error in thinking. Except that we still trade in physical goods (and even if all currency were digital cash, you would still trade in physical goods -- you need food, clothing, etc.), and we have had paper transactions managed by banks for centuries (which have simply moved computers, which are more efficient record keeping systems). At a basic level, credit is necessary in any economy because people with the skills needed to complete a task do not always have the resources needed for that task. A farmer might not have enough money to buy the fertilizer he needs for a particular growing season, a cook might not have the resources needed to start a restaurant, etc. At an even more fundamental level, you might need to work before you are able to pay the soldiers that protect you from a hostile enemy, but those soldiers need to be paid while they are busy protecting you; taxes themselves are a form of debt, and governments cannot function without tax revenue. The unfortunate thing about Bitcoin is that people have come to associate Bitcoin with digital cash. There are plenty of other digital cash systems that have all of Bitcoin's advantages without the serious disadvantages; those systems use a bank or other token issuing authority to renew tokens that have long transaction chains (thus avoiding the scalability problem) and are easy to back with a national currency, or perhaps to use as a national currency. Anarchists may not like the idea of a bank having power over currency, but that is just how currencies work: some central authority must back the currency. I am personally a big fan of digital cash, since it would solve a lot of the security problems that we see with debit and credit cards, but because of the various crypto battles and patents in the 90s digital cash never did take off. Re:Why Bitcoin is doomed (Score:4, Informative) which have already grown because of their use in previous transactions This isn't actually true. Coins don't keep getting split into smaller and smaller portions forever. Every time you spend it takes several old coins and combines them into (usually) two new ones: 1, the payment you make, and 2, your "change" (which goes back in your wallet). The previous inputs are permanently combined and no longer needed going forward. The current software does not yet actually implement it, but obsolete coins CAN be "pruned" entirely, facilitated by the Merkle tree.. Whether that will be a reasonable and manageable size is still an open question. all of Bitcoin's advantages without the serious disadvantages; those systems use a bank or other token issuing authority I want to know that the central bank won't just start issuing more currency and devalue mine. I want to send money to Wikileaks, but all the banks are forbidding it. I want to pay someone over the internet without Mastercard or Paypal or whoever taking a 2% cut. There is no other currency that currently has ALL of those advantages of Bitcoin. Some of the advantages are inherently incompatible with centralized, bank-operated currencies. It also has a long and substantial list of disadvantages too - no argument there. But on the whole it simply has a different set of tradeoffs than any other currency, and so it (or one of it's descendants; I don't expect Bitcoin is going to be the last word in decentralized e-currency) will be relevant for some time. Re: (Score:2). Which implies that Bitcoin is not secure. Somewhere, the storage or bandwidth require must grow with the number of transactions that any token is used in in any secure digital cash system, regardless of how the token is manipulated. If that is not the case, then either the system does not provide anonymity, or it does not provide security against doubt spending (I suspect the former in the case of Bitcoin). I want to know that the central bank won't just start issuing more currency and devalue mine. That's nice, but if your money supply cannot grow then your economy is going to have problems. Re: (Score:2) Re: (Score:2) Tradehill were the good guys (Score:5, Informative) Tradehill was probably the best-run Bitcoin exchange. They didn't steal customer funds, like some of the other defunct Bitcoin services. [betabeat.com] They didn't go down much. They didn't have a monthly crisis [thebitcoinsun.com] like Mt. Gox. (formerly Magic, the Gathering Online Exchange. Really.) If Tradehill does in fact return all customer funds, at least they shut down honestly. A basic problem with Bitcoin is that the ability to irrevocably transfer funds to anonymous parties is the scammer's dream. Bitcoin is thus a scammer magnet. Just about every known financial scam was replicated in the tiny Bitcoin world, from fake banks [globalstandardbank.com] to fake stock exchanges [glbse.com] to Ponzi schemes. [bitponzi.net] Re: (Score:2) That seems a little unfair. It'd be equally valid to say that a scammers dream is an electronic payments system that allows purchases to be made with only a fixed password, which must be given to anyone who accepts payments, which isn't connectable to any kind of second factor and in which the costs of fraud get sunk by the merchants (who can't do anything about it) rather than banks or end users, thus ensuring the party continues endlessly. How many credit card details can be bought on the black market aga Re: (Score:2) Re:Oh! The huge manatee! (Score:5, Funny) And not a single fuck was given that day. If everyone actually stopped fucking for a day, that would be huge news. (To everyone other than you) Re: (Score:2) Re: (Score:2) Weed? Give me a break, the biggest political attack on Bitcoin so far is because you *can* buy weed with it. Buying most of these online might not work for you, but for what it's worth, one of my friends buys beer online with the coins he mines. Belgian Flavours shop accepts Bitcoin AFAIK. You can buy PCs and all kinds of electronics for sure. Not sure how competitive the prices are though, at the worst case you can buy vouchers for more popular sites. Smokes, yes, there are a multitude of shops for tobacco Re: (Score:2) Bitcoin is a perfectly good idea.. I use it regularly to exchange currencies, someone in one country buys bitcoins with his local currency and sends them to me, i then convert them to local currency. Doing this with bank transfers or paypal has massively higher fees for me. Re: (Score:2) You're not that far off the mark. Re: (Score:3, Informative) Re: (Score:2) At AMD, not NVidia. Unless someone wrote a miner that works on NVidia GPU recently ? Why money has value (Score:3, Interesting) Re: (Score:2) Even with the above reasoning, Bitcoin can still survive if there are enough situations where no currency is de jure standard and Bitcoin has a considerable advantage. Black market for sure, and gray market might be a good candidate for it. In which case it would only take a digital currency system that does not suffer from Bitcoin's inherent scalability problem -- the fact that the computational resources needed for Bitcoin grow with the number of Bitcoin transactions, a fact that is inherent in all digital cash systems and that is typically resolved by means of a central issuing authority that can "renew" tokens -- to kill of Bitcoin. If the only advantage Bitcoin has is that it is a digital cash system, it is only a matter of time before Re: (Score:2) A design that is resilient to regulation is needed in order to have the advantage in the first place, Actually, the biggest advantage of digital cash is that it prevents an untrustworthy merchant from raiding customer accounts (e.g. if a merchant is compromised, credit card data could be used to make unauthorized payments). Anonymity is a secondary goal, and even anonymous payments do not free the parties in the system from regulation -- there is plenty of regulation on cash transactions, which offer a similar level of anonymity. at least some sort of decentralization is practically a requirement Yes, that is true -- the payments should be decentralized in a digital cas Re: (Score:2) What you are really saying is "I don't believe in bitcoin". Other people do, however, to the tune of $40 million USD. If you treat BitCoin as an experiment in electronic currency without a central bank, I would say it is worth it just to learn what works and does not work. Money has been getting ever more electronic over time, and we should have some idea how the fuck it works. Second Life is another experiment in electronic currency. It has a total money supply worth $27 million, convertibility back and Re: (Score:2) but it's better to experiment and make mistakes on one of those, than, say, Greece. True that working small is a good way to test. But the Greece analogy isn't very good. That wasn't about the form/format of money or the exchange thereof. That was about spending than you can afford and don't have the will to produce ... which is just as bad when you're on a barter system as when you're on a currency system. Entitlement mentality killed the Greek economy, not the ebb and flow around currency mechanisms. Re: (Score:2) "Entitlement", as in "investors are entitled to have their gambling losses covered by taxpayer money"? Because that entitlement absolutely dwarfs any and all entitlements the common people in Greece received. And it's the same problem everywhere, including the US. Re: (Score:2) Re: (Score:2) Even if it wasn't a pump and dump scheme it was doomed to failure as a currency for one simple reason: Built in deflation. The total number of bitcoins that can ever exist is finite, and as time goes on they get harder and harder to "mine". So as such, deflation is just built in to the currency, if it were ever adopted on a wide scale. While this is something that plenty of Internet 'tards who have no understanding of economics think is great "The money I have will be worth more!" anyone who knows economics k Re: (Score:3) Actually, I used to really like bitcoin and never thought most of the arguments against it held much water, since they mostly ignore that all the fiction in bitcoin is the same fiction in other currency. All currency is fake, because its all an abstraction. Nothing wrong with that. However, the more I learned about it and dove into it...the more convinced I came of this simple fact... a currency wants deflation because currency isn't intended to be a savings instrument. People hoard gold. People hoarded bitc Re: (Score:2) Sorry.... inflation.... not deflation. Inflation is good (up to a point). Re: (Score:2) Consumer Electronics keep getting cheaper and cheaper. According to your deflation argument, no one would ever buy CE products. The world economy currently relies on inflation. How's that working out, really? Re: (Score:2) If Bitcoins were a national currency its population would be protesting... a 20% overnight drop would be business news if this currency had enough people caring it existed. These money-like substances always seem to fail resulting in no payout to those holding the bag. Nothing left to see here, move along. Sure. But Bitcoin isn't a major reserve currency. It's current size is like a tiny stock, and volatility is expected at that scale. Unlike the corporate micro-currencies (Beenz, Flooz, whatever), Bitcoin doesn't suddenly go under and not pay out. Bitcoin is volatile, but it's still liquid - if you want to trade back to dollars, you can do so at market rate on any of several dozen markets. Bitcoin's not for you if you don't want to deal with volatility, but it has very different properties than any other cu Re: (Score:2, Funny) Zimbabwe should switch to Bitcoin. A 20% overnight drop in their national currency would be a cause for astonished celebration. Sounds interesting (Score:2) Sounds interesting, but I don't find anything about it on the wikipedia pages related to Dwolla and Bitcoin that I googled for. Re: (Score:2) the creators ... have long since turned their fake bitcoins into real spendable dollars The public blockchain [blockexplorer.com] shows that the majority of coins generated in Bitcoin's first year have not moved. Re: (Score:2) Recently, I would have to say that the exact opposite is the case. It remains fairly constant until some inflammatory and misleading article such as this one comes out.
https://news.slashdot.org/story/12/02/15/1658248/major-bitcoin-exchange-ceases-operation?sdsrc=nextbtmnext
CC-MAIN-2017-04
refinedweb
6,126
62.58
Content-type: text/html #include <unistd.h> int nice(int incr); The nice() function allows a process to change its priority. The invoking process must be in a scheduling class that supports the nice(). The nice() function adds the value of incr to the nice value of the calling process. A process's nice value is a non-negative number for which a greater positive value results in lower CPU priority. A maximum nice value of (2 * NZERO) -1 and a minimum nice value of 0 are imposed by the system. NZERO is defined in <limits.h> with a default value of 20. Requests for values above or below these limits result in the nice value being set to the corresponding limit. A nice value of 40 is treated as 39. Calling the nice() function has no effect on the priority of processes or threads with policy SCHED_FIFO or SCHED_RR. Only a process with the {PRIV_PROC_PRIOCNTL} privilege can lower the nice value. Upon successful completion, nice() returns the new nice value minus NZERO. Otherwise, -1 is returned, the process's nice value is not changed, and errno is set to indicate the error. The nice() function will fail if: EINVAL The nice() function is called by a process in a scheduling class other than time-sharing or fixed-priority. EPERM The incr argument is negative or greater than 40 and the {PRIV_PROC_PRIOCNTL} privilege is not asserted in the effective set of the calling process. The priocntl(2) function is a more general interface to scheduler functions. Since -1 is a permissible return value in a successful situation, an application wishing to check for error situations should set errno to 0, then call nice(), and if it returns -1, check to see if errno is non-zero. See attributes(5) for descriptions of the following attributes: nice(1), exec(2), priocntl(2), getpriority(3C), attributes(5), privileges(5), standards(5)
https://backdrift.org/man/SunOS-5.10/man2/nice.2.html
CC-MAIN-2020-34
refinedweb
319
55.54
Re: [openstack-dev] [fuel] Branching strategy vs feature freeze On Wed, Aug 26, 2015 at 4:23 AM, Igor Marnat imar...@mirantis.com wrote: Thierry, Dmitry, key point is that we in Fuel need to follow as much community adopted process as we can, and not to introduce something Fuel specific. We need not only to avoid forking code, but also to avoid forking processes and approaches for Fuel. Both #2 and #3 allow it, making it easier for contributors to participate in the Fuel. #3 (having internal repos for pre-release preparation, bug fixing and small custom features) from community perspective is the same as #2, provided that all the code from these internal repos always ends up being committed upstream. Purely internal logistics. The only one additional note from my side is that we might want to consider an approach slightly adopted similar to what's there in Puppet modules. AFAIK, they are typically released several weeks later than Openstack code. This is natural for Fuel as it depends on these modules and packaging of Openstack. I also think we should go with option #2. What it means to me * Short FF: create stable branch couple of weeks after FF for upstream Fuel * Untie release schedule for upstream Fuel and MOS. This should be two separate schedules * Fuel release schedule should be more aligned with OpenStack release schedule. It should be similar to upstream OpenStack Puppet schedule, where Puppet modules are developed during the same time frame as OpenStack and released just a few weeks later * Internally vendors can have downstream branches (which is option #3 from Dmitry’s email) Thanks, Ruslan __ OpenStack Development Mailing List (not for usage questions) Unsubscribe: openstack-dev-requ...@lists.openstack.org?subject:unsubscribe Re: [openstack-dev] [Congress] [Murano] Congress devstack installation is failing in murano gate job On Wed, Apr 29, 2015 at 6:46 PM, Davanum Srinivas dava...@gmail.com wrote: So, summarizing some chatter on #openstack-dev: Action item for unblocking the gate job: 1. Remove the -U in the shell script that installs thirdparty-requirements.txt in congress' repo. This patch to Congress stable/kilo resolved the issue with failing job gate-murano-congress-devstack-dsvm: If that's not enough: 2. make sure congress' stable/kilo requirements.txt/test-requirements.txt is sync'ed with the global stable/kilo. -- dims __ OpenStack Development Mailing List (not for usage questions) Unsubscribe: openstack-dev-requ...@lists.openstack.org?subject:unsubscribe Re: [openstack-dev] [Murano] SQLite support - drop or not? On Mon, Jan 26, 2015 at 6:12 PM, Andrew Pashkin apash...@mirantis.com wrote: On 26.01.2015 18:05, Ruslan Kamaldinov wrote: I think it's still important to perform migration specific checks. We want to make sure that DB is in expected state after each specific migration. Why? 1. It's not just the schema we care about. It's the effect of particular DB migration script on data stored in DB. We need to make sure that data is not corrupted or lost in any way 2. Some migrations add or remove indexes and constraints, we might want to test that Thanks, Ruslan __ OpenStack Development Mailing List (not for usage questions) Unsubscribe: openstack-dev-requ...@lists.openstack.org?subject:unsubscribe Re: [openstack-dev] [Murano] SQLite support - drop or not? On Mon, Jan 26, 2015 at 3:03 PM, Andrew Pashkin apash...@mirantis.com wrote: On 23.01.2015 23:39, Ruslan Kamaldinov wrote: 1. Use ModelsMigrationsSync from [2] in tests to make sure that SQLAlchemy models are in sync with migrations. Usage example can be found at [3] Seems like it is a great helper, as I understand it runs all migrations and then compares DB state with models state and throws an error if they are out of sync. What I don't understand - why they still manually write checks for every migration [1]? This is redundant, because ModelsMigrationsSync already does the job testing that DB is in sync with models. By the way in Heat project they do the same thing [2]. What am I missing? I think it's still important to perform migration specific checks. We want to make sure that DB is in expected state after each specific migration. [1] [2] 2. Populate DB schema from SQLAlchemy models in unit-tests which require access to DB You mean - using these tools [3]? [3] Yes, this one. We still have this code in source tree: In what conditions 5) will fail? I see only these cases: - If data migrations would be introduced and Murano would require some data in DB to work correctly. Actually, we already do that. We populate initial set of categories: Would it affect anyone? I don't think so. You always can populate these categories manually. - If Murano would use some database-specific features (stored procedures etc). That should never happen :) There are good chances that these cases will never happen in reality, as I understand, so I tend to agree. Agree -- Ruslan __ OpenStack Development Mailing List (not for usage questions) Unsubscribe: openstack-dev-requ...@lists.openstack.org?subject:unsubscribe Re: [openstack-dev] [Murano] SQLite support - drop or not? On Fri, Jan 23, 2015 at 9:04 PM, Andrew Pashkin apash...@mirantis.com wrote: Hello! Current situation with SQLite support: - Migration tests does not run on SQLIte. - At the same time migrations themselves support SQLite (with bugs). Today I came across this bug: Error during execution of database downgrade We can resolve this bug by hardening SQLite support, in that case: - We need to fix migrations and make them support SQLite without bugs, and then continuously make some effort to maintain this support (manually writing migrations and test cases for them). - Also need to introduce migration tests run on SQLite. We also can drop SQLite support and in this case: - We just factor out all that related to SQLite from migrations one time and set this bug as Won't fix. Let's discuss that. I agree that we don't need to support SQLite in migrations. As it was already said in [1], there is no point in running DB migrations against SQLite. Here is what I suggest to do: 1. Use ModelsMigrationsSync from [2] in tests to make sure that SQLAlchemy models are in sync with migrations. Usage example can be found at [3] 2. Populate DB schema from SQLAlchemy models in unit-tests which require access to DB 3. Wipe out everything related to SQLite from DB migrations code 4. Recommend all developers to use MySQL when they run Murano locally 5. For those who still insist on SQLite we can provide a command line option which would generate database schema from SQLAlchemy metadata. This should be declared as development only feature, not supported for any kind of production deployments [1] [2] [3] Thanks, Ruslan __ OpenStack Development Mailing List (not for usage questions) Unsubscribe: openstack-dev-requ...@lists.openstack.org?subject:unsubscribe Re: [openstack-dev] [Murano] Nominating Kate Chernova for murano-core Great Re: [openstack-dev] [Murano] Murano Agent On Mon, Dec 15, 2014 at 7:10 AM, raghavendra@accenture.com wrote: Please let me kow why Murano-agent is required and the components that needs to be installed in it. You can find more details about murano agent at: It can be installed with diskimage-builder: - Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano] - Install Guide Murano installation options are described at: Thanks, Ruslan On Tue, Dec 2, 2014 at 1:41 PM, raghavendra@accenture.com wrote: Hi All, I am new to Murano and trying to integrate with Openstack Juno. Any build guides or help would be appreciated. Warm Regards, Raghavendra Lad IDC–IC-P-Capability Infrastructure Consulting, Infrastructure Services – Accenture Operations Mobile - +91 9880040919. __ ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] IRC meeting cancelled today Folks, I'm canceling our weekly IRC meeting today since we've just released Murano 2014.2 and still working on figuring out roadmap for Kilo cycle. Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] Murano 2014.2 Juno is released I'm glad to announce release of Murano 2014.2 code-named Juno. This release includes 39 implemented blueprints and 140 bugfixes. Source tarballs along with detailed list of features and bugfixes can be found at the following link: Release notes: Thanks to everyone who participated in development of Murano! PS: special thanks to Sergey Lukjanov for handling the release process. -- Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] Juno RC2 available We had to release RC2 to address an issue blocking the inclusion of Murano Dashboard in Debian experimental packages. Tarballs with RC2 are available at: Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] weekly meeting cancelled Since there are no major updates and some folks will not be able to join Murano weekly meeting, we've decided to skip it for today. Short update: 1. The only remaining major item left for juno is documentation and everyone is pretty aware about items we need to have in our docs: 2. We were not able to merge trusts support in Juno and had to postpone it to Kilo 3. A few bugs need to be fixed before the release, most of them have patches on review 4. Murano 3rd party CI wasn't quite stable for a few days due relocation to another DC. Today it got back to normal state Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] Juno-3 released I'm glad to announce Juno-3 release of Murano: We've implemented 8 blueprints and closed 50 bugs. Thanks a lot to everyone who worked on this milestone. All these efforts helped to significantly improve quality and test-coverage of the project! Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [heat] heat.conf.sample is not up to date On Sun, Aug 24, 2014 at 11:10 AM, Mike Spreitzer mspre...@us.ibm.com wrote: What I really need to know is what to do when committing a change that really does require a change in the sample configuration file. Of course I tried running generate_sample.sh, but `tox -epep8` still complains. What is the right procedure to get a correct sample committed? BTW, I am doing the following admittedly risky thing: I run DevStack, and make my changes in /opt/stack/heat/. Mike, It seems that you have oslo.messaging installed from master (default behavior of Devstack), while heat.sample.config is built for oslo.messaging v 1.3.1. As a quick workaround I'd suggest to downgrade oslo.messaging to 1.3.1 in pep8 virtual environment: $ cd /opt/stack/heat $ source .tox/pep8/bin/activate $ pip install oslo.messaging==1.3.1 $ deactivate $ tox -e pep8 # should pass now I'd also like to know what would be the procedure to update sample config when new version of oslo.messaging is released? Maybe we should pin requirements to specific version of oslo library and update that requirement along with the sample config once new version is released? -- Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [pbr] help needed fixing bad version= lines in setup.cfg in many projects On Wed, Aug 20, 2014 at 5:12 AM, Robert Collins robe...@robertcollins.net wrote: Hi, in working on pbr I have run into some bad data in our setup.cfg's. Details are here: Short version: we need to do a missed step in the release project for a bunch of stable branches, and in some cases master, for a bunch of projects. I'm going to script up an automated push up of reviews for all of this, so I'm looking for core and stable branch maintainers to help get the reviews through quickly - as this is a blocker on pbr. We don't need to fix branches that won't be sdist'd anymore - so if its just there for tracking, thats fine. Everything else we should fix. Robert, Thanks a lot for taking care of stackforge projects too! We (Murano) will apply your changes to our active branches. -- Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] Time to Samba! :-) On Sat, Aug 16, 2014 at 11:03 PM, Martinx - ジェームズ thiagocmarti...@gmail.com wrote: Hey There are several existing OpenStack projects which can help to leverage Samba support: 1. Manila - it seems to be capable of provisioning and attaching CIFS/SMB shares. I know Samba is more than just a CIFS share, but it is a significant part of it 2. You can use Heat to spin up a VM and configure Samba server 3. You can use Murano to spin up VMs with Samba, LDAP, Kerberos, etc (done with Heat internally) and configure them to work together Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] Time to Samba! :-) On Sun, Aug 17, 2014 at 4:16 AM, Adam Lawson alaw...@aqorn.com wrote: Doesn't Murano address this already? Please note that Murano is no longer a windows-as-a-service or smth-as-a-serivce. Murano is an application catalog [1]. But you're absolutely right, this is a perfect use case for Murano - application developer can describe those applications and publish them in catalog, which will enable cloud users to combine those apps together. LDAP, Kerberos, Samba, ActiveDirectory - are applications in terms of Murano. [1] -- Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano] [Glance] Image tagging I was going to refer to Graffiti as a longer term plan for image tagging. This initiative seems to be like a really good fit for our image tagging use-cases. For a short-term solutions proposed by Steve I have a couple of comments: 1) Store allowed tags in the database, and allow administrators to add to that list. Ordinary users would likely not be able to create tags, though they could use pre-defined ones for images they owned. In some cases users might upload their own packages and they would likely need to mark some images as compatible with those specific packages. But I think there is a solution. Each time a new package is uploaded, Murano could create a tag with the same name (or fqn). That could help users to to tag package-specific images. 2) Have some public tags, but also allow user-specified tags for private packages. I think this leads to all sorts of tricky edge cases Agree, edge cases will bring a lot of unnecessary complexity. 3) Allow freeform tags (i.e. don’t provide any hints). Since there’s no formal link between the tag that a package looks for and the tags currently defined in code, this wouldn’t make anything more susceptible to inaccuracies In general, I tend to agree that option 1 (with a slight modification) is a good fit for a short-term solution. Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano] Nominations to Murano core Serg, Steve, welcome to Murano core team! -- Ruslan On Thu, Jun 26, 2014 at 8:06 PM, Georgy Okrokvertskhov gokrokvertsk...@mirantis.com wrote: +1 for both! Thanks for the great work! Regards, Gosha On Thu, Jun 26, 2014 at 7:05 AM, Timur Sufiev tsuf...@mirantis.com wrote: +1 for both. On Thu, Jun 26, 2014 at 3:29 PM, Stan Lagun sla...@mirantis.com wrote: +1 for both (or should I say +2?) Sincerely yours, Stan Lagun Principal Software Engineer @ Mirantis On Thu, Jun 26, 2014 at 1:49 PM, Alexander Tivelkov ativel...@mirantis.com wrote: +1 on both Serge and Steve -- Regards, Alexander Tivelkov On Thu, Jun 26, 2014 at 1:37 PM, Ruslan Kamaldinov rkamaldi...@mirantis.com wrote:] [Murano] Nominations to Murano core Re: [openstack-dev] [TC] [Murano] Follow up on cross-project session Hi Thierry! On Wed, Jun 18, 2014 at 1:14 PM, Thierry Carrez thie...@openstack.org wrote: So to take a practical example, Murano lets you pick (using UI or CLI) a wordpress package (which requires a DB) and compose it with a mysql package (which provides a DB), and will deploy that composition using Heat ? And additionally, it provides package-publisher-friendly features like certification, licensing and bulling ? That's a correct example. Does that mean, to come back to my example above, that we could substitute a Trove resource to the mysql package? Yes. Catalog may have several packages for MySQL implementations: MySQL Galera, single node, Trove-based. All of them can return database connection string which will be used by wordpress. or put a Neutron LBaaS load balancer on top ? It should be possible if application can run behind a load balancer and there is an LBaaS resource in Heat. or publish a DNS entry via Designate ? Should be possible, given the underlying infrastructure and catalog provides needed resources. As Murano uses Heat under the hood, whatever is possible in Heat will be possible in Murano. Once Designate resource is available in Heat, application developers can use it. Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [TC] [Murano] Follow up on cross-project session On Wed, Jun 11, 2014 at 8:07 PM, Thierry Carrez thie...@openstack.org wrote: I had a question about Murano's remaining feature set though. If the application catalog lives in Glance and the application deployment lives in Heat, what functionality does Murano end up providing ? Could you elaborate on the composition mission ? Yes, application composition is the main feature of Murano from the user perspective. Let me outline how we see the project responsibilities. Murano will use Glance to store and manage application packages as Glance artifacts. Murano packages could have different formats - currently Murano package. TOSCA TCAR and APS packages [1] will be supported by Murano in the future. Glance artifacts API will allow to store, query, list and index packages. Murano will use Glance to store and manage application packages as Glance artifacts. Heat is used by Murano to manage OpenStack resources and software components. Heat engine is responsible for actual resource provisioning and deployment. On top of those Murano provides the following features: - allow users to combine various packages from catalog by using capabilities and requirements of applications - provide easy-to-use rich UI for end users who don’t necessarily have understanding of the underlying cloud infrastructure - Murano knows how to merge different packages and generates Heat template to deploy the environment, which in terms of Murano is a logical aggregation of multiple applications - as an application catalog allows app publishers and cloud owners to certify and license packages, provide additional partner information - allow to define billing rules. Murano can generate events predefined by app publisher to Ceilometer and integrate with 3rd party billing systems to bill users based on Ceilometer statistics - third-party services plumbing to support integration with APIs, both in stack, like Trove, and external Hopefully this document [2] started as initiative elaborated from our cross-project session will help to understand what Murano provides from user perspective. [1] [2] Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [TC] [Murano] Follow up on cross-project session Hi community and TC members! First a little bit of history: Murano applied for incubation in February 2014 [1]. TC discussion [2] finished the following resolution (quote from ttx): Murano is slightly too far up the stack at this point to meet the measured progression of openstack as a whole requirement. We'll facilitate collaboration in that space by setting up a cross-project session to advance this at the next design summit. Thanks to the TC, we had two official cross-project sessions at the Atlanta summit. We also had a follow-up session with a more focused group of people. - I would like to share the results of these sessions with the community and with the TC members. The official etherpads from the session is located here: Now, more details. Here is the outcome of the first two (official) sessions: * We addressed questions about use-cases and user roles of Murano [3] * We clarified that Murano is already using existing projects and will use other projects (such as Heat and Mistral) to the fullest extent possible to avoid any functional duplication * We reached a consensus and vision on non-overlapping scopes of Murano and Solum Here is the link to the session etherpad [4]. Our follow-up session was very productive. The goal of this session was to define and document a clear scope for each project [5]. This is the main document in regards to the goals set by TC in response to Murano incubation request. We identified a clear scope for each project and possible points for integration and collaboration: * Application Development - Solum * Application Catalog/Composition - Murano (see for details) * Application Deployment/Configuration - Heat We hope that we addressed major concerns raised at the TC meeting [2] initiated by the previous Murano incubation request. We will now focus on stabilizing and maturing the project itself with the end goal of again applying for incubation by the end of the Juno cycle. [1] [2] [3] [4] [5] Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano] Murano API improvements Let's follow the standard procedure. Both blueprints lack specification of implementation details. There also has to be someone willing to implement these blueprints in near feature. I'm not opposed to these ideas and I'd really like to see Pecan added during Juno, but we still need to follow the procedure. I cannot approve an idea, it should be a specification. Let's work together on the new API specification first, then we'll need to find a volunteer to implement it on top of Pecan. -- Ruslan On Mon, Jun 2, 2014 at 8:35 AM, Timur Nurlygayanov tnurlygaya...@mirantis.com wrote: Hi all, We need to rewrite Murano API on new API framework and we have the commit: (Sergey, sorry, but -1 from me, need to fix small isses) Also, today I created blueprint: this feature allows to run many API threads on one host and this allows to scale Murano API processes. I suggest to update and merge this commit with migration to Pecan framework and after that we can easily implement this blueprint and add many other improvements to Murano API and Murano python agent. Ruslan, could you please approve these blueprints and target them to some milestone? Thank you! -- Timur, QA Engineer OpenStack Projects Mirantis Inc ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] repository murano-api renamed to murano Just a heads up: Repository stackforge/murano-api was renamed to stackforge/murano on May 23. All the commit and review history is preserved and can be viewed under the new name [1], [2]. We also renamed [3]: * internal package name from muranoapi to murano * config file names under etc/murano Now, our devstack/tempest job is green again. As it was agreed on the meeting today we're going to mark it as voting in one week from now. [1] [2] [3] -- Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano] Meet Murano developers at Atlanta summit On Wed, May 14, 2014 at 1:31 PM, Ruslan Kamaldinov rkamaldi...@mirantis.com wrote: Uh oh. Markeеplace on level 1 is closed today. We will be at the developer lounge in the B301-B306 area. Time is the same - from 3PM to 5PM on Thursday. ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] Meet Murano developers at Atlanta summit ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Heat] [Murano] [Solum] [TC] agenda for cross-project session - how to handle app lifecycle ? On Sat, May 10, 2014 at 7:02 AM, Ruslan Kamaldinov rkamaldi...@mirantis.com wrote: I've updated the session etherpad [1] with the follow-up. Please see the bottom of the document (I didn't want to modify notes taken during the session). Session went well. There were couple of items/questions raised during the session which should be discussed in more details. As we agreed at the design session, let us leverage the fact of the local presence of the members of each team (Heat, Murano, Solum) and to have a follow up session to: - reiterate over the cross-projects session results and ensure everybody understands it the same way - to start discussing an approach to have a common cross-project environment description Zane expressed readiness to participate in such a session on Thursday. Let's figure out who else can participate from Heat and Solum team to have a meeting on Thursday in one of the design PODs at the second level. [1] ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Heat] [Murano] [Solum] [TC] agenda for cross-project session - how to handle app lifecycle ? ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] How-to and best practices for developing new OpenStack service On Thu, May 8, 2014 at 11:16 AM, Ruslan Kiianchuk ruslan.kiianc...@gmail.com wrote: Short tutorial for developers not familiar with OpenStack infrastructure still would be useful. My task is to help Python developers that haven't worked with OpenStack before start an OpenStack service development in the shortest possible period. If none will come up, I'll be thinking about writing one :) Yes, intro tutorial could be useful. But before you start, please take a look at existing resources: 1. 2. 3. AFAIK Stefano and Tom are working on something similar. Added them to cc list. Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Murano] Release 0.5 I'd like to announce release of Murano 0.5 - Application Catalog for OpenStack. This release includes 28 implemented blueprints and 76 bug fixes. Release notes and tarballs can be found here: Here is the demo: More demos to come on the next week :) -- Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] How-to and best practices for developing new OpenStack service Hi Ruslan! I can recommend two resources: 1. cookiecutter [1] - template for a new OpenStack project 2. - this page helps to setup a project in OpenStack infrastructure, including code-review, Jenkins automation, etc. [1] Regards, Ruslan On Wed, May 7, 2014 at 4:08 PM, Ruslan Kiianchuk ruslan.kiianc...@gmail.com wrote: an OpenStack service from scratch? Something that would describe correct usage of Oslo project, common architecture and give recommendations for developers. Thank you. -- Sincerely, Ruslan Kiianchuk. ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Heat] Design summit preparation - Next steps for Heat Software Orchestration On Tue, Apr 22, 2014 at 8:42 PM, Thomas Spatzier thomas.spatz...@de.ibm.com wrote: #2 Enable add-hoc actions on software components: Apart from basic resource lifecycle hooks, it would be desirable to allow for invocation of add-hoc actions on software. Examples would be the ad-hoc creation of DB backups, application of patches, or creation of users for an application. Such hooks (implemented as scripts, Chef recipes or Puppet facts) could be defined in the same way as basic lifecycle hooks. They could be triggered by doing property updates on the respective SoftwareDeployment resources (just a thought and to be discussed during design sessions). I think this item could help bridging over to some discussions raised by the Murano team recently (my interpretation: being able to trigger actions from workflows). It would add a small feature on top of the current software orchestration in Heat and keep definitions in one place. And it would allow triggering by something or somebody else (e.g. a workflow) probably using existing APIs. Hi Thomas, This is exactly what we need in Heat for Murano workflows. Also, I believe that what you described above, perfectly maps on TOSCA, which is also very good for us :) From the implementation point of view and our previous discussions I figure out that Mistral can be a good fit for lifecycle hooks execution. Renat (Mistral lead) added a topic [1] for Heat weekly meeting, I hope we can discuss this today as part of that topic. [1] Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [murano] Proposal to add Ruslan Kamaldinov to murano-core team Thank you, guys :) Ruslan On Mon, Apr 21, 2014 at 1:40 PM, Timur Nurlygayanov tnurlygaya...@mirantis.com wrote: +1 Ruslan, congratulations! On Fri, Apr 18, 2014 at 1:41 PM, Timur Sufiev tsuf...@mirantis.com wrote: Ruslan, welcome to the Murano core team :)! On Thu, Apr 17, 2014 at 7:32 PM, Anastasia Kuznetsova akuznets...@mirantis.com wrote: +1 On Thu, Apr 17, 2014 at 7:11 PM, Stan Lagun sla...@mirantis.com wrote: +1 Sincerely yours, Stan Lagun Principal Software Engineer @ Mirantis On Thu, Apr 17, 2014 at 6:51 PM, Georgy Okrokvertskhov gokrokvertsk...@mirantis.com wrote: +1 On Thu, Apr 17, 2014 at 6:01 AM, Dmitry Teselkin dtesel...@mirantis.com wrote: +1 Agree On Thu, Apr 17, 2014 at 4:51 PM, Alexander Tivelkov ativel...@mirantis.com wrote: +1 Totally agree -- Regards, Alexander Tivelkov On Thu, Apr 17, 2014 at 4:37 PM, Timur Sufiev tsuf...@mirantis.com wrote: Guys, Ruslan Kamaldinov has been doing a lot of things for Murano recently (including devstack integration, automation scripts, making Murano more compliant with OpenStack standards and doing many reviews). He's actively participating in our ML discussions as well. I suggest to add him to the core team. Murano folks, please say your +1/-1 word. -- Timur Sufiev ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org -- Thanks, Dmitry Teselkin Deployment Engineer Mirantis ___ -- Timur, QA Engineer OpenStack Projects Mirantis Inc ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano] Working in devstack? Hi Mark! Actually we have working Devstack scripts at [0]. We use these scripts to setup Murano in the dsvm (devstack/tempest) gate job which run Murano functional tests. It means that our Devstack scripts are in a good shape. Please use Devstack scripts from [0], all the other scripts are deprecated. I will make sure we mark them as deprecated ASAP. There is also a patch [1] which enables murano-dashboard in Devstack. It should be merged soon. What we're missing at this moment is developer documentation for the current release 0.5. I've added a blueprint [2] and started working on it. Feel free to ping us at #murano channel (my irc handle is ruhe) if you have any questions. [0] [1] [2] Thanks, Ruslan On Wed, Apr 16, 2014 at 3:53 AM, Mark Kirkwood mark.kirkw...@catalyst.net.nz wrote: Thanks...yes, I'd not realized that running ./stack.sh again would unpatch my murano-api/setup.sh! Rerunning the db setup as you suggested gives me the tables. I didn't do it in as tidy a manner as yours however :-) $ export OS_USERNAME=admin $ export OS_PASSWORD=swordfish $ export OS_TENANT_NAME=demo $ export OS_AUTH_URL= $ murano-manage --config-file /etc/murano/murano-api.conf db-sync Cheers Mark On 16/04/14 11:23, Georgy Okrokvertskhov wrote: Hi Mark, Thank you for a detailed report. As I know Murano team is working on fixing devstack scripts. As for DB setup it should be done by a command: tox -evenv -- murano-manage --config-file etc/murano/murano-api.conf db-sync It works in my testing environment. Thanks Georgy On Tue, Apr 15, 2014 at 4:11 PM, Mark Kirkwood mark.kirkw...@catalyst.net.nz wrote: Hi all, There is some interest here in making use of Murano for Samba ADDC a service...so we've been (attempting) to get it up and running in devstack. In the process I've managed to get myself confused about the correct instructions for doing this: - the docs suggest content/ch04s03.html - the project provides murano-deployment/devstack-scripts/README.rst) ...which are markedly different approaches (it *looks* like the project README.rst is out of date, as it the scripts it runs try to get heat-horizon from repos that do not exist anymore). If this approach is not longer workable, we should really remove (or correct these instructions). So following content/ch04s03.html inside a Ubuntu 12.04 VM I stumbled into a few bugs: - several missing deps in various murano-*/requirements.txt (see attached) - typo in /murano-api/setup.sh (db_sync vs db-sync) Fixing these seems to get most things going (some tabs crash with missing tables, so I need to dig a bit more to find where they get created...). Any pointers/etc would be much appreciated! Cheers Mark ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Heat] [Murano] [Solum] applications in the cloud Update: Stan filed a blueprint [0] for type interfaces in HOT. I would like to outline the current vision of Murano Application format, to make sure we're all on the same page. We had a valuable discussion in several MLs and we also had a lot of discussions between Murano team members. As a result of these discussion we see the following plan for Murano: * Adopt TOSCA for application definition in Murano. Work with TOSCA committee * Utilize Heat as much as possible. Participate in discussions and implementations for hooks mechanism in Heat. Participate in HOT format discussions * Adopt Mistral DSL for workflow management. Find a way to compose Heat templates and Mistral DSL * Keep MuranoPL engine in the source tree to take care of all the features we need for our users until those features are implemented on top things described above Murano, Heat teams, please let me know if this plan sounds sane to you. [0] Thanks, Ruslan On Sat, Apr 5, 2014 at 12:25 PM, Thomas Spatzier thomas.spatz...@de.ibm.com wrote: Clint Byrum cl...@fewbar.com wrote on 04/04/2014 19:05:04: From: Clint Byrum cl...@fewbar.com To: openstack-dev openstack-dev@lists.openstack.org Date: 04/04/2014 19:06 Subject: Re: [openstack-dev] [Heat] [Murano] [Solum] applications inthe cloud Excerpts from Stan Lagun's message of 2014-04-04 02:54:05 -0700: Hi Steve, Thomas I'm glad the discussion is so constructive! If we add type interfaces to HOT this may do the job. Applications in AppCatalog need to be portable across OpenStack clouds. Thus if we use some globally-unique type naming system applications could identify their dependencies in unambiguous way. We also would need to establish relations between between interfaces. Suppose there is My::Something::Database interface and 7 compatible materializations: My::Something::TroveMySQL My::Something::GaleraMySQL My::Something::PostgreSQL My::Something::OracleDB My::Something::MariaDB My::Something::MongoDB My::Something::HBase There are apps that (say SQLAlchemy-based apps) are fine with any relational DB. In that case all templates except for MongoDB and HBase should be matched. There are apps that design to work with MySQL only. In that case only TroveMySQL, GaleraMySQL and MariaDB should be matched. There are application who uses PL/SQL and thus require OracleDB (there can be several Oracle implementations as well). There are also applications (Marconi and Ceilometer are good example) that can use both some SQL and NoSQL databases. So conformance to Database interface is not enough and some sort of interface hierarchy required. IMO that is not really true and trying to stick all these databases into one SQL database interface is not a use case I'm interested in pursuing. Far more interesting is having each one be its own interface which apps can assert that they support or not. Agree, this looks like a feasible goal and would already bring some value add in that one could look up appropriate provider templates instead of having to explicitly link them in environments. Doing too much of inheritance sounds interesting at first glance but burries a lot of complexity. Another thing that we need to consider is that even compatible implementations may have different set of parameters. For example clustered-HA PostgreSQL implementation may require additional parameters besides those needed for plain single instance variant. Template that consumes *any* PostgreSQL will not be aware of those additional parameters. Thus they need to be dynamically added to environment's input parameters and resource consumer to be patched to pass those parameters to actual implementation I think this is a middleware pipe-dream and the devil is in the details. Just give users the ability to be specific, and then generic patterns will arise from those later on. I'd rather see a focus on namespacing and relative composition, so that providers of the same type that actually do use the same interface but are alternate implementations will be able to be consumed. So for instance there is the non-Neutron LBaaS and the Neutron LBaaS, and both have their merits for operators, but are basically identical from an application standpoint. That seems a better guiding use case than different databases. ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [OpenStack-Infra][Ceilometer][MagnetoDB] HBase database in devstack On Tue, Apr 8, 2014 at 8:42 PM, Sean Dague s...@dague.net wrote: I think it's important to understand what we mean by stable in the gate. It means that the end point is 99.% available. And that it's up or down status is largely under our control. Things that are not stable by this definition which we've moved away from for the gate: * github.com - one of the reasons for git.openstack.org * pypi.python.org - one of the reasons for our own pypi mirror * upstream distro mirrors (we use cloud specific mirrors, which even then do fail some times, more than we'd like) Fedora.org is not stable by this measure either. Downloading an iso from fedora.org fails 5% of the time in the gate. I'm sure the Hortonworks folks are good folks, but by our standards of reliability, no one stacks up. And an outage on their behalf means that any project which gates on it will be blocked from merging any code until it's addressed. If Ceilometer wants to take that risk in their check queue (and be potentially blocked) that might be one thing, and we could talk about that. But we definitely can't co-gate and block all of openstack because of a hortonworks outage (which will happen, especially if we download packages from them 600 - 1000 times a day). A natural solution for this would be a local to infra package mirror for HBase, Ceilometer, Mongo and all the dependencies not present in upstream Ubuntu. It seems straightforward from the technical point of view. It'll help to keep the Gate invulnerable to any outages in 3-rd party mirrors. Of course, someone has to signup to create scripts for that mirror and support it in the future. But, other concerns were expressed in the past. Let me quote Jeremy Stanley (from): This will need to be maintained in Ubuntu (and backported to 12.04 in Ubuntu Cloud Archive or if necessary a PPA managed by the same package maintenance team taking care of it in later Ubuntu releases). We don't install test requirements system-wide on our long-running test slaves unless we can be assured of security support from the Linux distribution vendor. There is no easy workaround here. Traditionally this kind of software is installed from vendor-supported mirrors and distributions. And they're the ones who maintain and provide security updates from Hadoop/HBase packages. In case of Ceilometer, I think that importance of having real tests on real databases is more important than the requirement for the packages to have security support from a Linux distribution. Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [sahara] team meeting April 3 1800 UTC [savanna] On Wed, Apr 2, 2014 at 11:13 PM, Dmitry mey...@gmail.com wrote: Hi, I'm wondering if you have plans to use Murano for a cluster management? Thanks, Dmitry Dmitry, Sahara is not going to use Murano for cluster management. Sahara uses Heat for underlying infrastructure management and various Hadoop management tools (e.g. Ambari from Hortonworks Data Platform) to manage Hadoop clusters. Also Sahara builds a nice layer of abstraction above different distributions to define and use cluster templates to provision Hadoop and related software. On the other hand, Murano might expose Sahara/Hadoop clusters in the app catalog. Sahara developers already work on implementation of Sahara resource in Heat. So, it'll be available through Heat templates. Here [0] you can find an example of Heat template for Sahara. [0] Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Heat] [Murano] [Solum] applications in the cloud This is a continuation of the MuranoPL questions thread. As a result of ongoing discussions, we figured out that definition of layers which each project operates on and has responsibility for is not yet agreed and discussed between projects and teams (Heat, Murano, Solum (in alphabetical order)). Our suggestion and expectation from this working group is to have such a definition of layers, agreement on it and an approach of reaching it. As a starting point, we suggest the following: There are three layers of responsibility: 1. Resources of the cloud 2. Applications of the cloud 3. Layers specific for Murano and Solum (to be further discussed and clarified, for this discussion it's out of scope) Layer 1 is obviously covered by Heat. Most of the disagreement is around layer 2. Our suggestion is to figure out the way where we can have common engine, DSL and approach to apps description. For this we'll take HOT and TOSCA as a basis and will work on addition of functionality missing from Murano and Solum point of view. We'll be happy if existing Heat team continue working on it, having the full control of the project, provided that we agree on functionality missing there from Murano and Solum point of view and addition of this functionality in a systematic way. Let me outline the main concern in regards to HOT from Murano perspective. Others concerns could be figured out later. The typical use case for Murano is the following: Application writer sets a requirement for her application to use RDBMS assuming that it can be MySQL, PostgreSQL or MSSQL. HOT engine should be able to understand such requirements and be able to satisfy them by instantiating instances with DB. End user should be able to control which particular type of DB should be used. This is quite similar to abstract requirements described in TOSCA. As Heat wants to cover TOSCA format too this Murano requirement is pretty well aligned with what HOT\TOSCA can provide. Hopefully this functionality can be introduced into HOT. Solum and Murano will leverage it by using some common API, and implementing layer 3 as thin as possible. Again, this is only suggested starting point, something to begin with. Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] Doc to with pointers on how to review? On Mon, Mar 31, 2014 at 5:57 AM, Tom Fifield t...@openstack.org wrote: Hi, Just wondering, do we have a document somewhere that educates people on how to do a code review? eg giving a few pointers that reviewers for a particular project normally look for Hi Tom, The closest to your description document is: ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano][Heat] MuranoPL questions? On Thu, Mar 27, 2014 at 7:42 PM, Georgy Okrokvertskhov gokrokvertsk...@mirantis.com wrote: Given that I don't see the huge overlap here with Murano functionality as even if Solum stated that as a part of solution Heat template will be generated it does not necessarily mean that Solum itself will do this. From what is listed on the Solum page, in Solum sense - ALM is a way how the application build from source promoted between different CI\CD environments Dev, QA, Stage, Production. Solum can use other service to do this keeping its own focus on the target area. Specifically to the environments - Solum can use Murano environments which for Murano is just a logical unity of multiple applications. Solum can add CI\CD specific stuff on top of it keeping using Murano API for the environment management under the hood. Again, this is a typical OpenStack approach to have different services integrated to achieve the larger goal, keeping services itself very focused. Folks, I'd like to call for a cross-project work group to identify approaches for application description and management in the OpenStack cloud. As this thread shows there are several parties involved - Heat, Mistral, Murano, Solum (did I miss anyone?), there is no clear vision among us where and how we should describe things on top of Heat. We could spend another couple of months in debates, but I feel that focused group of dedicated people (i.e 2 from each project) would progress much faster and will be much more productive. What I'd suggest to expect from this joint group: * Identify how different aspects of applications and their lifecycle can be described and how they can coexist in OpenStack * Define a multi-layered structure to keep each layer with clear focus and set of responsibilities * End goal of the work for this group will be a document with a clear vision of covering areas higher up to Heat stack and how OpenStack should address that. This vision is not clear now for TC and that is the reason they say that it is to big step which Murano did * Agree on further direction * Come to ATL summit, agree again and drink beer Focused group would require additional communication channels: * Calls (Google Hangouts for instance) * Additional IRC meetings * Group work on design documents From Murano project I'd like to propose the following participants: * Stan Lagun (sla...@mirantis.com) * Ruslan Kamaldinov (rkamaldi...@mirantis.com) Do colleagues from Heat, Solum and Mistral feel the same way and would like to support this movement and delegate their participants to this working group? Is this idea viable? -- Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano][Heat] MuranoPL questions? Murano folks, I guess we should stop our debates with the Heat team about MuranoPL. What we should do instead is to carefully read this thread couple of times and collect and process all the feedback we've got. Steve and Zane did a very good job helping us to find a way to align with Heat and Orhcestration program. Let me outline the most important (imho) quotes: # START quotes Steven Dake: I see no issue with HOT remaining simple and tidy focused entirely on orchestration (taking a desired state and converting that into reality) with some other imperative language layered on top to handle workflow and ALM. I believe this separation of concerns is best for OpenStack and should be the preferred development path. Zane Bitter: I do think we should implement the hooks I mentioned at the start of this thread to allow tighter integration between Heat and a workflow engine (i.e. Mistral).). To me that implies that Murano should be a relatively thin wrapper that ties together HOT and Mistral's DSL. Steve Dake: --- I don't think HOT can do these things and I don't think we want HOT to do these things. I am ok with that, since I don't see the pushback on having two languages for two different things in OpenStack. I got from gokrove on iRC today that the rationale for the pushback was the TC wanted Murano folks to explore how to integrate better with Heat and possibly the orchestration program. I don't see HOT as a place where there is an opportunity for scope expansion. I see instead Murano creating HOT blobs and feeding them to Heat. Zane Bitter: Because there have to be some base types that you can use as building blocks. In the case of Heat, those base types are the set of things that you can create by talking to OpenStack APIs authenticated with the user's token. In the case of Mistral, I would expect it to be the set of actions that you can take by talking to OpenStack APIs authenticated with the user's token. And in the case of Murano, I would expect it to be the union of those two. Everything is a combination of existing resources, because the set of existing resources is the set of things which the operator provides as-a-Service. The set of things that the operator provides as a service plus the set of things that you can implement yourself on your own server (virtual or not) covers the entire universe of things. What you appear to be suggesting is that OpenStack must provide *Everything*-as-a-Service by allowing users to write their own services and have the operator execute them as-a-Service. This would be a breathtakingly ambitious undertaking, and I don't mean that in a good way. When the TC said Murano is slightly too far up the stack at this point to meet the measured progression of openstack as a whole requirement, IMO one of the major things they meant was that you're inventing your own workflow thing, leading to duplication of effort between this and Workflow as a Service. (And Mistral folks are in turn doing the same thing by not using the same workflow library, taskflow, as the rest of OpenStack.) Candidly, I'm surprised that this is not the #1 thing on your priority list because IMO it's the #1 thing that will delay getting the project incubated. # END quotes Also I should quote what Georgy Okrokvertkhov said: Having this aligned I see a Murano package as an archive with all necessary definitions and resources and Murano service will just properly pass them to related services like Heat and Mistral. I think then Murano DSL will be much more simple and probably will be closer to declarative format with some specific data operations. Summary: I would like to propose further path for Murano evolution where it evolves as an OpenStack project, aligned with others and developed in agreement between all the interested sides. Here is the plan: * Step forward and implement hooks (for workflow customization) in Heat. We will register a blueprint, discuss it with the Heat team and implement it * Use our cross-project session on ATL summit to set clear goals and expectations * Build pilot in Murano which: a. Uses new HOT Software components to do VM side software deployments b. Uses Mistral DSL to describe workflow. It'll require more focused discussion with Mistral team c. Bundles all that into an application package using new Murano DSL d. Allows users to combine applications in a single environenment * Continuously align with the Heat team * Continuously re-evaluate current state of pilot Re: [openstack-dev] Separating our Murano PL core in own package On Mon, Mar 24, 2014 at 10:08 PM, Joshua Harlow harlo...@yahoo-inc.com wrote: Seeing that the following repos already exist, maybe there is some need for cleanup? - - - - - - - - - - ...(did I miss others?) Can we maybe not have more git repositories and instead figure out a way to have 1 repository (perhaps with submodules?) ;-) It appears like murano is already exploding all over stackforge which makes it hard to understand why yet another repo is needed. I understand why from a code point of view, but it doesn't seem right from a code organization point of view to continue adding repos. It seems like murano () should just have 1 repo, with sub-repos (tests, docs, api, agent...) for its own organizational usage instead of X repos that expose others to murano's internal organizational details. -Josh Joshua, I agree that this huge number of repositories is confusing for newcomers. I've spent some time to understand mission of each of these repos. That's why we already did the cleanup :) [0] And I personally will do everything to prevent creation of new repo for Murano. Here is the list of repositories targeted for the next Murano release (Apr 17): * murano-api * murano-agent * python-muranoclient * murano-dashboard * murano-docs The rest of these repos will be deprecated right after the release. Also we will rename murano-api to just murano. murano-api will include all the Murano services, functionaltests for Tempest, Devstack scripts, developer docs. I guess we already can update README files in deprecated repos to avoid further confusion. I wouldn't agree that there should be just one repo. Almost every OpenStack project has it's own repo for python client. All the user docs are kept in a separate repo. Guest agent code should live in it's own repository to keep number of dependencies as low as possible. I'd say there should be required/comfortable minimum of repositories per project. And one more nit correction: OpenStack has it's own git repository [1]. We shoul avoid referring to github since it's just a convinient mirror, while [1] is an official OpenStack repository. [0] [1] Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] MuranoPL questions? Joshua, Clint, The only platform I'm aware about which fully supports true isolation and which has been used in production for this purpose is Java VM. I know people who developed systems for online programming competitions and really smart kids tried to break it without any luck :) Since we're speaking about Heat, Mistral and Murano DSLs and all of them need an execution engine. Do you think that JVM could become a host for that engine? JVM has a lot of potential: - it allows to fine-tune security manager to allow/disallow specific actions - it can execute a lot of programming languages - Python, Ruby, JS, etc - it has been used in production for this specific purpose for years But it also introduces another layer of complexity: - it's another component to deploy, configure and monitor - it's non-python, which means it should be supported by infra - we will need to run java service and potentially have some java code to accept and process user code Thanks, Ruslan On Mon, Mar 17, 2014 at 10:40 PM, Joshua Harlow harlo...a...@mirantis.com Reply-To: OpenStack Development Mailing List (not for usage questions) openstack-dev@lists.openstack.org Date: Monday, March 17, 2014 at 3:59 AM To: OpenStack Development Mailing List (not for usage questions) openstack-devlo...me...@mirantis.com Reply-To: OpenStack Development Mailing List (not for usage questions) openstack-dev@lists.openstack.org Date: Monday, March 10, 2014 at 8:36 PM To: OpenStack Development Mailing List (not for usage questions) openstack-dev Re: [openstack-dev] [Murano][Heat] MuranoPL questions? Here is my 2 cents: I personally think that evolving Heat/HOT to what Murano needs for it's use cases is the best way to make PaaS layer of OpenStack to look and feel as a complete and fully integrated solution. Standardising these things in a project like TOSCA is another direction we all should follow. I think that TOSCA is the place where developers (like us), application developers and enterprises can collaborate to produce a common standard for application lifecycle management in the clouds. But before Murano contributors jump into direction of extending HOT to the goal of application (or system) lifecycle management, we need an agreement that this is the right direction for Heat/HOT/DSL and the Orchestration program. There are a lot of use cases that current HOT doesn't seem to be the right tool to solve. As it was said before, it's not a problem to collaborate on extending it those use cases. I'm just unsure if Heat team would like these use cases to be solved with Heat/HOT/DSL. For instance: - If everyone agrees that this is the direction we all should follow, that we should expand HOT/DSL to that scope, that HOT should be the answer on can you express it?, then awesome - we can start speaking about implementation details. If it's not the direction these projects should follow then at least finding where Heat ends and Murano starts to avoid any functionality duplication would be great. Thanks, Ruslan On Wed, Mar 19, 2014 at 2:07 AM, Keith Bray keith.b...@rackspace.com wrote: Georgy, In consideration of the can you express it instead of the who will generate it, I see Heat's HOT evolving to support the expression of complex multi-tier architectures and applications (I would argue you can already do this today, perhaps with some additional features desired, e.g. Ability to define cloud workflows and workflow execution rules which could come when we have a workflow service like Mistral). Therefore, I would encourage Murano contributors to consider whether they can help make Heat sufficiently cover desired use cases. I have never viewed Heat templates as isolated components of a multi-tier architecture. Instead, a single template or a combination of master/subordinate templates together (using references, nesting, or inclusion) could express the complete architecture, both infrastructure and applications. If I've read your previous comments and threads correctly, you desire a way to express System Lifecycle Management across multiple related applications or components, whereby you view the System as a grouping of independently developed and/or deployed (but systematically related) components, whereby you view Components as individual disconnected Heat templates that independently describe different application stacks of the System. Did I get that correct? If so, perhaps the discussion here is one of scope of what can or should be expressed in a Heat template. Is it correct to state that your argument is that a separate system (such as Murano) should be used to express System Lifecycle Management as I've defined it here? If so, why could we not use the Heat DSL to also define the System? The System definition could be logically separated out into its own text file... But, we'd have a common DSL syntax and semantics for both lower level and higher level component interaction (a building block effect of sorts). As for who will generate it, ( with it being the Heat multi-tier application/infrastructure definition) I think that question will go through a lot more evolution and could be any number of sources: e.g. Solum, Murano, Horizon, Template Author with a text editor, etc. Basically, I'm a +1 for as few DSLs as possible. I support the position that we should evolve HOT if needed vs. having two separate DSLs that are both related to expressing application and infrastructure semantics. Workflow is quite interesting ... Should we be able to express imperative workflow semantics in HOT? Or, should we only be able to declare workflow configurations that get configured in a service like Mistral whereby Mistral's execution of a workflow may need to invoke Heat hooks or Stack Updates? Or, some other solution? I look forward to a design discussion on all this at the summit... This is fun stuff to think about! -Keith From: Georgy Okrokvertskhov gokrokvertsk...@mirantis.com Reply-To: OpenStack Development Mailing List (not for usage questions) openstack-dev@lists.openstack.org Date: Tuesday, March 18, 2014 1:49 PM To: OpenStack Development Mailing List (not for usage questions) openstack-dev@lists.openstack.org Subject: Re: [openstack-dev] [savanna] Documentation update for IceHouse As it was decided on our latest meeting I've added a new blueprint for documentation updates: Here is a list of work items I've proposed: * Update installation guide * Setup development environment * Devstack guide * Tempest tests for Savanna * DIB instructions * Replace github with git.o.o * How-to add a new migration script * Update rest-api docs Please, feel free to add new work items or assign them to yourself. Thanks, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Murano] Repositoris re-organization I'd suggest to reduce number of Murano repositories for several reasons: * All other OpenStack projects have a single repo per project. While this point might look like something not worth mentioning, it's really important: - unified project structure simplifies life for new developers. once they get familiar with one project, they can expect something similar from another project - unified project structure simplifies life for deployers. similar project structure simplifies packaging and deployment automation * Another important reason is to simplify gated testing. Just take a look at Solum layout [1], they have everything needed (contrib, functionaltests) to run dvsm job in a single repo. One simple job definition [2] allows to install Solum in DevStack and run Tempest tests for Solum. * As a side-effect, this approach will improve integrity of project components. Having murano-common in the same repo with other components will help to catch integration issues earlier. In an ideal world there will be only the following repos: - murano (api, common, conductor, docs, repository, tests) - python-muranoclient - murano-dashboard - murano-agent - puppet-murano (optional, but nice to have) [1] [2] Thanks, Ruslan On Thu, Feb 6, 2014 at 3:14 PM, Serg Melikyan smelik...@mirantis.comwrote: Hi, Alexander, In general I am completely agree with Clint and Robert, and as one of contributors of Murano I don't see any practical reasons for repositories reorganization. And regarding of your proposal I have a few thoughts that I would like to share below: This enourmous amount of repositories adds too much infrustructural complexity Creating a new repository is a quick, easy and completely automated procedure that requires only simple commit to Zuul configuration. All infrastructure related to repositories is handled by Openstack CI and supported by Openstack Infra Team, and actually don't require anything from project development team. About what infrastructure complexity you are talking about? I actually think keeping them separate is a great way to make sure you have ongoing API stability. (c) Clint I would like to share a little statistic gathered by Stan Lagun a little time ago regarding repositories count in different PaaS solution. If you are concerned about large number of repositories used by Murano, you will be quite amused: - - 275 - - 132 - - 49 - - 46 First of all, I would suggest to have a single reposository for all the three main components of Murano: main murano API (the contents of the present), workflow execution engine (currently murano-conductor; also it was suggested to rename the component itself to murano-engine for more consistent naming) and metadata repository (currently murano-repository). *murano-api* and *murano-repository* have many things in common, they are both present HTTP API to the user, and I hope would be rewritten to common framework (Pecan?). But *murano-conductor* have only one thing in common with other two components: code shared under *murano-common*. That repository may be eventually eliminated by moving to Oslo (as it should be done). Also, it has been suggested to move our agents (both windows and unified python) into the main repository as well - just to put them into a separate subfolder. I don't see any reasons why they should be separated from core Murano: I don't believe we are going to have any third-party implementations of our Unified agent proposals, while this possibility was the main reason for separatinng them. Main reason for murano-agent to have separate repository was not a possibility to have another implementation, but that all sources that should be able to be built as package, have tests and can be uploaded to PyPI (or any other gate job) should be placed in different repository. OpenStack CI have several rules regarding how repositories should be organized to support running different gate jobs. For example, to run tests *tox.ini* is need to be present in root directory, to build package *setup.py* should be present in root directory. So we could not simply move them to separate directories in main repository and have same capabilities as in separate repository. Next, deployment scripts and auto-generated docs: are there reasons why they should be in their own repositories, instead of docs and tools/deployment folders of the primary repo? I would prefer the latter: docs and deployment scripts have no meaning without the sources which they document/deploy - so it is better to have them consistent. We have *developers documentation* alongside with all sources: Re: [openstack-dev] [savanna] neutron and private networks This approach looks good. But I'd like to outline an issue people might hit in real-world production installations: Let's imagine OpenStack is installed in HA mode. There are several controllers, they run Savanna and Q3 services in HA mode. The problem is that active Savanna service should run on the same host with active Q3 service. Otherwise proposed approach will not work. It will require some advanced configuration in HA software - Savanna should always run on the same host with Q3. Ruslan On Thu, Oct 3, 2013 at 7:21 PM, Jon Maron jma...@hortonworks.com wrote: Hi, I'd like to raise an issue in the hopes of opening some discussion on the IRC chat later today: We see a critical requirement to support the creation of a savanna cluster with neutron networking while leveraging a private network (i.e. without the assignment of public IPs) - at least during the provisioning phase. So the current neutron solution coded in the master branch appears to be insufficient (it is dependent on the assignment of public IPs to launched instances), at least in the context of discussions we've had with users. We've been experimenting and trying to understand the viability of such an approach and have had some success establishing SSH connections over a private network using paramiko etc. So as long as there is a mechanism to ascertain the namespace associated with the given cluster/tenant (configuration? neutron client?) it appears that the modifications to the actual savanna code for the instance remote interface (the SSH client code etc) will be fairly small. The namespace selection could potentially be another field made available in the dashboard's cluster creation interface. -- J. ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [savanna] savanna-extra and hadoop-patch Matt, From the bug description: Affects Version/s:1.2.0, 2.0.3-alpha Target Version/s: 3.0.0, 2.3.0 So, it seems that Hadoop folks don't intend to include this patch into Hadoop 1.x Ruslan On Tuesday, August 27, 2013 at 2:41 PM, Matthew Farrellee wrote: Howdy Ivan, FYI, is currently targeting 1.2.0 and 2.0.3-alpha. And the code (HADOOP-8545-034.patch) appears to provide support to Hadoop 1.x HDFS, though I may be missing something. I'd suggest only adding a Swift HCFS repo only if the code is not destined to go to Apache Hadoop. +1 discuss at meeting Best, s/matt/erik/ On 08/27/2013 01:45 AM, Sergey Lukjanov wrote: Hi Erik, First of all, savanna-extra has been created exactly for such needs - to store all stuff that we need but couldn't be placed to another repos. Initially it contains elements and pre-builded jar with Swift HCFS. Now the last one has been moved to the CDN and it's a good idea to make separated project for elements. As for Swift HCFS the core attached to the HADOOP-8545 is targeted to the Hadoop 2 version and should be patched to work with Hadoop 1.X correctly. So, that's why we add it to the extra repo. It looks like that it's ok to add one more repo for Swift HCFS near the savanna at stackforge like HCFS for Gluster[0]. So, let's discuss both of the migrations at the next IRC team meeting. [0] Sincerely yours, Sergey Lukjanov Savanna Technical Lead Mirantis Inc. On Aug 27, 2013, at 5:18, Matthew Farrellee m...@redhat.com (mailto:m...@redhat.com) wrote: I didn't get back to this on Friday and it got merged this morning, so here's my feedback. The savanna-extra repository now appears to hold (a) DIB image elements as well as (b) the source for the Swift backed HCFS (Hadoop Compatible File System) implementation. If I understand this correctly, (b) is actually the patch set that is being proposed to the Apache Hadoop community. That patch set has not been accepted and is being tracked in HADOOP-8545[0], which appears stalled since July 2013. Let's break Savanna's DIB elements out of savanna-extra and into savanna-image-elements. It has a clear path forward and a good definition of scope. Let's also leave savanna-extra as a grab bag, whose only occupant is currently the Swift code. Eventually that code will need a proper home, either contributed to Apache Hadoop or broken out as its own project. Best, matt [0] ___ Re: [openstack-dev] [savanna] scalable architecture. * Installation of large Hadoop clusters (100+ nodes). Will be addressed by proposed architecture changes. * Anti-affinity support for HDFS redundancy in cloud environment * Circular dependencies - we should generate ‘/etc/hosts’ for all instances in provisioned cluster. We can’t use cloud init for this directly. There are a couple possible solutions using Heat, but none of them looks like a straightforward solution. * Level of complexity. We try to keep things as simple as possible. Adding extra layer will increase overall complexity of the solution. In addition both Savanna and Heat under active development changing lots of internals and even APIs and will require extra effort to coordinate. Here is what we’ll do: * Create a wiki page with text from this email * Create a list of requirements for Heat Once Heat fulfills all the requirements we will be able and should use Heat for VM provisionord...@gmail.com wrote: On Jul 23, 2013 12:34 PM, Sergey Lukjanov slukja.... ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org [openstack-dev] [Savanna] Savanna 0.3 features I'd like to start conversation on the subject of EDP(Elastic Data Processing) features we are going to implement in Savanna 0.3. Here is a link to etherpad: Regards, Ruslan ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] savanna version 0.3 - added UI mockups for EDP workflow Chad, I'd like to see more details about job progress on the Job list view. It should display current progress, logs, errors. For Hive, Pig and Oozie flows it would be useful to list all the jobs from the task. Something similar to would be great (without fancy graphs). Ruslan On Fri, Jul 12, 2013 at 7:14 PM, Chad Roberts crobe...@redhat.com wrote: I have added some initial UI mockups for version 0.3. Any comments are appreciated. Thanks, Chad ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [savanna]error while accessing Savanna UI Congratulations! On Jul 15, 2013, at 6:13 PM, Arindam Choudhury arin...@live.com wrote: Its solved. I started a cluster and then its working. Date: Mon, 15 Jul 2013 09:57:20 -0400 From: m...@redhat.com To: openstack-dev@lists.openstack.org CC: arin...@live.com; savanna-...@lists.launchpad.net Subject: Re: [openstack-dev] [savanna]error while accessing Savanna UI On 07/15/2013 08:45 AM, Arindam Choudhury wrote: Hi, I did: git clone cd savanna-dashboard python setup.py install pip show savannadashboard --- Name: savannadashboard Version: 0.2.rc2 Location: /usr/lib/python2.6/site-packages/savannadashboard-0.2.rc2-py2.6.egg Requires: then in /usr/share/openstack-dashboard/openstack_dashboard/settings.py HORIZON_CONFIG = { 'dashboards': ('project', 'admin', 'settings', 'savanna',), INSTALLED_APPS = ( 'openstack_dashboard', 'savannadashboard', and in /usr/share/openstack-dashboard/openstack_dashboard/local/local_settings.py SAVANNA_URL = '' But whenever I try to access savanna dashboard I get the following error in httpd error_access log: [Mon Jul 15 07:44:35 2013] [error] ERROR:django.request:Internal Server Error: /dashboard/savanna/ [Mon Jul 15 07:44:35 2013] [error] Traceback (most recent call last): [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/django/core/handlers/base.py, line 111, in get_response [Mon Jul 15 07:44:35 2013] [error] response = callback(request, *callback_args, **callback/horizon/decorators.py, line 54, in dec [Mon Jul 15 07:44:35 2013] [error] return view_func(request, *args, */django/views/generic/base.py, line 48, in view [Mon Jul 15 07:44:35 2013] [error] return self.dispatch(request, *args, **kwargs) [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/django/views/generic/base.py, line 69, in dispatch [Mon Jul 15 07:44:35 2013] [error] return handler(request, *args, **kwargs) [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/horizon/tables/views.py, line 155, in get [Mon Jul 15 07:44:35 2013] [error] handled = self.construct_tables() [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/horizon/tables/views.py, line 146, in construct_tables [Mon Jul 15 07:44:35 2013] [error] handled = self.handle_table(table) [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/horizon/tables/views.py, line 118, in handle_table [Mon Jul 15 07:44:35 2013] [error] data = self._get_data_dict() [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/horizon/tables/views.py, line 182, in _get_data_dict [Mon Jul 15 07:44:35 2013] [error] self._data = {self.table_class._meta.name: self.get_data()} [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/savannadashboard-0.2.rc2-py2.6.egg/savannadashboard/clusters/views.py, line 40, in get_data [Mon Jul 15 07:44:35 2013] [error] clusters = savanna.clusters.list() [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/savannadashboard-0.2.rc2-py2.6.egg/savannadashboard/api/clusters.py, line 74, in list [Mon Jul 15 07:44:35 2013] [error] return self._list('/clusters', 'clusters') [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/savannadashboard-0.2.rc2-py2.6.egg/savannadashboard/api/base.py, line 84, in _list [Mon Jul 15 07:44:35 2013] [error] resp = self.api.client.get(url) [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/savannadashboard-0.2.rc2-py2.6.egg/savannadashboard/api/httpclient.py, line 28, in get [Mon Jul 15 07:44:35 2013] [error] headers={'x-auth-token': self.token}) [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/requests/api.py, line 55, in get [Mon Jul 15 07:44:35 2013] [error] return request('get', url, **kwargs) [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/requests/api.py, line 44, in request [Mon Jul 15 07:44:35 2013] [error] return session.request(method=method, url=url, **kwargs) [Mon Jul 15 07:44:35 2013] [error] File /usr/lib/python2.6/site-packages/requests/sessions.py, line 335, in request [Mon Jul 15 07:44:35 2013] [error] resp = self.send(prep, **send_kwargs) [Mon Jul 15 07:44:35 2013] [error] File Re: [openstack-dev] [Savanna-all] How to run hadoop jobs Hi Arindam, There was a validation error during cluster creation. Can you send contents of cluster_create.json ? Also, please attach output of: $ http $SAVANNA_URL/images X-Auth-Token:$AUTH_TOKEN $ http $SAVANNA_URL/node-group-templates X-Auth-Token:$AUTH_TOKEN $ http $SAVANNA_URL/cluster-templates X-Auth-Token:$AUTH_TOKEN Savanna debug logs also would be helpful. Please use *openstack-dev* as a mail-list for Savanna-related questions. Just prefix the subject with [Savanna]. Thanks, Ruslan On Saturday, July 13, 2013 at 9:24 PM, Arindam Choudhury wrote: Hi, I installed savanna from the git repository. I can create cluster but only with admin, when I try to create cluster with non-admin user it gives me an error: (keystone_arindam)]# http $SAVANNA_URL/clusters X-Auth-Token:$AUTH_TOKEN cluster_create.json HTTP/1.1 500 INTERNAL SERVER ERROR Content-Length: 111 Content-Type: application/json Date: Sat, 13 Jul 2013 16:47:25 GMT { error_code: 500, error_message: Error occurred during validation, error_name: INTERNAL_SERVER_ERROR } The hadoop daemons are not started automatically so I could not run the test job. hadoop@cluster-1-master-001:/usr/share/hadoop$ hadoop jar hadoop-examples.jar pi 10 100 Exception in thread main java.io.IOException: Error opening job jar: hadoop-examples.jar at org.apache.hadoop.util.RunJar.main(RunJar.java:90) Caused by: java.io.FileNotFoundException: hadoop-examples.jar (No such file or directory) at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.init(ZipFile.java:214) at java.util.zip.ZipFile.init(ZipFile.java:144) at java.util.jar.JarFile.init(JarFile.java:153) at java.util.jar.JarFile.init(JarFile.java:90) at org.apache.hadoop.util.RunJar.main(RunJar.java:88) hadoop@cluster-1-master-001:/usr/share/hadoop$ start-all.sh () mkdir: cannot create directory `/mnt/log': Permission denied chown: cannot access `/mnt/log/hadoop/hadoop/': No such file or directory starting namenode, logging to /mnt/log/hadoop/hadoop//hadoop-hadoop-namenode-cluster-1-master-001.out /usr/sbin/hadoop-daemon.sh (): line 136: /mnt/log/hadoop/hadoop//hadoop-hadoop-namenode-cluster-1-master-001.out: No such file or directory head: cannot open `/mnt/log/hadoop/hadoop//hadoop-hadoop-namenode-cluster-1-master-001.out' for reading: No such file or directory hadoop@localhost's password: when I try to start hadoop manually, it asks for a password. How to do it? Am I missing something? Regards, Arindam -- Mailing list: Post to : savanna-...@lists.launchpad.net (mailto:savanna-...@lists.launchpad.net) Unsubscribe : More help : ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] : ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org Re: [openstack-dev] [Savanna-all] installation problem That's ok. You need to specify tenant id and provide auth token in headers. You can find detailed how-tos here btw, please use openstack-dev mail-list for Savanna-related questions. Just prefix mail subject with [Savanna]. Ruslan On Friday, July 12, 2013 at 1:59 PM, Arindam Choudhury wrote: Hi, The new document works great except this command $ sudo pip install savannadashboard. I changed the savanna config to: [DEFAULT] # REST API config port=8386 allow_cluster_ops=true # Address and credentials that will be used to check auth tokens os_auth_host=192.168.122.11 os_auth_port=35357 os_admin_username=admin os_admin_password=openstack os_admin_tenant_name=admin # (Optional) Name of log file to output to. If not set, # logging will go to stdout. (string value) log_file=/home/arindam/savanna.log [cluster_node] # An existing user on Hadoop image (string value) #username=root # User's password (string value) #password=swordfish # When set to false, Savanna uses only internal IP of VMs. # When set to true, Savanna expects OpenStack to auto-assign # floating IPs to cluster nodes. Internal IPs will be used for # inter-cluster communication, while floating ones will be # used by Savanna to configure nodes. Also floating IPs will # be exposed in service URLs (boolean value) use_floating_ips=true [sqlalchemy] # URL for sqlalchemy database (string value) database_uri=sqlite:tmp/savanna-server.db and I changed config of dashboard as specified. but I can not access the savanna dashboard: [arindam@sl-3 ~]$ curl html head title401 Unauthorized/title /head body h1401 Unauthorized/h1 This server could not verify that you are authorized to access the document you requested. Either you supplied the wrong credentials (e.g., bad password), or your browser does not understand how to supply the credentials required.br /br / Authentication required /body /html From: arin...@live.com (mailto:arin...@live.com) To: rkamaldi...@mirantis.com (mailto:rkamaldi...@mirantis.com) Subject: RE: [Savanna-all] installation problem Date: Fri, 12 Jul 2013 11:33:24 +0200 Thanks. Date: Fri, 12 Jul 2013 13:25:45 +0400 From: rkamaldi...@mirantis.com (mailto:rkamaldi...@mirantis.com) To: arin...@live.com (mailto:arin...@live.com) CC: openstack-dev@lists.openstack.org (mailto:openstack-dev@lists.openstack.org); savanna-...@lists.launchpad.net (mailto:savanna-...@lists.launchpad.net) Subject: Re: : -- Mailing list: Post to : savanna-...@lists.launchpad.net (mailto:savanna-...@lists.launchpad.net) Unsubscribe : More help : ___ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org
https://www.mail-archive.com/search?l=openstack-dev%40lists.openstack.org&q=from:%22Ruslan+Kamaldinov%22&o=newest&f=1
CC-MAIN-2019-43
refinedweb
13,738
55.44
you using st2 or st3? Blocks are good for rudimentary scoped var renaming too scoped def find_block_starts(view, block_tokens): regex = re.compile(block_tokens if block_tokens else BLOCKERS) return [r for r in view.find_by_selector('keyword,storage') if view.find(r'\S', view.line(r).begin()).begin() == r.begin() and regex.match(view.substr(r)) ] Basically by finding block starting tokens, bisecting the closest to each selection and then using some indentation comparing routines, to find extents of a block. Used a bit of scope awareness etc. Things like that worked better in ST 1 & 2 when the api was faster and you could do a lot of pt by pt stuff. pt Will see if I can dig it up and port it @wuub ST3 Great! Installation instructions: 1) Clone this repo into your Preferences -> Browse Packages directory.github.com/wuub/SublimeEyeball Preferences -> Browse Packages 2) make sure that at least one pythons have eyeball installed (pip install eyeball should work).Pick the one you code for, or both if you use py2 and py3. Eyeball relies on ast module and it can only parse the same version of python as itself, so py27 might not be able to understand all of python3 and vice versa.github.com/wuub/SublimeEyeball/ ... 20(Windows.sublime-settings 3) Ctrl+Shift+C to select block of code, repeat to cycle up. Notes: - STILL WiP! this is a sneak peek, early beta, preview, because sfranky asked nicely - plugin launches external python each and every time. On most machines it is fast enough (crazy fast on my workstation) and there is no plan to change this behaviour at least for now. - as said before external python dependency is caused by ast being tied to the specific python version, also I have some other plans for this library/plugin that would be difficult to code using internal sublime python - eventually I plan to include eyeball library within this plugin, but since PackageControl / github zipballs don't support git submodules, I need to think it through first I just saw this !! great! but... it's not working yet!I get this error in the console:SublimeEyeball c:\Python32\pythonw.exe No JSON object could be decoded(I have python 3.2 installed, not python 3.3, so i just changed the line in your file) 1). c:\python32\python.exe -m eyeball Edit: I did not check for py3.2 compatibility before, but it doesn't seem to be a problem here travis-ci.org/wuub/eyeball hmm that previous post i made was completely wrong, I m still looking into it.. eeer ok found the problem. It wasn't syntactically correct Works perfect now !! many thanks !!..
https://forum.sublimetext.com/t/fast-way-to-select-current-function-in-python/6822/14
CC-MAIN-2017-22
refinedweb
449
65.62
Define. Write an attribute. Calls to attribute() MUST follow a call to startTag() immediately. If there is no prefix defined for the given namespace, a prefix will be defined automatically. If namespace is null or empty string no namespace prefix is printed but just name. Finish writing. All unclosed start tags will be closed and output will be flushed. After calling this method no more output can be serialized until next call to setOutput() Return the current value of the feature with given name. NOTE: unknown properties are always returned as null Returns the name of the current element as set by startTag(). It can only be null before first call to startTag() or when last endTag() is called to close first startTag(). Returns the namespace URI of the current element as set by startTag(). NOTE: that means in particular that: Look up the value of a property. The property name is any fully-qualified URI. I NOTE: unknown properties are Set feature identified by name (recommended to be URI for uniqueness). Some well known optional features are defined in. If feature is not recognized or can not be set then IllegalStateException MUST be thrown. Set the output to the given writer. WARNING no information about encoding is available! Set to use binary output stream with given encoding. the value of a property. (the property name is recommended to be URI for uniqueness). Some well known optional properties are defined in. If property is not recognized or can not be set then IllegalStateException MUST be thrown. Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null) This method can only be called just after setOutput.. Writes text, where special XML chars are escaped automatically Writes text, where special XML chars are escaped automatically
http://developer.android.com/reference/org/xmlpull/v1/XmlSerializer.html
CC-MAIN-2014-52
refinedweb
299
58.28
27 August 2010 15:01 [Source: ICIS news] WASHINGTON (ICIS)--The Commerce Department on Friday said that US gross domestic production (GDP) in the second quarter was less than first estimated, revising the Q2 economic measure down to a 1.6% annual growth rate from the original 2.4%. The 1.6% GDP rate for the second quarter followed a far more robust 3.7% expansion reported for the first quarter and the strong 5.6% growth rate recorded in the fourth quarter last year when the economic recovery was getting started. The downward revision for second quarter results confirm what other economic indicators, the Federal Reserve and White House advisors have suggested - that the recovery is slowing significantly. The department said the 0.8-point reduction in second quarter GDP from the initial estimate of 2.4% on 30 July was due to more recent data showing a sharp acceleration in US imports and a decline in private inventory investment. Those negative factors were only partly offset by some gains in the housing sector and in commercial property investments, the department said. In April, the ?xml:namespace> The department said that increased spending by federal, state and local governments during the second quarter also was insufficient to overcome downward pressure exerted by the decline in inventory investment and the sharp rise in imports. News that the recovery cooled even further than first indicated in the second quarter followed earlier reports this week that both existing home sales and new home sales have fallen sharply in the first month of the third quarter.
http://www.icis.com/Articles/2010/08/27/9389008/q2-gdp-revised-downward-confirming-shaky-recovery.html
CC-MAIN-2014-41
refinedweb
263
51.78
Re: [docbook-apps] Endnotes in PDF? That colon is in the template that starts with this: between "label.markup" and "title.markup" Bob Stayton b...@sagehill.net On 12/24/2021 6:25 PM, M. Downing Roberts wrote: Hi Bob, I got your endnotes template working — really helpful! For anybody else who tries this Re: [docbook-apps] List of figures appears empty in PDF file This is odd. Your markup looks fine. I cannot figure out where that WARNING message is coming from. It doesn't seem to exist in the stock stylesheets. I cannot even find the word "Unknown" in any error message generated by the stylesheet. Are you using a customization layer? Bob Re: [docbook-apps] Endnotes in PDF? Hi, I used the same style of endnotes in a book that I wrote with DocBook, so I have attached the stylesheet module that I wrote to do that. You might need to make some adjustments to fit it into your customization layer. Bob Stayton b...@sagehill.net On 12/21/2021 7:02 AM, M. Downing Re: [docbook-apps] Creating Styles for an Attribute the outer color. Bob Stayton b...@sagehill.net On 9/13/2021 11:41 PM, David Cramer wrote: On 9/11/21 3:10 AM, Bob Stayton wrote: It's main limitation is that it only is applied to text nodes in your XML document, and so would not color generated text (like "Note" or xrefs) or any Re: [docbook-apps] Respecting table formatting in docbook source while producing html or epub Hi Esteban, Check out the section on table borders in my online book and see if that works: Bob Stayton b...@sagehill.net On 8/19/2021 3:13 AM, Esteban Zimanyi wrote: A table in my source DocBook xml document is defined as follows Variables Re: [docbook-apps] Image selection based on type using dbtoepub EPUB standard. Bob Stayton b...@sagehill.net On 8/17/2021 6:10 AM, Esteban Zimanyi wrote: I am using docbook, xsltproc, dblatex, and dbtoepub (epub not epub3) with a standard Ubuntu distribution < Re: [docbook-apps] Header and footer alignment for center cell Let me know if any of this requires further explanation. Bob Stayton b...@sagehill.net On 7/19/2021 12:39 PM, Kevin Dunn wrote: In double-sided xsl-fo, how can you control text-align for the center cell of the header or footer table (usually chapter or sec Re: [docbook-apps] Reminder -- how to unsubscribe You should be able to unsubscribe with this link: Bob Stayton b...@sagehill.net On 7/6/2021 8:14 AM, Kathleen Mattson wrote: Apologies for spamming the list with this - I have long since lost track of how to unsubscribe to this list. *Can someone Re: [docbook-apps] Lists of Tables, Figures, etc in xsl-fo You can rearrange that template to call "page-sequence" just once and put all the TOC content into its single "content" param. You'll still want to test each one to see if it should be included. If you want to force page breaks between LOTs, you can add: before each one. Re: [docbook-apps] insert.link.page.number in xsl stylesheets yle attribute): .;> Then you would get your style if you specify , otherwise you get the default. Bob Stayton b...@sagehill.net On 6/14/2021 8:27 PM, Kevin Dunn wrote: Putting "'yes'" (single in double quotes) Re: [docbook-apps] insert.link.page.number in xsl stylesheets I think the problem is in the param statement, where the string yes is being interpreted as an element name. (I added single quotes around the word yes). Bob Stayton b...@sagehill.net On 6/14/2021 12:05 PM, Kevin Dunn wrote: I'm customizing xrefs to render page numbers in pdf files Re: [docbook-apps] AH Formatter initial-letters Drop Cap Customization Hi Kevin, For your next stop, see Customizing cross references <>in my online book. Bob Stayton b...@sagehill.net On 6/13/2021 8:37 PM, Kevin Dunn wrote: The learning curve for transitioning from dsssl to xsl has not been as steep as Re: [docbook-apps] acronym and small caps case, you will see that font-variant is not supported yet. XEP may require some addtional configuration in the XEP configuration file to trigger the selection of a small caps font. Check the XEP documentation. Bob Stayton b...@sagehill.net On 6/12/2021 12:54 PM, Kevin Dunn wrote: Apo Re: [docbook-apps] Thumbnails? your logo inserted by any of those elements in your content, but not if the stylesheet generates a reference to the image directly. Bob Stayton b...@sagehill.net On 5/12/2021 3:46 AM, Michel van den Burg wrote: That’s an interesting parameter! Is there a way to apply this to some images, b Re: [docbook-apps] Thumbnails? irect link to the image file, which would show it unscaled (or full scale) in the browser window. Bob Stayton b...@sagehill.net On 5/7/2021 12:27 AM, Dave Pawson wrote: I've a set of photographs of document pages. With small text if the page is zoomed to make the text readable the main page text is . Re: [docbook-apps] Wrap some elements in a titlepage spec file? That question would need to be directed at Norm Walsh, the creator of the titlepage system. Not sure he would remember why. He wrote the original code when XSL was new. Bob Stayton b...@sagehill.net On 4/30/2021 3:25 AM, Tony Graham wrote: On 29/04/2021 21:10, Bob Stayton wrote Re: [docbook-apps] Wrap some elements in a titlepage spec file? the XSL I need in custom templates "book.titlepage.recto" and "book.titlepage.verso" to completely override the generated templates. Bob Stayton b...@sagehill.net On 4/29/2021 8:52 AM, Tony Graham wrote: Is is possible to wrap two or more elements inside a to generate Re: [docbook-apps] Removing italics from MathML The standard DocBook XSL stylesheet does not add the italics property to equations. You might ask on the Oxygen XML mailing list. Bob Stayton b...@sagehill.net On 4/18/2021 8:29 AM, Philo Calhoun wrote: Is there an easy way to change the docbook>pdf export in Oxygen XML Editor Re: [docbook-apps] Hypenation in titles ; to refer to titles, subtitles, and any other info elements that should appear at the beginning of a DocBook element. For your case, you will want to edit the spec file and add a hyphenate="false" property to the and elements you want to turn off, and then generate the titlepage XSL f Re: [docbook-apps] Thanks re docbook to ePub3 -element-mods.xsl files there is a template that starts with that handles the conversion of hard attributes to styles. The culprit is this line in that template: that needs to be changed to: to remove the exception for img elements. Bob Stayton b...@sagehill.net On 3/25/2021 9:21 PM, Bob Re: [docbook-apps] Thanks re docbook to ePub3 @style attribute by processing the generated img element in mode="convert.to.style". So I'm not yet clear on is where that process is going wrong such that you are seeing @width in your output. I'll need to investigate more. Bob Stayton b...@sagehill.net On 3/25/2021 4:46 AM, R Re: [docbook-apps] Pdf double endnote issue for generated text because it could be very long. The stylesheet recognizes that problem and issues this warning: WARNING: xref to para id="Ref1" has no generated text. Trying its ancestor elements. but then it doesn't seem to handle the attempt properly in this case. Bob Re: [docbook-apps] Figure title wrapping y. That information is under "index, columns" in my book's index. I should mention that using Saxon HE 10.3 might create compatibility issues because the DocBook XSL stylesheets are written in XSLT 1.0. I generally recommend using Saxon 6.5.5 to avoid such issues. Bob Stayton b...@ Re: [docbook-apps] transform td role to td class in HTML-output ate my book with all the changes that have been made to DocBook XSL. Bob Stayton b...@sagehill.net On 9/15/2020 5:21 AM, Peter Desjardins wrote: Hi, Michel! I have some templates that use class.mode in my customization. I can confirm that this XSL controls the class attribute in output HTML: Re: [docbook-apps] Continued page numbering in the frontmatter continues from the previous page-sequence. The original template is in fo/pagesetup.xsl. Bob Stayton b...@sagehill.net On 8/23/2020 1:12 PM, Bernhard Kleine wrote: Hi, I have this structure in my book.; schematypens=" Re: [docbook-apps] When double-sided print, how to avoid chapter starting on odd pages? parameters and changes that need to be made. It does not cover the thumb index because that's your own customization. Bob Stayton b...@sagehill.net On 8/15/2020 8:39 AM, Bernhard Kleine wrote: Am 14.08.2020 um 20:38 schrieb Tony Re: [docbook-apps] gentext.template.exists -- possible bug I'm inclined to think that is a bug, because there are perhaps legitimate reasons for the text attribute of a particular gentext template to be empty in some languages. Bob Stayton b...@sagehill.net On 8/11/2020 6:06 PM, Richard Hamilton wrote: The template gentext.template.exists in the 1.0 [docbook-apps] regarding olinks After the recent discussion of olinks, I came across this paper I wrote for a conference in 2005 describing olinks, titled "Linking Outside the Box". It might be of interest to those contemplating using olinks. -- Bob Re: [docbook-apps] Validating against Schematron I use Oxygen XML. Bob Stayton b...@sagehill.net On 7/28/2020 2:55 PM, Richard Hamilton wrote: This is a question for the group. What do you currently use for validating DocBook agains both RelaxNG and Schematron? I’ve been looking around and downloading and trying some 10-to-15 year old Re: [docbook-apps] target.db cannot be generated with Saxon? The short answer is: The DocBook XSL stylesheets are written in XSL 1, and work best with Saxon 6.5.5. Bob Stayton b...@sagehill.net On 7/12/2020 11:24 PM, Mark Giffin wrote: I'm messing with olinks and I'm trying to generate my target.db files from the command line (Windows 10) with Saxon Re: [docbook-apps] using olinks everywhere? nto the FO file for that purpose. But they don't seem to actually work in the PDF. There is an open bug report on this at the Apache site: Bob Stayton b...@sagehill.net On 7/10/2020 10:30 AM, Bob Stayton wrote: The problem with FOP, includi Re: [docbook-apps] using olinks everywhere? PDF. Bob Stayton b...@sagehill.net On 7/10/2020 8:00 AM, Barton Wright wrote: Thanks, Tony. As I said, PDF-fu. You work for Antenna House, Masters of the PDF Universe. Case, rested. But, the question for us is whether the DocBook XSL supports generating these links, and does so without Re: [docbook-apps] Finding which template, formatting part of a ToC ion of html/autotoc.xsl have a line like this: If so, then you can replace , which might solve some of your formatting problem. Bob Stayton b...@sagehill.net On 6/30/2020 10:38 AM, Jennifer Moore wrote: Hi folks On a hunt for which template I need to tweak for a table of cont Re: [docbook-apps] docbook-xsl URL mess Yes, this needs to be fixed. I'm cleaning up pull requests and issues and will be making a new release soon. Could you please file an issue on the DocBook XSL github with your recommended fix: Bob Stayton b...@sagehill.net On 6/8/2020 12:02 Re: [docbook-apps] javascript file in docbook generated html If you just want to change the @type attribute value for all scripts, there's a param for that: Bob Stayton b...@sagehill.net On 4/18/2020 5:01 AM, Niels Müller Larsen wrote: Hi all You may customize docbook Re: [docbook-apps] Section[1] only in toc t; template does not process any subsections. Bob Stayton b...@sagehill.net On 4/1/2020 2:05 AM, Peter Fleck wrote: Yes, sorry FO, I know I can use a manual.toc for HTML. Thanks, Peter On Tue, 31 Mar 2020 at 23:27, Bob Stayton <mailto:b...@sagehill.net>> wrote: You didn't menti Re: [docbook-apps] Section[1] only in toc You didn't mention whether this was for FO or HTML type of output. Bob Stayton b...@sagehill.net On 3/31/2020 2:08 PM, Peter Fleck wrote: I have an abnormal use case. The source file is a book with many articles, however the TOC is to be first level sections of each article Re: [docbook-apps] changing from xsltproc to saxon . In most cases, that is nothing, but there are some chunking configurations where some things are not chunked and they would go to standard output. Bob Stayton b...@sagehill.net On 3/29/2020 5:59 AM, Niels Müller Larsen wrote: Hi Bob You have done it again! You once helped me with missing Re: [docbook-apps] changing from xsltproc to saxon Re: [docbook-apps] changing from xsltproc to saxon is mapping the stylesheet URL to that file. Bob Stayton b...@sagehill.net On 3/28/2020 11:14 AM, Niels Müller Larsen wrote: When producing html output from my docbook I use the following fragment of a Makefile: html: rm -rf site mkdir site cp css Re: [docbook-apps] Converting Docbook epub to Kindle shows warnings how to use solar energy to eliminate poverty in the world. Bob Stayton b...@sagehill.net On 3/19/2020 9:16 PM, Robert Nagle wrote: This is very interesting to me. I have tried for two projects to generate indexes that would work on Kindle. The indexterm content had both a primary Re: [docbook-apps] Elements for presenting multiple language variants in a code example docbookxsl/HtmlCustomEx.html#CustomClassValues Let me know if this isn't sufficient for your needs. Bob Stayton b...@sagehill.net On 2/24/2020 8:13 PM, Peter Desjardins wrote: I'm trying to design a set of elements that I can render as a single code example with multiple programming language var Re: [docbook-apps] TOC and dialogue/drama/poetry included. Then each entry's element is processed in mode="toc" to format the listing, so look at the other mode="toc" templates for examples to create a new template in that mode for poetry. Bob Stayton b...@sagehill.net On 2/17/2020 7:07 AM, Pc Thoms wrote: The elements d Re: [docbook-apps] xsltproc does not render : 1 Bob Stayton b...@sagehill.net On 11/20/2019 9:16 AM, Shlomi Fish wrote: hi all! with the attached file and the command: xsltproc --nonet my-real-person-fan-fiction.docbook5.xml | less I am not seeing any tags. See Re: [docbook-apps] java.lang.NoClassDefFoundError in docbook build I don't see the resolver.jar in your classpath, which is used to resolve paths using an XML catalog file. Bob Stayton b...@sagehill.net On 10/24/2019 8:00 AM, Rob Flynn wrote: java.lang.NoClassDefFoundError in docbook build Hi all In a build that used to work, a ton of Linux patches were Re: [docbook-apps] section "label" attribute not producing label ction.autolabel|/ parameter to 1". Stylesheet parameters can be set on the command line or in an XSL customization layer as described elsewhere in the book. Once section numbering is turned on, the @label value on a sect1 element will override the default number. Bob Stayton b...@sagehill.net O Re: [docbook-apps] html table, create wrapper div with class ... If you need further control, you'll have to customize some of the internal table templates. Bob Stayton b...@sagehill.net On 8/29/2019 6:27 AM, Tim Arnold wrote: Hi, I'm converting DocBook 5 to html (docbook-xsl-1.79.2) with a customization layer. I now need to wrap my table e Re: [docbook-apps] Cannot get titlepage image to be full page width/height page margins are. I didn't test that, so let us know if it works. Bob Stayton b...@sagehill.net On 8/26/2019 12:26 PM, Gabriela Simonka wrote: Hello! I am trying to create a PDF file of an article with an image as the title page, but I keep getting a compilation error "[error] no Re: [docbook-apps] Creating Topics from Book and xi:include Hi Michael, You can achieve what you want by moving the code samples elsewhere when you make topics. An Xinclude that does not resolve is left as an xi:include element in the output of the parser. Then move the code files back. Bob Stayton Sagehill Enterprises b...@sagehill.net On 5/8/2019 Re: [docbook-apps] nroff output isn't aware of ordered list numeration type that specifies the number format for such a list. I'll file a bug report, but I can't say when it will get fixed. Bob Stayton Sagehill Enterprises b...@sagehill.net On 5/7/2019 3:16 PM, Emily Shaffer wrote: Hiya, I've run into an issue where we are seeing output from AsciiDoc->nroff produc [docbook-apps] proposed additions to DocBook for programming languages as originally proposed. Here is a link to the proposal: Your review and comments will help the DocBook TC in their deliberations about this proposal. Thank you for your time. -- Bob Stayton Sagehill Enterprises b...@sagehill.net Re: [docbook-apps] CreationDate in PDF files' metadata Hi Filippo, Information about embedding metadata in fo output which goes to the PDF is found here: The data can be changed by customizing this template found in fo/fop1.xsl: Bob Stayton Sagehill Enterprises b...@sagehill.net On 3/28 Re: [docbook-apps] Implementing support for filterin/filterout in assemblies ng. Bob Stayton Sagehill Enterprises b...@sagehill.net On 3/22/2019 1:04 PM, Peter Desjardins wrote: Hi! I need to do some conditional processing of a book that I'm assembling from an assembly structure. A specific audience needs a version o Re: [docbook-apps] docbook-xsl-nons-snapshot.zip (db5). docbook-xslt1-db4-1.80.1 - no namespace version for DocBook 4 (db4). The xslt1 part distinguishes them from the stylesheets written in xslt 2. Bob Stayton Sagehill Enterprises b...@sagehill.net On 3/11/2019 7:51 PM, Robert Nagle wrote: Hi, there, I'm going to try a new project using Docbook Re: [docbook-apps] ERROR - Invalid property value encountered in font-size="NaN": If body.font.master is set to '10pt' instead of '10', the stylesheet treats it as Not a Number (NaN) and generates that error. Bob Stayton Sagehill Enterprises b...@sagehill.net On 3/10/2019 10:34 AM, Bernhard Kleine wrote: Since today I encounter an error while transforming my book with the standard Re: [docbook-apps] Titlepage image the generated templates in your stylesheet customization layer. 4. Modify templates in |mode="titlepage.mode"| and more specific modes to customize how individual elements are handled. Bob Stayton Sagehill Enterprises b...@sagehill.net On 2/18/2019 11:19 AM, Bernhard Kl Re: [docbook-apps] Titlepage image Nothing follows. Did you omit an attachment? Bob Stayton Sagehill Enterprises b...@sagehill.net On 2/18/2019 12:54 AM, Bernhard Kleine wrote: Hi, I added the following (from docbook xsl book p. 187) to my customization file in oxygen 20.1 but the image does not show up. What is wrong Re: [docbook-apps] Docbook To Man Pages Convertion: Using Oxygen 20.1 with Saxon 6.5.5 - Missing Titles More details needed. Do those refsect1 elements contain title elements? Bob Stayton Sagehill Enterprises b...@sagehill.net On 2/15/2019 5:07 PM, Vivek Ghosh wrote: Hi, I noticed that converted man pages are missing < refsynopsisdiv> and < refsect1 > titles. For example Re: [docbook-apps] I have paragraphs that contains MarkDown. Is there a way in the XSLT to process them as markdown? The broken URL resolves to: but the book is at: Bob Stayton Sagehill Enterprises b...@sagehill.net On 2/16/2019 12:19 PM, Ron Catterall wrote: Hi Bob Re: [docbook-apps] I have paragraphs that contains MarkDown. Is there a way in the XSLT to process them as markdown? This is a great idea, but I must mention that we are in the process of updating that page about transforms in The Definitive Guide. There are several corrections that need to be made to the descriptions of how the attributes are to be used. Bob Stayton Sagehill Enterprises b...@sagehill.net Re: [docbook-apps] Footnote marks missing When I run into a problem like this, I start commenting out templates in my customization until I find the one causing the problem, then examine that one in more detail. If you find the culprit but cannot see why it is wrong, post it here. Bob Stayton Sagehill Enterprises b...@sagehill.net Re: [docbook-apps] Footnote marks missing rk, so I'm not sure why it is not working for you. Bob Stayton Sagehill Enterprises b...@sagehill.net On 2/8/2019 8:18 AM, Bernhard Kleine wrote: die Schmetterlinge Die Begriffe Falter und Schmetterling sind meines Wissens gleichbedeutend und werden in glei Re: [docbook-apps] Footnote marks missing That's odd. My footnotes are numbered, not lettered. How is it that your footnotes are lettered? Can you supply a sample of the markup you used? Bob Stayton Sagehill Enterprises b...@sagehill.net On 2/8/2019 4:49 AM, Bernhard Kleine wrote: In my book I noticed that footnote marks Re: [docbook-apps] Re: Font for the info part different than for the rest and the colophon it. Bob Stayton Sagehill Enterprises b...@sagehill.net On 1/29/2019 5:46 AM, Bernhard Kleine wrote: The culprit is in the fo visible: Copyright© 2019 Bernhard Kleine the serif in front of Alegreya. Am 29.01.2019 um 14:01 sch Re: [docbook-apps] Chapter title smaller than section title in the PDF. Customization of titles for print is covered in this section of my book: Bob Stayton Sagehill Enterprises b...@sagehill.net On 12/19/2018 3:02 AM, Bernhard Kleine wrote: Without changing anything to do with chapter and section titles Re: [docbook-apps] Adding new element to the scheme Hi Tony, That does work. Thanks for pointing that out. Bob Stayton Sagehill Enterprises b...@sagehill.net On 12/11/2018 11:11 AM, Tony Graham wrote: On 11/12/2018 05:40, Bob Stayton wrote: ... ... Also, the nodeset approach won't work for FO output because the informaltable Re: [docbook-apps] Adding new element to the scheme stylesheet approach. Bob Stayton Sagehill Enterprises b...@sagehill.net On 12/10/2018 5:44 AM, Ilan Finci wrote: Hi I’m new to docbook and XSLT, and tried to find the answer among the different books/websites and failed, so looking up for your help (pointers to the right place will be good as well Re: [docbook-apps] page numbers are not right aligned ' generates an element that produces the dot leaders. Bob Stayton Sagehill Enterprises b...@sagehill.net On 11/26/2018 12:19 AM, Bernhard Kleine wrote: Hi Bob, Unfortunately the case you cite is not applicable in my example. I looked for the spacing e.g. for this line: Häufige und Re: [docbook-apps] page numbers are not right aligned is caused by whitespace around the title. Your misaligned entries all seem to have short dot leaders. But it seems the fop algorithm has a problem with right alignments with dot leaders. Bob Stayton Sagehill Enterprises b...@sagehill.net On 11/25/2018 10:03 AM, Bernhard Kleine wrote: As can Re: [docbook-apps] Element title encountered in qandaentry Sorry, I should have tested that before posting. Indeed, it is more complicated because the qandaset is formatted with a layout table in HTML output. I think that template will need to be rewritten, so I don't have a quick fix for you. Bob Stayton Sagehill Enterprises b...@sagehill.net Re: [docbook-apps] Element title encountered in qandaentry : That will create a nested div with attribute class="title" inside the div for qandaentry, and then you can add a new CSS entry to your stylesheet to format it. Bob Stayton Sagehill Enterprises b...@sagehill.net On 11/21/2018 4:31 PM, ttl wrote: Hello, I have a title element as f Re: [docbook-apps] pubwork does not include a thesis values of the class attribute, otherclass= is another permitted attribute, and "somethingnew" is an arbitrary string. However, citetitle does not have this mechanism, so the role attribute would have to be used. Bob Stayton Sagehill Enterprises b...@sagehill.net On 11/19/2018 3:40 Re: [docbook-apps] Title of the List of Table Any generated text should be found in the locale files in the "common" directory of the stylesheet distribution, one for each locale. Customization of such content is described here: The key attribute for that item is "List Re: [docbook-apps] EPUB: suppress one chapter from the navigation document -- how? attribute: The context of toc.line is the current docbook element being processed (such as section), so you can match on its xml:id or some other attribute like role. Bob Stayton Sagehill Enterprises b...@sagehill.net On 10/31/2018 9:10 PM, Robert Nagle wrote: I am making an Re: [docbook-apps] danger admonition Yes, danger will be added to DocBook 5.2. There is not yet a scheduled release date for 5.2. There is a recent beta release of 5.2 on docbook.org if you want to try it out. Bob Stayton Sagehill Enterprises b...@sagehill.net On 10/26/2018 1:55 AM, Matteo Re: [docbook-apps] label separator? Hi Tim, That separator is supplied by a stylesheet parameter named 'xref.label-title.separator', whose default value is ": " Bob Stayton Sagehill Enterprises b...@sagehill.net On 10/24/20 Re: [docbook-apps] New to this list, with an XSL question... Strange. What happens when you change the first xsl:import statement to point to your local /usr/share/xml/... path to docbook.xsl instead of the http URL? Bob Stayton Sagehill Enterprises b...@sagehill.net On 10/24/2018 12:39 PM, Filippo Rusconi wrote: Greetings, Bob, On Wed, Oct 24 Re: [docbook-apps] New to this list, with an XSL question... not have the same name. Bob Stayton Sagehill Enterprises b...@sagehill.net On 10/24/2018 9:44 AM, Filippo Rusconi wrote: Greetings, Bob, On Wed, Oct 24, 2018 at 08:42:17AM -0700, Bob Stayton wrote: I'm not sure what the problem is here, as your process looks correct. Can you compare your generated Re: [docbook-apps] New to this list, with an XSL question... I'm not sure what the problem is here, as your process looks correct. Can you compare your generated titlepage.xsl to the original fo/titlepage.templates.xsl that is included with the distribution? They should be equivalent, modulo whitespace variations. Bob Stayton Sagehill Enterprises b Re: [docbook-apps] Combining para role templates Hi Peter, As you discovered, XSLT selects only one template for each match, even when more than one applies. You'll need to write a more general template to handle all your permutations, something like this: red xx-small Bob Stayton Sagehill [docbook-apps] continue support for xhtml-1_1 and epub version 2? 2011, seven years ago. The "epub3" directory uses xhtml5, not xhtml-1_1. Are people still generating epub documents in version 2, or has everyone moved on to version 3? Would it create hardship to not include the epub and xhtml-1_1 directories in forthcoming stylesheet distributions? Re: [docbook-apps] How to make chemical structure automatically numbered ] and one to match on figure[@condition = 'chem']. In each, you have elements to match the condition for counting. One further complication is the word "Figure" in your language would be applied to all of them. To change that will require further customization. Bob Stayton Sa Re: [docbook-apps] seek best practice using xinclude and imagedata/fileref . Bob Stayton Sagehill Enterprises b...@sagehill.net On 10/6/2018 11:37 PM, Dave Pawson wrote: You might like a level of indirection provided by xml catalog. Particularly if you think you may modify the layout as the system develops? HTH On Sun Re: [docbook-apps] Figure legends moving with the title-> How to indent caption on both sides by e.g. 2cm low easier customization. I'll add that for the next stylesheet release. Bob Stayton Sagehill Enterprises b...@sagehill.net On 10/5/2018 7:44 AM, Bernhard Kleine wrote: I had tomatoes over my eyes: I have not seen the caption tag. Now the question is : How to indent all the captions by let Re: [docbook-apps] Suppressing blank pages and double-sided printing - header and footer problem Hi Felix, Did you customize the page-master to comment out the use of page-position="first" as described in that archive posting? It is hard to diagnose the problem without seeing your XSL customization. If you don't want to post it you can send it directly to me. Bob Stayto Re: [docbook-apps] [oXygen-user] Pagenumbers in crossref with my own style rk for you. Bob Stayton Sagehill Enterprises b...@sagehill.net On 9/26/2018 1:45 PM, Bernhard Kleine wrote:;"/>;> Re: [docbook-apps] [oXygen-user] Pagenumbers in crossref with my own style;> Bob Stayton Sagehill Enterprises b...@sagehill.net On 9/26/2018 10:27 AM, Bernhard Kleine wrote: I have the following xml example Re: [docbook-apps] Would like to add Copyright info to footer content layer and rearrange it as needed. The call to the template named "gentext" generates the word "Copyright" in the appropriate language, and the call to the template named "dingbat" generates the copyright symbol. Bob Stayton Sagehill Enterprises b...@sagehill Re: [docbook-apps] Would like to add Copyright info to footer content k-description.html;>PDF version available If you are using DocBook 5 then you will need to add the namespace prefix to the element names. Bob Stayton Sagehill Enterprises b...@sagehill.net On 8/14/2018 8:37 AM, Peter Desjardins wrote: Hi, Gabri Re: [docbook-apps] Can't get olink to generate a working link between books in a set PDF file does not need a baseuri. Bob Stayton Sagehill Enterprises b...@sagehill.net On 8/10/2018 1:54 PM, Bob McIlvride wrote: Hi Bob, Thank you for the suggestion. This is unfamiliar territory for me, and I seem to have run into an obstacle implementing this suggestion: "So you ne Re: [docbook-apps] Can't get olink to generate a working link between books in a set stylesheet to generate separate data files for PDF output. Those files with different names would be referenced by the PDF version of the target database document. Bob Stayton Sagehill Enterprises b...@sagehill.net On 8/7/2018 12:07 PM, Bob McIlvride wrote: Hi Bob, That would make sense. I’ve Re: [docbook-apps] Can't get olink to generate a working link between books in a set as a sequence of document elements without a sitemap and without @baseuri's, which should then form relative links. etc. I haven't tested this, but I think it will work. Let me know if it doesn't. Bob Bob Stayton Sagehill Enterprises b Re: [docbook-apps] Can't get olink to generate a working link between books in a set ? Bob Stayton Sagehill Enterprises b...@sagehill.net On 8/1/2018 12:25 PM, Bob McIlvride wrote: Dear friends, After almost two years being moved to other tasks, I now have an opportunity to complete this project. The HTML output is working fine, but the issue now is PDF (FO) output. Here's Re: [docbook-apps] R: [docbook-apps] R: [docbook-apps] footnote - nested tables number properly as in my test. Bob Stayton Sagehill Enterprises b...@sagehill.net On 6/29/2018 2:10 AM, Matteo Regazzo wrote: Great Bob, thank you very much, it works! J While making some tests I’ve found 2 minor problems: -if I have to include more than one table in more than one and I Re: [docbook-apps] typo + Missing files? 1.79.1 Hi Dave, Yes, param.xsl is built prior to making a distribution. So you are looking at the source directories, not the distribution. As I said, you can download the already-built distribution from here: Bob Stayton Re: [docbook-apps] Watermark Images content. It might be possible to declare a full size image in one of those areas but extending out side the designated area, but I'm not sure if it would be under or over the page content. Bob Stayton Sagehill Enterprises b...@sagehill.net On 6/29/2018 8:56 PM, Otto Hirr wrote: Greetings, I Re: [docbook-apps] Catching up. ://docbook.org/xml/5.1/ Re: [docbook-apps] Re: Catching up. The build doc on Github is still in development, and it will explain ~/.xmlc when it is done. In the mean time, here is a link to the sample file: Bob Stayton Sagehill Enterprises b...@sagehill.net On 6/30/2018 7:03 AM Re: [docbook-apps] Catching up. 1.79.1. Bob Stayton Sagehill Enterprises b... Re: [docbook-apps] R: [docbook-apps] footnote - nested tables e main table, not the nested table, but at least it won't be duplicated. If this doesn't suit you, then you'll need to create an XSL customization layer to customize some XSL templates to handle the footnote in the nested table. Bob Stayton Sagehill Enterprises b...@sagehill.net On 6/27/
https://www.mail-archive.com/search?l=docbook-apps%40lists.oasis-open.org&q=from:%22Bob+Stayton%22&o=newest
CC-MAIN-2022-27
refinedweb
5,695
65.83
Hi all, lately, there were discussions on the cocoon-users list about how to interconnect HTML forms and XML documents. Jeremy posted a proposal for a taglib for this task a month ago but nobody replied. I think such a taglib would be very useful to a lot of people. Thus, I have retrieved a digest of Jeremies proposal and will respond to it below. I also would like to help implementing such a thing. Now, I won't claim that I have the ultimate idea of how such a tag lib must look like (Jeremy said something similar). Therefore, it would be nice if others could comment as well, so that this gets some "reality check". My background: I am currently converting parts of the old HTML website of my group to XML data bases. This includes things like a bookmark list, a bibliography, project descriptions & status, jobs offers, ... In order to make the maintainance easier, all those shall be editable by HTML forms over the web. The functionality needed is basicly add|edit|remove entries, no fancy ecommerce/business processes ;-) > --- Enclosed is a copy of the request I received. <snip> > Please keep in mind that this is at a very early stage ... <snip> > I don't fully understand XSP yet, so I need help working out if what I am > trying to do is going to be possible, and if there are better ways of > defining things. Same for me. I looked at the taglib code that comes with Cocoon 1.7.3 (sql, util, cookies,...), but for me there is still a lot of "magic" in it. <snip> > What should an xml:form tablib be able to do? > > First, in terms of "the seperation of contracts": > > Logic Contract > Where is that data to go? (XML Fragment, SQL db, email msg etc.) Another question would be "where does the data come from?" when you think about the "edit" mode. > How does the data need to be transformed to fit the storage? > What are the constraints on the data? (form checking) > Style Contract > How should it look? > What different formats should the form be output in? (HTML, WAP, PDF etc.) My first approach would be to say that the output of the taglib should happen to be HTML compatible, ie. you could use it with internet browsers without transforming it in any way. > Content Contract > What data is to be captured? > What are the fields called? > What form element should be used (input, textarea etc.) The type of form elements is sometimes a matter of layout. For example, you can use radiobuttons or comboboxes (<option> tag) for the same kind of choice. > What are the default values for the form? > What should you get when you fill in the form correctly? > What is the content of the page the form is in? > Second, in terms of functionality: > > The Form is rendered (method="GET") > Authorisation > (is this handled by the server?) I think so. If you would handle this from Cocoon, this probably would be a sitemap thing? > Choose Browser > Collect page content from anywhere as an included node > (based on user-lang or some other context) > Collect Form Field default values > (based on user-lang or some other context) > Collect Form Field "inherited" values (optional) > (Maybe someone is correcting or editing existing data or > form submission) > Assemble the Form > > The Form is submitted (method="POST") > Authorisation Another issue is a locking mechanism. If the form data goes to a SQL Database, this is probably handled implicitly, but the taglib should prevent 2 or more users from writing to the same XML file at the same time. > Convert PostArgs (or "GetArgs") into an XML Node, using "glue" to > define which Field goes into which Element. > Check the data. > too long, too short, coercable to correct data-type, > valid URL/email address, whatever ... >) > The first thing to note, if you have not worked it out already .... the > taglib responds differently depending on request method, I assume this is > possible. The request method can be queried, so this should be no problem. >? <snip> > The Tags: > > ? > <form:store> where form data is sent for storage > Can contain form:file, sql:connection-defs, mail:compose > etc. > . > <form:file> - depending on context, you want to read (include) or > write to nodes in a file > > <filepath> - where to find the file > type="relative | root | full | xlink | sitemap | url" > - what type of filepath is it? > - should new files be created on the server? > > <xpath> the XPath expression > > hopefully both these elements can contain tags from other > namespaces so you can do dynamic selection > <sql:connection-defs> > - depending on context, you want to get nodes by querying > SQL, write to/modify the node and overwrite the record. > you might be querying multiple records to get content or > only one > record if you are editing > > <form:field> - defines one field with an id > > <form:glue> - where to place field data in XML node you are > storing What kind of argument would this get? A XPath expression? A node set? Should be something that the various sources (sql, xml file,...) can provide easily. > <form:constraint> - verification information > > <datatype> - String, Integer, Double, Date, URL, > etc. > - Standard datatype coersions > ie. if it successfully coerces to the type, > it's OK > How can we check patterns like phone > numbers, credit card etc.? May here, the taglib should use types from the XML Schema definition. XML Schema has simple types such as string, float, boolean etc. It also provides facets to derive own types from it. For example, you can define ranges for integer values. Strings can be matched against regular expressions. The bad thing is that these types do not map 1:1 to Java types, so some extra work would need to be done. The good thing is that the Xerces team will have to bother about it so we can get this for free someday ;-) > <method> - user supplied verification method > > <form:transform> - method to transform data before storage > (or checking?) There should be also an transform option before the data is rendered. Just in case someone stores his or her date values in milliseconds since 1/1/70 ;-) > <form:action> - what should happen after verification and saving > > <form:trigger> - execute this when done (needs API?) What is the difference between <action>, <redirect> and <trigger>? > How does a Schema fit into this? Don't understand Schemas, but someone > talked about using them to define what gets edited by whom. Schemas are the next generation "DTDs". A Schema defines Content Models of XML entities (read "files"). The new things are name space support and "real" data typing (plus many others). Thus, one could dream of an application that reads a schema definition and outputs a form that lets you enter valid data according to that schema. But due to the complexity of schemas, this would be a lot of work. Well, where to go next? The central question would be how to design the interconnection between <data source> <-> <form taglib> Is it possible/sensible to mix tags from different tag libs? IE: <form:glue><sql:query (?)><form:glue> In this case we could split the problem in two sections: the form handling itself and the data source connection. For databases, the sql-taglib would be ready. Thus, we'd need something similar for accessing XML via XPath. Sven....
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200005.mbox/%3C391EBB61.94063139@gmx.net%3E
CC-MAIN-2015-14
refinedweb
1,225
73.98
36695/iot-in-serial-communication I'll put it a link below, which consists of a tutorial. It talks about how to implement a device firmware update process. It explains how you can start and monitor the firmware update process remotely through a back-end application connected to your hub. Azure IoT Hub supports three protocols: AMQP, ...READ MORE On Windows IoT you have to use Windows.Devices.SerialCommunication namespace ...READ MORE It is possible, but you should understand ...READ MORE Try following. Server loop void loop() { // ...READ MORE In IoT Hub there is a device ...READ MORE Answering your first question, Event Hubs are ...READ MORE The payload you receive will be a ...READ MORE That's because the two services do completely ...READ MORE Sorry, but it is not allowed in ...READ MORE Finding the mac-address would probably work. Basically, ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/36695/iot-in-serial-communication
CC-MAIN-2020-16
refinedweb
152
70.29
Hello, I am a Unity newbie. I have a bug model that crawls around randomly on the X/Z plane, using transform.Translate. I also have a terrain which I have set as a Mesh Collider. What I want is for the bug to crawl around on the terrain, setting his orientation to match the polygons he's crawling on. However, I'm having difficulty doing this with just the default collision functions. How can I determine the Z position of the terrain below my bug model? Can I get the orientation of this point, so I can use it as my model's "up" vector? Answer by UltimateWalrus · Jun 17, 2010 at 11:03 PM I found a reasonable answer to my problem. I used raycasting to find the proper Y coordinate, then used the normal to set orientation. I still wish I had a better handle on collision detection, but that's for another day I suppose... var hit : RaycastHit; if(Physics.Raycast(transform.position+Vector3(0,10,0),Vector3(0,-1,0), hit, 20)) { transform.position.y = hit.point.y; groundNormal = hit.normal; } Answer by e.bonneville · Jun 17, 2010 at 08:52 PM Here, this code should do the trick: function OnCollisionEnter(collision : Collision) { var contact = collision.contacts[0]; var rot = Quaternion.FromToRotation(Vector3.up, contact.normal); transform.rotation = rot; } It ensures that your bug's Y will be the same as the Y of the last thing it touched. Thanks for your help. I'm actually having trouble even getting functions like OnCollisionEnter to execute. I gave the terrain a mesh collider. Then, I gave my bug a box collider. Nothing happened. Then, I gave my bug a RidigBody component, and checked Is Kinematic. Still, nothing happened. I even tried making the terrain a RigidBody, to no avail. OnCollisionEnter just doesn't seem to be getting called. Am I missing something? :[ Answer by adamrmoss · Aug 20, 2011 at 02:30 AM If you're using a CharacterController you need to hook into the OnControllerColliderHit. Here's some C#: using UnityEngine; using System.Collections; public class FollowTerrain : MonoBehaviour { public TerrainCollider terrainCollider; public void OnControllerColliderHit(ControllerColliderHit hit) { if (hit.collider == terrainCollider) { var rot = Quaternion.FromToRotation(Vector3.up, hit.normal); transform.rotation =. Terrain Detail Mesh Collisions 1 Answer Mesh collide, terrain & object 1 Answer Collision Colliders - Box or Mesh for Terrain 1 Answer Mesh Collision system seems to be buggy. 1 Answer Giant colliders restricted to a set size? 0 Answers
http://answers.unity3d.com/questions/19842/crawling-around-the-terrain.html?sort=oldest
CC-MAIN-2015-48
refinedweb
413
51.44
If you spend much time around Configuration Manager you become aware that a lot of it runs through WMI. WMI is “Windows Management Instrumentation” and is essentially Microsoft’s implementation of a internet standard called Web Based Enterprise Management (WBEM). If you are doing task sequences and wanting to provide intelligent branching, digging into hardware inventory to possibly extend it, or working with the ConfigMgr SDK, you are playing around with WMI/WBEM. One tool I like to show my users who are new to WMI is one which is built right into every windows OS, called WBEMTEST. As you read this blog feel free to follow along, as I’m betting most readers are on a windows box. Go to Start and type “WBEMTEST” into the search or run box. Before I get too far, let me note that there are many WMI tools out there. On a regular basis I don’t use any of them? Why? Many are more friendly with a better UI designed. The big downside is that they have to be downloaded every time you want to use them. WBEMtest is at your fingers on any windows machine and OS learning to use it will speed your troubleshooting compared to going in search of your other favorite WMI tool. When you launch WBEMTEST different OS will work slightly differently. Some will automatically connect to a namespace, others (like Win7) will not. If you aren’t connected you can hit the connect button, make sure “root\cimv2” is selected, then hit connect again. Now you are back in the main UI with everything “lit up” and ready to go. A namespace is, to relate it to something most folks are familiar with, a directory within WMI. You can change directories to all kinds of namespaces. CIMV2 is where a good amount of hardware information is kept. From here you have lots of options. If you are already a WMI expert and know hat you are after you could hit the query button and type your WMI query to look at the results. For the beginner, just exploring WMI for the first time, I suggest you hit the “Enum Classes” button. In the pop-up choose “Recursive” and hit OK. You have just done the equivalent of a DIR to list all the contents of the name space. Everything with underscores (__) in the front of the name is what I call WMI overhead. This is what helps WMI be WMI. IN most cases you will skip over that and look at the other stuff. For this discussion I suggest going to Win32_Service and double clicking. You have now opened up this “file” in WMI which lists all the collect info about services on your machine. The file/directory analogy starts to break down at this point. Know that this is some definition information and skip past it by clicking on the instances button. You now get a list of all the services on your machine. Pick a service, such as RemoteRegistry” and double click it. You now get to see all the info about that specific service. This view is kind of a pain to look at, however, so I recommend you click the “Show MOF” button to get a nicer view of it all. Here you can see the service state, description, start mode, etc. Snoop around in WMI and see what you can find. Know that once you find something you could write queries in your task sequence to use that data as decision points, you could collect it via hardware inventory, or you could script against it using the SDK. All kinds of things open up for you. A few other namespaces you might be interested in are - root\ccm (ConfigMgr client info) - \root\SMS\site_ZZZ">\\<server>\root\SMS\site_ZZZ (where the ConfigMgr provider info is for the administration console) Have fun exploring!
https://blogs.technet.microsoft.com/michaelgriswold/2011/11/30/wbemtest-your-easiest-gateway-into-wmi/
CC-MAIN-2018-34
refinedweb
651
71.85
For example take a look at sys/kern/uipc_syscalls.c:accept1(). accept() and oaccept() are wrapper functions which pass differing flags to accept1() to turn on and off the logacy code. Here is a snip of the legacy code in accept1(). if (uap->name) { /* check sa_len before it is destroyed */ if (namelen > sa->sa_len) namelen = sa->sa_len; #ifdef COMPAT_OLDSOCK if (compat) ((struct osockaddr *)sa)->sa_family = sa->sa_family; #endif error = copyout(sa, (caddr_t)uap->name, (u_int)namelen); if (!error) gotnoname: error = copyout((caddr_t)&namelen, (caddr_t)uap->anamelen, sizeof (*uap->anamelen)); } The COMPAT_43 option turns on COMPAT_OLDSOCK which trashes the sa_len field of the sockaddr struct to be compatible with 4.3BSD. This occurs just before the copyout. This seems to be the main problem with the linux emulation code. It relies on alot of the old syscalls which use the old sockaddr struct. The trouble is that both the casting to a osockaddr struct and the copyout happen in the syscall functions. Thus it sounds like we need to implement the legacy syscalls in the linux emulation code. With the messaging system in place we will be able to intercept messages in the emulation layer and modify their contents before passing them on, right? This would solve the problems that I'm having with changing structures before a copyout. On another note: I think it would be a better idea to remove COMPAT_43 instead of fixing it because the legacy compat code is scattered all over the place. Comments? -- David P. Reese, Jr. daver@xxxxxxxxxxxx
https://www.dragonflybsd.org/mailarchive/kernel/2003-08/msg00206.html
CC-MAIN-2017-04
refinedweb
254
53.31
Hello, all How does one execute a parametrized query against an SAP HANA Database via the BoRecordSet object? It having no analog of DbConnection.AddParameter() method, with MS SQL Server I implemented my own mechanism for parametrized queries, which internally calls EXEC sp_executesql @query, @par_decl, @par1 = <val1>, @par2 = <val2>... It is much easier and safer to write: BoRecordSet rs; RecordSetWrapper rsw = new RecordSetWrapper( rs ); ... double GetRate( string currency, DateTime date ) { const string Query = @" SELECT ""Rate"" FROM ORTT WHERE ""RateDate"" = :date AND ""Currency"" = :currency "; rsw.AddParameter( "currency", currency); rsw.AddParameter( "date", date ); return ( double )rsw.GetValue(); } than double GetRate( string currency, DateTime date ) { const string Query = @" SELECT ""Rate"" FROM ORTT WHERE ""RateDate"" = '{0}' AND ""Currency"" = N'{1}' "; string query, date_str, cur_str; cur_db = currency.Replace( "'","''" ); // Ugly! date_db = date.ToString( "yyyyMMdd" ); // Ugly! // Ugly and inefficient and unsafe: query = String.Format( QueryTeml, date_db, cur_db ); return ( double )rsw.GetValue(); } I often have to use the DI SQL connection, and therefore BoRecordSet rather than DbConnection from Ado.Net, in situations such as performing a query from within a DI API transaction where any other connection would be locked. Futhermore, parametrized queries are more effective because they do not waste the precious SQL-plan cache, whereas wrapping every single query into a server-side procedure is utterly inconvenient. Therefore, if HANA did not support parametrized queries it would be a serious flaw, so I must be missing something. Am I? Add comment
https://answers.sap.com/questions/41276/parametrized-queries-with-borecordset.html
CC-MAIN-2019-22
refinedweb
235
56.35
I'm trying to make a 'TextWindow' that holds messages that the Application sends to it. The problem is that I have no idea on how to do this. I want to do something like, in C#, TextWindow.NewLine("This will be displayed in the TextWindow"); Would I just create a new script called "TextWindow" and set it up something like this? using UnityEngine; using System.Collections; public class TextWindow : MonoBehaviour { public TextWindow(Rect Size, string WindowName) { GUI.Box(new Rect(Size), WindowName); } public NewLine(string Text) { GUI.Label(new Rect(Rect), Text); } } Then call it using, TextWindow tWindow = new TextWindow(Size); Size of course being a Rect. This is a basic concept on how I want it to look in the end. Answer by Jamora · Sep 09, 2013 at 07:46 AM Because this is a console, and you will ever only need one, you should begin by making your console a static class. The basic principle is simple: you have a ScrollView, a VerticalArea, FlexibleSpace and a List. So something like: public static class MyConsole{ private static List< string > messages; private static Vector2 viewPoint; public static void DrawConsole(Rect area){ GUILayout.BeginArea(area); viewPoint = GUILayout.BeginScrollView(viewPoint); GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); //print each string in messages here //now close all the above areas } public static void NewMessage(string message){ messages.Add(message); viewPoint = Vector2.one; } } Now, in an OnGUI, to draw this, you use MyConsole.DrawConsole(area); and to add messages, MyConsole.NewMessage(message); MyConsole.DrawConsole(area); MyConsole.NewMessage(message); If you, for some reason need multiple consoles/textwindows, the same idea applies, you just need to remove the static, and keep track of the references. GUI Error: You are pushing more GUIClips than you are popping. Make sure they are balanced. I'm getting that error continuously. Also, I tried using the code, but it doesn't draw the console, nor can I write messages to it. I tried making them non-static, and initializing an instance of Console, but that didn't work either. I did have to set the return type of DrawConsole to void, it was giving me an error, Parse Error: Class, struct, or interface method must have a return type warning CS0649: Field `Console.messages' is never assigned to, and will always have its default value `null' General Warning, never goes away. I also had to 'using System.Collections.Generic;' even though I already have System.Collections. But oh well, not a problem there. I also get this error when I call Console.NewMessage. NullReferenceException: Object reference not set to an instance of an object Console.NewMessage Any reason you think it won't draw? This is the code I'm using it in. using UnityEngine; using System.Collections; public class Server : MonoBehaviour { public string IP; public string Port; public int ConnectionCap = 10; string ServerStatus; void OnGUI() { GUI.Label(new Rect(Screen.width*0.035f, Screen.height*0.035f, 150, 25), ServerStatus); GUI.Label(new Rect(Screen.width*0.035f, Screen.height*0.06f, 150, 25), "Connections: " + Network.connections.Length); IP = GUI.TextField(new Rect(Screen.width*0.035f, Screen.height*0.0935f, 150, 25), IP); Port = GUI.TextField(new Rect(Screen.width*0.035f, Screen.height*0.14f, 75, 25), Port); if(GUI.Button(new Rect(Screen.width*0.9f-50, Screen.height*0.9f-12.5f, 100, 25), "Start Server")) { ServerStatus = "Starting..."; Console.NewMessage(ServerStatus); Network.InitializeServer(ConnectionCap, int.Parse(Port), true); ServerStatus = "Started"; Console.NewMessage(ServerStatus); } if(GUI.Button(new Rect(Screen.width*0.9f-50, Screen.height*0.95f-12.5f, 100, 25), "Stop Server")) { ServerStatus = "Stopping..."; Console.NewMessage(ServerStatus); Network.Disconnect(); ServerStatus = "Stopped"; Console.NewMessage(ServerStatus); } Console.DrawConsole(new Rect(Screen.width/2-100, Screen.height/2-50, 200, 100)); } void Start() { ServerStatus = "Stopped"; } } Because I think Unity Answers isn't a Write-MyCode-For-Me service, I only gave you the rough idea on how to accomplish the console. The reason you get the GUIClips error is because you have to have a corresponding close statement for each begin; i.e. GUILayout.BeginVertical(); is closed with GUILayout.EndVertical();. I did mention this in the code snippet. GUILayout.BeginVertical(); GUILayout.EndVertical(); You also need to initialize the messages list. Currently it is only declared, and as such has the value null. I'll concede that I forgot to type in the return type to the DrawConsole method. I did attempt to write my own, so you aren't necessarily writing my code. Anyway, How would I go about printing the string's? I really don't have a clue about this one and that's why I come here after trying everything I can on my own. I do appreciate the help. I would like the text to get pushed upwards, and align right to left if you wouldn't mind doing that. I have the corresponding close statements as well. Still getting GUIClip error's. You would print the strings by iterating over the messages list, then using GUILayout.Label on each string. The text automatically gets pushed upwards, because you print all the strings in the list, then set the viewPoint to Vector2.one (that is bottom in ScrollViews). You can set all kinds of style options in GUIStyles, if you need a lot of GUIStyles, you can use a GUISkin, which is just a collection of GUIStyles. If you have EndArea, EndScrollView, and EndVertical; you shouldn't get GUIClip errors. Could I use a for loop where you stated to print the strings? Would that even work? Wouldn't it need to be in an update function or something? Or does OnGUI update by. GUI.label overlapping text 1 Answer Ngui Text Vertical Scrollbar? 1 Answer OnGUI called after LateUpdate screwing up debug text database 1 Answer GUI Text Blinking came up with one error. 3 Answers Unity 5 UI Text Glitch (illegible characters) 0 Answers
https://answers.unity.com/questions/533239/custom-console-in-application.html
CC-MAIN-2019-43
refinedweb
982
59.5
. If anyone is looking for a PDF library like this for .NET that is well supported, I recommend PDFKit.NET. Thanks for the recommendation — that’s handy to know. Im getting a NullPointerException when trying to use the .setValue…. SEVERE: java.lang.NullPointerException at org.apache.pdfbox.pdmodel.interactive.form.PDAppearance.calculateFontSize(PDAppearance.java:558) at org.apache.pdfbox.pdmodel.interactive.form.PDAppearance.setAppearanceValue(PDAppearance.java:303) at org.apache.pdfbox.pdmodel.interactive.form.PDVariableText.setValue(PDVariableText.java:131) at org.apache.jsp.index_jsp._jspService(index_jsp.java:91) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111) at javax.servlet.http.HttpServlet.service(HttpServlet.java:770) …. Have you checked if the field you tried to set the value is null? If not add the check… if (field != null) { field.setValue(value); } else { System.err.println(“No field found with name:” + name); } Thanks Erick!!This help me very match!! Glad if it helped! It’s always nice to hear that posting my solution to something I was working on helps someone else. Thanks a lot for sharing that! Very useful as I just started using PDFBox with forms. Glad to hear that people are still finding this useful, and thanks for the feedback. Always nice to hear when a post helped someone. in printFields, I get an error at line: ” Iterator fieldsIter = fields.iterator();” java.lang.ClassCastException: org.apache.pdfbox.pdmodel.common.COSArrayList incompatible with com.sun.xml.internal.bind.v2.schemagen.xmlschema.List do you know what is causing this? the quick fix tells me to add Cast to fields, however that does not fix the error I resolved the cast issue, by modifying my imports, I am now using: import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.common.COSArrayList; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; importorg.apache.pdfbox.pdmodel.common.COSObjectable; importorg.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.pdmodel.interactive.form.PDField; Excellent. thank you. Erik, thanks for this article. Because of your article, I did not waste any time in experimenting and could use your code. Excellent — glad it helped! Thank you for the example code, I have some fields that are not getting updated… I have a PDF form that has some PDCheckBox fields that only have one radio button choice (they are not part of a group of fields of the same name), setField(field, value) will not update those fields. if the PDF form has another check box of the same name with a different default radio button choice then setField will update the field. Any ideas how I can get around this issue without having to modify the forms? I honestly haven’t looked at that code or utility in over 2 years. I wish I could be more help, but it’d probably take me a good long time just to get to where I understood as much as you. thanks for this i tried this but returns all null: List fields = acroForm.getFields(); if( fields != null && fields.size()>0) { for(Object field : fields){ System.out.println(field.toString()); } } System.out.println(field+ ” |– “+ field.getPartialName()); //null |– a age 1 //null |– dob 1 processField(field, “|–“, field.getPartialName()); what should be that value of “name” here? PDField field = acroForm.getField( name ); This error returns: Don’t know how to calculate the position for non-simple fonts Wish I could be of more help, but it’s been years since I’ve even had access to that code, much less looked at it. Why did you write this code to use global, mutable state? I’m not sure what kind of answer you’re looking for. I wrote this post almost 3 years ago, and the code in question is code I took from an example in their API doco and tweaked to work for my purposes. This post was just, “here’s a thing I got this working that might help you.” It wasn’t intended to be any kind of lesson on encapsulation. It was an open-ended question. In retrospect, I can see how you interpreted it as a hostile comment from me. My apologies. Your explanation is great though: just a one off kind of thing. I thought your post was more on the lines of “this is how you programmatically fill out PDF forms in Java” not “he’s a hacked together recipe with PDF box.” No worries on my end 🙂 For a lot of years, I tended to reply with snark if I didn’t understand the context or tone of a question. Now, I just try to ask. Any static state that I use, generally, would either be the result of me having something foisted on me by existing code or an API, or it would be the result of me not knowing how to eliminate it. I test drive any production-targeted code that I write, so global state tends to be anathema to me because of its effect on testability. Easy way to iterate the fields in 2.0 version: Iterator iterator = acroForm.getFieldIterator(); while(iterator.hasNext()) { log.info(iterator.next()); } Appreciate the snippet! I’ve banging my head against the wall with an XFA form but convinced the client to re-render it as FDF, and this has gotten me well along my way. Glad if it helped! Very helpful. Thanks. Is that a way to read contents pdf fields with Apache pdfbox?
https://daedtech.com/programatically-filling-out-pdfs-in-java/
CC-MAIN-2022-40
refinedweb
923
59.7
So, I wanted one of those horizontal multi-selects with “available” and “chosen” boxes to associate users with groups in the Django auth admin UI. Turns out it all I had to do was import the UserAdmin class from django.contrib.auth.admin and override the filter_horizontal attribute: from django.contrib.auth.admin import UserAdmin UserAdmin.filter_horizontal = ('user_permissions', 'groups') Since importing the UserAdmin class runs the admin module from django.contrib.auth, the UserAdmin and GroupAdmin classes are registered for the admin site. All I have to do then is import my custom admin module in my URLconf instead of the one from django.contrib.auth to make sure my customizations are applied in my admin site. Update 1/5/11 As discovered by a commenter, there are some admin attributes which can’t be overridden as simply as shown above. However, you can first unregister the model with the admin site (this method is not publicly documented), override, then re-register the model: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User admin.site.unregister(User) class CustomUserAdmin(UserAdmin): filter_horizontal = ('user_permissions', 'groups') save_on_top = True list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'last_login') admin.site.register(User, CustomUserAdmin) #1 by bjubb on October 2, 2009 - 9:49 am Exactly how did you import your admin instead of the django.contrib.auth, yet also allow the autodiscover routine to run? Thanks – this tip should help me out nicely if I can get the import to work. #2 by David Chandek-Stark on October 2, 2009 - 8:26 pm I don’t use autodiscover because I want more control over what gets added to the admin UI, so I’m not sure how this recipe plays in that scenario. You might simply be able to add the lines I’ve given before or after the autodiscover call (or import the module that contains them, which is what I do). As I said, importing the UserAdmin class from django.contrib.auth.admin effectively registers the admin classes from that module. Does autodiscover blow up if it encounters admin classes that are already registered? #3 by bjubb on October 5, 2009 - 9:44 am i dont use autodiscover and use this instead in attempt to change which items are shown on the Auth->Users page: from django.contrib.auth.admin import UserAdmin UserAdmin.list_display(…) The User/Group classes register fine, its just that my changes to the list_display dont work. #4 by bjubb on October 5, 2009 - 9:46 am Sorry – here’s the real line of code: UserAdmin.list_display = (‘username’, ’email’, ‘first_name’, ‘last_name’, ‘is_staff’, ‘last_login’) Trying to add the last login to the page….it works if i just edit the actual django admin file , but obviously i liked your method better. #5 by David Chandek-Stark on January 5, 2011 - 2:02 pm See the 1/5/11 update, which shows how you can do this. #6 by Ryan Blunden on May 29, 2011 - 9:06 pm Thanks for this write up, updates marked 1/5/11 worked perfectly for me.
https://fragmentsofcode.wordpress.com/2009/05/26/tweaking-django-auth-admin/
CC-MAIN-2017-17
refinedweb
518
55.95
5 04 2017 Throw expressions in C# 7.0 C# 7.0 introduces throw expressions. We can add exception throwing to expression-bodied members, null-coalescing expressions and conditional expressions. This blog post introduces throw expressions, demonstrates how to use them and also provides a peek behind a compiled throw expressions. - Out variables in C# 7.0 - Tuple literals in C# 7.0 - Throw expressions in C# 7.0 - Local functions in C# 7.0 Throw expressions are the way to tell compiler to throw exception under specific conditions like in expression bodied members or inline comparisons. Before going to some practical use cases let’s see some illustrative examples of throw expressions that were originally posted with .NET Blog post What’s New in C# 7.0(); } Now let’s see what we can do with throw expressions in practice. Throw expressions in unit testing We can use throw expressions when writing non-functioning methods and properties we plan to cover with tests. As these members usually throw NotImplementedException we can save some space here.’’ public class Customer { // ... public string FullName => throw new NotImplementedException(); public Order GetLatestOrder() => throw new NotImplementedException(); public void ConfirmOrder(Order o) => throw new NotImplementedException(); public void DeactivateAccount() => throw new NotImplementedException(); } Of course, this example has also its dark side. It hides the fact that the class can grow too big and there can be need to split it to smaller pieces. Keeping setters short Using throw expressions we can keep some setters short. Here is the FirstName property of Person class. private string _firstName; public string FirstName { get => _firstName; set => _firstName = value ?? throw new ArgumentNullException(); } Notice that throw expressions work also with null-coalescing operator (??). NB! This example is not an example of bets practices. It applies to properties that actually need body with some logic. If automatic properties and validation rules match your needs then go with these. Don’t change your code to use throw expressions just because they are here or they are looking cool. Throw expressions in action Here is the code example where some method arguments are compared to null. public Order AddProductToNewOrder(Product product, Customer customer, double amount) { if(product == null) { throw new ArgumentNullException(nameof(product)); } if(customer == null) { throw new ArgumentNullException(nameof(customer)); } var orderLine = new OrderLine(); orderLine.Product = product; orderLine.Amount = amount; var order = new Order(); order.Customer = customer; order.AddLine(orderLine); return order; } We get this code shorter when using throw experssions. Actually Visual Studio proposes this change for us. Here is the code with null check simplifications and some well-hidden land mines. public Order AddProductToNewOrder(Product product, Customer customer, double amount) { var orderLine = new OrderLine(); orderLine.Product = product ?? throw new ArgumentNullException(nameof(product)); orderLine.Amount = amount; var order = new Order(); order.Customer = customer ?? throw new ArgumentNullException(nameof(customer)); order.AddLine(orderLine); return order; } As far creating order and order line is creating new instance of simple class we are safe to go with this code. I don’t like the fact that objects are created. If new instances of order and order line are created using factory classes we cannot use the code above as creating these instances may be resource consuming or complex activity. Factory classes are usually not introduced for fun. Behind the compiler Let’s take now the FirstName property shown above and see what compiler produces of it. Without any guidance by PDB-file JetBrains dotPeek decompiles the property for us this way. private string _firstName; public string FirstName { get { return this._firstName; } set { string str = value; if (str == null) throw new ArgumentNullException(); this._firstName = str; } } As you can see then throw expression is just a nice addition to language and it doesn’t have any meaning in runtime level. Without PDB-file telling decompiler the truth about the code in library we get back what was compiled. Wrapping up Throw expressions are here to help us write smaller code and use exceptions in expression-bodied members. It is just a language feature and not anything fundamental in language runtime. Although throw expressions help us to write shorter code it is not a silver bullet or cure for every disease. Use throw expressions only when they can help you. Tuple literals in C# 7.0 ASP.NET Core: SQL Server based distributed cache
http://gunnarpeipman.com/2017/04/throw-expressions/
CC-MAIN-2018-05
refinedweb
713
50.53
ImportError: cannot import name 'ki18n' when launching gdebi-kde Bug Description On Ubuntu 14.04 when I launch gdebi-kde I get the following stacktrace message: Traceback (most recent call last): File "/usr/bin/ from PyKDE4.kdeui import KApplication, KMessageBox, ki18n ImportError: cannot import name 'ki18n' I am using gdebi 0.9.5.2 Here the same error, i'm using gdebi-kde 0.9.5.3 on Kubuntu Trusty: File "/usr/bin/ from PyKDE4.kdeui import KApplication, KMessageBox, ki18n ImportError: cannot import name 'ki18n' I've installed/ Problem with python3 internalization. Patches from Michael Werle to solve the problem here: https:/ Patches tested, no more error messages and gdebi works. Patches fix: For gdebi-kde: * Fix ki18n import: from kdeui to kdecore * Replace ugettext with gettext * Pass bytes rather than strings to ki18n For GDebi/GDebiKDE.py: *replace QStringList with list *replace string operations with str Thanks to Michael Werle. For Ubuntu Users I have just built some .deb packages. Unfortunitley they are not in a PPA yet Here is the source code The attachment "gdebi-kde" gdebi - 0.9.5.4 --------------- gdebi (0.9.5.4) unstable; urgency=low [ Michael Vogt ] * fix installing of dependency packages when called with sudo (LP: #1309387) [ Michael Werle ] * gdebi-kde, GDebi/GDebiKDE.py: - Fix python3 internatlization bugs (Closes: #743756) (LP: #1304143). [ Luca Falavigna ] * Fix tests at build time (Closes: #743091). -- Luca Falavigna <email address hidden> Tue, 22 Apr 2014 10:54:48 +0200 This package does not seem to be in the Ubuntu repository. Marking as Fix Committed. Actually it is, but in 14.10 only. Technically Speaking this bug isn't fixed until it is backported to trusty as I reported it in trusty. I will work on uploading it to a PPA. For the trusty task to be fix committed a package fixing the bug should be available in the -proposed repository for that release. This is not the case for this bug. Thanks for clarifing that Brian Hello nOSinfinite, or anyone else affected, Accepted gdeb:/ gdebi_0. This bug was fixed in the package gdebi - 0.9.5.3ubuntu2 --------------- gdebi (0.9.5.3ubuntu2) trusty-proposed; urgency=medium [ Michael Werle ] * gdebi-kde, GDebi/GDebiKDE.py: - Fix python3 internatlization bugs (Closes: #743756) (LP: #1304143). -- Brian Murray <email address hidden> Thu, 01 May 2014 09:08:06 -0700 The verification of the Stable Release Update for gdeb reporting this issue and help making Ubuntu better. I get the same error message when attempting to start gdebi-kde 0.9.5.3 on Ubuntu Trusty.
https://bugs.launchpad.net/ubuntu/+source/gdebi/+bug/1304143
CC-MAIN-2017-51
refinedweb
422
67.35