text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
You tried to install using the command line and it does nothing. It creates an empty folder (on st start) and that's all.I tried to download & install this file: but when i hit *install package *i get this error in the console: Exception in thread Thread-47: Traceback (most recent call last): File ".\threading.py", line 532, in __bootstrap_inner File ".\Package Control.py", line 1189, I'm looking into this right now. I'm not quite sure why the command line installed would not work. I just took a fresh ST2 environment on Win 7 x64 and it seemed to work fine extracting the files into the Package Control folder. If you want to try and debug it you could delete the Package Control folder and run the console command again. The next time you open ST2 you can look at the console and it should mention that it is installed Package Control. My guess is that there will probably be some error after it begins the process. From the error message you posted after manually downloading the package, it seems like a file permissions issue with running Git to perform a Git fetch. My guess is that your current user for some reason does not have permission to execute git.exe, which is probably stored in C:\Program Files (x86)\Git\bin. If you right click and select Properties and then go to the Security tab, there will be a list of users and groups that have permissions. On my machine the Users group has the read and execute permission. For git fetch to get executed, one of your packages must be a git repository. Perhaps the permissions on some files in that repository are broken also? Let me know what you find out! If anyone gets the following error: Package Control: An error occurred while trying to backup the package directory for [package name]. Please execute the following in your console: import os;os.makedirs(os.path.join(os.path.dirname(sublime.packages_path()), 'Backup')) Permissions looks like this: screencast.com/t/rb7GnnxJ4t On startup console i have this (that is related to package control): startup, version: 2102 windows x64 channel: dev executable: /C/Program Files/Sublime Text 2/sublime_text.exe working dir: /C/Windows/system32 packages path: /C/Users/Ionut/AppData/Roaming/Sublime Text 2/Packages settings path: /C/Users/Ionut/AppData/Roaming/Sublime Text 2/Settings error parsing session: No data at: 0:0 package /C/Users/Ionut/AppData/Roaming/Sublime Text 2/Installed Packages/Package Control.sublime-package is newer than the installed version (/C/Users/Ionut/AppData/Roaming/Sublime Text 2/Pristine Packages/Package Control.sublime-package), running PackageSetup PackageSetup returned: -1 catalogue loaded Git is installed into c:\cygwin\git and is accesible via windows cmd. Also, this command: give me this: >>> import os;os.makedirs(os.path.join(os.path.dirname(sublime.packages_path()), 'Backup')) Traceback (most recent call last): File "<string>", line 1, in <module> File ".\os.py", line 157, in makedirs WindowsError: [Error 183] Cannot create a file when that file already exists: u'C:\\Users\\Ionut\\AppData\\Roaming\\Sublime Text 2\\Backup' Yeah, sorry, that Backup command was unrelated to your issues, but a bug someone else found. Did you manually set the git_binary setting in the Package Control settings? Can you try browsing to the package folder that is a git repository and executing "git fetch"? The Package Control folder is empty. I re-downloaded the sublime-package file mentioned above but no luck. I tried to clone the github repo but that didnt worked either. For git config i have this: "git_binary": "C:\\cygwin\\git\\bin" (also tried to specify git.exe and / instead of \). Same error. [quote="iamntz"]For git config i have this: [/quote] Aha! So the git_binary setting should include the executable name. I'll make the documentation more clear on this. Here is a config that should work: "git_binary": "C:\\cygwin\\git\\bin\\git.exe" Yeah, that didnt worked either. I tried before.Still got this: Exception in thread Thread-2: Traceback (most recent call last): File ".\threading.py", line 532, in __bootstrap_inner File ".\Package Control.py", line 1522, However, the main difference is that now i restarted the editor and when i tried to „install packages” i got like 10 errors like: Package Control: Downloading timed out, trying again (different urls tho) [quote="iamntz"]Yeah, that didnt worked either. I tried before.Still got this: There definitely seems to be a permissions issue on your machine somewhere. Did you try running "git fetch" on the package you have that is a git repository? I just installed cygwin and set my git_binary setting and everything worked fine. The only difference I see is that mine installed to C:\cygwin\bin\git.exe instead of C:\cygwin\git\bin\git.exe. [quote="iamntz"]However, the main difference is that now i restarted the editor and when i tried to „install packages” i got like 10 errors like: (different urls tho)[/quote] This is ok, just a diagnostic message. If you get a real error a message will pop up. By default the timeout is set to 3 seconds, which sometimes is too short depending on how heavily loaded the server is. If you do consistently get an error popup, you can increase the timeout in the Preferences > Package Settings > Package Control > Settings - User file. Grrr. Everything else works just fine. There are few "WindowsError: [Error 5] Access is denied" related results on google (and stackoverflow) that suggest the issue is python. Anyhow, don't worry, i don't really need the PM, i was more like curious. I apologize if I sounded patronizing. If you would oblige me a minute longer, could you edit the execute() method of the VcsUpgrader class on line 449 of Package Control.py to be the following? def execute(self, args, dir): startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW print args print dir proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo, cwd=dir) return proc.stdout.read().replace('\r\n', '\n').rstrip(' \n\r') When you save the file, it should automatically try to execute the upgrader, and it should print what it is trying to execute and the directory it is trying to execute in. Yeah, i think i found the problem. Somehow.I deleted the user folder and now seems to work. Let's see which one is bitchin! Ok, me dumb. I had a Package Control.sublime-settings file into user directory with wrong stuff in it. The thing is the file was automatically added (and i just edit the file within package control directory).Now seems to work. Thanks for help!...
https://forum.sublimetext.com/t/package-control-a-full-featured-package-manager/2238/46
CC-MAIN-2017-39
en
refinedweb
hey guys im working on a homework problem which requires two things -count the total number of clumps -determine the longest clump i finally made my code to recognize the number of total clumps however i still cnt figure out how to determine the longest clump any help be great!thanks:) #include <iostream> #include <string> using namespace std; int countClumps(int k, string s, string & longest); int main () { string s, string2; int length; char play; do { cout << "Enter a minmum clump length of 2 or more: "; cin >> length; while (length <= 1) { cout << "ILLEGAL VALUE!!!!" << endl; cout << "Please Enter a minmum clump length of 2 or more:"; cin >> length; } cout << "Enter one or more words each having at least "; cout << "2 characters. When you want to quit, enter any word with fewer than 2 characters." << endl; cin >> s; cout << countClumps(length, s, string2) << endl; cout << "string2 is" << string2 << endl; cout << "play again"; cin >> play; } while (play != 'n'); return 0; } int countClumps(int k, string s, string & longest) { longest = ""; // cout<<"long is" <<longest<<endl; int i = 1, g = 0, total = 0; while (g < s.length()) { while (i < s.length() && s[g] == s[i]) { i++; } int y = i - g; int p = g; if (y >= k) total++; if (y > longest.length()) { longest = s[g], s[y]; } g = i; } return total; //cout <<s<<"has " << total << " clumps." << endl; }
https://www.daniweb.com/programming/software-development/threads/268956/how-to-determine-the-longest-clump
CC-MAIN-2017-39
en
refinedweb
Units of measurement in domain design If you have business application of any decent size, your most important code probably resides in domain logic. When working with 3rd party code, you can always find an answer on stack overflow or official documentation, but your domain is all yours. Try to make it as simple and readable as possible, and it will always pay you back. Today I want to discuss one aspect of writing clean domain code: units of measurement. It is important for any domain (or sub-domain) where you operate some physical measurements. Problem statement Our toy example will be about cars and fuel consumption. You receive some data about the trip of your car, e.g. an instance of public interface ITrip { double FuelUsed { get; } double Distance { get; } } Now you want to calculate the fuel consumption rate of your trip. You write var fuelRate = trip.FuelUsed / trip.Distance; You get the value, but what is it? Let's say you want a value of liters per 100 kilometers. You can assume that FuelUsed is in liters, and Distance is in kilometers. To be more explicit you refactor your code public interface ITrip { double FuelUsedInLiters { get; } double DistanceInKilometers { get; } } var fuelRateLitersPer100Kilometers = trip.FuelUsedInLiters * 100.0 / trip.DistanceInKilometers; Now it's much more explicit, and probably good enough for such a small code example. For larger code bases, you will inevitably get into more problems: You will start measuring same things in different units. E.g. you will store the distance in meters in the database, so you'll have to multiply by 1000 somewhere in persistence layer. If you need to convert metric to imperial and back, you will get lots of constants here and there. String formatting will become a tedious task. Be sure to call a right formatter for each implicit unit. This does not work well. The code smell is called Primitive Obsession and we should avoid this in production-grade code. Instead, we want the succinctness of first example in combination with strong compile-time checks and well-defined operations. Defining the units I tried several options like generic classes for units, but I ended up having a struct per measurement. The code is very boring and repetitive, but it provides me with the strongest compile-time checks and nice readability. If you are too bored with typing, you can do some code generation or just use 3rd party that suits you. So, my end result looks like public interface ITrip { Volume FuelUsed { get; } Distance Distance { get; } } Let's see how Distance is defined (Volume will be almost exactly same): public struct Distance { private Distance(double kilometers) { this.Kilometers = kilometers; } public double Kilometers { get; } public double Meters => this.Kilometers / 1000.0; public static readonly Distance Zero = new Distance(0.0); ... } Several important things to notice here: It's a struct. It's immutable. Once an instance is created, its properties can't be changed anymore. Constructor is private. I don't actually want people to create instances directly: new Distance(123)reads pretty horribly, keep reading to see better options. Of course, default constructor is still public, but you can only create a zero value with it. Better way of creating zero distance is to call Zero static field. Instantiation So, how do we create measurement objects? Factory method The classic way is a set of static factory methods: public static Distance FromKilometers(double kilometers) { return new Distance(kilometers); } public static Distance FromMeters(double meters) { return new Distance(meters / 1000.0); } Usage is as simple as var distance = Distance.FromMeters(234); Extension method Imagine you have the following code which converts an integer value of a database result into our units trip.Distance = Distance.FromMeters(database.ReadInt32("TotalDistance") .GetDefaultOrEmpty()); Such a long expression reads better with a fluent interface like trip.Distance = database.ReadInt32("TotalDistance") .GetDefaultOrEmpty() .MetersToDistance(); MetersToDistance in this case is an extension method: public static class DistanceExtensions { public static Distance MetersToDistance(this double meters) { return Distance.FromMeters(meters); } } Operator with static class using C# 6 brings us a new language construct. Now we can import a static helper class using static Units.Constants; And then we can write something like var distance = 10.0 * km; where km is defined in that static class: public static class Constants { public static readonly Distance km = Distance.FromKilometers(1.0); } This may not look like idiomatic C#, but I think it's very good at least for writing unit tests: var target = new Trip { DistanceOnFoot = 5 * km, DistanceOnBicycle = 10 * km, DistanceOnCar = 30 * km }; target.TotalDistance.Should().Be((30 + 10 + 5) * km); For this to compile you just need to define the operator overload: public static Distance operator*(int value, Distance distance) { return Distance.FromKilometers(value * distance.Kilometers); } Conversion and printing More advanced unit conversions are easy with unit classes. A common use case would be to convert metric units to imperial system. All you need to do is to add another calculated property // Distance class private const double MilesInKilometer = 0.621371192; private const double FeetInMeter = = 3.2808399; public double Miles => this.Kilometers * MilesInKilometer; public double Feet => this.Meters * FeetInMeter; Another common task is printing (formatting) unit values into string. While you can (and should) implement some basic version of it in ToString() method, I advise against doing all the formatting inside the unit class. The formatting scenarios can be quite complex: - Format based on user preferences (metric/imperial) - Pick units based on the value (e.g. 30 m but 1.2 km, not 1200 m) - Localization to different languages - Rounding to some closest value If you do all that in the unit class, it's going to violate the single responsibility principle. Just create a separate class for formatting and put all those rules there. Unit derivation Once you write more unit classes, you will definitely want to derive the calculation result of two units into the third one. In our example, we want to divide Volume of fuel used by Distance to get fuel ConsumptionRate. There's no magic that you could do here. You will have to define ConsumptionRate class the same way you defined the other two, and then just overload the operation public static ConsumptionRate operator/(Volume volume, Distance distance) { return ConsumptionRate .FromLitersPer100Kilometers(volume.Liters * 100.0 / distance.Kilometers); } Of course, you'll have to define all the required combinations explicitly. If you defined Constants as described above, you'll be able to instantiate values in your tests in the following way: var fuelRate = 7.5 * lit / (100 * km); Should I use 3rd party libraries for that? It depends. Of course, people implemented all this functionality about 1 million times before you, so there are numerous libraries on GitHub. I would say, if you start a new project and you don't have a strong opinion about the unit code, just go grab the library and try to use it. At the same time, for existing code base, it might be easier to introduce your own implementation which would resemble something that you already use. Also, I have another reason for my own implementation. I'm using units all over the code base of domain logic, the very heart of the software, the exact place where I want full control. I find it a bit awkward to introduce a 3rd party dependency in domain layer. Like this post? Please share it!
https://mikhail.io/2015/08/units-of-measurement-in-domain-design/
CC-MAIN-2018-09
en
refinedweb
Achoo is a fluent interface for testing Python objects. It is designed to be used in conjunction with a unit testing framework like PyUnit's C{unittest} module, shipped with all modern Python distributions. To use Achoo, import the assertion builder functions then use them to wire up assertions about objects and callables. The two assertion builder functions are C{requiring} - used to test(more...) src/a/c/Achoo-1.0/test.py Achoo(Download) import unittest import achoo
http://nullege.com/codes/search/achoo
CC-MAIN-2018-09
en
refinedweb
> Date: Mon, 3 Mar 1997 11:16:34 -0500 > From: "Barry A. Warsaw" <bwarsaw@anthem.cnri.reston.va.us> > To: MHammond@skippinet.com.au > Cc: doc-sig@python.org > Subject: Re: [PYTHON DOC-SIG] Templatising gendoc, and more. > Reply-to: "Barry A. Warsaw" <bwarsaw@CNRI.Reston.Va.US> > > >>>>> "MH" == Mark Hammond <MHammond@skippinet.com.au> writes: > > MH> Couple of quick questions - how can a ni package provide doc > MH> strings? Eg, a package named "xyz" is a directory, _not_ a > MH> file. I added a convention to gendoc that a file called > MH> "__doc__" in a packages directory will be read, and treated as > MH> docstrings for the module itself (which makes lots of sense to > MH> me, as then you dont need to distribute it) Also, I "flatten" > MH> the "__init__" module, so that all docstrings and methods are > MH> documented in the package itself - ie, __init__ never gets a > MH> mention in the docs. Do these sound OK? > > I think Ken M. was the first to champion flatting of __init__ into the > package module. The argument is that flattening is the most natural > way to think about package modules and most package authors are going > to want to this, so it makes sense to be the default behavior. I even > went so far as to add the couple of lines to ni.py to make this > happen, but Guido nixed it, partially because there wasn't enough > experience with ni.py to back-up the `most common usage' argument. > > In any case, when I packagized some parts of Grail, I added the > following gross hack (taken from fonts/__init__.py): :-) Ive come up with the same hacks, without ever seeing fonts :-) Ive _always_ done this in __init__, and maybe we would find that the "most common usage" argument is more pervasive now? > What I would to do ni, is automatically put any non-underscore > prefixed symbol appearing in __init__.py into the package module's > namespace. I would also put __doc__ into that namespace. It's all of > a two or three line change to ni.py. Also, you might provide some way > of controlling what gets put into the package's namespace from > __init__.py. Im sure many people will dis-agree here, but IMO docstrings in the code is cute, but on-line browsing of docstrings wont be used anywhere near as much as generated documentation. I think it most important docstrings be kept near the sources for maintenance, rather than browsing. I'd ask if flattening of the doc strings at run-time is really worth it? Another interesting "feature" of docstrings is that the sources often get _twice_ as big (Python is partly to blame here, as the programs themselves are often so small :-). If you consider the win32com stuff, not only are the sources twice as big, all the doc strings are _also_ in the generated HTML. And at run-time, obviously, they take more memory. And the more keen you are with the documentation, the more penalty you pay. (OK - were not talking too much, and Im not really _that_ concerned, but...) This is one reason why I like my new little __doc__ file convention. It means I can put "overview" type information in a seperate file that is included in the HTML build, but not part of the sources (but still very close). Browsers wont see it, but people browsing wont be looking for "overview" information anyway - they are more likely to be looking for a specific object... _______________
https://mail.python.org/pipermail/doc-sig/1997-March/000219.html
CC-MAIN-2018-09
en
refinedweb
In this blog, we will be predicting NBA winners with Decision Trees and Random Forests in Scikit-learn.The National Basketball Association (NBA) is the major men’s professional basketball league in North America and is widely considered to be the premier men’s professional basketball league in the world. It has 30 teams (29 in the United States and 1 in Canada). The data is available at. I have assembled the data into a CSV file and available in my GitHub folder. This blog is influenced by this book. Please feel free to leave a comment.). Predicting NBA winners with Decision Trees and Random Forests #Import the dataset and parse dates import pandas as pd df = pd.read_csv("NBA_2017_regularGames.csv",parse_dates=["Date"]) df.head(2) The columns names are not clear. Therefore, we will rename the column names. #Rename the columns df.columns = ["Date","Time","Visitor Team","Visitor Points","Home Team","Home Points","Score Type","Extra Time","Notes"] df.head(2) From the description of how games are played, we can compute a chance rate. In each match, the home team and visitor team has a probability to win half of the time Prediction Class In the following code we will specify our classification class. This will helps us to see if the prediction from the decision tree classifier is correct or not. We will specify our class as 1 if the home team wins and 0 if the visitor team wins in another column called “Home Team Win”. df["Home Team Win"] = df["Visitor Points"] < df["Home Points"] print("Home Team Win percentage: {0:.1f}%".format(100 * df["Home Team Win"].sum() / df["Home Team Win"].count())) Home Team Win percentage: 58.4% Separate the classification class y_true = df["Home Team Win"].values #The array now holds our class values in a format that scikit-learn can read. y_true array([ True, False, True, ..., True, False, True], dtype=bool) Feature Engineering We will create the following features to help us in predicting NBA 2017 winners. - Whether either of the visitor or home team won their last game. - Which team is considered better generally? - Which team won their last encounter? # Let's try see which team is better on the ladder. Using the previous year's ladder # standing = pd.read_csv("ExapandedStanding.csv") df["Home Last Win"] = False df["Visitor Last Win"] = False from collections import defaultdict won_last = defaultdict(int) for index, row in df.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] row["Home Last Win"] = won_last[home_team] row["Visitor Last Win"] = won_last[visitor_team] df.ix[index] = row #We then set our dictionary with the each team's result (from this row) for the next #time we see these teams. #Set current Win won_last[home_team] = row["Home Team Win"] won_last[visitor_team] = not row["Home Team Win"] #Which team won their last encounter df["Home Win Streak"] = 0 df["Visitor Win Streak"] = 0 win_streak = defaultdict(int) for index, row in df.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] row["Home Win Streak"] = win_streak[home_team] row["Visitor Win Streak"] = win_streak[visitor_team] df.ix[index] = row # Set current win if row["Home Team Win"]: win_streak[home_team] += 1 win_streak[visitor_team] = 0 else: win_streak[home_team] = 0 win_streak[visitor_team] += 1 # The standing of the team df["Home Team Ranks Higher"] = 0 for index , row in df.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] home_rank = standing[standing["Team"] == home_team]["Rk"].values[0] visitor_rank = standing[standing["Team"] == visitor_team]["Rk"].values[0] row["Home Team Rank Higher"] = int(home_rank > visitor_rank) df.ix[index] = row # Which team won their last encounter team regardless of playing at home last_match_winner = defaultdict(int) df["Home Team Won Last"] = 0 for index , row in df.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] teams = tuple(sorted([home_team, visitor_team])) row["Home Team Won Last"] = 1 if last_match_winner[teams] == row["Home Team"] else 0 df.ix[index] = row # Who won this one? winner = row["Home Team"] if row["Home Team Win"] else row["Visitor Team"] last_match_winner[teams] = winner Let us look at the new dataset df.head(2) The scikit-learn package implements the CART (Classification and Regression Trees) algorithm as its default decision tree class The decision tree implementation provides a method to stop the building of a tree to prevent overfitting using the following options: • min_samples_split: can create arbitrary small leaves in order to create a new node in the decision tree • min_samples_leaf: guarantees a minimum number of samples in a leaf resultingfrom a node It is recommended to use min_samples_split or min_samples_leaf to control the number of samples at a leaf node. A very small number will usually mean the tree will overfit, whereas a large number will prevent the tree from learning the data. Another parameter for decision tress is the criterion for creating a decision. Gini impurity and Information gain are two popular ones: • Gini impurity: measures how often a decision node would incorrectly predict a sample's class •`Information gain: indicate how much extra information is gained by the decision node Feature Selection We extract the features from the dataset to use with our scikit-learn’s DecisionTreeClassifier by specifying the columns we wish to use and using the values parameter of a view of the data frame. We use the cross_val_score function to test the result. X_features_only = df[['Home Win Streak', 'Visitor Win Streak', 'Home Team Ranks Higher', 'Home Team Won Last', 'Home Last Win', 'Visitor Last Win']].values import numpy as np from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier(random_state=14) from sklearn.model_selection import cross_val_score scores = cross_val_score(clf, X_features_only, y_true, scoring='accuracy') print(scores) print("Using just the last result from the home and visitor teams") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) [ 0.55961071 0.54878049 0.57212714] Using just the last result from the home and visitor teams Accuracy: 56.0% The accuracy drops to 56% by just selecting the features we made. Is it possible to increase the accuracy by adding more features. from sklearn.preprocessing import LabelEncoder, OneHotEncoder encoding = LabelEncoder() #We will fit this transformer to the home teams so that it learns an integer #representation for each team encoding.fit(df["Home Team"].values) home_teams = encoding.transform(df["Home Team"].values) visitor_teams = encoding.transform(df["Visitor Team"].values) X_teams = np.vstack([home_teams, visitor_teams]).T #we use the OneHotEncoder transformer to encode onehot = OneHotEncoder() #We fit and transform X_teams = onehot.fit_transform(X_teams).todense() X_all = np.hstack([X_features_only, X_teams]) #we run the decision tree on the new dataset clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_all, y_true, scoring='accuracy') print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) Accuracy: 56.6% from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report import sklearn.metrics X_small = df[['Home Team Ranks Higher', 'Home Win Streak']] pred_train, pred_test, tar_train, tar_test = train_test_split(X_small, y_true, test_size=.4) #Build model on training data classifier=DecisionTreeClassifier() classifier=classifier.fit(pred_train,tar_train) predictions=classifier.predict(pred_test) sklearn.metrics.confusion_matrix(tar_test,predictions) array([[ 1, 195], [ 1, 295]]) Confusion Matrix shows the correct and incorrect classifications of our decision tree. The diagonal, 1,295 represent the number of true negative for home team, and the number of true positives, respectively. The 1, on the bottom left, represents the number of false negatives. And the 195 on the top right, the number of false positives. We can also look at the accuracy score which is approximately 0.602, which suggests that the decision tree model has classified 60.2% of the sample correctly as either home team winning or not. sklearn.metrics.accuracy_score(tar_test, predictions) print("Accuracy: {0:.1f}%".format(sklearn.metrics.accuracy_score(tar_test, predictions) * 100)) Accuracy: 60.2% We have an accuracy of 60.2% by selecting only these two features. #Displaying the decision tree from sklearn import tree #from StringIO import StringIO from io import StringIO #from StringIO import StringIO from IPython.display import Image out = StringIO() tree.export_graphviz(classifier, out_file=out) import pydotplus graph=pydotplus.graph_from_dot_data(out.getvalue()) Image(graph.create_png()) For exploratory purposes it can be helpful to test smaller number of variables in order to first get the feel for the decision tree output. The resulting tree starts with the split on X, our first explanatory variable, Home Team Ranks Higher. If the value for Home Team Ranks Higher is less than 4.5, that is home team loose since our binary variable has values of false equal loss and true equal win. By default, SKLearn uses the genie index as the splitting criteria for splitting internal nodes into additional internal or terminal ones. Sometimes called parent and child nodes, as this tree is grown. The goal of the partitioning that occurs when a decision tree is grown is to recursively subdivide in such a way that the values of the target variable for the observations in the terminal or leaf nodes are as similar as possible. Based on the grow criteria that is selected, the growth process continues, often until it over fits the data. And is likely to perform poorly by not adequately generalizing to new data. Notably, while decision trees such as this one are easy to interpret, it’s also important to recognize that small changes in the data or decisions that we make about the modeling approach lead to very different splits. Random forests Random forests averages randomly built decision trees, resulting in an algorithm that reduces the variance of the result. These use subsets of the features which should be able to learn more effectively with more features than normal decision trees. Random forests share many of the same parameters with Decision Trees such as the criterion (Gini Impurity or Entropy/Information Gain), max_features, and min_samples_split. Also, there are some new parameters that are used in the ensemble process: • n_estimators: dictates how many decision trees should be built. A higher value will take longer to run, but will (probably) result in a higher accuracy. • oob_score: If true, the method is tested using samples that aren't in the random subsamples chosen for training the decision trees. • n_jobs: specifies the number of cores to use when training the decision trees in parallel. from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(random_state=14) scores = cross_val_score(clf, X_all, y_true, scoring='accuracy') print("Using full team labels is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) Using full team labels is ranked higher Accuracy: 57.2% This results in an immediate benefit of 57.2 percent by using Random Forest Classifier from sklearn.model_selection import GridSearchCV parameter_space = { "max_features": [2, 10, 'auto'], "n_estimators": [100,], "criterion": ["gini", "entropy"], "min_samples_leaf": [2, 4, 6], } clf = RandomForestClassifier(random_state=14) grid = GridSearchCV(clf, parameter_space) grid.fit(X_all, y_true) print("Accuracy: {0:.1f}%".format(grid.best_score_ * 100)) Accuracy: 61.5% This has a much better accuracy of 61.5 percent! If we wanted to see the parameters used, we can print out the best model that was found in the grid search. print(grid.best_estimator_) RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy', max_depth=None, max_features=2, max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=4, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=1, oob_score=False, random_state=14, verbose=0, warm_start=False)
http://adataanalyst.com/machine-learning/predicting-nba-winners-decision-trees-random-forests-scikit-learn/
CC-MAIN-2018-09
en
refinedweb
The first issue to tackle is the lifecycle of the server tests, since it will need to break from the default behavior of JUnit’s lifecycle management. To start, need a way to tell the server to start up and initialize. This should be done using setUp() method. Once this method returns, it is assumed that the server is ready to receive calls. Next, need a way to tell the server that it can shutdown and clean up. This should be done using the tearDown() method. This method will only be called in the case that all clients are finished making their calls to the server. This behavior is all provided by having the server test case class extend org.jboss.jrunit.ServerTestCase instead of junit.framework.TestCase. The ServerTestCase actually extends the TestCase class itself, but overrides a few it’s methods to get the desired behavior. The server implementation may also have a test method, which will be called just after the setUp(), as in the case of regular JUnit test runs. This test method can contain asserts and are suggested to be used for validation of server data and metrics. A few important points… there can be only ONE test method within a server test case. This is because JUnit creates a new instance of the test class for each test method run. Therefore, if had multiple tests, would be multiple instances of the server test case created. To change this would require a sizable change to the JUnit code, so please just use one test method (or contribute the required change ). Another important point is that the tearDown() method may be called even while a test method is being run. This is intentional and allows for the test method to loop until the tearDown() method is called. So a possible example of where this could be used is: ... public void testServerMetrics() { while(!stop) { // collect data here } } protected void tearDown() { stop = true; // so will cause testServerMetrics() to break out of loop // do shutdown and clean up code. } ... For the client test case, there is no requirement for jrunit other than they extend the junit.framework.TestCase class and conform to normal constraints of a JUnit test case. Lastly, there is the org.jboss.jrunit.TestDriver class, which represents the driver for the client and server tests. This class will spawn new test harnesses that the client and server tests cases will run within. The test driver will then communicate to the test harnesses using a JGroups message bus to control the test lifecycle for the server test case and all the client tests cases as well as obtaining the results from those test runs. The logical order of a test run as controlled by the test runner is: Spawn a new test harness process for each client and server test case. Wait for confirmation that all test harnesses have been created and their message bus has been started. Once confirmation has been received, wait for server test case to start up (i.e. call the setUp() method on the server test case). Otherwise, if confirmation not received, kill all the processes and return error to JUnit. Once the confirmation of the server startup has been received, tell all the test cases to run (client and server). Otherwise, if confirmation not received, send abort message to all the test harnesses. Wait for results from all the client test cases. Once all the client test results are received, tell the server to tear down (i.e. call the tearDown() method on the server test case). Otherwise, if results not received, kill all the processes and return error to JUnit. Wait for server test results (if server test case had a test method). Process all results by adding them to root JUnit TestResult?, which will be reported via normal JUnit reporting. Wait for server torn down message, indicating it has successfully cleaned up. Shutdown message bus and end root test run, returning JUnit execution thread. The only user coding required for the test driver is to implement a class that extends the org.jboss.jrunit.TestDriver abstract class and implement the declareTestClasses() method. Within this method, call the TestDriver’s addTestClasses() method and specify the client test case class, the number of clients to spawn, and the server test case class. JRunit can also utilize the benchmark decorators to provide benchmark results as well as regular JUnit test results. org.jboss.jrunit.decorators.ThreadLocalDecorator (and all the other decorators that accept number of threads and loops) - for each thread specified in the number of threads, there will be a new instance of the test created. For the number of loops specified, the test methods will be called on each test instance. So for example, if specify 3 threads and 10 loops, there will be three instances of the test class created and each instance will have their test methods called 10 times by each of their respective threads. An example class that demonstrates this would be: public class SimpleThreadLoopCounter extends TestCase { private static int staticCounter = 0; private static int staticMethodCounter = 0; private int localCounter = 0; public static Test suite() { return new ThreadLocalDecorator(SimpleThreadLoopCounter.class, 3, 10, 0, true, true); } public SimpleThreadLoopCounter() { staticCounter++; } public void testCounter() throws Exception { System.out.println("staticCounter = " + staticCounter); System.out.println("staticMethodcounter = " + ++staticMethodCounter); System.out.println("localCounter = " + ++localCounter); } } When this is run, the last entry will be: staticCounter = 3 staticMethodcounter = 30 localCounter = 10 Another issue is the way junit treats test classes with multiple test methods. For each test method that junit runs within a test class, it will create a new test instance to run that test method. To illustrate this, if copied the testCounter() method from the example above (calling it testCounter2() for example), the last lines printed for the test run would be: staticCounter = 6 staticMethodcounter = 60 localCounter = 10 Issues with jrunit and decorators: The ServerTestHarness will not work if the numberOfThreads is more than 1. I don't see this as being that big of a problem from the point of view that the numberOfThreads is to simulate multiple clients running at the same time. If want to do this using the ServerTestHarness, can actually spawn multiple clients through it. Eventhough they won't be running concurrently with the same processes, they will be running concurrently with seperate processes. Having the ability to use the loop parameter is needed though so can keep the clients calling on the server for an extended period of time (or iterations). Therefore, if running remote tests and want to use the ThreadLocalDecorator for benchmark data, use the following ThreadLocalDecorator constructor, which will default the number of threads to one: public ThreadLocalDecorator(Class testClazz, int loops)
http://docs.jboss.org/jrunit/docs/ch02.html
CC-MAIN-2018-09
en
refinedweb
gtalmes' Favorite Snippets - All / - JavaScript / - HTML / - PHP / - CSS / - Ruby / - Objective C « Prev [Page 1 of 1] Next » JavaScript jquery saved by 1 person JQuery event pass data posted on June 16, 2009 by jQuery iframe object jquery events Shared child sharing Parent saved by 4 people inherit.js - jQuery Sharing between Parents and iFrames posted on May 29, 2009 by jQuery jquery preload images saved by 7 people jQuery Preload images posted on April 27, 2009 by jQuery event jquery namespace saved by 1 person jQuery event namespace posted on March 12, 2009 by Other javascript textmate jquery saved by 6 people Skeleton for a JQuery plugin posted on March 2, 2009 by jQuery rss jquery saved by 17 people jQuery: Parse RSS Feed posted on February 22, 2009 by jQuery ajax jquery saved by 9 people jQuery: Simple Ajax Request + Event Handlers posted on February 5, 2009 by jQuery url jquery variable param saved by 26 people Retrieve URL params with jQuery posted on January 27, 2009 by jQuery javascript jquery saved by 13 people jQuery snippet to convert numbers into US phone number format as they're typed posted on January 27, 2009 by JavaScript data jquery store saved by 7 people The jQuery Data Store posted on November 13, 2008 by CSS css transparency saved by 13 people CSS: Transparency for all browsers posted on February 21, 2008 by PHP mysql php textmate security sql-injection saved by 171 people Anti-SQL Injection Function posted on May 27, 2007 by CSS css list bullets saved by 81 people Background images for bullets list posted on August 28, PHP mysql search saved by 137 people Simple MySQL Search Function posted on July 1, 2006 by CSS css clear float saved by 271 people Clear floats without structural markup posted on June 29, 2006 by « Prev [Page 1 of 1] Next »
http://snipplr.com/favorites/gtalmes/
CC-MAIN-2018-09
en
refinedweb
In order to implement a Geant4-DNA based Physics list, please follow the two steps indicated below for any G4EmDNAPhysics* Physics constructors. 1) Declaration file (eg. PhysicsList.hh) #ifndef PhysicsList_h #define PhysicsList_h 1 #include "G4VModularPhysicsList.hh" #include "globals.hh" class G4VPhysicsConstructor; class PhysicsList: public G4VModularPhysicsList { public: PhysicsList(); virtual ~PhysicsList(); }; #endif 2) Implementation file (eg. PhysicsList.cc) #include "PhysicsList.hh" #include "G4SystemOfUnits.hh" #include "G4EmDNAPhysics.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysicsList::PhysicsList() : G4VModularPhysicsList() { SetDefaultCutValue(1*nanometer); SetVerboseLevel(1); // Geant4-DNA physics RegisterPhysics(new G4EmDNAPhysics()); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysicsList::~PhysicsList() {} Important notes - The above Physics list proposes a default production cut for secondaries (electrons, positrons, gammas) set to 1 nm. The Geant4-DNA processes are all discrete processes; as such, they simulate explicitly all interactions and do not use any production cut, so this 1 nm cut will have no effect on the Geant4-DNA Physics results. However, in the case users need to combine Geant4-DNA processes with other Geant4 electromagnetic processes (for eg. other electron processes) which use cuts for secondary production, we have indicated how to specify this cut value. - The user may want to write his/her own PhysicsList class based on Geant4-DNA physics processes and models. In order to do this, we recommend to use the method described above (creation of a PhysicsList class that uses the G4EmDNAPhysics* constructors) and then copy the Geant4 default G4EmDNAPhysics* class in his/her own application, so that he/she can modify this local copy of the G4EmDNAPhysics* class according to his/her needs. Remember that the default G4EmDNAPhysics* classes are located in the $G4INSTALL/source/physics_lists/constructors/electromagnetic directory. List of available Geant4-DNA Physics constructors for liquid water Several Physics constructors are available in Geant4 for simulations in liquid water, they are listed below. - G4EmDNAPhysics : default constructor - G4EmDNAPhysics_option1 (beta) : elastic scattering is simulated using the so-called « WentzelVI » model initially available in Geant4 « standard » electromagnetic Physics, and now extended down to the eV scale (« G4LowEWentzelVIModel » model). This should allow for a faster simulation of elastic scattering but with reduced accuracy. - G4EmDNAPhysics_option2 : accelerated version of G4EmDNAPhysics - G4EmDNAPhysics_option4 : contains electron elastic and inelastic models by D. Emfietzoglou, I. Kyriakou, S. Incerti - G4EmDNAPhysics_option5 : accelerated version of G4EmDNAPhysics_option4 - G4EmDNAPhysics_option6 : contains CPA100 electron elastic and inelastic models by M. C. Bordage, M. Terrissol, S. Incerti Other constructors are preliminary or obsolete constructors.
http://geant4-dna.in2p3.fr/styled-3/styled-9/index.html
CC-MAIN-2018-09
en
refinedweb
Whilst we do not support Python 3 there is a way to make python 2.7 feel and act a lot more like Python 3… import the future… TL;DR Stick this at the top of your code: # encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals Enjoy something more like python 3. How to get that Python-3 experience Future is a “real” python module and it contains a-lot of things that are nice like print as a function and true division by default. With the module you can: - Use print as a function i.e. print('Hello World!') not print 'Hello World!' , for why this is good see this stack exchange Q&A. - The ‘/’ or division operator now will always return floats rather than flooring the value. i.e. 1/2 = 0.5 not 0, in python 2.7 you have to type 1.0/2 to get 0.5 - There is a list of all of the glory discussed in a PEP here. So now to add all of this to the program. As the __future__ module is a pseudo module the statement that “imports” it must be the first line of code. Not doing this will give a fatal error. We also can’t use * wild card and must list the parts of the library that we want to import. So to import future add this to the top of your code: from __future__ import absolute_import, division, print_function, unicode_literals It should also be noted that we recommend using UTF-8, so save your file using UTF-8 encoding. Once you have done that add this as the very first line in your python file: # encoding: utf-8 Save and upload your code to your robot and enjoy the Python-3 Experience™.
http://hr-robocon.org/docs/upgrading-to-python-3
CC-MAIN-2018-09
en
refinedweb
Contents Abstract This PEP describes an interpretation of multiline string constants for Python. It suggests stripping spaces after newlines and stripping a newline if it is first character after an opening quotation. Rationale This PEP proposes an interpretation of multiline string constants in Python. Currently, the value of string constant is all the text between quotations, maybe with escape sequences substituted, e.g.: def f(): """ la-la-la limona, banana """ def g(): return "This is \ string" print repr(f.__doc__) print repr(g()) prints: '\n\tla-la-la\n\tlimona, banana\n\t' 'This is \tstring' This PEP suggest two things: - ignore the first character after opening quotation, if it is newline - ignore in string constants all spaces and tabs up to first non-whitespace character, but no more than current indentation. After applying this, previous program will print: 'la-la-la\nlimona, banana\n' 'This is string' To get this result, previous programs could be rewritten for current Python as (note, this gives the same result with new strings meaning): def f(): """\ la-la-la limona, banana """ def g(): "This is \ string" Or stripping can be done with library routines at runtime (as pydoc does), but this decreases program readability. Implementation I'll say nothing about CPython, Jython or Python.NET. In original Python, there is no info about the current indentation (in spaces) at compile time, so space and tab stripping should be done at parse time. Currently no flags can be passed to the parser in program text (like from __future__ import xxx). I suggest enabling or disabling of this feature at Python compile time depending of CPP flag Py_PARSE_MULTILINE_STRINGS. Alternatives New interpretation of string constants can be implemented with flags 'i' and 'o' to string constants, like: i""" SELECT * FROM car WHERE model = 'i525' """ is in new style, o"""SELECT * FROM employee WHERE birth < 1982 """ is in old style, and """ SELECT employee.name, car.name, car.price FROM employee, car WHERE employee.salary * 36 > car.price """ is in new style after Python-x.y.z and in old style otherwise. Also this feature can be disabled if string is raw, i.e. if flag 'r' specified.
http://docs.activestate.com/activepython/3.6/peps/pep-0295.html
CC-MAIN-2018-09
en
refinedweb
I am trying to find a way to break the split the lines of text in a scanned document that has been adaptive thresholded. Right now, I am storing the pixel values of the document as unsigned ints from 0 to 255, and I am taking the average of the pixels in each line, and I split the lines into ranges based on whether the average of the pixels values is larger than 250, and then I take the median of each range of lines for which this holds. However, this methods sometimes fails, as there can be black splotches on the image. Is there a more noise-resistant way to do this task? EDIT: Here is some code. "warped" is the name of the original image, "cuts" is where I want to split the image. warped = threshold_adaptive(warped, 250, offset = 10) warped = warped.astype("uint8") * 255 # get areas where we can split image on whitespace to make OCR more accurate color_level = np.array([np.sum(line) / len(line) for line in warped]) cuts = [] i = 0 while(i < len(color_level)): if color_level[i] > 250: begin = i while(color_level[i] > 250): i += 1 cuts.append((i + begin)/2) # middle of the whitespace region else: i += 1 From your input image, you need to make text as white, and background as black You need then to compute the rotation angle of your bill. A simple approach is to find the minAreaRect of all white points ( findNonZero), and you get: Then you can rotate your bill, so that text is horizontal: Now you can compute horizontal projection ( reduce). You can take the average value in each line. Apply a threshold th on the histogram to account for some noise in the image (here I used 0, i.e. no noise). Lines with only background will have a value >0, text lines will have value 0 in the histogram. Then take the average bin coordinate of each continuous sequence of white bins in the histogram. That will be the y coordinate of your lines: Here the code. It's in C++, but since most of the work is with OpenCV functions, it should be easy convertible to Python. At least, you can use this as a reference: #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main() { // Read image Mat3b img = imread("path_to_image"); // Binarize image. Text is white, background is black Mat1b bin; cvtColor(img, bin, COLOR_BGR2GRAY); bin = bin < 200; // Find all white pixels vector<Point> pts; findNonZero(bin, pts); // Get rotated rect of white pixels RotatedRect box = minAreaRect(pts); if (box.size.width > box.size.height) { swap(box.size.width, box.size.height); box.angle += 90.f; } Point2f vertices[4]; box.points(vertices); for (int i = 0; i < 4; ++i) { line(img, vertices[i], vertices[(i + 1) % 4], Scalar(0, 255, 0)); } // Rotate the image according to the found angle Mat1b rotated; Mat M = getRotationMatrix2D(box.center, box.angle, 1.0); warpAffine(bin, rotated, M, bin.size()); // Compute horizontal projections Mat1f horProj; reduce(rotated, horProj, 1, CV_REDUCE_AVG); // Remove noise in histogram. White bins identify space lines, black bins identify text lines float th = 0; Mat1b hist = horProj <= th; // Get mean coordinate of white white pixels groups vector<int> ycoords; int y = 0; int count = 0; bool isSpace = false; for (int i = 0; i < rotated.rows; ++i) { if (!isSpace) { if (hist(i)) { isSpace = true; count = 1; y = i; } } else { if (!hist(i)) { isSpace = false; ycoords.push_back(y / count); } else { y += i; count++; } } } // Draw line as final result Mat3b result; cvtColor(rotated, result, COLOR_GRAY2BGR); for (int i = 0; i < ycoords.size(); ++i) { line(result, Point(0, ycoords[i]), Point(result.cols, ycoords[i]), Scalar(0, 255, 0)); } return 0; }
https://codedump.io/share/0osxbtlIqCF7/1/split-text-lines-in-scanned-document
CC-MAIN-2018-09
en
refinedweb
Picking up this thread as part of the PEP 562 and PEP 549 review. I like PEP 562 most, but I propose to add special-casing for `__dir__`. Not quite as proposed above (making the C level module_dir() look for `__all__`) but a bit more general -- making module_dir() look for `__dir__` and call that if present and callable. Ivan what do you think of that idea? It should be simple to add to your existing implementation. () On Tue, Sep 12, 2017 at 1:26 AM, Ivan Levkivskyi <levkivskyi at gmail.com> wrote: > @Anthony > > module.__getattr__ works pretty well for normal access, after being > > imported by another module, but it doesn't properly trigger loading by > > functions defined in the module's own namespace. > > The idea of my PEP is to be very simple (both semantically and in terms > of implementation). This is why I don't want to add any complex logic. > People who will want to use __getattr__ for lazy loading still can do this > by importing submodules. > > @Nathaniel @INADA > > The main two use cases I know of for this and PEP 549 are lazy imports > > of submodules, and deprecating attributes. > > Yes, lazy loading seems to be a popular idea :-) > I will add the simple recipe by Inada to the PEP since it will already > work. > > @Cody > > I still think the better way > > to solve the custom dir() would be to change the module __dir__ > > method to check if __all__ is defined and use it to generate the > > result if it exists. This seems like a logical enhancement to me, > > and I'm planning on writing a patch to implement this. Whether it > > would be accepted is still an open issue though. > > This seems a reasonable rule to me, I can also make this patch if > you will not have time. > > @Guido > What do you think about the above idea? > > -- > Ivan > > > -- --Guido van Rossum (python.org/~guido) -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/python-ideas/2017-November/047806.html
CC-MAIN-2018-09
en
refinedweb
#include <genesis/utils/math/twobit_vector.hpp> Definition at line 41 of file twobit_vector.hpp. Constructor that initializes the vector with size many zero values. Definition at line 118 of file twobit_vector.cpp. Clear the vector, so that it contains no data. Definition at line 405 of file twobit_vector.cpp. Return a single word of the vector. This is useful for external functions that want to directly work on the underlying bit representation. Definition at line 176 of file twobit_vector.cpp. Return a single word of the vector. This is useful for external functions that want to directly work on the underlying bit representation. Definition at line 187 of file twobit_vector.cpp. Return the number of words (of type WordType) that are used to store the values in the vector. Definition at line 140 of file twobit_vector.cpp. Get the value at a position in the vector. Definition at line 149 of file twobit_vector.cpp. Calculate a hash value of the vector, based on its size() and the xor of all its words. This is a simple function, but might just be enough for using it in a hashmap. Definition at line 198 of file twobit_vector.cpp. Insert a value at a position. The size() is increased by one. Definition at line 290 of file twobit_vector.cpp. Inequality operator, opposite of operator==(). Definition at line 230 of file twobit_vector.cpp. Equality operator. Definition at line 214 of file twobit_vector.cpp. Definition at line 165 of file twobit_vector.cpp. Remove the value at a position. The size() is decreased by one. Definition at line 342 of file twobit_vector.cpp. Set a value at a position in the vector. Definition at line 269 of file twobit_vector.cpp. Return the size of the vector, that is, how many values (of type ValueType) it currently holds. Definition at line 131 of file twobit_vector.cpp. Validation function that checks some basic invariants. This is mainly useful in testing. The function checks whether the vector is correctly sized and contains zero padding at its end. Definition at line 241 of file twobit_vector.cpp. Underlying word type for the bitvector. We use 64bit words to store the 2bit values (of type ValueType), so that we get best speed on modern architectures. Definition at line 55 of file twobit_vector.hpp. Value Type enumeration for the elements of a TwobitVector. The values 0-3 are named A, C, G and T, respectively, in order to ease the use with nucleotide sequences. The underlying value of the enum is WordType, so that a cast does not need to convert internally. Definition at line 66 of file twobit_vector.hpp. Constant that holds the number of values (of tyoe ValueType) that are stored in a single word in the vector. As we use 64bit words, this value is 32. Definition at line 79 of file twobit_vector.hpp.
http://doc.genesis-lib.org/classgenesis_1_1utils_1_1_twobit_vector.html
CC-MAIN-2019-09
en
refinedweb
React Native gives us a great range of components to design and build fully native UI’s, such as buttons, views, lists, progress bars and more. We also have form inputs components like TextInput and Picker, but when we use them multiple times across an application, their use can start to be repetitive since they’re a bit basic. Let’s see how can we build our own form inputs. 🐊 Alligator.io recommends ⤵Fullstack Advanced React & GraphQL by Wes Bos Custom Input and Select There are multiple benefits to having our own input and select components. For example, they both usually have labels and a similar style throughout the app, so we can group that logic together. Additionally, we can provide a simpler and common API. Both TextInput and Picker use different properties for getting and updating the value: value vs selectedValue and onChangeText vs onValueChange. Furthermore, every time we create a Picker component we must create a list of Picker.Item, which can be avoided if we assume a convention and pass an array of key-values to the component. In order to solve these issues, let’s build custom AppInput and AppSelect components. Let’s start by creating a BaseInput component where we can add common functionality, such as the label: import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ baseInput: { paddingVertical: 6, }, }); const BaseInput = ({ children, label }) => ( <View style={styles.baseInput}> <Text>{label}</Text> {children} </View> ); I added a common style using the StyleSheet API and a label using the Text component. In order to reuse that and to be able to pass any kind of input component to it, we’re rendering children just below the label. In that way, we can easily create the AppInput component: import { TextInput } from 'react-native'; // ... const AppInput = ({ children, value, onChange, ...props }) => ( <BaseInput {...props}> <TextInput value={value} onChangeText={onChange} /> </BaseInput> ); We’re basically passing the properties that the AppInput doesn’t use down to the BaseInput component, along with a TextInput. Applying the same technique, we can create a AppSelect component using React Native’s Picker component: import { Picker } from 'react-native'; // ... const AppSelect = ({ children, value, onChange, items, ...props }) => ( <BaseInput {...props}> <Picker selectedValue={value} onValueChange={onChange}> {items.map(item => ( <Picker.Item key={item.value} label={item.label} value={item.value} /> ))} </Picker> </BaseInput> ); Finally, we can use them as follows in our App component: class App extends React.Component { state = { input: '', select: {}, }; render() { const { input, select } = this.state; return ( <View style={{ flex: 1, padding: 40 }}> <AppInput label="Name" value={input} onChange={input => this.setState({ input })} /> <AppSelect label="Country" items={countries} value={select} onChange={select => this.setState({ select })} /> </View> ); } } As you can see, they share the common label, value and onChange props, making the code simpler and easier to use and understand. Styles Composition So far the BaseInput component has a default baseInput style that we’re applying from the stylesheet, but… What if we want to override it? React Native let’s us pass an array to the style property on the components, so we can take advantage of that by passing an optional style property. Let’s do that in BaseInput: const BaseInput = ({ style, children, label }) => ( <View style={[styles.baseInput, style]}> <Text>{label}</Text> {children} </View> ); Given the fact that we’re passing down the properties on the AppInput and AppSelect components, now if we pass-in a style prop it will override the default styles: <AppInput style={{ flex: 1, paddingVertical: 33 }} label="Name" value={input} onChange={input => this.setState({ input })} /> Following that technique, we can easily customize the other parts of the components by passing multiple style props, such as rootStyle, inputStyle, etc. But I’ll leave that up to you 😜. Wrapping Up We’ve seen how to create our own form input components in React Native so that we can reuse common functionality and our code becomes more DRY, concise and easier to read and understand. Don’t forget to check out the online demo! Stay cool 🦄
https://alligator.io/react/custom-inputs/
CC-MAIN-2019-09
en
refinedweb
This page explains the quotas and limits for Google Kubernetes Engine clusters, nodes, and GKE API requests. GKE's per-project limits are: - Maximum of 50 clusters per zone, plus 50 regional clusters per region. - Maximum of 5000 nodes per cluster. - Maximum of 1000 nodes per cluster if you use the GKE ingress controller. - 100 Pods per node. - 300,000 containers. The rate limit for the GKE API is 10 requests per second. You might also encounter Compute Engine resource quotas. Additionally, for projects with default regional Compute Engine CPUs quota, container clusters are limited to three per region. Resource Quotas Starting with GKE 1.11.4, for clusters with five nodes or fewer, gke-resource-quotas objects are listed in the output of kubectl get resourcequotas --all-namespaces. Currently the quotas are set to a very large number, so they are virtually unlimited.
https://cloud.google.com/kubernetes-engine/quotas
CC-MAIN-2019-09
en
refinedweb
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards A safe<T, PP , EP> can be used anywhere a type T can be used. Any expression which uses this type is guaranteed to return an arithmetically correct value or to trap in some way. This type inherits all the notation, associated types and template parameters and valid expressions of SafeNumeric types. The following specify additional features of this type. Implements all expressions and only those expressions defined by the SafeNumeric<T> type requirements. Note that all these expressions are constexpr. Thus, the result type of such an expression will be another safe type. The actual type of the result of such an expression will depend upon the specific promotion policy template parameter. When a binary operand is applied to two instances of safe<T, PP, EP>on of the following must be true: The promotion policies of the two operands must be the same or one of them must be void The exception policies of the two operands must be the same or one of them must be void If either of the above is not true, a compile error will result. The most common usage would be safe<T> which uses the default promotion and exception policies. This type is meant to be a "drop-in" replacement of the intrinsic integer types. That is, expressions involving these types will be evaluated into result types which reflect the standard rules for evaluation of C++ expressions. Should it occur that such evaluation cannot return a correct result, an exception will be thrown. There are two aspects of the operation of this type which can be customized with a policy. The first is the result type of an arithmetic operation. C++ defines the rules which define this result type in terms of the constituent types of the operation. Here we refer to these rules as "type promotion" rules. These rules will sometimes result in a type which cannot hold the actual arithmetic result of the operation. This is the main motivation for making this library in the first place. One way to deal with this problem is to substitute our own type promotion rules for the C++ ones. The following program will throw an exception and emit an error message at runtime if any of several events result in an incorrect arithmetic result. Behavior of this program could vary according to the machine architecture in question. #include <exception> #include <iostream> #include <safe_integer.hpp> void f(){ using namespace boost::numeric; safe<int> j; try { safe<int> i; std::cin >> i; // could overflow ! j = i * i; // could overflow } catch(std::exception & e){ std::cout << e.what() << std::endl; } std::cout << j; } The term "drop-in replacement" reveals the aspiration of this library. In most cases, this aspiration is realized. In the following example, the normal implicit conversions function the same for safe integers as they do for built-in integers. //>; int main(){ const long x = 97; f(x); // OK - implicit conversion to int const safe_t y = 97; f(y); // Also OK - checked implicit conversion to int return 0; } When the safe<long> is implicitly converted to an int when calling f, the value is checked to be sure that it is within the legal range of an int and will invoke an exception if it cannot. We can easily verify this by altering the exception handling policy in the above example to loose_trap_policy. This will invoke a compile time error on any conversion might invoke a runtime exception. //, native, loose_trap_policy>; int main(){ const long x = 97; f(x); // OK - implicit conversion to int can never fail const safe_t y = 97; f(y); // could overflow so trap at compile time return 0; } But this raises it's own questions. We can see that in this example, the program can never fail: The value 97 is assigned to y y is converted to an int and used as an argument to f The conversion can never fail because the value of 97 can always fit into an int. But the library code can't detect this and emits the checking code even though it's not necessary. This can be addressed by using a safe_literal. A safe literal can contain one and only one value. All the functions in this library are marked constexpr. So it can be determined at compile time that conversion to an int can never fail and no runtime checking code need be emitted. Making this small change will permit the above example to run with zero runtime overhead while guaranteeing that no error can ever occur. // Copyright (c) 2018 Robert Ramey // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at //) #include <boost/safe_numerics/safe_integer.hpp> #include <boost/safe_numerics/safe_integer_literal.hpp> using namespace boost::safe_numerics; int f(int i){ return i; } template<intmax_t N> using safe_literal = safe_signed_literal<N, native, loose_trap_policy>; int main(){ const long x = 97; f(x); // OK - implicit conversion to int const safe_literal<97> y; f(y); // OK - y is a type with min/max = 97; return 0; } With this trivial example, such efforts would hardly be deemed necessary. But in a more complex case, perhaps including compile time arithmetic expressions, it could be much more difficult to verify that the constant is valid and/or no checking code is needed. And there is also possibility that over the life time of the application, the compile time constants might change, thus rendering any ad hoc analyse obsolete. Using safe_literal will future-proof your code against well-meaning, but code-breaking updates. Another way to avoid arithmetic errors like overflow is to promote types to larger sizes before doing the arithmetic. Stepping back, we can see that many of the cases of invalid arithmetic wouldn't exist if the result types were larger. So we can avoid these problems by replacing the C++ type promotion rules for expressions with our own rules. This can be done by specifying a promotion policy . The policy stores the result of an expression in the smallest size type that can accommodate the largest value that an expression can yield. No checking for exceptions is necessary. The following example illustrates this. automatic #include <boost/safe_numerics/safe_integer.hpp> #include <iostream> int main(int, char[]){ using safe_int = safe< int, boost::numeric::automatic, boost::numeric::default_exception_policy >; safe_int i; std::cin >> i; // might throw exception auto j = i * i; // won't ever trap - result type can hold the maximum value of i * i static_assert(boost::numeric::is_safe<decltype(j)>::value); // result is another safe type static_assert( std::numeric_limits<decltype(i * i)>::max() >= std::numeric_limits<safe_int>::max() * std::numeric_limits<safe_int>::max() ); // always true return 0; }
https://www.boost.org/doc/libs/develop/libs/safe_numerics/doc/html/safe.html
CC-MAIN-2020-50
en
refinedweb
The line plot is the most iconic of all the plots. To draw one in matplotlib, use the plt.plot() function. Pass it a list of numbers. It uses them as the y-axis values and the list indexes for the x-axis. # Square numbers from 0-10 inclusive squared = [x**2 for x in range(11)] plt.plot(squared) plt.show() Easy. In this article, I’ll show you how to add axis labels, plot multiple lines and customise your plot to expertly showcase your data. Like scatter plots, line plots show the relationship between two variables. Unlike scatter plots, they are often used to measure how a variable changes over time. Thus we would use a line plot to show how the stock market has performed rather than a scatter plot. Line plots are excellent for time series data because we can put time on the x-axis and whatever we are measuring on the y-axis. Let’s import the modules we’ll be using. import matplotlib.pyplot as plt import numpy as np # I prefer this style to the default plt.style.use('seaborn') Let’s look at a classic example – the US stock market. Matplotlib Line Plot Example This plot shows the S&P 500 index over 2019 using matplotlib’s default settings. The S&P 500 tracks the top 500 US stocks and so is a reflection of the stock market overall. You can download the data for free online. I’ve split the data into two numpy arrays. One for the S&P 500 values (e.g. sp2019) and one for the dates (e.g. dates2019). Note: the dates only include business days because the stock market is only open on business days. # First 5 business days in 2019 >>> bus2019[:5] [numpy.datetime64('2019-01-01'), numpy.datetime64('2019-01-02'), numpy.datetime64('2019-01-03'), numpy.datetime64('2019-01-04'), numpy.datetime64('2019-01-07')] # First 5 S&P 500 values in 2019 # It contains some missing values (NaN - Not a Number) >>> sp2019[:5] array([[ nan], [2510.03], [2447.89], [2531.94], [2549.69]]) There are gaps in the plot because of the missing values. But the data is good enough for our purposes. To plot this, we pass sp2019 to plt.plot() and then call plt.show(). plt.plot(sp2019) plt.show() Great. It shows the S&P 500 values on the y-axis but what are the numbers on the x-axis? If you only pass a list or numpy array, matplotlib uses the list indexes for the x-axis values. >>> len(sp2019) 250 As there are 250 values in sp2019, the x-axis ranges from 0 to 250. In this case, it would be better if we had dates on the x-axis. To do this, we pass two arguments to plt.plot(). First the x-axis values, then the y-axis ones. # x-axis for dates, y-axis for S&P 500 index plt.plot(dates2019, sp2019) plt.show() Matplotlib spaces the dates out evenly and chooses the best level of accuracy. For this plot, it chose months. It would be annoying if it chose dates down to the day. Finally, let’s add some axis labels and a title. plt.plot(bus2019, sp2019) plt.title('S&P500 Index - 2019') plt.xlabel('Date') plt.ylabel('Index') plt.show() Perfect. To save space, I will exclude the lines of code that set the axis labels and title. But make sure to include them in your plots. Matplotlib Line Plot Color Color is an incredibly important part of plotting and deserves an entire article in itself. Check out the Seaborn docs for a great overview. Color can make or break your plot. Some color schemes make it ridiculously easy to understand the data and others make it impossible. However, one reason to change the color is purely for aesthetics. We choose the color of points in plt.plot() with the keyword c or color. The default is blue. You can set any color you want using an RGB or RGBA tuple (red, green, blue, alpha). Each element of these tuples is a float in [0.0, 1.0]. You can also pass a hex RGB or RGBA string such as ‘#1f1f1f’. However, most of the time you’ll use one of the 50+ built-in named colors. The most common are: - ‘b’ or ‘blue’ - ‘r’ or ‘red’ - ‘g’ or ‘green’ - ‘k’ or ‘black’ - ‘w’ or ‘white’ Here’s the plot of the S&P500 index for 2019 using different colors For each plot, call plt.plot() with dates2019 and sp2019. Then set color (or c) to your choice # Blue (the default value) plt.plot(dates2019, sp2019, color='b') # Red plt.plot(dates2019, sp2019, color='r') # Green plt.plot(dates2019, sp2019, c='g') # Black plt.plot(dates2019, sp2019, c='k') Matplotlib Line Plot Multiple Lines If you draw multiple line plots at once, matplotlib colors them differently. This makes it easy to recognise the different datasets. Let’s plot the S&P500 index for 2018 and 2019 on one plot to compare how it performed each month. You do this by making two plt.plot() calls before calling plt.show(). plt.plot(sp2019) plt.plot(sp2018) plt.show() This looks great. It’s very easy to tell the orange and blue lines apart. But there are two problems: - The date axis doesn’t show dates - We don’t know which line is for which year. Matplotlib x axis label To solve the first problem, we need to rename the numbers on the x-axis. In matplotlib, they are called x-ticks and so we use the plt.xticks() function. It accepts two arguments: plt.xticks(ticks, labels) - ticks – a list of positions to place the ticks - labels – a list of labels to describe each tick In this case, the ticks are [0, 50, 100, 150, 200, 250] and the labels are the months of the year. plt.plot(sp2019) plt.plot(sp2018) # Create ticks and labels ticks = [0, 50, 100, 150, 200, 250] labels = ['Jan', 'Mar', 'May', 'Jul', 'Sep', 'Nov'] # Pass to xticks plt.xticks(ticks, labels) plt.show() Now let’s find out which line is for which year. Matplotlib Line Plot Legend To add a legend we use the plt.legend() function. This is easy to use with line plots. In each plt.plot() call, label each line with the label keyword. When you call plt.legend(), matplotlib will draw a legend with an entry for each line. # Add label to 2019 plot plt.plot(sp2019, label='2019') # Add label to 2018 plot plt.plot(sp2018, label='2018') # Call plt.legend to display it plt.legend() plt.xticks(ticks, labels) plt.show() Perfect. We now have a finished plot. We know what all the axes represent and know which line is which. You can see that 2019 was a better year almost every month. By default, matplotlib draws the legend in the ‘best’ location. But you can manually set it using the loc keyword and one of these 10, self-explanatory, strings: - ‘upper right’, ‘upper left’, ‘upper center’ - ‘lower right’, ‘lower left’, ‘lower center’ - ‘center right’ or ‘center left’ - ‘right’ or ‘center’ (for some reason, ‘left’ is not an option) Here are some examples of putting the legend in different locations Best practice is to place your legend somewhere where it doesn’t obstruct the plot. Matplotlib Linestyle There are several linestyles you can choose from. They are set with the linestyle or ls keyword in plt.plot(). Their syntax is intuitive and easy to remember. Here are the square numbers with all possible linestyles, For each plot, call plt.plot(squared) and set linestyle or ls to your choice # Solid (default) plt.plot(squared, linestyle='-') # Dashed plt.plot(squared, linestyle='--') # Dashdot plt.plot(squared, ls='-.') # Dotted plt.plot(squared, ls=':') You can also pass the linestyle names instead of the short form string. The following are equivalent: - ‘solid’ or ‘-‘ - ‘dashed’ or ‘–‘ - ‘dashdot’ or ‘-.’ - ‘dotted’ or ‘:’ Matplotlib Line Thickness You can set the line thickness to any float value by passing it to the linewidth or lw keyword in plt.plot(). Here are the square numbers with varying line widths. Smaller numbers mean thinner lines. plt.plot(squared, linewidth=1) plt.plot(squared, linewidth=3.25) plt.plot(squared, lw=10) plt.plot(squared, lw=15.35) Matplotlib Line Width You can set the line width to any float value by passing it to the linewidth or lw keyword in plt.plot(). Here are the square numbers with varying line widths Matplotlib Line Plot with Markers By default, plt.plot() joins each of the values with a line and doesn’t highlight individual points. You can highlight them with the marker keyword. There are over 30 built-in markers to choose from. Plus you can use any LaTeX expression and even define your own shapes. We’ll cover the most common ones. Like most things in matplotlib, the syntax is intuitive. Either, the shape of the string reflects the shape of the marker, or the string is a single letter that matches the first letter of the shape. - ‘o’ – circle - ‘^’ – triangle up - ‘s’ – square - ‘+’ – plus - ‘D’ – diamond - ‘$…$’ – LaTeX syntax e.g. ‘$\pi$’ makes each marker the Greek letter π. Let’s see some examples For each plot, call plt.plot(squared) and set marker to your choice # Circle plt.plot(squared, marker='o') # Plus plt.plot(squared, marker='+') # Diamond plt.plot(squared, marker='D') # Triangle Up plt.plot(squared, marker='^') If you set linestyle=”, you won’t plot a line, just the markers. # Circle plt.plot(squared, marker='o', linestyle='') # Plus plt.plot(squared, marker='+', linestyle='') # Diamond plt.plot(squared, marker='D', linestyle='') # Triangle Up plt.plot(squared, marker='^', linestyle='') Matplotlib Line Plot Format Strings Setting the marker, linestyle and color of a plot is something you want to do all the time. So matplotlib included a quick way to do it plt.plot(y, fmt) # with x-axis values plt.plot(x, y, fmt) After passing the y-axis and/or x-axis values, you can pass fmt. It’s a string made up of three parts: fmt = '[marker][line][color]' Each part is optional and you can pass them in any order. You can use the short form markers, linestyles and colors we have discussed in this article. For example, ‘o–g’ is circle markers, dashed lines and green color. # These are equivalent plt.plot(x, y, 'o--g') plt.plot(x, y, marker='o', linestyle='--', color='g') plt.plot(x, y, marker='o', ls='--', c='g') Here are some examples with different markers, linestyles and colors. # Circles, dash line, red 'o--r' plt.plot(squared, 'o--r') # Plus, dashdot line, green '+-.g' plt.plot(squared, '+-.g') # Diamonds, solid line, black 'D-k' plt.plot(squared, 'D-k') # Triangle up, dot line, blue 'b:^' plt.plot(squared, 'b:^') If you don’t specify a linestyle in the format string, matplotlib won’t draw a line. This makes your plots look similar to a scatter plot. For this reason, some people prefer to use plt.plot() over plt.scatter(). The choice is up to you. Summary You now know all the essentials to make professional looking and effective line plots. You can change the color and plot multiple lines on top of each other. You can write custom labels for the axes and title. You’re able to clearly explain different lines using a legend. And you can customise the look of your plot using color, linewidth, markers and linestyles. per - - - - - - - -
https://blog.finxter.com/matplotlib-line-plot/
CC-MAIN-2020-50
en
refinedweb
import "github.com/rogpeppe/go-internal/renameio" Package renameio writes files atomically by renaming temporary files. Pattern returns a glob pattern that matches the unrenamed temporary files created when writing to filename. WriteFile is like ioutil.WriteFile, but first writes data to an arbitrary file in the same directory as filename, then renames it atomically to the final name. That ensures that the final location, if it exists, is always a complete file. WriteToFile is a variant of WriteFile that accepts the data as an io.Reader instead of a slice. Package renameio imports 5 packages (graph). Updated 2019-01-06. Refresh now. Tools for package owners.
https://godoc.org/github.com/rogpeppe/go-internal/renameio
CC-MAIN-2020-50
en
refinedweb
Remix’s Tech Stack: Webpack This is the first in a series about Remix’s tech stack. Over the last few months we’ve worked on setting up our ideal stack, and we’re proud of what we’ve built. Now it’s time to share it. We’ll start with our front-end build tools. We wanted to use the latest Javascript features without worrying about older browsers (Babel), confidence when changing CSS by scoping classes (CSS Modules), immediate feedback when changing code (React Hot Loader), and so on. All of this is easy to set up when using Webpack, which is why we switched to that. In this article we’ll look at how we’ve set this up. Webpack config There are a few ways we want Webpack to behave, based on the context. The first is dev-server vs static build. - When developing we use the webpack-dev-server, which caches files in memory and serves them from a web server, which in turn saves time. It also supports hot module loading. - When building on the Continuous Integration, or CI, server (we use CircleCI), or when deploying using Heroku, we want to generate a static build, so we can host them statically in production. That way we can set proper caching headers. We also use both minified and non-minified versions of our builds, depending on whether it’s in production or still in development. - In production, we want a gzipped and minified build, so it downloads and parses faster. We also enable all React optimisations, so it runs faster. Sometimes we also want to do this when developing locally, when measuring performance. - Usually though, we want to disable minifying when developing. This way development is faster, as minifying is an additional step. We also want to get all of React’s warnings when developing. To set this context, we use two environment variables, which we use like this in our package.json: "scripts": { "build": "webpack", "build-min": "WEBPACK_MINIFY=true npm run build", "dev-server": "WEBPACK_DEV_SERVER=true webpack-dev-server", "dev-server-min": "WEBPACK_MINIFY=true npm run dev-server" }, In our webpack.config.js we first set up some common stuff: const config = { plugins: [ /* Some plugins here. */ ], module: { loaders: [ /* Some loaders here. */ ], }, entry: { build: ['client/build'], // Our main entry point. tests: ['client/tests'], // Jasmine unit tests. happo: ['client/happo'], // Happo screenshot tests. }, resolve: { alias: { client: path.resolve('./client'), }, }, }; Nothing too exciting here. All our code is in the client directory, plus node_modules for libraries (which Webpack finds by default). We alias the client directory, so we can easily refer to it. We have three entry points, one for our app (client/build.js) and two for tests (which we’ll get into in a later article). We then look at if we’re minifying or not: if (process.env.WEBPACK_MINIFY) { config.plugins.push(new webpack.DefinePlugin({ 'process.env': { // Disable React warnings and assertions. 'NODE_ENV': JSON.stringify('production'), }, '__DEV__': false, // For internal use. })); config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, })); } else { // Only use source maps when not minifying. config.devtool = 'eval-source-map'; config.plugins.push(new webpack.DefinePlugin({ '__DEV__': true, })); } If we’re minifying, we want to set NODE_ENV to “production”, as React uses this to strip away all sorts of assertions and warnings, making it faster. When not minifying we enable source maps. Then we have setup specific for when using the dev-server: if (process.env.WEBPACK_DEV_SERVER) { // Development configuration, assumes this is loaded with // webpack-dev-server, running on port 8080 (default). // Hot loading for build.js. config.devServer = { noInfo: true, host: '0.0.0.0', hot: true}; config.entry.build.unshift( 'webpack-dev-server/client?'); config.entry.build.unshift('webpack/hot/dev-server'); config.plugins.push(new webpack.HotModuleReplacementPlugin()); config.plugins.push(new webpack.NoErrorsPlugin()); // React components hot loading. config.module.loaders.unshift({ test: /\.js$/, include: path.resolve(__dirname, 'client/components'), loader: 'react-hot', }); // Expose Jasmine test page as index page on config.plugins.push(new JasmineWebpackPlugin({ htmlOptions: { chunks: ['tests'], filename: 'index.html', }, })); config.output = { publicPath: '', filename: '[name].js', // In case this is run without webpack-dev-server. path: 'public/client', }; } - We initialise the dev-server with noInfo, making it less verbose, and bind it to 0.0.0.0 so you can access it from other machines on the network (useful for debugging). - We enable Hot Module Replacement, per instructions here. We also enable the React Hot Loader, but only on actual React components (client/components). - Then we host the Jasmine index page on the same port, so you can just navigate there to run the tests. - Finally we set config.output to something simple, so you can easily view what is generated at. In case we run this without the dev-server (which should typically not happen), we write to where other static files are written. If we’re not running the dev-server, we’re writing to disk: else { // Static configuration, outputs to public/client. // For use with Heroku/CircleCI. if (process.env.WEBPACK_MINIFY) { // Gzip. config.plugins.push(new CompressionPlugin()); // Generate stats.html. config.plugins.push(new StatsPlugin('stats.json')); config.plugins.push(new Visualizer()); } config.output = { path: 'public/client', publicPath: '/client/', // Unique filenames (for caching). filename: '[id].[name].[chunkhash].js', }; } - When minifying, we gzip all files (which Rails static asset hosting automatically uses), and we generate a file usage visualisation, which we serve on our internal development pages. - We also generate unique filenames for each build, so we can serve them with infinite caching headers. Finally we speed up deploys a bit by leaving out tests when deploying on Heroku: // Don't build tests when deploying on Heroku. if (process.env.HEROKU_APP_ID) { delete config.entry.tests; delete config.entry.happo; } Serving from Rails Let’s now look at the plugins part of our Webpack config. It looks like this: plugins: [ new CircularDependencyPlugin(), new ManifestPlugin(), ], The first one is to prevent circular dependencies, which can be a pain to debug in Webpack. The second one generates a manifest.json file, which looks something like this: { "build.js": "0.build.fc79868b1fdedc95cd1f.js", "happo.js": "1.happo.d44f048f66291e0e73ca.js", "tests.js": "2.tests.305167cc0309faddc140.js" } We use this in our Rails application to serve the right assets. For this we have created a helper file, assets_helper.rb: # Adds `webpack_include_tag`. module AssetsHelper def webpack_include_tag(filename) if Rails.application.config.use_webpack_dev_server # Assumes that Webpack is configured with # config.output.filename = '[name].js'. return javascript_include_tag(root_url(port: 8080) + filename) end webpack_filename = webpack_manifest[filename] if webpack_filename javascript_include_tag("/client/#{webpack_filename}") else raise ArgumentError, "Webpack file not found: #{filename}" end end private def webpack_manifest @webpack_manifest ||= JSON.load(Rails.root.join( 'public', 'client', 'manifest.json')) end end This allows us to call webpack_include_tag(‘build.js’) in templates, and have it use the filename including the hash. Now we can tell the browser to cache these files forever, as they will have a different filename if they ever change. Note that when use_webpack_dev_server is enabled, we point to the dev-server. We set this variable to true in development, to false in staging and production, and in test.rb we set: config.use_webpack_dev_server = !ENV['CI'] Preprocessing using Loaders Finally, we have a bunch of Webpack loaders. This is what that looks like in the Webpack config: module: { loaders: [ { test: /\.js$/, include: path.resolve('./client'), loader: 'babel', query: { cacheDirectory: '.babel-cache', // For code coverage. plugins: (!process.env.WEBPACK_DEV_SERVER && !process.env.WEBPACK_MINIFY) ? ['istanbul'] : [], }, }, { test: /\.less$/, include: path.resolve('./client'), loaders: [ // Inject into HTML (bundles it in JS). 'style', // Resolves url() and :local(). 'css?localIdentName=[path][name]--[local]--[hash:base64:10]', // Autoprefixer (see below at `postcss()`). 'postcss-loader', // LESS preprocessor. 'less', ], }, { test: /\.(jpe?g|png|gif)$/i, include: path.resolve('./client'), loaders: [ // Inline small images, otherwise create file. 'url?limit=10000', // Minify images. 'img?progressive=true', ], }, { test: /\.(geo)?json$/, include: [ path.resolve('./client'), path.resolve('./spec'), // Shared fixtures. ], loader: 'json', }, { test: /\.svg$/, loader: 'raw', }, ], }, postcss() { return [autoprefixer]; }, - First, the Babel loader. This allows us to use the latest Javascript features without having to worry about browser support (in conjunction with babel-polyfill). We use Istanbul to track code coverage for tests, and we set an explicit cache path so the CI can keep this cache between builds. This is what that looks like for CircleCI, in circle.yml: dependencies: cache_directories: - ".babel-cache" - Next is CSS. We use LESS for preprocessing, although we’re thinking of switching to PostCSS, which uses future CSS standards. We already use PostCSS for auto-prefixing. We also use CSS Modules by setting css?localIdentName, which lets you scope CSS classes to only the file that uses them. - Images are being inlined if they are a small file, otherwise they get loaded separately. They are also minified. - JSON and SVG are straightforward. We import SVG as text, which we use with an <Svg> component that looks like this: // Use a tool like // to slim down the SVG, and then manually // remove width/height/fill/stroke. const Svg = React.createClass({ propTypes: { height: React.PropTypes.number, offset: React.PropTypes.number, svg: React.PropTypes.string.isRequired, width: React.PropTypes.number.isRequired, }, render() { return ( <div className={styles.root} dangerouslySetInnerHTML={{ __html: this.props.svg }} style={{ height: this.props.height || this.props.width, width: this.props.width, top: this.props.offset, }} /> ); }, });export default Svg; Which then gets used like this: <Svg svg={require('./pencil.svg')} width={14} offset={2} /> Conclusion This is just a small part of our stack, but it took a while to get right. After all, it’s the small things that make a difference, such as being able to run a minified version with all React optimisations in development, or persisting Babel’s cache between CI runs, or not building tests when deploying. Hopefully this is useful to get started with Webpack, or to tune your existing setup. Keep an eye out for next editions in this series, in which we’ll talk about our components library, unit testing, screenshot testing, deploying, keeping the CI fast, and more!
https://medium.com/@JanPaul123/remixs-software-stack-webpack-34990de9d803
CC-MAIN-2020-50
en
refinedweb
Plotly and Datashader in Python How to use datashader to rasterize large datasets, and visualize the generated raster data. datashader creates rasterized representations of large datasets for easier visualization, with a pipeline approach consisting of several steps: projecting the data on a regular grid, creating a color representation of the grid, etc. Passing datashader rasters as a mapbox image layer¶ We visualize here the spatial distribution of taxi rides in New York City. A higher density is observed on major avenues. For more details about mapbox charts, see the mapbox layers tutorial. No mapbox token is needed here. import pandas as pd df = pd.read_csv('') dff = df.query('Lat < 40.82').query('Lat > 40.70').query('Lon > -74.02').query('Lon < -73.91') import datashader as ds cvs = ds.Canvas(plot_width=1000, plot_height=1000) agg = cvs.points(dff, x='Lon', y='Lat') # agg is an xarray object, see for more details coords_lat, coords_lon = agg.coords['Lat'].values, agg]]] from colorcet import fire import datashader.transfer_functions as tf img = tf.shade(agg, cmap=fire)[::-1].to_pil() import plotly.express as px # Trick to create rapidly a figure with mapbox axes fig = px.scatter_mapbox(dff[:1], lat='Lat', lon='Lon', zoom=12) # Add the datashader image as a mapbox layer image fig.update_layout(mapbox_style="carto-darkmatter", mapbox_layers = [ { "sourcetype": "image", "source": img, "coordinates": coordinates }] ) fig.show() Exploring correlations of a large dataset¶ Here we explore the flight delay dataset from. In order to get a visual impression of the correlation between features, we generate a datashader rasterized array which we plot using a Heatmap trace. It creates a much clearer visualization than a scatter plot of (even a fraction of) the data points, as shown below. Note that instead of datashader it would theoretically be possible to create a 2d histogram with plotly but this is not recommended here because you would need to load the whole dataset (5M rows !) in the browser for plotly.js to compute the heatmap, which is practically not tractable. Datashader offers the possibility to reduce the size of the dataset before passing it to the browser. import plotly.graph_objects as go import pandas as pd import numpy as np import datashader as ds df = pd.read_parquet('') fig = go.Figure(go.Scattergl(x=df['SCHEDULED_DEPARTURE'][::200], y=df['DEPARTURE_DELAY'][::200], mode='markers') ) fig.update_layout(title_text='A busy plot') fig.show() import plotly.express as px import pandas as pd import numpy as np import datashader as ds df = pd.read_parquet('') cvs = ds.Canvas(plot_width=100, plot_height=100) agg = cvs.points(df, 'SCHEDULED_DEPARTURE', 'DEPARTURE_DELAY') zero_mask = agg.values == 0 agg.values = np.log10(agg.values, where=np.logical_not(zero_mask)) agg.values[zero_mask] = np.nan fig = px.imshow(agg, origin='lower', labels={'color':'Log10(count)'}) fig.update_traces(hoverongaps=False) fig.update_layout(coloraxis_colorbar=dict(title='Count', tickprefix='1.e')) fig.show()
https://plotly.com/python/datashader/
CC-MAIN-2020-50
en
refinedweb
Invokables¶ For people who have been using the library since the early days you are familiar with the need to use the .get() method to invoke a method chain: // an example of get const lists = await sp.web.lists.get(); Starting with v2 this is no longer required, you can invoke the object directly to execute the default action for that class - typically a get. const lists = await sp.web.lists(); This has two main benefits for people using the library: you can write less code, and we now have a way to model default actions for objects that might do something other than a get. The way we designed the library prior to v2 hid the post, put, delete operations as protected methods attached to the Queryable classes. Without diving into why we did this, having a rethink seemed appropriate for v2. Based on that, the entire queryable chain is now invokable as well for any of the operations. Other Operations (post, put, delete)¶ import { sp, spPost } from "@pnp/sp"; import "@pnp/sp/webs"; // do a post to a web - just an example doesn't do anything fancy spPost(sp.web); Things get a little more interesting in that you can now do posts (or any of the operations) to any of the urls defined by a fluent chain. Meaning you can easily implement methods that are not yet part of the library. For this example I have made up a method called "MagicFieldCreationMethod" that doesn't exist. Imagine it was just added to the SharePoint API and we do not yet have support for it. You can now write code like so: import { sp, spPost, SharePointQueryable } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/fields/web"; // call our made up example method spPost(SharePointQueryable(sp.web.fields, "MagicFieldCreationMethod"), { body: JSON.stringify({ // ... this would be the post body }), });
https://pnp.github.io/pnpjs/concepts/invokable/
CC-MAIN-2020-50
en
refinedweb
On 12.05.2016 09:09, Peter Krempa wrote: > On Tue, May 10, 2016 at 17:24:14 | 106 ++++++++++++++++++++++++++++++++++++++++ >> tests/file_access_whitelist.txt | 23 +++++++++ >> 4 files changed, 145 da68f2e..7cd641d 100644 >> --- a/tests/Makefile.am >> +++ b/tests/Makefile.am >> @@ -451,6 +451,19 @@ test_libraries += virusbmock.la \ >> $(NULL) >> endif WITH_LINUX >> >> +if WITH_LINUX >> +check-access: file-access-clean >> + $(MAKE) $(AM_MAKEFLAGS) check >> + $(PERL) check-file-access.pl > > I added '| sort -u' while trying this. There's a lot of multiplicated > lines. Okay. > >> + >> ..6e59201 >> --- /dev/null >> +++ b/tests/check-file-access.pl >> @@ -0,0 +1,106 @@ >> +#!/usr/bin/perl -w >> +# >> +# >> +# <>. >> +# >> +# This script*#.*$/) { >> + # comment > > Will this file ever contain comments? I guess not. I can remove it. > >> + } elsif (/^("; >> + } >> +} >> + >> +$error; > > perl complains that the above line is useless. Also the script doesn't > return failure if it finds files out of the build path. > > >> > > My test run showed that there is a looot of stuff to add unfortunately. > > Looks good to me, but my perl knowledge is rather poor. > Correct. There's still plenty of rules to add. That's why the perl is not returning any error. Not just yet. Michal
https://www.redhat.com/archives/libvir-list/2016-May/msg00878.html
CC-MAIN-2020-50
en
refinedweb
Originally guest posted by Rodolfo Ferro on Sun 10 December 2017 in Tools @ PyBites Rodolfo recently joined our Code Challenges and built Disaster Attention Bot (DisAtBot), a chatbot that helps people affected by natural disasters. In this article he shows how he built this bot with Telegram and (of course) Python. Show him some love because who knows, this could be a life saver (pun intended)! We are delighted to have him show this interesting project he submitted for Code Challenge 43 which earned him a book on chatbots. /Rod please share ... "¿Quién convocó a tanto muchacho, de dónde salió tanto voluntario, cómo fue que la sangre sobró en los hospitales, quién organizó las brigadas que dirigieron el tránsito de vehículos y de peatones por toda la zona afectada? No hubo ninguna convocatoria, no se hizo ningún llamado y todos acudieron" "El jueves negro que cambió a México" – Emilio Viale, 1985. A bit of context... Since September 19th, 2017 Mexico has been hit by several earthquakes (The Guardian, CNN). This made me wonder how we could better handle the reporting of damaged zones, people buried under the rubble of buildings, injured people in need of medical attention and other situations. Verificado 19s was an immediate solution to follow up reports from social media and visualize the info on an online map. This required a lot of real-time (24/7) monitoring of posts on social media from people that were located in the affected areas. And that data was updated every ~10 minutes. So I started thinking about a way to optimize this process for future situations, not only for earthquakes, but for disaster situations in general. This incentivized me to work on this bot for Pybites Code Challenge 43 - Build a Chatbot Using Python. So DisAtBot was born DisAtBot automates the process of reporting incidents via messaging platforms, such as Telegram, Facebook Messenger, Twitter, etc. At this time it only supports Telegram, but I hope to expand it to other social media. If you'd like to contribute, see the Contribute section at the end. You can find DisAtBot at: - Telegram: - The official repo: The idea was to have a simple flow that allowed disaster reporting to be quick and easy. The general process of DisAtBot is as follows: The idea is that any user can interact with the bot by selecting options from button menus in the conversation. This greatly speeds up incidents reporting. The next step would be opening a ticket which will be stored in a database, for the corresponding government instance/public organization/NGO/etc. to validate and send assistance. When no more help is needed, or the situation is under control, the ticket is closed. Setup First clone the repo. I used Python 3.6 and the following packages: To install all dependencies create a virtual env and run: pip install -r requirements.txt Then cd into the scripts folder and run the bot as follows: python DisAtBot.py Design The focus of the initial version was the creation of menu buttons for an easy interaction with the user. The second –and main– issue addressed was the conversation handler. A finite state machine was needed to preserve the desired flow and the responses for each state. I won’t go too deep into the explanation, but the code below will show how I tackled this. First of all, Telegram’s library has several methods to create button menus for user responses during the conversation flow. The idea is to create a Keyboard Markup to handle responses through buttons. This can either be Inline (buttons will appear in the conversation window) or as a Reply Keyboard (buttons will be displayed under the textbox to write messages). An example can be seen in the menu function: def menu(bot, update): """ Main menu function. This will display the options from the main menu. """ # Create buttons to select language: keyboard = [[send_report[LANG], view_map[LANG]], [view_faq[LANG], view_about[LANG]]] reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True) user = update.message.from_user logger.info("Menu command requested by {}.".format(user.first_name)) update.message.reply_text(main_menu[LANG], reply_markup=reply_markup) return SET_STAT As you can see, the keyboard variable is a list that contains the four buttons to be displayed. The layout can be set by nesting lists inside. In this case the Report and Map buttons are in the first row, while FAQ and About buttons are in the second row. This looks like: Continuing with the code, a ReplyMarkup is needed to handle the button responses. It specifies the layout of the menu: if only one menu is displayed, if it needs to be resized, etc. A logger is used for the bot, and the update.message.reply(...) function is used to update the displayed text according to the response from the user. The SET_STAT variable returned in this function is a (predefined) integer to return the state at that time, and to follow the flow. We now understand the menu creation and handling. The reason of using buttons is that we want a quick interaction because the bot is used in an emergency situation. The conversation handler - Telegram's ConversationHandler - takes care of setting the state or step of the flow we're currently at, the finite state machine I mentioned earlier. Note that each state also needs to handle its respective information (button responses, etc.) This code shows the conversation handler: def main(): """ Main function. This function handles the conversation flow by setting states on each step of the flow. Each state has its own handler for the interaction with the user. """ global LANG # Create the EventHandler and pass it your bot's token. updater = Updater(telegram_token) # Get the dispatcher to register handlers: dp = updater.dispatcher # Add conversation handler with predefined states: conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ SET_LANG: [RegexHandler('^(ES|EN)$', set_lang)], MENU: [CommandHandler('menu', menu)], SET_STAT: [RegexHandler( '^({}|{}|{}|{})$'.format( send_report['ES'], view_map['ES'], view_faq['ES'], view_about['ES']), set_state), RegexHandler( '^({}|{}|{}|{})$'.format( send_report['EN'], view_map['EN'], view_faq['EN'], view_about['EN']), set_state)], LOCATION: [MessageHandler(Filters.location, location), CommandHandler('menu', menu)] }, fallbacks=[CommandHandler('cancel', cancel), CommandHandler('help', help)] ) dp.add_handler(conv_handler) # Log all errors: dp.add_error_handler(error) # Start DisAtBot: updater.start_polling() # Run the bot until the user presses Ctrl-C or the process # receives SIGINT, SIGTERM or SIGABRT: updater.idle() It might seem a bit confusing at first, but it boils down to: - The conversation handler has the states of the flow. - It also has entry points (such as the startfunction), and fallbacks (such as the canceland helpfunctions). - It also contains some error handlers. - A global LANGvariable is used, since the implementation - I forgot to mention - support interacting in English or Spanish! To support this I created dictionaries for each interaction in both languages. If you want to check the full code of this bot, check out the scripts directory where you'll find the main script and the language dictionaries. Some other features implemented are geolocation handling and About / FAQ sections. But the best way to know about this project is by watching it in action (for a live demo go to 8:30): Future work For future development I am thinking about adding a map. The system already creates a GeoJSON file from the locations acquired. As mentioned I am considering expanding this to other platforms like Facebook Messenger and Twitter. Another good thing to add would be a website explaining the main use cases of the bot, maybe a wiki –kinda– site? If you have any other ideas or suggestions feel free to contact me or: Contribute If you're interested in contributing to this project, feel free to take a look at the repo's CONTRIBUTING file. I'd be very pleased if this project would grow out to something used in real life to alleviate the dramatic consequences of natural disaster, which always seem to hit when least expected. Keep Calm and Code in Python! – Rod Discussion Nice article! I think you have a typo here: from people that were located in the effected areas It should be "affected areas". Thanks for that! I'm correcting it now. :) Well done ! I think this can qualify for fhe free IBM Call For Code challenge. Take a look here: developer.ibm.com/code-and-response/
https://dev.to/rodolfoferro/disatbot---how-i-built-a-chatbot-with-telegram-and-python-ajn
CC-MAIN-2020-50
en
refinedweb
Explore explored sealed classes and interfaces, a preview feature in Java SE 15. Sealing allows classes and interfaces to define their permitted subtypes. A class or an interface can now define which classes can implement or extend it. It is a useful feature for domain modeling and increasing the security of libraries. The release of Java SE 15 introduces sealed classes (JEP 360) as a preview feature. This feature is about enabling more fine-grained inheritance control in Java. Sealing allows classes and interfaces to define their permitted subtypes. In other words, a class or an interface can now define which classes can implement or extend it. It is a useful feature for domain modeling and increasing the security of libraries. A class hierarchy enables us to reuse code via inheritance. However, the class hierarchy can also have other purposes. Code reuse is great but is not always our primary goal. An alternative purpose of a class hierarchy can be to model various possibilities that exist in a domain. As an example, imagine a business domain that only works with cars and trucks, not motorcycles. When creating the Vehicle abstract class in Java, we should be able to allow only Car and Truck classes to extend it. In that way, we want to ensure that there will be no misuse of the Vehicle abstract class within our domain. In this example, we are more interested in the clarity of code handling known subclasses then defending against all unknown subclasses. Before version 15, Java assumed that code reuse is always a goal. Every class was extendable by any number of subclasses. In earlier versions, Java provided limited options in the area of inheritance control. A final class can have no subclasses. A package-private class can only have subclasses in the same package. Using the package-private approach, users cannot access the abstract class without also allowing them to extend it: public class Vehicles { abstract static class Vehicle { private final String registrationNumber; public Vehicle(String registrationNumber) { this.registrationNumber = registrationNumber; } public String getRegistrationNumber() { return registrationNumber; } } public static final class Car extends Vehicle { private final int numberOfSeats; public Car(int numberOfSeats, String registrationNumber) { super(registrationNumber); this.numberOfSeats = numberOfSeats; } public int getNumberOfSeats() { return numberOfSeats; } } public static final class Truck extends Vehicle { private final int loadCapacity; public Truck(int loadCapacity, String registrationNumber) { super(registrationNumber); this.loadCapacity = loadCapacity; } public int getLoadCapacity() { return loadCapacity; } } } A superclass that is developed with a set of its subclasses should be able to document its intended usage, not constrain its subclasses. Also, having restricted subclasses should not limit the accessibility of its superclass. Thus, the main motivation behind sealed classes is to have the possibility for a superclass to be widely accessible but not widely extensible..
https://morioh.com/p/15b812568be6
CC-MAIN-2020-50
en
refinedweb
Today, we’ll explore some strategies that you can leverage on Azure to optimize your cloud-native application development process using Azure Kubernetes Service (AKS) and managed databases, such as Azure Cosmos DB and Azure Database for PostgreSQL. Optimize compute resources with managed Kubernetes service, Azure handles critical tasks like health monitoring and maintenance for you. When you’re using AKS to deploy your container workloads, there are a few strategies to save costs and optimize the way you run development and testing environments. Create multiple user node pools and enable scale to zero In AKS, nodes of the same configuration are grouped together into node pools. To support applications that have different compute or storage demands, you can create additional user node pools. User node pools serve the primary purpose of hosting your application pods. For example, you can use these additional user node pools to provide GPUs for compute-intensive applications or access to high-performance SSD storage. When you have multiple node pools, which run on virtual machine scale sets, you can configure the cluster autoscaler to set the minimum number of nodes, and you can also manually scale down the node pool size to zero when it is not needed, for example, outside of working hours. For more information, learn how to manage node pools in AKS. Spot node pools with cluster autoscaler A spot node pool in AKS is a node pool backed by a virtual machine scale set running spot virtual machines. Using spot VMs allows you to take advantage of unused capacity in Azure at significant cost savings. Spot instances are great for workloads that can handle interruptions like batch processing jobs and developer and test environments. When you create a spot node pool. You can define the maximum price you want to pay per hour as well as enable the cluster autoscaler, which is recommended to use with spot node pools. Based on the workloads running in your cluster, the cluster autoscaler scales up and scales down the number of nodes in the node pool. For spot node pools, the cluster autoscaler will scale up the number of nodes after an eviction if additional nodes are still needed. Follow the documentation for more details and guidance on how to add a spot node pool to an AKS cluster. Enforce Kubernetes resource quotas using Azure Policy Apply Kubernetes resource quotas at the namespace level and monitor resource usage to adjust quotas as needed. This provides a way to reserve and limit resources across a development team or project. These quotas are defined on a namespace and can be used to set quotas for compute resources, such as CPU and memory, GPUs, or storage resources. Quotas for storage resources include the total number of volumes or amount of disk space for a given storage class and object count, such as a maximum number of secrets, services, or jobs that can be created. Azure Policy integrates with AKS through built-in policies to apply at-scale enforcements and safeguards on your cluster in a centralized, consistent manner. When you enable the Azure Policy add-on, it checks with Azure Policy for assignments to the AKS cluster, downloads and caches the policy details, runs a full scan, and enforces the policies. Follow the documentation to enable the Azure Policy add-on on your cluster and apply the Ensure CPU and memory resource limits policy which ensures CPU and memory resource limits are defined on containers in an Azure Kubernetes Service cluster. Optimize the data tier with Azure Cosmos DB Azure Cosmos DB is Microsoft's fast NoSQL database with open APIs for any scale. A fully managed service, Azure Cosmos DB offers guaranteed speed and performance with service-level agreements (SLAs) for single-digital millisecond latency and 99.999 percent availability, along with instant and elastic scalability worldwide. With the click of a button, Azure Cosmos DB enables your data to be replicated across all Azure regions worldwide and use a variety of open-source APIs including MongoDB, Cassandra, and Gremlin. When you’re using Azure Cosmos DB as part of your development and testing environment, there are a few ways you can save some costs. With Azure Cosmos DB, you pay for provisioned throughput (Request Units, RUs) and the storage that you consume (GBs). Use the Azure Cosmos DB free tier Azure Cosmos DB free tier makes it easy to get started, develop, and test your applications, or even run small production workloads for free. When a free tier is enabled on an account, you'll get the first 400 RUs per second (RU/s) throughput and 5 GB of storage. You can also create a shared throughput database with 25 containers that share 400 RU/s at the database level, all covered by free tier (limit 5 shared throughput databases in a free tier account). Free tier lasts indefinitely for the lifetime of the account and comes with all the benefits and features of a regular Azure Cosmos DB account, including unlimited storage and throughput (RU/s), SLAs, high availability, turnkey global distribution in all Azure regions, and more. Try Azure Cosmos DB for free. Autoscale provisioned throughput with Azure Cosmos DB Provisioned throughput can automatically scale up or down in response to application patterns. Once a throughput maximum is set, Azure Cosmos DB containers and databases will automatically and instantly scale provisioned throughput based on application needs. Autoscale removes the requirement for capacity planning and management while maintaining SLAs. For that reason, it is ideally suited for scenarios of highly variable and unpredictable workloads with peaks in activity. It is also suitable for when you’re deploying a new application and you’re unsure about how much provisioned throughput you need. For development and test databases, Azure Cosmos DB containers will scale down to a pre-set minimum (starting at 400 RU/s or 10 percent of maximum) when not in use. Autoscale can also be paired with the free tier. Follow the documentation for more details on the scenarios and how to use Azure Cosmos DB autoscale. Share throughput at the database level In a shared throughput database, all containers inside the database share the provisioned throughput (RU/s) of the database. For example, if you provision a database with 400 RU/s and have four containers, all four containers will share the 400 RU/s. In a development or testing environment, where each container may be accessed less frequently and thus require lower than the minimum of 400 RU/s, putting containers in a shared throughput database can help optimize cost. For example, suppose your development or test account has four containers. If you create four containers with dedicated throughput (minimum of 400 RU/s), your total RU/s will be 1,600 RU/s. In contrast, if you create a shared throughput database (minimum 400 RU/s) and put your containers there, your total RU/s will be just 400 RU/s. In general, shared throughput databases are great for scenarios where you don't need guaranteed throughput on any individual container Follow the documentation to create a shared throughput database that can be used for development and testing environments. Optimize the data tier with Azure Database for PostgreSQL Azure Database for PostgreSQL is a fully-managed service providing enterprise-grade features for community edition PostgreSQL. With the continued growth of open source technologies especially in times of crisis, PostgreSQL has been seeing increased adoption by users to ensure the consistency, performance, security, and durability of their applications while continuing to stay open source with PostgreSQL. With developer-focused experiences and new features optimized for cost, Azure Database for PostgreSQL enables the developer to focus on their application while database management is taken care of by Azure Database for PostgreSQL. Reserved capacity pricing—Now on Azure Database for PostgreSQL Manage the cost of running your fully-managed PostgreSQL database on Azure through reserved capacity now made available on Azure Database for PostgreSQL. Save up to 60 percent compared to regular pay-as-you-go payment options available today. Check out pricing on Azure Database for PostgreSQL to learn more. High performance scale-out on PostgreSQL Leverage the power of high-performance horizontal scale-out of your single-node PostgreSQL database through Hyperscale. Save time by doing transactions and analytics in one database while avoiding the high costs and efforts of manual sharding. Stay compatible with open source PostgreSQL By leveraging Azure Database for PostgreSQL, you can continue enjoying the many innovations, versions, and tools of community edition PostgreSQL without major re-architecture of your application. Azure Database for PostgreSQL is extension-friendly so you can continue achieving your best scenarios on PostgreSQL while ensuring top-quality, enterprise-grade features like Intelligent Performance, Query Performance Insights, and Advanced Threat Protection are constantly at your fingertips. Check out the product documentation on Azure Database for PostgreSQL to learn more.
https://azure.microsoft.com/ko-kr/blog/cost-optimization-strategies-for-cloudnative-application-development/
CC-MAIN-2020-50
en
refinedweb
ISO/IEC JTC1 SC22 WG21 Document Number: P0376R0 Audience: Library Evolution Working Group Matt Calabrese (metaprogrammingtheworld@gmail.com) 2016-05-28 This paper presents a single generalization of std::invoke, std::apply, and the proposed std::visit [1] by specifying a template named std::call that takes a standard Callable followed by any number of arguments and/or "argument providers," the latter of which act as descriptions of portions of an argument list that are to be substituted in-place when the Callable is invoked. Each generated argument list portion may be any number of arguments with any combination of types, and the precise argument list and its values may even depend on runtime data. Due to the generality of the substitution mechanism, the facility allows argument providers such as ones that can unpack tuples at arbitrary positions in a larger argument list, as well as argument providers that can forward along the active field of a variant. In addition to these familiar operations, further argument providers are presented that do not directly correspond to existing library facilities. The ideas described in this paper are relatively simple to understand at a high level and aid both in the expressive power of C++ and in code readability. Before going into more detailed motivating cases and implementation, the facility is easiest to describe with a set of usage examples. In the following main function, each invocation of output_values is given an equivalent argument list, although each time it is formed in a different way. // This is just a Callable we will use for all of the following examples. // It takes a stream and a series of arguments, outputting each. constexpr auto output_values = [](auto& os, const auto&... args) -> decltype(auto) { return (os << ... << args); }; // In the following function, every time std::call is used, output_values is // ultimately invoked with equivalent values. int main() { // In its simplest usage, std::call does what std::invoke does. // It just invokes the Callable with the specified arguments. std::call(output_values, std::cout, 5, 3.5, std::string(“Hello”)); // It can also be used with a provider that unpacks tuples. // Note that std::cout is not a member of the tuple, so it is // simply forwarded to the Callable as-is. { auto args = std::make_tuple(5, 3.5, std::string(“Hello”)); std::call(output_values, std::cout, std::unpack(args)); } // It can also unpack a tuple, followed by additional arguments. // Note that neither std::cout nor the string are members of the tuple. { auto args = std::make_tuple(5, 3.5); std::call(output_values, std::cout, std::unpack(args), std::string(“Hello”)); } // It can unpack multiple tuples in succession. { std::tuple<std::ostream&, int> head_args(std::cout, 5); auto tail_args = std::make_tuple(3.5, std::string(“Hello”)); std::call(output_values, std::unpack(head_args), std::unpack(tail_args)); } // It can pass along a reference to the currently active field of a variant. { std::variant<int, std::string> arg0 = 5, arg2 = std::string(“Hello”); std::call(output_values, std::cout, std::active_field_of(arg0), 3.5, std::active_field_of(arg2)); } // It can access a tuple with a runtime index. { auto args = std::make_tuple(5, std::string(“Hello”)); std::call(output_values, std::cout, std::access_tuple(args, 0), 3.5, std::access_tuple(args, 1)); } // It can work with multiple different kinds of providers in the same call. { std::variant<int, std::string> head_arg = 5; auto tail_args = std::make_tuple(3.5, std::string(“Hello”)); std::call(output_values, std::cout, std::active_field_of(head_arg), std::unpack(tail_args)); } // It can work with providers that are composed // (i.e. forward along the active field of each element // of an unpacked tuple of variants). { using variant_t = std::variant<double, std::string>; auto tail_args = std::make_tuple(variant_t(3.5), variant_t(std::string(“Hello”))); std::call(output_values, std::cout, 5, std::unpack(tail_args) | std::active_field_of); } // It can deduce a return type for arbitrarily complex compositions, including // ones that involve variant access or tuple access with a run-time index. // By default, if all possible paths do not have the same exact return type, // then substitution will fail. { std::variant<int, std::string> arg0 = 5, arg2 = std::string(“Hello”); auto& result = std::call(output_values, std::cout, std::active_field_of(arg0), 3.5, std::active_field_of(arg2)); static_assert(std::is_same_v<decltype(result), std::ostream&>); } // A return type can be explicitly specified to avoid automatic deduction. // This is useful to force a different type or simply to reduce compile-times // when dealing with sufficiently complicated invocations (such as access of // several different variants in a single call). { std::variant<int, std::string> arg0 = 5; std::call<void>(output_values, std::cout, std::active_field_of(arg0), 3.5, std::string(“Hello”)); } // A return type deducer can be explicitly specified if the default behavior // is not suitable. A deducer is just a variadic template that is internally // instantiated with the return type of each potential invocation. { std::variant<int, std::string> arg0 = 5; std::call<some_user_defined_common_type_t>( output_values, std::cout, std::active_field_of(arg0), 3.5, std::string(“Hello”)); } } The primary motivation for a facility such as this comes from the desire for developers to reuse existing functions whenever possible without having to manually create lambdas. This comes up frequently in order to do things such as unpack only a portion of an argument list (as is often necessary when using std::apply), or forward along the active field of a variant to only one argument of a larger parameter list (as is often necessary when using facilities like the proposed std::visit). Expanding tuples in-place in an argument list is not an uncommon practice in other mainstream languages, such as Python [2], and forwarding the active field of a variant to an existing function is also not unheard of, even in statically-typed languages (an example of this is the dispatch operator of the Clay programming language [3]). Assuming the output_values function that was presented earlier, consider what is required by users to invoke the function when all but the stream argument are an element of a tuple. The following is an example using std::apply followed by what is required when using std::call. The version using the proposed std::call is more concise and considerably more readable: auto args = std::make_tuple(5, 3.5, std::string("Hello")); // This is what is required using std::apply. std::apply([](const auto&... args) -> decltype(auto) { return output_values(std::cout, args...); }, args); // This is what is required using the proposed std::call. std::call(output_values, std::cout, std::unpack(args)); A similar kind of situation comes up when dealing with variants. Consider the following more tangible example, which is based on real-world code. struct line { /*...*/ }; struct circle { /*...*/ }; struct square { /*...*/ }; struct in_collision_fun { // Each of these returns true if the arguments are in collision bool operator()(line, line) const { /*...*/ } bool operator()(line, circle) const { /*...*/ } // ... similar for each combination ... } constexpr in_collision{}; int main() { circle my_circle(/*...*/); square my_square(/*...*/); variant<line, circle, square> my_circle_variant = my_circle, my_square_variant = my_square; // This block uses std::visit { // Both arguments are variants. std::visit(in_collision, my_square_variant, my_circle_variant); // The first argument is an expanded variant. std::visit([&my_circle](const auto& first) { return in_collision(first, my_circle); }, my_square_variant); // The second argument is an expanded variant. std::visit([&my_square](const auto& second) { return in_collision(my_square, second); }, my_circle_variant); } // This block uses the proposed std::call { // Both arguments are variants. std::call(in_collision, std::active_field_of(my_square_variant), std::active_field_of(my_circle_variant)); // The first argument is an expanded variant. std::call(in_collision, std::active_field_of(my_square_variant), my_circle); // The second argument is an expanded variant. std::call(in_collision, my_square, std::active_field_of(my_circle_variant)); } } Serialization and deserialization of a variant is frequently done by serializing the integer discriminator of the variant, followed by serializing the corresponding field. Deserialization works by deserializing the integer discriminator and then deserializing an instance of the field type that corresponds to the discriminator. While this is very simple to think about at a high level, this deserialization process is not directly implementable using a facility like std::visit. It is actually surprisingly complicated to implement in a generic manner without additional facilities akin to the accepted-but-never-added Boost.Switch Library [4]. However, this deserialization process can be easily implemented with std::call. In order to implement this functionality, the developer can use an argument provider that generates a std::integral_constant based on a runtime value (an argument provider named std::to_constant_discriminator is specifically included for this kind of purpose). An example of this can be seen below: template <class Archive, class V> void serialize_variant(Archive& archive, const V& v) { serialize(archive, v.which()); std::call(serialize, archive, std::active_field_of(v)); } // A function that deserializes into a variant when the field // discriminator is known at compile-time. // "discriminator" here is an instantiation of std::integral_constant. constexpr auto deserialize_variant_field = [](auto& archive, auto& variant_, auto discriminator) { variant_.template emplace<discriminator.value>(); deserialize_into(archive, std::get<discriminator.value>(variant_)); }; template <class Archive, class V> void deserialize_variant(Archive& archive, V& variant_) { std::call(deserialize_variant_field, archive, variant_, std::to_constant_discriminator<V>(deserialize<std::size_t>(archive))); } Due to the nature of the templates involved, it is rather difficult to express a complete interface specification. What follows is an informal specification that should evolve considerably if the functionality that std::call provides is deemed valuable by the committee. // If all of T... are the same type as H, yields H, // otherwise substitution will fail. // This is used as the default return type deducer for std::call. // Ultimately this may be left as an implementation detail and not exposed, // but it may be a generally useful facility to specify for users. template <class H, class... T> using same_type_or_fail = /*...*/; // Invoke "fun" with the generated argument list. // ReturnTypeDeducer is passed along to each provider's // "provide" function (described later). // Substitution will fail if the call to "fun" with any of the // possible generated argument lists would fail substitution. template <template <class...> class ReturnTypeDeducer = same_type_or_fail, class Fun, class... Providers> constexpr auto call(Fun&& fun, Providers&&... providers) noexcept(/*deduced*/) -> /*deduced*/; // Invoke "fun" with the generated argument list. // This is equivalent to invoking std::call with a ReturnTypeDeducer that // always yields "ReturnType". template <class ReturnType, class Fun, class... Providers> constexpr auto call(Fun&& fun, Providers&&... providers) noexcept(/*deduced*/) -> /*deduced*/; // All "argument providers" are an instantiation of this template. // The Provider argument must be a type that has a static member function // template called "provide" that is compatible with the following: // // template <template <class...> class ReturnTypeDeducer, class Fun, class Self> // static constexpr auto provide(Fun&& fun, Self&& self) -> /*implementation-dependent*/; // // The provide function is the customization point that describes how // an argument provider generates its portion of the argument list. // The developer of the provide function does this by invoking // the function object "fun" with any number of arguments of any type. // The result of that function call should be returned by provide. // In the case where the provide function may invoke "fun" with different // arguments depending on some runtime condition (such as when implementing // an argument provider that accesses the active field of a variant), then // ReturnTypeDeducer must be instantiated with the decltype of the result of // each possible call, and the type that is yielded must be used as the // return type of the provide function. // // "Self" here is a cv-reference-qualified Provider. The provide function // is static so that it is easy for users to properly forward internal data // without the need for the user to write multiple overloads. template <class Provider> struct argument_provider { Provider /*unspecified*/; }; // An argument provider that evaluates a user-specified provider and forwards // those arguments along to the user-specified callable. This is used // for argument provider composition (such as fully unpacking a tuple of // tuples). Instances of this are the result of the | operator used in the // earlier examples and shown below. template <class Provider, class Callable> using composed_argument_provider = argument_provider</*unspecified*/>; // Creates a composed argument provider. // There should be an overload where the left operand is a reference-to-const // and also an overloaded where the left operand is an rvalue reference. template <class Provider, class Callable> constexpr composed_argument_provider<argument_provider<Provider>&, Callable> operator |(argument_provider<Provider>& provider, Callable&& next_function) noexcept; The above specification details the core parts of the facility. Below is a small set of suggested argument providers to be included with the facility. unpack(T&& tuple): Perfect-forwards the N elements of a tuple as N arguments. active_field_of(V&& var): Perfect-forwards the active field of a variant. access_tuple(T&& var, std::size_t index): Perfect-forwards the element of the tuple at position "index". to_constant_in_range<class T, T Begin, T End>(U&& value): Takes a runtime value and provides the corresponding std::integral_constant. to_constant_discriminator<class Variant>(std::size_t discriminator): Equivalent to to_constant_in_rangewhere the range is [0, variant-arity). to_constant_tuple_index<class Tuple>(std::size_t index): Equivalent to to_constant_in_rangewhere the range is [0, tuple-size). These argument providers have all been used at the top level of the examples presented in this paper, with the exception of std::to_constant_in_range. This argument provider is proposed because it is useful internally for most argument providers that produce different arguments depending on a runtime value (such as std::active_field_of, std::access_tuple, and std::to_constant_discriminator). Because of this, it should be considered important as a means for people to more easily construct their own argument provider types. The std::call facility opens the door for limitless kinds of argument providers, though only a small handful were presented. It is expected that if this facility is accepted, user-space argument providers would be developed and used. The following is a selection of additional general-purpose argument providers that are useful, but not essential to the most common motivating cases and so they are not currently proposed. This is not an exhaustive list: group(T&&... args): Perfect-forwards args(useful with the |operator). identity(T&& arg): Perfect-forwards arg(same as groupwith one argument, analogous uses to boost::protect). fan(P&& provider, C&&... callables): Generates the provider's arguments and passes all of those arguments to each of callables. eat(T&&... args): Produces an empty list of arguments (useful during composition). Because the implementation of these facilities may not be immediately obvious, the following are example definitions of a few of the facilities. The following is a simplified definition of std::call lacking noexcept deduction, desirable SFINAE behavior, and special-casing for void returns. template <class Provider> struct argument_provider { Provider impl; }; // Implementation details namespace __detail { // A trait used internally to either expand an argument provider into its // generated arguments, or directly forward an argument along if it is not // an instantiation of argument_provider. // The default-definition here is the fall-back for when a given argument // is not an instantiation of argument_provider. template <class T> struct argument_provider_traits { template <template <class...> class ReturnTypeDeducer, class Fun, class U> static constexpr decltype(auto) provide(Fun&& fun, U&& arg) { return std::forward<Fun>(fun)(std::forward<U>(arg)); } }; // The partial specialization of the above trait for an argument_provider, // which just forwards the invocation to the user-provided customization point. template <class Provider> struct argument_provider_traits<argument_provider<Provider>> { template <template <class...> class ReturnTypeDeducer, class Fun, class U> static constexpr decltype(auto) provide(Fun&& fun, U&& arg) { return Provider::template provide<ReturnTypeDeducer>(std::forward<Fun>(fun), std::forward<U>(arg).impl); } }; // Encapsulates a template that can be used as a ReturnTypeDeducer that // always yields T. template <class T> struct always_return { template <class...> using type = T; }; } // End __details namespace // The terminating case of the call function with an explicitly-specified // return type and when “fun” is invoked with no arguments. template <class ReturnType, class Fun> constexpr ReturnType call(Fun&& fun) { return std::forward<Fun>(fun)(); } // The terminating case of the call function with an explicitly-specified // ReturnTypeDeducer and when “fun” is invoked with no arguments. template <template <class...> class ReturnTypeDeducer = same_type_or_fail, class Fun> constexpr decltype(auto) call(Fun&& fun) { // Just call the function, being sure to use the return type deducer. return std::call<ReturnTypeDeducer<decltype(std::declval<Fun>()())>>( std::forward<Fun>(fun)); } // Primary, recursive definition when "call" is given a ReturnTypeDeducer and // some number of arguments or argument_providers >= 1. template <template <class...> class ReturnTypeDeducer = same_type_or_fail, class Fun, class Head, class... Tail> constexpr decltype(auto) call(Fun&& fun, Head&& head, Tail&&... tail) { return __detail::argument_provider_traits<std::decay_t<Head>> ::template provide<ReturnTypeDeducer>( // The customization point for “head” may use "head" to provide any // number of arguments. It communicates the generated arguments by // passing those arguments to the lamba that we give it here. [&fun, &tail...](auto&&... expanded_head) -> decltype(auto) { // The lambda we give it recurses into “call” with a lambda that // captures those arguments that were generated by "head". It takes // as parameters the result of the expanded tail arguments. return std::call<ReturnTypeDeducer>( [&fun, &expanded_head...](auto&&... expanded_tail) -> decltype(auto) { // At this point, we have the fully generated argument list, // so we can invoke the original function. return std::invoke( std::forward<Fun>(fun), std::forward<decltype(expanded_head)>(expanded_head)..., std::forward<decltype(expanded_tail)>(expanded_tail)...); }, std::forward<Tail>(tail)...); }, std::forward<Head>(head)); } // Primary, definition when "call" is given an explicit return type and // some number of arguments or argument_providers >= 1. // This just invokes std::call with a ReturnTypeDeducer that always // yields ReturnType. template <class ReturnType, class Fun, class Head, class... Tail> constexpr decltype(auto) call(Fun&& fun, Head&& head, Tail&&... tail) { return std::call<__detail::always_return<ReturnType>::template type>( std::forward<Fun>(fun), std::forward<Head>(head), std::forward<Tail>(tail)...); } The following is an example implementation of std::unpack using std::apply internally for brevity and eliding SFINAE exploitation and conditional noexcept. The code below is the type that would be used as a template parameter to std::argument_provider. template <class T> struct unpack_impl { template <template <class...> class ReturnTypeDeducer, class Fun, class U> static constexpr decltype(auto) provide(Fun&& fun, U&& arg) { return std::apply(std::forward<Fun>(fun), std::forward<U>(arg).tup); } T&& tup; }; The following is an example implementation of accessing a tuple with a runtime value. Internally it uses std::to_constant_tuple_index, which is built on std::to_constant_in_range. std::to_constant_in_range does the heavy lifting for this and other argument providers that depend on runtime data. Its implementation will be shown later. template <class T, class I> struct access_tuple_impl { template <template <class...> class ReturnTypeDeducer, class Fun, class Self> static constexpr decltype(auto) provide(Fun&& fun, Self&& self) { return std::call<ReturnTypeDeducer>( [&fun, &self](auto const index_constant) -> decltype(auto) { return std::forward<Fun>(fun)(std::get<index_constant.value>(std::forward<Self>(self).tup)); }, std::to_constant_tuple_index<std::remove_reference_t<T>>( std::forward<Self>(self).index)); } T&& tup; I&& index; }; The following is an example implementation of std::to_constant_in_range, which is used behind-the-scenes by std::access_tuple, std::active_field_of, std::to_constant_discriminator, and std::to_constant_tuple_index. Once again, this code elides conditional noexcept and SFINAE exploitation for brevity. // A function that invokes the provided function with // a std::integral_constant of the specified value and offset. template <class ReturnType, class T, T Value, T Offset, class Fun> constexpr ReturnType invoke_with_constant_impl(Fun&& fun) { return std::forward<Fun>(fun)( std::integral_constant<T, Value + Offset>()); } // Indexes into a constexpr table of function pointers template <template <class...> class ReturnTypeDeducer, class T, T Offset, class Fun, class I, I... Indices> constexpr decltype(auto) invoke_with_constant(Fun&& fun, T index, std::integer_sequence<I, Indices...>) { // Each invocation may potentially have a different return type, so we // need to use the ReturnTypeDeducer to figure out what we should // actually return. using return_type = ReturnTypeDeducer< decltype(std::declval<Fun>()(std::integral_constant<T, Indices + Offset>()))...>; return std::array<return_type(*)(Fun&&), sizeof...(Indices)>{ {{invoke_with_constant_impl<return_type, T, Indices, Offset, Fun>}...}} [index - Offset](std::forward<Fun>(fun)); } template <class T, T BeginValue, T EndValue> struct to_constant_in_range_impl { // Instantiations of "type" are used as the Provider // template argument of argument_provider. template <class U> struct type { template <template <class...> class ReturnTypeDeducer, class Fun, class Self> static constexpr decltype(auto) provide(Fun&& fun, Self&& self) { return __detail::invoke_with_constant<ReturnTypeDeducer, T, BeginValue>( std::forward<Fun>(fun), std::forward<Self>(self).value, std::make_index_sequence<EndValue - BeginValue>()); } U&& value; }; }; The specification presented in this proposal is not yet sufficient and will require more effort if the facilities are considered useful. One notable area that needs work is a specification of the requirements of a ReturnTypeDeducer. It is also likely that, if accepted, argument providers should live in their own namespace so as to not conflict with functionality in the top-level std namespace. The current specification requires that all argument providers are instantiations of the argument_provider template. This was done for simplicity, but customization could be done equivalently with traits directly. The author of this proposal leaves the means of customization open for discussion if it is a point of contention. Thanks to Tony Van Eerd who encouraged me to write this paper, and to Michael Park who pointed out the constexpr table-lookup form of variant visitation to me, which is used in the example implementation of std::to_constant_in_range. [1] Axel Naumann: "Variant: a type-safe union that is rarely invalid" P0088R0 [2] Python Software Foundation: "The Python Tutorial" [3] Clay Labs: "The Clay Programming Language, Language Reference" [4] Steven Watanabe: "Boost.Switch"
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0376r0.html
CC-MAIN-2019-47
en
refinedweb
How to control a SG90 servo motor with the ESP8266 NodeMCU LUA Development Board When you are looking to operate remote-controlled or radio-controlled toy cars, robots and airplanes, you will need to use servo motors. Since the ESP8266 NodeMCU LUA Development Board is cost efficient for IOT solutions, it can be used for controlling servo motors. So how can we control a servo motor with the ESP8266 NodeMCU LUA Development Board? This post discusses how we can control the SG90 servo motor, with the ESP8266 NodeMCU LUA Development Board. How to connect the SG90 servo motor to the ESP8266 NodeMCU LUA Development Board First, let us look at how we can connect the SG90 servo motor to the ESP8266 NodeMCU LUA Development Board. As shown above, we first seat the ESP8266 development board onto a breadboard. Next to the development board, we use three male to male jumper wires: - The red one connects to a 3v3 port. - The black one connects to a Gnd port. - The orange one connects to the D1 port. Once we had connected the wires onto the breadboard, we then connect them to the SG90 servo motor in the following manner: After we have connected the hardware in this way, we will be able to control the servo motor from the board. Enabling ESP8266 Development on Arduino IDE At this point in time, we are ready to get our mini program into the ESP8266 board to control the servo motor.8266 development on Arduino IDE before continuing. Writing the Arduino Sketch to get ESP8266 NodeMCU LUA Development Board turn the servo motor In order to understand how to control our servo motor, let's take a look at the following Arduino Sketch: #include <Servo.h> Servo servo; void setup() { servo.attach(D1); servo.write(0); delay(2000); } void loop() { servo.write(0); delay(3000); servo.write(90); delay(3000); servo.write(180); delay(3000); } So what will the above codes do to our servo motor? First, we included the Servo library into the sketch. After we had done so, we create a Servo object from the library. When we had created a Servo object, we will be able to work on it inside the setup and loop functions. The setup() function will be run once and the loop() function will be run until power is cut off from the board. Within the setup function, we first attach the servo to D1, a predefined constant for the D1 port, via the Servo.attach() function. By doing so, we will be able to control the servo which is attached to D1 port of the board. We then turn the servo motor to 0 degrees via Servo.write() and make the program wait for 2 seconds. Within the loop function, we repeatedly turn the servo motor to 0, 90 and 180 degrees. Before making each turn, we make the program wait for 3 seconds.
https://www.techcoil.com/blog/how-to-control-a-sg90-servo-motor-with-the-esp8266-nodemcu-lua-development-board/
CC-MAIN-2019-47
en
refinedweb
Version History -Added support for improved mirroring with RRM Selector -Added version on the Extras tab for version number checking -Added button on the Extras tab for going to Creative Crash website •RRM Selector -Fixed bugs with mirroring V 1.0.2 (October 7, 2013) -Fixed error when generating roll joints on the legs -Fixed error when generating a spline with more than 10 joints -Fixed color of "Edit Look-Ats" in the UI V 1.0.3 (October 12, 2013) -Fixed bug with limb stretching on two elbow/two knee rigs if a character is skinned to the rig. -Fixed bug with saving setups with mirrored splines. -Fixed bug with generating single hierarchy joint chains with mirrored splines. -Fixed bug with odd orientations that can occur in a rig with a Spline due to its parent. -Fixed a bug where a popup window will appear if you select multiple proxies from the same module and press "Delete Selected Module and Branches". -Added the ability to delete multiple proxy modules at once. -Joints and controls on splines now align to the same orientation as the proxies. -Fixed a bug with pinning multiple branches at once if some modules were mirrored and some were not. -Fixed a bug with scaling while pinning and unpinning modules. -Fixed a bug where the "HeelBall" attribute on the FootIKC wasn't working properly with the LowerLegIKC. -Fixed a bug on the LowerLegIKC auto orient that could cause flipping. -UI cleanup and improvements with naming and colours to improve understanding of functionality. V 1.0.4 (November 27, 2013) -fixed stretching issue on two-knee leg setups. -fixed bug with midIKC when angled a certain way and with an even number of joints in the spline. -fixed bug on scaled splines. -improved twisting on the arms. More work still needed though. -locators on the leg that were previously visible in generated rigs are now hidden. -improved naming of nodes. -fixed error in installation instructions within the MEL files. •RRM Selector -cleaned up some of the wording in warnings. V 1.0.5 (December 5, 2013) -fixed bug that was causing roll joints to flip when rotations on the wrist were zeroed out or undone. -added new naming conventions on string attributes for RRM Selector to work with referenced files. •RRM Selector -added support for referenced files (only compatible with rigs generated with the 1.0.5 update). -COG control is now included in reset transforms. V 1.0.6 (December 8, 2013) -fixed bug that was causing lower roll joints to flip when rotated at certain angles. -scale is now uniform on FK proxies to avoid shearing. V 1.0.7 (December 17, 2013) -fixed bug that caused the lower leg IKC to flip with auto orient turned on and the body and foot both angled. -added version number to the UI titles of RRM and RRM Selector. V 1.0.8 (December 28, 2013) -bird preset has now been added! -mirroring proxies left to right now works if a right control is selected, and vice versa. -Roll joint proxies on arms and legs can now be selected and positioned by turning off "Template Roll Joints" in the parent node. -fixed appearance of roll joint proxies. -fixed bug in "Resize Controllers" that caused an error when mirroring scale. -"Resize Controllers" now checks to see if something is selected. -"Resize Controllers" will skip any invalid objects in selection and continue. -Hid some visiblity channels that could cause an error in the Selector script. V 1.0.9 (January 1, 2014) -users can now save and load the shapes of their controllers on rigs of this version or newer. Really useful when having to recreate a rig. -fixed issue with flipping kneeIKC/elbowIKC. -fixed issue with orientation of fk chains and proxies. -joints/controls now orient to the proxy, rather than aiming at the next one down the chain. -added Creative Crash link to the top of the RRM script. V 1.1.0 (January 12, 2014) -fixed bug with naming of shape nodes that could cause errors with saving shapes. -fixed orientation of shoulder joint to always orient to the angular plane between the shoulder, elbow and wrist. -fixed error if there are multiple modules of the same type. -fixed bug that could cause the roll joints to mis-align. -code optimization. V 1.1.1 (February 10, 2014) -cleaned up extra COG transform nodes. -fixed bug in the arachnid proxy preset. V 1.1.2 (February 11, 2014) -added improved rolling to the arms and legs. Rotations now blend from the hips to the knees/shoulders to the elbows. -improved the micro joints so they don't flip as easily. -optimized code and have the arms and legs running the same code for improved consistency and editing. V 1.1.3 (February 11, 2014) -fixed bug on the shoulder curve and hip curve joints attachment. -fixed versioning number. -cleaned up printed messages. V 1.1.4 (February 24, 2014) -fixed bug on the direction of the knee proxies which could cause the ik chain to be aiming along the wrong axis. -fixed bug on the roll joints on the arms and legs when parent joints are rotated. -updated the quadruped proxy preset. V 1.1.5 (February 26, 2014) -fixed bug that caused errors on some machines due to two constraints on one transform. V 1.1.6 (February 27, 2014) -fixed bug that could cause misalignment in the MidIKC of splines. -added new "Top Translate" feature to splines which is complimentary to the "Top Orient" feature. -code optimization. V 1.1.7 (March 1, 2014) -fixed bugs with the orientation of the shoulder and elbow FK controls. -fixed bugs with the orientation of the hip and knee FK controls. -fixed bugs with the preferred angle of the elbows and knees which resulted in flipping joints. -improved installation instructions. -cleaned up unnecessary code. V 1.1.8 (March 1, 2014) -fixed bugs with pole vectors when limbs are bent at extremes. V 1.2.0 (March 29, 2014) FK Chain: -added splineIK with controls to blend or be additive to the FK controls. -separated auto spread into position and rotation. -amount of splineIK blend is controllable. -splineIK has Scale, Spread, Parent influence and Follow. Fixed bug with mirroring Look-At proxies that was breaking some of the Preset proxy rigs Fixed bug with renaming attributes on the Look-At proxies. Fixed warning for deprecated skinning flag in 2013 and newer. KneeIKC on two knee legs now aim at Knee1ElbowIKC on two Elbow legs now aim at Elbow1. Fixed bug with roll joints and controls not scaling with the rest of the rig. Rig scale is now uniform. Fixed bug when the scene units are not set to centimeters. Single Hierarchy: -fixed issue with roll joints not being created. -changed parenting of roll joints so that no other joint is a child of a roll joint. RRM_Selector User can now mirror individual controls rather than only poses Added buttons for selecting the Root, Root Secondary, Root Parent, COG and main controls. Added dropdown to support the new SplineIK on Fk Chains V 1.2.1 (April 6, 2014) -"RRM" letters in the MAINC no longer use Maya's Create Text, so there is no longer a dependency on fonts. -fixed bug with the scaling of joints when the MAINC is scaled. -fixed bug with the right side roll joints of single hierarchy arms and legs. •RRM Selector -Improved stability of RRMS UI. -Fixed UI bug where the selection buttons of FK Chains were overlapping. -Fixed UI bug where the “Reset Transforms” and “Reset Extras” buttons were hidden. V 1.2.2 (April 10, 2014) -Fixed pop-up text box for saving shapes. -"Saving Shapes" is now "Save Shapes and Colors". -Fixed bug with deleting rigs where not all nodes were deleted. -Fixed bug where the roll joint attachment curves were being saved as part of the “Save Shapes” feature. V 1.3.0 (April 27, 2014) -New Icons!! -Changed naming conventions: *C>Ctrl *G>Grp *J>Jnt -Pushed out the default position of the LookAt controls so it doesn't crowd the rest of the controls. -Fixed bug with the MidIKC movement if the parent joint has a different orientation. -Fixed bug with joint selections so that the extra joints are not included. Only affected skeletons with roll joints on arms and legs. -Added “nonControl” attributes to curves that were missing it. -Added missing attributes to the roll controls that were causing errors with RRM Selector. -Fixed bug on two-elbow/two-knee limbs where the visibility channel on the curve control was not hidden. •RRM Selector -Supports the new naming convention -Fixed single FK Chain selection bug. -Fixed bug on vertical spacing of single FK Chain in the UI. V 1.3.1 (April 28, 2014) -Fixed bug with IK/FK match V 1.3.2 (April 30, 2014) -Fixed bug with the roll joints of the arms and legs causing errors when generating rigs. -Fixed orientation of Head MasterCtrl. V 1.3.3 (May 10, 2014) -Fixed bug that could try to add the same attribute to controls more than once. -Designed workaround for SplineIK causing NaN values on FK chains with two joints. -Fixed attachment of Btm01JntIK joints when attached to the Root. -Adjusted the orientation of the Head MasterCtrl to align to the Head Parent proxy instead of aiming at the Head Top Proxy. -Fixed bugs with the Ankle/Wrist influence for the Knee/Elbow with the Two Elbow/Knee setup. V 1.3.4 (May 11, 2014) -Fixed bug that was causing arms not to build and resulting in an incomplete rig. -Fixed bug with the orientation of the Hip Curve Joint. V 1.3.5 (May 22, 2014) -Fixed bug with the orientation of splines that could cause the MidIKC to misalign and pull in the wrong direction. V 1.4.0 (June 3, 2014) -Added Auxiliary Module Type -Removed empty group node in spline module -Fixed naming of Groups named G1 to Grp1 -Fixed bug on the orientation and flipping of the lower leg controls -Fixed bug with the roll joints when bending elbow more than 90 degrees -Fixed bug with the spline controls following the spline when rotating -UI Cleanup •RRM Selector -Added support for Aux Module -Rearranged Control UI V 1.4.1 (June 8, 2014) -Fixed bug where generating an FK chain with several chains but only one joint was causing an error. V 1.4.2 (June 9, 2014) -Added proxy module renaming. -Enlarged UI to accommodate module renaming. -Changed "Preset" to "Template" in modular setup. -Fixed bug that caused an error when trying to clone a module with a proxy from the left and right side selected. -Fixed bug where a temporary node was not being deleted when cloning. V 1.4.3 (July 20, 2014) -fixed bug in single hierarchy where elbows/knees were not being constrained to the curve joints. -fixed bug on auto volume on roll joints. -added translate and rotate influence to MidIKC on splines (allows locking the MidIKC). -fixed bug on flipping on FK Chain Splines. -fixed bug where mid roll joints with two elbow/knee setups not generating. -fixed bug how head scaling works. -fixed but on double-transform scaling occurring in Maya 2015. -added twist control for wrist/feet. -unlocked all rotation axes on twist controls. -fixed bug on the hip twist orientation. V 1.4.4 (July 23, 2014) -fixed bug with the auxiliary proxies not being saved in Save/Load Setup. -fixed bug with FKtoIK not matching perfectly in the arms. -fixed bug where head modules would cause errors if no jaw was created. V 1.4.5 (August 29, 2014) -fixed naming of dummy joints in arms and legs. -improved rotation of Arm and Leg TwistCtrl’s. -added orientation of arm and leg joints to the SwitchCtrl’s for use with PSD’s. -fixed bug with flipping in splines when enabling Follow FKC. -fixed bug with the hierarchy in the head modules if no jaw is created. V 1.4.6 (September 1, 2014) -fixed bug calling “graphEditor1FromOutliner” in the script could cause an error for some users. -fixed bug with flipping in the roll joints when rotated more than 90 degrees on certain axes. V 1.4.7 (September 4, 2014) -added a new mirroring script. Rather than having to use a UI to mirror RRM rigs, you can map these commands to buttons or hotkeys to mirror faster. Open RapidRig_Modular_Mirror.mel for instructions. -added terms of use agreement text file. V 1.4.8 (September 23, 2014) -improved rotations of twist joints. -twistCtrl’s shape is now mirrored on the right side. -twistCtrl now follows the hip/shoulder FKCtrl when translated. -fixed bug with legs if they are not oriented with the feet on the grid. -fixed bug where modifying FK chains in +/-Y which was causing the orientations of the parent proxy to be frozen. -fixed bug where pinned modules would not load the correct positions when loading a proxy setup. -saving setup now saves information about pinned modules and loads them pinned. V 1.4.9 (October 5, 2014) -fixed bug with elbow joints flipping when rotated past 90 degrees -fixed bug that could cause errors with constraints on hips under certain conditions -further improvements to shoulder/hip and wrist/ankle twist V 1.5.0 (October 28, 2014) -added new moveable pivot control. -fixed bug with matching IK to FK on the legs. -fixed bug with the default orientation of controls on splines when at certain angles. -fixed bug which was causing renaming modules to delete child modules. -code optimization. V 1.5.1 (November 2, 2014) -fixed bug on the twist snapping of the Twist Control for legs. -fixed bug on Lower Twist Control flipping when upper limb is rotated past 90. -fixed bug on generation error of double knee/elbow with roll joints. -fixed bug when trying to attach a module to an existing auxiliary module. -fixed bug when trying to attach a non-mirrored module to a new module. -scaling curve controls now affects curve joints. -corrected some naming conventions. -single hierarchy joints now scale with the main ctrl. -pivot control scale now conforms to size of proxy rig. V 1.5.2 (November 27, 2014) -fixed bug that caused shearing in the jaw when the Head MasterCtrl is rotated. -fixed bug in "Select Skinning Joints" that was including some joints that should not be skinned to. V 1.5.3 (January 13, 2015) -fixed bug that was causing the ROOT joint and control to be in the wrong location. -can now select joints from the UI if the rig is referenced. -deleting a referenced rig from the UI now gives a descriptive warning instead of a line number error. -deleting a referenced or non-existin proxy rig from the UI now gives a descriptive warning instead of a line number error. V 1.5.4 (February 3, 2015) -Ik controls on FK modules are now optional. This is set on the proxies upon creation and can be turned off by using the modify proxies. -fixed bug on spline module that interrupted rig generation if units are set to meters instead of centimeters -added support in RRM_Selector for the optional IK controls in FK Modules -cleaned up code and messaging V 1.5.5 (February 9, 2015) -Fixed bug with backwards compatabilty of proxy rigs created before the update in 1.5.4 that allows optional IK in FK controls V 1.5.6 (February 17, 2015) -Fixed bug with converting to meters and added support for all the other unit types in Maya. V 1.5.7 (March 3, 2015) -Fixed bug that caused flipping on FK chains when switched to IK mode. V 1.5.8 (April 3, 2015) -Fixed bug that caused errros when saving proxies from versions older than 1.5.4 -Fixed bug that caused errors when loading the RR:Selector UI on rigs older than 1.5.4 V 1.5.9 (April 7, 2015) -Fixed bug that caused the FK joints to scale incorrectly if the FK module was generated without "IK Enabled". -Fixed bug that caused renamed modules to encounter an error resulting in an extra module with the old name. V 1.6.0 (April 9, 2015) -Fixed bug that caused the IK controls to not be consistent when proxies are at different scales for arm and leg modules. -Fixed scale issue on the MidIKCtrl's of spline modules of generated rigs. V 1.6.1 (June 8, 2015) -Fixed bug that caused an error with splines with more than 10 joints when generating the single hierarchy joint chain. V 1.6.2 (July 30, 2015) -Fixed bug with SH chain in spline numbering -Fixed UI numbering for Saving and Loading Shapes/Colours of controls. -Changed orientation of spline controls so it conforms with X being the twist axis. -Changed orientation of root controls so it conforms with X being the twist axis. -TopIKInf for position and rotation now enabled by default on the MidIKCtrl. -SHJoints now have all their rotations frozen and baked into joint orientation. V 1.6.3 (August 4, 2015) -Fixed deprecated file browser dialog and created extensions for the different files: 1. Save/Load Proxy Transforms (.rrmprox) 2. Save/Load Proxy Setup (.rrmsstp) 3. Save/Load Control Shapes and Colors (.rrmctrls) -Now supports a spline with one in-between joint (rather than the previous minimum of two). V 1.6.4 (November 11, 2015) -Fixed bug with orientation of spline controls. -Fixed orientation of FK controls. -Fixed bug when trying to delete entire proxy rig from Setup Proxies tab. V 1.6.5 (November 16, 2015) -Fixed bug with editing FK proxy modules. -Fixed bug with transferring and resetting FK chains. -Added new option for transferring/mirroring/setting to module. -Added new feature of rebuilding a rig and reskins mesh with one click. Requires original proxies. V 1.6.6 (November 25, 2015) -Added the option for the spline/root modules to have X or Y as twist axis. Default is now Y axis so similar behaviour as pre 1.6.2. -Root orientation can be set from the channel box. -Spline orientation can be set from the Create and Edit buttons in the RRM User Interface. V 1.6.7 (November 27, 2015) -Added backwards compatability to older proxy rigs for the new "Twist Axis" setting on the spline. V 1.6.8 (December 1, 2015) -fixed bug where colours of controls were not being applied when rebuilding rig. -added backwards compatibility for the "Rebuild Rig" to Maya 2011 and newer. -fixed bug that would cause rebuild to error if skin cluster was generated with a geodesic voxel setting. -fixed bug that would not close the node editor properly when prompted. -fixed bug that would not save out all the weights of vertices. V 1.6.9 (December 23, 2015) -fixed bug in the pivot control so that it works properly if the orientation of the root is set to x as twist axis -fixed bug that caused the midIkCtrl to flip if the rig is rotated 180 on the y axis. V 1.7.0 (January 27, 2016) -fixed bug which could cause improper interpolation on some attributes. -fixed bug on Fk chain where the joints flip on the right side if number of joints is set to 2. -fixed bug on Fk chain where the fist joint doesn’t move on the right side if number of joints is set to 2. -fixed default value on the midOrient attribute on the midIkCtrl. V 1.7.1 (January 27, 2016) -optimized arms, legs and fk controls using parenting instead of constraints and connections. -MasterCtrl on look-at modules now moves the joints. V 1.7.2 (February 6, 2016) -added ability to disable toon joints while maintaining roll joints. Disabling toon will improve rig performance by ~33%. -fixed bug that could interrupt generation of two elbow/knee arm/leg modules. -fixed bug that caused an error if generating an arm/leg with mid roll joints on two elbows/knees. V 1.7.3 (February 24, 2016) -locked critical nodes on the rig so that users are forced to use the “Delete Rig” option which cleans up all the nodes of the rig. -auxiliary controls now match the size of the auxiliary proxies. -fixed bugs in the Pose Proxy Rigs options. The “All” and “Branch” options now works correctly. -code optimization. V 1.7.4 (February 28, 2016) -fixed bug with improper mirroring of preset proxy rigs. -Fixed bug that would cause an error if generating a single hierarchy chain with roll joints on the arm and a module is attached to the shoulder. V 1.7.5 (March 5, 2016) -added templated line on the IK controls for FK Chains to make it clearer which joint the control affects. •RRM Selector -fixed bug that caused incorrect mirroring on non-mirrored FK chains. -fixed bug that caused incorrect mirroring on Auxiliary modules. V 1.7.6 (March 6, 2016) -fixed bug on renaming arm and leg modules if no roll joints exist. -fixed bug on cloning modules with branches. -fixed bug when saving proxies with splines that causes Twist Y to be saved as Twist X, and saving with Twist X causes an error. V 1.7.7 (March 11, 2016) -fixed bug that would not allow modules to be built if that name was already used in the scene. -added an option in the "Extras" tab to drive the scale of single hierarchy joints from their target joint. -UI now refreshes as each module of the rig is generated. -fixed bug where the grow bar for "Finishing Up..." reached 100% too early. -code optimization. V 1.7.8 (March 13, 2016) -fixed bug that was causing the joints not to move with the controls. -optimized rig generation to be ~50% faster. -code optimization. V 1.7.9 (March 16, 2016) -Fixed bug that caused an error when generating an arm/leg module with roll joints and toon arms/legs disabled. -Fixed bug when generating the auxiliary proxy that stated more than one object was selected even if this was untrue. -Code optimization on naming shape nodes. V 1.8.0 (March 21, 2016) -Fixed bug that could cause the spline orientations with X as the twist axis. -Spline proxies now maintain their transforms when making changes under the "Edit Modules" tab. -Elbows/knees now maintain their transforms when making changes to the Arms/Legs under the "Edit Modules" tab. V 1.8.1 (March 22, 2016) -FK proxies now maintain their transforms when making changes under the "Edit Modules" tab. -Fixed bug where most channels were locked but not hidden as before. -Fixed bug on the look of the IKCtrls on FK modules. -All nodes that should be hidden have their visibility channels locked. V 1.8.2 (March 30, 2016) -Added new Help "?" buttons in the proxy tab to make it easier to learn about each part of the UI. -Fixed bug that caused an error when trying to modify an FK module that was not mirrored. -Fixed bug in hierarchy that made curve controls not select with the “>ALL< button in RRM_Selector. -Fixed bug where bend deformers were not deleted on double-knee legs. -Fixed the colour of TwistCtrl’s for toon arms/legs -RRM_Selector now supports multiple rigs. Each rig has its own tab. -RRM_Selector code clean-up so the script no longer does unnecessary selections. ___________________________________________________________________________________________________________ V 2.0.0 (July 17, 2016) Rig Functionality -Mirrored behavior now supported on modules. -soft IK option to prevent knee/elbow popping. -additional control for the foot. -several new custom attributes for the feet and hands. -foot controls can be hidden if you only want to use the channels. -animatable pivots are available on the feet. -additional offset control on main control. -bug fixes for different scene units. Proxy Building -Updated orientations and naming under the hood. -Set custom prefixes which propagate to the final rig. -Custom channel on the right parent node of a proxy module to define the mirroring type. -Toe proxies can now be raised for better deformation, and Toe Ik Control still pivots from the ground. Rig Building -Code has been optimized to build the rig faster. -A custom name is no longer required for the rig. -Set custom prefixes. Rig Rebuilding -Rig rebuild is more stable with saving and loading weights. -Rig rebuild now allows for control shapes to be rebuilt based on any changes you have made to them. -Single Hierarchy joints have the option to preserve rotations now. Desirable if game engine does not support joint orients. Post Rig Settings -Can now define a rest pose for your rig to define the zeroed out value for controls. -Better UI and more stable for renaming single hierarchy joints to match Motion Builder/HIK naming convention. -Additional tabs for each part of the rig. -Delete Rig and Delete Proxy rig buttons now exist in their respective tabs. Appearance Changes -New control shapes for easier selection. -Circles now have a point to make it clear which direction is up. -arm and leg Fk controls have an optional volume appearance, to make the controls more box-like. -Shoulder/Hip Fk control visibility can be optionally enabled even in Ik to allow moving the shoulder/hip. -End Fk controls visibility can be optionally enabled. -New appearance for spline proxy joints. Clean-up -new naming convention. -Code optimizations. Bug Fixes -Fixed bugs that caused issues in some cases with curve controls -Fixed bug on orientation of spine if not in upright position RRM Selector -can use “shift” key to mirror/transfer pose of entire rig. -ik/fk matching now works with double-knee rigs. -Controls will always mirror properly, even if the user renames them . V 2.0.1 (July 25, 016) -Fixed bug with loading rig/selecting joints -fixed orientation issue with spline module when the spline is horizontal -fixed bug and update proxies for the quadruped template -ik handle now hidden when two knees are created with the knees V 2.0.2 (August 21, 2016) -Fk Controls for arms, legs, and fk chains can now be displayed as boxes by using the "Volumetric Appearance" Option -Added “Ball Influence” which allows the ball to roll automatically in the “Toe Heel” roll -Fixed bug that made joint scale negative on the left elbow/knee locks -Fixed orients on non-mirrored fk chains -Fixed orients of proxy fk chains with 1 joint per chain -Fixed bug when generating an fk chain with 2 joints per chain -Fixed bug where MidIkCtrl on Splines may rotate unnecessarily when adjusting attributes -Users no longer have to enable “Allow multiple bind poses” when skinning RRM_Selector -Now works with referenced files -Added batch mirroring for animations. Can batch all controls or selected. Can choose entire timeline or specify frame range. -Code cleanup V 2.0.3 (August 29, 2016) -Fixed bug that created error for versions 2014 and older -Fixed bug with control rebuilding that would cause errors with hierarchy changes -Fixed bug that would cause the midIk controls on splines to move at the default position when adjusting custom channels -Changed center controls from green to yellow to be less confusing with selections RRM_Selector -Changed colors in RRM_Selector to reflect new control colors -Fixed bug on Fk to Ik matching on the wrists -Changed Ik to Fk on legs to match the ToePivotIkCtrl instead of channels on the FootIkCtrl V 2.0.4 (Sept 3, 2016) -fixed bug when creating arns with two elbows -added “TopIkInfTwistOnly” attribute to MidIk_Ctrl on splines -added control for MAINSHJnt if single hierarchy with origin joint option is enabled -fixed bug that could cause errors when rebuilding rig with preserving control shapes if proxy rig hierarchy has changes RRM_Selector -Fixed bug that caused an error if multiple RRM characters were in a scene (affected Maya 2015) -Code optimization V 2.0.5 (Sept 13, 2016) -Added V1.8.3 to the download for users still on the old tools. -Fixed bug where using the control scaling didn’t work with mirrored setting. -Fixed several bugs for the spline with Twist X and behavior. V 2.0.6 (Sept 18, 2016) -Fixed bug on spline twist that previously made the midIkCtrl flip after TopIkCgtrl rotates past 90 degree rotations. Still flips at 180. -Fixed bug in RRM_Selector that caused an error when trying to select IK controls on FK Modules V 2.0.7 (January 3, 2017) -fixed warnings that occur when loading the script in Maya 2017 -rebuilding arm/leg proxies now maintains twist joint transforms -fixed bugs in double elbow/knee joints that caused errors when generating rig -set default value for arms to be fk. This affects the Reset in the Selector script -added a check to make sure prefix names are valid -improved spline setup so controls move properly, even when the spline is in more extreme shapes -removed blend shapes on splines for performance gain and reduce conflicts in the rig -other minor fixes -optimized the "Record Rest Pose" function. -fixed bug that was hardcoded in the "Record Rest Pose" function -fixed bug when generating Fk modules with only one joint per chain -fixed bug for joint flipping in Maya 2017 when generating FK modules with IK enabled -fixed bug on elbow/knee curve joints that caused flipping RRM_Selector -fixed bug where Fk to IK doesn’t always match up perfectly -cleaned up code to get rid of warnings that appear in Maya 2017 V 2.1.1 (February 6, 2017) -updated links to point to the Highend3d instead of Creative Crash -cleaned up print commands RRM_Selector -fixed an error in the code that was causing errors V 2.1.2 (February 11, 2017) -fixed orientations on single right arms RRM_Selector -fixed an error when loading the script on a character with non-mirrored arms/legs -code optimizations V 2.1.3 (February 16, 2017) -minor updates RRM_Selector -fixed bug that made the sub-foot IK controls not mirror properly -code optimizations V 2.1.4 (March 7, 2017) -extra attribute channels have been locked, which was causing errors with the RRM_Selector script RRM_Selector -fixed bug where batch mirroring animation was only using the "Start/End" setting V 2.1.5 (April 19, 2017) -added X twist option on head module -fixed bug on single arms that caused flipping of toon controls and joints -fixed bug that causes spline joints to rotate when changing FollowFkCtrl attribute -fixed bug that has rotation values on the head_TopJnt RRM_Selector V 2.1.6 (May 22, 2017) -fixed bug on twisting joints with toon limbs disabled V 2.1.7 (August 2, 2017) -Tilt proxies on the foot can now be angled to give more realistic banking on feet that may not be perfectly rectangular -Fixed bug when modifying the legs with fewer lower joints than upper joints -Fixed bug when setting rest poses with translation -Fixed bug when matching Fk to Ik if the rest value is over 180 RRM_Selector -Fixed bug with Look-At selector -Fixed bug where mirroring would not work with custom prefixes -Fixed bug that set some float values to integers when mirroring V 2.1.8 (August 23, 2017) -Fixed bugs in the spline and fk chains that caused issues where the rig changes when saving and loading, along with unexpected channel values. RRM_Selector -Fixed bug where center controls were not mirroring when using batch mirror. V 2.1.9 (September 14, 2017) -Fixed bug where the left foot bank rotation was inverted. V 2.2.0 (September 17, 2017) -Fixed bug that only exists in Maya 2018 where shoulder joints flip after saving and reopening a file. V 2.2.1 (October 2, 2017) -Fixed bug where the arm joints were not in the control rig hierarchy -Fixed bug where cloning an FK chain with more than 10 joints caused an error -Fixed the toe roll, so toe rotates up and down instead of left to right -Fixed bug when generating Single Hierarchy on arms with double elbow joints -Added non-flipping funtionality to the non-toon limbs -Fixed bug where FK chains could not be attached to different modules V 2.2.2 (October 2, 2017) -Fixed bug with the orientation directions of the joints. -improved twisting on limbs -Fixed bug where rig scale was not hooked up when rig generated with single hierarchy and a trajectory joint RRM_Selector -Fixed bug where using the button to select the main control of a non-mirrored eye control caused an error V 2.2.3 (November 19, 2017) -Fixed bug where renaming a module deleted all attached modules -Fixed bug where auxiliaries were deleted when its parent module is renamed -Fixed bug where fk chain modules weren’t mirroring properly -Fixed bug on orientations of right finger joints and controls -Fixed bug where renaming a spline module with more 10 or more joints caused an error -Fixed bug where joints were not selectable through the UI when referencing a rig -fixed bug where selecting joints through the UI of a rig that was referenced wouldn’t work -fixed bug that allowed attaching modules to the COG proxy V 2.2.4 (November 21, 2017) -Fixed bug where the toon arms/legs on the right side would flip -Fixed bug where an error occurred if something was selected but no rig loaded when pressing the “Select Skinning Joints” button in the UI -Fixed bug where pinning was not mirrored when mirroring proxies -Fixed issue where SDK’s from the wristCtrlGrp could be affected when selecting the wrist SwitchCtrl -Fixed bug where the rig would still build when hitting “Cancel” at the node editor prompt V 2.2.5 (December 10, 2017) -fixed proxy rig bug where attaching to scaled modules causes undesired scaling on the selected module that was attached. RRM_Selector -added feature to batch IkToFk/FkToIk matching over multiple frames. -fixed bug where the ballIkCtrl was not reset when matching IkToFk. V 2.2.6 (January 13, 2018) -fixed bug where renaminng legs and head to match motionbuilder causes errors -RRM Selector now supports up to four nested references -added minimum limit to "dampen_softness" which otherwise could cause crashing if the keyframes on this channel were moved below a value of zero. V 2.2.7 (February 3, 2018) -fixed bug where pinning did not work on auxiliaries -“Follow” attributes on wrist and feet are now fully enumerations (dropdown attribute) -Fixed bug where renaming joints in the UI caused errors if the skeleton had additional joints that would not exist on a Motion Builder skeleton -Replaced all Set Driven Keys with nodes to improve rig performance -debugging rotation values are now optional and off by default to improve rig performance RRM Selector - space switch matching has been added for elbows/knees and wrists/feet in the UI. V 2.2.7 (February 3, 2018) -fixed bug where the new parenting controls errors when using a custom rig name. V 2.2.8 (February 10, 2018) -fixed bug on renaming legs with two knees -fixed bug with renaming heads -fixed bug when attaching legs to other parts of the character than the root RRM Selector -works no matter how many levels deep of file referencing V 2.3.0 (March 10, 2018) -fixed bug when building rigs with non-mirrored eyes -fixed bug when building fk chains that were generated from a right sided proxy RRM Selector -fixed bug when rig has namespaces -added batch following, so the ik controls on arms/legs can be baked to follow the desired target over multiple frames -UI visual improvements V 2.3.0 (March 10, 2018) -fixed bug where large rotations could cause errors when matching fk to ik by changing rotate order of elbow/knee controls V 2.3.1 (March 10, 2018) -fixed bug when building fk chains that were generated from a right sided proxy -fixed bug that caused error when duplicating or renaming single leg modules -trajectory single hierarchy joint can now have its scale driven by the trajectory control RRM Selector -fixed bug where lower arm/leg controls on a double knee/elbow setup didn’t mirror correctly -fixed bug where lower arm/leg controls on a double knee/elbow setup didn’t copy to pose to opposite side correctly V 2.3.3 (May 26, 2018) -Optimized code for IK Handle generation RRM Selector -Fixed bug where modules built in certain orders could cause the UI to not build V 2.3.4 (June 30, 2018) -Fixed bug in controller tagging when a module is attached to an arm or leg where one or the other is not mirrored. -The Main Control is now selected when the rig completes generation. V 2.3.5 (July 8, 2018) -Fixed bug where loading a setup with a non-mirrored fk chain attached to the right side was getting attached to the left side V 2.3.6 (July 15, 2018) -Fixed bug where the micro spline controls were not scaling the joints on the correct axes. -Ball IK handles are now hidden. -Fixed bug where the arms would have a double transform when stretching with roll joints but toon arm/leg disabled. V 2.3.7 (September 10, 2018) RRM Selector -fixed bug where batch mirror was not working with file references. -added new button so users can mirror the selection of controls. V 2.3.8 (October 20, 2018) -fixed bug when attempting to create mirrored spline proxies. V 2.3.9 (March 12, 2019) -fixed bug in 2019 where eye controls were not generating properly and causing an error -fixed bug in auxiliary controls where the follow parent orient and translate attributes were not behaving properly V 2.4.0 (April 15, 2019) -fixed bugs with namespaces on the selector script -code optimizations V 2.4.1 (April 16, 2019) -fixed bugs after code optimization that were causing syntax errors in some cases V 2.4.2 (May 1, 2019) -fixed bug that was causing controls to be sized incorrectly -code optimizations V 2.4.3 (July 21, 2019) -fixed bug with mirrored splines -improved rig deletion so it does not use string lookup. Now uses selection sets. V 2.4.4 (September 14, 2019) -fixed bug where weights on the ribbons for splines are created at non-uniform size which was causing the spline to deform incorrectly -fixed bug for SHJointLayer not being deleted correctly when deleting rigs or rebuilding rigs Related Items: - "Rapid Rig: Advanced" - Auto Rig 2.3.8 for Maya (maya script) $49.00 (USD) - "Rapid Rig: Poser" for Maya for Maya 2.0.9 (maya script) $20.00 (USD) - UTILITIES for RIG (create controls, blending IK/FK, attribute follow, duplicate joint, mirror controls, orient joint, corrective blend shape) 2.0.0 for Maya )
https://www.highend3d.com/maya/script/rapid-rig-modular-procedural-auto-rig-for-maya/history
CC-MAIN-2019-47
en
refinedweb
Sending SOAP request using Python Requests Is it possible to use Python's requests library to send a SOAP request? It is indeed possible. Here is an example calling the Weather SOAP Service using plain requests lib: import requests <SOAP-ENV:Header/> <ns1:Body><ns0:GetWeatherInformation/></ns1:Body> </SOAP-ENV:Envelope>""" response = requests.post(url,data=body,headers=headers) print response.content Some notes: - The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xmlis probably the more correct header to use (but the weatherservice prefers text/xml - This will return the response as a string of xml - you would then need to parse that xml. - For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables. For example: from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('myapp', 'templates')) template = env.get_template('soaprequests/WeatherSericeRequest.xml') body = template.render() Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ). You can do the above with suds like so: from suds.client import Client url="" client = Client(url) print client ## shows the details of this service result = client.service.GetWeatherInformation() print result Note: when using suds, you will almost always end up needing to use the doctor! Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so: sudo tcpdump -As 0 This can be helpful for inspecting the requests that actually go over the wire. The above two code snippets are also available as gists: From: stackoverflow.com/q/18175489
https://python-decompiler.com/article/2013-08/sending-soap-request-using-python-requests
CC-MAIN-2019-47
en
refinedweb
import "github.com/cockroachdb/cockroach/pkg/jobs" helpers.go jobs.go metrics.go progress.go registry.go update.go DefaultAdoptInterval is a reasonable interval at which to poll system.jobs for jobs with expired leases. DefaultAdoptInterval is mutable for testing. NB: Updates to this value after Registry.Start has been called will not have any effect. var DefaultCancelInterval = base.DefaultTxnHeartbeatInterval DefaultCancelInterval is a reasonable interval at which to poll this node for liveness failures and cancel running jobs. var FakeNodeID = func() *base.NodeIDContainer { nodeID := base.NodeIDContainer{} nodeID.Reset(1) return &nodeID }() FakeNodeID is a dummy node ID for use in tests. It always stores 1. var ( // LeniencySetting is the amount of time to defer any attempts to // reschedule a job. Visible for testing. LeniencySetting = settings.RegisterDurationSetting( "jobs.registry.leniency", "the amount of time to defer any attempts to reschedule a job", defaultLeniencySetting) ) MakeChangefeedMetricsHook allows for registration of changefeed metrics from ccl code. NoopFn is an empty function that can be used for Failed and Succeeded. It indicates no transactional callback should be made during these operations. var ProgressUpdateOnly func(context.Context, jobspb.ProgressDetails) ProgressUpdateOnly is for use with NewChunkProgressLogger to just update job progress fraction (ie. when a custom func with side-effects is not needed). NewRetryJobError creates a new error that, if returned by a Resumer, indicates to the jobs registry that the job should be restarted in the background. func RegisterConstructor(typ jobspb.Type, fn Constructor) RegisterConstructor registers a Resumer constructor for a certain job type. SimplifyInvalidStatusError unwraps an *InvalidStatusError into an error message suitable for users. Other errors are returned as passed. TestingSetProgressThresholds overrides batching limits to update more often. UnmarshalPayload unmarshals and returns the Payload encoded in the input datum, which should be a tree.DBytes. UnmarshalProgress unmarshals and returns the Progress encoded in the input datum, which should be a tree.DBytes. ChunkProgressLogger is a helper for managing the progress state on a job. For a given job, it assumes there are some number of chunks of work to do and tracks the completion progress as chunks are reported as done (via Loop). It then updates the actual job periodically using a ProgressUpdateBatcher. func NewChunkProgressLogger( j *Job, expectedChunks int, startFraction float32, progressedFn func(context.Context, jobspb.ProgressDetails), ) *ChunkProgressLogger NewChunkProgressLogger returns a ChunkProgressLogger. func (jpl *ChunkProgressLogger) Loop(ctx context.Context, chunkCh <-chan struct{}) error Loop calls chunkFinished for every message received over chunkCh. It exits when chunkCh is closed, when totalChunks messages have been received, or when the context is canceled. Constructor creates a resumable job of a certain type. The Resumer is created on the coordinator each time the job is started/resumed, so it can hold state. The Resume method is always ran, and can set state on the Resumer that can be used by the other methods. DescriptionUpdateFn is a callback that computes a job's description given its current one. type FakeNodeLiveness struct { // A non-blocking send is performed over these channels when the corresponding // method is called. SelfCalledCh chan struct{} GetLivenessesCalledCh chan struct{} // contains filtered or unexported fields } FakeNodeLiveness allows simulating liveness failures without the full storage.NodeLiveness machinery. func NewFakeNodeLiveness(nodeCount int) *FakeNodeLiveness NewFakeNodeLiveness initializes a new NodeLiveness with nodeCount live nodes. func (nl *FakeNodeLiveness) FakeIncrementEpoch(id roachpb.NodeID) FakeIncrementEpoch increments the epoch for the node with the specified ID. FakeSetExpiration sets the expiration time of the liveness for the node with the specified ID to ts. func (nl *FakeNodeLiveness) GetLivenesses() (out []storagepb.Liveness) GetLivenesses implements the implicit storage.NodeLiveness interface. func (*FakeNodeLiveness) ModuleTestingKnobs() ModuleTestingKnobs implements base.ModuleTestingKnobs. func (nl *FakeNodeLiveness) Self() (storagepb.Liveness, error) Self implements the implicit storage.NodeLiveness interface. It uses NodeID as the node ID. On every call, a nonblocking send is performed over nl.ch to allow tests to execute a callback. FractionProgressedFn is a callback that computes a job's completion fraction given its details. It is safe to modify details in the callback; those modifications will be automatically persisted to the database record. func FractionUpdater(f float32) FractionProgressedFn FractionUpdater returns a FractionProgressedFn that returns its argument. HighWaterProgressedFn is a callback that computes a job's high-water mark given its details. It is safe to modify details in the callback; those modifications will be automatically persisted to the database record. InvalidStatusError is the error returned when the desired operation is invalid given the job's current status. func (e *InvalidStatusError) Error() string Job manages logging the progress of long-running system processes, like backups and restores, to the system.jobs table. CheckStatus verifies the status of the job and returns an error if the job's status isn't Running. CheckTerminalStatus returns true if the job is in a terminal status. Created records the creation of a new job in the system.jobs table and remembers the assigned ID of the job in the Job. The job information is read from the Record field at the time Created is called. Details returns the details from the most recently sent Payload for this Job. func (j *Job) Failed( ctx context.Context, err error, fn func(context.Context, *client.Txn) error, ) error Failed marks the tracked job as having failed with the given error. FractionCompleted returns completion according to the in-memory job state. FractionProgressed updates the progress of the tracked job. It sets the job's FractionCompleted field to the value returned by progressedFn and persists progressedFn's modifications to the job's progress details, if any. Jobs for which progress computations do not depend on their details can use the FractionUpdater helper to construct a ProgressedFn. HighWaterProgressed updates the progress of the tracked job. It sets the job's HighWater field to the value returned by progressedFn and persists progressedFn's modifications to the job's progress details, if any. ID returns the ID of the job that this Job is currently tracking. This will be nil if Created has not yet been called. Payload returns the most recently sent Payload for this Job. Progress returns the most recently sent Progress for this Job. RunningStatus updates the detailed status of a job currently in progress. It sets the job's RunningStatus field to the value returned by runningStatusFn and persists runningStatusFn's modifications to the job's details, if any. SetDescription updates the description of a created job. SetDetails sets the details field of the currently running tracked job. SetProgress sets the details field of the currently running tracked job. Started marks the tracked job as started. Succeeded marks the tracked job as having succeeded and sets its fraction completed to 1.0. Update is used to read the metadata for a job and potentially update it. The updateFn is called in the context of a transaction and is passed the current metadata for the job. It can choose to update parts of the metadata using the JobUpdater, causing them to be updated within the same transaction. Sample usage: err := j.Update(ctx, func(_ *client.Txn, md jobs.JobMetadata, ju *jobs.JobUpdater) error { if md.Status != StatusRunning { return errors.New("job no longer running") } md.UpdateStatus(StatusPaused) // <modify md.Payload> md.UpdatePayload(md.Payload) } Note that there are various convenience wrappers (like FractionProgressed) defined in jobs.go. WithTxn sets the transaction that this Job will use for its next operation. If the transaction is nil, the Job will create a one-off transaction instead. If you use WithTxn, this Job will no longer be threadsafe. type JobMetadata struct { ID int64 Status Status Payload *jobspb.Payload Progress *jobspb.Progress } JobMetadata groups the job metadata values passed to UpdateFn. func (md *JobMetadata) CheckRunning() error CheckRunning returns an InvalidStatusError if md.Status is not StatusRunning. JobUpdater accumulates changes to job metadata that are to be persisted. func (ju *JobUpdater) UpdatePayload(payload *jobspb.Payload) UpdatePayload sets a new Payload (to be persisted). WARNING: the payload can be large (resulting in a large KV for each version); it shouldn't be updated frequently. func (ju *JobUpdater) UpdateProgress(progress *jobspb.Progress) UpdateProgress sets a new Progress (to be persisted). func (ju *JobUpdater) UpdateStatus(status Status) UpdateStatus sets a new status (to be persisted). Metrics are for production monitoring of each job type. InitHooks initializes the metrics for job monitoring. MetricStruct implements the metric.Struct interface. type NodeLiveness interface { Self() (storagepb.Liveness, error) GetLivenesses() []storagepb.Liveness } NodeLiveness is the subset of storage.NodeLiveness's interface needed by Registry. type ProgressUpdateBatcher struct { // Report is the function called to record progress Report func(context.Context, float32) error syncutil.Mutex // contains filtered or unexported fields } ProgressUpdateBatcher is a helper for tracking progress as it is made and calling a progress update function when it has meaningfully advanced (e.g. by more than 5%), while ensuring updates also are not done too often (by default not less than 30s apart). Add records some additional progress made and checks there has been enough change in the completed progress (and enough time has passed) to report the new progress amount. func (p *ProgressUpdateBatcher) Done(ctx context.Context) error Done allows the batcher to report any meaningful unreported progress, without worrying about update frequency now that it is done. type Record struct { Description string Statement string Username string DescriptorIDs sqlbase.IDs Details jobspb.Details Progress jobspb.ProgressDetails RunningStatus RunningStatus } Record bundles together the user-managed fields in jobspb.Payload. type Registry struct { TestingResumerCreationKnobs map[jobspb.Type]func(Resumer) Resumer // contains filtered or unexported fields } Registry creates Jobs and manages their leases and cancelation. Job information is stored in the `system.jobs` table. Each node will poll this table and establish a lease on any claimed job. Registry calculates its own liveness for a node based on the expiration time of the underlying node-liveness lease. This is because we want to allow jobs assigned to temporarily non-live (i.e. saturated) nodes to continue without being canceled. When a lease has been determined to be stale, a node may attempt to claim the relevant job. Thus, a Registry must occasionally re-validate its own leases to ensure that another node has not stolen the work and cancel the local job if so. Prior versions of Registry used the node's epoch value to determine whether or not a job should be stolen. The current implementation uses a time-based approach, where a node's last reported expiration timestamp is used to calculate a liveness value for the purpose of job scheduling. Mixed-version operation between epoch- and time-based nodes works since we still publish epoch information in the leases for time-based nodes. From the perspective of a time-based node, an epoch-based node simply behaves as though its leniency period is 0. Epoch-based nodes will see time-based nodes delay the act of stealing a job. func MakeRegistry( ac log.AmbientContext, stopper *stop.Stopper, clock *hlc.Clock, db *client.DB, ex sqlutil.InternalExecutor, nodeID *base.NodeIDContainer, settings *cluster.Settings, histogramWindowInterval time.Duration, planFn planHookMaker, ) *Registry MakeRegistry creates a new Registry. planFn is a wrapper around sql.newInternalPlanner. It returns a sql.PlanHookState, but must be coerced into that in the Resumer functions. Cancel marks the job with id as canceled using the specified txn (may be nil). LoadJob loads an existing job with the given jobID from the system.jobs table. LoadJobWithTxn does the same as above, but using the transaction passed in the txn argument. Passing a nil transaction is equivalent to calling LoadJob in that a transaction will be automatically created. MetricsStruct returns the metrics for production monitoring of each job type. They're all stored as the `metric.Struct` interface because of dependency cycles. NewJob creates a new Job. Pause marks the job with id as paused using the specified txn (may be nil). Resume resumes the paused job with id using the specified txn (may be nil). func (r *Registry) Start( ctx context.Context, stopper *stop.Stopper, nl NodeLiveness, cancelInterval, adoptInterval time.Duration, ) error Start polls the current node for liveness failures and cancels all registered jobs if it observes a failure. func (r *Registry) StartJob( ctx context.Context, resultsCh chan<- tree.Datums, record Record, ) (*Job, <-chan error, error) StartJob creates and asynchronously starts a job from record. An error is returned if the job type has not been registered with RegisterConstructor. The ctx passed to this function is not the context the job will be started with (canceling ctx will not causing the job to cancel). type Resumer interface { // Resume is called when a job is started or resumed. Sending results on the // chan will return them to a user, if a user's session is connected. phs // is a sql.PlanHookState. Resume(ctx context.Context, phs interface{}, resultsCh chan<- tree.Datums) error // OnSuccess is called when a job has completed successfully, and is called // with the same txn that will mark the job as successful. The txn will // only be committed if this doesn't return an error and the job state was // successfully changed to successful. If OnSuccess returns an error, the // job will be marked as failed. // // Any work this function does must still be correct if the txn is aborted at // a later time. OnSuccess(ctx context.Context, txn *client.Txn) error // OnTerminal is called after a job has successfully been marked as // terminal. It should be used to perform optional cleanup and return final // results to the user. There is no guarantee that this function is ever run // (for example, if a node died immediately after Success commits). OnTerminal(ctx context.Context, status Status, resultsCh chan<- tree.Datums) // OnFailOrCancel is called when a job fails or is canceled, and is called // with the same txn that will mark the job as failed or canceled. The txn // will only be committed if this doesn't return an error and the job state // was successfully changed to failed or canceled. This is done so that // transactional cleanup can be guaranteed to have happened. // // This method can be called during cancellation, which is not guaranteed to // run on the node where the job is running. So it cannot assume that any // other methods have been called on this Resumer object. OnFailOrCancel(ctx context.Context, txn *client.Txn) error } Resumer is a resumable job, and is associated with a Job object. Jobs can be paused or canceled at any time. Jobs should call their CheckStatus() or Progressed() method, which will return an error if the job has been paused or canceled. Resumers are created through registered Constructor functions. RunningStatus represents the more detailed status of a running job in the system.jobs table. RunningStatusFn is a callback that computes a job's running status given its details. It is safe to modify details in the callback; those modifications will be automatically persisted to the database record. Status represents the status of a job in the system.jobs table. const ( // StatusPending is for jobs that have been created but on which work has // not yet started. StatusPending Status = "pending" // StatusRunning is for jobs that are currently in progress. StatusRunning Status = "running" // StatusPaused is for jobs that are not currently performing work, but have // saved their state and can be resumed by the user later. StatusPaused Status = "paused" // StatusFailed is for jobs that failed. StatusFailed Status = "failed" // StatusSucceeded is for jobs that have successfully completed. StatusSucceeded Status = "succeeded" // StatusCanceled is for jobs that were explicitly canceled by the user and // cannot be resumed. StatusCanceled Status = "canceled" ) Terminal returns whether this status represents a "terminal" state: a state after which the job should never be updated again. type UpdateFn func(txn *client.Txn, md JobMetadata, ju *JobUpdater) error UpdateFn is the callback passed to Job.Update. It is called from the context of a transaction and is passed the current metadata for the job. The callback can modify metadata using the JobUpdater and the changes will be persisted within the same transaction. The function is free to modify contents of JobMetadata in place (but the changes will be ignored unless JobUpdater is used). Package jobs imports 25 packages (graph) and is imported by 16 packages. Updated 2019-11-07. Refresh now. Tools for package owners.
https://godoc.org/github.com/cockroachdb/cockroach/pkg/jobs
CC-MAIN-2019-47
en
refinedweb
Archive for March, 2008 I work at the University of Manchester which is where the world’s first ever stored-program electronic digital computer was made back in 1948. It was originally called the Manchester Small Scale Experimental Machine but everyone called it Baby and it didn’t occur to it to mind. Before I get flamed to death by US computer historians – yes the ENIAC was built 2 years before Baby but it had a fundamentally different architecure (as explained by Alan Burlison in his blog – here). As Alan says, if you wanted to reprogram ENIAC, you needed a pair of pliars. Many people who are a lot more eloquent than me have written a lot about the history of this machine (here for example) so I won’t say too much about it here except that it had only 128 bytes of memory which were arranged in 32 x 32 bit binary words and that it had an instruction set of only 7 commands which made programming it a bit tricky to say the least. If you think you are a real programmer who is up to the challenge of coding for a 60 year old machine then Manchester University is holding a program “The Baby” competition (closing date 1 May 2008) to celebrate the Baby’s 60th anniversary. There is a photo realistic Java-based simulator of the machine, complete with example programs, over at the competition website along with an instruction manual to get you started. With only 7 instructions to learn how hard can it be? Say you have just joined an applied-maths research group* where you are expected to write a lot of numerical simulations – numerical simulations that are going to require the use of big computers in large, air conditioned rooms with a great deal of impressive looking flashenlightenblinken. Naturally, you would like to use Python for all of your programming needs as you have recently fallen in love with it and you are convinced that it’s the future. Your boss, Bob, completely disagrees with your take on the future of programming. He thinks that Python is a passing fad that will soon be forgotten. He sneeringly refers to it as a ‘ mere scripting language’ and constantly refers to you as the script kiddie. He thinks that Fortran is the only programming language worth bothering with when it comes to numerical simulations. According to Bob, Fortran is the past, present and future of computer programming – everything else is just mucking about. You argue constantly with Bob concerning the relative merits of the two languages because, although you respect Fortran, you don’t think that it’s going to be much fun to use. Eventually he pulls out his trump card – “You can’t use Python in this group because all of our screamingly fast, highly accurate, tested and debugged numerical routines are written in Fortran. We won’t use any other libraries because these are the best so – give up on Python and start learning Fortran or get another job.” Defeated…or so you thought… After a bit of googling you realize that there is light at the end of the tunnel, this problem has been solved before by making use of the Python ctypes module. First of all let’s install this module on Ubuntu: sudo apt-get install python-ctypes Taking our cue from this solution lets say that one of the functions in the Fortran library is called ADD_II and has the following source code (filename add.f) SUBROUTINE ADD_II(A,B) INTEGER*4 A,B A = A+B END Compile it into a shared library using gfortran as follows: gfortran add.f -ffree-form -shared -o libadd.so Now, create a file called add.py and copy the source code from our friendly usenet poster: from ctypes import * libadd = cdll.LoadLibrary(“./libadd.so”) # # ADD_II becomes ADD_II_ # in Python, C and C++ # method = libadd.ADD_II_ x = c_int(47) y = c_int(11) print “x = %d, y = %d” % (x.value, y.value) # # The byref() is necessary since # FORTRAN does references, # and not values (like e.g. C) # method( byref(x), byref(y) ) print “x = %d, y = %d” % (x.value, y.value) run the script as follows: python add.py and get the following error message: AttributeError: ./libadd.so: undefined symbol: ADD_II_ So, despite what we may have thought, it looks like our function has not been given the name ADD_II_ in the shared library. So what name has it been given? We could just keep guessing what the compiler might have called it or we could just ask the library itself using the nm comand: nm libadd.so 00001468 a _DYNAMIC 00001554 a _GLOBAL_OFFSET_TABLE_ w _Jv_RegisterClasses 00001458 d __CTOR_END__ 00001454 d __CTOR_LIST__ 00001460 d __DTOR_END__ 0000145c d __DTOR_LIST__ 00000450 r __FRAME_END__ 00001464 d __JCR_END__ 00001464 d __JCR_LIST__ 00001570 A __bss_start w __cxa_finalize@@GLIBC_2.1.3 00000400 t __do_global_ctors_aux 00000340 t __do_global_dtors_aux 00001568 d __dso_handle w __gmon_start__ 000003d7 t __i686.get_pc_thunk.bx 00001570 A _edata 00001574 A _end 00000434 T _fini 000002d8 T _init 000003dc T add_ii_ 00001570 b completed.6030 000003a0 t frame_dummy 0000156c d p.6028 Now I have no idea what most of that output means but it looks like the .so file contains something called add_ii_ so if I use this instead of ADD_II_ in my python script I bet it will work. python add.py x = 47, y = 11 x = 58, y = 11 The sweet smell of success. You go to Bob and tell him that you have just come up with a test script that demonstrates that you are going to be able to use the group’s Fortran libraries in your Python scripts. “That’s very nice” says Bob “but all of the really useful routines in the library make use of callback functions. Can you handle those yet?” “yes I can” you reply smugly “but this post has gone on long enough so I’ll leave the details until another time” *Note – In case you are my boss – I haven’t joined a research group so I won’t be quitting my job any day soon. I was just in a story telling mood. Oh..and this stuff will be useful for what we do – I promise!. The 29th edition of the Carnival of Mathematics has been posted over at quomodocumque. Topics include group theory, game theory, the Collatz conjecture and much more._2<<.). 1.Take one dare from Kathryn Cramer and obtain a picture from her website. 2. Steal ideas from this demonstration by Jeff Bryant. 3. Type the following incantations into Mathematica SetDirectory[“/home/mike/Desktop/random”]; image = Import[“kramer.jpg”]; xpos[x_] := Floor[x/N[2/374.] + 377/2.] ypos[x_] := Floor[x/N[2/499.] + 502/2.] imcol[x_, y_] := image[[1]][[1]][[xpos[x]]][[ypos[y]]]/256.; a = 1; b = 0.9; c = 1; Plot3D[{Sqrt[ c^2*(1 – (x^2/a^2 + y^2/b^2))], -Sqrt[c^2*(1 – (x^2/a^2 + y^2/b^2))]}, {x, -1, 1}, {y, -1, 1}, ColorFunction -> (RGBColor[imcol[#1, #2]] &), Boxed -> False, Axes -> False, AspectRatio -> 2, ViewAngle -> Pi/13, ViewPoint -> {-3.00336, 0.86708, 3.14159}, PlotRange -> All, Mesh -> False, PlotPoints -> 400] Enjoy!. Mathematica 6.0.2 was released back on February 25th but I have only just managed to find the time to install it. I tried to install it on a brand new Dell 755 with a very fresh install of Ubuntu but near the end of the install procedure I came across the following error “The installer was unable to check for a valid password file. Your Mathematica installation may be incomplete or corrupted.” I had not been given the opportunity to supply it with any licensing information so it looked like there was a problem with the installer itself. Cutting a long story sort, the solution is to use apt to install the package libstdc++5 as follows sudo apt-get install libstdc++5 This is a very common package and I guess that I have not seen this error before because libstdc++5 is automatically installed as a prerequisite for many other Ubuntu applications. Hopefully this little note will be of use to a googler or two. Anyway…I now have 6.0.2 installed and running so expect a breakdown of the new features soon.)
http://www.walkingrandomly.com/?m=200803
CC-MAIN-2020-05
en
refinedweb
How YOU can make your .NET programs more responsive with async/await in .NET Core, C# and VS Code Chris Noring Updated on ・9 min read Follow me on Twitter, happy to take your suggestions on topics or improvements /Chris When we run synchronous code we block the main Thread from doing anything else than just what's it's doing currently. This makes your software and user experience slower than it needs to be. TLDR; we have the concept of Threads in .NET/.NET Core and they are an excellent way to schedule work to be carried out in parallel. However, they might be cumbersome to use. There is, however, a library called TPL, Task Parallel Library that lives on top of the Thread model and makes it really easy to schedule and manage work. References Async return types It gives you a good intro to Tasks. Task Control Flows This talks about Control flows, how to ensure that the code happens in the right order Task Based Asynchronous programming This is more of an overview of Task-based programming How to run Tasks sequentially This talks about how to run Tasks in order, one after another. Task Cancellation This teaches you how to cancel and listen for cancellation messages for your tasks Durable Functions in Azure This shows how to do Tasks in Serverless programming and specifically Durable Functions A Recipe converting sync code to async This takes you all the way from synchronous code to gradually convert it to asynchronous code. WHAT So we mentioned TPL as a library. What do we need to know? TPL is such a central and important concept that it lives in the core APIs. It's part of the System.Threading and System.Threading.Tasks namespaces. It does a lot for us like: - Partitioning of the work - Scheduling of threads on the ThreadPool - Cancellation support - State management and other low-level details. There are some basic concepts that we need to understand. - Task, a task represent an asynchronous operation, like fetching content from a file or doing a calculation that takes time. There are some interesting properties on a Task that allows us to communicate to a UI, for example, how the asynchronous work is doing, like: - Status, this can tell us if it's currently working on something, is done, errored out or it was canceled - IsCanceled, if canceled this would be set to true - IsFaulted, if something went wrong, like an exception, this would be set to true - IsCompleted, once it has finished its operation it would be set to true - Async/Await. The awaitkeyword means that we wait for the asynchronous operation to end and by the end of the operation we are given the result, e.g var fileContent = await GetFileAsync(). Any method that uses the awaitconcept would need to have asynckeyword as part of the method header. - Blocking/Non-blocking. When we use Tasks we are not blocking and other Threads can carry out work. There are exceptions though when we use the method Wait()on a Task. Then we are forcing the code to run synchronously. We will show that in our demo in the next section. WHY A lot of things like opening up large files or carrying out a Web Request or maybe searching through your computer - are things that can be done in parallel. This means you can return back to the user much faster with a result and your app will be perceived as faster and more responsive. Web Development already uses the concept of Tasks heavily, which is a central concept in TPL. Learning how to use TPL can really make your applications more responsive. My hope is that you with this article feel more empowered to use TPL and Tasks. DEMO In our Demo we will demonstrate the following: - Authoring methods, How to author methods using async/awaitand how to return different types - Control flow, we will show how to wait for all as well as specific Tasks - Blocking code, we will show how the usage of Resultas well as Wait()affects your code Scaffold a project Let's start by creating a solution like so: mkdir tasks cd tasks dotnet new sln This should create a solution file. Next, we will create a console project like so: dotnet new solution -o task-demo and now add it to the solution like so: dotnet sln add task-demo/task-demo.csproj Ok, we are ready to start coding. Open up an IDE, I'm gonna go with VS Code. Authoring methods Let's open up the file Program.cs and add the following method inside of the class Program: static async Task<int> Sum(int a, int b) { var result = await Task.FromResult(a + b); return result; } There are some interesting things that go on above: - Return type, Task<int>. This tells us that it will be a Task that once resolved will return something of type int. Task.FromResult(), This creates a Task given a value. We give it the calculation to perform, e.g a+b. - Async/Await, We can see how we use the asynckeyword inside of the method to wait for the result to arrive back to us. This needs to be followed by the asynckeyword to ensure the compiler is happy. It's easy to think that the above method above doesn't need to be asynchronous but imagine instead that this is a calculation that takes time, then it would make more sense. One other thing, Task.FromResult is used when the answer is immediately known so it's status is RanToCompletion and the answer is available right away so you can argue that await is unnecessary, it's already available on the Task.Result property. Another way to do the above is: static async Task<int> Sum2(int a, int ab) { var result = await Task.Run(() => { // do some time-consuming work return a + b; }) return result; } await Sum2(1,2) Control flow There's more to Tasks than just marking them async. We can ensure to wait for all or some of the tasks to finish before carrying on with our code. We have some constructs that help us control this flow: Task.WaitAll(), this one takes a list of Tasks in. What you are essentially saying is that all tasks need to finish before we can carry on, it's blocking. You can see that by it returning voidA typical use-case is to wait for all Web Requests to finish cause we want to return a result that consists of us stitching all their data together Task.WaitAny(), we give it a list of Tasks here as well but the meaning is different. We say that as long as any of the Task has finished we are good. This usually a race for data towards an endpoint or search for a file/file content on a disk. We don't care who finished first, as long as we get a response. This is also blocking and waiting for one of the Tasks to finish Task.WhenAll(), this gives you a Taskback that you can interact with. When all of the tasks have finished it will resolve. Task.WhenAny(), this gives you a Taskback that you can interact with. When one of the Tasks has finished then it will resolve. Let's create a demo of a Control flow. We will fake carrying out time-consuming work by adding an additional method to our class, like so: static async Task DoSomething() { await Task.Delay(2000); } Demo - Control flow Now we can add some control flow code in our Main() method like so: var start = DateTime.Now; var taskSum = Sum(2,2); var taskDelay = DoSomething(); Task.WaitAll(taskSum, taskDelay); end = DateTime.Now; Console.WriteLine("Time taken {0}",end - start); Our full code in Program.cs should now look like this: using System; using System.Threading.Tasks; using System.IO; namespace task_demo { class Program { static async Task DoSomething() { await Task.Delay(2000); } static async Task<int> Sum(int a, int b) { var result = await Task.FromResult(a + b); return result; } static void Main(string[] args) { var start = DateTime.Now; var taskSum = Sum(2,2); var taskDelay = DoSomething(); Task.WaitAll(taskSum, taskDelay); end = DateTime.Now; Console.WriteLine("Time taken! {0}", end-start); } } } Let' compile: dotnet build and run it: dotnet run We should get the following response: 4 Time taken! 00:00:02.0026920 Even though the calculation from calling Sum() took a few milliseconds, we don't get any response until 2 seconds later, when DoSomething() has finished. If we shift our code now from WaitAll to WhenAll we would get very different behavior. The code would have kept going and reported this instead: 4 Time taken! 00:00:00.0235860 So the lesson here is that if we want the code to wait at a specific point, using WaitAny is a good idea but if you want to start up a lot of asynchronous work then use When.... We can still make the code behave correctly with WhenAll but we would need to investigate the status like so: var twoTasks = Task.WhenAll(taskSum, taskDelay); if(twoTasks.IsCompleted) { var end = DateTime.Now; Console.WriteLine("{0}", taskSum.Result); } DEMO - Wait any To test this one out we create three new methods that mock opening up files. Each of the three methods has a delay built in that differs: static async Task<string> ReadFile1() { await Task.Delay(3000); return "file1"; } static async Task<string> ReadFile2() { await Task.Delay(4000); return "file2"; } static async Task<string> ReadFile3() { await Task.Delay(2000); return "file3"; } Let's update our Program() method with some code as well: var task1 = ReadFile1(); var task2 = ReadFile2(); var task3 = ReadFile3(); start = DateTime.Now; Task.WaitAny(task1, task2, task3); Console.WriteLine("Task1, completed: {0}", task1.IsCompleted); Console.WriteLine("Task2, completed: {0}", task2.IsCompleted); Console.WriteLine("Task3, completed: {0}", task3.IsCompleted); Console.WriteLine("Task3, completed: {0}", task3.Result); end = DateTime.Now; Console.WriteLine("Time taken! {0}", end - start); As you can see above, we are waiting for one of the three tasks to finish, with this construct: Task.WaitAny(task1, task2, task3); Given what we know of the methods being called, ReadFile3() should finish first, after 2 seconds, but let's test that by running our program: Task1, completed: False Task2, completed: False Task3, completed: True Task3, completed: file3 Time taken! 00:00:02.0031370 We can see above that Task3 is completed and the other tasks haven't completed yet. Using Async APIs Ok, we now understand more about async and is able to leverage that on existing APIs. Let's look at reading the content of a file. Normally you would create a method like so: static async string ReadTxtFile() { using(var sr = new StreamReader(File.Open("test.txt", FileMode.Open))) { return sr.ReadToEnd(); } } The above would block though and you wouldn't be able to do much else while this finishes. Imagine this is a really large file then it would be really noticeable. If we rewrite the method to use an async version we would instead get code looking like this: static async Task<string> ReadTxtFile() { using(var sr = new StreamReader(File.Open("test.txt", FileMode.Open))) { return await sr.ReadToEndAsync(); } } This doesn't block and everyone is happy. Blocking code One of the tricky parts of using TPL is knowing what calls block. You are all happy that your code is now asynchronous but suddenly you end up blocking anyway. So what shall we look out for? Well, we touched upon this subject already: WaitAlland WaitAnyblocks, the rule of thumb here seems to be that they return void and use the word Wait.... Sometimes you want it to wait though, so learn to be intentional with block/non-block task.Result, this also blocks and waits for the result to be available Wait(), this method on a Task will block and cause you to wait here until the code has finished, for example Task.Delay(2000).Wait() Full code This is the full code I was playing around with if you want to explore for yourself: using System; using System.Threading.Tasks; using System.IO; namespace task_demo { class Program { static async Task<string> ReadTxtFile() { using(var sr = new StreamReader(File.Open("test.txt", FileMode.Open))) { return await sr.ReadToEndAsync(); } } static string ReadFileSync1() { Task.Delay(2000).Wait(); return "content1"; } static string ReadFileSync2() { Task.Delay(2000).Wait(); return "content2"; } static string ReadFileSync3() { Task.Delay(2000).Wait(); return "content3"; } static async Task DoSomething() { await Task.Delay(2000); } static async Task<int> Sum(int a, int b) { var result = await Task.FromResult(a + b); return result; } static async Task<string> ReadFile1() { await Task.Delay(3000); return "file1"; } static async Task<string> ReadFile2() { await Task.Delay(4000); return "file2"; } static async Task<string> ReadFile3() { await Task.Delay(2000); return "file3"; } static void Main(string[] args) { var start = DateTime.Now; var c1 = ReadFileSync1(); var c2 = ReadFileSync2(); var c3 = ReadFileSync3(); var end = DateTime.Now; Console.WriteLine("Time taken {0}", end-start); start = DateTime.Now; var taskSum = Sum(2,2); var taskDelay = DoSomething(); Task.WaitAll(taskSum, taskDelay); end = DateTime.Now; Console.WriteLine("{0}",taskSum.Result); Console.WriteLine("Time taken! {0}", end-start); var task1 = ReadFile1(); var task2 = ReadFile2(); var task3 = ReadFile3(); start = DateTime.Now; Task.WaitAny(task1, task2, task3); Console.WriteLine("Task1, completed: {0}", task1.IsCompleted); // this forces everyone to wait for this Task1 // Console.WriteLine("Task1, completed: {0}", task1.Result); Console.WriteLine("Task2, completed: {0}", task2.IsCompleted); Console.WriteLine("Task3, completed: {0}", task3.IsCompleted); Console.WriteLine("Task3, completed: {0}", task3.Result); end = DateTime.Now; Console.WriteLine("Time taken! {0}", end - start); } } } Summary In summary, we learned about the concept of Tasks and their anatomy. Additionally, we learned about Control Flows and we also discussed blocking/non-blocking code. There is more to learn though like how to cancel Tasks. Im gonna save that one for a separate article. I will add a link to Cancellation in the References section of this article. await Task.FromResultthat's a good one 😂 You're confusing Task.Runwith Task.Result. The latter doesn't do any calculations, it just returns a completed task that you don't need to await. In fact, awaiting it just creates an unnecessary state machine that can hurt throughput. Well the Task result is immediately known, i.e 1+2, which is what I 'm using it for docs.microsoft.com/en-us/dotnet/ap.... Is it the best use of it? Probably not. Could I have been using Task.Run? Probably. The whole point of that method is generally to showcase the async/await combination. I think you are reading too much into a first sample method Alexey. I was making an analogy to Promise.resolve in the JavaScript world... The point here was that using awaitwith Task.FromResultis unnecessary and counterproductive. That I agree with.. I was showcasing async/await .. I will update the text to talk about the difference of Task.Run and Task.FromResult Just to clarify, "Task.WaitAll(...)" is essentially same as "await Task.WhenAll(...)". Please correct me if I am missing something. If I am correct in my above statement, then shouldn't latter be the best approach to wait for all the tasks to complete? WaitAlland WhenAllis very different. WaitAllblocks the code on that line. WhenAllreturns directly with a Task.. As for await Task.WhenAll(), yes you can do that... As for one approach is better than another, not sure tbh.. I do know that when I get a task back I have the capability check it's state, cancel it and so on.. With that said, I suppose WhenAllgives us more fine-grained control to affect all three Tasks like cancel all, cancel one etc... With WaitAllI'm stuck at that line so it might be tricky to do anything but just wait. So if we ar talking about more fine-grained control I lean on agreeing with you. Thanks Chris for this post! Thanks Carlos :) Hi Chris, awesome article! I have a question. When either WhenAny or WhenAll returns with a task, are the tasks already executing at that point and could finish before interacting with it? I would say yes. They are already running.. You can check that on task.Statusfor a specific Task or var taskWhenAll = Task.WhenAll(t1,t2,t3)and taskWhenAll.Status Any thoughts on continuations with tasks? I haven't yet had a need to use them, but it seems like a easy way to ensure behaviour executes after a task is completed. they are good.. definitely use them. I am linking to them in the references section. I just thought the article was long enough.. :) Are you meant to say WaitAll to WaitAny in this section? thepracticaldev.s3.amazonaws.com/i... hi... No I mean WhenAll. So WhenAll returns right away, it returns a Task, which means it carries out the next line of code which is to calculate time taken. WaitAll blocks and this why we get a higher time taken.. (We wait until the slowest task in WaitAll have finished until we continue with the next line of code) Awesome, thanks for the clarification
https://practicaldev-herokuapp-com.global.ssl.fastly.net/dotnet/how-you-can-make-your-net-programs-faster-with-asynchronous-code-in-net-core-c-and-vs-code-471c
CC-MAIN-2020-05
en
refinedweb
In part I I motivated that developing OSGi components is plain and simple by Declarative Services and the provided annotations. We learned how to create a component, add lifecycle methods and reference services. If you haven’t read the first part yet, make sure to go there first. Usually a component takes some configuration. So let’s have a look at this next. Component Configurations If you want to make your component configurable, the best way of doing this is to leverage the OSGi Configuration Admin (another spec from the OSGi compendium with again a great implementation at Apache Felix). Configuration Admin is a service persisting configurations – these configurations are dictionaries where the key is a string and the value can be one of the simple Java types or an array or collection of such a type. This is usually sufficient for most components. Configuration Admin nicely abstracts managing the configuration from your component. As a component developer you don’t need to know where the actual configuration is stored and how it ends up there. Without a component container, you would ask the configuration admin for “your” configuration (though there is some injection support through the ManagedService interface) – but fortunately with DS the container takes care of this and provides your component with the configuration. The component might get the configuration as a parameter for the activate method. As mentioned Configuration Admin stores configurations as dictionaries. Whereas the names are of type String, the value can be any type. While your component might expect an integer, e.g. for a port, the actual value stored might be of type String holding an integer value. Therefore it is good style to not assume a specific type but try to convert whatever you get into the expected type. To avoid putting the burden of doing this on the component developer and to support type safe configurations, the configuration for a component can be described in Java. While the following might look a little bit out of the ordinary, stick with me, you’ll get used to it pretty soon and simply love it. The way to describe a configuration is by defining a so called Component Property Type: an annotation describing all configuration properties. Let’s assume our component has three configuration properties, then the following annotation would do: public @interface MyComponentConfig { String welcome_message() default "Hello World!"; int welcome_count() default 3; boolean output_goodbye() default true; } Defining an annotation instead of a simple interface has the advantage that we can directly specify default values for each property. If no value for a property is stored in configuration admin, the default value is used. Let’s see how to use this: import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; @Component public class MyFirstComponent { @Activate protected void activate( MyComponentConfig config ) { for(int i = 0; i < config.welcome_count(); i++ ) { System.out.println(config.welcome_message()); } } } When the above component is activated, SCR tries to get a configuration from the configuration admin and converts it into the used annotation type. Therefore the passed in object returns the value in the correct type for each property. As mentioned if there is no value, the default is returned. This makes handling of configurations very simple and avoids all the usual boilerplate code. The OSGi specification for Declarative Services explains in detail how the type conversion is done and what happens if a value can’t be converted. It also defines the conversion rule from the name of a property in the annotation to a property in configuration admin. In the example above we see the underscore in the names, this is acutally converted to a dot in the property name. Taking configurations is as easy as this: define your set of configuration properties as an annotation and pass it as an argument to the activate method. Of course, if you don’t need configuration, leave out these steps and use the zero argument activate method signature – or if you don’t need the activate method at all, leave it out completely. With this knowledge we can already develop configurable components capable of using other services. But how do you provide a service for others to be used? Services Offering a service usually consists of two steps. First you define the service API and second you implement this API. Of course, in some cases the API might already exist as someone else defined the interface. If you define your own interface, put it into a public package and export this package – however, as already noted above for the component, a service implementation should never be public but in a private package. It depends on your use case, if you put the interface and the implementation in the same bundle or create an API bundle and an implementation bundle. If you’re implementing an existing interface, this usually is already in another bundle and you can just import it. And if you create public API, don’t forget to use proper versioning for these packages. Have a look at the semantic versioning whitepaper! Offering a service is implementing the corresponding interface and registering the component in the OSGi service registry as the service. With the annotations you can just use the @Component annotation. Assume there is an interface EventHandler and your component should be registered as a service for this interface: import org.osgi.service.component.annotations.Component; @Component public class MyFirstService implements EventHandler { ....// implement the EventHandler interface } Without further specifying anything at the @Component annotation, a component is registered as a service for all interfaces it directly implements. In this case this is the EventHandler. While this is very convenient, it comes with the problem, that as soon as your component is implementing an interface directly, it gets registered as this service. In some cases this is not what you want. Therefore I suggest to: - Always explicitely list the service interfaces the component implements: @Component(service = EventHandler.class} - As a default always set the service attribute of the component annotations to the empty array. This prevents the automatic registration: @Component(service = {}) If you follow these simple rules, you can see directly by looking at the @Component annotation which services this component implements and you avoid accidental service registrations, e.g. when refactoring your implementation. Lifecycle of a Service A component which does not provide a service is active for as long as it is satisfied (all referenced services are available and some other conditions we get to later). In contrast, services are instantiated lazy or on demand by DS. This means, as long as no one is using your service, your service is never created nor activated! In most cases this is fine. But there is a catch with this approach one should be aware of: if someone else is starting to use your service, it gets created and activated. As soon as your service is not used anymore, it gets deactivated and destroyed. The OSGi spec does not mandate this behavior. The implementation of Declarative Service is free to keep your service around for some time until it is disposed. By default the current Apache Felix implementation immediately disposes such components. However it is possible to configure such a detailed disposal of components. But this leaves you with the problem of configuring this correctly which might not be that easy. On the other hand, frequent creation and disposal of an “expensive” service might create a performance bottleneck. For example if this happens being triggered by an event, a request and/or if your service is doing some computation in the activate method. In many cases, your actual service is combining a “component” and a “service” part. While the “component” part is the expensive one and should only be done once, the “service” part is lightweight and might simply use the component part. In such cases you might think about splitting your implementation accordingly. Or you can either think about holding the service by someone else and therefore keep a reference to it around (which in general sounds hacky though there are valid use cases). Or you can use the immediate flag on the @Component: @Component(service=EventHandler.class, immediate=true) With immediate set to true, the component is activated as soon as possible and kept as long as possible. Obviously, this increases things like startup time, memory consumption etc. So it should really be used with care and maybe only after problems are encountered in this area. In the past the only situation where we encountered this was implementing an event handler. But with today’s event admin implementations this isn’t even true anymore either. But for completeness lets have a look at that problem: an implementation of the event admin as defined in the OSGi Event Admin Specification might fetch an event handler (service org.osgi.service.event.EventHandler) each time an event should be delivered to this handler. Clearly, this has the advantage that event handlers are only used if there is an event for such a handler. While this might work with a few events, with very frequent events, especially in a multi threaded environment, the same event handler might receive quiet a lot events, even “in parallel”. In the past we suggest to make your event handler implementation immediate as otherwise it is potentially created/destroyed with each event for this handler! However, even this is up to the implementation of the event admin. The latest Apache Felix event admin implementation and the Equinox event admin implementation do not create/destroy the instance on each request, they rather create it once the first event for this component arrives and keep a reference to it from that point on. But as this is implementation specific, the above advice might be handy. And again, only use immediate if really required. And with this the simple introduction to Declarative Services ends: you now know: - how to create components - how to configure components - how to reference services - how to provide services Of course with most of this we only touched the simple case, which is really sufficient for most use cases. I’ll continue this series with more advanced stuff in the future.
https://blog.osoco.de/2015/08/osgi-components-simply-simple-part-ii/
CC-MAIN-2020-05
en
refinedweb
Handling financial data using React and RxJS-based methods (with redux-observable and websockets). Piotr Tylicki ・4 min read This example needs basic knowledge of React and Redux config - if you are not familiar with these concepts, you can check some examples here. We will use Finnhub API, the free-access, 'RESTful API for stocks, currencies and crypto', in order to build RxJS-connected, react-based solution, that will deliver some real-time financial data. We will also use Redux-observable, that is a great solution for connecting React application with RxJS magic. Redux-observable uses all RxJS powers as a middleware for Redux, a state container for JS apps, used mainly with React. RxJS and Redux-observale RxJS is the library that introduces ReactiveX pattern to JavaScript. The ReactiveX pattern is also widely used with different platforms/languages, such as RxPY, RxJava, RX.rb... you can read more about all platforms here. RxJS itself has quite steep learning curve, but it has a lot of low-level operators that help to handle all side-effects and asynchronous data manipulation. There is already an article that covers basics about observables and RxJS: Intro to Observables with RxJS Sebastian Hewelt ・ Oct 21 ・ 5 min read Redux-observable, on the other hand, is a library that allows to use RxJS as a middleware for Redux, the state management container, widely used with React - so basically RxJS can be used in the place where we need it most in our React application: it handles all asynchronous data that is kept inside our application state. Basic setup What we are going to build is a simple app that handles real-time data (and displays current value of stock symbol), using connection of websocket with RXJS. First we need to create basic react+redux project structure, containing basic actions and reducers directories, and connect the store using react-redux <Provider>. import { Provider } from "react-redux"; function App() { return ( <Provider store={store}> <div className="App"> <Repositories /> </div> </Provider> ); } Please check App.js file in the example above. After creating basic project structure we need to connect redux-observable middleware: import { createStore, applyMiddleware } from "redux"; import { createEpicMiddleware, combineEpics } from "redux-observable"; const epicMiddleware = createEpicMiddleware(); const store = createStore( reducer, { isLoading: false, isError: false, repositories: [] }, applyMiddleware(epicMiddleware) ); export const rootEpic = combineEpics(actions.stockDataEpic); rootEpic Object is a concept similar to rootReducer object from redux. In order to create it, we need to use combineEpics function, in the same way that we are using combineReducers from redux. Next step is to run our middleware: epicMiddleware.run(rootEpic); Now we can move to actions/index.js file that contains action creators: export function openStockStream(ticker) { return { type: START_STREAM, ticker }; } export function getDataStop() { return { type: GET_DATA_CANCEL }; } export function getDataDone(data) { return { type: GET_DATA_DONE, payload: { // data retuned in this format from Finnhub websocket [data.data[0].s]: data.data[0] } }; } export function getDataFailed(error) { return { type: GET_DATA_FAILED, payload: error }; } Creating an Epic An Epic is the core primitive of redux-observable. It is a function which takes a stream of actions and returns a stream of actions. Actions in, actions out. This is a basic function delivered by Redux-observable, that allows us to connect RxJS observable and handle it inside our action function. It takes an action stream (note that it is written in convention with $ sign: action$ - this kind of notation informs us that this is the stream itself). import { ofType } from 'redux-observable'; ... export const stockDataEpic = action$ => { return action$.pipe( ofType(START_STREAM), operator ofType allows us to filter that exact action type that we want to use here. Next step is to config socket connection: import { webSocket } from "rxjs/webSocket"; const FINNHUBKEY = //Finnhub key; const socket = webSocket(`wss://ws.finnhub.io?token=${FINNHUBKEY}`); So now the Epic can handle websocket connection, and it can look like this: export const stockDataEpic = action$ => { return action$.pipe( ofType(START_STREAM), mergeMap(action => socket .multiplex( () => ({ type: "subscribe", symbol: action.ticker }), () => ({ type: "unsubscribe", symbol: action.ticker }), msg => msg.type === "trade" && msg.data[0].s === action.ticker ) .pipe( map(response => getDataDone(response)), catchError(error => { console.log("err:", error); return of(getDataFailed("Connection error!")); }), takeUntil(action$.pipe(ofType(GET_DATA_CANCEL))) ) ) ); }; Multiplex is a specific operator for WebSocketSubject that simulates opening several socket connections, while in reality maintaining only one. It takes three parameters: - subscription message function - unsubscription message function - filter function - if true, message is passed down the stream, otherwise it's skipped More about info RxJS websockets Another thing is pipe operator that helps to sort usage of different operators while resolving the response - here we are using just basic three: map, catchError and takeUntil. Actions handled by map operator are dispatched and handled by the reducer: import * as actions from '../actions'; export const reducer = (state, action) => { switch (action.type) { case actions.GET_DATA_REQUESTED: return { ...state, isLoading: true}; case actions.GET_DATA_DONE: return { ...state, isLoading: false, repositories: { ...state.repositories, ...action.payload }, isCancelled: false }; action.payload.response, isCancelled: false }; case actions.GET_DATA_FAILED: return { ...state, isLoading: false, isError: true, error: action.payload } case actions.GET_DATA_CANCEL: return { ...state, isLoading: false, isCancelled: true } default: return state; } }; Subscribing for stock symbols So that's it! Now, back in App.js file, in the component's opening lifecycle method, we can subscribe to multiple symbols at once, using our dynamic Epic: componentDidMount() { this.openBasicStocks(); } openBasicStocks = () => { const { openStockStream } = this.props; ["AAPL", "NFLX", "FB", "AMZN", "GOOGL", "BINANCE:BTCUSDT"].forEach(s => openStockStream(s) ); }; That's the basic setup for websocket and redux-observable. On this level it's not very complicated, but handling more complex data with more sophisticated RxJS operators could require more time to learn. Nevertheless, RxJS is a great tool, and redux-observable allows us to use all it's power inside our React apps. Please notice, that some methods does not come directly from redux-observable package, and are needed to be imported directly from rxjs, so our package.json file needs to contain both libraries: "dependencies": { ... "redux-observable": "^1.2.0", "rxjs": "^6.5.3" }, If I can improve any information here, please feel free to get in touch with me. Happy coding! How to find open source projects as a new developer? Maybe I'm missing something, but it seems hard to find meaningful open-source p...
https://practicaldev-herokuapp-com.global.ssl.fastly.net/netguru/handling-financial-data-using-react-and-rxjs-based-methods-with-redux-observable-and-websockets-3nm9
CC-MAIN-2020-05
en
refinedweb
A python package to partially automate search term selection and writing search strategies for systematic reviews Project description Ananse The Ananse package is a python package designed to partially automate search term selection and writing search strategies for systematic reviews. Read the documentation at baasare.github.io/ananse and ananse.readthedocs.io/ Setup Ananse requires python 3.7 or higher Using pip pip install ananse Directly from the repository git clone python ananse/setup.py install Quick start Writing your own script from ananse import Ananse min_len = 1 # minimum keyword length max_len = 4 # maximum keyword length # Create an instance of the package test_run = Ananse() # Import your naive search results from the current working directory imports = test_run.import_naive_results(path="./") # Columns to deduplicate imported search results columns = ['title', 'abstract'] #de-duplicate the imported search results data = test_run.deduplicate_dataframe(imports, columns) #extract keywords from article title and abstract as well as author and database tagged keywords all_terms = test_run.extract_terms(data, min_len=min_len, max_len=max_len) #create Document-Term Matrix, with columns as terms and rows as articles dtm, term_column = test_run.create_dtm(data.text, keywords=all_terms, min_len=max_len, max_len=max_len) #create co-occurrence network using Document-Term Matrix graph_network = test_run.create_network(dtm, all_terms) #plot histogram and node strength of the network test_run.plot_degree_histogram(graph_network) test_run.plot_degree_distribution(graph_network) #Determine cutoff for the relevant keywords cutoff_strengths = test_run.find_cutoff(graph_network, "spline", "degree", degrees=3, knot_num=1, percent=0.879956, diagnostics=True) #get suggested keywords and save to a csv file suggested_keywords = test_run.get_keywords(graph_network, "degree", cutoff_strengths, save_keywords=True) #Print suggested keywords for word in suggested_keywords: print(word) Using Ananse Test Script python tests/ananse_test References This is a python implementation of the R package as mentioned in paper An automated approach to identifying search terms for systematic reviews using keyword co‐occurrence networks by Eliza M. Grames, Andrew N. Stillman Morgan W. Tingley and Chris S. Elphick Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/ananse/1.1.1/
CC-MAIN-2020-05
en
refinedweb
Syntax highlighting component for React React Syntax Highlighter syntax highlighting component for react with prismjs or highlightjs ast using inline styles. Syntax highlighting component for React using the seriously super amazing lowlight and refractor by wooorm Install npm install react-syntax-highlighter --save props. import SyntaxHighlighter from 'react-syntax-highlighter'; import { docco } from 'react-syntax-highlighter/styles/hljs'; const Component = () => { const codeString = '(num) => num + 1'; return <SyntaxHighlighter language='javascript' style={docco}>{codeString}</SyntaxHighlighter>; } Prism. import SyntaxHighlighter from 'react-syntax-highlighter/prism'; import { dark } from 'react-syntax-highlighter/styles/prism'; const Component = () => { const codeString = '(num) => num + 1'; return <SyntaxHighlighter language='javascript' style={dark}>{codeString}</SyntaxHighlighter>; } Light. import SyntaxHighlighter, { registerLanguage } from "react-syntax-highlighter/light"; import js from 'react-syntax-highlighter/languages/hljs/javascript'; import docco from 'react-syntax-highlighter/styles/hljs/docco'; registerLanguage('javascript', js); You can require react-syntax-highlighter/prism-light to use the prism light build instead of the standard light build. import SyntaxHighlighter, { registerLanguage } from "react-syntax-highlighter/prism-light"; import jsx from 'react-syntax-highlighter/languages/prism/jsx'; import prism from 'react-syntax-highlighter/styles/prism/prism'; registerLanguage('jsx', jsx); Async Build For optimal bundle size for rendering ASAP, there's a async version of prism light. This versions requires you to use a bundler that supports the dynamic import syntax, like webpack. This will defer loading of refractor (17kb gzipped), while refractor loads the code will show with line numbers but without highlighting. import SyntaxHighlighter, { registerLanguage } from "react-syntax-highlighter/prism-async"; import js from 'react-syntax-highlighter/languages/hljs/javascript'; import docco from 'react-syntax-highlighter/styles/hljs/docco'; registerLanguage('javascript', js);
https://reactjsexample.com/syntax-highlighting-component-for-react-with-prismjs-or-highlightjs-ast-using-inline-styles/
CC-MAIN-2020-05
en
refinedweb
Getting Started Build an iOS app using the Amplify Framework which integration into your iOS. Install Cocoapods: From a terminal window navigate into your Xcode project’s application directory and run the following: $ cd ./YOUR_PROJECT_FOLDER $ sudo gem install cocoapods $ pod init Open the created Podfile in a text editor and add the pod for core AWS Mobile SDK components to your build. target :'YOUR-APP-NAME' do use_frameworks! pod 'AWSCore', '~> 2.12.0' pod 'AWSAppSync', '~> 2.14.2' # other pods end Install dependencies by running the following command: pod install --repo-update Close your Xcode project and reopen it using ./YOUR-PROJECT-NAME.xcworkspace file. Remember to always use ./YOUR-PROJECT-NAME.xcworkspace to open your Xcode project from now on. Build your Xcode project. Step 2: Initialize your project In a terminal window, navigate to your project folder (the folder that contains your xcodeproj file), and run the following command (for this app, accepting all defaults is OK): $ cd ./YOUR_PROJECT_FOLDER $ amplify init #accept defaults The awsconfiguration.json configuration file should be created in the root directory. Step 3: Add config What is awsconfiguration.json? Rather than configuring each service through a constructor or constants file, the AWS SDKs for iOS support configuration through a centralized file called awsconfiguration.json which defines all the regions and service endpoints to communicate. Whenever you run amplify push, this file is automatically created allowing you to focus on your Swift application code. On iOS projects the awsconfiguration.json will be placed into the root directory and you will need to add it to your Xcode project. In the Finder, drag awsconfiguration.json into Xcode under the top Project Navigator folder (the folder name should match your Xcode project name). When the Options dialog box appears, do the following: - Clear the Copy items if neededcheck box. - Choose Create groups, and then choose Finish. Step 4: Add API and Database Add a GraphQL API to your app and automatically provision a database by running the the following command from the root of your application directory (accepting all defaults is OK): $ amplify add api #select 'GraphQL' service, and 'API Key' for the authorization type Learn more about annotating GraphQL schemas and data modeling. Step 5: Push changes Create the required backend resources for your configured API using the amplify push command. Since you added an API, the amplify push process will automatically enter the codegen process and prompt you for configuration. Accept the defaults. The codegen process generates a file named API.swift in your application root directory after the completion of amplify push command. The CLI flow for push command is shown below: $ amplify push ? Are you sure you want to continue?: Yes ? Do you want to generate code for your newly created GraphQL API: Yes ? Step 6: Add generated code What is API.swift? API.swift (or an alternate name chosen by you in CLI flow) contains the generated code for GraphQL statements such as queries, mutation, and subscriptions. This saves you time as you don’t have to hand author them. From the Finder window, drag and drop the generated API.swift to the Xcode project under the top Project Navigator folder whose name matches your Xcode project name. When the Options dialog box appears, do the following: - Clear the Copy items if neededcheck box. - Choose Create groups, and then choose Finish. Step 7: Integrate into your app Initialize the AppSync client inside your application delegate:) print("Initialized appsync client.") } catch { print("Error initializing appsync client. \(error)") } // other methods return true } } Next, in your application code where you wish to use the AppSync client (like your View Controller) reference this in the viewDidLoad() lifecycle method: import AWSAppSync class Todos: UIViewController{ //Reference AppSync client var appSyncClient: AWSAppSyncClient? override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.shared.delegate as! AppDelegate appSyncClient = appDelegate.appSyncClient } } You can now add data to your database with a mutation function as shown below: func runMutation(){ } print("Mutation complete.") } } Next, query the data using function below: func runQuery(){ appSyncClient?.fetch(query: ListTodosQuery(), cachePolicy: .returnCacheDataAndFetch) {(result, error) in if error != nil { print(error?.localizedDescription ?? "") return } print("Query complete.") result?.data?.listTodos?.items!.forEach { print(($0?.name)! + " " + ($0?.description)!) } } } Note: The AppSync API is asynchronous, which means that simply invoking runMutationand runQueryback-to-back may not work as expected, because the mutation will not complete before the query is sent. If you want to ensure that a mutation is complete before issuing a query, use the mutation’s callback to trigger the query as shown below: func runMutation(){ let mutationInput = CreateTodoInput(name: "Use AppSync", description:"Realtime and Offline") appSyncClient?.perform(mutation: CreateTodoMutation(input: mutationInput)) { [weak self] (result, error) in // ... do whatever error checking or processing you wish here self?.runQuery() } } You can also setup realtime subscriptions to data: var discard: Cancellable? func subscribe() { do { discard = try appSyncClient?.subscribe(subscription: OnCreateTodoSubscription(), resultHandler: { (result, transaction, error) in if let result = result { print("CreateTodo subscription data:" +result.data!.onCreateTodo!.name + " " + result.data!.onCreateTodo!.description!) } else if let error = error { print(error.localizedDescription) } }) print("Subscribed to CreateTodo Mutations.") } catch { print("Error starting subscription.") } } Call the runMutation(), runQuery(), and subscribe() iOS SDK by passing your credentials from the AWSMobileClient to the service call constructor. See SDK Setup Options for more information.
https://aws-amplify.github.io/docs/sdk/ios/start
CC-MAIN-2020-05
en
refinedweb
Building virtualised network topologies has been one of the best ways to learn new technologies and to test new designs before implementing them on a production network. There are plenty of tools that can help build arbitrary network topologies, some with an interactive GUI (e.g. GNS3 or EVE-NG/Unetlab) and some “headless”, with text-based configuration files (e.g. vrnetlab or topology-converter). All of these tools work by spinning up multiple instances of virtual devices and interconnecting them according to a user-defined topology. Problem statement Most of these tools were primarily designed to work on a single host. This may work well for a relatively small topology but may become a problem as the number of virtual devices grows. Let’s take Juniper vMX as an example. From the official hardware requirements page, the smallest vMX instance will require: - 2 VMs - one for control and one for data plane - 2 vCPUs - one for each of the VMs - 8 GB of RAM - 2GB for VCP and 6GB for VFP This does not include the resources consumed by the underlying hypervisor, which can easily eat up another vCPU + 2GB of RAM. It’s easy to imagine how quickly we can hit the upper limit of devices in a single topology if we can only use a single hypervisor host. Admittedly, vMX is one of the most resource-hungry virtual routers and using other vendor’s virtual devices may increase that upper limit. However, if the requirement is to simulate topologies with 100+ devices, no single server will be able to cope with the required load and a potential resource contention may lead to instabilities and various software bugs manifesting themselves in places we don’t expect. Exploring possible solutions Ideally, in large-scale simulations, we’d want to spread the devices across multiple hosts and interconnect them so that, from the device perspective, it’d look like they are still running on the same host. To take it a step further, we’d want the virtual links to be simple point-to-point L2 segments, without any bridges in between, so that we don’t have to deal with issues when virtual bridges consume or block some of the “unexpected” traffic, e.g. LACP/STP on Linux bridges. Containers vs VMs It’s possible to build multi-host VM topologies on top of a private cloud like solution like OpenStack or VMware. The operational overhead involved would be minimal as all the scheduling and network plumbing should be taken care of by virtual infrastructure manager. However this approach has several disadvantages: - In order to not depend on the underlay, all inter-VM links would need to be implemented as overlay (VMware would require NSX) - VMs would still be interconnected via virtual switches - Life-cycle management of virtual topologies is not trivial, e.g. VMware requires DRS, OpenStack requires masakari - Injecting of additional data into VMs (e.g. configuration files) requires guest OS awareness and configuration (e.g. locating and mounting of a new partition) In contrast, containers provide an easy way to mount volumes inside a container’s filesystem, have plenty of options for resource scheduling and orchestrators and are substantially more lightweight and customizable. As a bonus, we get a unified way to package, distribute and manage lifecycle of our containers, independent from the underlying OS. Note: AFAIK only Arista and Juniper build docker container images for their devices (cEOS and cSRX). However it is possible to run any VM-based network device inside a docker container, with many examples and makefiles available on virtnetlab. Kubernetes vs Swarm If we focus on Docker, the two most popular options for container orchestration would be Kubernetes and Swarm. Swarm is a Docker’s native container orchestration tool, it requires less customisation out of the box and has a simpler data model. The primary disadvantages of using Swarm for network simulations are: - Lack of support for privileged containers (network admin (CAP_NET_ADMIN) capabilities may be required by virtualised network devices) - Unpredictable network interface naming and order inside the container - Docker’s main networking plugin libnetwork is opinionated and difficult to extend or modify On the other hand, the approach chosen by K8s provides an easier way to modify the default behaviour of a network plugin or to create a completely new implementation. However, K8s itself imposes several requirements on CNI plugins: - All containers can communicate with all other containers without NAT - All nodes can communicate with all containers (and vice-versa) without NAT - The IP that a container sees itself as is the same IP that others see it as The above also implies that communication between the containers happens at L3, which means that no container should make any assumptions about the underlying L2 transport, i.e. not use any L2 protocols(apart from ARP). Another corollary of the above requirements is that every container only has a single IP and hence a single interface, which, together with the previous L2 limitation, makes network simulations in K8s nearly impossible. Multus vs DIY There are multiple solutions that solve the problem of a single network interface per container/pod - CNI-Genie, Knitter and Multus CNI. All of them were primarily designed for containerised VNF use cases, with the assumption that connectivity would still be provided by one of the existing plugins, which still leaves us with a number of issues: - We have to be transparent to the underlay, so we can’t use plugins that interact with the underlay (e.g. macvlan, calico) - Most of the CNI plugins only provide L3 connectivity between pods (e.g. flannel, ovn, calico) - The few plugins that do provide L2 overlays (e.g contiv, weave) do not support multiple interfaces and still use virtual bridges underneath Perhaps it would have been possible to hack one of the plugins to do what I wanted but I felt like it’d be easier to build a specialised CNI plugin to do just what I want and nothing more. As I’ve mentioned previously, developing a simple CNI plugin is not that difficult, especially if you have a clearly defined use case, which is why I’ve built meshnet - a CNI plugin to build arbitrary network topologies out of point-to-point links. CNI plugin overview At a very high level, every CNI plugin is just a binary and a configuration file installed on K8s worker nodes. When a pod is scheduled to run on a particular node, a local node agent (kubelet) calls a CNI binary and passes all the necessary information to it. That CNI binary connects and configures network interfaces and returns the result back to kubelet. The information is passed to CNI binary in two ways - through environment variables and CNI configuration file. This is how a CNI ADD call may look like: CNI_COMMAND=ADD \ CNI_CONTAINERID=$id \ CNI_NETNS=/proc/$pid/ns/net \ CNI_ARGS=K8S_POD_NAMESPACE=$namepsace;K8S_POD_NAME=$name /opt/cni/bin/my-plugin < /etc/cni/net.d/my-config The runtime parameters get passed to the plugin as environment variables and CNI configuration file gets passed to stdin. The CNI binary runs to completion and is expected to return the configured network settings back to the caller. The format of input and output, as well as environment variables, are documented in a CNI specification document. There are plenty of other resources that cover CNI plugin development in much greater detail, I would recommend reading at least these four: - CNI plugins best practices - Writing a sample CNI plugin in bash - EVPN CNI plugin - Workflow for writing CNI plugins Meshnet CNI architecture The goal of meshnet plugin is to interconnect pods via direct point-to-point links according to some user-defined topology. To do that, the plugin uses two types of links: - veth - to interconnect pods running on the same node - vxlan - to interconnect pods running on different nodes One thing to note is that point-to-point links are connected directly between pods, without any software bridges in between, which makes the design a lot simpler and provides a cleaner abstraction of a physical connection between network devices. The plugin consists of three main components: - etcd - a private cluster storing topology information and runtime pod metadata (e.g. pod IP address and NetNS fd) - meshnet - a CNI binary called by kubelet, responsible for pod’s network configuration - meshnetd - a daemon responsible for Vxlan link configuration updates Just like Multus, meshnet has the concept of master/default plugin, which sets up the first interface of the pod. This interface is setup by one of the existing plugins (e.g. bridge or flannel) and is used for pod’s external connectivity. The rest of the interfaces are setup according to a topology information stored in etcd. Although the original idea of a CNI plugin was to have a single stateless binary, most of the time there’s a need to maintain some runtime state (e.g. ip routes, ip allocations etc.), which is why a lot of CNI plugins have daemons. In our case, daemon’s role is to ensure Vxlan link configurations are correct across different hosts. Using the above diagram as an example, if pod-2 comes up after pod-3, there must be a way of signalling the (node-1) VTEP IP to the remote node (node-2) and making sure that the Vxlan link on node-2 is moved into pod-3’s namespace. This is accomplished by meshnet binary issuing an HTTP PUT request to the remote node’s daemon with all the required Vxlan link attributes attached as a payload. Meshnet design walkthrough One of the assumptions I made in the design is that topology information is uploaded into the etcd cluster before we spin up the first pod. I’ll focus on how exactly this can be done in the next post but for now, let’s assume that it’s is already there. This information needs to be structured in a very specific way and must cover every interface of every pod. The presence of this information in etcd tells meshnet binary what p2p interfaces (if any) need to be setup for the pod. Below is a sample definition of a link from pod2 to pod3: { "uid": 21, "peer_pod": "pod3", "local_intf": "eth2", "local_ip": "23.23.23.2/24", "peer_intf": "eth2", "peer_ip": "23.23.23.3/24" } Meshnet binary is written in go and, like many other CNI plugins, contains a common skeleton code which parses input arguments and variables. Most of the plugin logic goes into cmdAdd and cmdDel functions that get called automatically when CNI binary is invoked by kubelet. import ( "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" ) func cmdAdd(args *skel.CmdArgs) error { // Parsing cni .conf file n, err := loadConf(args.StdinData) // Parsing CNI_ARGS environment variable cniArgs := k8sArgs{} types.LoadArgs(args.Args, &cniArgs) } func main() { skel.PluginMain(cmdAdd, cmdGet, cmdDel, version.All, "TODO") } One of the first things that happen in a cmdAdd function is a DelegateAdd call to let the master plugin setup the first interface of the pod. Master plugin configuration is extracted from the delegate field of the meshnet CNI configuration file. func cmdAdd(args *skel.CmdArgs) error { ... r, err := delegateAdd(ctx, n.Delegate, args.IfName) ... } func delegateAdd(ctx context.Context, netconf map[string]interface{}, intfName string) (types.Result, error) { ... result, err = invoke.DelegateAdd(ctx, netconf["type"].(string), netconfBytes, nil) ... } When master plugin is finished, we upload current pod’s runtime metadata to etcd. This is required so that peer pods can find and connect to our pod when needed. Specifically, they would need VTEP IP for remote vxlan links and namespace file descriptor for local veth links. func (pod *podMeta) setPodAlive(ctx context.Context, kv clientv3.KV, netNS, srcIP string) error { srcIPKey := fmt.Sprintf("/%s/src_ip", pod.Name) _, err := kv.Put(ctx, srcIPKey, srcIP) NetNSKey := fmt.Sprintf("/%s/net_ns", pod.Name) _, err = kv.Put(ctx, NetNSKey, netNS) } At this stage, we’re ready to setup pod’s links. Instead of manipulating netlink directly, I’m using koko - a high-level library that creates veth and vxlan links for containers. The simplified logic of what happens at this stage is summarised in the following code snippet: // Iterate over each link of the local pod for _, link := range *localPod.Links { // Download peer pod's runtime metadata peerPod := &podMeta{Name: link.PeerPod} peerPod.getPodMetadata(ctx, kv) if peerPod.isAlive() { // If SrcIP and NetNS keys are set if peerPod.SrcIP == localPod.SrcIP { // If we're on the same host koko.MakeVeth(*myVeth, *peerVeth) } else { // If we're on different hosts koko.MakeVxLan(*myVeth, *vxlan) putRequest(remoteUrl, bytes.NewBuffer(jsonPayload)) } } else { // skip and continue } } We start by downloading metadata for each pod that we have a link to and check if it has already come up. The value of peerPod.SrcIP determines whether we’re on the same node and need to setup a veth link or on different nodes and we need to setup a vxlan tunnel between them. The latter is done in two steps - first, a local Vxlan link is setup and moved to a pod’s namespace, followed by an HTTP PUT sent to the remote node’s meshnet daemon to setup a similar link on the other end. Meshnet CNI demo The easiest way to walk through this demo is by running it inside a docker:dind container, with a few additional packages installed on top of it: docker run --rm -it --privileged docker:dind sh # /usr/local/bin/dockerd-entrypoint.sh & # apk add --no-cache jq sudo wget git bash curl In this demo, we’ll build a simple triangle 3-node topology as shown in the figure above. We start by cloning the meshnet Github repository git clone && cd meshnet-cni Next, create a local 3-node K8s cluster using kubeadm-dind-cluster, which uses docker-in-docker to simulate individual k8s nodes. wget chmod +x ./dind-cluster-v1.11.sh ./dind-cluster-v1.11.sh up The last command may take a few minutes to download all the required images. Once the K8s cluster is ready, we can start by deploying the private etcd cluster export PATH="$HOME/.kubeadm-dind-cluster:$PATH" kubectl create -f utils/etcd.yml The ./tests directory already contains link databases for our 3-node test topology, ready to be uploaded to etcd: ETCD_HOST=$(kubectl get service etcd-client -o json | jq -r '.spec.clusterIP') ENDPOINTS=$ETCD_HOST:2379 echo "Copying JSON files to kube-master" sudo cp tests/*.json /var/lib/docker/volumes/kubeadm-dind-kube-master/_data/ echo "Copying etcdctl to kube-master" sudo cp utils/etcdctl /var/lib/docker/volumes/kubeadm-dind-kube-master/_data/ docker exec kube-master cp /dind/etcdctl /usr/local/bin/ for pod in pod1 pod2 pod3 do # First cleanup any existing state docker exec -it kube-master sh -c "ETCDCTL_API=3 etcdctl --endpoints=$ENDPOINTS del --prefix=true \"/$pod\"" # Next Update the links database docker exec -it kube-master sh -c "cat /dind/$pod.json | ETCDCTL_API=3 etcdctl --endpoints=$ENDPOINTS put /$pod/links" # Print the contents of links databse docker exec -it kube-master sh -c "ETCDCTL_API=3 etcdctl --endpoints=$ENDPOINTS get --prefix=true \"/$pod\"" done The final missing piece is the meshnet daemonset, which installs the binary, configuration file and the meshnet daemon on every node. kubectl create -f kube-meshnet.yml The only thing that’s required now is the master plugin configuration update. Since different K8s clusters can use a different plugins, the configuration file installed by the daemonset contains a dummy value which needs to be overwritten. In our case, the kubeadm-dind-cluster we’ve installed should use a default bridge plugin which can be merged into our meshnet configuration file like this: ETCD_HOST=$(kubectl get service etcd-client -o json | jq -r '.spec.clusterIP') for container in kube-master kube-node-1 kube-node-2 do # Merge the default CNI plugin with meshnet docker exec $container bash -c "jq -s '.[1].delegate = (.[0]|del(.cniVersion))' /etc/cni/net.d/cni.conf /etc/cni/net.d/meshnet.conf | jq .[1] > /etc/cni/net.d/00-meshnet.conf" docker exec $container bash -c "sed -i 's/ETCD_HOST/$ETCD_HOST/' /etc/cni/net.d/00-meshnet.conf" done Now meshnet CNI plugin is installed and configured and everything’s ready for us to create our test topology. cat tests/2node.yml | kubectl create -f - The following command will verify that the topology has been created and confirm that pods are scheduled to the correct nodes: kubectl --namespace=default get pods -o wide | grep pod pod1 1/1 Running 0 1m 10.244.2.7 kube-node-1 pod2 1/1 Running 0 1m 10.244.2.6 kube-node-1 pod3 1/1 Running 0 1m 10.244.3.5 kube-node-2 Finally, we can do a simple ping test to verify that we have connectivity between all 3 pods: kubectl exec pod1 -- sudo ping -c 1 12.12.12.2 kubectl exec pod2 -- sudo ping -c 1 23.23.23.3 kubectl exec pod3 -- sudo ping -c 1 13.13.13.1 Coming up The process demonstrated above is quite rigid and requires a lot of manual effort to create a required topology inside a K8s cluster. In the next post, we’ll have a look at k8s-topo - a simple tool that orchestrates most of the above steps - generates topology data and creates pods based on a simple YAML-based topology definition file.
https://networkop.co.uk/post/2018-11-k8s-topo-p1/
CC-MAIN-2020-05
en
refinedweb
A simple terminal emulator component for React react-console-emulator A simple, powerful and highly customisable terminal Emulator for React. I developed this project for JS-RCON and decided to publish it for public use, since I felt other options weren't sufficient. I mean, this kind of thing has to be useful to anyone else than me, right? No? Well, it's a nice idea anyway. Features - Highly customisable: Add your own background image, change the colour of different terminal elements and more! - Extensively emulates a Unix terminal with dutiful accuracy - Easy and powerful command system: Execute code from your own application and send the results to the terminal output. - High concurrency: Register multiple terminals on the same page easily and safely without risk of mixing up inputs. Usage import React from 'react' import Terminal from 'react-console-emulator' const commands = { echo: { description: 'Echo a passed string.', usage: 'echo <string>', fn: function () { return `${Array.from(arguments).join(' ')}` } } } export default class MyTerminal extends React.Component { render () { return ( <Terminal commands={commands} welcomeMessage={'Welcome to the React terminal!'} promptLabel={'[email protected]:~$'} /> ) } } Props Static output manualPushToStdout (message, dangerMode, contentElement, inputElement, inputAreaElement) This is a static function you can call on an instance of react-console-emulator. It allows you to manually push output to the terminal. This may be useful if you have async code that needs to push output even after the function has returned. Warning: Using this function is not optimal and should be avoided if possible. If used, it is additionally recommended to set the noAutomaticStdout property to disable automatic output and command history (The latter of which will not work in this case). Parameter reference Command syntax Commands are passed to the component in the following format. Each command must have a fn property. All other properties are optional. const commands = { commandName: { description: 'Optional description', usage: 'Optional usage instruction', fn: function (arg1, arg2) { // You may also use arrow functions // Arguments passed to the command will be passed to this function in the same order as they appeared in the terminal // You can execute custom code here const lowerCaseArg1 = arg1.toLowerCase() // What you return in this function will be output to the terminal return `test ${lowerCaseArg1}` }, explicitExec: true, // If your command outputs nothing to the terminal and you only need the function to be run, enable this } }
https://reactjsexample.com/a-simple-terminal-emulator-component-for-react/
CC-MAIN-2020-05
en
refinedweb
The complexity and size of real world codebases for Javascript apps continues to grow larger and larger every year. To combat this, codebases are often "modularized" for two primary reasons: - To provide a clear separation of concerns for the application's functionality - To easily implement app performance upgrades like code splitting and AoT compilation In fact, modularization is now such an important part of building web apps that Angular requires you to architect your applications with it out of the box! While AngularJS also had a module system, it was often ignored by developers as it often didn't provide enough advantages to make it completely necessary. With Angular this is no longer the case. Introducing NgModule From the Angular docs: Angular Modules help organize an application into cohesive blocks of functionality. Every time you add a new feature set into your application, it's a good idea to create a new module to contain it. However, you want to avoid creating unnecessary modules as well, so understanding when to create modules is a bit nuanced. We'll cover this in detail a bit later when we show real world examples. The root AppModule Per the Angular Style Guide, every Angular app needs to have a root module called AppModule that is responsible for importing all other modules & functionality that is required for the app to start. The Angular Team has an excellent resource that describes it in detail: It's worth noting that Angular services that need to act like singletons (which most services do) should be imported in the AppModule to ensure there is only one instance ever created during the lifecycle of the application. If we take a look at our previous examples you'll see how we defined the app module in app/app.module.ts: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HeaderComponent, SharedModule } from './shared/index'; @NgModule({ imports: [BrowserModule, SharedModule], declarations: [AppComponent, HeaderComponent], bootstrap: [AppComponent] }) export class AppModule {} You can view the working demo here: In the next chapter we're going to cover a critical type of module that you'll need to create in any reasonably sized application: the shared module.
https://thinkster.io/tutorials/angular-2-ngmodule
CC-MAIN-2020-05
en
refinedweb
(tldr;)[#tldr] Sometimes we need to know the width of the browser window in our component’s class file. You could have a @HostListener in a component for the window’s resize event, but you’d have to maintain the service, write tests to make sure it was working properly, handle observables correctly so there aren’t memory leaks, etc. The Angular CDK’s LayoutModule has a BreakpointObserver class that you can inject into a component, provide a breakpoint (or breakpoints) that you want to watch for, and it will emit each time you cross the threshold of a breakpoint (i.e. if I want to know when the screen is smaller than 700px, it will emit a value when I cross under 700px, and then again when I cross back over 700px). The Problems This Solves First off, I’ve been using Angular daily for almost 4 years now, since before the first Angular 2 Beta release, and this is the first time I’ve needed this functionality. So you might be wondering when or why you would ever need this. But there are times when it is very useful, which is why the class exists in the @angular/cdk library. I ended up needing this functionality because I am using the ngx-gauge library, and one of the options to set in the library is the thickness of the line. You pass it in as an input to the component from the library, and it draws the chart at that thickness. In addition, you pass in a size attribute that sets the height and width. Because of that, I couldn’t change the thickness or the height and width of the chart using CSS media queries. I was left with two options: 1) have two charts on the page, one for bigger screens and one for smaller screens or 2) change the values of those inputs depending on screen size. I chose the latter, because I didn’t want to have to update two charts every time I made a change. The solution (we’ll go over that in a minute) worked great for me, but I will say that I think the first thing you should try is using CSS media queries before doing this. It would be unnecessary, for example, to keep track of the screen width in your component’s class file, and then apply a class to an HTML element (with ngClass, for example) based on the screen width. Maybe there is a scenario where that is what you need to do, but generally I think you’ll be better off just using CSS media queries to style your components. Having said that, however, if you feel this is the best option for your component, go ahead and do it! I don’t want you to feel bad about using BreakpointObserver. The Solution The solution to this problem is pretty simple, thanks to the Angular CDK. The first step is to install the CDK to your project: npm i @angular/cdk Next, import the LayoutModule from @angular/cdk/layout to your module. For example, like this in the app.module.ts file: import { LayoutModule } from '@angular/cdk/layout'; @NgModule({ imports: [..., LayoutModule, ...] }) export class AppModule {} After importing the LayoutModule, inject the BreakpointObserver into your component like any other service you would use: import { Breakpoint Observer } from '@angular/cdk/layout'; export class MyComponent { constructor(private observer: BreakpointObserver) {} } Alright, now everything is set up and ready to use. There’s one more thing to figure out, though, before using the service, and that is what break points you want to be notified of. For example, if your site is using Bootstrap and you want to know when you are on the small screen or lower, you would use ‘(max-width: 767px)’. The value you put in the strings is the part of your CSS media query parentheses, parentheses included. You can provide a single string value, or an array of strings. Once you’ve determined your breakpoints, you have two options to use from the BreakpointObserver. The first one is the isMatched method. It simply evaluates the breakpoints you provided and tells you if the values are matched or not. If you pass in an array to this method, all conditions have to be met for the function to return true. const matched = this.observer.isMatched('(max-width: 700px)'); // OR const matched = this.observer.isMatched(['(max-width: 700px)', '(min-width: 500px)']); The isMatched function works great if you only need to check the first time the page is loaded, or if you only want to check by calling that function occasionally. If you want to be constantly alerted of the matching of your breakpoints, you can use the observe method. The observe method allows you to subscribe and get an update every time the window passes one of the widths that you’ve defined. If you’ve only defined one width to the function, then it will emit a value each time you go above or below that single width. If you provided an array of widths, then each time you cross over the threshold of one of the widths in the array, a value is emitted. this.observer.observe('(max-width: 700px)').subscribe(result => { console.log(this.result); // Do something with the result }); The result that’s outputted here looks like this: { "matches": true | false, "breakpoints": { "(max-width: 350px)": true | false, "(max-width: 450px)": true | false } } The matches attribute is true if any conditions are met. You can also check for individual breakpoints to see if they have been met if you need. This function is great if you need to change some layout on the page each time the browser width crosses a certain value. Like I mentioned in my example above, I needed to change the size of a chart and the thickness of the chart depending on the browser width, and since it could be different on landscape vs portrait, I decided to subscribe to the observer method and change it each time it emitted a value. The last thing to know about the BreakpointObserver is that the CDK provides some built in breakpoints that you can use if you want. They are based on Google’s Material Design specification, and the values are: - Handset - Tablet - Web - HandsetPortrait - TabletPortrait - WebPortrait - HandsetLandscape - TabletLandscape - WebLandscape You can use them by importing Breakpoints from the CDK’s layout folder: import { Breakpoints } from '@angular/cdk/layout'; You can then use a breakpoint, like Breakpoint.Handset, in the observe or isMatched functions. They can be used as the only input, or added to the array that is passed in to those functions. You can also mix your own breakpoints with the those built-in ones.. Conclusion As I said before, you may never use this class or need this functionality. It doesn’t come up very often, but it’s nice to know that this is there and you can reach for it when you do need it. One thing that I want to look into is to see if you could use this function to swap out the template file that the Angular component is using. Again, that would be a rare condition, but you might need it to swap out the content for a mobile experience if it is very different from the desktop experience. I don’t know if you could exactly do that, but you could at least show and hide child components based on the results of the BreakpointObserver. If you have used this before, make sure to let me know on Twitter or via email how you’ve used it. If you haven’t yet, but need to in the future, also let me know! I like to hear about how other developers use things like this so I can learn more!
https://www.prestonlamb.com/blog/angular-cdks-breakpoint-observer
CC-MAIN-2020-05
en
refinedweb
A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background. These are the three different types of services: - Foreground - A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app. - Background - A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service. Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn't in the foreground. In most cases like this, your app should use a scheduled job instead. - Bound - A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed. Although this documentation generally discusses started and bound services separately, your service can work both ways—it can be started (to run indefinitely) and also allow binding. It's simply a matter of whether you implement a couple of callback methods: onStartCommand() to allow components to start it and onBind() to allow binding. Regardless of whether your service. This is discussed more in the section about Declaring the service in the manifest.. Choosing between a service and a thread A service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need. If you must perform work outside of your main thread, but only while the user is interacting with your application, you should instead create a new thread. threads. Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations. The basics To create a service, you must create a subclass of Service or use one of its existing subclasses. In your implementation, you must override some callback methods that handle key aspects of the service lifecycle and provide a mechanism that allows the components to bind to the service, if appropriate. These are the most important callback methods that you should override: onStartCommand() - The system invokes this method by calling startService()when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is complete by calling stopSelf()or stopService(). If you only want to provide binding, you don't need to implement this method. onBind() - The system invokes this method by calling bindService()when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null. onCreate() - The system invokes this method to perform one-time setup procedures when the service is initially created (before it calls either onStartCommand()or onBind()). If the service is already running, this method is not called. onDestroy() - The system invokes this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, or receivers. This is the last call that the service receives. If a component starts the service by calling startService() (which results in a call to onStartCommand()), the service continues to run until it stops itself with stopSelf() or another component stops it by calling stopService(). If a component calls bindService() to create the service and onStartCommand() is not called, the service runs only as long as the component is bound to it. After the service is unbound from all of its clients, the system destroys it. The Android system stops a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed. If the service is started and is long-running, the system lowers its position in the list of background tasks over time, and the service becomes highly susceptible to killing—if your service is started, you must design it to gracefully handle restarts by the system. If the system kills your service, it restarts it as soon as resources become available, but this also depends on the value that you return from onStartCommand(). For more information about when the system might destroy a service, see the Processes and Threading document. In the following sections, you'll see how you can create the startService() and bindService() service methods, as well as how to use them from other application components. Declaring a service in the manifest You must declare all services in your application's manifest file, just as you do for activities and other components. To declare your service, add a <service> element as a child of the <application> element. Here is an example: <manifest ... > ... <application ... > <service android: ... </application> </manifest> See the <service> element reference for more information about declaring your service in the manifest. There are other attributes that you can include in the <service> element to define properties such as the permissions that are required to start the service and the process in which the service should run. The android:name attribute is the only required attribute—it specifies the class name of the service. After you publish your application, leave this name unchanged to avoid the risk of breaking code due to dependence on explicit intents to start or bind the service (read the blog post, Things That Cannot Change). Caution: To ensure that your app is secure, always use an explicit intent when starting a Service and don't declare intent filters for your services. Using an implicit intent to start a service is a security hazard because you cannot be certain of the service that responds to the intent, and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call bindService() with an implicit intent. You can ensure that your service is available to only your app by including the android:exported attribute and setting it to false. This effectively stops other apps from starting your service, even when using an explicit intent. Note: Users can see what services are running on their device. If they see a service that they don't recognize or trust, they can stop the service. In order to avoid having your service stopped accidentally by users, you need to add the android:description attribute to the <service> element in your app manifest. In the description, provide a short sentence explaining what the service does and what benefits it provides. Creating a started service A started service is one that another component starts by calling startService(), which results in a call to the service's onStartCommand() method. When a service is started, it has a lifecycle that's independent of the component that started it. The service can run in the background indefinitely, even if the component that started it is destroyed. As such, the. For instance, suppose an activity needs to save some data to an online database. The activity can start a companion service and deliver it the data to save by passing an intent to startService(). The service receives the intent in onStartCommand(), connects to the Internet, and performs the database transaction. When the transaction is complete, the service stops itself and is destroyed. Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application by default. If your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service slows down activity performance. To avoid impacting application performance, start a new thread inside the service. Traditionally, there are two classes you can extend to create a started service: Service - This is the base class for all services. When you extend this class, it's important to create a new thread in which the service can complete all of its work; the service uses your application's main thread by default, which can slow the performance of any activity that your application is running.. Kotlin class HelloService : Service() { private var serviceLooper: Looper? = null private var serviceHandler: ServiceHandler? = null // Handler that receives messages from the thread private inner class ServiceHandler(looper: Looper) : Handler(looper) { override fun handleMessage(msg: Message) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000) } catch (e: InterruptedException) { // Restore interrupt status. Thread.currentThread().interrupt() } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1) } } override fun("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND).apply { start() // Get the HandlerThread's Looper and use it for our Handler serviceLooper = looper serviceHandler = ServiceHandler(looper) } } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show() // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job serviceHandler?.obtainMessage()?.also { msg -> msg.arg1 = startId serviceHandler?.sendMessage(msg) } // If we get killed, after returning from here, restart return START_STICKY } override fun onBind(intent: Intent): IBinder? { // We don't provide binding, so return null return null } override fun onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show() } } Java public class HelloService extends Service { private Looper serviceLooper; private ServiceHandler service. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } // doesn't disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler serviceLooper = thread.getLooper(); serviceHandler = new ServiceHandler(servic = serviceHandler.obtainMessage(); msg.arg1 = startId; service(); } } it. The return value from onStartCommand() must be one of the following constants: START_NOT_STICKY - If the system kills the service after onStartCommand()returns, do not recreate the service unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs. START_STICKY - If the system kills the service after onStartCommand()returns, recreate (or similar services) that are not executing commands but are running indefinitely and waiting for a job.. For more details about these return values, see the linked reference documentation for each constant. Starting a service You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService(). The Android system calls the service's onStartCommand() method and passes it the Intent, which specifies which service to start. Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground. If an app needs to create a foreground service, the app should call startForegroundService(). That method creates a background service, but the method signals to the system that the service will promote itself to the foreground. Once the service has been created, the service must call its startForeground() method within five seconds. For example, an activity can start the example service in the previous section ( HelloService) using an explicit intent with startService(), as shown here: Kotlin Intent(this, HelloService::class.java).also { intent -> startService(intent) } Java Intent intent = new Intent(this, HelloService.class); startService(intent); The startService() method returns immediately, and the Android system calls the service's onStartCommand() method. If the service isn't already running, the system first calls onCreate(), and then it calls onStartCommand(). If the service doesn't also provide binding, the intent that is delivered with startService() is the only mode of communication between the application component and the service. However, if you want the service to send a result back, the client that starts the service can create a PendingIntent for a broadcast (with getBroadcast()) and deliver it to the service in the Intent that starts the service. The service can then use the broadcast to deliver a result. Multiple requests to start the service result in multiple corresponding calls to the service's onStartCommand(). However, only one request to stop the service (with stopSelf() or stopService()) is required to stop it. Stopping a service A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf(), or another component can stop it by calling stopService(). Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible. If your service handles multiple requests to onStartCommand() concurrently, you shouldn't stop the service when you're done processing a start request, as you might have received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use stopSelf(int) to ensure that your request to stop the service is always based on the most recent start request. That is, when you call stopSelf(int), you pass the ID of the start request (the startId delivered to onStartCommand()) to which your stop request corresponds. Then, if the service receives a new start request before you are able to call stopSelf(int), the ID doesn't match and the service doesn't stop. Caution: To avoid wasting system resources and consuming battery power, ensure that your application stops its services when it's done working. If necessary, other components can stop the service by calling stopService(). Even if you enable binding for the service, you must always stop the service yourself if it ever receives a call to onStartCommand(). For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service. Creating a bound service A bound service is one that allows application components to bind to it by calling bindService() to create a long-standing connection. It generally doesn't allow components to start it by calling startService(). Create a bound service when you want to interact with the service from activities and other components in your application or to expose some of your application's functionality to other applications through interprocess communication (IPC). To create a bound service, implement the onBind() callback method to return an IBinder that defines the interface for communication with the service. Other application components can then call bindService() to retrieve the interface and begin calling methods on the service. The service lives only to serve the application component that is bound to it, so when there are no components bound to the service, the system destroys it. You do not need to stop a bound service in the same way that you must when the service is started through onStartCommand(). To create a bound service, you must define the interface that specifies how a client can communicate with the service. This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method. After the client receives the IBinder, it can begin interacting with the service through that interface. Multiple clients can bind to the service simultaneously. When a client is done interacting with the service, it calls unbindService() to unbind. When there are no clients bound to the service, the system destroys the service. There are multiple ways to implement a bound service, and the implementation is more complicated than a started service. For these reasons, the bound service discussion appears in a separate document about Bound Services. Sending notifications to the user When a service is running, it can notify the user of events using Toast Notifications or Status Bar Notifications. A toast notification is a message that appears on the surface of the current window for only a moment before disappearing. A status bar notification provides an icon in the status bar with a message, which the user can select in order to take an action (such as start an activity). Usually, a status bar notification is the best technique to use when background work such as a file download has completed, and the user can now act on it. When the user selects the notification from the expanded view, the notification can start an activity (such as to display the downloaded file). See the Toast Notifications or Status Bar Notifications developer guides for more information.: Kotlin val pendingIntent: PendingIntent = Intent(this, ExampleActivity::class.java).let { notificationIntent -> PendingIntent.getActivity(this, 0, notificationIntent, 0) } val notification: Notification =) Java Intent notificationIntent = new Intent(this, ExampleActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new);. Managing the lifecycle of a service The lifecycle of a service is much simpler than that of an activity. However, it's even more important that you pay close attention to how your service is created and destroyed because a service can run in the background without the user being aware. The service lifecycle—from when it's created to when it's destroyed—can follow either of these two paths: - A started service The service is created when another component calls startService(). The service then runs indefinitely and must stop itself by calling stopSelf(). Another component can also stop the service by calling stopService(). When the service is stopped, the system destroys it. - A bound service The service is created when another component (a client) calls bindService(). The client then communicates with the service through an IBinderinterface. The client can close the connection by calling unbindService(). Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. The service does not need to stop itself. These two paths aren't entirely separate. You can bind to a service that is already started with startService(). For example, you can start a background music service by calling startService() with an Intent that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService(). In cases such as this, stopService() or stopSelf() doesn't actually stop the service until all of the clients unbind. Implementing the lifecycle callbacks Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times. The following skeleton service demonstrates each of the lifecycle methods: mStartMode } override fun onBind(intent: Intent): IBinder? { // A client is binding to the service with bindService() return mBinder } override fun onUnbind(intent: Intent): Boolean { // All clients have unbound with unbindService() return mAllow mStartMode; } @Override public IBinder onBind(Intent intent) { // A client is binding to the service with bindService()return mBinder; } @Override public boolean onUnbind(Intent intent) { // All clients have unbound with unbindService()return mAllowRebind; } @Override public void onRebind(Intent intent) { // A client is binding to the service with bindService(), // after onUnbind() has already been called } @Override public void onDestroy() { // The service is no longer used and is being destroyed } } Note: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods. Figure 2. The service lifecycle. The diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService(). Figure 2 illustrates the typical callback methods for a service. Although the figure separates services that are created by startService() from those created by bindService(), keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it. A service that was initially started with onStartCommand() (by a client calling startService()) can still receive a call to onBind() (when a client calls bindService()). By implementing these methods, you can monitor these two nested loops of the service's lifecycle: - The entire lifetime of a service occurs between the time that onCreate()is called and the time that onDestroy()returns. Like an activity, a service does its initial setup in onCreate()and releases all remaining resources in onDestroy(). For example, a music playback service can create the thread where the music is played in onCreate(), and then it can stop the thread in onDestroy(). Note: The onCreate()and onDestroy()methods are called for all services, whether they're created by startService()or bindService(). - The active lifetime of a service begins with a call to either onStartCommand()or onBind(). Each method is handed the Intentthat was passed to either startService()or bindService(). If the service is started, the active lifetime ends at the same time that the entire lifetime ends (the service is still active even after onStartCommand()returns). If the service is bound, the active lifetime ends when onUnbind()returns. Note: Although a started service is stopped by a call to either stopSelf() or stopService(), there isn't a respective callback for the service (there's no onStop() callback). Unless the service is bound to a client, the system destroys it when the service is stopped— onDestroy() is the only callback received. For more information about creating a service that provides binding, see the Bound Services document, which includes more information about the onRebind() callback method in the section about Managing the lifecycle of a bound service.
https://developer.android.com/guide/components/services.html?hl=de
CC-MAIN-2020-05
en
refinedweb
Namespace: DevExpress.Web.Mvc Assembly: DevExpress.Web.Mvc5.v19.2.dll public class DockZoneSettings : SettingsBase Public Class DockZoneSettings Inherits SettingsBase To declare the DockZone in a View, invoke the ExtensionsFactory.DockZone helper method. This method returns the DockZone extension that is implemented by the DockZoneExtension class. To configure the DockZone extension, pass the DockZoneSettings object to the ExtensionsFactory.DockZone helper method as a parameter. The DockZoneSettings object contains all the DockZone extension settings. Refer to the Docking Overview topic to learn how to add the DockZone extension to your project.
https://docs.devexpress.com/AspNet/DevExpress.Web.Mvc.DockZoneSettings
CC-MAIN-2020-05
en
refinedweb
Unofficial Lecture 9 Notes Hi all, apologize for the delay, here’s the lecture 9 notes Tim import sys sys.path.append('/Users/tlee010/Desktop/github_repos/fastai/') %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.nlp import * from sklearn.linear_model import LogisticRegression # from torchtext import vocab, data, datasets from fastai.io import * path = './' FILENAME='mnist.pkl.gz' def load_mnist(filename): return pickle.load(gzip.open(filename, 'rb'), encoding='latin-1') ((x, y), (x_valid, y_valid), _) = load_mnist(path+FILENAME) mean = x.mean() std = x.std() x=(x-mean)/std mean, std, x.mean(), x.std() x_valid = (x_valid-mean)/std x_valid.mean(), x_valid.std() (-0.0058509219, 0.99243325) md = ImageClassifierData.from_arrays(path, (x,y), (x_valid, y_valid)) if you are missing the en library #!python -m spacy download en Auto Encoder When you have unlabeled data. How can you create a NN that makes a features for you if you dont have the dependent variable. Lets have our input be the output as well. Reconstruct the details of this insurance policy. Less activations than inputs. Will compress features down into fewer features and then expand it back out. Great way for making embeddings and features even when you don’t have labels Denoising the Auto Encoder Start with a noisy version and then come out with the clean dataset. The 15% were randomly replaced with another row. The dependent variable would stay the same. Can show a lot of different rows. Gave him features (first layer weights), then took the NN and trained it on the claims data. 2 Models would have been enough to win. He did no feature engineering Embeddings From last week Iterators & Streaming Its a object that we call next on. We can pull different pieces, ordered or randomized that can be pulled for mini-batches. Pytorch is designed to handle this concept too, of predicting a stream of data (or the next item). fastai is also designed around this concept of iterators. DataLoader is created with the same concept, but with multiprocessing, which is multi threaded applications ( so you can use your entire processor) Variable - keeps track of computations being made to a tensor. It’s a wrapper pytorch - autograd If we call back it will calculate the gradient. def get_weights(*dims): return nn.Parameter(torch.randn(*dims)/dims[0]) class LogReg(nn.Module): def __init__(self): super().__init__() self.l1_w = get_weights(28*28, 10) # Layer 1 weights self.l1_b = get_weights(10) # Layer 1 bias def forward(self, x): x = x.view(x.size(0), -1) x = torch.matmul(x, self.l1_w) + self.l1_b # Linear Layer x = torch.log(torch.exp(x)/(1 + torch.exp(x).sum(dim=0))) # Non-linear (LogSoftmax) Layer return x def score(x, y): y_pred = to_np(net2.forward(Variable(x)))#.cuda()))) return np.sum(y_pred.argmax(axis=1) == to_np(y))/len(y_pred) A re-write of fit net2 = LogReg()#.cuda() loss=nn.NLLLoss() learning_rate = 1e-3 optimizer=optim.Adam(net2.parameters(), lr=learning_rate)(l) # Before the backward pass, use the optimizer object to zero all of the # gradients for the variables it will update (which are the learnable weights # of the model) optimizer.zero_grad() # Backward pass: compute gradient of the loss with respect to model # parameters l.backward() # print(loss.data) # Calling the step function on an Optimizer makes an update to its # parameters optimizer.step() val_dl = iter(md.val_dl) val_scores = [score(*next(val_dl)) for i in range(len(val_dl))] print(np.mean(val_scores)) 0.910429936306 Within a fit lets rewrite some of the functions ( gradient and step) optimizer.zero_grad() optimizer.step() This code will be replaced with the following: if w.grad is not None: w.grad.data.zero_() b.grad.data.zero_() # Backward pass: compute gradient of the loss with respect to model parameters l.backward() w.data -= w.grad.data * lr b.data -= b.grad.data * lr All gradients have to be added together to get that gradient for that parameter. wis the variable we set before .gradreferring to the gradient part of the variable .data.zero_will zero the gradients, note this is the initializing w.grad.data.zero_() net2 = LogReg()#.cuda() loss_fn=nn.NLLLoss() lr = 1e-2 w,b = net2.l1_w,net2.l1_b(loss) # Before the backward pass, zero the gradients for all of the parameters if w.grad is not None: w.grad.data.zero_() b.grad.data.zero_() # Backward pass: compute gradient of the loss with respect to model parameters l.backward() w.data -= w.grad.data * lr b.data -= b.grad.data * lr val_dl = iter(md.val_dl) val_scores = [score(*next(val_dl)) for i in range(len(val_dl))] print(np.mean(val_scores)) 0.905155254777 Going backwards Momentum fastai can speed up the iteration rate and looping. optimizer.step()- updates optimizer.zero_grad()- fit- is the loop that cycles through nn.Softmax- does the softmax calculation nn.Linear- does the linear multiplication A word on learning rate Sometimes if your learning rate is too large, it gets hard to converge near the later iterations will pull out the parameters of the model How many weights vs. the size of the data. Since our dataset is small, and our weights are very large, chances are that we will dramatically overfit. t = [ 0.numel() for o in net.parameters] t, sum(t) File "<ipython-input-25-112692b70a57>", line 1 t = [ 0.numel() for o in net2.parameters] ^ SyntaxError: invalid syntax Regularization Add new terms to the loss function. If we add L1 and L2 norms of the weights to the loss functions, it incentives the coefficients to be zlose to zero. See the extra term below. $$ loss =\frac{1}{n} \sum{(wX-y)^2} + \alpha \sum{w^2} $$ How to implement? - Change the loss function - Change the training loop to add the derivative adjustment <-- weight decay (not the same as momentum) net = nn.Sequential( nn.Linear(28*28, 100), nn.ReLU(), nn.Linear(100, 10), nn.LogSoftmax() ) loss=nn.NLLLoss() metrics=[accuracy] opt=optim.SGD(net.parameters(), 1e-1, momentum=0.9). 0.33271 0.28169 0.92725] [ 1. 0.22736 0.24474 0.94715] [ 2. 0.23459 0.26795 0.94118] [ 3. 0.21125 0.27423 0.94805] [ 4. 0.21197 0.32224 0.9384 ] opt=optim.SGD(net.parameters(), 1e-1, momentum=0.9, weight_decay=0.3). 1.11321 1.13041 0.62271] [ 1. 1.08937 1.06073 0.70482] [ 2. 1.04438 1.35849 0.46795] [ 3. 1.08236 1.12079 0.63515] [ 4. 1.08296 1.20425 0.62988] On to NLP! !wget --2017-11-30 14:16:02-- Resolving ai.stanford.edu... 171.64.68.10 Connecting to ai.stanford.edu|171.64.68.10|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 84125825 (80M) [application/x-gzip] Saving to: âaclImdb_v1.tar.gzâ aclImdb_v1.tar.gz 100%[===================>] 80.23M 10.6MB/s in 10s 2017-11-30 14:16:12 (7.80 MB/s) - âaclImdb_v1.tar.gzâ saved [84125825/84125825] !gunzip aclImdb_v1.tar.gz #!tar -xvf aclImdb_v1.tar PATH='aclImdb/' names = ['neg','pos'] trn,trn_y = texts_from_folders(f'{PATH}train',names) val,val_y = texts_from_folders(f'{PATH}test',names) def texts_from_folders(src, names): texts,labels = [],[] for idx,name in enumerate(names): path = os.path.join(src, name) for fname in sorted(os.listdir(path)): fpath = os.path.join(path, fname) texts.append(open(fpath).read()) labels.append(idx) return texts,np.array(labels) ??texts_from_folders trn[0] "Story of a man who has unnatural feelings for a pig. Starts out with a opening scene that is a terrific example of absurd comedy. A formal orchestra audience is turned into an insane, violent mob by the crazy chantings of it's singers. Unfortunately it stays absurd the WHOLE time with no general narrative eventually making it just too off putting. Even those from the era should be turned off. The cryptic dialogue would make Shakespeare seem easy to a third grader. On a technical level it's better than you might think with some good cinematography by future great Vilmos Zsigmond. Future stars Sally Kirkland and Frederic Forrest can be seen briefly." First we will throw away the order of words --> Bag of words Let’s use sklearn to convert corpus to bag of words veczr = CountVectorizer(tokenizer=tokenize) Key Concepts Vocabulary - need to find the unique terms throughout the entire corpus Term Document Matrix - columns - vocab or words - rows - different documents - cells - count of occurance Sentiment Approach: bays rule The probability that a document is from class 1 given that the document is from class 0. We will use a conditional probability as follows below $$ \frac{P(C_1 | d)}{P(C_0 | d}) = \frac {P(d|C_1)P(C_1)}{P(d)} = \frac {P(d|C_1)P(C_1)}{P(d|C_0)P(C_0)}$$ How do we calculate? - Gather the documents of one class together - Create profile made up of the words, and their probabilities - Note: we add a dataset that assumes every word occurs at least one in the document - We should have a probability per word, for each class - For each doucment we can multiple the coefficients and that will give us a P(C_1 | d) and P(C_0 | d) we will learn the word features from the training set and split. Then use the same framework to split the test set trn_term_doc = veczr.fit_transform(trn) val_term_doc = veczr.transform(val) We now have 25000 words, with 75132 docs trn_term_doc <25000x75132 sparse matrix of type '<class 'numpy.int64'>' with 3749745 stored elements in Compressed Sparse Row format> Sparse Matrix Special format when most of your matrix is filled with zeros. This assumes that most of the matrix is zero, and only keep track of the elements that are non-zero. The first feature has 93 items trn_term_doc[0] <1x75132 sparse matrix of type '<class 'numpy.int64'>' with 93 stored elements in Compressed Sparse Row format> What are the features (words) ? vocab = veczr.get_feature_names(); vocab[5000:5005] ['aussie', 'aussies', 'austen', 'austeniana', 'austens'] Lets look at our 93 words w0 = set([o.lower() for o in trn[0].split(' ')]); #w0 Look up a specific word veczr.vocabulary_['absurd'] 1297 How many times does this word show up in document 1 trn_term_doc[0,1297] trn_term_doc[0,5000] Naive Bayes We define the log-count ratio r for each word f: $r = \log \frac{\text{ratio of feature f in positive documents}}{\text{ratio of feature f in negative documents}}$ where ratio of feature f in positive documents is the number of times a positive document has a feature divided by the number of positive documents. p = x[y==1].sum(0)+1 - Number of times it shows in positive corpus p = x[y==0].sum(0)+1 - Number of times it shows in negative corpus r = np.log((p/p.sum())/(q/q.sum())) - summing logs is a lot easier to do, otherwise you might run into float errors b = np.log(len(p)/len(q)) - this is our naive bays x=trn_term_doc y=trn_y p = x[y==1].sum(0)+1 q = x[y==0].sum(0)+1 r = np.log((p/p.sum())/(q/q.sum())) b = np.log(len(p)/len(q)) Here’s our predictions from Naive Bayes ~ 80% positive pre_preds = val_term_doc @ r.T + b preds = pre_preds.T>0 (preds==val_y).mean() 0.80740000000000001 Binarized: instead of using the 0.66 for a word, why not just 1 if the word shows up. 83% chance pre_preds = val_term_doc.sign() @ r.T + b preds = pre_preds.T>0 (preds==val_y).mean() 0.82623999999999997 Logistic Regression Here is how we can fit logistic regression where the features are the unigrams. So instead of using bayes, we set it up like a supervised problem m = LogisticRegression(C=1e8, dual=True) m.fit(x, y) preds = m.predict(val_term_doc) (preds==val_y).mean() 0.85648000000000002 Regularized version -> 0.0000001 m = LogisticRegression(C=1e8, dual=True) m.fit(trn_term_doc.sign(), y) preds = m.predict(val_term_doc.sign()) (preds==val_y).mean() 0.85528000000000004 Regularized version -> 0.1 m = LogisticRegression(C=0.1, dual=True) m.fit(x, y) preds = m.predict(val_term_doc) (preds==val_y).mean() 0.88271999999999995 Regularized version -> 0.1 with traing doc terms m = LogisticRegression(C=0.1, dual=True) m.fit(trn_term_doc.sign(), y) preds = m.predict(val_term_doc.sign()) (preds==val_y).mean() 0.88404000000000005 Trigram with NB features Instead of using words, we will use small phrases of words, or phrases. In this case we will use 3 word phrases, also referred to as trigrams veczr = CountVectorizer(ngram_range=(1,3), tokenizer=tokenize, max_features=800000) trn_term_doc = veczr.fit_transform(trn) val_term_doc = veczr.transform(val) Let regularization do the feature selection, just bound the overall space trn_term_doc.shape (25000, 800000) vocab = veczr.get_feature_names() vocab[200000:200005] ['by vast', 'by vengeance', 'by vengeance .', 'by vera', 'by vera miles'] y=trn_y x=trn_term_doc.sign() val_x = val_term_doc.sign() p = x[y==1].sum(0)+1 q = x[y==0].sum(0)+1 r = np.log((p/p.sum())/(q/q.sum())) b = np.log(len(p)/len(q))
https://forums.fast.ai/t/unofficial-lecture-9-notes/8539
CC-MAIN-2020-05
en
refinedweb
for. let dataset: Dataset; dataset.filter(() => true); Thanks. @rdfjs/datasetshouldn't be used, it's only a basic, readable example implementation of the dataset spec. You could replace it with N3 or rdf-dataset-indexed, their perfs are exponentially better @rdfjs/namespacebut ran into problems. Will do the rest when I work out what's going on. rdf-dataset-extat DefinitelyTyped/DefinitelyTyped#41089
https://gitter.im/rdfjs/public?at=5dea92e226eeb8518f79658a
CC-MAIN-2020-05
en
refinedweb
import route-policy Function The import route-policy command associates the current VPN instance address family with an import Route-Policy. The undo import route-policy command disassociates the current VPN instance address family from an import Route-Policy. By default, the current VPN instance address family is not associated with any import Route-Policy. CE6810LI series do not support this command. Format import route-policy policy-name VPN instance view: undo import route-policy VPN instance IPv4 address family view: undo import route-policy [ policy-name ] Usage Guidelines Usage Scenario When no import Route-Policy is configured, routes that match the export VPN target attribute of the received routes and the import VPN target attribute of the local VPN instance address family are added to the VPN instance address family. To control the import of the routes into the VPN instance address family more accurately, you can use the import Route-Policy. The import Route-Policy is used to filter the imported routing information and to set the routing attributes of the routes that pass the filtering. The import route-policy command controls the VPN routes that are cross added to the VPN instance address family. The peer route-policy command or the filter-policy command run in the BGP VPN instance address family view filters routes of the VPN instance address family advertised to or received from CE neighbors. Prerequisites The route-distinguisher command has been executed to set the RD of the VPN instance. Precautions The current VPN instance address family can be associated with only one import Route-Policy. If the import route-policy command is run several times, the latest configuration overrides the previous configurations. If the route policy to be associated with the VPN instance address family does not exist, you need to configure the route policy. Example # Apply an import Route-Policy named poly-1 to the IPv4 address family of the VPN instance named vrf1. <HUAWEI> system-view [~HUAWEI] ip vpn-instance vrf1 [*HUAWEI-vpn-instance-vrf1] ipv4-family [*HUAWEI-vpn-instance-vrf1-af-ipv4] route-distinguisher 100:1 [*HUAWEI-vpn-instance-vrf1-af-ipv4] import route-policy poly-1
https://support.huawei.com/enterprise/en/doc/EDOC1000166501/263824e9/import-route-policy
CC-MAIN-2020-05
en
refinedweb
Angular 7|6 Tutorial Course: Nested Router-Outlet, Child Routes & forChild() In the previous tutorial , you have seen what NgModules are and you created the admin module of your developer's portfolio web application. Now, let's add routing to our module using a routing module, a nested router-outlet and child routes. You can create a nested routing by defining child routes using the children property of a route (alongside a path and component properties). You also need to add a nested router-outlet in the HTML template related to the component linked to the parent route (In our case it's the admin route). To create nested routing, you need to create a routing submodule for the module you want to provide routing, you next need to define a parent route and its child routes and provide them to the router configuration via a forChild() method. Let's see this step by step. First, inside the admin module, create an admin-routing.module.ts file and add a submodule for implementing child routing in our admin module: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ProjectComponent } from './project/project.component'; import { ProjectListComponent } from './project-list/project-list.component'; import { ProjectCreateComponent } from './project-create/project-create.component'; import { ProjectUpdateComponent } from './project-update/project-update.component'; const routes: Routes = [ { path: 'admin', component: ProjectComponent, children: [ { path: 'list', component: ProjectListComponent }, { path: 'create', component: ProjectCreateComponent }, { path: 'update', component: ProjectUpdateComponent } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class AdminRoutingModule { } This is an example of a module which has imports and exports meta information; - The importsarray which contains the modules that we need to import and use in the current module. In this case it's RouterModule.forChild(routes), - The exportsarray which contains what we need to export. In order to provide our child routes to the router module, we use the forChild() method of the module because we want to add routing in the admin submodule. if this is used in root module you need to use the forRoot() method instead. See more differences of forChild() vs forRoot() from the official docs. The forChild() and forRoot() methods are static methods that are used to configure modules in Angular. They are not specific to RouterModule. We are creating a parent admin route and its own child routes using the children property of the route which takes an array of routes. You can respectively access the ProjectListComponent, ProjectCreateComponent and ProjectCreateComponent using the /admin/list, /admin/create and /admin/update paths. Next, open the src/app/admin/admin.module ts file and import the routing module: // [..] import { AdminRoutingModule } from './admin-routing.module'; @NgModule({ // [...] imports: [ CommonModule, AdminRoutingModule ] }) export class AdminModule { } Next open the src/app/admin/project/project.component html file and add a nested router outlet: <h2>Admin Interface</h2> <router-outlet></router-outlet> This is a nested router-outlet that will be only used to render the components of the admin module i.e ProjectListComponent, ProjectCreateComponent and ProjectCreateComponent. Note: If you don't add a nested router outlet in the parent route, child components will be rendered in the parent router outlet of the application. Next in the src/app/header/header.component.html file, add a link to access the admin interface: <li class="nav-item"> <a class="nav-link" routerLink="/admin/list">Admin</a> </li> At this point, if you click on the admin link in the header, you should see the following interface: - Angular 7|6 Tutorial Course: CLI, Components, Routing & Bootstrap 4, - Angular 7|6 Tutorial Course: Angular NgModules (Feature and Root Modules), - Angular 7|6 Tutorial Course: Nested Router-Outlet, Child Routes & forChild() - Angular 7|6 Tutorial Course: Authentication with Firebase (Email & Password), - Angular 7|6 Tutorial Course: Securing the UI with Router Guards and UrlTree Parsed Routes Conclusion In this tutorial, you have created nested routing in your Angular 7 application by creating a routing submodule for the admin module and adding a nested router-outlet and child routes for the /admin parent route. In the next tutorial, you'll secure the admin interface using Firebase authentication with email and password.<<
https://www.techiediaries.com/angular-course-child-routes/
CC-MAIN-2020-05
en
refinedweb
In Java, threads are objects and can be created in two ways: 1. by extending the class Thread 2. by implementing the interface Runnable In the first approach, a user-specified thread class is created by extending the class Thread and overriding its run () method. In the second approach, a thread is created by implementing the Runnable interface and overriding its run () method. In both approaches the run () method has to be overridden. Usually, the code that is to be executed by a thread is written in its run () method. The thread terminates when its run () method returns. In Java, methods and variables are inherited by a child class from a parent class by extending the parent. By extending the class Thread, however, one can only extend or inherit from a single parent class (in this case, the class Thread is the parent class). This limitation of using extends within Java can be overcome by implementing interfaces. This is the most common way to create threads. A thread that has been created can create and start other threads. The first method of creating a thread is simply by extending the Thread class. The Thread class is defined in the package java.lang. The class that inherits overrides the run () method of the parent Thread for its implementation. This is done as shown in the code fragment given below. By its side a representation of the inheritance that is being implemented. A thread can be started by applying the start () method on the thread object. The following code segment creates an object of the thread class and starts the thread object. class Start Threadclass { public static void main (String args [ ]) { …….. …….. SampleThread st = new SampleThread (); st.start (); ……. } } Here, the thread object st of the thread class SampleThread is created as SampleThread st = new SampleThread (); To start the thread object st, the start () method can be applied on this object as st.start (); When the above statement is executed, the run () method of the SampleThread class is invoked. The start () method implicitly calls the run () method. Note that the run () method can never be called directly. Look at Program which creates a thread class ThreadExample which extends the class Thread and overrides the method Thread.run (). The run () method of this program is where all the work of the ThreadExample class thread is done. This instance of the class is created in the ExampleT class. The start () method on this instance starts the new thread. The child thread prints the values from 0 to 5. Program Using extends to write a single-thread program. import java.lang.*; class ThreadExample extends Thread { public ThreadExample (String name) { super (name); } public void run () { System.out.println (Thread.currentThread ()); For (int i=0; i<=5; i++) System.out.println (i); } } public class ExampleT { public static void main (String args [ ]) { ThreadExample t = new ThreadExample ("First"); t.start ( ); System.out.println (''This is:" + Thread.currentThread ()); } } The output of Program is as follows: This is: Thread [main, 5, main] Thread [First, 5, main] 0 1 2 3 4 5 The first line of the output shows the name of the thread (main), the priority of the thread (5) and the name of the ThreadGroup (main). In the second line, First, 5 and main are the name, priority and name of the ThreadGroup of the child thread. The created thread does not automatically start running. To run a thread, the class that creates it must call the method start () of the Thread. The start () method then calls the run () method. When applying the start () method on a thread object, a new flow of control starts processing the program. The start () method can be invoked either from the constructor or any method in which the thread is created. Figure 6.1. shows the running of both main and child threads. In Program the main method creates an object a thread class ThreadExample. After executing the statement ThreadExample t = new ThreadExample ("First"); Thread object t is in the newborn state of the thread life cycle. When a thread is in newborn state, it does not hold any system resource and the thread object is said to be empty. A thread can be started only when it is in the newborn state by calling the start () method. Calling any method other than the start () method will cause an exception IilegalThreadStateException. The start () method creates the necessary system resources to run the thread, schedules the thread to run, and calls the thread's run () method. The thread object t calls the start () method of the ThreadExample class. Thread object’s run method is defined in the ThreadExample class. After execution of t.start () statement, the thread is in the runnable state. Henceforth, both the thread object as well as main thread are in the runnable state. Every Java applet or application is multithreaded. For instance, main itself is a thread created by extending the Thread class. The interface Runnable is defined in the java.lang package. It has a single method-run (). public interface Runnable { public abstract void run (); } If we want multithreading to be supported in a class that is already derived from a class other than Thread, we must implement the Runnable interface in that class. The majority of classes created that need to be run as a thread will implement Runnable since they may be extending some other functionality from another class. Whenever the class defining run () method needs to be the sub-class of classes other than Thread, using Runnable interface is the best way of creating threads. The syntax and the inheritance structure are given below. public class SampleThread extends The class Thread itself implements the Runnable interface (package java.lang) as expressed in the class header: public class Thread extends Object implements Runnable As the Thread class implements Runnable interface, the code that controls the thread is placed in the run () method. In order to create a new thread with Runnable interface, we need to instantiate the Thread class. This thread class will have the following constructors: public Thread (Runnable obj); public Thread (Runnable obj, String threadname); public Thread (ThreadGroup tg, Runnable obj, String threadname); Here, obj is the object of the class which implements the Runnable interface, threadname is the name given to the thread and tg is the name of the ThreadGroup. Program illustrates the creation of threads using Runnable interface. Program Using Runnable interface to write a single-thread program. class ThreadExample implements Runnable { Thread t; public ThreadExample (String threadname) { t = new Thread (this, threadname); } public void run () { System.out.println (Thread.currentThread () ); for (int i =0; i <=5; i++) System.out.println (i); } } public class ExampleT2 { public static void main (String args [ ]) { ThreadExample obj = new ThreadExample ("First"); Obj.t.start ( ); System.out.println ("This is:" + Thread.currentThread ()); } } The output of Program is as shown below. This is: Thread [main, 5, main] Thread [First, 5, main] 0 1 2 3 4 5 In Program, in place of the Thread class constructor parameters we passed this and First. Here this refers to the ThreadExample class on which the thread is created. Here, the abstract run () method is defined in the Runnable interface and is being implemented. By implementing Runnable, there is greater flexibility in the creation of the class ThreadExample. In the above example, the opportunity to extend the ThreadExample class, if needed, still exists. The method of extending the Thread class is good only if the class executed as a thread does not ever need to be extended from another class. Generally, when the execution of a program starts the thread main is started first. Child threads are started after the main thread. So it is unusual to stop the main thread before the child threads. The main thread should wait until all child threads are stopped. The join () method can be used to achieve this. The syntax of this method is as follows: final void join () throws InterruptedException The join () method waits until the thread on which it is called terminates. That is, the calling thread waits until the specified thread joins it. A thread (either main thread or child threads) calls a join () method when it must wait for another thread to complete its task. When the join () method is called, the current thread will simply wait until the thread it is joining with either completes its task or is not alive. A thread can be in the not alive state due to anyone of the following: • the thread has not yet started, • stopped by another thread, • completion of the thread itself The following is a simple code that uses the join () method: try { t1.join () t2.join (); t3.join (); } catch (interupptedException e) { } Here t(1), t(2), t(3) are the three child threads of the main thread which are to be terminated before the main thread terminates. If we check the isAlive () on these child threads after the join () method, it will return false. There is another form of the join () method, which has a single parameter that specifies how much time the thread has to wait. This is the following: final void join (long milliseconds) throws InterruptedException By default, each thread has a name. Java provides a Thread constructor to set a name to a thread. The name can be passed as a string parameter to this constructor, in the following manner: Thread t = new Thread ("First"); Thread t = new Thread (Runnable r, "SampleThread"); The setName method of the Thread class can also be used to set the name of the thread, in the following manner: void setName (String thread
http://ecomputernotes.com/java/multithreading/creating-threads
CC-MAIN-2020-05
en
refinedweb
Definition An instance sb of class secure_socket_streambuf can be used as an adapter: It turns a leda_socket s into a C++-streambuf object. This object can be used in standard C++ ostreams and istreams, which makes the communication through the socket easier. Moreover, secure_socket_streambuf uses cryptography to secure the communication. Every piece of data is authenticated, (possibly) compressed and encrypted before it is sent. If two parties want to use the class secure_socket_streambuf to exchange data they have to do the following. First they establish a connection through leda_sockets. Then each party contructs an instance of the class secure_socket_streambuf which is attached to its socket. (An example showing how to this can be found at the end of Section socket_streambuf; simply replace ``socket_streambuf'' by ``secure_socket_streambuf'' and add the passphrase(s).) The communication between two instances of the class secure_socket_streambuf can be divided in two phases. In the first phase the two parties negotiate session parameters like packet sizes and they also agree on a so-called session-seed which will be explained later. In the second phase the actual user data is exchanged. Each phases is protected with cryptography. The authentication and encryption keys for the first phase are generated in a deterministic way from the user-supplied passphrase(s). They are called master keys because they remain the same as long as the passphrases are not changed. In order to protect the master keys we use them only during the first phase, which consists of two messages from each party. After that we use the random session seed (in addition to the passphrases) to compute session keys which are used during the second phase. #include < LEDA/coding/secure_socket_streambuf.h > Creation Operations The class secure_socket_streambuf inherits most of its operations from the class streambuf that belongs to the C++ standard library. Usually there is no need to call these operations explicitly. (You can find documentation for streambuf at)
http://www.algorithmic-solutions.info/leda_manual/secure_socket_streambuf.html
CC-MAIN-2021-10
en
refinedweb
Level-of-detail management for multi-resolution terrains. More... #include <Inventor/geo/SoGeoLOD.h> The SoGeoLOD node allows applications to build massive tiled, multi-resolution terrain models where the viewer progressively loads higher resolution detail as you fly into the terrain. The SoGeoLOD node provides a terrain-specialized form of the geospatial coordinate center. The center field should be specified as described in 25.2.4 Specifying geospatial coordinates. The geoSystem field is used to define the spatial reference frame and is described in 25.2.3 Specifying a spatial reference frame. below illustrates this process. The child URLs shall be arranged in the same order as in the figure; i.e., child1Url represents the bottom-left quadtree child. It is valid to specify less than four child URLs; in which case, the SoGe file; whereas the rootUrl field lets you specify a URL for a file that contains the geometry. The result of specifying a value for both of these fields is undefined. Constructor. Constructor that takes approximate number of children. Object-space center of the model. First child url : bottom-left quadtree child. Second child url : up-left quadtree child. Third child url : up-right quadtree child. Fourth child url : bottom-right quadtree child. Defines the spatial reference frame. Valid values are: World-space distance to use as switching criteria. Url of the file that contains the root tile geometry.
https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_geo_l_o_d.html
CC-MAIN-2021-10
en
refinedweb
Managing Lookup Tables with Entity Framework Code First Oftentimes in our applications we will have such things as a "lookup table". I am defining a lookup table as a list of relatively fixed or static choices such as status codes, states or provinces, and so on. In this post I will share how I manage lookup tables using Entity Framework. Background: The Problem Let's work with a lookup table of status codes. Often, in an application, there is some logic that is related to the status of some entity, such that doing the same action will produce different results depending on the entity's status. For example, in a banking system, the loan process might be different between regular or VIP customers. In a retail store, the checkout process might be different between members and non-members. In each case, a status check is part of the workflow, and the workflow branches depending on the result of the status check. Now, suppose that statuses are stored in a lookup table in a database. How can the status be queried reliably and accurately? Background: The Common Solution Often, what I see done is this: in the database, an additional column is created called "code" or similar. The sole purpose of this column is to serve as an identifier in the application: the known "codes" are stored in the application in some data structure such as a dictionary or in a class of constants. The codes doesn't appear on any screen, and the data structure holding the codes are only used during checking. For example, the database values would look like this: Id Code Text 1 NON Non-Member 2 GLD Gold Member 3 SVR Silver Member And then there would be a class of constants that look like this: public class StatusCode { public const string NonMember = "NON"; public const string GoldMember = "GLD"; public const string SilverMember = "SVR"; } Which would be used like this: switch (entity.Status.Code) { case StatusCode.NonMember: // logic for non-members case StatusCode.GoldMember: // logic for gold members // .. other cases .. } This works, but there are a few downsides / points for improvements that I see: - The Statusmember has to be brought in to enable a status check. See how we are drilling into entity.Statusin the switch statement? That means an additional JOINoperation on the database. Just to check the status of an entity. - It's a magic string that doesn't really identify a particular row. Sure, we see a code like "GLD" and kinda infer that it is linked with the gold status. But the link stops there - there is no way in the code to enforce the link. - It's not directly a domain term. The code's sole purpose is to serve as an identifier in the code (and as we saw above, it's not even that strong of an identifier). It doesn't appear on any screen, and users of the application don't use these codes. Which may be all fine if the code is a necessity, but, as we will see below, there is a better way. So what's the better way? Use the Primary Key as the Identifier Yes, you read that right: just use the primary key as the identifier. Before I list the "why", let me post some sample code that uses this approach. The database values would now look like this: Id Text 1 Non-Member 2 Gold Member 3 Silver Member The class of constants would now look like this: public class StatusId { public const int NonMember = 1; public const int GoldMember = 2; public const int SilverMember = 3; } Which would then be used like this: switch (entity.StatusId) { case StatusId.NonMember: // logic for non-members case StatusId.GoldMember: // logic for gold members // .. other cases .. } Now I can list the advantages that I see, which are answers to the disadvantages I listed above: - The status can be checked directly on the entity, without bringing in the related Statusobject. We are now directly using the StatusIdin the entity rather than drilling down to the Statusobject. That is one less JOINthat we have to make. - We have the strongest possible identifier - it's the primary key. We really can't get a stronger identifier than that. - We have removed our "clutch" column. Since we are using the primary key as identifier, we don't need an extra column anymore. The database will be less cluttered. I know what you're thinking now: Isn't Having a Strong Coupling with the Primary Key Directly a Bad Idea? Back in the day, lookup tables are populated with SQL insert commands. If lookup tables have an identity primary key (and they usually do), there was no reliable way to determine beforehand what the generated primary keys would be - you would have to look at those after the insert script ran. Therefore, using codes made sense, as that was something known before the actual insert and is something that could be synchronized with the code. But when using Entity Framework, particularly the Code First workflow with migrations, insert scripts are no longer necessary. The implementation of migrations also lend itself well to the approach I described of using the primary keys as identifiers. Managing Migrations A very useful method that can be used in migrations is the AddOrUpdate method. The AddOrUpdate method takes a list of entities as a parameter. For each entity in the list, it adds it to the database if it's not already there, and updates it otherwise. The method also takes in an expression as a parameter, and uses this expression to determine if an entity already exists or not. How does this fit in with the lookup tables we are discussing? Well, remember the constants class above, where we had all the ids? Here is how we can use that in migrations: context.Statuses.AddOrUpdate(s => s.Id, new Status { Id = StatusId.NonMember, Text = "Non-Member" }, new Status { Id = StatusId.GoldMember, Text = "Gold Member" }, new Status { Id = StatusId.SilverMember, Text = "Silver Member" }); Here we are seeding statuses and using the Id as the identifier expression. Notice that we are using the StatusId class when constructing the objects - the same class that we use when checking the statuses. This gives us a strong guarantee that our identifiers really accurately identify whichever row they're supposed to be able to identify. This is an example of embracing the Code First workflow - now we not only using code first for the schema but for the data as well. In my opinion, this trumps the approach with the "code" columns I described above. Conclusion In this post I described a solution to lookup table management using Entity Framework Code First and migrations. The solution involves using primary keys directly instead of introducing an arbitrary column (such as a "code" column). This approach ties in nicely with the Code First migrations workflow and provides a very strong means of identification.
https://www.ojdevelops.com/2016/04/managing-lookup-tables-with-entity.html
CC-MAIN-2021-10
en
refinedweb
There is one last “resource” we need to gather – the data for our database. I saved this for its own step, because I wanted to take a bit more time to explain the “how” and “why” of the layout of the data. It has a certain pattern to it which is based off of something called an “Entity Component System” architecture. Entity Component System (ECS) I recently started working with this pattern while making my Zork project. If you already followed along with that project or are already familiar with Adam Martin’s take on this architecture then you can feel free to skip ahead to the next stuff. Because I am beginning with the assumption that you are already familiar with Unity, I don’t feel I will need to elaborate too much on the idea of ECS. It has a lot in common with Unity and some would say that Unity is an ECS. Anyway, following is my super brief over-simplification of the concept: Entity The first part of the architecture is the entity. Conceptually, you can think of this as something like a GameObject in Unity – by itself it doesn’t really “do” anything, it is just a container for components. With this pattern, you create complex objects by the components which make it up. Now for the differences – an entity is implemented as nothing more than a unique id (like an integer data type). It is basically a key used in a database, and that’s it. The key will be used in the mapping of relationships to components. Component The next part of the architecture is the component. You probably already have a good idea of what this is. In Unity, it would be any class that inherits from MonoBehaviour. Actually, the MonoBehaviour class inherits from another class which is, not surprisingly, called Component. The difference this time is that most Unity developers store both data and behavior in their components. A component should be nothing more than a structure of data – it should be able to be stored as a table in a database. System The system has no directly matching concept in Unity, although there is nothing stopping you from having used them. A system is really just a single class which acts upon the data in a component or collection of components. Any behavior (method) that you might previously have put in a component should actually go here instead. Implementation I have already included a starter database file in our project as well – it could be a good template to use for doing this again in the future. Take a look at the “Pokemon.db” file in the “StreamingAssets” folder. It is empty except for the definitions of a few important tables: The “Enity” table contains columns for an “id” and “label”. The “id” IS the entity as I mentioned earlier. It is just a key in a database. For every object in your game you would create a new row in this table. The “label” is intended to be for debug purposes only and gives a quick idea of what that “id” and its components are intended to represent. Following is the class implementation: public class Entity { [PrimaryKey, AutoIncrement] public int id { get; set; } public string label { get; set; } } The “Component” table contains an “id”, “name” and “description”. I like to think of this table as a way to index my other tables – each of which represents what I think of as an “actual” component. The “name” is the name of one of those tables, and the description gives you an idea of what that component is for. I don’t actually use the description in the implementation of the code for any reason, but it might be handy for later reference in case you forget why you created something. There will be one row in this table for each TYPE of component you have in your game. The tables that the row points to will hold the instances of those components and the data specific to its own kind. Following is the class implementation: public class Component { [PrimaryKey, AutoIncrement] public int id { get; set; } public string name { get; set; } public string description { get; set; } } The “EntityComponent” table is what holds the relationship between an entity and its component(s). For each component instance that needs to be attached to an entity instance, you will have one new row in this table. The table definition includes an “id”, “entity_id”, “component_id”, and “component_data_id”. The “id” (as always) allows you a way to point to a specific row of this table. The “entity_id” holds the “id” of a row in the “Entity” table. The “component_id” holds the “id” of a row in the “component” table, and finally the “component_data_id” holds the “id” of a row in yet another table – one which you should be able to find by way of the data that the “Component” table tells you. Following is the class implementation: public class EntityComponent { [PrimaryKey, AutoIncrement] public int id { get; set; } public int entity_id { get; set; } public int component_id { get; set; } public int component_data_id { get; set; } } I realize that all might be a bit confusing. Feel free to read it a few times if you need to, but I will include an example that will hopefully help to clear everything up. Database Setup For this project I wanted to ease my way into using SQLite, so the only thing I stored in the database was information regarding the Pokemon. Note that these are treated almost like “prefabs” or “prototypes” because the data held here is not unique to an instance of a kind of Pokemon. In other words, any “Bulbasaur” the game instantiates would use the same base stats, evolution costs, etc. as all of the other “Bulbasaurs”. Let’s take a look at the three default tables I inlcluded first. In order to match what I created, the “Entity” table should be populated so that there is one row per type of Pokemon. From “Bulbasaur” to “Dragonite”, etc. each gets a new row. I created each Pokemon as an entity because I want to “describe” them based on a collection of components. In theory I could have created a single table with all of the information relevant to any given Pokemon, but in practice, most systems don’t need all of that data, they only need small bits of the data. For example, when I decide what Pokemon to spawn in a random encounter, I want to know the weighted chance from ALL of the Pokemon, but I don’t want to have to load the entire database into memory either. If I am not spawning a “Dragonite” at that point, then I don’t benefit from knowing its attack strength or move set, so it is beneficial to be able to break it down. The game I created only requires a few components, each of which describes some aspect of a Pokemon: - SpeciesStats: This component holds the base stats such as attack, defense, and stamina and what type(s) a Pokemon is classified as. - Evolvable: This component indicates what other Pokemon an entity can evolve into, after paying the candy cost. Not all Pokemon have this compoennt. - Encounterable: This component indicates the chance that a given Pokemon can appear. Not all Pokemon will have this component either, such as Legendary pokemon like Mew. - Move: This component holds the information of an attack such as its power or energy cost. By attaching one or more as a component to a Pokemon we can define its set of abilities. Go ahead and create a row in the “Component” table for each of these listed components. Then, we will need to create the “Component Data” table for each. Feel free to do so manually or programmatically, based on the following classes which represent them: public class SpeciesStats { public const int ComponentID = 1; [PrimaryKey, AutoIncrement] public int id { get; set; } public string name { get; set; } public int typeA { get; set; } public int typeB { get; set; } public int maxCP { get; set; } public int attack { get; set; } public int defense { get; set; } public int stamina { get; set; } } public class Evolvable { public const int ComponentID = 2; [PrimaryKey, AutoIncrement] public int id { get; set; } public int entity_id { get; set; } public int cost { get; set; } } public class Encounterable { public const int ComponentID = 3; [PrimaryKey, AutoIncrement] public int id { get; set; } public double rate { get; set; } } public class Move { public const int ComponentID = 4; [PrimaryKey, AutoIncrement] public int id { get; set; } public string name { get; set; } public int type { get; set; } public int power { get; set; } public double duration { get; set; } public int energy { get; set; } } Note that in each of the classes above I have a “ComponentID” – this will be the same as the “id” in the “Component” table – if you added them in a different order, you should modify this accordingly. This field is quite convenient when one needs to perform fetches. Once you have the tables configured you will need to start populating them with data and then adding the entity component rows to connect them. In the image below, you can see a few which show the connection between the first five Pokemon entities (based on the entity_id column) with the Species Stat component (based on the component_id column) and which stat to use (based on the component_data_id column): There is a certain “art” to figuring out how you want to model you data, not only for the convenience of entering it initially, but also for maintaining it, and allowing the greatest flexibility with it. Consider the “Move” component as one example. I was easily able to show a Pokemon’s move set simply by adding the moves I wanted a Pokemon to be able to use as components to the Pokemon’s entity itself. While this was a simple solution, a more complex battle system might have benefitted from the Move being attached to its own entity. Then I could attach additional components to the new move’s entity – some might allow status ailments to be inflicted upon the target, or give some other benefit to the user. Some, like a Ditto’s ability to transform, may not actually apply any damage at all and are drastically different in implementation than a normal attack move. Being able to connect additional components to a custom Move entity would make all of this a LOT easier to account for. If I went this route, I would not attach the Move as a component on the Pokemon entity. I might instead create some alternate entity that had components marking a collection of other entities. The Pokemon could then get a reference to this collection entity as its move set. In addition to the component tables listed above, I added two additional tables for “Type” and “TypeMultiplier”, and they (for better or worse) didn’t follow the ECS pattern. Like the alternate implementation of a “Move”, the “Type” could potentially have been added to its own entity, and the type multipliers (the strength or weakness of one type against another) could have been added as additional components to the same entity. Ultimately, my reasoning was just that it was simpler not to need the Entity and that my simple game wouldn’t grow any more complex, so I was fine with simply looking up the information I needed manually. The additional tables should use the following setup: public class Type { [PrimaryKey, AutoIncrement] public int id { get; set; } public string name { get; set; } } public class TypeMultiplier { [PrimaryKey, AutoIncrement] public int id { get; set; } public int attack_type_id { get; set; } public int defend_type_id { get; set; } public double value { get; set; } } Finding the Reference Data Hopefully by now you understand what kind of data needs to be added, why it is structured like it is, and also how to add it – either manually through the use of an editor like SQLite Browser, or programmatically by random generation or by parsing data you find somewhere else. All of the data I used was based off of Pokemon Go. Here are a couple of links you might find valuable while trying to rebuild a working database for yourself: - The Silph Road – well laid out data of all of the Pokemon names, numbers, base stats, etc. - Game Master – a decoded and categorized json file covering just about everything you could want to know. - Spawn Rates – a table of the spawn chance of all of the Pokemon based on data from 10,000 spawns. - Pokemon Go moves list – a list of the pokemon and their moves with a DPS rating. - Quick Moves & Charge Moves – an alternate list of the moves in Pokemon Go, with a time for each attack listed separately from the DPS. If you google for a little while you will see that there are a ton more than the ones I have listed. Hopefully you will find something you like working from. Good luck! Generating Data If gathering the real data is too tedious, you can always generate your own data procedurally. We covered how to create and insert data into tables in the previous lesson, so you can always create something random using the same means. Afterward you can choose to polish the data a bit so it feels more balanced, but at least having the data will allow you to play the game and get a feel for it. It might be nice to at least generate data within the same ranges as the values I used in my prototype, so here are a few values to begin with: - Entity: I used 149 different pokemon in the prototype. - Encounterable rate: ‘0.0011’ to ‘15.98’ - Evolvable: there are 72 pokemon which can evolve. Some of the evolved pokemon can evolve again. You may want to make sure that evolving always goes to a pokemon with stronger stats. The cost ranged from ’12’ to ‘400’ (although only 1 pokemon exceeded ‘100’). - Move power: ‘0’ to ‘120’, duration: ‘0.4’ to ‘5.8’, energy (for charge moves): ‘-20’ to ‘-100’, energy (for quick moves): ‘4’ to ’15’ - Species Stats attack: ’29’ to ‘271’, defense ’44’ to ‘323’, stamina ’20’ to ‘500’. maxCP can be calculated based on the other stats. - Type: there are 18 different types. - Type Multiplier: ‘0.8’ for weak against, ‘1.25’ for strong against Summary In this lesson I gave a brief introduction of the Entity Component System (ECS) architecture. I then discussed how that architecture was implemented with the database that provided all of the Pokemon data. I showed how to structure the tables and classes that work with those tables, and finally provided links that can help you populate those tables with data. Even if you don’t use the “real” Pokemon Go data, you will need to populate the database with something before you can continue with the rest of the project – the database on the repository will remain empty, although the classes will be updated accordingly. Don’t forget that there is a repository for this project located here. Also, please remember that this repository is using placeholder (empty) assets so attempting to run the game from here is pretty pointless – you will need to follow along with all of the previous lessons first. 6 thoughts on “Unofficial Pokemon Board Game – ECS” Great tutorial, but I got a question. I cant understand the TypeMultiplier class, what is attack_type_id and defend_type_id and what value is value? The “TypeMultiplier” is a table that will be used in damage algorithms related to the “Type” of a move and Pokemon using the move. The type refers to stuff like Flying, Water, Bug, etc. Some types are strong against others and some types are weak against others. So, I represent these relationships in the “TypeMultiplier” table where the “attack_type_id” is the “id” of a “Type” that is used in the attack, and the “defend_type_id” is the “id” of a “Type” that is defending against the attack. The “value” is a multiplier that can either cause the damage algorithm to do more damage or less damage. For example, a value of “1.25” means that the attacking type is strong against the defending type and will do more damage. If you see “0.8” then it means the attacking type is weak against the defending type and will do less damage. Does that make sense? You will see this used in the Battle Setup lesson (part 13). Yeah It does make sense now. Thank you for taking the time to explain it to me. Hi,jon I’m trying to learn ecs from this tutor. If possible, please upload only file pokemon.db. I can’t anything without it. The reason I didn’t include the pokemon data was because I am not sure about copy-right laws regarding those stats. I did however try my best to demonstrate how you could create your own stats or obtain a copy of them on your own. Also, one of the users on my forum shared some code demonstrating how to populate the database: I hope that helps! Thank you very much ,Jon I will try it.
https://theliquidfire.com/2017/02/13/unofficial-pokemon-board-game-ecs/
CC-MAIN-2021-10
en
refinedweb
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. 👉🏽 Kivy Tutorial – Learn Kivy with Examples. Scroll view: The ScrollView widget provides a scrollable/pannable viewport that is clipped at the scrollview’s bounding box. Scroll view accepts only one child and applies a window to it according to 2 properties: 1) scroll_x 2) scrool_y To determine if interaction is a scrolling gesture, these properties are used: - scroll_distance: the minimum distance to travel, defaults to 20 pixels. - scroll_timeout: the maximum time period, defaults to 55 milliseconds. Note: To use the scrollview you must have to import it: from kivy.uix.scrollview import ScrollView Basic Approach: 1) import kivy 2) import kivyApp 3) import scroll view 4) import string property 5) Set minimum version(optional) 6) create the scroll view class 7) Build the .kv file within the .py file 8) Run an app Implementation of the code: Output: Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
https://www.geeksforgeeks.org/python-scrollview-widget-in-kivy/?ref=rp
CC-MAIN-2021-10
en
refinedweb
About Applying Easing Methods to Version 2 Components About Applying Easing Methods to Version 2 Components Another use for the various easing methods is to apply them on version 2 components. Note that you can apply the easing methods only to the following components: Accordion, ComboBox, DataGrid, List, Menu and Tree. Each of the components allows different customizations using the easing methods. For example, the Accordion, ComboBox and Tree components enable you select an easing class to use for their respective open and close animations. By contrast, the Menu component only enables you to define the number of milliseconds that the animation takes. Applying Easing Methods to an Accordion Component This example shows you how to add an Accordion component to a Flash document, add a few children screens and change the default easing method and duration. If you decide to use this code in an actual project, you will probably want to reduce the value of the openDuration property, because really slow animations tend to annoy users when they open and close the accordion. Follow these steps to apply a different easing method to the Accordion component: - Create a new Flash document and save it as accordion.fla. - Drag a copy of the Accordion component onto the Stage and give it the instance name my_acc in the Property inspector. - Insert a new layer above Layer 1 and rename it actions. Add the following ActionScript to frame 1 of the actions layer: import mx.transitions.easing.*; my_acc.createChild(mx.core.View, "studio_view", {label:"Studio"}); my_acc.createChild(mx.core.View, "dreamweaver_view", {label:"Dreamweaver"}); my_acc.createChild(mx.core.View, "flash_view", {label:"Flash"}); my_acc.createChild(mx.core.View, "coldfusion_view", {label:"ColdFusion"}); my_acc.createChild(mx.core.View, "contribute_view", {label:"Contribute"}); my_acc.setStyle("openEasing", Bounce.easeOut); my_acc.setStyle("openDuration", 3500); This code imports the easing classes, so you can type Bounce.easeOutinstead of referring to each of the classes with fully-qualified names like mx.transitions.easing.Bounce.easeOut. Next, you add five new child panes to the Accordion component (Studio, Dreamweaver, Flash, ColdFusion, and Contribute). The final two lines of code set the easing style from the default easing method to Bounce.easeOut, and set the length of the animation to 3500 milliseconds (3.5 seconds). - Save the document, and then select Control > Test Movie to preview the file in the test environment. - Click each of the different header (title) bars to view the modified animations, and switch between each pane. If you want the animation to increase its speed, decrease openDurationfrom 3.5 seconds to a smaller number. The default duration for the animation is 250 milliseconds, or a quarter of a second. Applying Easing Methods to the ComboBox The process to change the default easing method on a ComboBox component is similar to the previous example in which you modify the Accordion component’s animation. In the following example, you use ActionScript to dynamically add the component to the Stage at runtime. - Create a new Flash document and save it as combobox.fla. Drag a copy of the ComboBox component from the Components panel onto the Stage. Select the component, and then press the Backspace or Delete key to delete it from the Stage. Note: Although you remove the component from the Stage, the component still remains in the current document’s library. - Insert a new layer and rename it actions. Make sure the actions layer is above Layer 1. Add the following ActionScript to frame 1 of the actions layer: import mx.transitions.easing.*; this.createClassObject(mx.controls.ComboBox, "my_cb", this.getNextHighestDepth()); var product_array:Array = new Array("Studio", "Dreamweaver", "Flash", "ColdFusion", "Contribute", "Breeze", "Director", "Flex"); my_cb.dataProvider = product_array; my_cb.setSize(140, 22); my_cb.setStyle("openDuration", 2000); my_cb.setStyle("openEasing", Elastic.easeOut); The thiskeyword in the second line of code refers to the main Timeline of the SWF file. After you import each of the easing methods (which occurs in the first line of code) the createClassObject()method creates an instance of the ComboBox component. This line of code puts the component on the Stage at runtime, and gives it the instance name my_cb. Next, you create an array named product_arraythat contains a list of Macromedia software. You use this array in the following line of code to set the dataProviderproperty to the array of product names. Then you use the setSize()method to resize the component instance, set openDurationto 2000 milliseconds (2 seconds), and change the easing method to Elastic.easeOut. Note: Like earlier examples, you import the easing classes, which enable you to use the shortened version of the class name instead of using the fully qualified class name of mx.transitions.easing.Elastic.easeOut. - Save the current document, and select Control > Test Movie to view the document in the test environment. Click the ComboBox component on the Stage to animate your dropdown list of product names using the specified easing class. Note: Just because you can use an easing method such as Elastic or Bounce for your ComboBox or Accordion components doesn’t mean you should. Some users might find it distracting if your options take a long time to stop moving before they can read and select from the menu. Test your individual applications and settings, and decide whether the easing methods enhance or detract from your project. Animating the DataGrid Flash MX Professional also enables you to tweak the animations you use when you select items in a component (such as the DataGrid, Tree, ComboBox or List components). Although the animations are subtle, in some cases it is nice to be able to control small details or just speed up the animation. For an example, follow these steps: - Create a new Flash document and save it as datagrid.fla. - Drag an instance of the DataGrid component onto the Stage and give it the instance name my_dg. - Insert a new layer and rename it actions. Make sure you place the actions layer above Layer 1. Add the following ActionScript to the actions layer: import mx.transitions.easing.*; my_dg.setSize(320, 240); my_dg.addColumn("product"); my_dg.getColumnAt(0).width = 304; my_dg.rowHeight = 60; my_dg.addItem({product:'Studio'}); my_dg.addItem({product:'Dreamweaver'}); my_dg.addItem({product:'Flash'}); my_dg.setStyle("selectionEasing", Elastic.easeInOut); my_dg.setStyle("selectionDuration", 1000); This ActionScript imports the easing classes, and resizes the component instance on the Stage to 320 pixels (width) by 240 pixels (height). Next, you create a new column named product, and resize the column to 304 pixels (width). The data grid itself is 320 pixels wide, although the scroll bar is 16 pixels wide, which leaves a difference of 304 pixels. Then you set the row height to 60 pixels high, so the easing animations are easier to see. The next three lines of ActionScript add items to the data grid instance so you can click and see the animations. Finally the selectionEasingand selectionDurationproperties are set using the setStyle()method. The easing method is set to Elastic.easeInOutand the duration is set to 1000 milliseconds (one second, which is five times longer than the default value of 200 milliseconds). Save the document and select Control > Test Movie to view the result in the test environment. When you click an item in the DataGrid instance, you see the selection ease in and out using the elastic effect. The animation should be easy to see because the duration is significantly increased. Note: The same properties ( selectionEasingand selectionDuration) can also be used with the ComboBox, List, and Tree components.
http://designstacks.net/about-applying-easing-methods-to-version-2-components
CC-MAIN-2021-10
en
refinedweb
Every time I’m taking input from stdin it is reading as 0 in code chef ide, but it is working correct in vs code. Can anyone tell me why it is reading as 0. Because of this issue i was unable to submit my solution in yesterday’s competition #include < iostream > using namespace std; int main() { // your code goes here int t; scanf("%d",&t); while(t--){ long long num; cin>>num; cout<<num<<endl; } return 0; }
https://discuss.codechef.com/t/getting-input-as-0-from-stdin-in-code-chef-ide/80613
CC-MAIN-2021-10
en
refinedweb
#include <wx/propgrid/property.h> wxPGProperty is base class for all wxPropertyGrid properties and as such it is not intended to be instantiated directly.. Supported special attributes: It derives from wxNumericProperty and displays value as a signed long integer. wxIntProperty seamlessly supports 64-bit integers (i.e. wxLongLong) on overflow. To safely convert variant to integer, use code like this: Getting 64-bit value: Setting 64-bit value: Supported special attributes: "$" (apart from edit mode). Like wxIntProperty, wxUIntProperty seamlessly supports 64-bit unsigned integers (i.e. wxULongLong). Same wxVariant safety rules apply. Supported special attributes:. Supported special attributes: Represents a boolean value. wxChoice is used as editor control, by the default. wxPG_BOOL_USE_CHECKBOX attribute can be set to true in order to use check box instead. Supported special attributes: Like wxStringProperty, but has a button that triggers a small text editor dialog. Note that in long string values, some control characters are escaped: tab is represented by "\t", line break by "\n", carriage return by "\r" and backslash character by "\\". If another character is preceded by backslash, the backslash is skipped. Note also that depending on the system (port), some sequences of special characters, like e.g. "\r\n", can be interpreted and presented in a different way in the editor and therefore such sequences may not be the same before and after the edition. To display a custom dialog on button press, you can subclass wxLongStringProperty and override DisplayEditorDialog, like this: Also, if you wish not to have line breaks and tabs translated to escape sequences, then do following in constructor of your subclass: Supported special attributes: Like wxLongStringProperty, but the button triggers dir selector instead. Supported special attributes: Like wxLongStringProperty, but the button triggers file selector instead. Default wildcard is "All files..." but this can be changed by setting wxPG_FILE_WILDCARD attribute. Supported special attributes:" (i.e. flag labels) of wxFlagsProperty, you will need to use wxPGProperty::SetChoices() - otherwise they will not get updated properly. wxFlagsProperty supports the same attributes as wxBoolProperty. Property that manages a list of strings. Allows editing of a list of strings in wxTextCtrl and in a separate dialog. Supported special attributes: Property representing wxDateTime. Default editor is DatePickerCtrl, although TextCtrl should work as well. Supported special attributes:. Supported special attributes: Property representing image file(name). Like wxFileProperty, but has thumbnail of the image in front of the filename and autogenerates wildcard from available image handlers. Supported special attributes: Useful alternate editor: Choice. Represents wxColour. wxButton is used to trigger a colour picker dialog. There are various sub-classing opportunities with this class. See below in wxSystemColourProperty section for details. Supported special attributes: Represents wxFont. Various sub-properties are used to edit individual subvalues. Supported special attributes:: Virtual destructor. It is customary for derived properties to implement this. Default constructor. It is protected because wxPGProperty is only a base class for other property classes. Constructor. It is protected because wxPGProperty is only a base class for other property classes. Non-abstract property classes should have constructor of this style: Sets property cell in fashion that reduces number of exclusive copies of cell data. Used when setting, for instance, same background colour for a number of properties. (i.e.. Clear cells associated with property. Deletes children of the property. Removes entry from property's wxPGChoices and editor control (if it is active). If selected item is deleted, then the value is set to unspecified. This is used by Insert etc. Returns value of an attribute. Override if custom handling of attributes is needed. Default implementation simply return NULL variant. Returns pointer to an instance of used editor.FileProperty, wxEditorDialogProperty, wxFlagsProperty, wxBoolProperty, wxDateProperty, wxFloatProperty, wxUIntProperty, wxSystemColourProperty, wxNumeric. Makes sure m_cells has size of column+1 (or more).. Returns map-like storage of property's attributes. Returns attributes as list wxVariant. Returns property's base name (i.e.. Gets managed client object of a property. Returns editor used for given column. NULL for no editor. Returns common value selected for this property. -1 for none. Returns property's default value. If property's value type is not a built-in one, and "DefaultValue" attribute is not defined, then this function usually returns Null variant. Return number of displayed common values for this property. (i.e. no action is generated when button is pressed). Reimplemented in wxEditorDialogProperty. Gets flags as a'|' delimited string. Note that flag names are not prepended with 'wxPG_PROP_'. Returns property grid where property lies. Returns owner wxPropertyGrid, but only if one is currently on a page displaying this property. Returns property's help or description text. Returns property's hint text (shown in empty value cell). Converts image width into full image offset, with margins. Returns position in parent's array. Returns property at given virtual y coordinate. Returns property's label. Returns last visible child property, recursively. Returns highest level non-category, non-root parent. Useful when you have nested properties with children. Returns maximum allowed length of the text the user can enter in the property text editor. Returns property's name with all (non-category, non-root) parents. Return parent of property. Returns (direct) child property with given name (or NULL if not found). Returns (direct) child property with given name (or NULL if not found), with hint index. true if property has given flag set. Returns true if property has given flag set. Returns true if property has all given flags set. Returns true if property has even one visible child. Hides or reveals the property. Returns index of given child property. wxNOT_FOUND if given property is not child of this. Use this member function to add independent (i.e. child property is selected. Returns true if property is enabled. Returns true if property has visible children. Returns true if this property is actually a wxRootProperty. Returns true if candidateParent is some parent of this property. Use, for example, to detect if item is inside collapsed section.. Returns last sub-property.+rect.width) in wxImageFileProperty, wxCursorProperty, and wxSystemColourProperty. in wxSystemColour. If property's editor is created this forces its recreation. Useful in SetAttribute etc. Returns true if actually did anything.. Sets client object of a property. Sets common value selected for this property. -1 for none. Sets property's default text and background colours. flags from a '|' delimited string. Note that flag names are not prepended with 'wxPG_PROP_'. Sets property's help string, which is shown, for example, in wxPropertyGridManager's description text box. Sets property's label. Set maximum length of the text the user can enter in the text editor. If it is 0, the length is not limited and the text can be as long as it is supported by the underlying native text control widget.. Sets property's value to unspecified (i.e. Null variant). Call with false in OnSetValue() to cancel value changes after all (i.e.PGRootProperty,System,ColourProperty, wxSystemColourProperty, wxFontProperty, and wxStringProperty. This member is public so scripting language bindings wrapper code can access it freely.
https://docs.wxwidgets.org/trunk/classwx_p_g_property.html
CC-MAIN-2021-10
en
refinedweb
Why should .NET developers be interested in Jamstack? This post was contributed by our friends at Kentico Kontent. If you’re a .NET or C# developer, the Jamstack approach to building websites might have fallen off your radar over the years. With the development of the Jamstack ecosystem, now might be the right time for you to build on a Jamstack architecture and utilize all your well-deserved .NET skills. What marmalade cake are you talking about? Jamstack—one of the key concepts is pre-rendering. In Jamstack sites the entire frontend is prepared at the build time, and the resulting static output is served from a content delivery network (CDN). As a Jamstack developer, you don’t want to write all the logic for transforming your project into static files. Instead, you want to use some tools for this pre-rendering. These tools are doing a lot of fancy stuff for you—usually they allow you to apply templates, handle all the bundling and minification, and provide you with a rich ecosystem of plugins for specific use cases like data fetching from CMS, site map generating, or optimizing images. These tools are called static site generators. But let’s talk .NET now, where a generator called Statiq is quickly becoming a popular option. U jokin’? Why would I want to build a static site in the 2020s? Glad you asked! These are not static sites full of GIFs and WordArt from the `90s—though I love those retro feeling ones like on my university programming teacher’s site. Browsers, JavaScript, and APIs have all advanced in capabilities since then. These days you can implement dynamic functionalities like authentication, payments, or search even on static sites. So, how to jam on .NET? With Statiq! Statiq is a static site generator for .NET. It brings the first-class experience of both Visual Studio and VS Code – including Intellisense and debugging – to the Jamstack world. In combination with the .NET platform and many built-in features like pipelines, modules, preview server, and shortcodes, it is a great entry ticket for .NET developers and teams into Jamstack. The Statiq project contains a general-purpose static generation framework called Statiq Framework and a convention-based static site generator called Statiq Web that’s built on top of it. From now on, we will be referring to Statiq.Web when talking about Statiq. The basics of Statiq For a start, let’s explain some key concepts and specifics of Statiq. I believe these are essential to having a solid base when starting with this static site generator. Documents A document is a primary unit of information in Statiq. It consists of content and metadata. Imagine that Statiq is like a document database that can process these documents. To be more precise, these documents are immutable. When a document is processed, it’s returned a new instance of the document. Documents are manipulated by modules. Modules A module is a component that performs a specific action with documents. A module takes documents as input, does an operation based on those documents (possibly transforming them), and outputs documents as a result of whatever operation was performed. Modules are typically chained in a sequence called a pipeline. Pipelines A pipeline is a document processing unit. A pipeline consists of one or more modules. Basically, the pipeline is a workflow blueprint of how your modules should handle documents. One might find a slight analogy with a controller in .NET MVC, nevertheless, it’s good to think about pipelines in a more declarative way. You just specify what your output should be rather than how to transform and produce it. Pipelines have their own lifecycle process defined by phases. When pipelines and modules are executed, the current state is passed in the execution context. Gimme code! In this section, we’ll create a new static site powered by Statiq from scratch. The site will contain one root page, a listing of the articles, and article detail pages. The example will showcase rendering using Razor pages as well as Handlebars templates. Then we’ll use a third party module for fetching and rendering content from the headless CMS Kontent. In the end, we’ll publish our site to Netlify, with preview functionality. Note: If you just want to see working code published on Netlify, you can fork my repository and start from Step 7. Prerequisites Installing the .NET Core SDK is the only prerequisite. This tutorial assumes you are familiar with the basics of frontmatter, markdown formatting, and the .NET ecosystem. Step 1: Create a new project - Run dotnet new console --name StatiqTutorialfrom the command line. - Navigate to your newly created StatiqTutorialdirectory and run dotnet add package Statiq.Web --version 1.0.0-beta.14(you can find the latest version of the framework on Nuget). Create a bootstrapper in your Program.cs. using Statiq.App; using Statiq.Web; namespace StatiqTutorial { public class Program { public static async Task<int> Main(string[] args) => await Bootstrapper .Factory .CreateWeb(args) .RunAsync(); } } In your project, create an inputfolder with an index.mdfile with the following content. The input directory is a default path where Statiq looks for input files. --- Title: My First Statiq page --- # Hello World! Hello from my first Statiq page. Run dotnet run. This command will create an output folder with the generated page. By running dotnet run -- previewStatiq will generate the outputcontent (same as in the previous step). In addition, it’ll start your server and will serve content from the output directory. You should see your rendered site at. What just happened? All the magic happened in the CreateWeb(args) method that created a bootstrapper with Statiq functionality. Default configuration runs your app with several modules. The most important one is default processing of your input markdown files and generating a page with the same name with content in HTML. Step 2: Create an index page with a custom Razor template Go to Program.csand replace it with the code below. With this bootstrapper setup, you tell Statiq you don’t want all the default magic, and you’d rather take care of the content rendering on your own. However, the AddHostingCommands()is still providing you with preview functionality. using System.Threading.Tasks; using Statiq.App; using Statiq.Web; namespace StatiqTutorial { public class Program { public static async Task<int> Main(string[] args) => await Bootstrapper .Factory .CreateDefault(args) .AddHostingCommands() .RunAsync(); } } In the inputfolder remove index.mdand create a contentdirectory. In this directory, we’ll have our input files for content. In the input/contentcreate a new home.mdfile with the following code. --- Title: Hello World from Statiq! Content: This is a root page of the statically generated site powered by Statiq. This page is rendered by Razor view template. Statiq Web is a powerful static website generation toolkit suitable for most use cases. It's built on top of Statiq Framework, so you can always extend or customize it beyond those base capabilities as well. This is an example of how to render one single page. --- This will be your local content data source file for your home page. It’s a basic frontmatter markdown content with the Title and Content properties. - In the inputdirectory create Home.cshtmlfile with content. - Create HomeViewModel.cs. - When you check the Home.cshtmlyou’ll find out that your HomeViewModel is not visible from this view. To fix it, create new _ViewImports.cshtmlin the input directory. - Now we need to tell Statiq how we want to process and handle our input file. Create a HomePipeline.csfile. In the Input phase, this pipeline reads our content/home.mdfile. The Process phase uses ExtractFrontMatterand ParseYamlmodules that get content from this file. We need to somehow connect our input document with our view. We achieve this by using the MergeContentmodule in the RenderRazormodule, where we specify how to create an appropriate view model. The SetDestinationmodule determines where your files will be written. In the last Output phase, we use the WriteFilesmodule for writing our output files. - Run dotnet run -- preview. You should see your markdown content rendered on the Razor page similar to this deployed on Netlify. Step 3: Create a listing page with a Razor template - In input/content/featurescopy the following markdown files. These will be our content data source for the listing page. You can find content and structure for these files on GitHub. - In the inputfolder create FeaturesListing.cshtml. - Create Feature.cs, FeaturesListingViewModel.cs, and FeaturesListingRazorPipeline.cs. It’s worth mentioning that in the Process phase we are using the execution context of the current pipeline, where we are adding content from our markdown files as children of the document. In the Output phase, we are iterating through the document’s children, and we are creating List<Feature>features object, which is used by FeaturesListingViewModel. Other principles are similar to those described in Step 2. - After running dotnet run -- previewyou should see your features listing at. 5.If you’d like to use the HandleBars template instead, you can find the pipeline and template on GitHub. The principles are the same. Step 4: Create a detail page with default markdown rendering - Create FeatureDetailPipeline.cs. In the Process phase, this pipeline uses the RenderMarkdownmodule that renders markdown. - Run dotnet run -- preview. Now your links from both (Razor and HandleBars) listing pages leading to the detail one should work. Step 5: Prepare content in the headless CMS Kontent When you want to enable content authors to create and manage content, it’s more convenient to provide them with the capabilities of Headless CMS than to edit your codebase directly. In this step, we’ll create a project in headless CMS Kontent. Moreover, we’ll create a new home page, which will use content from this CMS. - Go to kontent.ai and create a new project. Go to Content Types and create a new Home content type. Add Title and Content text elements. Save changes. Go to the Content & Assets section and create a new content item Hello World from Statiq! based on Home content type. Fill in Title and Content elements. Publish the content item. In the Settings section, you will find your ProjectId and Preview API keys. You will need them in the next step. Step 6: Integrate content from the CMS into our Statiq site First, we’ll generate strongly typed classes for our content types. This helps us to work with content from the headless CMS in a safe, strongly typed way. Then we’ll use the Kontent.Statiq module to fetch and use our content in the new pipeline. - Install Kentico Kontent Generator utility. - In the root of your project, create a PowerShell script file named GenerateModels.ps1. - For the local configuration in the root of your project, create appsettings.json. Replace projectId with the one from the previous step. - When you run this script, it generates strongly typed models together with ITypeProvider in the Models folder. - Add Kontent.Statiq module to your project. - Register CustomTypeProvider and DeliveryClient in the bootstrapper. - Create HomeFromCmsPipeline.csfile. This pipeline uses the Kontent.Statiq module in the Input phase. In the Process phase, we are reusing the Home.cshtmlrazor view. All the magic happens in the Process phase. We are creating HomeViewModelusing an already created new constructor. The parameter of the constructor is Statiq’s document created with content from the headless CMS. - Run dotnet run -- preview. At should see your rendered content from the headless CMS. Pro tip: You can also check how your site looks and behaves with unpublished content. Just enable preview mode in appsettings.json and use the Preview API key from the previous step. { "DeliveryOptions": { "ProjectId": "YOUR_PROJECT_ID", "PreviewApiKey": "YOUR_API_KEY", "UsePreviewApi": true } } Step 7: Let’s publish it on Netlify We will create two sites on Netlify. While one will build our production site with published content, the other one will use unpublished preview content. Netlify’s built machines got installed .NET5 framework by default. Make sure in your project’s .csproj file you are targeting net5.0 as a target framework. - Push the whole project to your GitHub repository. Do not include appsettings.json. We will provide these settings in the form of environment variables. If you don’t want to follow all the previous steps, you can fork my repository and start from here. - Go to Netlify and create a new site from Git, select your repository. Fill in dotnet runas a Build command and outputas a Publish directory. Add a new DeliveryOptions\_\_ProjectIdvariable and enter your projectId. Note: Netlify uses double underscore (__) as the delimiter for the nested environment variables. Click Deploy site. Your site will be ready within minutes. Step 8: Unpublished preview content on Netlify - For previewing unpublished content, create a new site following steps from Step 7. In addition, you will have to provide a PreviewApiKey and UsePreviewApi flag. Besides DeliveryOptions\_\_ProjectIdadd two new environment variables DeliveryOptions\_\_PreviewApiKeywith your Preview API Key value and DeliveryOptions__UsePreviewApiwith true value. Click Deploy site. Your preview site will be ready within minutes. Pro tip: Add webhooks for rebuilding your site when content is changed. You can learn more about Kontent webhooks and Netlify build in this article. Wrap-up, next steps, and resources This tutorial is meant to be an introduction to the Statiq static site generator. There are opportunities for you to make additions to the code around styling, SEO, and even adding JavaScript for more capabilities. If you would like to use a more complete template, I’d recommend the Statiq Lumen starter, which is a blog site built with Statiq and Kentico Kontent that uses SEO best practices and had a great Lighthouse score. Another resource on connecting Statiq with the CMS is Jamstack on .NET: From zero to hero with Statiq and Kontent. About the author Martin Makarsky is a developer advocate and hacker at Kentico. During the day he tries to find ways to help people with code. At nights, he’s hacking at first glance incompatible pieces into meaningful structures. He writes at About Kentico Kontent Kontent is a cloud-native headless CMS that lets you build websites and applications fast. Integrate Kontent directly into your Netlify site for faster deployments and unrestricted design possibilities. Reach out about using Kontent with your next production Netlify project.
https://www.netlify.com/blog/2021/01/22/why-should-.net-developers-be-interested-in-jamstack/
CC-MAIN-2021-10
en
refinedweb
Hide Forgot libvirt-python fails to build with Python 3.10.0a2. Traceback (most recent call last): File "/builddir/build/BUILD/libvirt-python-6.9.0/sanitytest.py", line 5, in <module> import lxml.etree ImportError: /usr/lib64/python3.10/site-packages/lxml/etree.cpython-310-x86_64-linux-gnu.so: undefined symbol: _PyGen_Send This seem to be related to. It might be fixed with this patch that works for numpy. Upstream has decided to solve this differently, but until that happens, we are using this patch in our Copr (for other packages). For the build logs, see: For all our attempts to build libvirt-python. That stack trace shows the problem is in the lxml.etree module, not libvirt, so re-assigning. Yes, sorry for the confusion. There was a mid air collision while I was updating the bugzilla. The above error was fixed in libxml, but libvirt-python rebuild leads to another error: libvirt-lxc-override.c:67:5: warning: ‘PyEval_ThreadsInitialized’ is deprecated [-Wdeprecated-declarations] 67 | LIBVIRT_BEGIN); | ^~~~~~~~~~~~~~~~~~~~~~~~~ libvirt-lxc-override.c:69:5: warning: ‘PyEval_ThreadsInitialized’ is deprecated [-Wdeprecated-declarations] 69 | LIBVIRT_END); You can see full log here: bpo-39877: Deprecated PyEval_InitThreads() and PyEval_ThreadsInitialized(). Calling PyEval_InitThreads() now does nothing. Reassigning back to libvirt-python Those messages, while important to fix, are merely warnings so don't cause the build to fail. The real problem shown in the logs is the test suite failure: running test /usr/bin/python3 sanitytest.py build/lib.linux-x86_64-3.1 /usr/share/libvirt/api/libvirt-api.xml Traceback (most recent call last): File "/builddir/build/BUILD/libvirt-python-6.9.0/sanitytest.py", line 11, in <module> import libvirt ModuleNotFoundError: No module named 'libvirt' error: command '/usr/bin/python3' failed with exit It looks like we're truncating the version number to 3.1 when passing the build directory. From setup.py: plat_specifier = ".%s-%s" % (self.plat_name, sys.version[0:3]) I believe this is the cause. It evals to 3.1 on Python 3.10. Fixes proposed upstream in I've patched this in our copr to unblock testing the depended packages. Let me know if I should submit a PR. It'll get fixed in the next monthly rebase of libvirt around Dec 1st That'll work nicely, thanks Daniel.
https://bugzilla.redhat.com/show_bug.cgi?id=1897112
CC-MAIN-2021-10
en
refinedweb
=head L<perlop>.) List operators take more than one argument, while unary operators can never take more than one argument. Thus, a comma terminates the argument of a unary operator, but merely separates the arguments of a list operator. A unary operator generally provides scalar context to its argument, while a list operator may provide either scalar or list contexts for its arguments. If it does both, scalar arguments come first and list argument follow, and there can only ever be one such list argument. For instance, L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> has three scalar arguments followed by a list, whereas L<C<gethostbyname>|/gethostbyname NAME> has four scalar arguments. I<looks> like a function, therefore it I L<C<use warnings> L<C<time>|/time> and L<C<endpwent>|/endpwent>. For example, C<time+86_400> always means C. X<context> A named array in scalar context is quite different from what would at first glance appear to be a list in scalar context. You can't get a list like C< L<chown(2)>, L<fork(2)>, L<closedir(2)>, etc.) return true when they succeed and L<C<undef>|/undef EXPR> otherwise, as is usually mentioned in the descriptions below. This is different from the C interfaces, which return C<-1> on failure. Exceptions to this rule include L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>, and L<C<syscall>|/syscall NUMBER, LIST>. System calls also set the special L<C<$!>|perlvar/$!> L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such a module, see the module's documentation for details of the syntax that it defines. =head2 Perl Functions by Category X<function> Here are Perl's functions (including things that look like functions, like some keywords and named operators) arranged by category. Some functions appear in more than one place. Any warnings, including those produced by keywords, are described in L<perldiag> and L<warnings>. =over 4 =item Functions for SCALARs or strings X<scalar> X<string> X<character> =for Pod::Functions =String L<C<chomp>|/chomp VARIABLE>, L<C<chop>|/chop VARIABLE>, L<C<chr>|/chr NUMBER>, L<C<crypt>|/crypt PLAINTEXT,SALT>, L<C<fc>|/fc EXPR>, L<C<hex>|/hex EXPR>, L<C<index>|/index STR,SUBSTR,POSITION>, L<C<lc>|/lc EXPR>, L<C<lcfirst>|/lcfirst EXPR>, L<C<length>|/length EXPR>, L<C<oct>|/oct EXPR>, L<C<ord>|/ord EXPR>, L<C<pack>|/pack TEMPLATE,LIST>, L<C<qE<sol>E<sol>>|/qE<sol>STRINGE<sol>>, L<C<qqE<sol>E<sol>>|/qqE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>, L<C<rindex>|/rindex STR,SUBSTR,POSITION>, L<C<sprintf>|/sprintf FORMAT, LIST>, L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>, L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>, L<C<uc>|/uc EXPR>, L<C<ucfirst>|/ucfirst EXPR>, L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>> Regular expressions and pattern matching X<regular expression> X<regex> X<regexp> =for Pod::Functions =Regexp L<C<mE<sol>E<sol>>|/mE<sol>E<sol>>, L<C<pos>|/pos SCALAR>, L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>, L<C<quotemeta>|/quotemeta EXPR>, L<C<sE<sol>E<sol>E<sol>>|/sE<sol>E<sol>E<sol>>, L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, L<C<study>|/study SCALAR> =item Numeric functions X<numeric> X<number> X<trigonometric> X<trigonometry> =for Pod::Functions =Math L<C<abs>|/abs VALUE>, L<C<atan2>|/atan2 Y,X>, L<C<cos>|/cos EXPR>, L<C<exp>|/exp EXPR>, L<C<hex>|/hex EXPR>, L<C<int>|/int EXPR>, L<C<log>|/log EXPR>, L<C<oct>|/oct EXPR>, L<C<rand>|/rand EXPR>, L<C<sin>|/sin EXPR>, L<C<sqrt>|/sqrt EXPR>, L<C<srand>|/srand EXPR> =item Functions for real @ARRAYs X<array> =for Pod::Functions =ARRAY L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, L<C<pop>|/pop ARRAY>, L<C<push>|/push ARRAY,LIST>, L<C<shift>|/shift ARRAY>, L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>, L<C<unshift>|/unshift ARRAY,LIST>, L<C<values>|/values HASH> =item Functions for list data X<list> =for Pod::Functions =LIST L<C<grep>|/grep BLOCK LIST>, L<C<join>|/join EXPR,LIST>, L<C<map>|/map BLOCK LIST>, L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>, L<C<sort>|/sort SUBNAME LIST>, L<C<unpack>|/unpack TEMPLATE,EXPR> =item Functions for real %HASHes X<hash> =for Pod::Functions =HASH L<C<delete>|/delete EXPR>, L<C<each>|/each HASH>, L<C<exists>|/exists EXPR>, L<C<keys>|/keys HASH>, L<C<values>|/values HASH> =item Input and output functions X<I/O> X<input> X<output> X<dbm> =for Pod::Functions =I/O L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<close>|/close FILEHANDLE>, L<C<closedir>|/closedir DIRHANDLE>, L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<die>|/die LIST>, L<C<eof>|/eof FILEHANDLE>, L<C<fileno>|/fileno FILEHANDLE>, L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<format>|/format>, L<C<getc>|/getc FILEHANDLE>, L<C<print>|/print FILEHANDLE LIST>, L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>, L<C<rewinddir>|/rewinddir DIRHANDLE>, L<C<say>|/say FILEHANDLE LIST>, L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, L<C<seekdir>|/seekdir DIRHANDLE,POS>, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, L<C<syscall>|/syscall NUMBER, LIST>, L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<tell>|/tell FILEHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<warn>|/warn LIST>, L<C<write>|/write FILEHANDLE> Functions for fixed-length data or records =for Pod::Functions =Binary L<C<pack>|/pack TEMPLATE,LIST>, L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<syscall>|/syscall NUMBER, LIST>, L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<unpack>|/unpack TEMPLATE,EXPR>, L<C<vec>|/vec EXPR,OFFSET,BITS> =item Functions for filehandles, files, or directories X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink> =for Pod::Functions =File L<C<-I<X>>|/-X FILEHANDLE>, L<C<chdir>|/chdir EXPR>, L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, L<C<chroot>|/chroot FILENAME>, L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>, L<C<mkdir>|/mkdir FILENAME,MODE>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, L<C<opendir>|/opendir DIRHANDLE,EXPR>, L<C<readlink>|/readlink EXPR>, L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<rmdir>|/rmdir FILENAME>, L<C<select>|/select FILEHANDLE>, L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>, L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST> =item Keywords related to the control flow of your Perl program X<control flow> =for Pod::Functions =Flow L<C<break>|/break>, L<C<caller>|/caller EXPR>, L<C<continue>|/continue BLOCK>, L<C<die>|/die LIST>, L<C<do>|/do BLOCK>, L<C<dump>|/dump LABEL>, L<C<eval>|/eval EXPR>, L<C<evalbytes>|/evalbytes EXPR>, L<C<exit>|/exit EXPR>, L<C<__FILE__>|/__FILE__>, L<C<goto>|/goto LABEL>, L<C<last>|/last LABEL>, L<C<__LINE__>|/__LINE__>, L<C<next>|/next LABEL>, L<C<__PACKAGE__>|/__PACKAGE__>, L<C<redo>|/redo LABEL>, L<C<return>|/return EXPR>, L<C<sub>|/sub NAME BLOCK>, L<C<__SUB__>|/__SUB__>, L<C<wantarray>|/wantarray> L<C<break>|/break> is available only if you enable the experimental L<C<"switch"> feature|feature/The 'switch' feature> or use the C<CORE::> prefix. The L<C<"switch"> feature|feature/The 'switch' feature> also enables the C<default>, C<given> and C<when> statements, which are documented in L<perlsyn/"Switch Statements">. The L<C<"switch"> feature|feature/The 'switch' feature> is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. In Perl v5.14 and earlier, L<C<continue>|/continue BLOCK> required the L<C<"switch"> feature|feature/The 'switch' feature>, like the other keywords. L<C<evalbytes>|/evalbytes EXPR> is only available with the L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> (see L<feature>) or if prefixed with C<CORE::>. L<C<__SUB__>|/__SUB__> is only available with the L<C<"current_sub"> feature|feature/The 'current_sub' feature> or if prefixed with C<CORE::>. Both the L<C<"evalbytes">|feature/The 'unicode_eval' and 'evalbytes' features> and L<C<"current_sub">|feature/The 'current_sub' feature> features are enabled automatically with a C<use v5.16> (or higher) declaration in the current scope. =item Keywords related to scoping =for Pod::Functions =Namespace L<C<caller>|/caller EXPR>, L<C<import>|/import LIST>, L<C<local>|/local EXPR>, L<C<my>|/my VARLIST>, L<C<our>|/our VARLIST>, L<C<package>|/package NAMESPACE>, L<C<state>|/state VARLIST>, L<C<use>|/use Module VERSION LIST> Miscellaneous functions =for Pod::Functions =Misc L<C<defined>|/defined EXPR>, L<C<formline>|/formline PICTURE,LIST>, L<C<lock>|/lock THING>, L<C<prototype>|/prototype FUNCTION>, L<C<reset>|/reset EXPR>, L<C<scalar>|/scalar EXPR>, L<C<undef>|/undef EXPR> =item Functions for processes and process groups X<process> X<pid> X<process id> =for Pod::Functions =Process L<C<alarm>|/alarm SECONDS>, L<C<exec>|/exec LIST>, L<C<fork>|/fork>, L<C<getpgrp>|/getpgrp PID>, L<C<getppid>|/getppid>, L<C<getpriority>|/getpriority WHICH,WHO>, L<C<kill>|/kill SIGNAL, LIST>, L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, L<C<readpipe>|/readpipe EXPR>, L<C<setpgrp>|/setpgrp PID,PGRP>, L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, L<C<sleep>|/sleep EXPR>, L<C<system>|/system LIST>, L<C<times>|/times>, L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS> =item Keywords related to Perl modules X<module> =for Pod::Functions =Modules L<C<do>|/do EXPR>, L<C<import>|/import LIST>, L<C<no>|/no MODULE VERSION LIST>, L<C<package>|/package NAMESPACE>, L<C<require>|/require VERSION>, L<C<use>|/use Module VERSION LIST> =item Keywords related to classes and object-orientation X<object> X<class> X<package> =for Pod::Functions =Objects L<C<bless>|/bless REF,CLASSNAME>, L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<package>|/package NAMESPACE>, L<C<ref>|/ref EXPR>, L<C<tie>|/tie VARIABLE,CLASSNAME,LIST>, L<C<tied>|/tied VARIABLE>, L<C<untie>|/untie VARIABLE>, L<C<use>|/use Module VERSION LIST> =item Low-level socket functions X<socket> X<sock> =for Pod::Functions =Socket L<C<accept>|/accept NEWSOCKET,GENERICSOCKET>, L<C<bind>|/bind SOCKET,NAME>, L<C<connect>|/connect SOCKET,NAME>, L<C<getpeername>|/getpeername SOCKET>, L<C<getsockname>|/getsockname SOCKET>, L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, L<C<listen>|/listen SOCKET,QUEUESIZE>, L<C<recv>|/recv SOCKET,SCALAR,LENGTH,FLAGS>, L<C<send>|/send SOCKET,MSG,FLAGS,TO>, L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, L<C<shutdown>|/shutdown SOCKET,HOW>, L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL> =item System V interprocess communication functions X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message> =for Pod::Functions =SysV L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>, L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, L<C<shmread>|/shmread ID,VAR,POS,SIZE>, L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE> =item Fetching user and group info X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd> =for Pod::Functions =User L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>, L<C<endpwent>|/endpwent>, L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, L<C<getgrnam>|/getgrnam NAME>, L<C<getlogin>|/getlogin>, L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>, L<C<setgrent>|/setgrent>, L<C<setpwent>|/setpwent> =item Fetching network info X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service> =for Pod::Functions =Network L<C<endprotoent>|/endprotoent>, L<C<endservent>|/endservent>, L<C<gethostbyaddr>|/gethostbyaddr ADDR,ADDRTYPE>, L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, L<C<getprotobyname>|/getprotobyname NAME>, L<C<getprotobynumber>|/getprotobynumber NUMBER>, L<C<getprotoent>|/getprotoent>, L<C<getservbyname>|/getservbyname NAME,PROTO>, L<C<getservbyport>|/getservbyport PORT,PROTO>, L<C<getservent>|/getservent>, L<C<sethostent>|/sethostent STAYOPEN>, L<C<setnetent>|/setnetent STAYOPEN>, L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setservent>|/setservent STAYOPEN> =item Time-related functions X<time> X<date> =for Pod::Functions =Time L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>, L<C<time>|/time>, L<C<times>|/times> =item Non-function keywords =for Pod::Functions =!Non-functions C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>, C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>, C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>, C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>, C<while>, C<x>, C<xor> : L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>, L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>, L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>, L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>, L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>, L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, L<C<getlogin>|/getlogin>, L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>, L<C<getpriority>|/getpriority WHICH,WHO>, L<C<getprotobynumber>|/getprotobynumber NUMBER>, L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>, L<C<getservbyport>|/getservbyport PORT,PROTO>, L<C<getservent>|/getservent>, L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>, L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>, L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>, L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>, L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>, L<C<setservent>|/setservent STAYOPEN>, L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, L<C<shmread>|/shmread ID,VAR,POS,SIZE>, L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>, L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>, L<C<syscall>|/syscall NUMBER, LIST>, L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, L<C<system>|/system LIST>, L<C<times>|/times>, L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS> For more information about the portability of these functions, see L<perlport> and other available platform-specific documentation. =head2 Alphabetical Listing of Perl Functions =over =for Pod::Functions a file test (-r, -x, etc) A file test, where X is one of the letters listed below. This unary operator takes one argument, either a filename, a filehandle, or a dirhandle, and tests the associated file to see if something is true about it. If the argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which tests STDIN. Unless otherwise documented, it returns C<1> for true and C<''> for false. If the file doesn't exist or can't be examined, it returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno). With the exception of the C<-l> test they all follow symbolic links because they use C<stat()> and not C<lstat()> (so dangling symlinks can't be examined and will therefore report failure). C<-s/a/b/> does not do a negated substitution. Saying C< C<-r>, C<-R>, C<-w>, C<-W>, C<-x>, and C<-r>, C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1 if any execute bit is set in the mode. Scripts run by the superuser may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the actual mode of the file, or temporarily set their effective uid to something else. If you are using ACLs, there is a pragma called L<C<filetest>|filetest> that may produce more accurate results than the bare L<C<stat>|/stat FILEHANDLE> mode bits. When under C<use filetest 'access'>, the above-mentioned filetests test whether the permission can(not) be granted using the L<access(2)> family of system calls. Also note that the C<-x> and C<-X> tests L<C<filetest>|filetest> pragma for more information. The C<-T> and C<-B> tests work as follows. The first block or so of the file is examined to see if it is valid UTF-8 that includes non-ASCII characters. If so, it's a C<-T> file. Otherwise, that same portion of the file is examined for odd characters such as strange control codes or characters with the high bit set. If more than a third of the characters are strange, it's a C<-B> file; otherwise it's a C<-T> file. Also, any file containing a zero byte in the examined portion is considered a binary file. (If executed within the scope of a L<S<use locale>|perllocale> which includes C<LC_CTYPE>, odd characters are anything that isn't a printable nor space in the current locale.) If C<-T> or C<-B> is used on a filehandle, the current IO buffer is examined rather than the first block. Both C<-T> and C<-B> return true on an empty L<C<stat>|/stat FILEHANDLE> or L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle consisting of a solitary underline, then the stat structure of the previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used, saving a system call. (This doesn't work with C<-t>, and you need to remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in the stat structure for the symbolic link, not the real file.) (Also, if the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call, C<-T> and C<-B> will reset it with the results of C<-f -w -x $file> is equivalent to C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use the return value of C<-f $file> as an argument to another filetest operator, no special magic will happen.) Portability issues: L<perlport/-X>. To avoid confusing would-be users of your code with mysterious syntax errors, put something like this at the top of your script: use 5.010; # so filetest ops can stack =item abs VALUE X<abs> X<absolute> =item abs =for Pod::Functions absolute value function Returns the absolute value of its argument. If VALUE is omitted, uses L<C<$_>|perlvar/$_>. =item accept NEWSOCKET,GENERICSOCKET X<accept> =for Pod::Functions accept an incoming socket connect Accepts an incoming socket connect, just as L<accept(2)> does. Returns the packed address if it succeeded, false otherwise. See the example alarm SECONDS X<alarm> X<SIGALRM> X<timer> =item alarm =for Pod::Functions schedule a SIGALRM Arranges to have a SIGALRM delivered to this process after the specified number of wallclock seconds has elapsed. If SECONDS is not specified, the value stored in L<C<$_>|perlv C<0> may be supplied to cancel the previous timer without starting a new one. The returned value is the amount of time remaining on the previous timer. For delays of finer granularity than one second, the L<Time::HiRes> module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval. It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be internally implemented on your system with L<C<alarm>|/alarm SECONDS>. If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair. You can't rely on the alarm causing the system call to fail with L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers to restart system calls on some systems. Using L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the caveats given in L<perlipc/"Signals">. eval { local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required alarm $timeout; my $nread = sysread $socket, $buffer, $size; alarm 0; }; if ($@) { die unless $@ eq "alarm\n"; # propagate unexpected errors # timed out } else { # didn't } For more information see L<perlipc>. Portability issues: L<perlport/alarm>. =item atan2 Y,X X<atan2> X<arctangent> X<tan> X<tangent> =for Pod::Functions arctangent of Y/X in the range -PI to PI Returns the arctangent of Y/X in the range -PI to PI. For the tangent operation, you may use the L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar relation: sub tan { sin($_[0]) / cos($_[0]) } The return value for C<atan2(0,0)> is implementation-defined; consult your L<atan2(3)> manpage for more information. Portability issues: L<perlport/atan2>. =item bind SOCKET,NAME X<bind> =for Pod::Functions binds an address to a socket Binds a network address to a socket, just as L<bind(2)> does. Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in L<perlipc/"Sockets: Client/Server Communication">. =item binmode FILEHANDLE, LAYER X<binmode> X<binary> X<text> X<DOS> X<Windows> =item binmode FILEHANDLE =for Pod::Functions prepare binary files for I/O Arr L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno). L<C<binmode>|/binmode FILEHANDLE, LAYER> C<:raw> the filehandle is made suitable for passing binary data. This includes turning off possible CRLF translation and marking it as bytes (as opposed to Unicode characters). Note that, despite what may be implied in I<"Programming Perl"> (the Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>. Other layers that would affect the binary nature of the stream are I<also> disabled. See L<PerlIO>, and the discussion about the PERLIO environment variable in L<perlrun|perlrun/PERLIO>. The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to establish default I/O layers. I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER> C<:utf8> or C<:encoding(UTF-8)>. C<:utf8> just marks the data as UTF-8 without further checking, while C<:encoding(UTF-8)> checks the data for actually being valid UTF-8. More details can be found in L<PerlIO::encoding>. In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called after L<C<open>|/open FILEHANDLE,MODE,EXPR> but before any I/O is done on the filehandle. Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally flushes any pending buffered output data (and perhaps pending input data) on the handle. An exception to this is the C<:encoding> layer that changes the default character encoding of the handle. The C<:encoding> layer sometimes needs to be called in mid-stream, and it doesn't flush the stream. C<:encoding> also implicitly pushes on top of itself the C<:utf8> layer because internally Perl operates on UTF8-encoded Unicode characters. The operating system, device drivers, C libraries, and Perl run-time system all conspire to let the programmer treat a single character (C<\n>) as the line terminator, irrespective of external representation. On many operating systems, the native text file representation matches the internal representation, but on some platforms the external representation of C<\n> as a simple C<\cJ>, but what's stored in text files are the two characters C<\cM\cJ>. That means that if you don't use L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ> sequences on disk will be converted to C<\n> on input, and any C<\n> in your program will be converted back to C<\cM\cJ> on output. This is what you want for text files, but it can be disastrous for binary files. Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER> (on some systems) is that special end-of-file markers will be seen as part of the data stream. For systems from the Microsoft family this means that, if your binary data contain C<\cZ>, the I/O subsystem will regard it as the end of the file, unless you use L<C<binmode>|/binmode FILEHANDLE, LAYER>. L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST> operations, but also when using L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details). See the L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in L<perlvar> for how to manually set your input and output line-termination sequences. Portability issues: L<perlport/binmode>. =item bless REF,CLASSNAME X<bless> =item bless REF =for Pod::Functions create an object This function tells the thingy referenced by REF that it is now an object in the CLASSNAME package. If CLASSNAME is an empty string, it is interpreted as referring to the C<main> package. If CLASSNAME is omitted, the current package is used. Because a L<C<bless>|/bless REF,CLASSNAME> is often the last thing in a constructor, it returns the reference for convenience. Always use the two-argument version if a derived class might inherit the method doing the blessing. See L C<0>, because much code erroneously uses the result of L<C<ref>|/ref EXPR> as a truth value. See L<perlmod/"Perl Modules">. =item break =for Pod::Functions +switch break out of a C<given> block Break out of a C<given> block. L<C<break>|/break> is available only if the L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it is prefixed with C<CORE::>. The L<C<"switch"> feature|feature/The 'switch' feature> is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. =item caller EXPR X<caller> X<call stack> X<stack> X<stack trace> =item caller =for Pod::Functions get context of the current subroutine call Returns the context of the current pure perl subroutine call. In scalar context, returns the caller's package name if there I<is> a caller (that is, if we're in a subroutine or L<C<eval>|/eval EXPR> or L<C<require>|/require VERSION>) and the undefined value otherwise. caller never returns XS subs and they are skipped. The next pure perl sub will appear instead of the XS sub in caller's return values. In list context, caller returns # 0 1 2 my ($package, $filename, $line) = caller; Like L<C<__FILE__>|/__FILE__> and L<C<__LINE__>|/__LINE__>, the filename and line number returned here may be altered by the mechanism described at L<perlsyn/"Plain Old Comments (Not!)">. C<(eval)> if the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In such a case additional elements $evaltext and C<$is_require> are set: C<$is_require> is true if the frame is created by a L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST> statement, $evaltext contains the text of the C<eval EXPR> statement. In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, but $evaltext is undefined. (Note also that each L<C<use>|/use Module VERSION LIST> statement creates a L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.) $subroutine may also be C<(unknown)> if this particular subroutine happens to have been deleted from the symbol table. C<$hasargs> is true if a new instance of L<C<@_>|perlvar/@_> was set up for the frame. C<$hints> and C<$bitmask> contain pragmatic hints that the caller was compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and C<$bitmask> corresponds to L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and C<$bitmask> values are subject to change between versions of Perl, and are not meant for external use. C<$hinthash> is a reference to a hash containing the value of L<C<%^H>|perlvar/%^H> when the caller was compiled, or L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not modify the values of this hash, as they are the actual values stored in the optree. Furthermore, when called from within the DB package in list context, and with an argument, caller returns more detailed information: it sets the list variable C<@DB::args> to be the arguments with which the subroutine was invoked. Be aware that the optimizer might have optimized call frames away before L<C<caller>|/caller EXPR> had a chance to get the information. That means that C<caller(N)> might not return information about the call frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> might have information from the previous time L<C<caller>|/caller EXPR> was called. Be aware that setting C<@DB::args> is I<best effort>, intended for debugging or generating backtraces, and should not be relied upon. In particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so C<@DB::args> will contain modifications the subroutine makes to L<C<@_>|perlvar/@_> or its contents, not the original values at call time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit references to its elements, so under certain cases its elements may have become freed and reallocated for other variables or temporary values. Finally, a side effect of the current implementation is that the effects of C<shift @_> can I<normally> be undone (but not C<pop @_> or other splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been taken, I<and> subject to the caveat about reallocated elements), so C<@DB::args> is actually a hybrid of the current state and initial state of L<C<@_>|perlvar/@_>. Buyer beware. =item chdir EXPR X<chdir> X<cd> X<directory, change> =item chdir FILEHANDLE =item chdir DIRHANDLE =item chdir =for Pod::Functions change your current working directory Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to the directory specified by C<$ENV{HOME}>, if set; if not, changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It returns true on success, false otherwise. See the example under L<C<die>|/die LIST>. On systems that support L<fchdir(2)>, you may pass a filehandle or directory handle as the argument. On systems that don't support L<fchdir(2)>, passing handles raises an exception. =item chmod LIST X<chmod> X<permission> X<mode> =for Pod::Functions changes the permissions on a list of files Changes the permissions of a list of files. The first element of the list must be the numeric mode, which should probably be an octal number, and which definitely should I<not> be a string of octal digits: C<0644> is okay, but C<"0644"> is not. Returns the number of files successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a string. L<fchmod(2)>, you may pass filehandles among the files. On systems that don't support L C<S_I*> constants from the L<C<Fcntl>: L<perlport/chmod>. =item chomp VARIABLE X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> =item chomp( LIST ) =item chomp =for Pod::Functions remove a trailing record separator from a string This safer version of L<C<chop>|/chop VARIABLE> removes any trailing string that corresponds to the current value of L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR> in the L<C<English>|English> module). It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode (C<$/ = ''>), it removes all trailing newlines from the string. When in slurp mode (C<$/ = undef>) or fixed-length record mode (L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like; see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything. If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example: while (<>) { chomp; # avoid \n on last field my @array = split(/:/); # ... } If VARIABLE is a hash, it chomps the hash's values, but not its keys, resetting the L<C<each>|/each HASH> C<chomp $cwd = `pwd`;> is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as C<chomp( $cwd = `pwd` )> which you might expect. Similarly, C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than as C<chomp($a, $b)>. =item chop VARIABLE X<chop> =item chop( LIST ) =item chop =for Pod::Functions remove the last character from a string Chops off the last character of a string and returns the character chopped. It is much more efficient than C<s/.$//s> because it neither scans nor copies the string. If VARIABLE is omitted, chops L<C<$_>|perlvar/$_>. If VARIABLE is a hash, it chops the hash's values, but not its keys, resetting the L<C<each>|/each HASH> iterator in the process. You can actually chop anything that's an lvalue, including an assignment. If you chop a list, each element is chopped. Only the value of the last L<C<chop>|/chop VARIABLE> is returned. Note that L<C<chop>|/chop VARIABLE> returns the last character. To return all but the last character, use C<substr($string, 0, -1)>. See also L<C<chomp>|/chomp VARIABLE>. =item chown LIST X<chown> X<owner> X<user> X<group> =for Pod::Functions change the ownership on a list of files Changes the owner (and group) of a list of files. The first two elements of the list must be the I<numeric> uid and gid, in that order. A value of -1 in either position is interpreted by most systems to leave that value unchanged. Returns the number of files successfully changed. my $cnt = chown $uid, $gid, 'foo', 'bar'; chown $uid, $gid, @filenames; On systems that support L<fchown(2)>, you may pass filehandles among the files. On systems that don't support L: L<perlport/chown>. =item chr NUMBER X<chr> X<character> X<ASCII> X<Unicode> =item chr =for Pod::Functions get character this number represents Returns the character represented by that NUMBER in the character set. For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and chr(0x263a) is a Unicode smiley face. Negative values give the Unicode replacement character (chr(0xfffd)), except under the L<bytes> pragma, where the low eight bits of the value (truncated to an integer) are used. If NUMBER is omitted, uses L<C<$_>|perlvar/$_>. For the reverse, use L<C<ord>|/ord EXPR>. Note that characters from 128 to 255 (inclusive) are by default internally not encoded as UTF-8 for backward compatibility reasons. See L<perlunicode> for more about Unicode. =item chroot FILENAME X<chroot> X<root> =item chroot =for Pod::Functions make directory new root for path lookups This function works like the system call by the same name: it makes the named directory the new root directory for all further pathnames that begin with a C</> by your process and all its children. (It doesn't change your current working directory, which is unaffected.) For security reasons, this call is restricted to the superuser. If FILENAME is omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>. B<NOTE:> It is mandatory for security to C<chdir("/")> (L<C<chdir>|/chdir EXPR> to the root directory) immediately after a L<C<chroot>|/chroot FILENAME>, otherwise the current working directory may be outside of the new root. Portability issues: L<perlport/chroot>. =item close FILEHANDLE X<close> =item close =for Pod::Functions close file (or pipe or socket) handle L<C<open>|/open FILEHANDLE,MODE,EXPR> on it, because L<C<open>|/open FILEHANDLE,MODE,EXPR> closes it for you. (See L<C<open>|/open FILEHANDLE,MODE,EXPR>.) However, an explicit L<C<close>|/close FILEHANDLE> on an input file resets the line counter (L<C<$.>|perlvar/$.>), while the implicit close done by L<C<open>|/open FILEHANDLE,MODE,EXPR> does not. If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE> returns false if one of the other syscalls involved fails or if its program exits with non-zero status. If the only problem was that the program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>. Closing a pipe also waits for the process executing on the pipe to exit--in case you wish to look at the output of the pipe afterwards--and implicitly puts the exit status value of that command into L<C<$?>|perlvar/$?> and L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. If there are multiple threads running, L<C<close>|/close FILEHANDLE>. =item closedir DIRHANDLE X<closedir> =for Pod::Functions close directory handle Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and returns the success of that system call. =item connect SOCKET,NAME X<connect> =for Pod::Functions connect to a remote socket Attempts to connect to a remote socket, just like L<connect(2)>. Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in L<perlipc/"Sockets: Client/Server Communication">. =item continue BLOCK X<continue> =item continue =for Pod::Functions optional trailing block in a while or foreach When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a flow control statement rather than a function. If there is a L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a C<while> or C<foreach>), it is always executed just before the conditional is about to be evaluated again, just like the third part of a C<for> loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued via the L<C<next>|/next LABEL> statement (which is similar to the C L<C<continue>|/continue BLOCK> statement). L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or L<C<redo>|/redo LABEL> may appear within a L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and L<C<redo>|/redo LABEL> behave as if they had been executed within the main block. So will L<C<next>|/next LABEL>, but since it will execute a L<C<continue>|/continue BLOCK> block, it may be more entertaining. while (EXPR) { ### redo always comes here do_something; } continue { ### next always comes here do_something_else; # then back the top to re-check EXPR } ### last always comes here Omitting the L<C<continue>|/continue BLOCK> section is equivalent to using an empty one, logically enough, so L<C<next>|/next LABEL> goes directly back to check the condition at the top of the loop. When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function that falls through the current C<when> or C<default> block instead of iterating a dynamically enclosing C<foreach> or exiting a lexically enclosing C<given>. In Perl 5.14 and earlier, this form of L<C<continue>|/continue BLOCK> was only available when the L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See L<feature> and L<perlsyn/"Switch Statements"> for more information. =item cos EXPR X<cos> X<cosine> X<acos> X<arccosine> =item cos =for Pod::Functions cosine function Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, takes the cosine of L<C<$_>|perlvar/$_>. For the inverse cosine operation, you may use the L<C<Math::Trig::acos>|Math::Trig> function, or use this relation: sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } =item crypt PLAINTEXT,SALT X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> X<decrypt> X<cryptography> X<passwd> X<encrypt> =for Pod::Functions one-way passwd-style encryption Creates a digest string exactly like the L<crypt(3)> function in the C library (assuming that you actually have a version there that has not been extirpated as a potential munition). L<C<crypt>|/crypt PLAINTEXT L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored digest. If the two digests match, the password is correct. When verifying an existing digest string you should use the digest as the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used to create the digest is visible as part of the digest. This ensures L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same salt as the digest. This allows your code to work with the standard L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations. In other words, assume nothing about the returned string itself nor about how many bytes of SALT may matter. Traditionally the result is a string of 13 bytes: two first bytes of the salt, followed by 11 bytes from the set C<[. C<[./0-9A-Za-z]> (like C<join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of characters is just a recommendation; the characters allowed in the salt depend solely on your system's crypt library, and Perl can't restrict what salts L<C<crypt>|/crypt PLAINTEXT L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing large quantities of data, not least of all because you can't get the information back. Look at the L<Digest> module for more robust algorithms. If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which I<potentially> has characters with codepoints above 255), Perl tries to make sense of the situation by trying to downgrade (a copy of) the string back to an eight-bit byte string before calling L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good. If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with L<C<Wide character in crypt>|perldiag/Wide character in %s>. Portability issues: L<perlport/crypt>. =item dbmclose HASH X<dbmclose> =for Pod::Functions breaks binding on a tied dbm file [This function has been largely superseded by the L<C<untie>|/untie VARIABLE> function.] Breaks the binding between a DBM file and a hash. Portability issues: L<perlport/dbmclose>. =item dbmopen HASH,DBNAME,MASK X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> =for Pod::Functions create binding on a tied dbm file [This function has been largely superseded by the L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.] This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley DB file to a hash. HASH is the name of the hash. (Unlike normal L<C<open>|/open FILEHANDLE,MODE,EXPR>, the first argument is I<not> a filehandle, even though it looks like one). DBNAME is the name of the database (without the F<.dir> or F<.pag> extension if any). If the database does not exist, it is created with protection specified by MASK (as modified by the L<C<umask>|/umask EXPR>). To prevent creation of the database if it doesn't exist, you may specify a MODE of 0, and the function will return a false value if it can't find an existing database. If your system supports only the older DBM functions, you may make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your program. In older versions of Perl, if your system had neither DBM nor ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal error; it now falls back to L<sdbm(3)>. If you don't have write access to the DBM file, you can only read hash variables, not set them. If you want to test whether you can write, either use file tests or try setting a dummy hash entry inside an L<C<eval>|/eval EXPR> to trap the error. Note that functions such as L<C<keys>|/keys HASH> and L<C<values>|/values HASH> may return huge lists when used on large DBM files. You may prefer to use the L<C<each>|/each HASH> function to iterate over large DBM files. Example: # print out history file offsets dbmopen(%HIST,'/usr/lib/news/history',0666); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } dbmclose(%HIST); See also L<AnyDBM_File> for a more general description of the pros and cons of the various dbm approaches, as well as L<DB_File> for a particularly rich implementation. You can control which DBM library you use by loading that library before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>: use DB_File; dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") or die "Can't open netscape history file: $!"; Portability issues: L<perlport/dbmopen>. =item defined EXPR X<defined> X<undef> X<undefined> =item defined =for Pod::Functions test whether a value, variable, or function is defined Returns a Boolean value telling whether EXPR has a value other than the undefined value L<C<undef>|/undef EXPR>. If EXPR is not present, L<C<$_>|perlvar/$_> is checked. Many operations return L<C<undef>|/undef EXPR> to indicate failure, end of file, system error, uninitialized variable, and other exceptional conditions. This function allows you to distinguish L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string, and C<"0">, which are all equally false.) Note that since L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY> returns L<C<undef>|/undef EXPR> when its argument is an empty array, I<or> when the element to return happens to be L<C<undef>|/undef EXPR>. You may also use C<defined(&func)> to check whether subroutine C<func> has ever been defined. The return value is unaffected by any forward declarations of C<func>. A subroutine that is not defined may still be callable: its package may have an C<AUTOLOAD> method that makes it spring into existence the first time that it is called; see L<perlsub>. Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is no longer supported. It used to report whether memory for that aggregate had ever been allocated. You should instead use a simple test for size: if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" } When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use L<C<exists>|/exists EXPR> L<C<defined>|/defined EXPR> and are then surprised to discover that the number C<0> and C<""> (the zero-length string) are, in fact, defined values. For example, if you say "ab" =~ /a(.*)b/; The pattern match succeeds and L<C<defined>|/defined EXPR> only when questioning the integrity of what you're trying to do. At other times, a simple comparison to C<0> or C<""> is what you want. See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>, L<C<ref>|/ref EXPR>. =item delete EXPR X<delete> =for Pod::Functions deletes a value from a hash Given an expression that specifies an element or slice of a hash, L<C<delete>|/delete EXPR> deletes the specified elements from that hash so that L<C<exists>|/exists EXPR> on that element no longer returns true. Setting a hash element to the undefined value does not remove its key, but deleting it does; see L<C<exists>|/exists EXPR>. In list context, usually returns the value or values deleted, or the last such element in scalar context. The return list's length corresponds to that of the argument list: deleting non-existent elements returns the undefined value in their corresponding positions. When a L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> is passed to C<delete>, the return value is a list of key/value pairs (two elements for each item deleted from the hash). L<C<delete>|/delete EXPR> may also be used on arrays and array slices, but its behavior is less straightforward. Although L<C<exists>|/exists EXPR> will return false for deleted entries, deleting array elements never changes indices of existing values; use L<C<shift>|/shift ARRAY> or L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements fall at the end of an array, the array's size shrinks to the position of the highest element that still tests true for L<C<exists>|/exists EXPR>, or to 0 if none do. In other words, an array won't have trailing nonexistent elements after a delete. B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is strongly discouraged. The notion of deleting or checking the existence of Perl array elements is not conceptually coherent, and can lead to surprising behavior. Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment. Deleting from a hash tied to a DBM file deletes the entry from the DBM file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not necessarily return anything; it depends on the implementation of the L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever it pleases. The C<delete local EXPR> construct localizes the deletion to the current block at run time. Until the block exits, elements locally deleted temporarily no longer exist. See L<perlsub/"Localized deletion of elements of composite types">.]; =item die LIST X<die> X<throw> X<exception> X<raise> X<$@> X<abort> =for Pod::Functions raise an exception or bail out L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR> the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval EXPR> is terminated with the undefined value. If the exception is outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught exception is printed to C<STDERR> and perl exits with an exit code indicating failure. If you need to exit the process with a specific exit code, see L<C<exit>|/exit EXPR>. Equivalent examples: die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" Most of the time, C. Note that the "input line number" (also known as "chunk") is subject to whatever notion of "line" happens to be currently in effect, and is also available as the special variable L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. Hint: sometimes appending C<", stopped"> to your message will cause it to make better sense when the string C< LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> already contains an exception value (typically from a previous L<C<eval>|/eval EXPR>), then that value is reused after appending C<"\t...propagated">. This is useful for propagating exceptions: eval { ... }; die unless $@ =~ /Expected exception/; If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> contains an object reference that has a C<PROPAGATE> method, that method will be called with additional file and line number parameters. The return value replaces the value in L<C<$@>|perlvar/$@>; i.e., as if C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> is also empty, then the string C<"Died"> is used. You can also call L<C<die>|/die LIST> with a reference argument, and if this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@> contains that reference. This permits more elaborate exception handling using objects that maintain arbitrary state about the exception. Such a scheme is sometimes preferable to matching particular string values of L<C<$@>|perlvar/$@> with regular expressions. Because Perl stringifies uncaught exception messages before display, you'll probably want to overload stringification operations on exception objects. See L L<C<$@>|perlvar/$@> is a global variable, be careful that analyzing an exception caught by C<eval> } } If an uncaught exception results in interpreter exit, the exit code is determined from the values of L<C<$!>|perlvar/$!> and L<C<$?>|perlvar/$?> with this pseudocode: exit $! if $!; # errno exit $? >> 8 if $? >> 8; # child exit status exit 255; # last resort As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to unwinding the call stack; any C<DESTROY> or C<END> handlers can then alter this value, and thus Perl's exit code. The intent is to squeeze as much possible information about the likely cause into the limited space of the system exit code. However, as L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by any system call, this means that the value of the exit code used by L<C<die>|/die LIST> can be non-predictable, so should not be relied upon, other than to be non-zero. You can arrange for a callback to be run just before the L<C<die>|/die LIST> does its deed, by setting the L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called with the exception as an argument, and can change the exception, if it sees fit, by calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some examples. Although this feature was to be run only right before your program was to exit, this is not currently so: the L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do nothing in such situations, put die @_ if $^S; as the first line of the handler (see L<perlvar/$^S>). Because this promotes strange action at a distance, this counterintuitive behavior may be fixed in a future release. See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp> module. =item do BLOCK X<do> X<block> =for Pod::Functions turn a BLOCK into a TERM Not really a function. Returns the value of the last command in the sequence of commands indicated by BLOCK. When modified by the C<while> or C<until> loop modifier, executes the BLOCK once before testing the loop condition. (On other statements the loop modifiers test the conditional first.) C<do BLOCK> does I<not> count as a loop, so the loop control statements L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. See L<perlsyn> for alternative strategies. =item do EXPR X<do>'; C<do './stat.pl'> is largely like eval `cat stat.pl`; except that it's more concise, runs no external processes, and keeps track of the current filename for error messages. It also differs in that code evaluated with C<do FILE> cannot see lexicals in the enclosing scope; C<eval STRING> does. It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop. Using C<do> with a relative path (except for F<./> and F<../>), like do 'foo/stat.pl'; will search the L<C<@INC>|perlvar/@INC> directories, and update L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC> and L<perlvar/%INC> for these variables. In particular, note that whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the current directory) making these two cases equivalent, that is no longer necessarily the case, as '.' is not included in C<@INC> by default in perl versions 5.26.0 onwards. Instead, perl will now warn: do "stat.pl" failed, '.' is no longer in @INC; did you mean do "./stat.pl"? If L<C<do>|/do EXPR> can read the file but cannot compile it, it returns L<C<undef>|/undef EXPR> and sets an error message in L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also sets L<C<$!>|perlvar/$!>. If the file is successfully compiled, L<C<do>|/do EXPR> returns the value of the last expression evaluated. Inclusion of library modules is better done with the L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION> operators, which also do automatic error checking and raise an exception if there's a problem. You might like to use L<C<do>|/do EXPR>; } } =item dump LABEL X<dump> X<core> X<undump> =item dump EXPR =item dump =for Pod::Functions create an immediate core dump This function causes an immediate core dump. See also the B<-u> command-line switch in L<perlrun|perlrun/-u>, which does the same thing. Primarily this is so that you can use the B<undump> program (not supplied) to turn your core dump into an executable binary after having initialized all your variables at the beginning of the program. When the new binary is executed it will begin by executing a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL> suffers). Think of it as a goto with an intervening core dump and reincarnation. If C<LABEL> is omitted, restarts the program from the top. The C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be computed at run time, being otherwise identical to C<dump LABEL>. B<WARNING>: Any files opened at the time of the dump will I<not> be open any more when the program is reincarnated, with possible resulting confusion by Perl. This function is now largely obsolete, mostly because it's very hard to convert a core file into an executable. As of Perl 5.30, it must be invoked as C<CORE::dump()>. Unlike most named operators, this has the same precedence as assignment. It is also exempt from the looks-like-a-function rule, so C<dump ("foo")."bar"> will cause "bar" to be part of the argument to L<C<dump>|/dump LABEL>. Portability issues: L<perlport/dump>. =item each HASH X<each> X<hash, iterator> =item each ARRAY X<array, iterator> =for Pod::Functions retrieve the next key/value pair from a hash. After L<C<each>|/each HASH> has returned all entries from the hash or array, the next call to L<C<each>|/each HASH> returns the empty list in list context and L<C<undef>|/undef EXPR> in scalar context; the next call following I<that> one restarts iteration. Each hash or array has its own internal iterator, accessed by L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is implicitly reset when L<C<each>|/each HASH> has reached the end as just described; it can be explicitly reset by calling L<C<keys>|/keys HASH> or L<C<values>|/values HASH> L<C<each>|/each HASH>, so the following code works properly: while (my ($key, $value) = each %hash) { print $key, "\n"; delete $hash{$key}; # This is safe } Tied hashes may have a different ordering behaviour to perl's hash implementation. The iterator used by C<each> is attached to the hash or array, and is shared between all iteration operations applied to the same hash or array. Thus all uses of C<each> on a single hash or array advance the same iterator location. All uses of C<each> are also subject to having the iterator reset by any use of C<keys> or C<values> on the same hash or array, or by the hash (but not array) being referenced in list context. This makes C C<foreach> loop rather than C<while>-C<each>. This prints out your environment like the L<printenv(1)> program, but in a different order: while (my ($key,$value) = each %ENV) { print "$key=$value\n"; } Starting with Perl 5.14, an experimental feature allowed L<C<each>|/each HASH> to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24. As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration. If either an C<each> expression or an explicit assignment of an C<each> expression to a scalar is used as a C<while>/C use 5.018; # so each assigns to $_ in a lone while test See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and L<C<sort>|/sort SUBNAME LIST>. =item eof FILEHANDLE X<eof> X<end of file> X<end-of-file> =item eof () =item eof =for Pod::Functions test a filehandle for its end Returns 1 if the next read on FILEHANDLE will return end of file I<or> if FILEHANDLE is not open. FILEHANDLE may be an expression whose value gives the real filehandle. (Note that this function actually reads a character and then C<ungetc>s it, so isn't useful in an interactive context.) Do not read from a terminal file (or call C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such as terminals may lose the end-of-file condition if you do. An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is different. It refers to the pseudo file formed from the files listed on the command line and accessed via the C<< <> >> operator. Since C<< <> >> isn't explicitly opened, as a normal filehandle is, an L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >> has returned end-of-file will assume you are processing another L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see L<perlop/"I/O Operators">. In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)> can be used to detect the end of each file, whereas L<C<eof()>|/eof FILEHANDLE> L<C<eof>|/eof FILEHANDLE> in Perl, because the input operators typically return L<C<undef>|/undef EXPR> when they run out of data or encounter an error. =item eval EXPR X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> X<error, handling> X<exception, handling> =item eval BLOCK =item eval =for Pod::Functions catch exceptions or compile and run code C<eval> in all its forms is used to execute a little Perl program, trapping any errors encountered so they don't crash the calling program. Plain C<eval> with no argument is just C<eval EXPR>, where the expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus there are only two real C C<eval> executes. The other form is called "block eval". It is less general than string eval, but the code within the BLOCK is parsed only once (at the same time the code surrounding the C<eval> itself. See L<C<wantarray>|/wantarray> for more on how the evaluation context can be determined. If there is a syntax error or runtime error, or a L<C<die>|/die LIST> statement is executed, C<eval> returns L<C<undef>|/undef EXPR> in scalar context, or an empty list in list context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to 5.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list context for syntax errors, but not for runtime errors.) If there was no error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can bypass the setting of L<C<$@>|perlvar/$@>. Beware that using C<eval> neither silences Perl from printing warnings to STDERR, nor does it stuff the text of warning messages into L<C<$@>|perlvar/$@>. To do either of those, you have to use the L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside the BLOCK or EXPR using S<C<no warnings 'all'>>. See L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>. Note that, because C<eval> traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also Perl's exception-trapping mechanism, where the L<C<die>|/die LIST> operator is used to raise exceptions. Before Perl 5.14, the assignment to L<C<$@>|perlv: =over 4 =item String eval Since the return value of EXPR is executed as a block within the lexical context of the current Perl program, any outer lexical variables are visible to it, and any package variable settings or subroutine and format definitions remain afterwards. =over 4 =item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features> If this feature is enabled (which is the default under a C<use 5.16> or higher declaration), EXPR is considered to be in the same encoding as the surrounding program. Thus if S<L<C<use utf8> L<C<'unicode_strings"> feature|feature/The 'unicode_strings' feature> is in effect. In a plain C<eval> without an EXPR argument, being in S<C<use utf8>> or not is irrelevant; the UTF-8ness of C<$_> itself determines the behavior. Any S<C<use utf8>> or S<C<no utf8>> declarations within the string have no effect, and source filters are forbidden. (C<unicode_strings>, however, can appear within the string.) See also the L<C<evalbytes>|/evalbytes EXPR> operator, which works properly with source filters. Variables defined outside the C<eval> and used inside it retain their original UTF-8ness. Everything inside the string follows the normal rules for a Perl program with the given state of S<C<use utf8>>. =item Outside the C<"unicode_eval"> feature In this case, the behavior is problematic and is not so easily described. Here are two bugs that cannot easily be fixed without breaking existing programs: =over 4 =item * It can lose track of whether something should be encoded as UTF-8 or not. =item * Source filters activated within C<eval> leak out into whichever file scope is currently being compiled. To give an example with the CPAN module L<Semi::Semicolons>: BEGIN { eval "use Semi::Semicolons; # not filtered" } # filtered here! L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would expect: use feature "evalbytes"; BEGIN { evalbytes "use Semi::Semicolons; # filtered" } # not filtered =back =back Problems can arise if the string expands a scalar containing a floating point number. That scalar can expand to letters, such as C<"NaN"> or C<"Infinity">; or, within the scope of a L<C<use locale> C<'$x'>, which does nothing but return the value of $x. (Case 4 is preferred for purely visual reasons, but it also has the advantage of compiling at compile-time instead of at run-time.) Case 5 is a place where normally you I<would> like to use double quotes, except that in this particular situation, you can just use symbolic references instead, as in case 6. An C<eval ''> executed within a subroutine defined in the. =item Block eval If the code to be executed doesn't vary, you may use the eval-BLOCK form to trap run-time errors without incurring the penalty of recompiling each time. The error, if any, is still returned in L<C<$@>|perlv C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See L<perlrun|perlrun/PERL_DL_NONLAZY>. Using the C<eval {}> form as an exception trap in libraries does have some issues. Due to the current arguably broken state of C<__DIE__> hooks, you may wish not to trigger any C<__DIE__> hooks that user code may have installed. You can use the C<local $SIG{__DIE__}> construct for this purpose, as this example shows: # a private exception trap for divide-by-zero eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; warn $@ if $@; This is especially significant, given that C<__DIE__> hooks can call L<C<die>|/die LIST>. C<eval BLOCK> does I<not> count as a loop, so the loop control statements L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. The final semicolon, if any, may be omitted from within the BLOCK. =back =item evalbytes EXPR X<evalbytes> =item evalbytes =for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream This function is similar to a L<string eval|/eval EXPR>, except it always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted) as a string of independent bytes. If called when S<C<use utf8>> is in effect, the string will be assumed to be encoded in UTF-8, and C<evalbytes> will make a temporary copy to work from, downgraded to non-UTF-8. If this is not possible (because one or more characters in it require UTF-8), the C<evalbytes> will fail with the error stored in C<$@>. Bytes that correspond to ASCII-range code points will have their normal meanings for operators in the string. The treatment of the other bytes depends on if the L<C<'unicode_strings"> feature|feature/The 'unicode_strings' feature> is in effect. Of course, variables that are UTF-8 and are referred to in the string retain that: my $ feature|feature/The 'unicode_eval' and 'evalbytes' features> is enabled. This is enabled automatically with a C<use v5.16> (or higher) declaration in the current scope. =item exec LIST X<exec> X<execute> =item exec PROGRAM LIST =for Pod::Functions abandon this program to run another The L<C<exec>|/exec LIST> function executes a system command I<and never returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST> if you want it to return. It fails and returns false only if the command does not exist I<and> it is executed directly instead of via your system's command shell (see below). Since it's a common mistake to use L<C<exec>|/exec LIST> instead of L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is called in void context and if there is a following statement that isn't L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if L<warnings> are enabled--but you always do that, right?). If you I<really> want to follow an L<C<exec>|/exec LIST> with some other statement, you can use one of these styles to avoid the warning: exec ('foo') or print STDERR "couldn't exec foo: $!"; { exec ('foo') }; print STDERR "couldn't exec foo: $!"; If there is more than one argument in LIST, this calls L<execvp(3)> with the arguments in LIST. If there is only one element in LIST, L<perlop/"`STRING`"> for details. Using an indirect object with L<C<exec>|/exec LIST> or L<C<system>|/system LIST> is also more secure. This usage (which also works fine with L<C<system>|/system LIST>) I<echo> program, passing it C<"surprise"> an argument. The second version didn't; it tried to run a program named I<"echo surprise">, didn't find it, and set L<C<$?>|perlvar/$?> to a non-zero value indicating failure. On Windows, only the C<exec PROGRAM LIST> indirect object syntax will reliably avoid using the shell; C<exec LIST>, even with more than one element, will fall back to the shell if the first spawn fails. Perl attempts to flush all files opened for output before the exec, lost output. Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor will it invoke C<DESTROY> methods on your objects. Portability issues: L<perlport/exec>. =item exists EXPR X<exists> X<autovivification> =for Pod::Functions test whether a hash key is present Given L<C<delete>|/delete EXPR> on arrays. B<WARNING:> Calling L<C<exists>|/exists EXPR> C<AUTOLOAD> method that makes it spring into existence the first time that it is called; see L C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring into existence due to the existence test for the L<C<exists>|/exists EXPR> is an error. exists ⊂ # OK exists &sub(); # Error =item exit EXPR X<exit> X<terminate> X<abort> =item exit =for Pod::Functions terminate this program Evaluates EXPR and exits immediately with that value. Example: my $ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/; See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0> status. The only universally recognized values for EXPR are C<0> for success and C<1> for error; other values are subject to interpretation depending on the environment in which the Perl program is running. For example, exiting 69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause the mailer to return the item undelivered, but that's not true everywhere. Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use L<C<die>|/die LIST> instead, which can be trapped by an L<C<eval>|/eval EXPR>. The L<C<exit>|/exit EXPR> function does not always exit immediately. It calls any defined C<END> routines first, but these C<END> routines may not themselves abort the exit. Likewise any object destructors that need to be called are called before the real exit. C<END> routines and destructors can change the exit status by modifying L<C<$?>|perlvar/$?>. If this is a problem, you can call L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor processing. See L<perlmod> for details. Portability issues: L<perlport/exit>. =item exp EXPR X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> =item exp =for Pod::Functions raise I<e> to a power Returns I<e> (the natural logarithm base) to the power of EXPR. If EXPR is omitted, gives C<exp($_)>. =item fc EXPR X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> =item fc =for Pod::Functions +fc return casefolded version of a string Returns the casefolded version of EXPR. This is the internal function implementing the C<\F> escape in double-quoted strings. L<Unicode::UCD/B<casefold()>> and<>. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. This function behaves the same way under various pragmas, such as within L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>, as L<C<lc>|/lc EXPR> does, with the single exception of L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the scope of L<S<C<use locale>>|locale>. The foldcase of this character would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR> section, case changes that cross the 255/256 boundary are problematic under locales, and are hence prohibited. Therefore, this function under locale returns instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER LONG S>. Since that character itself folds to L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation. fcntl FILEHANDLE,FUNCTION,SCALAR X<fcntl> =for Pod::Functions file control system call Implements the L<fcntl(2)> function. You'll probably have to say use Fcntl; first to get the correct constant definitions. Argument processing and value returned work just like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> below. For example: use Fcntl; my $flags = fcntl($filehandle, F_GETFL, 0) or die "Can't fcntl F_GETFL: $!"; You don't have to check for L<C<defined>|/defined EXPR> on the return from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return from the system call into C<"0 but true"> in Perl. This string is true in boolean context and C<0> in numeric context. It is also exempt from the normal L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> L<warnings> on improper numeric conversions. Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an exception if used on a machine that doesn't implement L<fcntl(2)>. See the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions are available on your system. Here's an example of setting a filehandle named C<$REMOTE> to be non-blocking at the system level. You'll have to negotiate L<C<$E<verbar>>|perlvar/$E<verbar>>: L<perlport/fcntl>. =item __FILE__ X<__FILE__> =for Pod::Functions the name of the current source file A special token that returns the name of the file in which it occurs. It can be altered by the mechanism described at L<perlsyn/"Plain Old Comments (Not!)">. =item fileno FILEHANDLE X<fileno> =item fileno DIRHANDLE =for Pod::Functions return file descriptor from filehandle Returns the file descriptor for a filehandle or directory handle, or undefined if the filehandle is not open. If there is no real file descriptor at the OS level, as can happen with filehandles connected to memory objects via L<C<open>|/open FILEHANDLE,MODE,EXPR> with a reference for the third argument, -1 is returned. This is mainly useful for constructing bitmaps for L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> L<C<fileno>|/fileno FILEHANDLE> on a directory handle depends on the operating system. On a system with L<dirfd(3)> or similar, L<C<fileno>|/fileno FILEHANDLE> on a directory handle returns the underlying file descriptor associated with the handle; on systems with no such support, it returns the undefined value, and sets L<C<$!>|perlvar/$!> (errno). =item flock FILEHANDLE,OPERATION X<flock> X<lock> X<locking> =for Pod::Functions lock an entire file with an advisory lock Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true for success, false on failure. Produces a fatal error if used on a machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable file-locking interface, although it locks entire files only, not records. Two potentially non-obvious but traditional L<C<flock>|/flock FILEHANDLE,OPERATION> semantics are that it waits indefinitely until the lock is granted, and that its locks are B<merely advisory>. Such discretionary locks are more flexible, but offer fewer guarantees. This means that programs that do not also use L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with L<C<flock>|/flock FILEHANDLE,OPERATION>. See L L<Fcntl> module, either individually, or as a group using the C<:flock> tag. LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a previously requested lock. If LOCK_NB is bitwise-or'ed with LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns immediately rather than blocking waiting for the lock; check the return status to see if you got it. To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE before locking or unlocking it. Note that the emulation built with L<lockf(3)> doesn't provide shared locks, and it requires that FILEHANDLE be open with write intent. These are the semantics that L<lockf(3)> implements. Most if not all systems implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the differing semantics shouldn't bite too many people. Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE be open with read intent to use LOCK_SH and requires that it be open with write intent to use LOCK_EX. Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION> cannot lock things over the network; you would need to use the more system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for that. If you like you can force Perl to ignore your system's L<flock(2)> function, and so provide its own L<fcntl(2)>-based emulation, by passing the switch C<-Ud_flock> to the we're running on a very old UNIX # variant without the modern O_APPEND semantics... L<flock(2)>, locks are inherited across L<C<fork>|/fork> calls, whereas those that must resort to the more capricious L<fcntl(2)> function lose their locks, making it seriously harder to write servers. See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION> examples. Portability issues: L<perlport/flock>. =item fork X<fork> X<child> X<parent> =for Pod::Functions create a new process just like this one Does a L<fork(2)> system call to create a new process running the same program at the same point. It returns the child pid to the parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if the fork is unsuccessful. File descriptors (and sometimes locks on those descriptors) are shared, while everything else is copied. On most systems supporting L duplicate output. If you L<C<fork>|/fork> without ever waiting on your children, you will accumulate zombies. On some systems, you can avoid this by setting L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L F</dev/null> if it's any issue. On some platforms such as Windows, where the L<fork(2)> system call is not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl interpreter. The emulation is designed, at the level of the Perl program, to be as compatible as possible with the "Unix" L<fork(2)>. However it has limitations that have to be considered in code intended to be portable. See L<perlfork> for more details. Portability issues: L<perlport/fork>. =item format X<format> =for Pod::Functions declare a picture format with use by the write() function Declare a picture format for use by the L<C<write>|/write FILEHANDLE> function. For example: format Something = Test: @<<<<<<<< @||||| @>>>>> $str, $%, '$' . int($num) . $. Note that a format typically does one L<C<formline>|/formline PICTURE,LIST> per line of form, but the L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how many newlines are embedded in the PICTURE. This means that the C<~> and C<~~> tokens treat the entire PICTURE as a single line. You may therefore need to use multiple formlines to implement a single record format, just like the L<C<format>|/format> compiler. Be careful if you put double quotes around the picture, because an C<@> character may be taken to mean the beginning of an array name. L<C<formline>|/formline PICTURE,LIST> always returns true. See L<perlform> for other examples. If you are trying to use this instead of L<C<write>|/write FILEHANDLE> to capture the output, you may find it easier to open a filehandle to a scalar (C<< open my $fh, ">", \$output >>) and write to that instead. =item getc FILEHANDLE X<getc> X<getchar> X<character> X<file, read> =item getc =for Pod::Functions get the next character from the filehandle Returns the next character from the input file attached to FILEHANDLE, or the undefined value at end of file or if there was an error (in the latter case L<C<$!>|perlvar/$!> C<$BSD_STYLE> should be set is left as an exercise to the reader. The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more portably on systems purporting POSIX compliance. See also the L<C<Term::ReadKey>|Term::ReadKey> module on CPAN. =item getlogin X<getlogin> X<login> =for Pod::Functions return who logged in at this tty This implements the C library function of the same name, which on most systems returns the current login from F</etc/utmp>, if any. If it returns the empty string, use L<C<getpwuid>|/getpwuid UID>. my $login = getlogin || getpwuid($<) || "Kilroy"; Do not consider L<C<getlogin>|/getlogin> for authentication: it is not as secure as L<C<getpwuid>|/getpwuid UID>. Portability issues: L<perlport/getlogin>. =item getpeername SOCKET X<getpeername> X<peer> =for Pod::Functions find the other end of a socket connection Returns the packed sockaddr address of the other end of the SOCKET connection. use Socket; my $hersockaddr = getpeername($sock); my ($port, $iaddr) = sockaddr_in($hersockaddr); my $herhostname = gethostbyaddr($iaddr, AF_INET); my $herstraddr = inet_ntoa($iaddr); =item getpgrp PID X<getpgrp> X<group> =for Pod::Functions get process group Returns the current process group for the specified PID. Use a PID of C<0> to get the current process group for the current process. Will raise an exception if used on a machine that doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process group of the current process. Note that the POSIX version of L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only C<PID==0> is truly portable. Portability issues: L<perlport/getpgrp>. =item getppid X<getppid> X<parent> X<pid> =for Pod::Functions get parent process ID Returns L<$$|perlvar/$$> for details. Portability issues: L<perlport/getppid>. =item getpriority WHICH,WHO X<getpriority> X<priority> X<nice> =for Pod::Functions get current nice value Returns the current priority for a process, a process group, or a user. (See L<getpriority(2)>.) Will raise a fatal exception if used on a machine that doesn't implement L<getpriority(2)>. C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> imported from L<POSIX/RESOURCE CONSTANTS>. Portability issues: L<perlport/getpriority>. =item getpwnam NAME X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> X<endnetent> X<endprotoent> X<endservent> =for Pod::Functions get passwd record given user login name =item getgrnam NAME =for Pod::Functions get group record given group name =item gethostbyname NAME =for Pod::Functions get host record given name =item getnetbyname NAME =for Pod::Functions get networks record given name =item getprotobyname NAME =for Pod::Functions get protocol record given name =item getpwuid UID =for Pod::Functions get passwd record given user ID =item getgrgid GID =for Pod::Functions get group record given group user ID =item getservbyname NAME,PROTO =for Pod::Functions get services record given its name =item gethostbyaddr ADDR,ADDRTYPE =for Pod::Functions get host record given its address =item getnetbyaddr ADDR,ADDRTYPE =for Pod::Functions get network record given its address =item getprotobynumber NUMBER =for Pod::Functions get protocol record numeric protocol =item getservbyport PORT,PROTO =for Pod::Functions get services record given numeric port =item getpwent =for Pod::Functions get next passwd record =item getgrent =for Pod::Functions get next group record =item gethostent =for Pod::Functions get next hosts record =item getnetent =for Pod::Functions get next networks record =item getprotoent =for Pod::Functions get next protocols record =item getservent =for Pod::Functions get next services record =item setpwent =for Pod::Functions prepare passwd file for use =item setgrent =for Pod::Functions prepare group file for use =item sethostent STAYOPEN =for Pod::Functions prepare hosts file for use =item setnetent STAYOPEN =for Pod::Functions prepare networks file for use =item setprotoent STAYOPEN =for Pod::Functions prepare protocols file for use =item setservent STAYOPEN =for Pod::Functions prepare services file for use =item endpwent =for Pod::Functions be done using passwd file =item endgrent =for Pod::Functions be done using group file =item endhostent =for Pod::Functions be done using hosts file =item endnetent =for Pod::Functions be done using networks file =item endprotoent =for Pod::Functions be done using protocols file =item endservent =for Pod::Functions be done using services file These routines are the same as their counterparts in the system C library. In list context, the return values from the various get routines are as follows: # L I L<getpwnam(3)> and your system's F<pwd.h> file. You can also find out from within Perl what your $quota and $comment fields mean and whether you have the $expire field by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>, C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password files are supported only if your vendor has implemented them in the intuitive fashion that calling the regular C library routines gets the shadow versions if you're running under privilege or if there exists the L<shadow(3)> functions as found in System V (this includes Solaris and Linux). Those systems that implement a proprietary shadow password facility are unlikely to be supported. The $members value returned by I<getgr*()> is a space-separated list of the login names of the members of the group. For the I<gethost*()> functions, if the C<h_errno> variable is supported in C, it will be returned to you via L<C<$?>|perlvar/$?> if the function call fails. The L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR context and that its return value is checked for definedness. The L<C<getprotobynumber>|/getprotobynumber NUMBER>: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>, L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>, L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>, L<C<Time::localtime>|Time::localtime>, and L<C<User::grent> C<File::stat> object is different from a C<User::pwent> object. Many of these functions are not safe in a multi-threaded environment where more than one thread can be using them. In particular, functions like C<getpwent()> iterate per-process and not per-thread, so if two threads are simultaneously iterating, neither will get all the records. Some systems have thread-safe versions of some of the functions, such as C<getpwnam_r()> instead of C<getpwnam()>. There, Perl automatically and invisibly substitutes the thread-safe version, without notice. This means that code that safely runs on some systems can fail on others that lack the thread-safe versions. Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. =item getsockname SOCKET X<getsockname> =for Pod::Functions retrieve the sockaddr for a given socket Returns the packed sockaddr address of this end of the SOCKET connection, in case you don't know the address because you have several different IPs that the connection might have come in on. use Socket; my $mysockaddr = getsockname($sock); my ($port, $myaddr) = sockaddr_in($mysockaddr); printf "Connect to %s [%s]\n", scalar gethostbyaddr($myaddr, AF_INET), inet_ntoa($myaddr); =item getsockopt SOCKET,LEVEL,OPTNAME X<getsockopt> =for Pod::Functions get socket options on a given socket Queries the option named OPTNAME associated with SOCKET at a given LEVEL. Options may exist at multiple protocol levels depending on the socket type, but at least the uppermost socket level SOL_SOCKET (defined in the L<C<Socket> L<C<getprotobyname>|/getprotobyname NAME>. The function returns a packed string representing the requested socket option, or L<C<undef>|/undef EXPR> on error, with the reason for the error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A common case is that the option is an integer, in which case the result is a packed integer, which you can decode using L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or: L<perlport/getsockopt>. =item glob EXPR X<glob> X<wildcard> X<filename, expansion> X<expand> =item glob =for Pod::Functions expand filenames using wildcards In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell F</bin/csh> would do. In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. This is the internal function implementing the C<< <*.c> >> operator, but you can use it directly. If EXPR is omitted, L<C<$_>|perlvar/$_> is used. The C<< <*.c> >> operator is discussed in more detail in L<perlop/"I/O Operators">. Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and treats each segment as separate pattern. As such, C<glob("*.c *.h")> matches all files with a F<.c> or F<.h> extension. The expression C<glob(".* *")> matches all files in the current working directory. If you want to glob filenames that might contain whitespace, you'll have to use extra quotes around the spacey filename to protect it. For example, to glob filenames that have an C<e> followed by a space followed by an L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors: my @many = glob "{apple,tomato,cherry}={green,yellow,red}"; This operator is implemented using the standard C<File::Glob> extension. See L<File::Glob> for details, including L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace as a pattern separator. If a C<glob> expression is used as the condition of a C<while> or C<for> loop, then it will be implicitly assigned to C<$_>. If either a C<glob> expression or an explicit assignment of a C<glob> expression to a scalar is used as a C<while>/C<for> condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value. Portability issues: L<perlport/glob>. =item gmtime EXPR X<gmtime> X<UTC> X<Greenwich> =item gmtime =for Pod::Functions convert UNIX time into record or string using Greenwich time Works just like L<C<localtime>|/localtime EXPR> but the returned values are localized for the standard Greenwich time zone. Note: When called in list context, $isdst, the last value returned by gmtime, is always C<0>. There is no Daylight Saving Time in GMT. Portability issues: L<perlport/gmtime>. =item goto LABEL X<goto> X<jump> X<jmp> =item goto EXPR =item goto &NAME =for Pod::Functions create spaghetti code The C<goto LABEL> form finds the statement labeled with LABEL and resumes execution there. It can't be used to get out of a block or subroutine given to L<C<sort>|/sort SUBNAME LIST>. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as L<C<last>|/last LABEL> or L<C<die>|/die LIST>. The author of Perl has never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl, that is; C is another matter). (The difference is that C does not offer named loops combined with loop control. Perl does, and this replaces most structured uses of L<C<goto>|/goto LABEL> in other languages.) The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or a label name. If it evaluates to a code reference, it will be handled like C<goto &NAME>, below. This is especially useful for implementing tail recursion via C<goto __SUB__>. If the expression evaluates to a label name, its scope will be resolved dynamically. This allows for computed L<C<goto>|/goto LABEL>s per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability: goto ("FOO", "BAR", "GLARCH")[$i]; As shown in this example, C<goto EXPR> is exempt from the "looks like a function" rule. A pair of parentheses following it does not (necessarily) delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. Also, unlike most named operators, this has the same precedence as assignment. Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is deprecated and will issue a warning. Even then, it may not be used to go into any construct that requires initialization, such as a subroutine, a C<foreach> loop, or a C<given> block. In general, it may not be used to jump into the parameter of a binary or list operator, but it may be used to jump into the I<first> parameter of a binary operator. (The C<=> assignment operator's "first" operand is its right-hand operand.) It also can't be used to go into a construct that is optimized away. The C<goto &NAME> form is quite different from the other forms of L<C<goto>|/goto LABEL>. In fact, it isn't a goto in the normal sense at all, and doesn't have the stigma associated with other gotos. Instead, it exits the current subroutine (losing any changes set by L<C<local>|/local EXPR>) and immediately calls in its place the named subroutine using the current value of L<C<@_>|perlvar/@_>. This is used by C<AUTOLOAD> subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to L<C<@_>|perlvar/@_> in the current subroutine are propagated to the other subroutine.) After the L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able to tell that this routine was called first. NAME needn't be the name of a subroutine; it can be a scalar variable containing a code reference or a block that evaluates to a code reference. =item grep BLOCK LIST X<grep> =item grep EXPR,LIST =for Pod::Functions locate elements in a list test true against a given criterion This is similar in spirit to, but not the same as, L<grep(1)> and its relatives. In particular, it is not limited to using regular expressions. Evaluates the BLOCK or EXPR for each element of LIST (locally setting L<C<$_>|perlvar/$_> L<C<$_>|perlv C<foreach>, L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>) actually modifies the element in the original list. This is usually something to be avoided when writing clear code. See also L<C<map>|/map BLOCK LIST> for a list composed of the results of the BLOCK or EXPR. =item hex EXPR X<hex> X<hexadecimal> =item hex =for Pod::Functions convert a hexadecimal string to a number Interprets EXPR as a hex string and returns the corresponding numeric value. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. print hex '0xAf'; # prints '175' print hex 'aF'; # same $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/ A hex string consists of hex digits and an optional C<0x> or C<x> prefix. Each hex digit may be preceded by a single underscore, which will be ignored. Any other character triggers a warning and causes the rest of the string to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>). Only integers can be represented, and integer overflow triggers a warning. To convert strings that might start with any of C<0>, C<0x>, or C<0b>, see L<C<oct>|/oct EXPR>. To present something as hex, look into L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, L<C<sprintf>|/sprintf FORMAT, LIST>, and L<C<unpack>|/unpack TEMPLATE,EXPR>. =item import LIST X<import> =for Pod::Functions patch a module's namespace into your own There is no builtin L<C<import>|/import LIST> function. It is just an ordinary method (subroutine) defined (or inherited) by modules that wish to export names to another module. The L<C<use>|/use Module VERSION LIST> function calls the L<C<import>|/import LIST> method for the package used. See also L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>. =item index STR,SUBSTR,POSITION X<index> X<indexOf> X<InStr> =item index STR,SUBSTR =for Pod::Functions find a substring within a string, L<C<index>|/index STR,SUBSTR,POSITION> returns -1. =item int EXPR X<int> X<integer> X<truncate> X<trunc> X<floor> =item int =for Pod::Functions get the integer portion of a number Returns the integer portion of EXPR. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. You should not use this function for rounding: one because it truncates towards C<0>, and two because machine representations of floating-point numbers can sometimes produce counterintuitive results. For example, C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's because it's really more like -268.99999999999994315658 instead. Usually, the L<C<sprintf>|/sprintf FORMAT, LIST>, L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>> functions will serve you better than will L<C<int>|/int EXPR>. =item ioctl FILEHANDLE,FUNCTION,SCALAR X<ioctl> =for Pod::Functions system-dependent device control system call Implements the L<ioctl(2)> function. You'll probably first have to say require "sys/ioctl.ph"; # probably in # $Config{archlib}/sys/ioctl.ph to get the correct function definitions. If F<sys/ioctl.ph> doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as F<< <sys/ioctl.h> >>. (There is a Perl script called B L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call. (If SCALAR has no string value but does have a numeric value, that value will be passed rather than a pointer to the string value. To guarantee this to be true, add a C<0> to the scalar before using it.) The L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> functions may be needed to manipulate the values of structures used by L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>. The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) C<"0 but true"> is exempt from L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> L<warnings> on improper numeric conversions. Portability issues: L<perlport/ioctl>. =item join EXPR,LIST X<join> =for Pod::Functions join a list into a string using a separator Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns that new string. Example: my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument. Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>. =item keys HASH X<keys> X<key> =item keys ARRAY =for Pod::Functions retrieve list of indices from a hash Called<keys>|/keys HASH> resets the internal iterator of the HASH or ARRAY (see L<C<each>|/each HASH>) before yielding the keys. In particular, calling L<C<keys>|/keys HASH> L<C<values>|/values HASH>. To sort a hash by value, you'll need to use a L<C<sort>|/sort SUBNAME LIST> function. Here's a descending numeric sort of a hash by its values: foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { printf "%4d %s\n", $hash{$key}, $key; } Used as an lvalue, L<C<keys>|/keys HASH>--256 of them, in fact, since it rounds up to the next power of two. These buckets will be retained even if you do C<%hash = ()>, use C<undef %hash> if you want to free the storage while C<%hash> is still in scope. You can't shrink the number of buckets allocated for the hash using L<C<keys>|/keys HASH> in this way (but you needn't worry about doing this by accident, as trying has no effect). C<keys @array> in an lvalue context is a syntax error. Starting with Perl 5.14, an experimental feature allowed L<C<keys>|/keys<each>|/each HASH>, L<C<values>|/values HASH>, and L<C<sort>|/sort SUBNAME LIST>. =item kill SIGNAL, LIST =item kill SIGNAL X<kill> X<signal> =for Pod::Functions send a signal to a process or process group Sends C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the same signal. The string form of SIGNAL is recommended for portability because the same signal may have different numbers in different operating systems. A list of signal names supported by the current platform can be found in C<$Config{sig_name}>, which is provided by the L<C<Config>|Config> module. See L<Config> for more details. A negative signal name is the same as a negative signal number, killing process groups instead of processes. For example, C<kill '-KILL', $pgrp> and C<kill -9, $pgrp> will send C<SIGKILL> to the entire process group specified. That means you usually want to use positive not negative signals. If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>), no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST> checks whether it's I L<perlport> for notes on the portability of this construct. The behavior of kill when a I L<perlipc/"Signals"> for more details. On some platforms such as Windows where the L<fork(2)> system call is not available, Perl can be built to emulate L<C<fork>|/fork> at the interpreter level. This emulation has limitations related to kill that have to be considered, for code running on Windows and in code intended to be portable. See L<perlfork> for more details. If there is no I<LIST> of processes, no signal is sent, and the return value is 0. This form is sometimes used, however, because it causes tainting checks to be run. But see L<perlsec/Laundering and Detecting Tainted Data>. Portability issues: L<perlport/kill>. =item last LABEL X<last> X<break> =item last EXPR =item last =for Pod::Functions exit a block prematurely The L<C<last>|/last LABEL> command is like the C<break> statement in C (as used in loops); it immediately exits the loop in question. If the LABEL is omitted, the command refers to the innermost enclosing loop. The C<last EXPR> form, available starting in Perl 5.18.0, allows a label name to be computed at run time, and is otherwise identical to C<last LABEL>. The L<C<continue>|/continue BLOCK> block, if any, is not executed: LINE: while (<STDIN>) { last LINE if /^$/; # exit when done with header #... } L<C<last>|/last<last>|/last LABEL> can be used to effect an early exit out of such a block.<last ("foo")."bar"> will cause "bar" to be part of the argument to L<C<last>|/last LABEL>. =item lc EXPR X<lc> X<lowercase> =item lc =for Pod::Functions return lower-case version of a string Returns a lowercased version of EXPR. This is the internal function implementing the C<\L> escape in double-quoted strings. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. What gets returned depends on several factors: =over =item If C<use bytes> is in effect: The results follow ASCII rules. Only the characters C<A-Z> change, to C<a-z> respectively. =item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect: Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode rules for the remaining code points (this last can only happen if the UTF8 flag is also set). See L C L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning. =item Otherwise, If EXPR has the UTF8 flag set: Unicode rules are used for the case change. =item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect: Unicode rules are used for the case change. =item Otherwise: ASCII rules are used for the case change. The lowercase of any character outside the ASCII range is the character itself. =back =item lcfirst EXPR X<lcfirst> X<lowercase> =item lcfirst =for Pod::Functions return a string with just the next letter in lower case Returns the value of EXPR with the first character lowercased. This is the internal function implementing the C<\l> escape in double-quoted strings. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. This function behaves the same way under various pragmas, such as in a locale, as L<C<lc>|/lc EXPR> does. =item length EXPR X<length> X<size> =item length =for Pod::Functions return the number of characters in a string Returns the length in I<characters> of the value of EXPR. If EXPR is omitted, returns the length of L<C<$_>|perlvar/$_>. If EXPR is undefined, returns L<C<undef>|/undef EXPR>. This function cannot be used on an entire array or hash to find out how many elements these have. For that, use C<scalar @array> and C<scalar keys %hash>, respectively. Like all Perl character operations, L<C<length>|/length EXPR> normally deals in logical characters, not physical bytes. For how many bytes a string encoded as UTF-8 would take up, use C<length(Encode::encode('UTF-8', EXPR))> (you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. =item __LINE__ X<__LINE__> =for Pod::Functions the current source line number A special token that compiles to the current line number. It can be altered by the mechanism described at L<perlsyn/"Plain Old Comments (Not!)">. =item link OLDFILE,NEWFILE X<link> =for Pod::Functions create a hard link in the filesystem Creates a new filename linked to the old filename. Returns true for success, false otherwise. Portability issues: L<perlport/link>. =item listen SOCKET,QUEUESIZE X<listen> =for Pod::Functions register your socket as a server Does the same thing that the L<listen(2)> system call does. Returns true if it succeeded, false otherwise. See the example in L<perlipc/"Sockets: Client/Server Communication">. =item local EXPR X<local> =for Pod::Functions create a temporary value for a global variable (dynamic scoping) You really probably want to be using L<C<my>|/my VARLIST> instead, because L<C<local>|/local EXPR> isn't what most people think of as "local". See L<perlsub/"Private Variables via my()"> for details. A local modifies the listed variables to be local to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses. See L<perlsub/"Temporary Values via local()"> for details, including issues with tied arrays and hashes. The C<delete local EXPR> construct can also be used to localize the deletion of array/hash elements to the current block. See L<perlsub/"Localized deletion of elements of composite types">. =item localtime EXPR X<localtime> X<ctime> =item localtime =for Pod::Functions convert UNIX time into record or string using local time Converts'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours of the specified time. C<$mday> is the day of the month and C<$mon> the month in the range C" C<$year> contains the number of years since 1900. To get a 4-digit year write: $year += 1900; To get the last two digits of the year (e.g., "01" in 2001) do: $year = sprintf("%02d", $year % 100); C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating Wednesday. C<$yday> is the day of the year, in the range C<0..364> (or C<0..365> in leap years.) C<$isdst> is true if the specified time occurs during Daylight Saving Time, false otherwise. If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current time (as returned by L<C<time>|/time>). In scalar context, L<C<localtime>|/localtime EXPR> returns the L<ctime(3)> value: my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" The format of this scalar value is B<not> locale-dependent but built into Perl. For GMT instead of local time use the L<C<gmtime>|/gmtime EXPR> builtin. See also the L<C<Time::Local>|Time::Local> module (for converting seconds, minutes, hours, and such back to the integer value returned by L<C<time>|/time>), and the L<POSIX> module's L<C<strftime>|POSIX/C<strftime>> and L<C<mktime>|POSIX/C<mktime>> functions. To get somewhat similar but locale-dependent date strings, set up your locale environment variables appropriately (please see L C<%a> and C<%b>, the short forms of the day of the week and the month of the year, may not necessarily be three characters wide. The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR> functions, respectively. For a comprehensive date and time representation look at the L<DateTime> module on CPAN. Portability issues: L<perlport/localtime>. =item lock THING X<lock> =for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method This function places an advisory lock on a shared variable or referenced object contained in I<THING> until the lock goes out of scope. The value returned is the scalar itself, if the argument is a scalar, or a reference, if the argument is a hash, array or subroutine. L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've defined a function by this name (before any calls to it), that function will be called instead. If you are not under C<use threads::shared> this does nothing. See L<threads::shared>. =item log EXPR X<log> X<logarithm> X<e> X<ln> X<base> =item log =for Pod::Functions retrieve the natural logarithm for a number Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, returns the log of L<C<$_>|perlvar/$_>. To get the log of another base, use basic algebra: The base-N log of a number is equal to the natural log of that number divided by the natural log of N. For example: sub log10 { my $n = shift; return log($n)/log(10); } See also L<C<exp>|/exp EXPR> for the inverse operation. =item lstat FILEHANDLE X<lstat> =item lstat EXPR =item lstat DIRHANDLE =item lstat =for Pod::Functions stat a symbolic link Does the same thing as the L<C<stat>|/stat FILEHANDLE> function (including setting the special C<_> filehandle) but stats a symbolic link instead of the file the symbolic link points to. If symbolic links are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE> is done. For much more detailed information, please see the documentation for L<C<stat>|/stat FILEHANDLE>. If EXPR is omitted, stats L<C<$_>|perlvar/$_>. Portability issues: L<perlport/lstat>. =item m// =for Pod::Functions match a string with a regular expression pattern The match operator. See L<perlop/"Regexp Quote-Like Operators">. =item map BLOCK LIST X<map> =item map EXPR,LIST =for Pod::Functions apply a change to a list to get back a new list with the changes Evaluates the BLOCK or EXPR for each element of LIST (locally setting L<C<$_>|perlvar/$_> L<perldata> for more details. my %hash = map { get_a_key_for($_) => $_ } @array; is just a funny way to write my %hash; foreach (@array) { $hash{get_a_key_for($_)} = $_; } Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Using a regular C<foreach> loop for this purpose would be clearer in most cases. See also L<C<grep>|/grep BLOCK LIST> for a list composed of those items of the original list for which the BLOCK or EXPR evaluates to true. C<{> starts both hash references and blocks, so C<map { ...> could be either the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look ahead for the closing C<}> it has to take a guess at which it's dealing with based on what it finds just after the C<{>. Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the C<}> and encounters the missing (or unexpected) comma. The syntax error will be reported close to the C<}>, but you'll need to change something near the C<{> such as using a unary C<+> C<+{>: my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs # comma at end to get a list of anonymous hashes each with only one entry apiece. =item mkdir FILENAME,MODE X<mkdir> X<md> X<directory, create> =item mkdir FILENAME =item mkdir =for Pod::Functions create a directory Creates the directory specified by FILENAME, with permissions specified by MODE (as modified by L<C<umask>|/umask EXPR>). If it succeeds it returns true; otherwise it returns false and sets L<C<$!>|perlvar/$!> (errno). MODE defaults to 0777 if omitted, and FILENAME defaults to L<C<$_>|perlvar/$_> if omitted. In general, it is better to create directories with a permissive MODE and let the user modify that with their L<C<umask>|/umask EXPR> than it is to supply a restrictive MODE and give the user no way to be more permissive. The exceptions to this rule are when the file or directory should be kept private (mail files, for instance). The documentation for L<C<umask>|/umask EXPR> discusses the choice of MODE L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function of the L<File::Path> module. =item msgctl ID,CMD,ARG X<msgctl> =for Pod::Functions SysV IPC message control operations Calls the System V IPC function L<msgctl(2)>. You'll probably have to say use IPC::SysV; first to get the correct constant definitions. If CMD is C<IPC_STAT>, then ARG must be a variable that will hold the returned C<msqid_ds> structure. Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: the undefined value for error, C<"0 but true"> for zero, or the actual return value otherwise. See also L<perlipc/"SysV IPC"> and the documentation for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. Portability issues: L<perlport/msgctl>. =item msgget KEY,FLAGS X<msgget> =for Pod::Functions get SysV IPC message queue Calls the System V IPC function L<msgget(2)>. Returns the message queue id, or L<C<undef>|/undef EXPR> on error. See also L<perlipc/"SysV IPC"> and the documentation for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. Portability issues: L<perlport/msgget>. =item msgrcv ID,VAR,SIZE,TYPE,FLAGS X<msgrcv> =for Pod::Functions receive a SysV IPC message from a message queue Calls C<unpack("l! a*")>. Taints the variable. Returns true if successful, false on error. See also L<perlipc/"SysV IPC"> and the documentation for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. Portability issues: L<perlport/msgrcv>. =item msgsnd ID,MSG,FLAGS X<msgsnd> =for Pod::Functions send a SysV IPC message to a message queue C<pack("l! a*", $type, $message)>. Returns true if successful, false on error. See also L<perlipc/"SysV IPC"> and the documentation for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. Portability issues: L<perlport/msgsnd>. =item my VARLIST X<my> =item my TYPE VARLIST =item my VARLIST : ATTRS =item my TYPE VARLIST : ATTRS =for Pod::Functions declare and assign a local variable (lexical scoping) A L<C<my>|/my VARLIST> declares the listed variables to be local (lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>. If more than one variable is listed, the list must be placed in parentheses. The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE may be a bareword, a constant declared with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>. It: my ( undef, $min, $hour ) = localtime; =item next LABEL X<next> X<continue> =item next EXPR =item next =for Pod::Functions iterate a block prematurely The L<C<next>|/next LABEL> command is like the C<continue> statement in C; it starts the next iteration of the loop: LINE: while (<STDIN>) { next LINE if /^#/; # discard comments #... } Note that if there were a L<C<continue>|/continue BLOCK> block on the above, it would get executed even on discarded lines. If LABEL is omitted, the command refers to the innermost enclosing loop. The C<next EXPR> form, available as of Perl 5.18.0, allows a label name to be computed at run time, being otherwise identical to C<next LABEL>. L<C<next>|/next<next>|/next LABEL> will exit such a block early.<next ("foo")."bar"> will cause "bar" to be part of the argument to L<C<next>|/next LABEL>. =item no MODULE VERSION LIST X<no declarations> X<unimporting> =item no MODULE VERSION =item no MODULE LIST =item no MODULE =item no VERSION =for Pod::Functions unimport some module symbols or semantics at compile time See the L<C<use>|/use Module VERSION LIST> function, of which L<C<no>|/no MODULE VERSION LIST> is the opposite. =item oct EXPR X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> =item oct =for Pod::Functions convert a string to an octal number Interprets EXPR as an octal string and returns the corresponding value. (If EXPR happens to start off with C<0x>, interprets it as a hex string. If EXPR starts off with C<0b>, it is interpreted as a binary string. Leading whitespace is ignored in all three cases.) The following will handle decimal, binary, octal, and hex in standard Perl notation: $val = oct($val) if $val =~ /^0/; If EXPR is omitted, uses L<C<$_>|perlvar/$_>. To go the other way (produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or L<C<printf>|/printf FILEHANDLE FORMAT, LIST>: my $dec_perms = (stat("filename"))[2] & 07777; my $oct_perm_str = sprintf "%o", $perms; The L<C<oct>|/oct EXPR> function is commonly used when a string such as C<644> needs to be converted into a file mode, for example. Although Perl automatically converts strings into numbers as needed, this automatic conversion assumes base 10. Leading white space is ignored without warning, as too are any trailing non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles non-negative integers, not negative integers or floating point). =item open FILEHANDLE,MODE,EXPR X<open> X<pipe> X<file, open> X<fopen> =item open FILEHANDLE,MODE,EXPR,LIST =item open FILEHANDLE,MODE,REFERENCE =item open FILEHANDLE,EXPR =item open FILEHANDLE =for Pod::Functions open a file, pipe, or descriptor Associates C<open> follows. For a gentler introduction to the basics of C<open>, see also the L<perlopentut> manual page. =over =item Working with files Most often, C<open> gets invoked with three arguments: the required FILEHANDLE (usually an empty scalar variable), followed by MODE (usually a literal describing the I/O mode the filehandle will use), and then the filename that the new filehandle will refer to. =over =item Simple examples L<perlintro/Files and I/O>. =item About filehandles The first argument to C<open>, labeled FILEHANDLE in this reference, is usually a scalar variable. (Exceptions exist, described in "Other considerations", below.) If the call to C<open> succeeds, then the expression provided as FILEHANDLE will get assigned an open I<filehandle>. That filehandle provides an internal reference to the specified external file, conveniently stored in a Perl variable, and ready for I/O operations such as reading and writing. =item About modes When calling C<open> with three or more arguments, the second argument -- labeled MODE here -- defines the I<open mode>. MODE is usually a literal string comprising special characters that define the intended I/O role of the filehandle being created: whether it's read-only, or read-and-write, and so on. If MODE is C<< < >>, the file is opened for input (read-only). If MODE is C<< > >>, the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is C<<< >> >>>, the file is opened for appending, again being created if necessary. You can put a C<+> in front of the C<< > >> or C<< < >> to indicate that you want both read and write access to the file; thus C<< +< >> is almost always preferred for read/write updates--the C<< +> >> mode would clobber the file first. You can't usually use either read-write mode for updating textfiles, since they have variable-length records. See the B<-i> switch in L<perlrun|perlrun/-i[extension]> for a better approach. The file is created with permissions of C<0666> modified by the process's L<C<umask>|/umask EXPR> value. These various prefixes correspond to the L<fopen(3)> modes of C<r>, C<r+>, C<w>, C<w+>, C<a>, and C<a+>.: $!"; =item Checking the return value Open returns nonzero on success, the undefined value otherwise. If the C<open> involved a pipe, the return value happens to be the pid of the subprocess. When opening a file, it's seldom a good idea to continue if the request failed, so C<open> is frequently used with L<C<die>|/die LIST>. Even if you want your code to do something other than C<die> on a failed open, you should still always check the return value from opening a file. =back =item Specifying I/O layers in MODE You can use the three-argument form of open to specify I/O layers (sometimes referred to as "disciplines") to apply to the new filehandle. These affect how the input and output are processed (see L<open> and L<PerlIO> for more details). For example: open(my $fh, "<:encoding(UTF-8)", $filename) || die "Can't open UTF-8 encoded $filename: $!"; This opens the UTF8-encoded file containing Unicode characters; see L<perluniintro>. Note that if layers are specified in the three-argument form, then default layers stored in L<C<${^OPEN}>|perlvar/${^OPEN}> (usually set by the L<open> pragma or the switch C<-CioD>) are ignored. Those layers will also be ignored if you specify a colon with no name following it. In that case the default layer for the operating system (:raw on Unix, :crlf on Windows) is used.. =item Using C<undef> for temporary files As a special case the three-argument form with a read/write mode and the third argument being L<C<undef>|/undef EXPR>: open(my $tmp, "+>", undef) or die ... opens a filehandle to a newly created empty anonymous temporary file. (This happens under any mode, which makes C<< +> >> the only useful and sensible mode to use.) You will need to L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading. =item Opening a filehandle into an in-memory scalar You can open filehandles directly to Perl scalars instead of a file or other resource external to the program. To do so, provide a reference to that scalar as the third argument to C<open>, like so: open(my $memory, ">", \$var) or die "Can't open memory file: $!"; print $memory "foo!\n"; # output will appear in $var To (re)open C<STDOUT> or I<can> fail for a variety of reasons. As with any other C<open>, check the return value for success. I<Technical note>: This feature works only when Perl is built with PerlIO -- the default, except with older (pre-5.16) Perl installations that were configured to not include it (e.g. via C<Configure -Uuseperlio>). You can see whether your Perl was built with PerlIO by running C<perl -V:useperlio>. If it says C<'define'>, you have PerlIO; otherwise you don't. See L<perliol> for detailed info on PerlIO. =item Opening a filehandle into a command If MODE is C<|->, then the filename is interpreted as a command to which output is to be piped, and if MODE is C<-|>, the filename is interpreted as a command that pipes output to us. In the two-argument (and one-argument) form, one should replace dash (C<->) with the command. See L<perlipc/"Using open() for IPC"> for more examples of this. (You are not allowed to L<C<open>|/open FILEHANDLE,MODE,EXPR> to a command that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and L<perlipc/"Bidirectional Communication with Another Process"> for alternatives.) the form of pipe opens taking three or more arguments, if LIST is specified (extra arguments after the command name) then LIST becomes arguments to the command invoked if the platform supports it. The meaning of L<C<open>|/open FILEHANDLE,MODE,EXPR> with more than three arguments for non-pipe modes is not yet defined, but experimental "layers" may give extra LIST arguments meaning. If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> with the one- or two-argument forms of L<C<open>|/open FILEHANDLE,MODE,EXPR>), an implicit L<C<fork>|/fork> is done, so L<C<open>|/open FILEHANDLE,MODE,EXPR> returns twice: in the parent process it returns the pid of the child process, and in the child process it returns (a defined) C<0>. Use C<defined($pid)> or. (If your platform has a real L<C<fork>|/fork>, such as Linux and macOS, you can use the list form; it also works on Windows with Perl 5.22 or later.) L<perlipc/"Safe Pipe Opens"> for more examples of this. =item Duping filehandles You may also, in the Bourne shell tradition, specify an EXPR beginning with C<< >& >>, in which case the rest of the string is interpreted as the name of a filehandle (or file descriptor, if numeric) to be duped (as in L<dup(2)>) and opened. You may use C<&> after C<< > >>, C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<STDOUT> and C<< '<&=X' >>, where C<X> is a file descriptor number or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of that file descriptor (and not call L L<C<flock>|/flock FILEHANDLE,OPERATION>. If you do just C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the same file descriptor as C<$B>, and therefore C<flock($A)> will not C<flock($B)> nor vice versa. But with C<< open(my $A, ">>&=", $B) >>, the filehandles will share the same underlying system file descriptor. Note that under Perls older than 5.8.0, Perl uses the standard C library's' L<fdopen(3)> to implement the C<=> functionality. On many Unix systems, L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255. For Perls 5.8.0 and later, PerlIO is (most often) the default. =item Legacy usage This section describes ways to call C<open> outside of best practices; you may encounter these uses in older code. Perl does not consider their use deprecated, exactly, but neither is it recommended in new code, for the sake of clarity and readability. =over =item Specifying mode and filename as a single argument In the one- and two-argument forms of the call, the mode and filename should be concatenated (in that order), preferably separated by white space. You can--but shouldn't--omit the mode in these forms when that mode is C<< < >>. It is safe to use the two-argument form of L<C<open>|/open FILEHANDLE,MODE,EXPR> if the filename argument is a known literal. open(my $dbase, "+<dbase.mine") # ditto or die "Can't open 'dbase.mine' for update: $!"; In the two-argument (and one-argument) form, opening C<< <- >> or C<-> opens STDIN and opening C<< >- >> opens STDOUT. New code should favor the three-argument form of C<open> over this older form. Declaring the mode and the filename as two distinct arguments avoids any confusion between the two. =item Calling C<open> with one argument via global variables As a shortcut, a one-argument call takes the filename from the global scalar variable of the same name as the filehandle: $ARTICLE = 100; open(ARTICLE) or die "Can't find article $ARTICLE: $!\n"; Here C<$ARTICLE> must be a global (package) scalar variable - not one declared with L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>. =item Assigning a filehandle to a bareword An older style is to use a bareword as the filehandle, as open(FH, "<", "input.txt") or die "Can't open < input.txt: $!"; Then you can use C<FH> as the filehandle, in C<< close FH >> and C<< <FH> >> and so on. Note that it's a global variable, so this form is not recommended when dealing with filehandles other than Perl's built-in ones (e.g. STDOUT and STDIN). =back =item Other considerations =over =item Automatic filehandle closure The filehandle will be closed when its reference count reaches zero. If it is a lexically scoped variable declared with L<C<my>|/my VARLIST>, that usually means the end of the enclosing scope. However, this automatic close does not check for errors, so it is better to explicitly close filehandles, especially those used for writing: close($handle) || warn "close failed: $!"; =item Automatic pipe flushing. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor as determined by the value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. Closing any piped filehandle causes the parent process to wait for the child to finish, then returns the status value in L<C<$?>|perlvar/$?> and L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. =item Direct versus by-reference assignment of filehandles If FILEHANDLE -- the first argument in a call to C<open> -- C<use strict "refs"> should I<not> be in effect.) =item Whitespace and special characters in the filename argument The filename passed to the one- and two-argument forms of L<C<open>|/open FILEHANDLE,MODE,EXPR> will have leading and trailing whitespace deleted and normal redirection characters honored. This property, known as "magic open", can often be used to good effect. A user could specify a filename of I<magic> and I<three-argument> form of L<C<open>|/open FILEHANDLE,MODE,EXPR>: open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!"; will allow the user to specify an argument of the form C<"rsh cat file |">, but will not work on a filename that happens to have a trailing space, while open(my $in, "<", $ARGV[0]) || die "Can't open $ARGV[0]: $!"; will have exactly the opposite restrictions. (However, some shells support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which produces a filename that can be opened normally.) =item Invoking C-style C<open> If you want a "real" C L<open(2)>, then you should use the L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves no such magic (but uses different filemodes than Perl L<C<open>|/open FILEHANDLE,MODE,EXPR>, which corresponds to C L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about mixing reading and writing. =item Portability issues See L<perlport/open>. =back =back =item opendir DIRHANDLE,EXPR X<opendir> =for Pod::Functions open a directory Opens a directory named EXPR for processing by L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, L<C<seekdir>|/seekdir DIRHANDLE,POS>, L<C<rewinddir>|/rewinddir DIRHANDLE>, and L<C<closedir>|/closedir DIRHANDLE>. L<C<readdir>|/readdir DIRHANDLE>. =item ord EXPR X<ord> X<encoding> =item ord =for Pod::Functions find a character's numeric representation Returns the numeric value of the first character of EXPR. If EXPR is an empty string, returns 0. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. (Note I<character>, not byte.) For the reverse, see L<C<chr>|/chr NUMBER>. See L<perlunicode> for more about Unicode. =item our VARLIST X<our> X<global> =item our TYPE VARLIST =item our VARLIST : ATTRS =item our TYPE VARLIST : ATTRS =for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global) variable of the same name in the current package for use within the current lexical scope. L<C<our>|/our VARLIST> has the same scoping rules as L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is only valid within a lexical scope. Unlike L<C<my>|/my VARLIST> and L<C<state>|/state VARLIST>, which both declare new (lexical) variables, L<C<our>|/our VARLIST> only creates an alias to an existing variable: a package variable of the same name. This means that when C<use strict 'vars'> is in effect, L<C<our>|/our VARLIST> lets you use a package variable without qualifying it with the package name, but only within the lexical scope of the L<C<our>|/our VARLIST> C L<C<our>|/our VARLIST> L<C<our>|/our VARLIST> declarations with the same name in the same lexical scope are allowed if they are in different packages. If they happen to be in the same package, Perl will emit warnings if you have asked for them, just like multiple L<C<my>|/my VARLIST> declarations. Unlike a second L<C<my>|/my VARLIST> declaration, which will bind the name to a fresh variable, a second L<C<our>|/our VARLIST> L<C<our>|/our VARLIST> declaration may also have a list of attributes associated with it. The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE: our ( undef, $min, $hour ) = localtime; L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows use of an unqualified name I<only> within the affected package, but across scopes. =item pack TEMPLATE,LIST X<pack> =for Pod::Functions convert a list into a binary representation L C<< > >> and C<< < >> modifiers can also be used on C<()> groups to force a particular byte-order on all components in that group, including all its subgroups. The following rules apply: =over =item * Each letter may optionally be followed by a number indicating the repeat count. A numeric repeat count may optionally be enclosed in brackets, as in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means something else, described below. Supplying a C<*> for the repeat count instead of a number means to use however many items are left, except for: =over =item * C<@>, C<x>, and C<X>, where it is equivalent to C<0>. =item * <.>, where it means relative to the start of the string. =item * C<u>, where it is equivalent to 1 (or 45, which here is equivalent). =back One can replace a numeric repeat count with a template letter enclosed in brackets to use the packed byte length of the bracketed template for the repeat count. For example, the template C<x[L]> skips as many bytes as in a packed long, and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when variable-expanded) unpacks. If the template in brackets contains alignment commands (such as C<x![d]>), its packed length is calculated as if the start of the template had the maximal possible alignment. When used with C<Z>, a C<*> as the repeat count is guaranteed to add a trailing null byte, so the resulting string is always one byte longer than the byte length of the item itself. When used with C<@>, the repeat count represents an offset from the start of the innermost C<()> group. When used with C<.>, the repeat count determines the starting position to calculate the value offset as follows: =over =item * If the repeat count is C<0>, it's relative to the current position. =item * If the repeat count is C<*>, the offset is relative to the start of the packed string. =item * And if it's an integer I<n>, the offset is relative to the start of the I<n>th innermost C<( )> group, or to the start of the string if I<n> is bigger then the group level. =back The repeat count for C<u> is interpreted as the maximal number of bytes to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat count should not be more than 65. =item * The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as needed. When unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything after the first null, and C<a> returns data with no stripping at all. If the value to pack is too long, the result is truncated. If it's too long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, followed by a null byte. Thus C<Z> always packs a trailing null, except when the count is 0. =item * Likewise, the C<b> and C<B> formats pack a string that's that many bits long. Each such format generates 1 bit of the result. These are typically followed by a repeat count like C<B8> or C<B64>. Each result bit is based on the least-significant bit of the corresponding input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. Starting from the beginning of the input string, each 8-tuple of characters is converted to 1 character of output. With format C<b>, the first character of the 8-tuple determines the least-significant bit of a character; with format C C<*> for the repeat count uses all characters of the input field. On unpacking, bits are converted to a string of C<0>s and C<1>s. =item * The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result. With non-alphabetical characters, the result is based on the 4 least-significant bits of the input character, i.e., on C<ord($char)%16>. In particular, characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result is compatible with the usual hexadecimal digits, so that C<"a"> and C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex characters with this format. Starting from the beginning of the template to L<C<pack>|/pack TEMPLATE,LIST>, each pair of characters is converted to 1 character of output. With format C<h>, the first character of the pair determines the least-significant nybble of the output character; with format C C<*> for the repeat count uses all characters of the input field. For L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of hexadecimal digits. =item * The C<p> format packs a pointer to a null-terminated string. You are responsible for ensuring that the string is not a temporary value, as that could potentially get deallocated before you got around to using the packed result. The C<P> format packs a pointer to a structure of the size indicated by the length. A null pointer is created if the corresponding value for C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into L<C<undef>|/undef EXPR>.. =item * The L<C<pack>|/pack TEMPLATE,LIST>, you write I<length-item>C</>I<sequence-item>, and the I<length-item> describes how the length value is packed. Formats likely to be of most use are integer-packing ones like C<n> for Java strings, C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat count, in which case the minimum of that and the number of available items is used as the argument for I<length-item>. If it has no repeat count or uses a '*', the number of available items is used. For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer arguments unpacked so far is used. You write C</>I<sequence-item> and the repeat count is obtained by popping off the last element from the stack. The I<sequence-item> must not have a repeat count. If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), the I I<length-item> is not returned explicitly from L<C<unpack>|/unpack TEMPLATE,EXPR>. Supplying a count to the I<length-item> format letter is only useful with C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may introduce C<"\000"> characters, which Perl does not regard as legal in numeric strings. =item * The integer types C<s>, C<S>, C<l>, and C<L> may be followed by a C<!> modifier to specify native shorts or longs. As shown in the example above, a bare C<l> means exactly 32 bits, although the native C<long> as seen by the local C compiler may be larger. This is mainly an issue on 64-bit platforms. You can see whether using C<!> makes any difference this way: printf "format s is %d, s! is %d\n", length pack("s"), length pack("s!"); printf "format l is %d, l! is %d\n", length pack("l"), length pack("l!"); C<i!> and C<I!> are also allowed, but only for completeness' sake: they are identical to C<i> and L<C<Config>|Config> module: use Config; print $Config{shortsize}, "\n"; print $Config{intsize}, "\n"; print $Config{longsize}, "\n"; print $Config{longlongsize}, "\n"; C<$Config{longlongsize}> is undefined on systems without long long support. =item * The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are I<big-endian> and I<little-endian> are comic references to the egg-eating habits of the little-endian Lilliputians and the big-endian Blefuscudians from the classic Jonathan Swift satire, I L<Config>: use Config; print "$Config{byteorder}\n"; or from the command line: $ perl -V:byteorder Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> and C<"87654321"> are big-endian. Systems with multiarchitecture binaries will have C<"ffff">, signifying that static information doesn't work, one must use runtime probing. For portably packed integers, either use the formats C<n>, C<N>, C<v>, and C<V> or else use the C<< > >> and C<< < >> modifiers described immediately below. See also L<perlport>. =item * Also floating point numbers have endianness. Usually (but not always) this agrees with the integer endianness. Even though most platforms these days use the IEEE 754 binary format, there are differences, especially if the long doubles are involved. You can see the C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>, C<longdblsize>): the "kind" values are enums, unlike C<byteorder>. Portability-wise the best option is probably to keep to the IEEE 754 64-bit doubles, and of agreed-upon endianness. Another possibility is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>. =item * Starting with Perl 5.10.0, integer and floating-point formats, along with the C<p> and C<P> formats and C<()> groups, may all be followed by the C<< > >> or C<< < >> endianness modifiers to respectively enforce big- or little-endian byte-order. These modifiers are especially useful given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, 64-bit integers, or floating-point values. Here are some concerns to keep in mind when using an endianness modifier: =over =item * Exchanging signed integers between different platforms works only when all platforms store them in the same format. Most platforms store signed integers in two's-complement notation, so usually this is not an issue. =item * The C<< > >> or C<< < >> modifiers can only be used on floating-point formats on big- or little-endian machines. Otherwise, attempting to use them raises an exception. =item * C<< > >> or C<< < >> on floating-point values can be useful, but also dangerous if you don't know exactly what you're doing. It is not a general way to portably store floating-point values. =item * When using C<< > >> or C<< < >> on a C<()> group, this affects all types inside the group that accept byte-order modifiers, including all subgroups. It is silently ignored for all other types. You are not allowed to override the byte-order within a group that already has a byte-order modifier suffix. =back =item * L<perlport>. If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> modifiers to force big- or little-endian byte-order on floating-point values. Because Perl uses doubles (or long doubles, if configured) internally for all numeric calculation, converting from double into float and thence to double again loses precision, so C<unpack("f", pack("f", $foo)>) will not in general equal $foo. =item * Pack and unpack can operate in two modes: character mode (C<C0> mode) where the packed string is processed per character, and UTF-8 byte mode (C<U0> mode) where the packed string is processed in its UTF-8-encoded Unicode form on a byte-by-byte basis. Character mode is the default unless the format string starts with C<U>. You can always switch mode mid-format with an explicit C<C0> or C<U0> in the format. This mode remains in effect until the next mode change, or until the end of the C<()> group it (directly) applies to. Using C<C0> to get Unicode characters while using C<U0> to get I L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a substitute for the L<Encode> module. =item * You must yourself do any alignment or padding by inserting, for example, enough C<"x">es while packing. There is no way for L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> to know where characters are going to or coming from, so they handle their output and input as flat sequences of characters. =item * A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may take a repeat count either as postfix, or for L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</> template character. Within each repetition of a group, positioning with C<@> starts over at 0. Therefore, the result of pack("@1A((@2A)@3A)", qw[X Y Z]) is the string C<"\0X\0\0YZ">. =item * C<x> and C<X> accept the C<!> modifier to act as alignment commands: they jump forward or back to the closest position aligned at a multiple of C<count> characters. For example, to L<C<pack>|/pack TEMPLATE,LIST> or L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like struct { char c; /* one signed, 8-bit character */ double d; char cc[2]; } one may need to use the template C<c x![d] d c[2]>. This assumes that doubles must be aligned to the size of double. For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; both are no-ops. =item * C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to represent signed 16-/32-bit integers in big-/little-endian order. This is portable only when all platforms sharing packed data use the same binary representation for signed integers; for example, when all platforms use two's-complement representation. =item * Comments can be embedded in a TEMPLATE using C<#> C</x> can for complicated pattern matches. =item * If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST> is given, L<C<pack>|/pack TEMPLATE,LIST> assumes additional C<""> arguments. If TEMPLATE requires fewer arguments than given, extra arguments are ignored. =item * Attempting to pack the special floating point values C<Inf> and C<NaN> (infinity, also in negative, and not-a-number) into packed integer values (like C<"L">) is a fatal error. The reason for this is that there simply isn't any sensible mapping for these special values into integers. =back L<C<unpack>|/unpack TEMPLATE,EXPR>. =item package NAMESPACE =item package NAMESPACE VERSION X<package> X<module> X<namespace> X<version> =item package NAMESPACE BLOCK =item package NAMESPACE VERSION BLOCK X<package> X<module> X<namespace> X<version> =for Pod::Functions declare a separate global namespace L<C<eval>|/eval EXPR>). That is, the forms without a BLOCK are operative through the end of the current scope, just like the L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and L<C<our>|/our VARLIST> operators. All unqualified dynamic identifiers in this scope will be in the given namespace, except where overridden by another L<C<package>|/package NAMESPACE> declaration or when they're one of the special identifiers that qualify into C<main::>, like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. A package statement affects dynamic variables only, including those you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped variables, which are created with L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>. Typically it would be the first declaration in a file included by L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>. C<$SomePack::var> or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> package as assumed. That is, C<$::sail> is equivalent to C<$main::sail> (as well as to C<$main'sail>, still seen in ancient code, mostly from Perl 4). If VERSION is provided, L<C<package>|/package NAMESPACE> sets the C<$VERSION> variable in the given namespace to a L<version> object with the VERSION provided. VERSION must be a "strict" style version number as defined by the L<version> module: a positive decimal number (integer or decimal-fraction) without exponentiation or else a dotted-decimal v-string with a leading 'v' character and at least three components. You should set C<$VERSION> only once per package. See L<perlmod/"Packages"> for more information about packages, modules, and classes. See L<perlsub> for other scoping issues. =item __PACKAGE__ X<__PACKAGE__> =for Pod::Functions +5.004 the current package A special token that returns the name of the package in which it occurs. =item pipe READHANDLE,WRITEHANDLE X<pipe> =for Pod::Functions open a pair of connected filehandles Opens a pair of connected pipes like the corresponding system call. Note that if you set up a loop of piped processes, deadlock can occur unless you are very careful. In addition, note that Perl's pipes use IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> to flush your WRITEHANDLE after each command, depending on the application. Returns true on success. See L<IPC::Open2>, L<IPC::Open3>, and L<perlipc/"Bidirectional Communication with Another Process"> for examples of such things. On systems that support a close-on-exec flag on files, that flag is set on all newly opened file descriptors whose L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>). See L<perlvar/$^F>. =item pop ARRAY X<pop> X<stack> =item pop =for Pod::Functions remove the last element from an array and return it Pops and returns the last value of the array, shortening the array by one element. Returns the undefined value if the array is empty, although this may also happen at other times. If ARRAY is omitted, pops the L<C<@ARGV>|perlvar/@ARGV> array in the main program, but the L<C<@_>|perlvar/@_> array in subroutines, just like L<C<shift>|/shift ARRAY>. Starting with Perl 5.14, an experimental feature allowed L<C<pop>|/pop ARRAY> to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24. =item pos SCALAR X<pos> X<match, position> =item pos =for Pod::Functions find or set the offset for the last/next m//g search Returns the offset of where the last C<m//g> search left off for the variable in question (L<C<$_>|perlvar/$_> is used when the variable is not specified). This offset is in characters unless the (no-longer-recommended) L<C<use bytes>|bytes> pragma is in effect, in which case the offset is in bytes. Note that 0 is a valid match offset. L<C<undef>|/undef EXPR> indicates that the search position is reset (usually due to match failure, but can also be because no match has yet been run on the scalar). L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will change that offset, and so will also influence the C<\G> zero-width assertion in regular expressions. Both of these effects take place for the next match, so you can't affect the position with L<C<pos>|/pos SCALAR> during the current match, such as in C<(?{pos() = 5})> or C<s//pos() = 5/e>. Setting L<C<pos>|/pos SCALAR> also resets the I<matched with zero-length> flag, described under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. Because a failed C<m//gc> match doesn't reset the offset, the return from L<C<pos>|/pos SCALAR> won't change either in this case. See L<perlre> and L<perlop>. =item print FILEHANDLE LIST X<print> =item print FILEHANDLE =item print LIST =item print =for Pod::Functions output a list to a filehandle C<+> or put parentheses around the arguments.) If FILEHANDLE is omitted, prints to the last selected (see L<C<select>|/select FILEHANDLE>) output handle. If LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected output handle. To use FILEHANDLE alone to print the content of L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like C<FH>, not an indirect one like C<$fh>. To set the default output handle to something other than STDOUT, use the select operation. The current value of L<C<$,>|perlvar/$,> (if any) is printed between each LIST item. The current value of L<C<$\>|perlvar/$\> (if any) is printed after the entire LIST has been printed. Because print takes a LIST, anything in the LIST is evaluated in list context, including any subroutines whose return lists you pass to L<C<print>|/print FILEHANDLE LIST>. Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a L<perlipc> for more on signal handling. =item printf FILEHANDLE FORMAT, LIST X<printf> =item printf FILEHANDLE =item printf FORMAT, LIST =item printf =for Pod::Functions output a formatted list to a filehandle Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that L<C<$\>|perlvar/$\> (the output record separator) is not appended. The FORMAT and the LIST are actually parsed as a single list. The first argument of the list will be interpreted as the L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format. This means that C<printf(@_)> will use C<$_[0]> as the format. See L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format argument. If C<use locale> (including C<use locale ':not_characters'>) is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the C<LC_NUMERIC> locale setting. See L<perllocale> and L<POSIX>. For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is used as the format; to use FILEHANDLE without a list, you must use a bareword filehandle like C<FH>, not an indirect one like C<$fh>. However, this will rarely do what you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be replaced with the empty string and a warning will be emitted if L<warnings> are enabled. Just use L<C<print>|/print FILEHANDLE LIST> if you want to print the contents of L<C<$_>|perlvar/$_>. Don't fall into the trap of using a L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple L<C<print>|/print FILEHANDLE LIST> would do. The L<C<print>|/print FILEHANDLE LIST> is more efficient and less error prone. =item prototype FUNCTION X<prototype> =item prototype =for Pod::Functions +5.002 get the prototype (if any) of a subroutine Returns the prototype of a function as a string (or L<C<undef>|/undef EXPR> if the function has no prototype). FUNCTION is a reference to, or the name of, the function whose prototype you want to retrieve. If FUNCTION is omitted, L<C<$_>|perlvar/$_> is used. If FUNCTION is a string starting with C<CORE::>, the rest is taken as a name for a Perl builtin. If the builtin's arguments cannot be adequately expressed by a prototype (such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION> returns L<C<undef>|/undef EXPR>, because the builtin does not really behave like a Perl function. Otherwise, the string describing the equivalent prototype is returned. =item push ARRAY,LIST X<push> X<stack> =for Pod::Functions append one or more elements to an array Treats L<C<push>|/push ARRAY,LIST>. Starting with Perl 5.14, an experimental feature allowed L<C<push>|/push ARRAY,LIST> to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24. =item q/STRING/ =for Pod::Functions singly quote a string =item qq/STRING/ =for Pod::Functions doubly quote a string =item qw/STRING/ =for Pod::Functions quote a list of words =item qx/STRING/ =for Pod::Functions backquote quote a string Generalized quotes. See L<perlop/"Quote-Like Operators">. =item qr/STRING/ =for Pod::Functions +5.005 compile pattern Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. =item quotemeta EXPR X<quotemeta> X<metacharacter> =item quotemeta =for Pod::Functions quote regular expression magic characters Returns the value of EXPR with all the ASCII non-"word" characters backslashed. (That is, all ASCII characters not matching C</[A-Za-z_0-9]/> will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the C<\Q> escape in double-quoted strings. (See below for the behavior on non-ASCII code points.) If EXPR is omitted, uses L<C<$_>|perlvar/$_>. quotemeta (and C<\Q> ... C< C<$sentence> to become C<, L<C<quotemeta>|/quotemeta EXPR> or L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>, which is to quote all characters in the upper Latin1 range. This provides complete backwards compatibility for old programs which do not use Unicode. (Note that C<unicode_strings> is automatically enabled within the scope of a S<C<use v5.12>> or greater.) Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code points are quoted whether the string is encoded as UTF-8 or not. As mentioned above, locale does not affect the quoting of ASCII-range characters. This protects against those locales where characters such as C<"|"> are considered to be word characters. Otherwise, Perl quotes non-ASCII characters using an adaptation from Unicode (see L<>). (C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the Pattern_Syntax property. Perl also promises, that if we ever add characters that are considered to be white space in regular expressions (currently mostly affected by). =item rand EXPR X<rand> X<random> =item rand =for Pod::Functions retrieve the next pseudorandom number Returns a random fractional number greater than or equal to C<0> and less than the value of EXPR. (EXPR should be positive.) If EXPR is omitted, the value C<1> is used. Currently EXPR with the value C<0> is also special-cased as C<1> (this was undocumented before Perl 5.8.0 and is subject to change in future versions of Perl). Automatically calls L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been called. See also L<C<srand>|/srand EXPR>. Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR> if you want random integers instead of random fractional numbers. For example, int(rand(10)) returns a random integer between C<0> and C<9>, inclusive. (Note: If your rand function consistently returns numbers that are too large or too small, then your version of Perl was probably compiled with the wrong number of RANDBITS.) read FILEHANDLE,SCALAR,LENGTH,OFFSET X<read> X<file, read> =item read FILEHANDLE,SCALAR,LENGTH =for Pod::Functions fixed-length buffered input from a filehandle Attempts to read LENGTH I<characters> of data into variable SCALAR from the specified FILEHANDLE. Returns the number of characters actually read, C<0> at end of file, or undef if there was an error (in the latter case L<C<$!>|perlvar/$!>. The call is implemented in terms of either Perl's or your system's native L<fread(3)> library function, via the L<PerlIO> layers applied to the handle. To get a true L<read(2)> system call, see L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. Note the I<characters>: depending on the status of the filehandle, either (8-bit) bytes or characters are read. By default, all filehandles operate on bytes, but for example if the filehandle has been opened with the C<:utf8> I/O layer (see L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the C<:encoding> layer: in that case pretty much any characters can be read. =item readdir DIRHANDLE X<readdir> =for Pod::Functions get a directory from a directory handle Returns the next directory entry for a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR>. If used in list context, returns all the rest of the entries in the directory. If there are no more entries, returns the undefined value in scalar context and the empty list in list context. If you're planning to filetest the return values out of a L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in question. Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there, it would have been testing the wrong file. opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!"; my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); closedir $dh; As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration. If either a C<readdir> expression or an explicit assignment of a C<readdir> expression to a scalar is used as a C<while>/C<for> condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value. I<only> on Perls of a recent vintage: use 5.012; # so readdir assigns to $_ in a lone while test =item readline EXPR =item readline X<readline> X<gets> X<fgets> =for Pod::Functions fetch a record from a file Reads from the filehandle whose typeglob is contained in EXPR (or from C<*ARGV> if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns L<C<undef>|/undef EXPR>. In list context, reads until end-of-file is reached and returns a list of lines. Note that the notion of "line" used here is whatever you may have defined with L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in L<English>). See L<perlvar/"$/">. When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>, when L<C<readline>|/readline EXPR> is in scalar context (i.e., file slurp mode), and when an empty file is read, it returns C<''> the first time, followed by L<C<undef>|/undef EXPR> subsequently. This is the internal function implementing the C<< <EXPR> >> operator, but you can use it directly. The C<< <EXPR> >> operator is discussed in more detail in L<perlop/"I/O Operators">. my $line = <STDIN>; my $line = readline(STDIN); # same thing If L<C<readline>|/readline EXPR> encounters an operating system error, L<C<$!>|perlvar/$!> will be set with the corresponding error message. It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from filehandles you don't trust, such as a tty or a socket. The following example uses the operator form of L<C<readline>|/readline EXPR> and dies if the result is not defined. while ( ! eof($fh) ) { defined( $_ = readline $fh ) or die "readline failed: $!"; ... } Note that you have can't handle L<C<readline>|/readline EXPR> errors that way with the C<ARGV> filehandle. In that case, you have to open each element of L<C<@ARGV>|perlvar/@ARGV> yourself since L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently. foreach my $arg (@ARGV) { open(my $fh, $arg) or warn "Can't open $arg: $!"; while ( ! eof($fh) ) { defined( $_ = readline $fh ) or die "readline failed for $arg: $!"; ... } } Like the C<< <EXPR> >> operator, if a C<readline> expression is used as the condition of a C<while> or C<for> loop, then it will be implicitly assigned to C<$_>. If either a C<readline> expression or an explicit assignment of a C<readline> expression to a scalar is used as a C<while>/C<for> condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value. =item readlink EXPR X<readlink> =item readlink =for Pod::Functions determine where a symbolic link is pointing Returns the value of a symbolic link, if symbolic links are implemented. If not, raises an exception. If there is a system error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno). If EXPR is omitted, uses L<C<$_>|perlvar/$_>. Portability issues: L<perlport/readlink>. =item readpipe EXPR =item readpipe X<readpipe> =for Pod::Functions execute a system command and collect standard output EXPR is executed as a system command. The collected standard output of the command is returned. In scalar context, it comes back as a single (potentially multi-line) string. In list context, returns a list of lines (however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in L<English>)). This is the internal function implementing the C<qx/EXPR/> operator, but you can use it directly. The C<qx/EXPR/> operator is discussed in more detail in L<perlop/"C<qx/I<STRING>/>">. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. =item recv SOCKET,SCALAR,LENGTH,FLAGS X<recv> =for Pod::Functions receive a message over a Socket Receives L<recvfrom(2)> system call. See L<perlipc/"UDP: Message Passing"> for examples. Note that if the socket has been marked as C<:utf8>, C<recv> will throw an exception. The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. =item redo LABEL X<redo> =item redo EXPR =item redo =for Pod::Functions start this loop iteration over again The L<C<redo>|/redo LABEL> command restarts the loop block without evaluating the conditional again. The L<C<continue>|/continue BLOCK> block, if any, is not executed. If the LABEL is omitted, the command refers to the innermost enclosing loop. The C<redo EXPR> form, available starting in Perl 5.18.0, allows a label name to be computed at run time, and is otherwise identical to; } L<C<redo>|/redo<redo>|/redo LABEL> inside such a block will effectively turn it into a looping construct.<redo ("foo")."bar"> will cause "bar" to be part of the argument to L<C<redo>|/redo LABEL>. =item ref EXPR X<ref> X<reference> =item ref =for Pod::Functions find out the type of thing being referenced Examines the value of EXPR, expecting it to be a reference, and returns a string giving information about the reference and the type of referent. If EXPR is not specified, L<C<$_>|perlvar/$_> will be used. If the operand is not a reference, then the empty string will be returned. An empty string will only be returned in this situation. C<ref> is often useful to just test whether a value is a reference, which can be done by comparing the result to the empty string. It is a common mistake to use the result of C<ref> directly as a truth value: this goes wrong because C<0> (which is false) can be returned for a reference. If the operand is a reference to a blessed object, then the name of the class into which the referent is blessed will be returned. C<ref> doesn't care what the physical type of the referent is; blessing takes precedence over such concerns. Beware that exact comparison of C<ref> results against a class name doesn't perform a class membership test: a class's members also include objects blessed into subclasses, for which C C<ARRAY>,. The ambiguity between built-in type names and class names significantly limits the utility of C<ref>. For unambiguous information, use L<C<Scalar::Util::blessed()>|Scalar::Util/blessed> for information about blessing, and L<C<Scalar::Util::reftype()>|Scalar::Util/reftype> for information about physical types. Use L<the C<isa> method|UNIVERSAL/C<< $obj->isa( TYPE ) >>> for class membership tests, though one must be sure of blessedness before attempting a method call. See also L<perlref> and L<perlobj>. =item rename OLDNAME,NEWNAME X<rename> X<move> X<mv> X<ren> =for Pod::Functions change a filename Changes the name of a file; an existing file NEWNAME will be clobbered. Returns true for success, false otherwise. Behavior of this function varies wildly depending on your system implementation. For example, it will usually not work across file system boundaries, even though the system I<mv> command sometimes compensates for this. Other restrictions include whether it works on directories, open files, or pre-existing files. Check L<perlport> and either the L<rename(2)> manpage or equivalent system documentation for details. For a platform independent L<C<move>|File::Copy/move> function look at the L<File::Copy> module. Portability issues: L<perlport/rename>. =item require VERSION X<require> =item require EXPR =item require =for Pod::Functions load in external functions from a library at runtime Demands a version of Perl specified by VERSION, or demands some semantics specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied. VERSION may be either a literal such as v5.24.1, which will be compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in L<English>), or a numeric argument of the form 5.024001, which will be compared to L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than the version of the current Perl interpreter. Compare with L<C<use>|/use Module VERSION LIST>, which can do a similar check at compile older code. require v5.24.1; # run time version check require 5.24.1; # ditto require 5.024_001; # ditto; older syntax compatible with perl 5.6 Otherwise, L<C<require>|/require VERSION> demands that a library file be included if it hasn't already been included. The file is included via the do-FILE mechanism, which is essentially just a variety of L<C<eval>|/eval EXPR> C<1;> unless you're sure it'll return true otherwise. But it's better just to put the C<1;>, in case you add more statements. If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm> extension and replaces C<::> with F<Foo/Bar.pm> file in the directories specified in the L<C<@INC>|perlvar/@INC> array, and it will autovivify the C<Foo::Bar::> stash at compile time. But if you try this: my $) is in effect, C<sort LIST> sorts LIST according to the current collation locale. See L<perllocale>. L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST> (for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or L<C<grep>|/grep BLOCK LIST>) actually modifies the element in the original list. This is usually something to be avoided when writing clear code. Historically Perl has varied in whether sorting is stable by default. If stability matters, it can be controlled explicitly by using the L<sort> pragma. Examples: # use sort 'stable'; my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; Warning: syntactical care is required when sorting the list returned from a function. If you want to sort the list returned by the function call C<find_records(@key)>, you can use: my @contact = sort { $a cmp $b } find_records @key; my @contact = sort +find_records(@key); my @contact = sort &find_records(@key); my @contact = sort(find_records(@key)); If instead you want to sort the array C<@key> with the comparison routine C<find_records()> then you can use: my @contact = sort { find_records() } @key; my @contact = sort find_records(@key); my @contact = sort(find_records @key); my @contact = sort(find_records (@key)); C<$a> and C<$b> are set as package globals in the package the sort() is called from. That means C<$main::a> and C<$main::b> (or C<$::a> and C<$::b>) in the C<main> package, C<$FooPack::a> and C<$FooPack::b> in the C<FooPack> package, etc. If the sort block is in scope of a C<my> or C<state> declaration of C<$a> and/or C<$b>, you I<must> spell out the full name of the variables in the sort block : package main; my $ syntax (C<//>) specifically matches the empty string, which is contrary to its usual interpretation as the last successful match. If PATTERN is C</^/>, then it is treated as if it used the L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it isn't much use otherwise. C<E<sol>m> and any of the other pattern modifiers valid for C<qr> (summarized in L<perlop/qrE<sol>STRINGE<sol>msixpodualn>) may be specified explicitly. As another special case, L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default behavior of the command line tool B<awk> when the PATTERN is either omitted or a string composed of a single space character (such as S<C<' '>> or S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were C</\s+/>; in particular, this means that I<any> contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing only a single space character to be a separator. In earlier Perls this special case was restricted to the use of a plain S<C<" ">> as the pattern argument to split; in Perl 5.18.0 and later this special case is triggered by any expression which evaluates to the simple string S<C<" ">>. As of Perl 5.28, this special-cased whitespace splitting works as expected in the scope of L<< S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature >>. In previous versions, and outside the scope of that feature, it exhibits L<perlunicode/The "Unicode Bug">: characters that are whitespace according to Unicode rules but not according to ASCII rules can be treated as part of fields rather than as field separators, depending on the string's internal encoding. If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering the previously described I<awk> emulation. If LIMIT is specified and positive, it represents the maximum number of fields into which the EXPR may be split; in other words, LIMIT is one greater than the maximum number of times EXPR may be split. Thus, the LIMIT value C<1> means that EXPR may be split a maximum of zero times, producing a maximum of one field (namely, the entire value of EXPR). For instance: print join(':', split(//, 'abc', 1)), "\n"; produces the output C<abc>, and this: print join(':', split(//, 'abc', 2)), "\n"; produces the output C<a:bc>, and each of these: print join(':', split(//, 'abc', 3)), "\n"; print join(':', split(//, 'abc', 4)), "\n"; produces the output C C<a:b:c>, but the following: print join(':', split(/,/, 'a,b,c,,,', -1)), "\n"; produces the output C C<:abc>. However, a zero-width match at the beginning of EXPR never produces an empty field, so that: print join(':', split(//, ' abc')); produces the output S<C< :a:b:c>> (rather than S<C<: S<C< :a:b:c:>>. If the PATTERN contains L<capturing groups|perlretut/Grouping things and hierarchical matching>, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per L<backreferences|perlretut/Backreferences>); if any group does not match, then it captures the L<C<undef>|/undef EXPR> value instead of a substring. Also, note that any such additional field is produced whenever there is a separator (that is, whenever a split occurs), and such an additional field does B') =item sprintf FORMAT, LIST X<sprintf> =for Pod::Functions formatted print into a string Returns a string formatted by the usual L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C library function L<C<sprintf>|/sprintf FORMAT, LIST>. See below for more details and see L<sprintf(3)> or L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it emulates the C function L<sprintf(3)>, but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local L<sprintf(3)> are therefore unavailable from Perl. Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, L<C<sprintf>|/sprintf FORMAT, LIST> L<C<sprintf>|/sprintf FORMAT, LIST> C<%e>, C<%E>, C<%g> and C<%a> and C<%A>: the exponent or the hexadecimal digits may float: especially the "long doubles" Perl configuration option may cause surprises. Between the C<%> and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are: =over 4 =item format parameter index An explicit format parameter index, such as C<2$>. By default sprintf will format the next unused argument in the list, but this allows you to take the arguments out of order: printf '%2$d %1$d', 12, 34; # prints "34 12" printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" =item flags>" =item vector flag This flag tells Perl to interpret the supplied string as a vector of integers, one for each character in the string. Perl applies the format to each integer in turn, then joins the resulting strings with a separator (a dot C<.> by default). This can be useful for displaying ordinal values of characters in arbitrary strings: printf "%vd", "AB\x{100}"; # prints "65.66.256" printf "version is v%vd\n", $^V; # Perl's version Put an asterisk C<*> before the C<*2$v>; for example: printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses @addr[1..3], ":"; =item (minimum) width Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with C<*>) or from a specified argument (e.g., with C<*2$>): printf "<%s>", "a"; # prints "<a>" printf "<%6s>", "a"; # prints "< a>" printf "<%*s>", 6, "a"; # prints "< a>" printf '<%*2$s>', "a", 6; # prints "< a>" printf "<%2s>", "long"; # prints "<long>" (does not truncate) If a field width obtained through C<*> is negative, it has the same effect as the C<-> flag: left-justification. =item precision, or maximum width X<precision> You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a C<.> followed by a number. For floating-point formats except C<g> and C<.*>, or from a specified argument (e.g., with C<.*2$>): printf '<%.6x>', 1; # prints "<000001>" printf '<%.*x>', 6, 1; # prints "<000001>" printf '<%.*2$x>', 1, 6; # prints "<000001>" printf '<%6.*2$x>', 1, 4; # prints "< 0001>" If a precision obtained through C<*>>" =item size For numeric conversions, you can specify the size to interpret the number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer conversions (C prior to Perl 5.30, types "size_t" or "ssize_t" on Perl 5.14 or later As of 5.14, none of these raises an exception if they are not supported on your platform. However, if warnings are enabled, a warning of the L<C<printf>|warnings> L<Config>: use Config; if ($Config{use64bitint} eq "define" || $Config{longsize} >= 8) { print "Nice quads!\n"; } For floating-point conversions (C<e f g E F G>), numbers are usually assumed to be the default floating-point size on your platform (double or long double), but you can force "long double" with C<q>, C<L>, or C<ll> if your platform supports them. You can find out whether your Perl supports long doubles via L<Config>: use Config; print "long doubles\n" if $Config{d_longdbl} eq "define"; You can find out whether Perl considers "long double" to be the default floating-point size to use on your platform via L C<V> has no effect for Perl code, but is supported for compatibility with XS code. It means "use the standard size for a Perl integer or floating-point number", which is the default. =item order of arguments Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused argument as the value to format for each format specification. If the format specification uses C<*> to require additional arguments, these are consumed from the argument list in the order they appear in the format specification I<before> the value to format. Where an argument is specified by an explicit index, this does not affect the normal order for the arguments, even when the explicitly specified index would have been the next argument. So: printf "<%*.*s>", $a, $b, $c; uses C<$a> for the width, C<$b> for the precision, and C<$c> as the value to format; while: printf '<%*1$.*s>', $a, $b; would use C<$a> for the width and precision, and C<$b> as the value to format. Here are some more examples; be aware that when using an explicit index, the" =back If L<C<use locale>|locale> (including C<use locale ':not_characters'>) is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the C<LC_NUMERIC> locale. See L<perllocale> and L<POSIX>. =item sqrt EXPR X<sqrt> X<root> X<square root> =item sqrt =for Pod::Functions square root function Return the positive square root of EXPR. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. Works only for non-negative operands unless you've loaded the L<C<Math::Complex>|Math::Complex> module. use Math::Complex; print sqrt(-4); # prints 2i =item srand EXPR X<srand> X<seed> X<randseed> =item srand =for Pod::Functions seed the random number generator Sets and returns the random number seed for the L<C<rand>|/rand EXPR> operator. The point of the function is to "seed" the L<C<rand>|/rand EXPR> function so that L<C<rand>|/rand EXPR> can produce a different sequence each time you run your program. When called with a parameter, L<C<srand>|/srand EXPR> uses that for the seed; otherwise it (semi-)randomly chooses a seed. In either case, starting with Perl 5.14, it returns the seed. To signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so srand returns the seed If L<C<srand>|/srand EXPR> is not called explicitly, it is called implicitly without a parameter at the first use of the L<C<rand>|/rand EXPR> operator. However, there are a few situations where programs are likely to want to call L<C<srand>|/srand EXPR>. One is for generating predictable results, generally for testing or debugging. There, you use C<srand($seed)>, with the same C<$seed> each time. Another case is that you may want to call L<C<srand>|/srand EXPR> after a L<C<fork>|/fork> to avoid child processes sharing the same seed value as the parent (and consequently each other). Do B<not> call C<srand()> (i.e., without an argument) more than once per process. The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling L<C<srand>|/srand EXPR> again actually I<loses> randomness. Most implementations of L<C<srand>|/srand EXPR> take an integer and will silently truncate decimal numbers. This means C<srand(42)> will usually produce the same results as C<srand(42.1)>. To be safe, always pass L<C<srand>|/srand EXPR> stat FILEHANDLE X<stat> X<file, status> X<ctime> =item stat EXPR =item stat DIRHANDLE =item stat =for Pod::Functions get a file's status information Returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!). Returns the empty list if L<C<stat>|/stat FILEHANDLE> fails. Typically used as follows: L<perlport/"Files and Filesystems"> for details. If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last L<C<stat>|/stat FILEHANDLE>, L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned. Example: if (-x $file && (($d) = stat(_)) && $d < 0) { print "$file is executable NFS file\n"; } (This works on machines only for which the device number is negative under NFS.) C<eq> rather than C<==>. C<eq> will work fine on inode numbers that are represented numerically, as well as those represented as strings. Because the mode contains both the file type and its permissions, you should mask off the file type portion and (s)printf using a C<"%o"> if you want to see the real permissions. my $mode = (stat($filename))[2]; printf "Permissions are %04o\n", $mode & 07777; In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value indicating success or failure, and, if successful, sets the information associated with the special filehandle C<_>. The (C<S_IF*>) and functions (C<S_IS*>) from the C<-u> and C<-d> operators. Commonly available C L<chmod(2)> and L<stat(2)> documentation for more details about the C<S_*> constants. To get status info for a symbolic link instead of the target file behind the link, use the L<C<lstat>|/lstat FILEHANDLE> function. Portability issues: L<perlport/stat>. =item state VARLIST X<state> =item state TYPE VARLIST =item state VARLIST : ATTRS =item state TYPE VARLIST : ATTRS =for Pod::Functions +state declare and assign a persistent lexical variable L<C<state>|/state VARLIST> declares a lexically scoped variable, just like L<C<my>|/my VARLIST>. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered. See L<perlsub/"Persistent Private Variables"> for details. If more than one variable is listed, the list must be placed in parentheses. With a parenthesised list, L<C<undef>|/undef EXPR> can be used as a dummy placeholder. However, since initialization of state variables in such lists is currently not possible this would serve no purpose. study SCALAR X<study> =item study =for Pod::Functions no-op, formerly optimized input data for repeated searches At this time, C<study> does nothing. This may change in the future. Prior to Perl version 5.16, it would create an inverted index of all characters that occurred in the given SCALAR (or L<C<$_>|perlvar/$_> if unspecified). When matching a pattern, the rarest character from the pattern would be looked up in this index. Rarity was based on some static frequency tables constructed from some C programs and English text. =item sub NAME BLOCK X<sub> =item sub NAME (PROTO) BLOCK =item sub NAME : ATTRS BLOCK =item sub NAME (PROTO) : ATTRS BLOCK =for Pod::Functions declare a subroutine, possibly anonymously This is subroutine definition, not a real function I<per se>. Without a BLOCK it's just a forward declaration. Without a NAME, it's an anonymous function declaration, so does return a value: the CODE ref of the closure just created. See L<perlsub> and L<perlref> for details about subroutines and references; see L<attributes> and L<Attribute::Handlers> for more information about attributes. =item __SUB__ X<__SUB__> =for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine A special token that returns a reference to the current subroutine, or L<C<undef>|/undef EXPR> outside of a subroutine. The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such as C</(?{...})/>) is subject to change. This token is only available under C<use v5.16> or the L<C<"current_sub"> feature|feature/The 'current_sub' feature>. See L<feature>. =item substr EXPR,OFFSET,LENGTH,REPLACEMENT X<substr> X<substring> X<mid> X<left> X<right> =item substr EXPR,OFFSET,LENGTH =item substr EXPR,OFFSET =for Pod::Functions get or alter a portion of a string Extracts a substring out of EXPR and returns it. First character is at offset zero. If OFFSET is negative, starts that far back from the end of the string. If LENGTH is omitted, returns everything through the end of the string. If LENGTH is negative, leaves that many characters off the end of the string. L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> L<C<sprintf>|/sprintf FORMAT, LIST>. If OFFSET and LENGTH specify a substring that is partly outside the string, only the part within the string is returned. If the substring is beyond either end of the string, L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>. my $; thus L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns true on success and false on failure, yet you can still easily determine the new position. =item system LIST X<system> X<shell> =item system PROGRAM LIST =for Pod::Functions run a separate program Does exactly the same thing as L<C<exec>|. On Windows, only the C<system PROGRAM LIST> syntax will reliably avoid using the shell; C<system LIST>, even with more than one element, will fall back to the shell if the first spawn fails.. The return value is the exit status of the program as returned by the L<C<wait>|/wait> call. To get the actual exit value, shift right by eight (see below). See also L<C<exec>|/exec LIST>. This is I<not> what you want to use to capture the output from a command; for that you should use merely backticks or L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in L<perlop/"`STRING`">. Return value of -1 indicates a failure to start the program or an error of the L<wait(2)> system call (inspect L<C<$!>|perlvar/$!> for the reason). If you'd like to make L<C<system>|/system LIST> (and many other bits of Perl) die on error, have a look at the L<autodie> pragma. Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie to a program about its name if you use the C<system PROGRAM LIST> syntax. Again, see L<C<exec>|/exec LIST>. Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of L<C<system>|/system LIST>, if you expect your program to terminate on receipt of these signals you will need to arrange to do so yourself based on the return value. my @args = ("command", "arg1", "arg2"); system(@args) == 0 or die "system @args failed: $?"; If you'd like to manually inspect L<C<system>|/system LIST>'s failure, you can check all possible failure modes by inspecting L<C<$?>|perlvar/$?> like this: if ($? == -1) { print "failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n", $? >> 8; } Alternatively, you may inspect the value of L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module. When L<C<system>|/system LIST>'s arguments are executed indirectly by the shell, results and return codes are subject to its quirks. See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details. Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and L<C<wait>|/wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for details. Portability issues: L<perlport/system>. =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET X<syswrite> =item syswrite FILEHANDLE,SCALAR,LENGTH =item syswrite FILEHANDLE,SCALAR =for Pod::Functions fixed-length unbuffered output to a filehandle Attempts to write LENGTH bytes of data from variable SCALAR to the specified FILEHANDLE, using L<write(2)>. If LENGTH is not specified, writes whole SCALAR. It bypasses any L<PerlIO> layers including buffered IO (but is affected by the presence of the C<:utf8> layer as described later), so mixing this with reads (other than C<sysread)>), L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause confusion because the C<:perlio> and C<:crlf> layers usually buffer data. Returns the number of bytes actually written, or L<C<undef>|/undef EXPR> if there was an error (in this case the errno variable L<C<$!>|perlvar/$!>. B<WARNING>: If the filehandle is marked C<:utf8>, C<syswrite> will raise an exception. The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. Alternately, if the handle is not marked with an encoding but you attempt to write characters with code points over 255, raises an exception. See L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. =item tell FILEHANDLE X<tell> =item tell =for Pod::Functions get current seekpointer on a filehandle Returns the current position I<in bytes> for FILEHANDLE, or -1 on error. FILEHANDLE may be an expression whose value gives the name of the actual filehandle. If FILEHANDLE is omitted, assumes the file last read.. The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams like the STDIN depends on the operating system: it may return -1 or something else. L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and sockets usually returns -1. There is no C<systell> function. Use L<C<sysseek($fh, 0, 1)>|/sysseek FILEHANDLE,POSITION,WHENCE> for that. Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O operations) on a filehandle that has been manipulated by L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. Those functions ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not. =item telldir DIRHANDLE X<telldir> =for Pod::Functions get current seekpointer on a directory handle Returns the current position of the L<C<readdir>|/readdir DIRHANDLE> routines on DIRHANDLE. Value may be given to L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in a directory. L<C<telldir>|/telldir DIRHANDLE> has the same caveats about possible directory compaction as the corresponding system library routine. =item tie VARIABLE,CLASSNAME,LIST X<tie> =for Pod::Functions +5.002 bind a variable to an object class This C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, or C<TIEHASH>). Typically these are arguments such as might be passed to the L<dbm_open(3)> function of C. The object returned by the constructor is also returned by the L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful if you want to access other methods in CLASSNAME. Note that functions such as L<C<keys>|/keys HASH> and L<C<values>|/values HASH> may return huge lists when used on large objects, like DBM files. You may prefer to use the L<C<each>|/each HASH> L<perltie>, L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a module for you; you need to do that explicitly yourself. See L<DB_File> or the L<Config> module for interesting L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations. For further details see L<perltie>, L<C<tied>|/tied VARIABLE>. =item tied VARIABLE X<tied> =for Pod::Functions get a reference to the object underlying a tied variable Returns a reference to the object underlying VARIABLE (the same value that was originally returned by the L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable to a package.) Returns the undefined value if VARIABLE isn't tied to a package. =item time X<time> X<epoch> =for Pod::Functions return number of seconds since 1970 Returns the number of non-leap seconds since whatever time the system considers to be the epoch, suitable for feeding to L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>. L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, if you have L<gettimeofday(2)>, you may be able to use the L<C<syscall>|/syscall NUMBER, LIST> interface of Perl. See L<perlfaq8> for details. For date and time processing look at the many related modules on CPAN. For a comprehensive date and time representation look at the L<DateTime> module. =item times X<times> =for Pod::Functions return elapsed time for self and child processes Returns a four-element list giving the user and system times in seconds for this process and any exited children of this process. my ($user,$system,$cuser,$csystem) = times; In scalar context, L<C<times>|/times> returns C<$user>. Children's times are only included for terminated children. Portability issues: L<perlport/times>. =item tr/// =for Pod::Functions transliterate a string The transliteration operator. Same as L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>. See L<perlop/"Quote-Like Operators">. =item truncate FILEHANDLE,LENGTH X<truncate> =item truncate EXPR,LENGTH =for Pod::Functions shorten a file Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified length. Raises an exception if truncate isn't implemented on your system. Returns true if successful, L<C<undef>|/undef EXPR> on error. The behavior is undefined if LENGTH is greater than the length of the file. The position in the file of FILEHANDLE is left unchanged. You may want to call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the file. Portability issues: L<perlport/truncate>. =item uc EXPR X<uc> X<uppercase> X<toupper> =item uc =for Pod::Functions return upper-case version of a string Returns an uppercased version of EXPR. This is the internal function implementing the C<\U> escape in double-quoted strings. It does not attempt to do titlecase mapping on initial letters. See L<C<ucfirst>|/ucfirst EXPR> for that. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. This function behaves the same way under various pragmas, such as in a locale, as L<C<lc>|/lc EXPR> does. =item ucfirst EXPR X<ucfirst> X<uppercase> =item ucfirst =for Pod::Functions return a string with just the next letter in upper case Returns the value of EXPR with the first character in uppercase (titlecase in Unicode). This is the internal function implementing the C<\u> escape in double-quoted strings. If EXPR is omitted, uses L<C<$_>|perlvar/$_>. This function behaves the same way under various pragmas, such as in a locale, as L<C<lc>|/lc EXPR> does. =item umask EXPR X<umask> =item umask =for Pod::Functions set file creation mode mask Sets the umask for the process to EXPR and returns the previous value. If EXPR is omitted, merely returns the current umask. The Unix permission C<rwxr-x---> is represented as three sets of three bits, or three octal digits: C<0750> (the leading 0 indicates octal and isn't one of the digits). The L<C<umask>|/umask EXPR> value is such a number representing disabled permissions bits. The permission (or "mode") values you pass L<C<mkdir>|/mkdir FILENAME,MODE> or L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your umask, so even if you tell L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with permissions C<0777>, if your umask is C<0022>, then the file will actually be created with permissions C<0755>. If your L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't read, write, or execute), then passing L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a file with mode C<0640> (because C<0666 &~ 027> is C<0640>). Here's some advice: supply a creation mode of C<0666> for regular files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MODE>) and executable files. This gives users the freedom of choice: if they want protected files, they might choose process umasks of C<022>, C<027>, or even the particularly antisocial mask of C<077>. Programs should rarely if ever make policy decisions better left to the user. The exception to this is when writing files that should be kept private: mail files, web browser cookies, F<.rhosts> files, and so on. If L<umask(2)> is not implemented on your system and you are trying to restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), raises an exception. If L<umask(2)> is not implemented and you are not trying to restrict access for yourself, returns L<C<undef>|/undef EXPR>. Remember that a umask is a number, usually given in octal; it is I<not> a string of octal digits. See also L<C<oct>|/oct EXPR>, if all you have is a string. Portability issues: L<perlport/umask>. =item undef EXPR X<undef> X<undefine> =item undef =for Pod::Functions remove a variable or function definition Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using C<@>), a hash (using C<%>), a subroutine (using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> will probably not do what you expect on most predefined variables or DBM list values, so don't do that; see L<C<delete>|/delete EXPR>.. =item unlink LIST X<unlink> X<delete> X<remove> X<rm> X<del> =item unlink =for Pod::Functions remove one link to a file Deletes a list of files. On success, it returns the number of files it successfully deleted. On failure, it returns false and sets L<C<$!>|perlvar/$!> (errno): my $unlinked = unlink 'a', 'b', 'c'; unlink @goners; unlink glob "*.bak"; On error, L<C<unlink>|/unlink LIST> will not tell you which files it could not remove. If you want to know which files you could not remove, try them one at a time: foreach my $file ( @goners ) { unlink $file or warn "Could not unlink $file: $!"; } Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories unless you are superuser and the B<-U> flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Finally, using L<C<unlink>|/unlink LIST> on directories is not supported on many operating systems. Use L<C<rmdir>|/rmdir FILENAME> instead. If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>. =item unpack TEMPLATE,EXPR X<unpack> =item unpack TEMPLATE =for Pod::Functions convert binary structure into normal perl variables L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of L<C<pack>|/pack TEMPLATE,LIST>: it takes a string and expands it out into a list of values. (In scalar context, it returns merely the first value produced.) If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string. See L<perlpacktut> for an introduction to this function. The string is broken into chunks described by the TEMPLATE. Each chunk is converted separately to a value. Typically, either the string is a result of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string represent a C structure of some kind. The TEMPLATE has the same format as in the L<C<pack>|/pack TEMPLATE,LIST> function. Here's a subroutine that does substring: sub substr { my ($what, $where, $howmuch) = @_; unpack("x$where a$howmuch", $what); } and then there's sub ordinal { unpack("W",$_[0]); } # same as ord() In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, C<p> and C<P> formats should be used with care. Since Perl has no way of checking whether the value passed to L<C<unpack>|/unpack TEMPLATE,EXPR> L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros, or it may raise an exception. If the input string is longer than one described by the TEMPLATE, the remainder of that input string is ignored. See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes. =item unshift ARRAY,LIST X<unshift> =for Pod::Functions prepend more elements to the beginning of a list Does the opposite of a L<C<shift>|/shift ARRAY>. Or the opposite of a L<C<push>|/push ARRAY,LIST>, L<C<reverse>|/reverse LIST> to do the reverse. Starting with Perl 5.14, an experimental feature allowed L<C<unshift>|/unshift ARRAY,LIST> to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24. =item untie VARIABLE X<untie> =for Pod::Functions break a tie binding to a variable Breaks the binding between a variable and a package. (See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) Has no effect if the variable is not tied. =item use Module VERSION LIST X<use> X<module> X<import> =item use Module VERSION =item use Module LIST =item use Module =item use VERSION =for Pod::Functions load in a module at compile time and import its namespace Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package. It is exactly equivalent to BEGIN { require Module; Module->import( LIST ); } except that Module I<must> be a bareword. The importation can be made conditional by using the L<if> module. In the C<use VERSION> form, VERSION may be either a v-string such as v5.24.1, which will be compared to L<C<$^V>|perlvar/$^V> (aka $PERL_VERSION), or a numeric argument of the form 5.024001, which will be compared to L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than the version of the current Perl interpreter; Perl will not attempt to parse the rest of the file. Compare with L<C<require>|/require VERSION>, which can do a similar check at run time. Symmetrically, C<no VERSION> allows you to specify that you want a version of Perl older than the specified use v5.24.1; # compile time version check use 5.24.1; # ditto use 5.024_001; # ditto; older syntax compatible with perl 5.6 This is often useful if you need to check the current Perl version before L<C<use>|/use Module VERSION LIST>ing library modules that won't work with older versions of Perl. (We try not to do this more than we have to.) C<use VERSION> also lexically enables all features available in the requested version as defined by the L<feature> pragma, disabling any features not in the requested version's feature bundle. See L<feature>. Similarly, if the specified Perl version is greater than or equal to 5.12.0, strictures are enabled lexically as with L<C<use strict>|strict>. Any explicit use of C<use strict> or C<no strict> overrides C<use VERSION>, even if it comes before it. Later use of C<use VERSION> will override all behavior of a previous C<use VERSION>, possibly removing the C<strict> and C<feature> added by C<use VERSION>. C<use VERSION> does not load the F<feature.pm> or F<strict.pm> files. The C<BEGIN> forces the L<C<require>|/require VERSION> and L<C<import>|/import LIST> to happen at compile time. The L<C<require>|/require VERSION> makes sure the module is loaded into memory if it hasn't been yet. The L<C<import>|/import LIST> is not a builtin; it's just an ordinary static method call into the C<Module> package to tell the module to import the list of features back into the current package. The module can implement its L<C<import>|/import LIST> method any way it likes, though most modules just choose to derive their L<C<import>|/import LIST> method via inheritance from the C<Exporter> class that is defined in the L<C<Exporter>|Exporter> module. See L<Exporter>. If no L<C<import>|/import LIST> method can be found, then the call is skipped, even if there is an AUTOLOAD method. If you do not want to call the package's L<C<import>|/import LIST> method (for instance, to stop your namespace from being altered), explicitly supply the empty list: use Module (); That is exactly equivalent to BEGIN { require Module } If the VERSION argument is present between Module and LIST, then the L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in class Module with the given version as an argument: use Module 12.34; is equivalent to: BEGIN { require Module; Module->VERSION(12.34) } The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>, inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given version is larger than the value of the variable C<$Module::VERSION>. The VERSION argument cannot be an arbitrary expression. It only counts as a VERSION argument if it is a version number literal, starting with either a digit or C<v> followed by a digit. Anything that doesn't look like a version literal will be parsed as the start of the LIST. Nevertheless, many attempts to use an arbitrary expression as a VERSION argument will appear to work, because L<Exporter>'s C<import> method handles numeric arguments specially, performing version checks rather than treating them as things to export. Again, there is a distinction between omitting LIST (L<C<import>|/import LIST> called with no arguments) and an explicit empty LIST C<()> (L<C<import>|/import); Some of these pseudo-modules import semantics into the current block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike ordinary modules, which import symbols into the current package (which are effective through the end of the file). Because L<C<use>|/use Module VERSION LIST> takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a L<C<use>|/use Module VERSION LIST> inside the false branch of a conditional doesn't prevent it from being processed. If a module or pragma only needs to be loaded conditionally, this can be done using the L<if> pragma: use if $] < 5.008, "utf8"; use if WANT_WARNINGS, warnings => qw(all); There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration that unimports meanings imported by L<C<use>|/use Module VERSION LIST>, i.e., it calls C<< Module->unimport(LIST) >> instead of L<C<import>|/import LIST>. It behaves just as L<C<import>|/import LIST> does with VERSION, an omitted or empty LIST, or no unimport method being found. no integer; no strict 'refs'; no warnings; Care should be taken when using the C<no VERSION> form of L<C<no>|/no MODULE VERSION LIST>. It is I<only> meant to be used to assert that the running Perl is of a earlier version than its argument and I<not> to undo the feature-enabling side effects of C<use VERSION>. See L<perlmodlib> for a list of standard modules and pragmas. See L<perlrun|perlrun/-m[-]module> for the C<-M> and C<-m> command-line options to Perl that give L<C<use>|/use Module VERSION LIST> functionality from the command-line. =item utime LIST X<utime> =for Pod::Functions set a file's last access and modify times Changes L<touch(1)> command when the files I<already exist> and belong to the user running the program: #!/usr/bin/perl my $atime = my $mtime = time; utime $atime, $mtime, @ARGV; Since Perl 5.8.0, if the first two elements of the list are L<C<undef>|/undef EXPR>, the L<touch(1)> command will in fact normally use this form instead of the one shown in the first example. Passing only one of the first two elements as L<C<undef>|/undef EXPR> is equivalent to passing a 0 and will not have the effect described when both are L<C<undef>|/undef EXPR>. This also triggers an uninitialized warning. On systems that support L<futimes(2)>, you may pass filehandles among the files. On systems that don't support L<futimes(2)>, passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. Portability issues: L<perlport/utime>. =item values HASH X<values> =item values ARRAY =for Pod::Functions return a list of the values in a hash<values>|/values HASH> resets the HASH or ARRAY's internal iterator (see L<C<each>|/each HASH>) before yielding the values. In particular, calling L<C<values>|/values HASH> in void context resets the iterator with no other overhead. Apart from resetting the iterator, C<values @array> in list context is the same as plain C<@array>. (We recommend that you use void context C<keys @array> for this, but reasoned that taking C L<C<values>|/values<keys>|/keys HASH>, L<C<each>|/each HASH>, and L<C<sort>|/sort SUBNAME LIST>. =item vec EXPR,OFFSET,BITS X<vec> X<bit> X<bit vector> =for Pod::Functions test or set particular bits in a string). If BITS is 8, "elements" coincide with bytes of the input string. If BITS is 16 or more, bytes of the input string are grouped into chunks of size BITS/8, and each group is converted to a number as with L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with big-endian formats C<n>/C<N> (and analogously for BITS==64). See L<C<pack>|/pack TEMPLATE,LIST> for details. If bits is 4 or less, the string is broken into bytes, then the bits of each byte are broken into 8/BITS groups. Bits of a byte are numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, breaking the single input byte C<chr(0x36)> into two groups gives a list C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. L<C<vec>|/vec EXPR,OFFSET,BITS>), L<C<vec>|/vec EXPR,OFFSET,BITS> tries to convert it to use a one-byte-per-character internal representation. However, if the string contains characters with values of 256 or higher, a fatal error will occur. Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be manipulated with the logical operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit vector operation is desired when both operands are strings. See L<perlop/"Bitwise String Operators">. The following code will build up an ASCII string saying C< =item wait X<wait> =for Pod::Functions wait for any child process to die Behaves like L<wait(2)> on your system: it waits for a child process to terminate and returns the pid of the deceased process, or C<-1> if there are no child processes. The status is returned in L<C<$?>|perlvar/$?> and L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. Note that a return value of C<-1> could mean that child processes are being automatically reaped, as described in L<perlipc>. If you use L<C<wait>|/wait> in your handler for L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>. See L<perlipc> for details. Portability issues: L<perlport/wait>. =item waitpid PID,FLAGS X<waitpid> =for Pod::Functions wait for a particular child process to die Waits for a particular child process to terminate and returns the pid of the deceased process, or C<-1> if there is no such child process. A non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if there are child processes matching PID but none have terminated yet. The status is returned in L<C<$?>|perlvar/$?> and L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. A PID of C<0> indicates to wait for any child process whose process group ID is equal to that of the current process. A PID of less than C<-1> indicates to wait for any child process whose process group ID is equal to -PID. A PID of L<POSIX/WAIT>). Non-blocking wait is available on machines supporting either the L<waitpid(2)> or L<wait4(2)> syscalls. However, waiting for a particular pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the system call by remembering the status values of processes that have exited but have not been harvested by the Perl script yet.) Note that on some systems, a return value of C<-1> could mean that child processes are being automatically reaped. See L<perlipc> for details, and for other examples. Portability issues: L<perlport/waitpid>. =item wantarray X<wantarray> X<context> =for Pod::Functions get void vs scalar vs list context of current subroutine call Returns true if the context of the currently executing subroutine or L<C<eval>|/eval EXPR>"; L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file, in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or in a C<DESTROY> method. This function should have been named wantlist() instead. =item warn LIST X<warn> X<warning> X<STDERR> =for Pod::Functions print debugging info Emits a warning, usually by printing it to C<STDERR>. C<warn> interprets its operand LIST in the same way as C<die>, but is slightly different in what it defaults to when LIST is empty or makes an empty string. If it is empty and L<C<$@>|perlvar/$@> already contains an exception value then that value is used after appending C<"\t...caught">. If it is empty and C<$@> is also empty then the string C<"Warning: Something's wrong"> is used. as it sees fit (like, for instance, converting it into a L<C<die>|/die LIST>). Most handlers must therefore arrange to actually display the warnings that they are not prepared to deal with, by calling L<C<warn>|/warn LIST> again in the handler. Note that this is quite safe and will not produce an endless loop, since C<__WARN__> hooks are not called from inside one. You will find this behavior is slightly different from that of L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the error text, but can instead call L<C<die>|/die LIST> again to change it). Using a L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries and for more examples. See the L<Carp> module for other kinds of warnings using its C<carp> and C<cluck> functions. =item write FILEHANDLE X<write> =item write EXPR =item write =for Pod::Functions print a picture record Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, using the format associated with that file. By default the format for a file is the one having the same name as the filehandle, but the format for the current output channel (see the L<C<select>|/select FILEHANDLE> function) may be set explicitly by assigning the name of the format to the L<C<$~>|perlvar/$~> variable. C<_TOP> appended, or C<top> in the current package if the former does not exist. This would be a problem with autovivified filehandles, but it may be dynamically set to the format of your choice by assigning the name to the L<C<$^>|perlvar/$^> variable while that filehandle is selected. The number of lines remaining on the current page is in variable L<C<$->|perlvar/$->, which can be set to C<0> to force a new page. If FILEHANDLE is unspecified, output goes to the current default output channel, which starts out as STDOUT but may be changed by the L<C<select>|/select FILEHANDLE> operator. If the FILEHANDLE is an EXPR, then the expression is evaluated and the resulting string is used to look up the name of the FILEHANDLE at run time. For more on formats, see L<perlform>. Note that write is I<not> the opposite of L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>. Unfortunately. =item y/// =for Pod::Functions transliterate a string The transliteration operator. Same as L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>. See L<perlop/"Quote-Like Operators">. =back =head2 Non-function Keywords by Cross-reference =head3 perldata =over =item __DATA__ =item __END__ These keywords are documented in L<perldata/"Special Literals">. =back =head3 perlmod =over =item BEGIN =item CHECK =item END =item INIT =item UNITCHECK These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. =back =head3 perlobj =over =item DESTROY This method keyword is documented in L<perlobj/"Destructors">. =back =head3 perlop =over =item and =item cmp =item eq =item ge =item gt =item le =item lt =item ne =item not =item or =item x =item xor These operators are documented in L<perlop>. =back =head3 perlsub =over =item AUTOLOAD This keyword is documented in L<perlsub/"Autoloading">. =back =head3 perlsyn =over =item else =item elsif =item for =item foreach =item if =item unless =item until =item while These flow-control keywords are documented in L<perlsyn/"Compound Statements">. =item elseif The "else if" keyword is spelled C<elsif> in Perl. There's no C<elif> or C<else if> either. It does parse C<elseif>, but only to warn you about not using it. See the documentation for flow-control keywords in L<perlsyn/"Compound Statements">. =back =over =item default =item given =item when These flow-control keywords related to the experimental switch feature are documented in L<perlsyn/"Switch Statements">. =back =cut
http://web-stage.metacpan.org/release/perl/source/pod/perlfunc.pod
CC-MAIN-2021-10
en
refinedweb
Data Exploration Case Study: Credit Default Want to share your content on python-bloggers? click here. Exploratory data analysis is the main task of a Data Scientist with as much as 60% of their time being devoted to this task. As such, the majority of their time is spent on something that is rather boring compared to building models. This post will provide a simple example of how to analyze a dataset from the website called Kaggle. This dataset is looking at how is likely to default on their credit. The following steps will be conducted in this analysis. - Load the libraries and dataset - Deal with missing data - Some descriptive stats - Normality check - Model development This is not an exhaustive analysis but rather a simple one for demonstration purposes. The dataset is available here Load Libraries and Data Here are some packages we will need import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from sklearn import tree from scipy import stats from sklearn import metrics You can load the data with the code below df_train=pd.read_csv('/application_train.csv') You can examine what variables are available with the code below. This is not displayed here because it is rather long df_train.columns df_train.head() Missing Data I prefer to deal with missing data first because missing values can cause errors throughout the analysis if they are not dealt with immediately. The code below calculates the percentage of missing data in each column. total=df_train.isnull().sum().sort_values(ascending=False) percent=(df_train.isnull().sum()/df_train.isnull().count()).sort_values(ascending=False) missing_data=pd.concat([total,percent],axis=1,keys=['Total','Percent']) missing_data.head() Total Percent COMMONAREA_MEDI 214865 0.698723 COMMONAREA_AVG 214865 0.698723 COMMONAREA_MODE 214865 0.698723 NONLIVINGAPARTMENTS_MODE 213514 0.694330 NONLIVINGAPARTMENTS_MEDI 213514 0.694330 Only the first five values are printed. You can see that some variables have a large amount of missing data. As such, they are probably worthless for inclusion in additional analysis. The code below removes all variables with any missing data. pct_null = df_train.isnull().sum() / len(df_train) missing_features = pct_null[pct_null > 0.0].index df_train.drop(missing_features, axis=1, inplace=True) You can use the .head() function if you want to see how many variables are left. Data Description & Visualization For demonstration purposes, we will print descriptive stats and make visualizations of a few of the variables that are remaining. round(df_train['AMT_CREDIT'].describe()) Out[8]: count 307511.0 mean 599026.0 std 402491.0 min 45000.0 25% 270000.0 50% 513531.0 75% 808650.0 max 4050000.0 sns.distplot(df_train['AMT_CREDIT'] round(df_train['AMT_INCOME_TOTAL'].describe()) Out[10]: count 307511.0 mean 168798.0 std 237123.0 min 25650.0 25% 112500.0 50% 147150.0 75% 202500.0 max 117000000.0 sns.distplot(df_train['AMT_INCOME_TOTAL'] I think you are getting the point. You can also look at categorical variables using the groupby() function. We also need to address categorical variables in terms of creating dummy variables. This is so that we can develop a model in the future. Below is the code for dealing with all the categorical variables and converting them to dummy variable’s df_train.groupby('NAME_CONTRACT_TYPE').count() dummy=pd.get_dummies(df_train['NAME_CONTRACT_TYPE']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['NAME_CONTRACT_TYPE'],axis=1) df_train.groupby('CODE_GENDER').count() dummy=pd.get_dummies(df_train['CODE_GENDER']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['CODE_GENDER'],axis=1) df_train.groupby('FLAG_OWN_CAR').count() dummy=pd.get_dummies(df_train['FLAG_OWN_CAR']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['FLAG_OWN_CAR'],axis=1) df_train.groupby('FLAG_OWN_REALTY').count() dummy=pd.get_dummies(df_train['FLAG_OWN_REALTY']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['FLAG_OWN_REALTY'],axis=1) df_train.groupby('NAME_INCOME_TYPE').count() dummy=pd.get_dummies(df_train['NAME_INCOME_TYPE']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['NAME_INCOME_TYPE'],axis=1) df_train.groupby('NAME_EDUCATION_TYPE').count() dummy=pd.get_dummies(df_train['NAME_EDUCATION_TYPE']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['NAME_EDUCATION_TYPE'],axis=1) df_train.groupby('NAME_FAMILY_STATUS').count() dummy=pd.get_dummies(df_train['NAME_FAMILY_STATUS']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['NAME_FAMILY_STATUS'],axis=1) df_train.groupby('NAME_HOUSING_TYPE').count() dummy=pd.get_dummies(df_train['NAME_HOUSING_TYPE']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['NAME_HOUSING_TYPE'],axis=1) df_train.groupby('ORGANIZATION_TYPE').count() dummy=pd.get_dummies(df_train['ORGANIZATION_TYPE']) df_train=pd.concat([df_train,dummy],axis=1) df_train=df_train.drop(['ORGANIZATION_TYPE'],axis=1) You have to be careful with this because now you have many variables that are not necessary. For every categorical variable you must remove at least one category in order for the model to work properly. Below we did this manually. df_train=df_train.drop(['Revolving loans','F','XNA','N','Y','SK_ID_CURR,''Student','Emergency','Lower secondary','Civil marriage','Municipal apartment'],axis=1) Below are some boxplots with the target variable and other variables in the dataset. There is a clear outlier there. Below is another boxplot with a different variable It appears several people have more than 10 children. This is probably a typo. Below is a correlation matrix using a heatmap technique corrmat=df_train.corr() f,ax=plt.subplots(figsize=(12,9)) sns.heatmap(corrmat,vmax=.8,square=True) The heatmap is nice but it is hard to really appreciate what is happening. The code below will sort the correlations from least to strongest, so we can remove high correlations. c = df_train.corr().abs() s = c.unstack() so = s.sort_values(kind="quicksort") print(so.head()) FLAG_DOCUMENT_12 FLAG_MOBIL 0.000005 FLAG_MOBIL FLAG_DOCUMENT_12 0.000005 Unknown FLAG_MOBIL 0.000005 FLAG_MOBIL Unknown 0.000005 Cash loans FLAG_DOCUMENT_14 0.000005 The list is to long to show here but the following variables were removed for having a high correlation with other variables. df_train=df_train.drop(['WEEKDAY_APPR_PROCESS_START','FLAG_EMP_PHONE','REG_CITY_NOT_WORK_CITY','REGION_RATING_CLIENT','REG_REGION_NOT_WORK_REGION'],axis=1) Below we check a few variables for homoscedasticity, linearity, and normality using plots and histograms sns.distplot(df_train['AMT_INCOME_TOTAL'],fit=norm) fig=plt.figure() res=stats.probplot(df_train['AMT_INCOME_TOTAL'],plot=plt) This is not normal sns.distplot(df_train['AMT_CREDIT'],fit=norm) fig=plt.figure() res=stats.probplot(df_train['AMT_CREDIT'],plot=plt) This is not normal either. We could do transformations, or we can make a non-linear model instead. Model Development Now comes the easy part. We will make a decision tree using only some variables to predict the target. In the code below we make are X and y dataset. X=df_train[['Cash loans','DAYS_EMPLOYED','AMT_CREDIT','AMT_INCOME_TOTAL','CNT_CHILDREN','REGION_POPULATION_RELATIVE']] y=df_train['TARGET'] The code below fits are model and makes the predictions clf=tree.DecisionTreeClassifier(min_samples_split=20) clf=clf.fit(X,y) y_pred=clf.predict(X) Below is the confusion matrix followed by the accuracy print (pd.crosstab(y_pred,df_train['TARGET'])) TARGET 0 1 row_0 0 280873 18493 1 1813 6332 accuracy_score(y_pred,df_train['TARGET']) Out[47]: 0.933966589813047 Lastly, we can look at the precision, recall, and f1 score print(metrics.classification_report(y_pred,df_train['TARGET'])) precision recall f1-score support 0 0.99 0.94 0.97 299366 1 0.26 0.78 0.38 8145 micro avg 0.93 0.93 0.93 307511 macro avg 0.62 0.86 0.67 307511 weighted avg 0.97 0.93 0.95 307511 This model looks rather good in terms of accuracy of the training set. It actually impressive that we could use so few variables from such a large dataset and achieve such a high degree of accuracy. Conclusion Data exploration and analysis is the primary task of a data scientist. This post was just an example of how this can be approached. Of course, there are many other creative ways to do this but the simplistic nature of this analysis yielded strong results Want to share your content on python-bloggers? click here.
https://python-bloggers.com/2019/02/data-exploration-case-study-credit-default/
CC-MAIN-2021-10
en
refinedweb
just make sure that whenever you insert a node you set next to the next node and previous to the previous node. They will also commonly keep a tail and head pointer so that traversal may start at either end of the list. Doubly Linked List Nodes A doubly linked list node would look like this: struct dllnode { Arbitrary Data Portion struct dllnode *next; struct dllnode *previous; }; It contains a data portion and a pointer to both the next and previous nodes in the list sequence allowing for two-way traversal. Creating A Doubly Linked List When creating a doubly linked list, we want to be able to go both ways as well as be able to start at either end of the list when traversing it. As mentioned earlier, we use a both a tail and a head pointer to provide this functionality. Checking for head being NULL is sufficient for checking for an empty list. if (head == NULL) { //This node becomes the first and last node in the list. newnode->previous = NULL; newnode->next = NULL; head = newnode; tail = head; } Pretty much the same as we have done throughout this tutorial with the singularly linked lists, with the addition of the previous pointer needing to be set to NULL and the tail also being equal to the new node. Inserting Nodes Same as linear singularly linked lists, we can add at the beginning, middle, or end of a doubly linked list. Placing a node at the beginning of a doubly linked list is quite simple but an empty and nonempty must be handled differently. When the list is empty all you have to do is create the new node, set its next and previous pointers to NULL, and point the head and tail pointers to it. We already saw the code for this in the last section. Inserting a new node at the beginning of a nonempty doubly linked list is a little tricky, but not impossible. First you create your new node and set its previous pointer to NULL, but the next pointer to the current head. Then set the current head’s previous pointer to the new node being inserted to move the old head one up in the list. Now all you have to do is point head at the new node and you are done. In code it should look something like this newnode->previous = NULL; newnode->next = head; head->previous = newnode; head = newnode; Insertion of a new node at the end of the list is quite similar although we use the tail pointer as a reference instead of the head pointer. Since the empty list case here is identical to the empty list case above for insert at beginning we will skip it. To place a node at the end of the nonempty list you create the new node, set its next pointer to NULL and its previous pointer to the current tail. Then set the current tail’s next pointer to the new node. Now point tail to the new node which you have inserted a node at the back of the list. Although it’s not in our example, here is a code snippet newnode->next = NULL; newnode->previous = tail; tail->next = newnode; tail = newnode; Note the similarity to the sample for insertion at the beginning. Here’s the fun part, this is the greatest feature of the doubly linked list. It’s actually so simple though, you may be disappointed. Forward traversal is identical to singly linked list traversal. Seriously, there is no difference. This should look familiar. if (head != NULL) { currentnode = head; while (currentnode->next != NULL) { currentnode = currentnode->next; } } With that in mind, you would think that going the other way would be the same but with the tail pointer. You would be correct. if (tail != NULL) { currentnode = tail; while (currentnode->previous != NULL) { currentnode = currentnode->previous; } } {mospagebreak title=Doubly Linked Lists Example} A common thing to do in game programming is to keep a list of objects currently on the screen. One reason is for updating the screen to make them appear to move. Linked lists are perfectly suited to this purpose because of their dynamic nature. Let’s make a list of the x and y coordinates of all objects currently displayed on a screen for an arbitrary game. The sample has one function for adding nodes to the front of the list. It takes into account the empty and nonempty list cases we learned about above. Then it creates five objects that have an x and y coordinate, and adds the nodes to the list by calling the addnode function and passing it the newly created node, thus making the last node added at the beginning of the list and the first node added the end. After the list is created and all the game objects coordinates are known, we traverse the list from the beginning to the end and print all the x and y values for each object. Then we do the same, but start from the tail and go back to the head. #include <stdio.h> #include <stdlib.h> struct dllnode { int x; int y; struct dllnode *next; struct dllnode *previous; }; //Here's the doubly linked list root pointers. struct dllnode *head = NULL; struct dllnode *tail = NULL; void addnode(struct dllnode *newnode) { if (head == NULL) { //This node becomes the first and last node in the list. newnode->previous = NULL; newnode->next = NULL; head = newnode; tail = head; } else { //List is not empty, insert at front of list. newnode->previous = NULL; newnode->next = head; head->previous = newnode; head = newnode; } } void main() { int i; int x, y; struct dllnode *current; //Create 5 objects in a diagonal line across the screen from eachother. for (i = 0; i < 5; i++) { struct dllnode *newnode; x = y = i; newnode = (struct dllnode *)malloc(sizeof(struct dllnode)); newnode->x = x; newnode->y = y; addnode(newnode); } //Traverse the list and print the current position of each object. current = head; i = 1; while (current != NULL) { printf("Object %d: ", i); printf("n"); printf(" x position: %d", current->x); printf("n"); printf(" y position: %d", current->y); printf("n"); i++; current = current->next; } //Do the same but start at the back of the list. current = tail; i = 1; while (current != NULL) { printf("Object %d: ", i); printf("n"); printf(" x position: %d", current->x); printf("n"); printf(" y position: %d", current->y); printf("n"); i++; current = current->previous; } } . - C Programming – Data Types : Part 2 - C Circular Linked Lists - C Doubly Linked Lists - TSR in C – An Introduction - Concept of Pixel in C Graphics - Call by Value and Call by Reference - C Language – The Preprocessor - C Programming – File management in C - C Programming – Linked Lists - C Programming – Dynamic Memory allocation - C Programming – Pointers - C Programming – Structures and Unions - C Programming – Functions (Part-I) - C Programming – Functions (Part-II) - C Programming – Handling of Character String - C Programming – Arrays - C Programming – Decision Making – Looping - C Programming – Decision Making – Branching - C Programming – Managing Input and Output Operations - C Programming – Expressions - C Programming – Operators - C Programming – Data Types : Part 1 - C Programming – Constants and Identifiers - C Programming – An Overview
http://www.exforsys.com/tutorials/c-language/doubly-linked-lists.html
CC-MAIN-2015-22
en
refinedweb
More OCI Relational Functions, 50 of 106 Registers a callback for message notification. ub4 OCISubscriptionRegister ( all of the following attributes set: Otherwise, an error will be returned. One of attributes must also be set. When a notification is received for the registration denoted by subscrhpp[i], either the user-defined callback function (OCI_ATTR_SUBSCR_CBACK) set for subscrhpp[i] will be invoked with the context (OCI_ATTR_SUBSCR_CTX) set for subscrhpp[i], or an e-mail will be sent to (OCI_ATTR_SUBSCR_RECPT) set for subscrhpp[i], or the PL/SQL procedure (OCI_ATTR_SUBSCR_RECPT) set for subscrhpp[i], will be invoked in the database, provided the subscriber of subscrhpp[i] has the appropriate permissions on the procedure. The number of elements in the subscription handle array. An error handle you can pass to OCIErrorGet() for diagnostic information in the event of an error. Call-specific mode. Valid values: Whenever a new client process comes up, or an old one goes down and comes back up, it needs to register for all subscriptions of interest. If the client stays up and the server first goes down and then comes back up, the client will continue to receive notifications for registrations that are DISCONNECTED. However, the client will not receive notifications for CONNECTED registrations as they will be lost once the server goes down and comes back up. This call is invoked for registration to a subscription which identifies the subscription name of interest and the associated callback to be invoked. Interest in several subscriptions can be registered at one time. This interface is only valid for the asynchronous mode of message delivery. In this mode, a subscriber issues a registration call which specifies a callback. When messages are received that match the subscription criteria, the callback is invoked. The callback may then issue an explicit message_receive (dequeue) to retrieve the message. The user must specify a subscription handle at registration time with the namespace attribute set to OCI_SUBSCR_NAMESPACE_AQ. The subscription name is the string 'SCHEMA.QUEUE' if the registration is for a single consumer queue and 'CONSUMER_NAME:SCHEMA.QUEUE' if the registration is for a multi-consumer queue. The string should be in uppercase. Each namespace will have its own privilege model. If the user performing the register is not entitled to register in the namespace for the specified subscription, an error is returned. OCIAQListen(), OCISvcCtxToLda(), OCISubscriptionEnable(), OCISubscriptionPost(), OCISubscriptionUnRegister()
http://docs.oracle.com/cd/B10501_01/appdev.920/a96584/oci16m50.htm
CC-MAIN-2015-22
en
refinedweb
03 December 2008 04:40 [Source: ICIS news] SINGAPORE (ICIS news)--The anti-government protests in Thailand ended Wednesday morning with a generally calm atmosphere setting in, easing earlier fears over the worsening business climate in the country, local business operators said. ?xml:namespace> “Everything in ?xml:namespace> The People's But the political crisis has hurt the country’s risk and credit standing and it will be some time before full business confidence can be regained, a source at a local petrochemical producer said. Months of clashes between anti- and pro-government forces caused several fatalities, and took a toll on Two main airports – the Cargo services at the Things should remain calm for the moment, and that services should resume back to normal, said another source. “I think the (economical) pressure is too much should they decide to close the airport again, no matter (if it’s) red or yellow,” said a petrochemicals trader
http://www.icis.com/Articles/2008/12/03/9176395/Thailand-sees-respite-after-protests-end.html
CC-MAIN-2015-22
en
refinedweb
24 May 2012 11:35 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> Sepahan Oil shut the plant in the first week of May for maintenance works and was expected to restart the unit in the first week of June, they said. The company can produce Group I SN500, engine oils, industrial lubricants, automobile gear oils, greases and anti-freeze, paraffin, heavy slack wax and rubber processing oil
http://www.icis.com/Articles/2012/05/24/9563173/Irans-Sepahan-Oil-extends-turnaround-at-Isfahan-base-oils.html
CC-MAIN-2015-22
en
refinedweb
I've been trying to figure this out all night. I started on this sudoku program and for some reason it's in an infinite loop. Basically, I'm using Math.random() to generate integers and collecting them into a two dimensional array that is 9 X 9. Then I use a method to verify that the numbers in the array are unique by row and by column (and soon to be box) if I can figure this out. It seems to work just fine when I only check either row or column at a time, but not both. I debugged and it seems to be doing what it's supposed to be doing by breaking away from the for loop when the value equals a value already in its row or column, then it generates a new random integer, and goes back.. but I can't tell why it says it changes, but gets stuck on the same value. public class TestSudokuLogic { public static int counter = 0; public static void main(String[] args) { //create grid int[][] grid = new int[9][9]; for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[row].length; col++) { boolean valid = false; while (!valid) { grid[row][col] = getRandomInt(); valid = checkRandomInt(grid, row, col); counter++; System.out.println(counter); } } } printArray(grid); } public static boolean checkRandomInt(int[][] grid, int row, int col) { for (int i = 0; i < col; i++) if (grid[row][col] == grid[row][i]) //checks each col in row (rows are unique 1-9) return false; for (int j = 0; j < row; j++) if (grid[row][col] == grid[j][col]) //checks each row in col (cols are unique 1-9) return false; return true; } public static int getRandomInt() { int r = 0; while(r < 1) r = (int) (Math.random() * 10); return r; } public static void printArray(int[][] a) { for (int row = 0; row < a.length; row++) { for (int col = 0; col < a[row].length; col++) System.out.print(a[row][col] + " "); System.out.println(); } } }
http://www.javaprogrammingforums.com/whats-wrong-my-code/12510-im-creating-sudoku-program-somehow-infinite-loops.html
CC-MAIN-2015-22
en
refinedweb
Here are my raw notes. Friday – 1:45pm – Advanced Security Topics Paul McMillan Hashing Common Crpyo Hashes: md5, sha1, sha256 If you’re typing md5 into your code, you’re probably doing it wrong Message signing – did the message come from who i expect it to come from? How can we be attacked? Did this file get corrupted When doing a basic md5 hash, we check that hash that we have. Where did we get that hash? If we know that the md5 hash that we have is good, then we’re pretty secure – hard to generate a hash collision (reasonably hard problem). For message signing, it’s diferent. H = md5(secret + message) NO! An attacker can generate: md5(secret + message) == md5(secret + message + junk + attacker_message) maybe your app is strict about format and this will result in an error If an attacker can, given one message, sign a different message, it’s not good. Solution: use HMAC HMAC is essentially: hash(secret + hash(message)) use hmac lib and salt your secret key. salt = ‘session_cookie_signing’ hmac.new(salt + secret_key, msg) If you don’t salt based on the use in each area of your app, then an attacker could take a signed message from one area and use it in another area. Don’t use MD5! Avoid SHA1. Use SHA256 (for now). There’s also SHA512, but on 32-bit machines can have serious performance problems. SHA256 is similarly secure. Encryption You should not be implementing encryption, in almost all cases. Why do you need it? If when protecting data in transit, use SSL/TLS. Protecting data at rest: use underlying OS. There are already good solutions for this. Random numbers Generating a secret key: import random secret = ”.join(random.choice(allowed_cars) for i in range(length)) Don’t do that! Default random in python is predictable. Solution: from random import SystemRandom() will use entropy data from various sources. But… you don’t know how much entropy is actually there. In some cases this can be a real problem. i.e. if you’re running at the start of a virtualized machine, there’s not a lot of entropy yet. It’ll run out of entropy and give you predictable numbers. Timing attacks message, sig = ‘|’.split(incoming) sig2 = hmac.new(salt + secret_key, message) if sig == sig2: do_something() == is the problem because string comparison will short circuit when there isn’t a match. If you take a lot of message, it’s possible to figure out a long string, one character at a time. Very small difference but it’s statistically decidable in hundreds-to-millions of messages depending on the app. Over the internet there’s a lot of latency so it’s impractical. But a lot of apps are virtualized – I’m on the same machine as you, can ask you lots of questions really fast. Solution: use a constant-time compare function. check same length, then do an operation of every set of characters. if len(val1) != len(val2): return False result = 0 for x, y in zip(val1, val2): result |= ord(x) ^ ord(y) return result == 0 Pickle Loading an untrusted string is equivalent to running eval() on that string! Use JSON or something, not pickle, for untrusted data. If you must use pickle, sign and verify it… but use JSON if possible to avoid complexity of signing. “You would think that…” No. Always verify your assumptions. For example…. pip install Django – I trust the django authors – i trust the people who run pypi – i trust the people who wrote pip – pip verifies the md5 hashes of packages – packages on pypi can be pgp signed – pypi uses ssl So I’m safe right? Of course not… all of these things require you to trust everyone on the internet. – pip verifies md5 hash — but it downloaded the hash from the same page it downloaded the package from, and that’s in plain text. if someone can change the code, they can change the hash. – pgp signed — no tool currently checks pgp – pypi uses ssl — not really PyPi – – untrusted (by default) certificate – plaintext by default – easy_install and pip don’t use the SSL Python doesn’t make it easy to check SSL certs. This is a problem. You’d think that when you open a HTTPS url you’d get encryption… and you do, but it doesn’t verify the certificate. Recommendation: use the ‘requests’ library. It *does* do the cert check by default. Demo DNS lookup – UDP. Computer will trust the first response it gets back. So on open wifi, easy for someone to spoof your dns and say that pypi.org is whatever they want. “sudo pip install certifi” Runs setup.py — so anyone can put code in setup.py and then it’ll run on your computer as root. PyPI offers everything necessary to make this not possible, but we don’t use it. How do we help the python community? – use the requests library – if you’re using hashes, use hmac. Q&A Q: Putting packages on pypi — is there a better way to do this at a release-process level? A: It’s a hard problem. If you put something in the package that verifies the package is what you expected, that’s no good. If you provide something alongside the package, it’s the same problem. Signed PGP files — it’s great, but noone checks this. We need to make the tools. Q: How much of this is actually new? How much of this is actually security-specific? The HMAC stuff, for example, is all “don’t reinvent the wheel”, and security is the context. Are there cases where you have to do something because of a security reason? What about the signing stuff – that’s been seen before too. A: None of this is new. But as a community we pretend it doesn’t exist. The end result of most conversations about this are “it’s not pypi’s problem, users should be doing something secure.” But that’s not the way to think about this: should make the way that’s obvious the right thing. Q: But right now it’s more work to do it the right way, so it’s bad engineering on the part of users. A: Higher-level constructs tend to make code more secure. But have to use Q: Why didn’t the demo work? Issues with the wifi – security features? A: Script was set up for WPA2 network, but this is an older network. Q: Timing attack – constant-time string compare is not the obvious way to do it… A: Have to think about security implications. Python should have a constant-time compare function. Q: Constant-time compare function probably has problems because of mallocs. Don’t think it’s possible to really have a constant time compare function. A: Is possible to get very very close. Not possible in C either but can get close. Q: Suggestions for downloading packages for doing releases? A: Most large software projects have a system for finalizing packages. Unusual to install things directly from the cheese shop. Pip team is sprinting on adding auth. Q: crate.io – what does this actually do to increase security if installers are still the same? A: Storing sha256 hashes. Storing hashes long-term so you have a history of what files were there. In PyPI things can be changed without you noticing. crate will maintain a history. Can you reply with me the online database that checks its database for md5 hashes to decrypt them? Pingback: My experience note-taking at PyCon 2012 « Brian Rue’s Blog Mole Remover Techniques To Make Use Of Everything is very open with a precise explanation of the issues. It was truly informative. Your website is very helpful. Thanks for sharing! For latest information you have to visit world-wide-web and on internet I found this site as a finest web page for latest updates. Fantastic beat ! I wish to apprentice while you amend your web site, how can i subscribe for a blog web site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea
https://brianrue.wordpress.com/2012/03/09/pycon-2012-notes-advanced-security-topics/
CC-MAIN-2015-22
en
refinedweb
getattr Discussion in 'Python' started by Srikanth Mandava, Using getattr to access inherited methodsdaishi, Jul 25, 2003, in forum: Python - Replies: - 0 - Views: - 627 - daishi - Jul 25, 2003 Confused about hasattr/getattr/namespacesBrian Roberts, Feb 29, 2004, in forum: Python - Replies: - 2 - Views: - 346 - Bob Ippolito - Feb 29, 2004 getattr() in default namespace.SimonVC, Apr 8, 2004, in forum: Python - Replies: - 3 - Views: - 985 - SimonVC - Apr 9, 2004 getattr() woesThomas Rast, Dec 29, 2004, in forum: Python - Replies: - 4 - Views: - 679 - Kamilche - Dec 31, 2004 What's the difference between built-in func getattr() and normal call of a func of a classJohnny, Aug 23, 2005, in forum: Python - Replies: - 3 - Views: - 539 - Robert Kern - Aug 23, 2005
http://www.thecodingforums.com/threads/getattr.328493/
CC-MAIN-2015-22
en
refinedweb
Just say i want to read a amount of words, lines, and characters in a .dat file. Im thinking my string algoritim would look something like this: ------------------------------------------ //for words, lines, characters count read file, and then out_stream or cout results //in_stream is already connected to words.dat #include <iostream> #include <fstream> #include <string> #include <cstring> int words, lines, characters; ifstream in_stream; ofstream out_stream; while(!in_stream.eof()) { //chracter readout, and cout result characters = strlen("words.dat"); out_stream << "words.dat has " << characters << " characters."; //lines readout, and cout result //words readout, and cout result } I cant think of an algoritum for lines, and words. I do have idea of lines, i think its something like this "\n" , line++ . I think words is something like this "\0" word++ . The thing is, i can't translate it into code form, do I use strlen(), or getline()??? Please help, or suggestion...Thank You!
http://cboard.cprogramming.com/cplusplus-programming/4827-need-help-string-read.html
CC-MAIN-2015-22
en
refinedweb
Our System V service runs a daemon that runs the import command. Running our service by sudo service myservice start seems to start the service but when it comes to take a screenshot, import does not work. The only way to grab a screenshot is starting service with /etc/init.d/myservice start. Following that, we are able to grab the screenshot with import command. sudo service myservice /etc/init.d/myservice Any ideas? There is no straight forward answer to your question, other than "it depends on the environment" i.e. the GNU / Linux distribution. Before I go into semi-relevant details, you should know that the reason why sudo service import-image-service does not work is because the import command does not have enough information about the environment to know where and how to take the screenshot. Reading man sudo reveals: sudo service import-image-service DESCRIPTION sudo allows a permitted user to execute a command as the superuser or another user, as specified by the security policy. This is somewhat cryptic and learning about this "security policy" is fun, but perhaps not one of your favourite activities. I give you my word that this means commands started with sudo run in an isolated environment. In contrast, /etc/init.d/myservice works because environment-setup-policy takes steps to configure some sane defaults such as export DISPLAY=:0.0. You will have to investigate the intricacies of the distribution in use to figure out how to properly inform a service about the presence of an X server. In the mean time, you can try sudo -E service myservice export DISPLAY=:0.0 sudo -E service myservice -E The -E (preserve environment) option indicates to the secu‐ rity policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the -E option is specified and the user does not have permission to preserve the environment. warning: this section is semi-factual and biased historically The services in a GNU / Linux system behave somewhat arbitrarily from one distribution to the next. Mostly, the difference is in the setup of the environment before the service is run. This depends on several factors, the most important ones being: Debian, Slackware and Gentoo (OpenRC) use a conceivably similar approach where /etc/init.d/ services are independent scripts that optionally get additional information from /etc/default/servicename, /etc/conf.d/servicename and similar. The scripts may or may not rely on distribution-specific init-function such as /lib/lsb/init-functions or /lib64/rc/sh/functions.sh. These additional shell libraries may get information (set up the environment) from additional distribution-specific sources. Ubuntu (Upstart) and systemd have an "entirely" different approach where each service has a configuration file and the init system does all the magic. To fully understand what's going on, one has to read and understand the init system and the quirks of the distribution in use. * the process of initializing environment variables and starting a service. import sudo -u <user> import.. This is very clearly explained in the manual page for the Linux old System V service in the very first sentence: service service runs a System V init script in as predictable environment as possible, removing most environment variables and with current working directory set to /. service runs a System V init script in as predictable environment as possible, removing most environment variables and with current working directory set to /. How do you think that the image command knows where to find your X server? It's the DISPLAY environment variable of course. image DISPLAY Don't rely upon the notion that services run in an interactive login environment with controlling terminals, DISPLAY environment variables, and so forth. They do not. If you've designed a service based upon these assumptions, then you've designed it wrongly, and you've designed something that isn't even working for you now, let alone that will work should you use a different init system such as systemd, upstart, nosh, runit and so forth, all of which ensure that services are not affected by the arbitrary values of an interactive shell's environment variables (and other process state) when a service is brought up/down. sudo By posting your answer, you agree to the privacy policy and terms of service. asked 1 year ago viewed 69 times active
http://superuser.com/questions/734758/what-causes-import-command-to-fail-as-running-through-a-service/735644
CC-MAIN-2015-22
en
refinedweb
! Thanks a lot of this mini guide. It was very helpful. Everything works as expected, but I keep getting this warning when doing a normal “manage.py runserver” in eclipse while the pydev remote debug server is running: —————————- PYDEV DEBUGGER WARNING: sys.settrace() should not be used when the debugger is being used. This may cause the debugger to stop working correctly. If this is needed, please check: to see how to restore the debug tracing back correctly. Call Location: File “/Applications/eclipse/plugins/org.python.pydev.debug_1.3.10/pysrc/pydevd.py”, line 743, in settrace sys.settrace(debugger.trace_dispatch) ———————– Despite the warning, things are working very well so it’s not really a big deal. Thanks again! Comment by Duc Nguyen — November 26, 2007 @ 12:53 am | You can run manage.py with “run as python run” option, not “debug as python run”. This warning won’t appear anymore. The “debug as …” is only needed when you want to set breakpoint in manage.py or the code executed before auto reload thread. In my original post, everything is ok in eclipse, but command line. I do some modification for this to make manage.py runserver work well in command line mode. def inReloadThread(): “”” Manage.py is called in reload thread or not? @return True if we are in reload thread. “”” return os.environ.get(“RUN_MAIN”) == “true” if settings.DEBUG and (command == “runserver” or command == “testserver”): # Make pydev debugger works for auto reload. usePydevd = True try: import pydevd except ImportError: if not inReloadThread(): print (“PYDEVD DEBUG DISABLED: ” “You must add org.python.pydev.debug.pysrc ” “to your PYTHONPATH for debugging in Eclipse.\n\n”) usePydevd = False if usePydevd: from django.utils import autoreload m = autoreload.main def main(main_func, args=None, kwargs=None): Please enjoy this. I am very happy this code is helpful for you. Comment by bear330 — December 1, 2007 @ 5:55 am | Hi, I was unable to get this to work. Where did you place the code in manage.py? In the first line, “if settings.DEBUG and (command == “runserver” or command == “testserver”):”, there is no “command” in manage.py. I got rid of this (since I was only running this from Eclipse). After that, it would not connect to the debugger because the port is randomized each time, but the code is using a hardcoded value. I rememdied this with the following hack: import os import re # HACK: Get remote debugger port from ppid fd = os.popen(‘ps wwo command -p %d’ % os.getppid()) re_port = re.compile(r’–port\s*(\d+)\s*’) port = int(re_port.search(fd.readlines()[1]).groups()[0]) I finally got it running with this, but now I get the same warning as comment #1 and none of my breakpoints work. The debugger works fine if I use –noreload with the default manage.py, but I would really like to get this working with autoreload. Comment by impulse — December 8, 2007 @ 10:24 am | Ignore my previous comment. I wasn’t using the PyDev extensions remote debugger. It’s working now. Comment by impulse — December 8, 2007 @ 11:29 am | works like a charm :) Thanks a lot! Comment by Duc Nguyen — December 13, 2007 @ 7:38 am | very interesting, but I don’t agree with you Idetrorce Comment by Idetrorce — December 16, 2007 @ 3:03 am | I desperately want to get this working, but I’m having trouble repeating everyone’s success from almost a year ago. First, I have the same confusion as Duc Nguyen: I don’t know where to drop in this code. When I put it at the top level of my manage.py there is no “command” variable defined. Second, even when I leave out the conditional and always run this code, I get the error “No module named pydevd” when it tries to execute the “import pydevd” line. I swear I have this properly in my PYTHONPATH. Indeed, from the Python console, I can import pydevd without any problems. Any hints for either problem? Comment by digi — September 29, 2008 @ 4:24 pm | I am very sorry to put a vague code here. The command variable is: if len(sys.argv) > 1: command = sys.argv[1] And you must make pydevd available for your project. In my .pydevproject file, I make it as external source folder: <pydev_pathproperty name=”org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH”> <path>C:\Program Files\Eclipse 3.4\plugins\org.python.pydev.debug_1.3.20\pysrc</path> </pydev_pathproperty> You can set up this by Properties->PyDev – PYTHONPATH page or simply put these lines in your .pydevproject file. If you still have any problem, feel free to let me know. Comment by bear330 — September 30, 2008 @ 11:24 am | Hi bear330, I have the following in my .pydevproject file. /home/nicta/eclipse/plugins/org.python.pydev.debug_1.6.5.2011020317/pysrc however, when I run my script with the following code at the beginning, it still saying I don’t have pysrc in my PYTHONPATH. #################### REMOTE_DBG = True # append pydev remote debugger if REMOTE_DBG: # Make pydev debugger works for auto reload. # Note pydevd module need to be copied in XBMC\system\python\Lib\pysrc try: import pysrc.pydevd as pydevd # stdoutToServer and stderrToServer redirect stdout and stderr to eclipse console pydevd.settrace(‘localhost’, stdoutToServer=True, stderrToServer=True) except ImportError: sys.stderr.write(“Error: ” + “You must add org.python.pydev.debug.pysrc to your PYTHONPATH.”) sys.exit(1) #################### My eclipse is Eclipse SDK Version: 3.6.1 Build id: M20100909-0800 any idea? Comment by peizhao — February 18, 2011 @ 11:03 pm | sorry, the debug code should change to import pydevd it works now. Comment by peizhao — February 18, 2011 @ 11:15 pm Belated thanks for the clarification! This definitely helps me understand your solution. Comment by Chris DiGiano — October 31, 2008 @ 5:57 pm | On Ubuntu pydevd source folder is located $HOME/.eclipse/org.eclipse.sdk.ide/updates/eclipse/plugins/org.python.pydev.debug_1.3.24/pysrc/ Comment by MIkko Ohtamaa — December 29, 2008 @ 10:44 am | […] should be. I’ve uploaded that to snippet to django snippets. It was originally posted here in 2007, so I’ve copied it to Django snippets in case that post […] Pingback by Django+Eclipse with Code Complete Screencast « vlku.com — June 11, 2009 @ 12:16 am | Off topic – need help with email settings How do I change Gmails SMTP settings? Dr Gil Lederman Gil Lederman Gil Lederman MD Comment by Gil Lederman — September 7, 2009 @ 3:19 am | Thanks for the hack. I had to make a few changes to get this to work with Django 1.1 (since the “inner_run” method now takes no arguments as opposed to the earlier system where it took the *args and **kwargs). I posted the changes at Comment by Raja — December 6, 2009 @ 5:07 am | Hi all, I have been following along with this. Having updated my manage.py code to reflect “if len(sys.argv) > 1: command = sys.argv[1]”, I now get an error related to sitecustomise.py when I run the debug: sys.path.extend(paths_removed) AttributeError: ‘NoneType’ object has no attribute ‘path’ coming specifically from line 148. I’m pretty sure that I have pydevd correctly set up and have it attached to my PYTHONPATH okay. I’m running python 2.6. Has anybody any ideas? Thanks in advance, G (pretty new to all this) Comment by Gerry — December 9, 2009 @ 6:08 pm |. online football betting. Comment by FrancescaRivierra — May 17, 2010 @ 2:47 am | txing Comment by ppheiko — June 4, 2010 @ 10:56 am | Welcome First time skipped right here in your web site, founde on ASK. Thanks for the short response. Your information was very element and knowledgeable. Comment by Daily File — October 2, 2010 @ 4:50 am | Please move me if this is not the right area for my post. You can call me william. I research about workout Check out my site diet program reviews. I look forward to reading more about this website bear330.wordpress.com Comment by SwewSilmhic — January 16, 2011 @ 10:06 pm | I was just browsing every now and then along with you just read this post. I have to admit that I am inside the hand of luck today otherwise getting this excellent post to learn wouldn’t are actually achievable for me personally, at the least. Really appreciate your content. Comment by tramdol {1|2|3|4|5|6}{2|3|4|5|6|7}{a|1|2|3f|g|hR} — April 7, 2011 @ 5:01 pm | Длительность диеты 9 дней, и за это время можно похудеть на 8–9 кг. Выходить из диеты следует осторожно, не набрасываясь сразу на калорийные продукты. Диеты считаются одними из самых эффективных способов избавиться от лишнего веса. Масса информации, которую необходимо знать о диетах для быстрого похуденияветы как похудеть – диеты, кремлевская диета, правильное питание, таблицы калорийности, диета, аэробика.», Comment by Swettejup — July 15, 2011 @ 10:09 pm | I am receiving “NameError: name ‘sys’ is not defined” Here is my manage.py #!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write(“Error: Can’t find the file ‘settings__”: if len(sys.argv) > 1: command = sys.argv execute_manager(settings) Comment by eros — October 12, 2011 @ 12:58 am | […] How to debug django web application with autoreload.: How to debug django web application with autoreload in Eclipse pydev plugin. […] Pingback by Django resources | 岭南六少 - 一朵在LAMP架构下挣扎的云 — October 17, 2011 @ 8:27 am | эффективные диеты… […]How to debug django web application with autoreload. « yet another blog.[…]… Trackback by эффективные диеты — January 29, 2012 @ 1:29 pm | What’s Going down i am new to this, I stumbled upon this I’ve found It absolutely helpful and it has aided me out loads. I’m hoping to give a contribution & help different customers like its helped me. Good job. Comment by Cindy — February 2, 2013 @ 10:50 pm |. Comment by glass — April 16, 2013 @ 5:45 am | This is the point where you can try gh supplement called releasers instead. The problem is that people cannot really openly acquire these supplements. The availability and lower price of processed and canned foods. This in turn will encourage your body to function properly. Comment by hghreleasersreview.com — May 2, 2013 @ 11:15 pm | One should never exercise if nursing schools united states it causes pain. Comment by online masters nursing programs — May 9, 2013 @ 1:16 am | Creighton 58 – Alabama 57 Well, we are planning and expect to open Tinley Park in May. Operator This concludes accelerated nursing today’s conference call. And just because there’s not — there’s more competition doesn’t mean that you should simply choose the school that can accommodate the student’s needs. Comment by what are the best nursing schools — May 9, 2013 @ 2:14 am | That’s the end of my first term as president of the United States by the aggressive American Entertainment Industry. He got some kind of comforting statement that sets some kind of bounds on good nursing schools the actions of this guy because I don’t think many historians would agree that that would have been the outcome. Comment by — May 9, 2013 @ 3:38 am | The brain scans also showed many different brain regions are involved in nyu accelerated nursing a beyblade battle to ensure fair play. Meanwhile, on the Russian space programme. Comment by — May 9, 2013 @ 4:12 am | The more experienced you are, the more evidence nursing school scholarships we can bring some of the details that support this. Jo Jo the Dog Faced Boy Dec 1, 2012, 10:16am UTC Well, we did just that, for a long time. This does not remove the fact that your claim has been refuted by the original source the daily mail cherry picked it’s data from, and go on to state it as fact. Comment by Elizabet — May 9, 2013 @ 4:25 am | Information gathered by the research firm IDC and Intel, the same milestone will be achieved in perpendicular recording. Stress : Either physical injury or emotional disturbance is frequently blamed as the initial cause of the shortfall appears to be the most sacred group in America, has some personal knowledge of the subject matter. She said that research was urgently needed. That rhetoric has become a tradition. Comment by how do i become a nicu nurse — May 23, 2013 @ 7:35 pm | Either the PET scan showed a better picture or the tumor was growing. 2 Veterinary OfficersMust have a Bachelor of Arts in a Catholic all-girls school, St. Some report as many as 1, 400 women who were victims of the worst slime known to man. A week later she issued a press release from the U. 4 16 kg, they are too ‘busy’. She amazed her nurse practitioner programs in texas doctors! Comment by — May 23, 2013 @ 11:32 pm | Defenseman Aaron Rome tga kenad elbow support is back from IR for the Dallas Stars. 9 min: Newcastle are solid. After Harper returned to school, her new cast made her a celebrity, sitting on the end with Sam in the middle and lower trapezius. Try it now Please give my family the same dignity that you allow for your own much-loved film. Fear, like everything else. Comment by — May 28, 2013 @ 11:24 pm | A veces se tarda mucho en encontrar articulos coherentemente expresados, asi que debo felicitar al autor. S2 Comment by antonio — July 10, 2013 @ 4:35 am | To understand teen photoshop fails, you often make bad choices. No doubt some of these materials. His company, Sherry Accessories, has been booked. Comment by eastern appalachian teen challenge — August 4, 2013 @ 11:50 pm | Because the admin of this web site is working, no doubt very soon it will be renowned, due to its feature contents. Comment by dover business college — August 7, 2013 @ 9:00 pm | I’m very happy to uncover this site. I need to to thank you for ones time for this fantastic read!! I definitely loved every little bit of it and i also have you book marked to check out new stuff on your site. Comment by mobile games — March 23, 2014 @ 6:58 pm | WOW just what I was looking for. Came here by searching for none Comment by hay day astuce ipad — May 8, 2014 @ 4:38 pm | Howdy! Someone in my Myspace group shared this website with us so I came to give it a look. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Fantastic blog and outstanding design and style. Comment by Internet manager download crack download — May 31, 2014 @ 12:07 am | You, yourself, it is important for dog training techniques a dog, either. The” shock collars are not easy. The desire of some dog training techniques commercial mixtures or home. When your dog to feel it. If your dog does something right and wrong ways to make dog training program. Electronic fences Are usually Silent fences By which restrain your pet barks. Comment by google.com — August 21, 2014 @ 4:01 pm |
https://bear330.wordpress.com/2007/10/30/how-to-debug-django-web-application-with-autoreload/
CC-MAIN-2015-22
en
refinedweb
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo fabioz at: Python 2.5 doesn't support the with statement unless you add an import for it (Python 2.6 onwards doesn't require it): from __future__ import with_statement Cheers, Fabio
http://sourceforge.net/p/pydev/mailman/message/27428253/
CC-MAIN-2015-22
en
refinedweb
05 August 2009 12:50 [Source: ICIS news] (Recasts lead) SINGAPORE (ICIS news)--China’s buoyant linear low density polyethylene (LLDPE) futures trade has boosted sentiment in the physical LLDPE market, as local traders try to cash in on the wide price gap between the two, Chinese traders said on Wednesday. Based on the November LLDPE futures contract traded on the Dalian Commodity Exchange (DCE) – the most traded contract on the DCE on Wednesday – the gap between futures and physical spot prices was up to yuan (CNY) 1,155/tonne ($169/tonne), according to a Beijing-based trader. “A speculator could buy a cargo in the physical market now to cover a November position on the futures market, because the price gap more than covers his holding cost,” he said in Mandarin. The holding cost includes storage, delivery and interest charges for owning a physical cargo until it is delivered to cover a position on the futures market. November LLDPE futures on the DCE closed on Wednesday at yuan CNY11,755/tonne, with 847,210 tonnes traded, according to DCE data. In the physical spot market, LLDPE was selling at around CNY10,600-11,000/tonne ex-warehouse in northern ?xml:namespace> With LLDPE offered at $1,300/tonne CFR (cost and freight) Around 24,980 tonnes of LLDPE has been delivered since the futures launched in 2007, of which 64% was delivered in the first seven months of this year, according to DCE data. ($1 = CNY6.83) For more on LLDPE
http://www.icis.com/Articles/2009/08/05/9237716/Chinas-LLDPE-futures-trade-boosts-physical-market-sentiment.html
CC-MAIN-2015-22
en
refinedweb
in reply to Re: Perl 5.6.0 on HPUX/11 won't compile in thread Perl 5.6.0 on HPUX/11 won't compile :-/ I actually tried to use gcc, gnu make, et al., but I get the following insanity: I've tried to compile and run the following simple program: #include <stdio.h> int main() { printf("Ok\n"); exit(0); } I used the command: gcc -O -D_HPUX_SOURCE -Aa -L/lib/pa1.1 -DUINT32_MAX_BROKEN -fn +o-strict-a liasing -I/usr/local/include -o try -L/usr/local/lib try.c -lnsl -lnm +-lndbm -lm alloc -ldld -lm -lc -lndir -lcrypt -lsec ./try and I got the following output: *Initialization*:1: missing token-sequence in `#assert' I can't compile the test program. (The supplied flags or libraries might be incorrect.) You have a BIG problem. Shall I abort Configure [y] Ok. Stopping Configure. [download] The make versions on the two machines appear identical, same for cc et al.; possible that more serious magic was required to compile on the other box, but no one seems to be able to find who did that build. Addition: GNU gdb does give a backtrace where the default debugger would not. tye was right (in CB): it's miniperl dying: (gdb) bt #0 0x2af1c in Perl_malloc () from /usr/perltest/build/perl-5.6.0/./mi +niperl #1 0x9848c in Perl_pregcomp () from /usr/perltest/build/perl-5.6.0/./ +miniperl #2 0x1aa38 in Perl_pmruntime () from /usr/perltest/build/perl-5.6.0/. +/miniperl #3 0x93c24 in ?? () from /usr/perltest/build/perl-5.6.0/./miniperl #4 0x2618c in ?? () from /usr/perltest/build/perl-5.6.0/./miniperl #5 0x255bc in perl_parse () from /usr/perltest/build/perl-5.6.0/./min +iperl #6 0x1492c in main () from /usr/perltest/build/perl-5.6.0/./miniperl [download] So, I'll try building without perl's malloc and see if that helps. More amends... (gdb) bt #0 0xc0180598 in _sigfillset () from /usr/lib/libc.2 #1 0xc017e048 in _memset () from /usr/lib/libc.2 #2 0xc0183750 in malloc () from /usr/lib/libc.2 #3 0x46f80 in Perl_safesysmalloc () from /usr/perltest/build/perl-5.6.0/./miniperl #4 0x1ab74 in Perl_newSVOP () from /usr/perltest/build/perl-5.6.0/./m +iniperl #5 0x31814 in ?? () from /usr/perltest/build/perl-5.6.0/./miniperl #6 0x33000 in Perl_yylex () from /usr/perltest/build/perl-5.6.0/./min +iperl #7 0x908d4 in Perl_yyparse () from /usr/perltest/build/perl-5.6.0/./m +iniperl #8 0x260dc in ?? () from /usr/perltest/build/perl-5.6.0/./miniperl #9 0x25544 in perl_parse () from /usr/perltest/build/perl-5.6.0/./min +iperl #10 0x1490c in main () from /usr/perltest/build/perl-5.6.0/./miniperl [download] Perl_malloc doesn't seem to be the problem, then. gcc -O -D_HPUX_SOURCE -Aa [download] -- Me spell chucker work grate. Need grandma chicken. OK, I feel pretty stupid for not thinking of comparing the two manuals... (I did, however, scan the gcc manual in a moment of desparation) but that seems to have done the trick. A couple (lit. "2") failed tests, but I think that we're good to go. Thanks, yak
http://www.perlmonks.org/?node_id=57250
CC-MAIN-2015-22
en
refinedweb
Re: Beckton to Thamesmead bridge? - Thanks for that reassuring clarification, much better than what I heard.Barry----- Original Message -----From: Cllr Alex GrantSent: Friday, November 29, 2002 9:06 PMSubject: Re: Beckton to Thamesmead bridge?Barry Sorry to nit-pick but I think you have rather misrepresented my contribution to this meeting. I did not say simply "We support the bridge". I said that while the council supported the idea of a new crossing in principle - to redress the shortage of river crossings (both road and public transport) in east London as compared to West - we would want to consider the details carefully including the width, health impact and traffic generation projections. We haven't seen a concrete plan until this month. Council will not blindly accept whatever is consulted upon but will look at proposal carefully and comment in usual way. The council's environment, regeneration and development scrutiny panel (which I chair) will also want to consider the proposal. Best wishes Alex Grant masonb wrote: Here's some too quick notes I took at last night's meeting about the new bridge. Let's discuss it at our next meeting:Wednesday 4 December.I'll try and get a TfL speaker for that meet. Martin?Great venue last night. Terrible bike parking. Barry07905 889 005London Thames Gateway Forum The Challenge of the New River Crossings <?xml:namespace prefix = o Meeting: Monday 25 November. 7pm Room 9, House of Commons John Austin, Labour MP for Erith and Thamesmead, was chairing the meeting and said that, although he was opposed to the planned East London River Crossing, he was a neutral chair. Transport for London would speak first. Then Susan Kramer with a personal view (LibDem MP for Richmond and dissenting TfL Board Member). Then Professors John Whitelegg and John Adams. The meeting was timetabled and due to end at 9pm. TfL Barry Broe – TfL Director of Planning Bridget Rosewell – GLA Economist Martin Stuckey – Thames Gateway Bridge Project Manager BB: Thames Gateway is the largest growth area in Europe. BR will talk about the amount of social deprivation in the area. The TGB will create 26,000 jobs. 88% of the bridges new capacity will be for public transport. Of the 6 lanes, 2 will be for buses, bikes and pedestrians. The latest estimate is £353m, and rising.It will be tolled to limit long distant travelling by cars etc. It links Beckton and Thamesmead and the 2 new waterfront transit systems on each side of the Thames. 98% of the traffic that uses the new bridge will be from the 6 adjoining local boroughs. £35m will be spent on the new East London Waterfront Transit that opens in 2006. £25m on Greenwich’s that opens 2008. Without the new bridge much private vehicle travel will be suppressed, and the economy likewise. MS: the way forward is becoming clear. Stakeholders will be consulted in February 2003. The public in June 2003. Local businesses and boroughs all want the project. Feedback from local communities is 80% favourable. Impact studies will now start on traffic, visual, environmental issues. Oxleas Wood, Rainham Marshes and Woodlands Farm will remain fully protected. Local tolling will limit traffic. By October 2003 the bridge design will be finalised. Work starts in 2007, it opens in 2010. Question. Dr Barry Grey (People Against the River Crossing and respiratory consultant): the crossing has been rejected in 3 official reports by the GLC and DTp, its traffic generation will be unacceptable. It is deceitful rubbishto say the bridge will be used by mostly local traffic. And whatever happened to Government traffic reduction and health impact policies? The London Mayor is mandated to reduce traffic. Why is he decongesting central London and stimulating traffic to the east? Question. Jenny Bates. Greenwich Friends of the Earth. When does consultation start? TfL: there will be very full consultation and health and traffic impact assessments. Question: Tom Wednesday (?). Dissenting TfL Board member. I’m very against even more 40 tonne lorries in the area. Public transport must be the answer. Why is that hundreds of millions of pounds can always for found for road schemes, and not public transport schemes? Question: ex GLC member. Better local access is essential. The DLR should extend to Thamesmead and river services hugely improved. Question. The Thames Society. Our river is only ever mentioned as a barrier. It should be a highway. The scoping of much improved river services must start now. TfL: the project is about regenerating the area with jobs through better crossings. Susan Kramer, Dissenting TfL member: the TfL Board was split down the middle on this two weeks ago. Ken, the Mayor, then voted for the crossing and swung the decision. This is not the local bridge TfL say it is. It’s a 4 lane motorway link between the A2 and A13. Canary Wharf has boomed, but not helped the locals much. Staff are mostly bussed in from Essex. And for TfL to claim that only 12% of use will be by private vehicles is ludicrous. Richmond (SK’s constituency) has outstanding public transport links and horrendous roads, yet is booming. We have in Thames Gateway an amazing opportunity to create a sustainable city the area of Tokyo. And yet all we’re getting is 1960/70s new town development planning that has failed so badly in the past. The new bridge will be like west London’s westway. Park Royal there stays poor and deprived as polluting traffic roars through and over it. It’s lack of education and opportunity that hold people back, not easy access. Question. Why on earth do we need 17m more roads trips a year into Greenwich, the third most polluted borough in London? Alex Grant: I’m chair of Greenwich Council’s Environmental Committee. We support the new bridge. Question: and don’t forget the A2 goes to Cliffe, and the new airport?! Professor John Whitelegg (Leader of the Implementing Sustainability Group, Stockholm Environment Group. And University of York): I agree the need for more jobs locally, and for less travel, and improved health, and more cycling, more walking, and more public transport. Do big projects create jobs? 8 official Government reports since 1977 say No. The 1994 Royal Commission on Environmental Pollution showed that road building does not necessarily lead to growth. “Good roads can speed the decline of less prosperous areas”. There is no evidence anywhere of a simple link between improved accessibility and economic performance. In 1999 the National Audit Office and English Partnerships estimated the cost of creating a new job to be £10,000. Actual costs then were around £23,000. The National Audit Office looked at the Limehouse Link in 1995 and found there was no acceptable method of appraising road schemes to inner city regeneration. But we know a lot about transport and social exclusion. Kids from deprived areas are 5 times more likely to be involved in road traffic incidents than their wealthler peers. More traffic equals more health problems. The new crossing will generate extra traffic. Belfasts similar Lagan Bridge in 1995 increased local volumes by 13%. But access is essential to modern life. Walking and cycling can make up 30% of all trips...but not in London because conditions are so bad: traffic speeds, HGV’s. Public transport use and access depends on frequency, space, cost and security. We need to get these factors right.The bridge planning process is so deficient. It’s the worst I’ve ever seen. The community has not been asked. DETR in 1998 set down the general consultation ground rules, they’ve been ignored. There’s been no health impact assessment. There’s been no parity of time and costs for exploring other options. The process is deeply flawed. The aim is to get commitment to big infrastructure and more traffic. The poor will suffer even more. Professor John Adams: University College. I’ve got 3 qualifications. I spoke at the Royal Society of Arts debate in favour of the motion that Cars Kill Cities. My seconder was Stephen Norris! I also wrote the Social Consequences of Hyper-mobility. So I recognise tonight yet more road growth nonsense from TfL on the sort that’s been pumped out for 30 years. Remember that in 1950 in the UK each of us travelled 5 miles a day on average. 30 miles a day now. 60 in 2025. This has surely got to stop. We are told that travel knits communities together. It doesn’t. There are no communities for the hyper-mobile. We don’t know our neighbours. We need to get away from huge schemes whose aim is simply to save the motorist time. Question. The Blackwall Tunnel didn’t regenerate Greenwich Peninsula. And remember that 30% of Greenwich has no car. Question. Paul Weburne. I’m from Eltham. All of Greenwich transport plans are in the north of the borough. More railways and the DLR should head south. Question. Barry Grey: this new bridge is part of Ringway 2. A new motorway box. We do not need more roads or more traffic. Question: Paul Aylot. Beckton. The area is very congested, we do need a new pedestrian bridge. Professor Whitelegg: we need more pulbic transport options. The river must not be seen as a barrier. It’s an artery. Sydney hs wonderful ferries. Professor Adams: we’re seeing a rerun of M25 planning tactiocs here. That vast scheme saw no public inquiry, simply local and uncoordinated ones. Question. Dennis Robinson, GLA LibDems: why is the waterfront transit a bus not a tram? Question: Bexley Local Agenda 21 group: have yet to be invited to comment. Question: Kenneth Hobday. Abbey Wood: we must all now put pressure on Ken Livingstone against the bridge. At 9pm John Austin stopped the meeting. Jeremy Cotton of the London Thames Gateway Forum thanked all those who helped him organise this useful evening. Notes of the meeting would be circulated and another meeting organised in due course. BAM 26 November 2002 07905 889 005 lfgf1 London Thames Gateway Forum contact details: LTGF, Brady Centre, 192 Hanbury Street, London E1 5HU 020 7377 1822 mail@...
https://groups.yahoo.com/neo/groups/greenwichcyclists/conversations/topics/2166?xm=1&m=s&l=1
CC-MAIN-2015-22
en
refinedweb
Hi, they do have an API ( ) but I couldn't find an updated python library for it (py-stockexchange reads 1.1 API version whereas the latest is 2.1). Nonetheless, their API return json data, hence you can very easily parse it with python (or whatever other language supporting json). To see the kind of json returned (or tune the query) you can visit This is a very simple example of how to put the pieces together in python (far from being usable in production, but already useful to avoid manual searches): [elisiano@pc-elisiano ~/Projects ]$ cat couchdb_stack_overflow.py #!/usr/bin/env python2 import urllib2 from StringIO import StringIO import gzip import json url="""""" req=urllib2.Request(url) req.add_header('Accept-Encoding', 'gzip') # should be the default res=urllib2.urlopen(req) buf=StringIO(res.read()) f=gzip.GzipFile(fileobj=buf) data=json.loads(f.read()) ### print only unanswered questions for question in data['items']: if not question['is_answered']: print "%s => %s" % (question['title'], question['link']) [elisiano@pc-elisiano ~/Projects ]$ ./couchdb_stack_overflow.py couchdb map/reduce view: counting only the most recent items => couchDB sorting complex key => How to specify individual database location in couchdb? => Query Ad-Hoc (Temporary) Views with ektorp => Google closure on CouchDB => couchdb conflict identical document => What database(s) for storing user data, and also support targeting queries? => CouchDB Security in a Lightweight Stack? => CouchDB: synchronize between slave databases => CouchDB "virtual" database, that combines 2 databases into 1 => CouchDB didn't start in Windows XP? Anybody has same experince? => How to retrieve the couchDB data by given limit(start_limit,end_limit) using cradle in node.js? => On Sat, 2013-03-09 at 11:08 -0800, Mark Hahn wrote: > Is this automated? If not then it should be. I assume stackoverflow has > an api. > > > On Sat, Mar 9, 2013 at 6:17 AM, Noah Slater <nslater@apache.org> wrote: > > > Dear community, > > > > Here are the latest StackOverflow questions about CouchDB. These might be a > > good opportunity to earn some StackOverflow reputation and help out the > > wider CouchDB community at the same time! > > > > CouchDB Security in a Lightweight Stack? > > > > > > > > CouchDB didn't start in Windows XP? Anybody has same experince? [closed] > > > > > > > > Thanks, > > > > -- > > NS > >
http://mail-archives.apache.org/mod_mbox/couchdb-user/201303.mbox/%3C1362996146.10903.29.camel@localhost.localdomain%3E
CC-MAIN-2015-22
en
refinedweb
02 January 2009 13:57 [Source: ICIS news] TORONTO (ICIS news)--Albermarle has completed the sale of its facility in Port de Bouc, France, to Azur Chimie, a wholly-owned affiliate of International Chemical Investors Group (ICIG), the US specialty chemicals and catalysts producer said on Friday. Azur Chimie would toll manufacture certain products for ?xml:namespace> "This strategic divestiture will position us to better focus on our core business initiatives," said vice president of Albemarle's fine chemicals segment Ron Gardner. As a result of the sale, The Port de Bouc plant, near Marseille, employs approximately 180 people and produces a wide variety of bromine fine chemicals and intermediates. Frankfurt-based ICIG is described as a privately-held investment company focused on mid-sized chemicals businesses. ($1 = €0.71)
http://www.icis.com/Articles/2009/01/02/9181208/albemarle-completes-sale-of-french-facility.html
CC-MAIN-2015-22
en
refinedweb
Post your Comment How to get client's address in a servlet How to get client's address in a servlet  ... client's address in a servlet. In this example we have used method getremoteAddr() of the ServletRequest interface which returns IP address of the client PHP Get Browser IP Address PHP Get Browser IP Address PHP provides us $_SERVER['REMOTE_ADDR'] function is used to display the Browser IP address PHP Get IP Address Code: <?php echo "My Browser IP is :". $_SERVER['REMOTE_ADDR']; ?> Get IP Address in Java Get IP Address in Java In this example we will describe How to get ip address in java. An IP address is a numeric unique recognition number which...(). getHostAddress(). InetAddress():-The InetAddress is class represents an IP address ssl client - JSP-Servlet ssl client How do you write SSL Client? Take example of SSL Socket Client Client Side Address Validation in Struts Client Side Address Validation in Struts In this lesson we will create JSP page for entering the address...; The Address Form that validates the data on the client side using Stuts Validator Client Auto Refresh in Servlets Client Auto Refresh in Servlets This section illustrates you how client gets auto refresh. We are providing...("Refresh", "15") refreshes the servlet after every 15 seconds till Get IP Address Example Get IP Address Example This example shows you ip address of your... : NetworkInterface.getNetworkInterfaces() : Network Interface class is used for get name, and a list of IP Getting IP Address Getting IP Address Hi... i want to get the ip address of the current... get the ip address 247 in database but i need to get the ip address of that particular system.... how to get that please help me doing that... thank Client Socket Information Client Socket Information In this section, you will learn how to get client... way. In this way we find out the Local address, Local host information Java Get IP Address Java Get IP Address This section illustrates you how to obtain the IP Address of local host... getHostAddress() returns the IP address. Here is the code of Java Get IP Java Servlet : Get URL Example Java Servlet : Get URL Example In this tutorial, You will learn how to get url of servlet. Servlet getRequestURL : getRequestURL() method reconstruct the requested client URL. It returns the current URL which containing protocol how to get an lan system ip and mac address in java code how to get an lan system ip and mac address in java code strong text? run exe on remote client run exe on remote client I am making a client server application using netbins 6.1 , Jsp servlet, Mysql5.1... I want to run an batch file or exe file on client pc in my network if i know the username & password. I have get the servlet feature - JSP-Servlet get the servlet feature when the servlet get servlet feature? Hi Friend, Please clarify your problem. Thanks Client side refresh Client side refresh What is client side refresh? The standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers. <META HTTP-EQUIV="Refresh" CONTENT="5; URL=/servlet/MyServlet What is Java Client Socket? socket connections. To get connection in client socket in java used the class...What is Java Client Socket? Hi, What is client socket in Java..., The client socket is basic communication interface between networked computers Java client posting to a servlet - Development process Java client posting to a servlet Hi, I would like to create a java client that post to a servlet. I am trying to test out a webserver and would like to drive a number of connections using this process. Thanks Hi Failed Client-Socket Communication Failed Client-Socket Communication I hve written a server program & a client program. The server is supposed to echo watever is typed in the client. I hve to get 16 values to be echoed. I hve created a string and all Header Information available from the client in Servlet Header Information available from the client in Servlet In this section you will studied how to display the header information in servlet. When a HTTP client sends a request Find Exact Location from IP address in java? Find Exact Location from IP address in java? I am looking for API where we can pass IP address and get the location (Cityname,Country name). please suggest any API OR sample code. Thank you servlet com.ilp.tsi.um.bean.BankBean; import com.ilp.tsi.um.service.BankService; /** * Servlet... operation to get retailer information { private static final long... addr=request.getParameter("address"); String ph Java : Servlet Tutorials How to get client's address in a servlet This is detailed java code to get client's address in a servlet... how to get parameter from jsp page in your servlet. In the jsp Java example program to get IP address of own system Java example program to get IP address of own system java get own IP address An IP... the computer system's local host with IP address. Now we can get the IP address Post your Comment
http://roseindia.net/discussion/21723-How-to-get-clients-address-in-a-servlet.html
CC-MAIN-2015-22
en
refinedweb
Name | Synopsis | Description | Return Values | VALID STATES | Errors | TLI COMPATIBILITY | Attributes | See Also | Warnings #include <xti.h> int t_accept(int fd, int resfd, const struct t_call *call);.:. Name | Synopsis | Description | Return Values | VALID STATES | Errors | TLI COMPATIBILITY | Attributes | See Also | Warnings
http://docs.oracle.com/cd/E19253-01/816-5170/6mbb5et5j/index.html
CC-MAIN-2015-22
en
refinedweb
Classes (C# Programming Guide). For more information, see Static Classes and Static Class Members (C# Programming Guide). Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming. For more information, see Inheritance (C# Programming Guide). Classes are declared by using the class keyword, as shown in the following example: The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members. Although they are sometimes used interchangeably,:: This code creates two object references that both refer to the same object. Therefore, any changes to the object made through object3 will be reflected in subsequent uses of object4. Because objects that are based on classes are referred to by reference, classes are known as reference types. Inheritance is accomplished by using a derivation, which means a class is declared by using a base class from which it inherits data and behavior. A base class is specified by appending a colon and the name of the base class following the derived class name, like this: When a class declares a base class, it inherits all the members of the base class except the constructors. Unlike C++, a class in C# can only directly inherit from one base class. However, because a base class may itself inherit from another class, a class may indirectly inherit multiple base classes. Furthermore, a class can directly implement more than one interface. For more information, see Interfaces (C# Programming Guide). A class can be declared abstract. An abstract class contains abstract methods that have a signature definition but no implementation. Abstract classes cannot be instantiated. They can only be used through derived classes that implement the abstract methods. By constrast, a sealed class does not allow other classes to derive from it. For more information, see Abstract and Sealed Classes and Class Members (C# Programming Guide). Class definitions can be split between different source files. For more information, see Partial Classes and Methods (C# Programming Guide). In the following example, a public class that contains a single field, a method, and a special method called a constructor is defined. For more information, see Constructors (C# Programming Guide). The class is then instantiated with the new keyword. public class Person { // Field public string name; // Constructor public Person() { name = "unknown"; } // Method public void SetName(string newName) { name = newName; } } class TestPerson { static void Main() { Person person = new Person(); Console.WriteLine(person.name); person.SetName("John Smith"); Console.WriteLine(person.name); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: unknown John Smith */ For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
https://msdn.microsoft.com/en-US/library/x9afc042(v=vs.100).aspx
CC-MAIN-2015-22
en
refinedweb
Ioctl Requests audio(7I) NAME audio - generic audio device interface SYNOPSIS #include <sys/audio.h> OVERVIEW An audio device is used to play and/or record a stream of audio data. Since a specific audio device may not support all of the functionality described below, refer to the device-specific manual pages for a complete description of each hardware device. An application can use the AUDIO_GETDEV ioctl(2) to determine the current audio hardware associated with /dev/audio. AUDIO FORMATS deter- mined for- mats when playing or recording. Sample Rate Sample rate is a number that represents the sampling fre- quency (in samples per second) of the audio data. Encodings An encoding parameter specifies the audio data representa- tion. u-Law encoding corresponds to CCITT G.711, and is the standard for voice data used by telephone companies in the United States, Canada, and Japan. A-Law encoding is also SunOS 5.8 Last change: 16 January 2001 1 Ioctl Requests audio(7I) pro- portional to audio signal voltages. Each sample is a 2's complement number that represents a positive or negative amplitude. Precision Precision indicates the number of bits used to store each audio sample. For instance, mu-Law and A-Law data are stored with 8-bit precision. PCM data may be stored at various precisions, though 16-bit PCM is most common. Channels. DESCRIPTION The device /dev/audio is a device driver that dispatches audio requests to the appropriate underlying audio device driver. confi- guration. Opening the Audio Device SunOS 5.8 Last change: 16 January 2001 2 Ioctl Requests audio(7I) The audio device is treated as an exclusive resource - only one process can open the device at a time. However, if the AUDIO_DUBLEX bit is set in hw_features of the audio_info_t structure, two processes may simultaneously access the dev- ice. This allows one process to open the device as read-only and a second process to open it as write-only. See below for details. When a process cannot open /dev/audio because the requested access mode is busy: o if either the O_NDELAY or O_NONBLOCK flags are set in the open() oflag argument, then -1 is immediately returned, with errno set to EBUSY. o will reset the data format of the device to the default state of 8-bit, 8Khz, mono u-Law data. If the device is already open and a different audio format has been set, this will not be possible on some devices. Audio applications should expli- citly set the encoding characteristics to match the audio data requirements, rather than depend on the default confi- guration. dev- ice whenever another process requests write access. Recording Audio Data The read() system call copies data from the system immedi- ately, but may return fewer bytes than requested. Refer to the read(2) manual page for a complete description of this behavior. SunOS 5.8 Last change: 16 January 2001 3 Ioctl Requests audio(7I) struc- ture parame- ters result in a changed sample size. Input data can accumulate in STREAMS buffers very quickly. At a minimum, it will accumulate at 8000 bytes per second for 8-bit, 8 KHz, mono, mu-Law data. If the device is con- figured con- tains a discontinuity. For this reason, audio recording applications should open the audio device when they are prepared to begin reading data, rather than at the start of extensive initialization. Playing Audio Data The write() system call copies data from an application's buffer to the STREAMS output queue. Ordinarily, write() blocks until the entire user buffer is transferred. The dev- ice may alternatively be set to a non-blocking mode, in which case write() completes immediately, but may have transferred fewer bytes than requested (see write(2)). Although write() returns when the data is successfully queued, the actual completion of audio output may take con- siderably. SunOS 5.8 Last change: 16 January 2001 4 Ioctl Requests audio(7I) The final close(2) of the file descriptor hangs until audio output has drained. If a signal interrupts the close(), or if the process exits without closing the device, any remain- ing data queued for audio output is flushed and the will be played from the STREAMS buffers at a rate of at least 8000 bytes per second for u-Law or A-Law will be generated and the device must be closed before any future writes will succeed. Asynchronous I/O The I_SETSIG STREAMS ioctl enables asynchronous notifica- tion, through the SIGPOLL signal, of input and output ready conditions. The O_NONBLOCK flag may be set using the F_SETFL fcntl(2) to enable non-blocking read() and write() requests. This is normally sufficient for applications to maintain an audio stream in the background. Audio Control Pseudo-Device It is sometimes convenient to have an application, such as a volume control panel, modify certain characteristics of the audio device while it is being used by an unrelated process. The /dev/audioctl pseudo-device is provided for this pur- pose. Any number of processes may open /dev/audioctl simul- taneously. con- structed by appending the letters "ctl" to the path name of the audio device. Audio Status Change Notification Applications that open the audio control pseudo-device may request asynchronous notification of changes in the state of the audio device by setting the S_MSG flag in an I_SETSIG STREAMS ioctl. Such processes receive a SIGPOLL signal when any of the following events occur: SunOS 5.8 Last change: 16 January 2001 5 Ioctl Requests audio(7I) o An AUDIO_SETINFO ioctl has altered the device state. o An input overflow or output underflow has occurred. o An end-of-file record (zero-length buffer) has been processed on output. o An open() or close() of /dev/audio has altered the device state. o An external event (such as speakerbox volume control) has altered the device state. IOCTLS Audio Information Structure The state of the audio device may be polled or modified using the AUDIO_GETINFO and AUDIO_SETINFO ioctl commands. These commands operate on the audio_info structure as defined, in <sys/audioio; /* modifyable I/O ports */ } audio_prinfo_t; /* This structure is used in AUDIO_GETINFO and AUDIO_SETINFO ioctl commands */ SunOS 5.8 Last change: 16 January 2001 6 Ioctl Requests audio(7I) typedef struct audio_info { audio_prinfo_t record; /* input status information */ audio_prinfo_t play; /* output status information */ uint_t monitor_gain; /* input to output mix */ uchar_t output_muted; /* non-zero if output muted */ uint_t hw_features; /* supported H/W features */ uint_t sw_features; /* supported S/W features */ uint_t sw_features_enabled; supported S/W features enabled */ } and avail_ports) */ /* output ports (several might be enabled at once) */ #define AUDIO_SPEAKER (0x01) /* output to built-in speaker */ #define AUDIO_HEADPHONE (0x02) /* output to headphone jack */ #define AUDIO_LINE_OUT (0x04) /* output to line out */ #define AUDIO_SPDIF_OUT (0x08) /* output to SPDIF port */ #define AUDIO_AUX1_OUT (0x10) /* output to aux1 out */ #define AUDIO_AUX2_OUT (0x20) /* output to aux2 out */ /* input ports (usually only one may be enabled at a time) */ #define AUDIO_MICROPHONE (0x01) /* input from microphone */ #define AUDIO_LINE_IN (0x02) /* input from line in */ #define AUDIO_CD (0x04) * input from on-board CD inputs */ #define AUDIO_SPDIF_IN (0x08) /* input from SPDIF port */ #define AUDIO_AUX1_IN (0x10) /* input from aux1 in */ #define AUDIO_AUX2_IN (0x20) / * input from aux2 in */ #define AUDIO_CODEC_LOOPB_IN (0x40) input from Codec inter. loopback */ #define MAX_AUDIO_DEV_LEN (16) /* These defines are for hardware features */ #define AUDIO_HWFEATURE_DUPLEX (0x00000001u) simult. play & cap. supported */ #define AUDIO_HWFEATURE_MSCODEC (0x00000002u) /* multi-stream Codec */ SunOS 5.8 Last change: 16 January 2001 7 Ioctl Requests audio(7I) /* These defines are for software features */ #define AUDIO_SWFEATURE_MIXER (0x00000001u) * audio mixer audio pers. mod. */ /* Parameter for the AUDIO_GETDEV ioctl to determine current audio devices */ #define MAX_AUDIO_DEV_LEN (16) typedef struct audio_device { char name[MAX_AUDIO_DEV_LEN]; char version[MAX_AUDIO_DEV_LEN]; char config[MAX_AUDIO_DEV_LEN]; } out- put ports that may be turned on and off. If a port is miss- ing from play.mod_ports then that port is assumed to always be on. The input ports can be either AUDIO_MICROPHONE (microphone jack), AUDIO_LINE_IN (line-out port), AUDIO_CD (internal CD-ROM), AUDIO_AUX1_IN (auxilary1 in), AUDIO_AUX2_IN (auxi- con- trol propor- tionally reduced. SunOS 5.8 Last change: 16 January 2001 8 Ioctl Requests audio indica- tion that a process may be waiting to access the device. These flags are set automatically when a process blocks on open(), though they may also be set using the AUDIO_SETINFO ioctl command. They are cleared only when a process relinqu- ishes access by closing the device. The play.samples and record.samples fields are initialized, at open(), to zero and increment each time a data sample is copied to or from the associated STREAMS queue. Some audio drivers may be limited to counting buffers of samples, instead of single samples for the samples accounting. For this reason, applications should not assume that the samples fields contain a perfectly accurate count. The play.eof field increments whenever a zero-length output buffer is synchronously processed. Applications may use this field to detect the completion of particular segments of audio out- put. applica- tion, subse- quent SunOS 5.8 Last change: 16 January 2001 9 Ioctl Requests audio(7I) the requested change size. The record.buffer_size field may be modified only on the /dev/audio device by processes that have it opened for read- ing. The play.buffer_size field is currently not supported. The audio data format is indicated by the sample_rate, chan- nels,. Streamio IOCTLS. Audio IOCTLS The audio device additionally supports the following ioctl commands: AUDIO_DRAIN. AUDIO_GETDEV The argument is a pointer to an audio_device struc- ture. This command may be issued for either /dev/audio or /dev/audioctl. The returned value in the name field SunOS 5.8 Last change: 16 January 2001 10 Ioctl Requests audio(7I) will be a string that will identify the current /dev/audio hardware device, the value in version will be a string indicating the current version of the hardware, and config will be a device-specific string identifying the properties of the audio stream associ- ated with that file descriptor. Refer to the audio device-specific manual pages to determine the actual strings returned by the device driver. AUDIO_GETINFO The argument is a pointer to an audio_info_t struc- ture. This command may be issued for either /dev/audio or /dev/audioctl. The current state of the /dev/audio device is returned in the structure. AUDIO_SETINFO The argument is a pointer to an audio_info was issued. This allows programs to automatically modify these fields while retrieving the previous value. Certain fields in the configura- tion is not possible, or EBUSY when another process has con- trol of the audio device. Once set, the following values persist through subsequent open() and close() calls of the device: play.gain, record.gain, play.balance, record.balance, play.port, record.port and monitor_gain. However, an automatic device driver unload will reset these parameters to their default values on the next load. All other state is reset when the corresponding I/O stream of /dev/audio is closed. SunOS 5.8 Last change: 16 January 2001 11 Ioctl Requests audio(7I). ERRORS An open() will fail if: EBUSY The requested play or record access is busy and either the O_NDELAY or O_NONBLOCK flag was set in the open() request. EINTR The requested play or record access is busy and a sig- nal interrupted the open() request. An ioctl() will fail if: EINVAL The parameter changes requested in the AUDIO_SETINFO ioctl are invalid or are not supported by the device. EBUSY The parameter changes requested in the AUDIO_SETINFO ioctl could not be made because another process has the device open and is using a different format. FILES The physical audio device names are system dependent and are rarely used by programmers. The programmer should use the generic device names listed below. /dev/audio symbolic link to the system's primary audio device /dev/audioctl symbolic link to the control device for /dev/audio /dev/sound/0 first audio device in the system /dev/sound/0ctl SunOS 5.8 Last change: 16 January 2001 12 Ioctl Requests audio(7I) audio control device for /dev/sound/0 /usr/share/audio audio files ATTRIBUTES See attributes(5) for a description of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | | Architecture | All | | Availability | SUNWcsu, SUNWaudd,| | | SUNWauddx, SUNWaudh | | Stability Level | Evolving | |_____________________________|_____________________________| SEE ALSO close(2), fcntl(2), ioctl(2), open(2), poll(2), read(2), write(2), audiocs(7D), dbri(7D), sbpro(7D), usb_ac(7D), audio_support(7I) mixer(7I) streamio(7I) BUGS DIRECTIONS Future audio drivers should use the mixer(7I) audio device to gain access to these new features. SunOS 5.8 Last change: 16 January 2001 13
http://www.manpages.info/sunos/audio.7.html
CC-MAIN-2015-22
en
refinedweb
Spring String user; That’s so simple that nothing prevent you from doing it wherever you need it, ending up with… Just a mess, if you want to rename (or remove) a property from your configuration file because you assume it is not used, you can just pray (and trust your test coverage)! Because you cannot be 100% sure that you removed it from wherever it has been used. That’s why I always take care of the way we manage our properties. My preferred way to manage properties is to define an unique class which will be responsible of the handling of the property, and I just inject this bean wherever I need. If I need to rename, I have only one place to look, if I decide to remove, I can simply remove the getter and the compiler will directly complain if it is still used somewhere in my application. Another aspect of this implementation is that it allows you to replace the implementation by another one in your test, for example. OK, so, technically speaking, how does it work? Very simple, my unique class: import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class PropertyHandler { @Value("${net.classnotfound.spring.user}") private String user; public String getUser() { return user; } } And how to use it: @Autowired private PropertyHandler propertyHandler; @RequestMapping("/handler") public String boot() { return "Best wishes from Classnotfound to " + propertyHandler.getUser(); } Yes, you can… But don’t 😉 A full example is available on this github repository
http://classnotfound.net/?p=430
CC-MAIN-2021-49
en
refinedweb
Approaches to web development are always evolving. That’s why at Grammarly we’ve sometimes adopted new open source libraries—and other times we’ve built our own to solve the unique challenges we face. For instance, the Grammarly Editor has a complex UI structure, and being data-driven as a company means we want to support many simultaneous experiments without creating a mess of spaghetti code. A few years ago, we released Focal, a framework for immutable and observable state management with TypeScript. Now we’re happy to announce a new UI framework we’ve been busy building and testing for the last year: Embrace. Embrace is a type-safe, declarative UI engine written on top of React and Focal. It lets you compose UI components without having to write boilerplate code or worry about routing states. You can represent your UI as data so that it’s easily patched, allowing you to run hundreds of front-end experiments easily. We hope you’ll go to GitHub and try out Embrace for yourself. This article explains our motivation for building this library and gives you some examples of how to use it. We hope this background helps you and your team understand whether Embrace is a good fit for your use cases. A brief history of the Grammarly Editor architecture The Grammarly Editor is our browser-based text editor where users can create and edit documents, adjust their settings, and manage their subscriptions. Back in 2016, we rewrote both the UX and architecture for the Grammarly Editor so it could handle new kinds of features for our users. As Grammarly grew, we learned more about how our users worldwide were using our product for different kinds of communication—from academic assignments to personal emails to professional writing. There’s so much more to good writing than proper spelling and grammar, and so we brought users an update that included AI-powered writing suggestions for correctness, clarity, engagement, and delivery. The Grammarly Editor needed to be redesigned to support these capabilities. We changed our tech stack from Vue.JS/JavaScript to React/TypeScript, and with a strong belief in object-orientation and two-way data binding, we designed Focal to handle state management for our new architecture. import { Atom, bind, F } from '@grammarly/focal' const TwoWayBindingComponent = ({ state }: { state: Atom<{ text: string }> }) => ( <F.input {...bind({ value: state.lens('text') })} ) Here is an example of two-way data binding using Focal. As our team grew and the Grammarly Editor continued to evolve, we began to notice that two-way data binding has its issues: - Components can become hard to reuse because of the tight two-way coupling between a component (or view) and its state (or model). - By doing “in-place” updates of the state, we lost the ability to react to user actions in a more declarative way. Filtering, throttling, and logging user actions became more challenging. From two-way data binding to model-view-intent To address these issues, we drew from the model-view-intent (MVI) pattern for a new approach to state management. With this approach, a React component (the “view”) would listen for state updates (implemented as Focal Atoms) to re-render. When it received a user event, it would emit an explicit action (the “intent”). These actions are handled by a state manager (the “model”) that encapsulates a piece of app state and sends out state updates, continuing the cycle. Simple MVI mental model Let’s rewrite the sample component from above using this MVI approach: interface Actions { kind: 'updateText' text: string } interface State { text: string } Interfaces for a component’s actions and state const ActionEmittingComponent = ({ state, actions }: { state: ReadOnlyAtom<State>, actions: Rx.Observer<Actions> }) => ( <F.input value={state.view('text')} onChange={e => action.next({ kind: 'updateText', text: e.currentTarget.value })} /> ) The same two-way binding component from before is rewritten to use read-only state and emit actions. class StateManager { constructor( public state = Atom.create<State>({ text: '' }), private _actions = new Rx.Subject<Actions>() ) { const handleAction = (a: Actions) => (s: State) => ({ ...s, text: a.text }) this._actions.subscribe(a => state.modify(handleAction(a))) } get actions(): Rx.Observer<Actions> { return this._actions } } The state manager (model) that does updates const Root = () => { const sm = new StateManager() return <ActionEmittingComponent state={sm.state} actions={sm.actions} /> } “Rendering” the component by providing it with the state and the place to emit actions to Today, most of the Grammarly Editor is implemented using this MVI-based architecture, which has many benefits: - The state management and view logic is nicely decoupled. Views can be reused as long as the corresponding data is provided, and we can iterate on state management without affecting the view logic. - Simple abstractions (Rx Observables) and small interfaces (action messages) make it easier to compose UI pieces together. However, we quickly discovered that this approach came with its own new set of challenges. New challenge: Nesting components When implementing the Grammarly Editor features as described above, we soon found ourselves writing a lot of boilerplate and wiring code to nest and compose components. As each component’s state is nicely abstracted away behind a read-only Atom interface, combining and nesting such components meant that we often had to make the resulting Atom more complex—and then write the code that “selects” part of it: interface State1 { one: string } const Component1 = (_props: { state: ReadOnlyAtom<State1> }) => ( <F.div>{state.one}<F.div/> ) interface State2 { two: string } const Component2 = (_props: { state: ReadOnlyAtom<State2> }) => ( <F.div>{state.two}<F.div/> ) const Component3 = (_props: { state: ReadOnlyAtom<{ one: State1, two: State2 }> }) => ( <div> <Component1 state={props.stae.view('one')} /> <Component2 state={props.stae.view('two')} /> <div/> ) Component3 needs to provide state for both Component1 and Component2. Although Focal has some nice utils to make it easier to write code like this (e.g., the view function above), we still need to manually implement this state routing, which only became more complex with more levels of nesting in the UI. The same problem occurs with actions: interface Actions1 [ kind: 'one' } const Component1 = (_props: { actions: Rx.Oberver<Actions1> }) => ( <div></div> ) interface Actions2 { kind: 'two' } const Component2 = (_props: { actions: Rx.Oberver<Actions2> }) => ( <div></div> ) const Component3 = (_props: { actions: Rx.Oberver<Actions1 | Actions2> }) => ( <div> <Component1 actions={props.actions as Rx.Observer<Actions1>} /> <Component2 actions={props.actions as Rx.Observer<Actions2>} /> </div> ) Component3 needs to provide observers for actions coming from both Component1 and Component2. To avoid writing code like this, we often found ourselves combining all the types of actions into one union type and that we would pass to all the components, which technically works and eliminates a lot of boilerplate—but at the cost of introducing more coupling and breaking the encapsulation of different components. New challenge: Side effects When working within our MVI approach, we’d often experience an unpleasant surprise: Even though we’ve nicely decoupled state from our UI components, React still makes it extremely easy to introduce a side effect, which often results in bugs and code that is hard to understand. const UndercoverEffectComponent = ({ state, actions }: { state: ReadOnlyAtom<State>, actions: Rx.Observer<Actions> }) => { React.useEffect(() => console.log('I can do what I want!!!')) return ( <F.input value={state.view('text')} onChange={e => actions.next({ kind: 'updateText', text: e.currentTarget.value })} /> ) } Here’s an example of a component that produces a side effect without emitting an action. New challenge: Experiments At Grammarly, we rely heavily on data when developing new features, which means we do a lot of A/B testing. We even built our own custom experimentation framework that our teams use internally to manage their A/B tests. Here were two versions of a new feature—which gives Grammarly Premium users the option to accept multiple suggestions at once—in the Grammarly Editor. How do we implement experiments like these in the Grammarly Editor, assuming that we have a way to tell which “feature flags” are enabled for a specific user? We could use if/else statements: const ComponentWithExperiment = ({ state }: { state: Atom<{ features: { fancyComponent: boolean } }> }) => ( <F.Fragment> {pipe( state.view('features'), Rx.map(f => { if (f.fancyCompenent) { return <FancyComponent /> } else { return <NormalComponent /> } }) )} </F.Fragment> ) This if/else code renders different versions of a component based on a feature flag. But while code like this might work in the short term, it introduces problems that become more visible as the number of experiments grows: - It’s hard to maintain the code because anyone who works on it now needs to keep in mind two (or even more) possible behaviors. - As the number of experiments increases, the number of potential UIs grows exponentially. If there’s a conflict somewhere, which becomes increasingly likely, the issue could go uncaught because it’s very hard to test all the possible scenarios. - If we modify the code directly like this to add experiments, multiple teams may need to be involved to run an A/B test (for example, if the Growth team wants to run an A/B test, they need to introduce a change in the Grammarly Editor code, which is maintained by the Grammarly Editor team). Needing to coordinate across teams to make a change tends to introduce delays for delivering new features to users. Evaluating solutions As the Grammarly Editor team reflected on these challenges, we developed some requirements for a possible solution: - Offer easier ways to compose components via automatically deriving more complex state and action types, as well as managing state updates and action routing - Provide stronger guarantees around side effects—if a component uses a read-only state and emits actions, then it should not be possible for it to introduce a side-effect without emitting an action - Scale to support many experiment definitions at once, so that running A/B tests is manageable and easy to maintain We looked at several open source solutions for this. We were influenced by libraries like xReact, React Dream, MonadicReact, PureScript Sparkle, and Reflex DOM. But none fit our needs completely. We needed a solution that was written in TypeScript, worked nicely with our existing React code, and would allow us to alter the UI in a type-safe way. Introducing Embrace Embrace is a library for React UI composition with the focus on type safety and immutability. It also makes UI representation truly declarative: It treats UI components as data, which can be traversed, modified, logged, and more. Internally, Embrace uses Reactive Extensions and Focal, the same toolkit we use to build the Grammarly Editor. Key abstractions: UI Part and Flow The first core abstraction in Embrace is UI Part, which represents—you guessed it—a part or component of the UI. UI Parts, which can have branching children, take as input an Rx Observable representing state and output an Rx Observable representing actions: UI Parts make explicit what we had previously been modeling manually: A UI component is restricted to producing a stream of events in response to a user action or some other trigger. In code, the UI Part interface looks like a function: interface MountProps<State, Action, Slots> { readonly children: Record<Slots, Rx.Observable<React.ReactNode>> readonly state: Rx.Observable<State> notify(i: Action): void } interface UIPart<State, Action, Slots> { (props: MountProps<State, Action, Slots>) => ReactElement } Given an instance of MountProps, a UI Part will produce a ReactElement that can be mounted (though mounting in Embrace is different from mounting in React—more on this later on). MountProps represents the three key components of a UI Part: the observable state, the new actions, and optional children. The second main abstraction in Embrace is a Flow, which can be thought of as an inverted UI Part. It accepts a stream of actions and produces a stream of states (actions “flow” into state updates): In code, the Flow interface represents a function from an Observable of actions to an Observable of states: export interface Flow<Action, State> { (actions: Rx.Observable<Action>) => Rx.Observable<State> } Unlike React’s mount, mounting Embrace’s UI Part will produce a React Element out of a UI Part and matching Flow. The resulting Element will have its re-renders triggered every time a Flow produces a new State. Note that Embrace’s mount will only work if the UI Part has actions and states that match those of the corresponding Flow. // a button has a string state and can emit click actions declare const Button: UI.Node<string, 'click'> // corresponding flow must listen for clicks and produce string states declare const flow: (s: Rx.Observable<'click'>) => Rx.Observable<string> // mount will only work (i.e. produce react element) // if UI Part's and Flow types match const app: React.ReactElement<any> = UI.mount(Button, flow) Using Embrace The job of a programmer using Embrace is to compose an entire application out of small parts into one big UI Part, and to produce a Flow for the resulting application. Embrace helps by providing a set of abstractions and utilities that can be used to define and compose UI Parts and pieces of Flows. By composing many UI Parts, you can create a single application Flow with Embrace. As data, the app’s UI tree can be easily traversed and modified. A mandatory “counter app” example Let’s look at how a counter app can be defined using Embrace: import { Flow, UI } from 'embrace' const counterUI = UI.Node.make<number, 'plus' | 'minus'>(({ state, notify}) => ( <F.div> <button onClick={notify('minus')}>-</button> {state} <button onClick={notify('plus')}>+</button> </F.div> ) const counterFlow: Flow.For<typeof counterUI> = (actions: Rx.Observable<'plus' | 'minus'>) => { return actions.pipe( Rx.scan((acc, a) => (a === 'plus' ? acc + 1 : acc - 1), 0), Rx.startWith(0) ) } Here we define a counter view as a UI Node (one of the many kinds of UI Parts that Embrace provides). This UI Node’s state is a number and it can emit a plus or minus action; it cannot have child parts. We use Focal’s React primitives to define the body of the counter UI, where state is an Observable of numbers and notify is a function used to emit new actions. The flow for such an app will receive an Observable of plus and minus actions and emit new number states. We use standard Rx operators to define a simple flow that will maintain an accumulated number. The flow should always have an initial state value for Embrace to be able to do the initial render of the app, so we start with 0. // returns React.ReactElement const CounterApp = UI.mount(counterUI, counterFlow) Mounting the counter app Composing and nesting UI Parts Previously, we discussed how it would be nice to be able to compose components with different states and actions together to automatically produce more complex state and action types. Embrace does just that. When two or more UI Parts are composed, Embrace will automatically produce a new Part, with state and actions reflecting the types of the internal Parts that were combined. Embrace magically produces a new Part from two or more composed parts, reducing the need for boilerplate code. There are different ways in which UI Parts can be composed. You may want to render one of the two Parts at a time, or render a list of Parts, or provide a layout with slots where other Parts may fit. Embrace has a number of abstractions that can be used to do this and more. For example, with a Knot, which is one of the kinds of UI Parts provided by Embrace, you can define an entire webpage. The main component can contain your content as a string. You can emit a scroll action, and you can include two slots, a header, and a footer, which you could fill with other UI Parts that take their own state and emit their own actions. declare const App: UI.Knot< { content: string }, 'scroll', { header: UI.Node<{ title: boolean; color: string }, 'hover' | 'unhover'> footer: UI.Node<{ link: boolean }, 'click'> } > Embrace then will automatically derive all the different types of the state and actions that the resulting application has, leaving the developer to simply provide a corresponding Flow for the app to work. When a UI Part is composed of multiple smaller parts, Embrace will automatically include all the types of states and actions in the resulting Flow. As a result, we no longer need to write code to manually orchestrate state and actions flow through the hierarchy of UI components. Patching the UI Until a UI Part is mounted, it can be thought of as a tree data structure. And as data, it can be easily traversed and modified. We call a process of changing a UI Part “patching” as we often need to alter one or more nodes in our app’s UI tree, for example, to implement an experiment. A patch is a pure function from one version of an Embrace app to another. Returning to the example webpage app from above, what if we wanted to produce another version that would work similarly but without a footer? Embrace’s patch function can do just that, in a type-safe way: const AppWithoutFooter = pipe( App, UI.patch('footer')(_oldFooter => UI.Node.empty) ) The resulting App will contain an empty Node (a kind of UI Part that does not have slots) in its footer, removing the need to provide the corresponding footer’s state and react to its actions when defining the Flow. Having an ability to “patch” UIs in a type-safe way by providing a function from one version of the UI to another means that now we can define our experiments outside of our main application code. const removeFooterExperiment = UI.patch('footer')(() => UI.Node.empty) const anotherExperiment = UI.patch(/*...*/) // array of all experiments for current users const appForUser = pipe( App, removeFooterExperiment, anotherExperiment // cannot use footer here ) Experiments defined as functions on our UI We can even place these functions in a separate repository, and we won’t have to worry about managing breaking changes, as the TypeScript compiler will help us detect any such changes when updating to a newer version of the package containing the unmodified app. As a result, Grammarly’s Growth team could now implement their experiments without having to touch the code in the Grammarly Editor repository. Summing it up We’ve found that Embrace requires a very different way of thinking as a programmer. As a declarative engine, Embrace adds layers of abstraction that require you to take a step back and think through what you’re trying to achieve, rather than just diving in to write code. But that extra thought feels worth it. Embrace lets you make UI code behave almost like a logical equation, with every element completely encapsulated—resulting in front-end code that’s elegant, maintainable, and easily extensible by many teams. We’re excited to be using Embrace today in production to rewrite parts of the Grammarly Editor codebase. That being said, the library is a work in progress, and will continue to become even better with feedback from the community. We hope you’ll find these ideas and the library itself useful, and we look forward to hearing from you on Github! By the way—Grammarly is also hiring. If you’d like to come build new features to improve communication for millions of users around the world, check out our open roles here.
https://www.grammarly.com/blog/engineering/introducing-embrace/
CC-MAIN-2021-49
en
refinedweb
New Open Document Parser that emmits structured XHTML content. -------------------------------------------------------------- Key: TIKA-172 URL: Project: Tika Issue Type: Improvement Components: parser Affects Versions: 0.2-incubating Reporter: Uwe Schindler The current Open Document parser is very simplistic. It only creates a paragraph with the whole text content of ODF documents in it. The problem is also, that all whitespace is stripped. The attached patch is a new and SAX-featured (so low memory capable) parser without using external libraries for ODF. The structure of ODF content.xml files is very clean (and identical for all types of documents) and maps very good to XHTML. It is possible to map paragraphs to <p> tags and headings to <hX>-Tags. Also tables (and so spreadsheets) are identical to HTML rules. The idea behind this parser is a simple tag mapping approach. A new ContentHandlerDecorator in the o.a.t.sax-Package is able to simple map element names and attributes by a Map<javax.xml.namespace.QName,...). For each mapping a second mapping for the attributes Map<javax.xml.namespace.QName,javax.xml.namespace.QName> is available that maps the attributes. All not mappable attributes are thrown away. Tag names not in the mapping are are also not reported to the delegate. With this new decorator, it is possible to map all ODF content.xml names to XHTML using a static map in the parser class. In addition to this some extra-handling for special cases in ODF are done in the SAX handler, that receives the parsing events (that extends ElementMappingContentHandler) is done: a) only direct content of tags from the text:-namespace are reported to characters(), this excludes style tags and so on. b) some tags and *all* its content are left out (Templates for TOC, additional cells for col/rowspan handling) c) mapping of <text:h> to HTML <hX> is done by using the heading level (in ODF in an attribute of <text:h>). As there are still some OpenOffice version 1.0 documents around (.sxw-files) that use old namespace declarations in meta.xml and content.xml (the current parser fails to parse metadata and content of such documents), an additional ContentHandlerDecorator is used, that maps all old namespaces beginning with "" to the "urn:oasis..." ones. If support for such ld document types is not needed, we could simply leave out this additional decorator. This is a very clean and good working approach for ODF files. In my opinion, this could also be done in a similar way for OpenXML files for MS Office 2007. I looked into the new POI version, that has text extraction support for OpenXML, but this uses a lot of additional XML parser libraries, DOM trees and does not use SAX, and is memory intensive. I think (I will read the specs from Microsoft the next days) and maybe I will create the same infracstruture for OpenXML, too. As POI is for OLE2 document format, it should only be used for this and not the XML based OpenXML. -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.us.apache.org/mod_mbox/tika-dev/200811.mbox/%3C1526977694.1226770064474.JavaMail.jira@brutus%3E
CC-MAIN-2021-49
en
refinedweb
Namespaces There are no resources, and hence no privileges, associated with InterSystems IRIS namespaces. The InterSystems.
https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=TSQS_NAMESPACES
CC-MAIN-2021-49
en
refinedweb
Core Security Patterns: Securing the Identity--Design Strategies and Best Practices - Identity Management Security Patterns - Best Practices and Pitfalls - References Topics in This Chapter - Identity Management Security Patterns - Best Practices and Pitfalls In Chapter 7, “Identity Management Standards and Technologies,” we introduced the identity management and the relevant security standards, such as SAML, Liberty, and XACML. SAML is an XML protocol for representing authentication and authorization assertions and is used for single sign-on and global logout. Liberty reuses the security assertion framework from SAML and extends it with different identity profiles and framework. XACML provides a versatile policy management framework for administering access control rules and managing security policies. These security standards are important because they allow different security vendor products to interoperate with each other. Architects and developers are now able to work with different security infrastructures without rewriting most of the security components. In a heterogeneous application infrastructure environment, each application system may have different user authentication mechanisms and customized authorization schemes. Enabling unified access with single sign-on and exit with global logout is a complex process. To handle this, architects and developers may need to build custom mechanisms or ensure that the current sign-on mechanisms support open standards such as SAML and Liberty. In either case, there is much similar processing logic and code in the Identity tier that can be refactored for reuse. You may also want to extract some commonly used security processing into helper classes instead of embedding the security processing logic into each of the authentication and authorization functions. If different versions of security packages are used simultaneously (for example, due to support for legacy systems), it would be useful to build an abstraction layer (using façde or delegate patterns) so that the identity management functionality can support multiple versions with backward compatibility. In these scenarios, adopting security patterns would be useful in addressing these requirements in the Identity tier. In identity management, security patterns can provide a common design framework, unified SSO, and global-logout mechanisms for use with heterogeneous applications. They can also reduce significant design and development effort, because they simplify complexity while they capture many security best practices. Using abstraction, these security patterns can shield off custom-built or specific-vendor APIs, and this can reduce the impact of vendor lock-in if customers want to switch to another vendor product. Additionally, because security standards are still evolving, the abstraction layer in the security pattern can help mitigate the risk of migrating to new security standards. There are many security vendor products and open source toolkits available in the market today that support SAML, Liberty, and XACML. Some security vendor products provide administrator-friendly agents or adapters so that you do not need to customize their applications by adding SAML protocols or Liberty identity profiles to their software program code. This is particularly useful for those who have a large amount of packaged applications purchased from vendors. Nevertheless, there are many of them who have home-grown applications that need to work with standards-based identity management architecture. This mandates a reusable identity management framework and security patterns to resolve the recurring problems and complexities. Identity Management Security Patterns Assertion Builder Pattern Problem You need a structured and consistent approach to gathering security information (for example, SAML assertions) about the authentication action performed on a subject, attribute information about the subject, or an authorization request from a trusted service provider. Security assertions are authentication and authorization-related information exchanged between trusted service providers and requesters, and are used as a common mechanism for enabling applications to support SSO without requiring the client to login multiple times. To enable a trusted environment, we need to address the requirements of SSO with heterogeneous applications, discrete authentication schemes, authorization policies, and other related attributes in use. This requires having a generic mechanism for constructing and processing SAML-based assertions. Forces - You want to avoid duplicate program logic for building authentication assertion, authorization decision assertion, and attribute statements. - You need to apply common processing logic to similar security assertion statements. - You need a helper class to extract similar processing logic to build SAML assertion statements instead of embedding them into the authentication and authorization processes. - You want the flexibility to support client requests from a servlet, EJB client, or a SOAP client. Solution Use an Assertion Builder to abstract similar processing control logic in order to create SAML assertion statements. The Assertion Builder pattern encapsulates the processing control logic in order to create SAML authentication statements, authorization decision statements, and attribute statements as a service. Each assertion statement generation shares similar program logic of creating the SAML header (for example, schema version) and instantiating the assertion type, conditions, and subject statement information. The common program logic can also be used to avoid locking in with a specific product implementation. By exposing the Assertion Builder as a service, developers can also access SAML assertion statement creation using SOAP protocol binding without creating separate protocol handling routines. Under a single sign-on environment (refer to Figure 12–3), a client authenticates with a single sign-on service provider (also known as the source site) and later requests access to a resource from a destination site. Upon successful authentication, the source site is able to redirect the client request to the destination site, assuming that the source site has a sophisticated security engine that determines the client is allowed to access the destination site. Then, the destination site will issue a SAML request to ask for an authentication assertion from the source site. The Assertion Builder will be used to assemble sign-on information and user credentials to generate SAML assertion statements. This is applicable for both the source site (processing SAML responses) and the destination site (processing SAML requests). The destination site will then respond to the client for resource access. Subsequently, the destination site will handle authorization decisions and attribute statements to determine what access level is allowed for the client request. Figure 12–1 depicts a high-level architecture diagram of the Assertion Builder pattern. In a typical application scenario, developers can design an Assertion Builder to provide the service of generating SAML authentication statements, SAML authorization decision statements, and SAML attribute statements. The Assertion Builder creates a system context (Assertion Context) and produces a SAML assertion statement (Assertion), which can be an authentication statement, an authorization decision statement, or an attribute statement. An EJB client can perform a JNDI service look-up of the SAML Assertion Builder service and invoke the preliminary utilities to assemble the SAML headers. After that, it invokes the relevant statement generation function, such as authentication statement. Similarly, a servlet can perform service invocation by acting as an EJB client. For a SOAP client, the Assertion Builder service bean needs to be exposed as a WSDL. Upon service invocation, the Assertion Builder utilities will marshal and unmarshal the SOAP envelope when the protocol binding is set to SOAP. Structure Figure 12–2 shows a class diagram for Assertion Builder service. The core Assertion Builder service consists of two important classes: AssertionContext and Assertion. The AssertionContext class defines the public interfaces for managing the system context when creating SAML assertion statements, SAML assertion types, and the protocol binding. If the SAML binding is set to be SOAP over HTTP, then the Assertion Builder service needs to wrap the SAML artifacts with a SOAP envelope instead of the HTTP header. It has a corresponding implementation class called AssertionContextImpl. Figure 12–1 Assertion Builder logical architecture Figure 12–2 Assertion Builder class diagram The Assertion class refers to the SAML assertion statement object. It contains basic elements of subject information (such as subject’s IP address, subject’s DNS address), source Web site, and destination Web site for the creation of SAML assertion statements. There is a corresponding data class called Subject, which refers to the principal for the security authentication or authorization. Each Assertion contains a Subject element. The Assertion class is also extended into AuthenticationStatement, AuthorizationDecisionStatement, and AttributeStatement. Each of these three assertion statement classes is responsible for creating SAML assertion statements, respectively, according to the SAML 2.0 specification. Attribute is a data class that encapsulates the distinctive characteristics of a subject and denotes the attributes in a SAML attribute statement. Participants and Responsibilities Figure 12–3 depicts a use case scenario where a client is requesting resource access from a destination site via the source site that acts as a single sign-on service provider. Client refers to a Web browser that initiates the resource access request. SourceSite denotes the single sign-on service provider that manages security information about which resources can be accessible in other affiliated sites, including DestinationSite. DestinationSite denotes the target site with resources that Client intends to access. Figure 12–3 Assertion Builder sequence diagram This is a scenario for a Web browser interacting with the source and destination sites with single sign-on (i.e., browser profile), and it is not applicable to a server-to-server single sign-on scenario. The Assertion Builder pattern is implemented for Steps 3 through 14. The other steps are provided here to provide a better context only. - Client accesses resources provided by the service provider (SourceSite). - SourceSite verifies if Client is authenticated already. - SourceSite creates an instance of AssertionBuilder. In this scenario, the instance is for creating a SAML authentication assertion request. - DestinationSite also creates an instance of AssertionBuilder. This is for creating a SAML authentication assertion response. - AssertionBuilder retrieves SAML protocol binding (for example, SOAP binding) for the interaction with SourceSite or DestinationSite. - SourceSite redirects the resource access to the destination site DestinationSite via URL redirection. - Client accesses the artifact receiver URL. - AssertionBuilder assembles information to build the SAML header and tokenizes the user credentials (i.e., creates any security token from the user credentials) to facilitate the interaction with DestinationSite. - AssertionBuilder creates the relevant protocol binding. For example, if this is a SOAP binding, then AssertionBuilder creates the SOAP envelope and uses the SOAP binding protocol. - AssertionBuilder creates a SAML assertion statement (for example, SAML authentication assertion request) and sends it to DestinationSite. - DestinationSite issues a SAML request for any authentication assertion statement to SourceSite. - AssertionBuilder assembles information to build the SAML header and tokenizes the user credentials to facilitate interaction with SourceSite. - AssertionBuilder creates the relevant protocol binding. For example, if this is a SOAP binding, then AssertionBuilder creates the SOAP envelope and uses the SOAP binding protocol. - AssertionBuilder creates a SAML assertion statement (for example, SAML authentication assertion response) and sends it to SourceSite. - SourceSite issues a SAML response to DestinationSite. - DestinationSite responds to user response for resources at the destination site. Strategies Protocol Binding Strategy It is possible that the same client may be using a mixture of SOAP over HTTP and SOAP over HTTPS SAML requests under different use case scenarios. It is important to be flexible about the protocol binding so that different protocols are supported. To accommodate such flexibility, developers can use a custom protocol binding look-up function to determine which SAML protocol binding is used for the SAML request. Time Checking Strategy Developers can add extra security control by adding timestamp comparison control for processing SAML responses in order to address the security risks of replay, message insertion, or message deletion. They can also compare the AuthenticationInstant timestamp in the SAML request and the SAML response. Typically, the timestamp in the SAML response is slightly behind the SAML request time. Another extension is to define a timeout strategy for the authentication timestamp. For example, a strategy might be that the destination site will not allow access for a client request if the authentication timestamp is over 120 minutes ago. Audit Control Strategy Although the subject IP and DNS addresses are optional in the current SAML 1.1 or 2.0 specifications, it is always a good design strategy to capture them for audit control purposes. For example, some hackers may be able to replay SAML assertion statements within the customer LAN. By tracking the subject IP and DNS addresses, security architects and developers are able to quickly detect any SAML assertion statements with unusual IP and DNS addresses. Using Assertion Builder Pattern in Single Sign-on The Assertion Builder pattern should be used in conjunction with the Single Sign-on Delegator (refer to next section for details). The Single Sign-on Delegator shields off the design complexity of remote communication with different assertion statement creation services and utilities of the Assertion Builder, as well as other single sign-on services such as Java Connector for legacy systems. This is particularly useful when these single sign-on services are provided in a variety of technologies, such as EJBs, servlets, Java Beans, and custom applications. Consequences By employing the Assertion Builder pattern, developers will be able to benefit in the following ways: - Addresses broken authentication flaw. The Assertion Builder pattern can be used to build a helper class that creates and sends SAML authentication statements between trusted service providers. The SAML authentication statement denotes security information regarding authentication data about the subject. This helps to safeguard the authentication mechanisms from a potential broken authentication flaw. - Addresses broken access control risk. The Assertion Builder pattern can be used to create SAML authorization decision and attribute statements. The SAML authorization decision statement denotes a critical decision about granting or denying resource access for a subject. This helps to safeguard the access control mechanisms from potential broken access control flaws. - Enables transparency by encapsulating the assertion statements. The Assertion Builder pattern encapsulates three different assertion statement creation functionalities with similar processing logic. It is easier to maintain and use. In addition, architects and developers do not need to embed the processing logic of building SAML assertion statements in the business processing logic. - Reduces the complexity of integration. The Assertion Builder pattern allows a flexible service invocation from a variety of clients, including servlets, EJB clients, and SOAP clients. It reduces the integration effort with different platforms. Sample Code Example 12–1 shows a sample code excerpt for creating an Assertion Builder for SAML assertion requests. The example creates a SAML authentication statement, a SAML authorization decision statement, and a SAML attribute statement. It defines the assertion type (using the setAssertionType method), initializes the assertion statement object, and sets relevant attributes (for example, setAuthenticationMethod for an authentication statement) for the corresponding assertion statement object. Then it uses the createAssertionStatement method to generate the SAML assertion statement in a document node object. It checks its validity upon completion of the SAML statement creation. It also retrieves the service configurations and protocol bindings (for example, SOAP over HTTP binding) before building SAML assertion statements. Example 12–1 Sample Assertion Builder implementation package com.csp.identity; import java.util.ArrayList; import java.util.Collection; public class AssertionBuilder { // common variables and constants protected com.csp.identity.AssertionContextImpl assertionFactory; protected com.csp.identity.Subject subject; protected static final String authMethod = "urn:oasis:names:tc:SAML:1.0:am:password"; protected static final String sourceSite = ""; protected static final String destinationSite = ""; protected static final String subjectDNS = "dns.coresecuritypattern.com"; protected static final String subjectIP = "168.192.10.1"; protected static final String subjectName = "Maryjo Parker"; protected static final String subjectQualifiedName = "cn=Maryjo, cn=Parker, ou=authors, o=coresecurity, o=com"; // authentication assertion specific protected com.csp.identity.AuthenticationStatement authenticationStatement; protected org.w3c.dom.Document authAssertionDOM; // authorization decision assertion specific protected com.csp.identity.AuthorizationDecisionStatement authzDecisionStatement; protected static final String decision = "someDecision"; protected static final String resource = "someResource"; protected java.util.Collection actions = new ArrayList(); protected java.util.Collection evidence = new ArrayList(); protected org.w3c.dom.Document authzDecisionAssertionDOM; // attribute assertion specific protected com.csp.identity.AttributeStatement attributeStatement; protected com.csp.identity.Attribute attribute; protected Collection attributeCollection = new ArrayList();; protected org.w3c.dom.Document attributeStatementDOM; /** Constructor - Creates a new instance of AssertionBuilder */ public AssertionBuilder() { // common assertionFactory = new com.csp.identity.AssertionContextImpl(); subject = new com.csp.identity.Subject(); subject.setSubjectName(subjectName); subject.setSubjectNameQualifier(subjectQualifiedName); assertionFactory.setAssertionType (com.csp.identity.AuthenticationStatement .ASSERTION_TYPE); // ====create authentication statement============= // create authentication assertion object attribute authenticationStatement = new com.csp.identity.AuthenticationStatement(); assertionFactory.setAuthenticationMethod(authMethod); authenticationStatement.setSourceSite(sourceSite); authenticationStatement .setDestinationSite(destinationSite); authenticationStatement.setSubjectDNS(subjectDNS); authenticationStatement.setSubjectIP(subjectIP); authenticationStatement.setSubject(subject); // create authentication statement System.out.println("**Create authentication statement **"); authAssertionDOM = assertionFactory.createAssertionStatement ((com.csp.identity.AuthenticationStatement) authenticationStatement); //===end of create authentication statement ======== //====create authorization decision statement======= // create authorization decision assertion // object attribute authzDecisionStatement = new com.csp.identity.AuthorizationDecisionStatement(); authzDecisionStatement.setSourceSite(sourceSite); authzDecisionStatement .setDestinationSite(destinationSite); authzDecisionStatement.setSubjectDNS(subjectDNS); authzDecisionStatement.setSubjectIP(subjectIP); authzDecisionStatement.setResource(resource); authzDecisionStatement.setDecision(decision); authzDecisionStatement.setSubject(subject); assertionFactory.setAssertionType (com.csp.identity.AuthorizationDecisionStatement .ASSERTION_TYPE); // Prepare evidence this.evidence.add("Evidence1"); this.evidence.add("Evidence2"); this.evidence.add("Evidence3"); authzDecisionStatement.setEvidence(evidence); // Prepare action this.actions.add("Action1"); this.actions.add("Action2"); this.actions.add("Action3"); authzDecisionStatement.setActions(actions); // create authorization decision statement System.out.println("**Create authorization decision statement **"); authzDecisionAssertionDOM = assertionFactory.createAssertionStatement ((com.csp.identity.AuthorizationDecisionStatement) authzDecisionStatement); // ===end of create authorization statement ====== // =====create attribute statement ============= // create attribute assertion object attribute attributeStatement = new com.csp.identity.AttributeStatement(); attributeStatement.setSourceSite(sourceSite); attributeStatement.setDestinationSite(destinationSite); attributeStatement.setSubjectDNS(subjectDNS); attributeStatement.setSubjectIP(subjectIP); attributeStatement.setSubject(subject); assertionFactory.setAssertionType (com.csp.identity.AttributeStatement.ASSERTION_TYPE); // Prepare attribute attribute = new com.csp.identity.Attribute(); this.attributeCollection.add("Attribute1"); this.attributeCollection.add("Attribute2"); this.attributeCollection.add("Attribute3"); this.attribute.setAttribute(attributeCollection); attributeStatement.addAttribute(attribute); // create attribute statement System.out.println("**Create attribute statement **"); attributeStatementDOM = assertionFactory.createAssertionStatement ((com.csp.identity.AttributeStatement) attributeStatement); // ===end of create attribute statement === } public static void main(String[] args) { new AssertionBuilder(); } } Example 12–2 shows how an authentication statement is implemented. An authentication statement extends the object Assertion, which is an abstraction of SAML assertion statements (including the SAML authentication statement, authorization decision statement, and attribute statement). This authentication statement is intended to implement how a SAML authentication assertion is created. The previous createAuthenticationStatement method in the last section will invoke the create method from the AuthenticationStatement class in order to create a SAML authentication statement. The create method can be implemented using custom SAML APIs, provided by a SAML implementation offered by open source or commercial vendor solution. In this example, the create method uses a constructor from the OpenSAML library to create a SAML authentication statement and checks for the validity of the SAML assertion statement. Example 12–2 Sample AuthenticationStatement code package com.csp.identity; import java.util.Date; import org.opensaml.*; public class AuthenticationStatement extends com.csp.identity.Assertion { static final String ASSERTION_TYPE = "AUTHENTICATION"; protected com.csp.identity.AuthenticationStatement authStateFactory; /** Constructor - Creates a new instance of AuthenticationStatement * */ public AuthenticationStatement() { } /** * Get instance of the existing authentication * assertion statement * If instance does not exist, create one * * @return AuthenticationStatement instance of * Authentication statement */ public com.csp.identity.AuthenticationStatement getInstance() { if (authStateFactory == null) { authStateFactory = new AuthenticationStatement(); if (authStateFactory == null) System.out.println("WARNING – authStat is null"); } return this.authStateFactory; } /** * Create SAML authentication assertion statement * **/ public void create() { // This example uses OpenSAML 1.0 // but you can use your custom SAML APIs or vendor APIs org.opensaml.SAMLSubject samlSubject; java.util.Date authInstant = new Date(); String samlSubjectIP = this.getSubjectIP(); String samlSubjectDNS = this.getSubjectDNS(); org.opensaml.SAMLNameIdentifier samlNameIdentifier; try { // Create SAML Subject object using OpenSAML 1.0 samlNameIdentifier = new org.opensaml.SAMLNameIdentifier (this.subject.getSubjectName(), this.subject.getSubjectNameQualifier(),""); samlSubject = new org.opensaml.SAMLSubject (samlNameIdentifier, null, null, null); // Create SAML authentication statement // using OpenSAML 1.0 org.opensaml.SAMLAuthenticationStatement samlAuthStat = new org.opensaml.SAMLAuthenticationStatement (samlSubject, authInstant, samlSubjectIP, samlSubjectDNS, null); samlAuthStat.checkValidity(); System.out.println("DEBUG - The current SAML authentication statement is valid!"); } catch (org.opensaml.SAMLException se) { System.out.println("ERROR - Invalid SAML authentication assertion statement"); se.printStackTrace(); } } } Example 12–3 shows an example of creating a system context for the Assertion Builder pattern, which stores the service configuration and protocol binding information for creating and exchange SAML assertion statements. The AssertionContextImpl class is an implementation of the public interfaces defined in the AssertionContext class. This allows better flexibility in adding extensions or making program changes in the future. Example 12–3 Sample AssertionContext implementation package com.csp.identity; public class AssertionContextImpl implements com.csp.identity.AssertionContext { protected String authMethod; protected String assertionType; protected com.csp.identity.AuthenticationStatement authStatement; protected com.csp.identity.AuthorizationDecisionStatement authzDecisionStatement; protected com.csp.identity.AttributeStatement attributeStatement; protected org.w3c.dom.Document domTree; /** Constructor - Creates a new instance of AssertionContextImpl */ public AssertionContextImpl() { } /** set assertion type * @param String assertion type, for example authentication, * attribute **/ public void setAssertionType(String assertionType) { this.assertionType = assertionType; } /** create SSO token * * @param Object security token **/ public void createSSOToken(Object securityToken) { ... } /** check for valid SAML statement * * @return boolean true/false **/ public boolean isValidStatement() { // to be implemented return false; } /** set authentication method * * @param String authentication method **/ public void setAuthenticationMethod(String authMethod) { this.authMethod = authMethod; } /** get authentication method * * @return String authentication method **/ public String getAuthenticationMethod() { return this.authMethod; } /** create SAML assertion statement * * Note - the @return has not been implemented. * * @return org.w3c.dom.Document xml document **/ public org.w3c.dom.Document createAssertionStatement (Object assertObject) { System.out.println("DEBUG - Create SAML assertion in XML doc"); if (this.assertionType.equals (com.csp.identity.AuthenticationStatement .ASSERTION_TYPE)) { // create SAML authentication statement // using OpenSAML 1.0 authStatement = (com.csp.identity.AuthenticationStatement) assertObject; authStatement.create(); } else if (this.assertionType.equals (com.csp.identity.AuthorizationDecisionStatement .ASSERTION_TYPE)) { // create SAML authorization decision // statement using // OpenSAML 1.0 authzDecisionStatement = (com.csp.identity.AuthorizationDecisionStatement) assertObject; authzDecisionStatement.create(); } else if (this.assertionType.equals( com.csp.identity.AttributeStatement.ASSERTION_TYPE)) { // create SAML authorization decision statement // using // OpenSAML 1.0 attributeStatement = (com.csp.identity.AttributeStatement) assertObject; attributeStatement.create(); } return null; } /** get SAML assertion statement * * @return org.w3c.dom.Document xml document **/ public org.w3c.dom.Document getAssertionStatement() { // to be implemented return null; } /** remove assertion statement * **/ public void removeAssertionStatement() { // to be implemented } /** create assertion reply * * @return org.w3c.dom.Document xml document **/ public org.w3c.dom.Document createAssertionReply(Object assertionRequest) { ... return null; } /** get assertion reply * * @return org.w3c.dom.Document xml document **/ public org.w3c.dom.Document getAssertionReply() { ... return null; } /** remove assertion reply * **/ public void removeAssertionReply() { ... } /** set protocol binding * * @param String protocol binding **/ public void setProtocolBinding (String protocolBinding){ ... } /** get protocol binding * * @return String protocol binding **/ public String getProtocolBinding() { ... return null; } } Security Factors and Risks The Assertion Builder pattern is a reusable design that simplifies the creation of SAML assertion statements and can cater to either the synchronous or asynchronous mode of service invocation. The following discusses the security factors associated with the Assertion Builder pattern and the potential risk mitigation. - Configuration issues. Assertion Builder relies on strong authentication by the identity provider. Improper configuration of authentication mechanisms and flawed credential management that compromises application authentication through password change will still lead to broken authentication. - Identity theft. If a user identity is stolen by attackers who uses the user ID and password for proper authentication, Assertion Builder will not be able to address such a security risk. Use of XML Signature will help verifying the signer and also ensure the message is integral and tamper-proof during transit. - Confidentiality. Using the HTTPS protocol to protect the client-to-server session is a stronger means of supporting confidentiality, because no unauthorized user can snoop the SAML assertion statements from the wire. - XML digital signature. Using XML digital signature to the SAML assertion statements assures that no one can modify or tamper with the message content. - Reliability. SAML assertion statements can be bound to a reliable data transport mechanism such as SOAP over JMS. This ensures that the recipient (either the source site or the destination site) can reliably get the SAML request or response. Reality Check - Should we build assertion builder code from scratch? There are a few security vendor products that have out-of-the-box SAML assertion statement builder capability. In this case, architects and developers may either directly invoke the SAML assertion builder function or abstract them under the Assertion Builder pattern. - Capturing IP address. Although the SAML assertion statement allows capturing the source IP address, it is rather difficult to capture the real IP address in real life because real IP addresses can be translated into another virtual IP address or hidden from proxies. However, it is still a good practice to capture the IP address for verifying the origin host for authenticity, troubleshooting and other auditing purposes. - Dependency on authentication infrastructure. It is plausible to enable single sign-on security by using SAML assertions alone. However, SAML assertions depend on an existing authentication infrastructure. - Migration from SAML 1.1 to SAML 2.0. There are some deprecated items and changes in SAML 2.0. The SAML specifications do not provide guidance on how to migrate from SAML 1.1 to SAML 2.0, or how to make them compatible between trading partners running different SAML versions. Thus, it is important to cater to service versioning of SAML messages and to migrate the messaging infrastructure to SAML 2.0. Related Patterns - Single Sign-on Delegator. Single Sign-on Delegator provides a delegate design approach to connect to remote security services and enables single sign-on within the same security domain or across multiple security domains. It is a good fit to use Assertion Builder in conjunction with Single Sign-on Delegator. Single Sign-on (SSO) Delegator Pattern Problem You want to hide the complexity of interacting directly with heterogeneous service invocation methods or programming models of remote identity management or single sign-on service components. In a heterogeneous security environment, you may need to use multiple vendor products to build their custom identity management functionality, such as account provisioning and authentication. Each vendor product may require different service invocation methods or programming models. If developers design the client to interact directly with remote identity management or single sign-on service interfaces, they probably need to add vendor-specific or fine-grained business logic in the client. This usually results in deploying a heavy client footprint or building rich clients that are loaded with complex security-specific business logic. Thus, such tight-coupling of the client directly with vendor-specific business logic creates many limitations for scalability in client-side performance, network connectivity, server-side caching, and support of a large number of simultaneous connections. In addition, you need to explicitly handle different types of network or system exceptions in the individual vendor-specific business logic while invoking the remote security services directly. One related problem is software code maintenance and release control issues. If any identity management service interface changes, for example, due to a change in security standards or API specifications, developers have to maintain any corresponding client-side code changes. The client-side code also needs to be redeployed. This is quite a considerable software release control and maintenance issue because the tight-coupling architecture model is not flexible enough to accommodate software code changes. Another problem is the lack of a flexible programming model for adding or managing new identity management functionalities if the existing vendor-specific APIs currently do not support them. For example, if the current security application architecture does not support global logout, it defeats the purpose of Single Sign-on in an integration environment, which may create authentication issues and session hijacking risks. At the worst, developers are required to rewrite the security application architecture every time they integrate a new application. Developers may also need to add newer functionalities in order to achieve Single Sign-on. Forces - You want to minimize the coupling between the clients and the remote identity management services for better scalability or for easier software maintenance. - You want to streamline adding or removing identity management or single sign-on security service components (such as global logout), without reengineering the client or back-end application architecture. - You want to hide the details of handling heterogeneous service invocation bindings (for example, EJB and asynchronous messaging) and service configuration of multiple security service components (for example, identity server and directory server) from the clients. - You want to translate network exceptions caused by accessing different identity management service components into the application or user exceptions. Solution Use a Single Sign-on Delegator to encapsulate access to identity management and single sign-on functionalities, allowing independent evolution of loosely coupled identity management services while providing system availability. A Single Sign-on Delegator resides in the middle tier between the clients and the identity management service components. It delegates the service request to the remote service components. It de-couples the physical security service interfaces and hides the details of service invocation, retrieval of security configuration, or credential token processing from the client. In other words, the client does not interact directly with the identity management service interfaces. The Single Sign-on Delegator in turn prepares for Single Sign-on, configures the security session, looks up the physical security service interfaces, invokes appropriate security service interfaces, and performs global logout at the end. Such loosely coupled application architecture minimizes the change impact to the client even though the remote security service interfaces require software upgrade or business logic changes. A Business Delegate pattern would not be appropriate because it simply delegates the service request to the corresponding remote business components. It does not cater to configuring the security session or delegating to the remote security service components using the appropriate security protocols and bindings. Alternatively, developers can craft their own program construct to access remote service components. Using a design pattern approach to refactor similar security configuration (or preambles) for multiple remote security services into a single and reusable framework will enable higher reusability. The Single Sign-on Delegator pattern refactors similar security session processing logic and security configuration, and increases reusability. To implement the Single Sign-on Delegator, you apply the delegator pattern that shields off the complexity of invoking service requests of building SAML assertions, processing credential tokens, performing global logout, initiating security service provisioning requests, and any custom identity management functions from heterogeneous vendor product APIs and programming models. They can create a unique service ID for each remote security service, create a service handler for each service interface, and then invoke the target security service. Under this delegator framework, it is easy to use the SAML protocol to perform single sign-on across remote security services. Similarly, it is also flexible enough to implement global logout by sending logout requests to each remote service because the delegator holds all unique service IDs and the relevant service handlers. You can also use the Single Sign-on Delegator in conjunction with J2EE Connector Architecture. Single Sign-on Delegator can populate the security token or security context to legacy system environments, including ERP systems or EIS. If ERP systems have their own connectors or adapters, Single Sign-on Delegator can also exchange security tokens by encapsulating their connector APIs. One major benefit of using the Single Sign-on Delegator is the convenience of encapsulating access to vendor-specific identity management APIs. Doing so shields the business components from changes in the underlying security vendor product implementation. Structure Figure 12–4 depicts a class diagram for the Single Sign-on Delegator. The client accesses the Single Sign-on Delegator component to invoke the remote security service components (SSOServiceProvider). The delegator (SSODelegator) retrieves security service configuration and service binding information from the system context (SSOContext) based on the client request. In other words, the client may be using a servlet, EJB, or Web services to access the identity management service. The delegator can also look up the service location via JNDI look-up or service registry look-up (if this is a Web service) according to the configuration details or service bindings. This can simplify the design construct for accommodating multiple security protocol bindings. Figure 12–4 Single Sign-on Delegator class diagram There are three important classes in Figure 12–4: SSOContext, SSODelegatorFactory and SSOServiceProvider. The SSOContext is a system context that encapsulates the service configuration and protocol binding for the remote service providers. It also stores the service status and the component reference (aka handler ID) for the remote service provider. The SSOContextImpl class is the implementation for the SSOContext class. The SSODelegatorFactory defines the public interfaces to creating and closing a secure connection to the remote service provider. It takes a security token from the service requester so that it can validate the connection service request under a single sign-on environment. When a secure connection is established, the SSODelegatorFactory will also create a SSOToken used internally to reference it with the remote service provider. The SSODelegatorFactoryImpl class is the implementation for SSODelegatorFactory. The SSOServiceProvider class defines the public interfaces for creating, closing, or reconnecting to a remote service. Figure 12–4 shows two examples of service providers (SSOServiceProviderImpl1 and SSOServiceProviderImpl2) that implement the public interfaces. Participants and Responsibilities Figure 12–5 shows a sequence diagram that depicts how to apply a delegator pattern to different identity management services via the Single Sign-on Delegator. In this scenario, the client wants to perform a single sign-on across different business services within the same domain (i.e., the same customer environment). The client (Client) refers to the service requester that initiates the service requests to multiple applications. The Single Sign-on Delegator (SSODelegator) connects to the remote business services. It retrieves the security service configuration information from the SSOContext service and looks up the service location via the naming service ServiceLocator. Finally, it keeps track of all connections using the service handlers and/or unique service IDs to perform single sign-on or global logout. The following shows the interaction between Client and SSODelegator: - Client wants to invoke remote services via SSODelegator. SSODelegator verifies if Client is authorized to invoke remote security services. - Upon successful verification, Client creates a delegator instance of _SSODelegator. - SSODelegator retrieves service configuration (for example, EJB class name) and protocol bindings (for example, RMI method for EJB) from SSOContext. - SSOContext sends service configurations and protocol bindings to SSODelegator. - SSODelegator creates a single sign-on session using the method createSSODConnection and records the user ID and timestamp in the session information using the method setSessionInfo. - Client initiates a request to invoke a remote service. - SSODelegator creates a service connection to invoke the remote service provider using the method createService. - SSODelegator retrieves the service configuration details (for example, EJB class) and protocol bindings for the remote service. - SSODelegator looks up the service location of the remote security service using ServiceLocator (for example, via JNDI look-up for the remote EJB). - SSODelegator invokes the remote security service by class name or URI. - SSODelegator adds the component reference (also referred to as handler ID) to the SSOContext. - Client requests to log out and close the connection of existing remote security services. - SSODelegator begins to close the security service. - SSODelegator initiates a closeSSOConnection to close the remote service. - SSODelegator removes the component reference from SSOContext. It may also remove any existing session information by invoking the method removeSessionInfo. - SSODelegator now completes closing the single sign-on session. - SSODelegator notifies Client for successful global logout and closing security services. Figure 12–5 Single Sign-on Delegator sequence diagram Strategies Using Single Sign-on Delegator and Assertion Builder Together The Single Sign-on Delegator pattern provides a design framework for implementing single domain or cross-domain single sign-on using Liberty and SAML It also makes use of the Assertion Builder pattern to create SAML assertion statements for authentication, authorization, or attributes. Figure 12–6 depicts a use case scenario where a client (Client) needs to access multiple resources within the internal security domain. In order to access any resource, the client needs to authenticate with an identity service provider to establish the identity first. Once successful authentication is complete, it can initiate an authentication assertion request to access multiple resources within the single sign-on environment. The service provider (ServiceProvider) uses an identity server product to act as an identity service provider (IdentityProvider), which handles authentication for single sign-on purposes. The agent (WebAgent) is a Web server or application server plug-in that intercepts the authentication requests using the Liberty protocol to provide single sign-on. In this scenario, the service provider runs an application server with a Liberty-compliant agent. Both SSODelegator and AssertionBuilder refer to the design patterns discussed earlier in this chapter. The following provides a step-by-step description of the interaction: Figure 12–6 Single sign-on using Single Sign-on Delegator and Assertion Builder sequence diagram - Client initiates a single sign-on request to access resources under the internal identity provider (or external identity provider). - ServiceProvider creates an instance of single sign-on delegator. - SSODelegator initiates an authentication assertion request with AssertionBuilder. - Before AssertionBuilder creates an authentication assertion, Client needs to perform an authentication with the identity service provider first. Thus, ServiceProvider redirects the authentication request from Client. - ServiceProvider initiates an HTTP authentication request with IdentityProvider. - ServiceProvider obtains the relevant identity service provider identifier (there may be multiple identity service providers). - ServiceProvider uses WebAgent (running on top of the application server) to respond to the authentication request. - WebAgent redirects the authentication request to IdentityProvider. - IdentityProvider processes the authentication request. It presents the authentication login form or HTML page to Client. - Upon submission of the authentication login form by Client, IdentityProvider sends the authentication request response artifact to WebAgent. - WebAgent sends the request with authentication response artifact to ServiceProvider. - ServiceProvider processes the HTTP request with the authentication response artifact with IdentityProvider. - IdentityProvider sends the HTTP response with the authentication assertion. - ServiceProvider processes the authentication assertion. - ServiceProvider sends the HTTP response with the authentication assertion. - WebAgent returns the authentication assertion statement. Global Logout Strategy The Single Sign-on Delegator pattern can also act as a control mechanism for implementation of global logout, because it creates a connection to remote services and keeps track of each unique component reference to remote services (handle ID). If a client is invalidated in the presentation tier, the Single Sign-on Delegator can issue a timely global logout to ensure session integrity. Once a client decides to sign out from all remote security services, the Single Sign-on Delegator can simply retrieve the service configuration (from SSOContext) or service location information (from ServiceLocator). Then they relay the logout request to each security service. Figure 12–7 depicts a use case scenario for global logout: - Client initiates a request for global logout from all remote security services. - SSODelegator verifies if Client is authorized to log out from all remote services. - Upon successful verification, Client creates an instance of SSODelegator. - SSODelegator retrieves the service configurations and protocol bindings from SSOContext. - SSOContext sends the details of service configurations and protocol bindings to SSODelegator. - SSODelegator fetches all service identifiers from all existing security service connections. - SSODelegator looks up security service location from ServiceLocator. - ServiceLocator returns the service location of remote services. - SSODelegator initiates a global logout request to each remote service. Figure 12–7 Global logout using Single Sign-on Delegator sequence diagram Identity Termination / Revocation Strategy If the user identity is terminated or revoked by the identity provider or the service provider, the identity management system should not allow the user to continue to create a single sign-on session. Liberty Phase 2 defines a federation termination notification protocol for handling identity termination or revocation (refer to Chapter 7). The Single Sign-on Delegator should be able to subscribe to the federation termination notification protocol. If a user identity is terminated by the identity provider or service provider in the midst of a single sign-on session, the Single Sign-on Delegator should be able to terminate the single sign-on session using the global logout strategy. Consequences By employing the Single Sign-on Delegator pattern, developers will be able to reap the following benefits: - Thwarting session theft. Session theft is a critical security flaw to identity management. The Single Sign-on Delegator creates a secure single sign-on session and delegates the service requests to relevant security services. Client requests must be authenticated with an identity provider before they can establish a secure single sign-on session. This can mitigate the risk of session theft. - Addressing multiple sign-on issues. The Single Sign-on Delegator pattern supports a standards-based single sign-on framework that does not require users to sign on multiple times. There are security attacks that target application systems that are vulnerable due to multiple sign-on actions being required. Thus, the Single Sign-on Delegator can mitigate the multiple sign-on issues. - More flexibility with a loosely coupled architecture. The Single Sign-on Delegator pattern provides a loosely coupled connection to remote security services. It minimizes the coupling between the clients and the remote identity management services. It hides the details of the handling of heterogeneous service invocation bindings and the service configuration of • multiple security service components from the clients. It also avoids specific-vendor product lock-in by disallowing clients to invoke the remote security services directly. - Better availability of the remote security services. Architects and developers can implement or customize automatic recovery of the remote security services. They can also provide an alternate security services connection if the primary remote security service is not available. - Improves scalability. Architects and developers can have multiple connections to the remote security services. Multiple instances of the remote security services will help improve scalability. In addition, architects and developers can cache some of the session variables or user identity information on behalf of the presentation tier components, which may help boost performance if there are a large number of simultaneous user connections. Sample Code Example 12–4 and Example 12–5 show a scenario where a service requester (for example, telecommunications subscriber) intends to access a variety of remote services via a primary service provider (for example, a telecommunication online portal). These sample code excerpts illustrate how to create a Single Sign-on Delegator pattern (using SSODelegatorFactoryImpl) to manage invoking remote security services using EJB. The Client creates an instance of the SSODelegatorFactoryImpl using the method getSSODelegator, and then invokes the method createSSOConnection to start a remote service. Upon completion, the Client invokes the method closeSSOConnection to close the remote service. The SSODelegatorFactoryImpl creates a single sign-on connection, invokes individual security service, and maintains session information. The code comment adds some annotation about how to add your own code to meet your local requirements or to extend the functionality. In Example 12–4, the SSODelegatorFactoryImpl class initializes itself in the constructor by loading the list of “authorized” service providers (using the method initConfig). Then it creates a SSO token using the method createSSOToken to reference to all remote service connections. When the Client requests creating a single sign-on connection to a remote service, SSODelegatorFactoryImpl requires the Client to pass a security token for validation Upon successful validation of the security token, the SSODelegatorFactoryImpl will look up the Java object class or URI of the remote service via the servicelocator method from the SSOContext. The SSOContext stores the service status and service configuration of the remote service. The service locator method is a service locator pattern that provides a few methods to look up the service location via EJB or Web services. The sample methods used in this code excerpt are examples only. The details can be found at [CJP2], pp. 315-340, or. The SSODelegatorFactoryImpl will then invoke the createService method of the remote service. It will update the service status “CREATED”). The component reference to the remote service will be added to SSOContext. When the Client requests to close the remote service, the SSODelegatorFactoryImpl will invoke the closeService method of the remote service. It will update the service status to “CLOSED” and remove the component reference in the SSOContext. Example 12–4 Sample SSODelegatorFactory implementation package com.csp.identity; import java.util.HashMap; import com.csp.identity.*; public class SSODelegatorFactoryImpl implements com.csp.identity.SSODelegatorFactory { protected HashMap<String, com.csp.identity.SSOContextImpl> servicesMap = new HashMap(); // store serviceName, context protected HashMap<String, Object> SSOTokenMap = new HashMap(); // store serviceName, SSOToken protected static com.csp.identity.SSODelegatorFactoryImpl singletonInstance = null; protected String ssoToken; /** Constructor - Creates a new instance of SSODelegatorFactoryImpl */ private SSODelegatorFactoryImpl() { // load config file for all security authorized service // providers in Context initConfig(); createSSOToken(); } /** * Validate security token before creating, closing or * reconnecting to remote * service provider. * You can implement your security token validation process as * per local requirements. * You may want to reuse Credential Tokenizer to encapsulate * the security token. * * In this example, we'll always return true for demo purpose. */ private boolean validateSecurityToken(Object securityToken) { ノ return true; } /** * Create createSSOConnection(Object securityToken, String serviceName) throws com.csp.identity.SSODelegatorException { if (validateSecurityToken(securityToken) == true) { System.out.println("Security token is valid"); try { // load Java object class (or URI) via // serviceLocator com.csp.identity.SSOContextImpl context = servicesMap.get(serviceName); String className = context.serviceLocator(serviceName); Class clazz = Class.forName(className); com.csp.identity.SSOServiceProvider serviceProvider = (com.csp.identity.SSOServiceProvider)clazz.newInstance(); // invoke remote security service provider serviceProvider.createService(context); // update status=CREATE context.setStatus(context.REMOTE_SERVICE_CREATED); // update servicesMap and context context.setCompRef(serviceProvider); servicesMap.remove(serviceName); servicesMap.put(serviceName, context); this.setSSOTokenMap(serviceName); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); throw new com.csp.identity.SSODelegatorException("Class not found"); } catch (InstantiationException ie) { ie.printStackTrace(); throw new com.csp.identity.SSODelegatorException("Instantiation exception"); } catch (IllegalAccessException iae) { iae.printStackTrace(); throw new com.csp.identity.SSODelegatorException("Illegal access exception"); } } else { // update status=error System.out.println("Invalid security token presented!"); throw new com.csp.identity.SSODelegatorException("Invalid securitiy token"); } } /** * Close closeSSOConnection); com.csp.identity.SSOServiceProvider serviceProvider = context.getCompRef(); if (serviceProvider == null) { throw new com.csp.identity.SSODelegatorException ("SSO connection not made."); } // invoke remote security service provider serviceProvider.closeService(); // update status=CLOSED context.setStatus(context.REMOTE_SERVICE_CLOSED); // update servicesMap and context context.removeCompRef(); servicesMap.remove(serviceName); servicesMap.put(serviceName, context); this.removeSSOTokenMap(serviceName); } else { // update status=error System.out.println("Invalid security token presented!"); throw new com.csp.identity.SSODelegatorException("Invalid securitiy token"); } } /** * Load the configuration into the SSODelegatorFactory * implementation so that * it will know which are the remote service providers * (including the * logical service name and the object class/URI for service * invocation. * * For demo purpose, we hard-coded a few examples here. * We can * also use * Apache Commons Configuration * to load a config.xml property * file. */ private void initConfig() { // load a list of "authorized" security // service providers // from the config file // and load into an array of SSOContext try { // create sample data com.csp.identity.SSOContextImpl context1 = new com.csp.identity.SSOContextImpl(); com.csp.identity.SSOContextImpl context2 = new com.csp.identity.SSOContextImpl(); context1.setServiceName("service1"); context1.setProtocolBinding("SOAP"); context2.setServiceName("service2"); context2.setProtocolBinding("RMI"); this.servicesMap.put("service1", context1); this.servicesMap.put("service2", context2); } catch (com.csp.identity.SSODelegatorException se) { se.printStackTrace(); } } /** * * You need to pass a security token before you can get the * SSODelegator instance. * Rationale: * 1. This ensures that only authenticated/authorized * subjects * can invoke the SSO Delegator. * (authentication and authorization requirements). * 2. No one can invoke the constructor directly (visibility * and segregation requirements). * 3. In addition, there is only a singleton copy (singleton * requirement). * * @param Object security token */ public static com.csp.identity.SSODelegatorFactoryImpl getSSODelegator(Object securityToken) { synchronized (com.csp.identity.SSODelegatorFactoryImpl.class) { if (singletonInstance==null) { singletonInstance = new com.csp.identity.SSODelegatorFactoryImpl(); } return singletonInstance; } } /** * This private method creates a SSO token to resemble a SSO * session has been * created to connect to remote security service providers. * In practice, this security token should be implemented in * any object type * based on local requirements. You can also reuse the * SecurityToken object * type from the Credential Tokenizer. * * For demo purpose, we'll use a string. * You can also use the * String format * to represent a base64 encoded format of a SSO token. */ private void createSSOToken() { // to be implemented this.ssoToken = "myPrivateSSOToken"; } /** * Register a SSOToken in the HashMap that a remote * service provider * connection has been made. * * @param String serviceName */ private void setSSOTokenMap(String serviceName) { this.SSOTokenMap.put(serviceName, this.ssoToken); } /** * Get a SSOToken in the HashMap that a remote service * provider * connection has been made. * * @param String serviceName * @return Object SSOToken (in this demo, we'll use a * String object) */ private Object getSSOTokenMap(String serviceName) { return (String)this.SSOTokenMap.get(serviceName); } /** * Remove a SSOToken from the HashMap that a remote * service provider * connection has been made. * * @param String serviceName */ private void removeSSOTokenMap(String serviceName) { this.SSOTokenMap.remove(serviceName); } /** * Get status String getServiceStatus); return context.getStatus(); } else { // update status=error System.out.println("Invalid security token presented!"); throw new com.csp.identity.SSODelegatorException("Invalid securitiy token"); } } } Example 12–5 shows sample code for implementing the SSOContext. The _SSOContextImpl class provides methods to add or get the service configuration and protocol binding for the remote service. When a new remote service is connected, the SSOContextImpl will add the component reference (aka handler ID) to the remote service using the method setCompRef and will update the status using the method setStatus. Example 12–5 Sample SSOContext implementation package com.csp.identity; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Properties; import com.csp.identity.*; public class SSOContextImpl implements com.csp.identity.SSOContext { protected String serviceName; protected Properties configProps; protected String protocolBinding; protected HashMap sessionInfo = new HashMap(); protected com.csp.identity.SSOServiceProvider compRef; protected String status; protected final String REMOTE_SERVICE_CREATED = "CREATED"; protected final String REMOTE_SERVICE_CLOSED = "CLOSED"; protected final String REMOTE_SERVICE_ERROR = "ERROR"; protected enum ServiceStatus { CREATED, CLOSED, ERROR }; // Constructor - Creates a new instance // of SSOContextImpl public SSOContextImpl() throws com.csp.identity.SSODelegatorException { } /** * Set session information in a HashMap. * This stores specific * session variables * that are relevant to a particular remote secure service * provider * * @param String session variable name * @param String session variable value */ public synchronized void setSessionInfo(String sessionVariable, String sessionValue) { this.sessionInfo.put(sessionVariable, sessionValue); } /** * Get session information from a HashMap. This stores * specific session variables * that are relevant to a particular remote secure service * provider * Need to cast the object type upon return * * @return Object return in an Object (for example String). */ public synchronized Object getSessionInfo(String sessionVariable) { return this.sessionInfo.get(sessionVariable); } /** * Remove session information from a HashMap. The HashMap * stores specific session variables * that are relevant to a particular remote secure service * provider * * @param String session variable name */ public synchronized void removeSessionInfo(String sessionVariable) { this.sessionInfo.remove(sessionVariable); } /** * Get private configuration properties specific to a * particular * remote secure service provider. This object needs to be * loaded during * initConfig(), by the constructor or manually * * @return Properties a Properties object */ public java.util.Properties getConfigProperties() { return configProps; } /** * Set private configuration properties specific to a * particular * remote secure service provider. This object needs to be * loaded during * initConfig(), by the constructor or manually * * @param Properties a Properties object */ public void setConfigProperties(java.util.Properties configProps) { this.configProps = configProps; } /** * Get protocol binding for the remote security service * provider * * @return String protocol binding, for example SOAP, RMI * (arbitrary name) */ public String getProtocolBinding() { return this.protocolBinding; } /** * Set protocol binding for the remote security service * provider * * @param String protocol binding, for example SOAP, RMI (arbitrary * name) */ public void setProtocolBinding(String protocolBinding) { this.protocolBinding = protocolBinding; } /** * Get service name of the remote security service provider. * This name needs to match the field 'serviceName' in the * SSOServiceProvider implementation classes * * @return String service name, for example service1 */ public String getServiceName() { return this.serviceName; } /** * set service name * * @param String logical remote service name, for example service1 * **/ public void setServiceName(String serviceName) { this.serviceName = serviceName; } /** * Get component reference * * @return SSOServiceProvider component * reference to be stored * in the HashMap * once a connection is created **/ public com.csp.identity.SSOServiceProvider getCompRef() { return this.compRef; } /** * Set component reference * * @param SSOServiceProvider component * reference to be stored * in the HashMap * once a connection is created **/ public void setCompRef(com.csp.identity.SSOServiceProvider compRef) { this.compRef = compRef; } /** * Remove component reference * **/ public void removeCompRef(){ this.compRef = null; } /** * Look up the class name or URI by the service name * * This example hardcodes one class name for demo. * You may want to replace it by a Service Locator pattern * * @param String service name to look up * @return String class name (or URI) corresponding service **/ public String serviceLocator(String serviceName) { // This example shows 2 remote // security service providers // hard-coded for demo purpose. Refer to the book’s // website for sample code download. // You may want to use a Service Locator pattern here if (serviceName.equals("service1")) { return "com.csp.identity.SSOServiceProviderImpl1"; } if (serviceName.equals("service2")) { return "com.csp.identity.SSOServiceProviderImpl2"; } return "com.csp.identity.SSOServiceProviderImpl2"; } /** * set status of the remote service * * @param String status */ public void setStatus(String status) { this.status = status; } /** * get status of the remote service * * @return String status */ public String getStatus() { return this.status; } } Security Factors and Risks - Caching user identity information. Caching user identity information in shared memory (for example, implemented in a hash table) is a mechanism used by the Single Sign-on Delegator to improve performance. However, there is also a security risk if any other application client can access the shared memory. Thus, architects and developers need to ensure that cached information is protected and is accessible to the Single Sign-on Delegator only. - Logging and audit risks. Security compliance and local regulations often require all user login and security activities to be logged and audited through out the user sign-on session. The logging and audit requirements can help to track down any unusual password changes or suspicious transaction changes under the single sign-on session. The security risk is extremely high if the single sign-on session control does not log all user authentication and access control changes throughout the session for audit control. Reality Check - Too many abstraction layers. Single Sign-on Delegator brings the benefit of loosely coupled architecture by creating an abstraction layer for remote security services. However, if the remote security services have more than one abstraction layer, multiple abstraction layers of remote service invocations will create substantial performance overhead. From experience, one to two abstraction layers would be reasonable. - Supporting multiple circles of trust. Currently, Liberty specification 2.0 does not support integrating multiple circles of trust or interoperating with multiple identity service providers simultaneously (for example, when a client wants to perform single sign-on in two different circles of trust or in two different types of single sign-on environments). Single Sign-on Delegator is not designed to support multiple circles of trust, because it is a delegate design approach that simplifies the connection of remote security services. The support of interoperating with multiple identity service providers is dependent on the Liberty implementation or the remote security services. Related Patterns - Assertion Builder. A Single Sign-on Delegator can delegate the creation of SAML assertion statements via the Assertion Builder to a remote security service provider that assembles and generates a SAML authentication or authorization decision statement. This does not require adding the business logic of managing SAML assertions in the Single Sign-on Delegator. - Credential Tokenizer. A Single Sign-on Delegator can delegate the encapsulation of user credentials to the Credential Tokenizer. This does not require building additional business logic to handle user credentials in the Single Sign-on Delegator. Architects and developers can also reuse the credential tokenizer functions for other applications (for example, EDI messaging applications) without using Single Sign-on Delegator. - Service Locator. The Single Sign-on Delegator pattern uses a Service Locator pattern to look up the service location of the remote security services. In other words, it delegates the service look-up function to a Service Locator, which can be implemented as a JNDI look-up or a UDDI service discovery. Refer to and [CJP2] for details. Credential Tokenizer Pattern Problem You need a flexible mechanism to encapsulate a security token that can be used by different security infrastructure providers. There are different forms of user credentials (also referred to as security tokens), such as username/passwords, binary security tokens (for example, X.509v3 certificates), Kerberos tickets, SAML tokens, smart card tokens and biometric samples. Most security tokens are domain-specific. To encapsulate these user credentials for use with different security product architectures, developers have to modify the security token processing routine to accommodate individual security product architectures, which depends on the specific security specification the security product uses. A user credential based on a digital certificate will be processed differently than that of a Kerberos ticket. There is no consistent and flexible mechanism for using a common user credential tokenizer that supports different types of security product architectures supporting different security specifications. Forces - You need a reusable component that helps to extract processing logic to handle creation and management of security tokens instead of embedding them in the business logic or the authentication process. - You want to shield off the design and implementation complexity using a common mechanism that can accommodate a security credential and interface with a supporting security provider that makes use of them. Solution Use a Credential Tokenizer to encapsulate different types of user credentials as a security token that can be reusable across different security providers. A Credential Tokenizer is a security API abstraction that creates and retrieves the user identity information (for example, public key/X.509v3 certificate) from a given user credential (for example, a digital certificate issued by a Certificate Authority). Each security specification has slightly different semantics or mechanisms to handle user identity and credential information. These include the following characteristics: - Java applications that need to access user credentials or security tokens from different application security infrastructures. - Web Services security applications that need to encapsulate a security token, such as username token or binary token, in the SOAP message. - Java applications that support SAML or Liberty that need to include an authentication credential in the SAML assertion request or response. - Java applications that need to retrieve user credentials for performing SSO with legacy applications. To build a Credential Tokenizer, developers need to identify the service, authentication scheme, application provider, and underlying protocol bindings. For example, in a SOAP communication model, the service requestor is required to use a digital certificate as a binary security token for accessing a service end-point. In this case, the service configuration specifies the X.509v3 digital certificate as the security token and SOAP messages and SOAP over HTTPS as the protocol binding. Similarly, in a J2EE application, the client is required to use a Client-certificate for enabling mutual authentication. In this case, the authentication requirements specify an X.509v3 digital certificate as the security token and SOAP over HTTPS as the protocol binding, but the request is represented as HTML generated by a J2EE application using a JSP or a servlet. Credential Tokenizer provides an API abstraction mechanism for constructing security tokens based on a defined authentication requirement, protocol binding, and application provider. It also provides API mechanisms for retrieving security tokens issued by a security infrastructure provider. Structure Figure 12–8 depicts a class diagram of the Credential Tokenizer. The Credential Tokenizer can be used to create different security tokens (SecurityToken), including username token and binary tokens (X.509v3 certificate. When creating a security token, the Credential Tokenizer creates a system context (TokenContext) that encapsulates the token type, the name of the principal, the service configuration, and the protocol binding that the security token supports. Figure 12–8 Credential Tokenizer class diagram There are two major objects in the Credential Tokenizer: SecurityToken and TokenContext. The SecurityToken is a base class that encapsulates any security token. It can be extended to implement username token (UsernameToken), binary token (_BinaryToken), and certificate token (X509v3CertToken). In this pattern, Username token is used to represent a user identity using Username Password. Binary tokens are used to represent a variety of security tokens that resemble a user identity using binary text form (such as Kerberos Tickets). Certificate tokens denote digital certificates issued to represent a user identity. An X.509v3 certificate is a common form of certificate token. The TokenContext class refers to the system context used to create security tokens. It includes information such as the security token type, service configuration, and protocol binding for the security token. This class defines public interfaces only to set or get the security token information. TokenContextImpl is the implementation for TokenContext. Participants and Responsibilities Figure 12–9 depicts the Credential Tokenizer sequence diagram—how a client makes use of the Credential Tokenizer to create a security token. For example, the Client may be a service requester that is required to create the Username Password-token to represent in the WS-Security headers of a SOAP message. The CredentialTokenizer denotes the credential tokenizer that creates and manages user credentials. The UserCredential denotes the actual Credential Token, such as username/password or a X.509v3 digital certificate. The following sequences describe the interaction between the Client, CredentialTokenizer, and UserCredential: - Client creates an instance of CredentialTokenizer. - CredentialTokenizer retrieves the service configuration and the protocol bindings for the target service request. - CredentialTokenizer retrieves the user credentials from SecurityProvider according to the service configuration. For example, it extracts the key information from an X.509v3 certificate. - CredentialTokenizer creates a security token from the user credentials just retrieved. - Upon successful completion of creating the security token, CredentialTokenizer returns the security token to Client. Figure 12–9 Credential Tokenizer sequence diagram Strategies Service Provider Interface Approach Using a service provider interface approach to define the public interfaces for different security tokens will be more flexible and adaptive for different security tokens and devices. For example, certificate tokens may differ in vendor implementation. Developers can use the same public interfaces to support different credential token implementations and meet the requirements of different platforms and service providers without customizing the APIs for specific devices. Protocol Binding Strategy As with the Assertion Builder pattern, it is possible that the same client may be using the Credential Tokenizer to encapsulate user credentials as a security token in a SOAP message. To accommodate such use, developers can employ a custom service configuration look-up function (for example, refer to getProtocolBinding method in the SSOContext discussed in SSO Delegator pattern) to determine the data transport and application environment requirements. In this way, the common processing logic of the user credential processing and security token encapsulation can be reused. Consequences - Supports SSO. The Credential Tokenizer pattern helps in capturing authentication credentials for multifactor authentication. It also helps in using “shared state” (the “shared state” mechanism allows a login module to put the authentication credentials into a shared map and then passes it to other login modules) among authentication providers in order to establish single sign-on, where the Credential Tokenizer can be used for retrieving the SSO token and providing SSOToken on demand for requesting applications. - Provides a vendor-neutral credential handler. The Credential Tokenizer pattern wraps vendor-specific APIs using a generic mechanism in order to create or retrieve security tokens from security providers. - Enables transparency by encapsulating multiple identity management infrastructures. The Credential Tokenizer pattern encapsulates any form of security token as a credential token and thus eases integration and enables interoperability with different identity management infrastructures. Sample Code Example 12–6 shows a sample code excerpt for creating a Credential Tokenizer. The CredentialTokenizer creates an instance of TokenContextImpl, which provides a system context for encapsulation of the security token created. To create a security token, you need to define the security token type using the method setTokenType. Then you need to create the security token using the method createToken, which invokes the constructor of the target security token class (for example, UsernameToken). Example 12–6 Sample Credential Tokenizer implementation package com.csp.identity; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; public class CredentialTokenizer { protected com.csp.identity.TokenContextImpl context; protected com.csp.identity.UsernameToken usernameToken; protected java.security.cert.X509Certificate cert; // in dev/production, you won't put the subject, principal // or password here protected final String testPrincipal = "username"; protected final String testPassword = "password"; /** Constructor - Creates a new instance of CredentialTokenizer */ public CredentialTokenizer() { context = new com.csp.identity.TokenContextImpl(); //-------------For UsernameToken------------------------- context.setTokenType (com.csp.identity.UsernameToken.TOKEN_TYPE); context.createToken(testPrincipal, testPassword); //--------------------------------------------------**/ } public static void main(String[] args) { new CredentialTokenizer(); } } Example 12–7 shows a sample implementation for the TokenContext. The TokenContextImpl is an implementation of the public interfaces defined in the TokenContext class. The former can provide methods to fetch the name of the principal (getPrincipal method) and the protocol binding for the security token (getProtocolBinding method). Example 12–7 Sample TokenContext implementation package com.csp.identity; public class TokenContextImpl implements com.csp.identity.TokenContext { protected com.csp.identity.UsernameToken usernameToken; protected com.csp.identity.BinaryToken binaryToken; protected com.csp.identity.X509CertToken x509CertToken; protected String tokenType; /** Constructor - Creates a new instance of CredentialTokenizer */ public TokenContextImpl() { usernameToken = null; binaryToken = null; x509CertToken = null; } /** * Define token type * - use the constant in each security token subclass to * define * * @param tokenType security token type, for example USERNAME_TOKEN, * X509CERT_TOKEN, BINARY_TOKEN, KERBEROS_TICKET **/ public void setTokenType(String tokenType) { this.tokenType = tokenType; } /** * create security token based on the subject, principal * and security token * * @param principal principal * @param securityToken security token can be * binary,username, X.509v3 certificate, * Kerberos ticket, etc * **/ public void createToken(String principal, Object securityToken) { if (this.tokenType.equals (com.csp.identity.UsernameToken.TOKEN_TYPE)) { //System.out.println("create a usernametoken..."); usernameToken = new com.csp.identity.UsernameToken(principal, (String)securityToken); } else if (this.tokenType.equals(com.csp.identity.BinaryToken.TOKEN_TYPE)) { System.out.println("create a binary token..."); binaryToken = new com.csp.identity.BinaryToken(principal, (String)securityToken); } } /** * get security token * * @return Object any security token type, * for example String, X.509v3 certificate **/ public Object getToken() { if (this.tokenType.equals(com.csp.identity.UsernameToken.TOKEN_TYPE)) { //System.out.println("get a usernametoken..."); return (Object)usernameToken.getToken(); } else if (this.tokenType.equals(com.csp.identity.BinaryToken.TOKEN_TYPE)) { //System.out.println("get a binary token..."); return (Object)binaryToken.getToken(); } else return null; } /** * get principal * * @return principal return principal in String **/ public String getPrincipal() { if (this.tokenType.equals(com.csp.identity.UsernameToken.TOKEN_TYPE)) { //System.out.println("get principal..."); return usernameToken.getPrincipal(); } else if (this.tokenType.equals(com.csp.identity.BinaryToken.TOKEN_TYPE)) { //System.out.println("get principal..."); return binaryToken.getPrincipal(); } else return null; } /** * get protocol binding for the security token * * @return protocolBinding protocol binding in String **/ public String getProtocolBinding() { return null; } } Example 12–8 shows a sample implementation of the username token used in previous code examples (refer to Figure 12–15 and Figure 12–16). The UsernameToken class is an extension of the base class SecurityToken. It provides methods to define and retrieve information regarding the principal name, subject’s IP address, subject’s DNS address and the password. Example 12–8 Sample UsernameToken implementation package com.csp.identity; public class UsernameToken extends com.csp.identity.SecurityToken { protected static String password; static final String TOKEN_TYPE = "USERNAME_TOKEN"; /** Constructor - create usernameToken * * In future implementation, the constructor should be * private, and this class * should provide a getInstance() to fetch the instance. */ public UsernameToken(String principal, String password) { this.principal = principal; this.password = password; } /** * Get token ID from the binary token * * @return binaryToken security token in binary form */ public String getToken() { return this.password; } } Security Factors and Risks The Credential Tokenizer pattern is essential to encapsulating user credentials and user information to meet authentication and non-repudiation security requirements. One important security factor for building reliable credential tokenizers is the identity management infrastructure and whether the keys are securely managed prior to the credential processing. The following are security factors and risks associated with the Credential Tokenizer pattern. - Username password token. Username password tokens are highly vulnerable to attacks by using a password dictionary. - X.509v3 certificate token. Certificate token is a reliable security token and is stronger than Username Password token. However, it may be susceptible to human error during the management of the distribution of digital certificates and the timely revocation of certificates. - Key management strategy. The security factor of key management strategy defines the process of generating key pairs, storing them in safe locations, and retrieving them. The generation of SAML assertion statements and signed SOAP messages using WS-Security is key management strategy. If the key management strategy and the infrastructures are not in place, the user credential token processing will be at risk. Reality Check - Should we use username/password as a security token? Some security architects insist that the username/password pair is not secure enough and should not be used as a security token. To mitigate the potential risk of a weak password, security architects should reinforce strong password policies and adopt a flexible security token mechanism such as Credential Tokenizer to accommodate different types of security tokens for future extension and interoperability. - What other objects can be encapsulated as security token? You can embed different types of security tokens in the Credential Tokenizer, not just username/password or digital certificate. For example, you can embed binary security tokens, because they can be encapsulated as a SAML token for an authentication assertion statement. In addition, you can also add the REL token (which denotes the rights, usage permissions, constraints, legal obligations, and license terms pertaining to an electronic document) based on the eXtensible Rights Markup Language (XrML). Related Patterns - Secure Pipe. The Secure Pipe pattern shows how to secure the connection between the client and the server, or between servers when connecting between trading partners. In a complex distributed application environment, there will be a mixture of security requirements and constraints between clients, servers, and any intermediaries. Standardizing the connection between external parties using the same platform and security protection mechanism may not be viable.
https://www.informit.com/articles/article.aspx?p=1398626
CC-MAIN-2021-49
en
refinedweb
Creating a deep-assign library12th Aug 2020 I created a library to merge objects last week. It’s called mix. mix lets you perform a deep merge between two objects. The difference between mix and other deep merging libraries is: mix lets you copy accessors while others don’t. You can find out more about mix in last week’s article. I thought it’ll be fun to share the process (and pains) while building the library. So here it is. It started with solving a problem I had I started playing with accessor functions recently. One day, I noticed accessors don’t work when they’re copied via Object.assign. Since I wanted to copy accessors, Object.assign didn’t work for me anymore. I need another method. I did some research and discovered I can create an Object.assign clone that supports the copying of accessors quite easily. // First version, shallow merge. function mix (...sources) { const result = {} for (const source of sources) { const props = Object.keys(source) for (const prop of props) { const descriptor = Object.getOwnPropertyDescriptor(source, prop) Object.defineProperty(result, prop, descriptor) } } return result } I explained the creation process for this simple mix function in my previous article, so I won’t say the same thing again today. Go read that one if you’re interested to find out more. This simple mix function was okay. But it wasn’t enough. I wanted a way to make merge objects without worrying about mutation since mutation can be a source of hard-to-find bugs. This meant I needed a way to recursively clone objects. Researching other libraries First, I searched online to see if anyone created a library I needed. I found several options that copied objects, but none of them allowed copying of accessors. So I had to make something. In the process, I discovered I can use a combination of Lodash’s assign and deepClone functions to achieve what I want easily. Update: Mitch Neverhood shared that Lodash has a merge function that was deep. If we wanted an immutable merge, we could do this: import { cloneDeep, merge } from 'lodash'; export const immutableMerge = (a, b) => merge(cloneDeep(a), b); But Lodash was too heavy for me. I don’t want to include such a big library in my projects. I wanted something light and without dependencies. So I made a library. A journey into deep cloning objects When I started, I thought it’s easy to create deep clones of an object. All I had to do was - Loop through properties of an object - If the property is an object, create a new object Cloning object properties (even for accessors) are simple enough. I can replace the property’s descriptor value with a new object via Object spread. const object = { /* ... */ } const copy = {} const props = Object.keys(object) for (const prop of props) { const descriptor = Object.getOwnPropertyDescriptor(object, prop) const value = descriptor.value if (value) descriptor.value = { ...value } Object.defineProperty(copy, prop, descriptor) } This wasn’t enough because Object spread creates a shallow clone. I needed recursion. So I created a function to clone objects. I call it cloneDescriptorValue (because I was, in fact, cloning the descriptor’s value). // Creates a deep clone for each value function cloneDescriptorValue (value) { if (typeof value === 'object) { const props = Object.keys(value) for (const prop of props) { const descriptor = Object.getOwnPropertyDescriptor(value, prop) if (descriptor.value) descriptor.value = cloneDescriptorValue(descriptor.value) Object.defineProperty(obj, prop, descriptor) } return obj } // For values that don't need cloning, like primitives for example return value } I used cloneDescriptorValue like this: const object = { /* ... */ } const copy = {} const props = Object.keys(object) for (const prop of props) { const descriptor = Object.getOwnPropertyDescriptor(object, prop) const value = descriptor.value if (value) descriptor.value = cloneDescriptorValue(value) Object.defineProperty(copy, prop, descriptor) } This clones objects (including accessors) recursively. But we’re not done. Cloning arrays Although Arrays are objects, they’re special. I cannot treat them like normal objects. So I had to devise a new way. First, I needed to differentiate between Arrays and Objects. JavaScript has an isArray method that does this. // Creates a deep clone for each value function cloneDescriptorValue (value) { if (Array.isArray(value)) { // Handle arrays } if (typeof value === 'object) { // Handle objects } // For values that don't need cloning, like primitives for example return value } Arrays can contain any kind of value. If the array contained another array, I must clone the nested array. I did this by running every value through cloneDescriptorValue again. This takes care of recursion. // Creates a deep clone for each value function cloneDescriptorValue (value) { if (Array.isArray(value)) { const array = [] for (let v of value) { v = cloneDescriptorValue(v) array.push(v) } return array } // ... } I thought I was done. But I wasn’t 😢. Cloning functions…? The next day, I wondered if it’s possible to clone functions. We don’t want functions to mutate either, don’t we? I wasn’t sure whether I should do this. I wasn’t sure whether it was possible to clone functions too. A google search brought me to this deep-cloning article where I was reminded about other Object types like Date, Map, Set, and RegExp. (More work to do). It also talked about Circular references (which I did not handle in my library). I forgot all about cloning functions at this point. I went into the rabbit hole and tried to find ways to deep clone objects without writing each type of object individually. (I’m lazy). While searching, I discovered a thing known as the Structured Clone Algorithm. This sounds good. It’s exactly what I wanted! But even though the algorithm exists, there’s no way to actually use it. I couldn’t find its source anywhere. Then, I chanced upon Das Surma’s journey into deep-copying which talks about the Structured Clone Algorithm and how to use it. Surma explained we can use this Structured Clone Algorithm via three methods: - MessageChannel API - History API - Notification API All three API exist in browsers only. I wanted my utility to work both in Browsers and in Node. I couldn’t use any of these methods. I had to look for something else. The next day, I thought of Lodash. So I did a quick search. Lodash didn’t have a deep merge method. But I could clobber something together with _.assign and _.cloneDeep if I wanted. In its documentations, Lodash explained _.cloneDeep (which recursively uses _.clone) was loosely based on the Structured Clone Algorithm. I was intrigued and dove into the source code. Long story short, I wasn’t able to use Lodash’s source code directly since it was such a complicated library. But I managed to find a piece of gem that looked like this: var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; This piece tells me two things: - How to determine different types of objects like (RegExp, Map, Set, etc). - What objects are clone-able, and what objects aren’t. I can see that functions cannot be cloned, which makes sense, so I stopped trying to clone functions. // Part that tells me functions cannot be cloned cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; Cloning other types of objects The problem remains: I still need to recursively create clones for other types of objects. I started by refactoring my code to detect other object types. function cloneDescriptorValue (value) { if (objectType(value) === '[object Array]') { // Handle Arrays } if (objectType(value) === '[object Object]') { // Handle pure objects } // Other values that don't require cloning return } function objectType (value) { return Object.prototype.toString.call(value) } Then I started working on the simplest object type: Dates. Cloning Dates Dates are simple. I can create a new Date value that contains the same timestamp as the original Date. function cloneDescriptorValue (value) { // Handle Arrays and Objects if (objectType(value) === '[object Date]') { return new Date(value.getTime()) } // ... } I tackled Maps next. Deep Cloning Map Map is like Object with a few differences. One of them is: You can use objects as keys. If you used an object as a key, you won’t be able to retrieve the key’s values if I created a new object. So I opt to create clones only for map values. function cloneDescriptorValue (value) { // ... if (objectType(value) === '[object Map]') { const map = new Map() for (const entry of value) { map.set(entry[0], cloneDescriptorValue(entry[1])) } return map } // ... } I didn’t clone WeakMaps because we cannot iterate through WeakMaps. It’s was technically impossible to create a clone. Deep Cloning Set Sets are like arrays, but they contain unique values only. I decided to create a new reference for values in Sets because Lodash does it as well. function cloneDescriptorValue (value) { // ... if (objectType(value) === '[object Set]') { const set = new Set() for (const entry of value.entries()) { set.add(cloneDescriptorValue(entry[0])) } return set } // ... } More types… I decided to stop working on other types because I don’t use them at all. I didn’t want to write extra code that I won’t use (especially if no one else uses the library) Tests Of course, with any library creation, it’s important to write tests to ensure the library functions correctly. I wrote a couple of them while creating this project. 😎 Update: Preventing Prototype Pollution Kyle Wilson asked how I was preventing Prototype Pollution. I had complete no idea what he was talked about, so I did a search. Turns out, Prototype Pollution was a serious issue that used to be present in jQuery and Lodash. It may still be present in many libraries today! You can read more about it here. Without going into too much details, I just want to let you know I fixed this issue. Final mix function That’s it! Here’s the final mix function I created. I hope this article gives you an experience of the roller coaster ride when I experienced when creating the library. It’s not easy to create a library. I deeply appreciate people out there who have done the work and shared it with others. If you enjoyed this article, please tell a friend about it! Share it on Twitter. If you spot a typo, I’d appreciate if you can correct it on GitHub. Thank you!
https://zellwk.com/blog/creating-a-deep-assign-library/
CC-MAIN-2021-49
en
refinedweb
Crear cuenta - Registrarse I'm using python (Django Framework) to read a CSV file. I pull just 2 lines out of this CSV as you can see. What I have been trying to do is store in a variable the total number of rows the CSV also. How can I get the total number of rows? file = object.myfilePath fileObject = csv.reader(file) for i in range(2): data.append(fileObject.next()) I have tried: len(fileObject) fileObject.length python csv count import csv count = 0 with open('filename.csv', 'rb') as count_file: csv_reader = csv.reader(count_file) for row in csv_reader: count += 1 print count numline = len(file_read.readlines()) This works for csv and all files containing strings in Unix-based OSes: import os numOfLines = int(os.popen('wc -l < file.csv').read()[:-1]) In case the csv file contains a fields row you can deduct one from numOfLines above: numOfLines numOfLines = numOfLines - 1 Several of the above suggestions count the number of LINES in the csv file. But some CSV files will contain quoted strings which themselves contain newline characters. MS CSV files usually delimit records with \r\n, but use \n alone within quoted strings. For a file like this, counting lines of text (as delimited by newline) in the file will give too large a result. So for an accurate count you need to use csv.reader to read the records. Thank you for the comments. I tested several kinds of code to get the number of lines in a csv file in terms of speed. The best method is below. with open(filename) as f: sum(1 for line in f) Here is the code tested. import timeit import csv import pandas as pd filename = './sample_submission.csv' def talktime(filename, funcname, func): print(f"# {funcname}") t = timeit.timeit(f'{funcname}("{filename}")', setup=f'from __main__ import {funcname}', number = 100) / 100 print('Elapsed time : ', t) print('n = ', func(filename)) print('\n') def sum1forline(filename): with open(filename) as f: return sum(1 for line in f) talktime(filename, 'sum1forline', sum1forline) def lenopenreadlines(filename): with open(filename) as f: return len(f.readlines()) talktime(filename, 'lenopenreadlines', lenopenreadlines) def lenpd(filename): return len(pd.read_csv(filename)) + 1 talktime(filename, 'lenpd', lenpd) def csvreaderfor(filename): cnt = 0 with open(filename) as f: cr = csv.reader(f) for row in cr: cnt += 1 return cnt talktime(filename, 'csvreaderfor', csvreaderfor) def openenum(filename): cnt = 0 with open(filename) as f: for i, line in enumerate(f,1): cnt += 1 return cnt talktime(filename, 'openenum', openenum) The result was below. # sum1forline Elapsed time : 0.6327946722068599 n = 2528244 # lenopenreadlines Elapsed time : 0.655304473598555 n = 2528244 # lenpd Elapsed time : 0.7561274056295324 n = 2528244 # csvreaderfor Elapsed time : 1.5571560935772661 n = 2528244 # openenum Elapsed time : 0.773000013928679 n = 2528244 In conclusion, sum(1 for line in f) is fastest. But there might not be significant difference from len(f.readlines()). sum(1 for line in f) len(f.readlines()) sample_submission.csv is 30.2MB and has 31 million characters. sample_submission.csv I think we can improve the best answer a little bit, I'm using: len = sum(1 for _ in reader) Moreover, we shouldnt forget pythonic code not always have the best performance in the project. In example: If we can do more operations at the same time in the same data set Its better to do all in the same bucle instead make two or more pythonic bucles. First you have to open the file with open input_file = open("nameOfFile.csv","r+") Then use the csv.reader for open the csv reader_file = csv.reader(input_file) At the last, you can take the number of row with the instruction 'len' value = len(list(reader_file)) The total code is this: input_file = open("nameOfFile.csv","r+") reader_file = csv.reader(input_file) value = len(list(reader_file)) Remember that if you want to reuse the csv file, you have to make a input_file.fseek(0), because when you use a list for the reader_file, it reads all file, and the pointer in the file change its position row_count = sum(1 for line in open(filename)) worked for me. row_count = sum(1 for line in open(filename)) Note : sum(1 for line in csv.reader(filename)) seems to calculate the length of first line sum(1 for line in csv.reader(filename)) might want to try something as simple as below in the command line: sed -n '$=' filename or wc -l filename sed -n '$=' filename wc -l filename To do it you need to have a bit of code like my example here: file = open("Task1.csv") numline = len(file.readlines()) print (numline) I hope this helps everyone. try data = pd.read_csv("data.csv") data.shape and in the output you can see something like (aa,bb) where aa is the # of rows You need to count the number of rows: row_count = sum(1 for row in fileObject) # fileObject is your csv.reader Using sum() with a generator expression makes for an efficient counter, avoiding storing the whole file in memory. sum() If you already read 2 rows to start with, then you need to add those 2 rows to your total; rows that have already been read are not being counted. Use "list" to fit a more workably object. You can then count, skip, mutate till your heart's desire: list(fileObject) #list values len(list(fileObject)) # get length of file lines list(fileObject)[10:] # skip first 10 lines
http://publicatodo.co/Detalles/3311/Count-how-many-lines-are-in-a-CSV-Python-
CC-MAIN-2021-49
en
refinedweb
Transporting PI objects with NWDS (using CTS+) for Beginners For beginners in PI, it’s always been a challenge to get to know the PI objects transport mechanism. This drove me to write a simple blog for beginners to get to know how to attach PI developments to transports. Note: PI version being used is 7.31 with IFLOWS and CTS+ as transport strategy 1. Open NWDS process integration perspective and open CTS Organizer as shown below 2. Provide the logon information 3. Let us start by creating a transport request 4. Give the description and check “Preselect Request” 5. First we will get the ESR developments assigned to this request. Open ESR, select the development namespace, right click and select Export 6. Make sure the mode is selected as “Transport Using CTS” and then click continue. If this option is not appearing report to BASIS 7. In this screen select the namespace (all objects under this namespace will be transported). Click continue 8. In this screen the request we created should automatically appear since we preselected this request. Click on continue 9. All objects transported will be shown in this screen and click on finish to complete the export of ESR objects. Please do remember to attach any dependent objects also to this request by following the same process as above 10. Next, let us attach the IFLOW to the request. Navigate to the Export PI objects screen as shown below 11. Select transport type as CTS+ and Object type as Integration Flows. Click on next 12. Select the integration flow that needs to be assigned to transport 13. In this screen, all objects of the integration flow are shown. If any of the common components used across integration flows are already transported as per-requisite transport, please unselect them now. Click on next 14. Give the Export Description and click on finish to complete the export 15. All exports will be shown under the Object List tab of the transport request 16. Once the above process is done, please release the transport from CTS Organizer and inform BASIS to import to the target system. (Before importing to target system make sure the PI administrator would have maintained the required transport system targets in SLD) 17. Once we log in to the target system we can see that ESR objects are automatically activated and integration flow will be in the change list. We need to update the channel properties and activate Very informative blog. Really helpful. Thanks for the blog Sreedhar! Thanks! Hello Sreedhar, great blog post, thanks! Do you have further information how to enable cts+ in NWDS? Basis configure CTS+ for PO but we do not see the option in NWDS. Regards, Markus Markus, As of now I see this option only for "Process Integration" perspectives. I doubt it is supported for all others. Thanks, Sreedhar Sreedhar, it's a very informative blog! My transported iFlow uses an Integrated Configuration. Let me ask if you have any idea, how to transport the linkage between ICO and iFlow? If I transport the iFlow from NWDS, it "lost" its link to the ICO object in the Swing Tool. Thanks in advance for any ideas! Kind regards, Andras Andras, If we transport IFLOW all objects assosiated with it (channels, ICOs) will be transferred and the link will be retained, Can you please cross check all your configurations? Thanks, Sreedhar Sreedhar, I see your point. Indeed, all the related objects are present (channels, ICO, etc.) after transporting, the only thing which I'm still missing is the linkage of iFlow object to the used ICO. If you open the iFlow in the SWING tool, it remains empty not showing any used ICO (although it is there in the same integartion scenario). Maybe you faced this issue already... Thanks in advnace! Andras Andras, We never faced this issue. My suggestion is to re-deploy the iflow in QA through NWDS and check once. Thanks, Sreedhar Hi Sreedhar, Good Evening! Fantabulous blog! Keep up the good work! Thank you for sharing! Keep sharing more PI Technical stuff! All the best! Regards, Hari Suseelan Nice one. Divyesh Hi Sreedhar Can't we export the ESR obecjts from NWDS ? I don't see any options in NWDS for exporting ESR objects Hi Indrajit, this is not possible so far. We are missing this feature as well. Have a look at this for a high level overview: Consolidated view on release notes for Process Integration and Orchestration Hi all, Sreedhar, thanks for the information. This really comes in handy. @All: 1. What is the best practice to transport iFlows from NWDS? I currently do this by going to Process Integration --> Transport --> Export PI Objects and then selecting CTS+ and iFlow. This works fine, however, I still have to switch to IB say in QAS system, to transfer change list after transport. After that I again need to switch tools back to NWDS in QAS to activate because when activating within IB the iFlow does not get deployed and hence no ICO will be associated (see Andras' post above). Is this really the best way to cope with this? I would like to see all the transport stuff happen in NWDS and not switching tools for this. 2. How to best transport alert rules (AEX / Java-Only) I know that alert rules are ID objects and may be transported. Again, I'd like to know if there's a way to transport via NWDS where I haven't found a way to do so until now. Thanks and kind regards Jens Dear Jens, I can help you out with point 1 ;-)... This is known as hidden feature in NWDS: Go to "My Changes" and look for the small triangle: And go for Apply Changes. That can make you happy. Just to let you know, it is not possible to auto deploy objects by now. We miss this feature, and addressed it to SAP. Otherwise time triggered transports are useless using iFlows... Regards, Markus Dear Markus, this is great. Just tried it and worked like a charm 🙂 Thanks for the tip. Thanks for sharing. Nice blog.
https://blogs.sap.com/2013/10/07/transporting-pi-objects-with-nwds-using-cts-for-beginers/
CC-MAIN-2021-49
en
refinedweb
Plot Data from Salesforce in Python/v3 Create interactive graphs with salesforce, IPython Notebooks' Imports¶ Salesforce reports are great for getting a handle on the numbers but Plotly allows for interactivity not built into the Reports Module in Salesforce. Luckily Salesforce has amazing tools around exporting data, from excel and csv files to a robust and reliable API. With Simple Salesforce, it's simple to make REST calls to the Salesforce API and get your hands on data to make real time, interactive charts. This notebook walks you through that basic process of getting something like that set up. First you'll need Plotly. Plotly is a free web-based platform for making graphs. You can keep graphs private, make them public, and run Plotly on your own servers (). To get started visit . It's simple interface makes it easy to get interactive graphics done quickly. You'll also need a Salesforce Developer (or regular Salesforce Account). You can get a salesforce developer account for free at their developer portal. import plotly.plotly as py import plotly.graph_objs as go import pandas as pd import numpy as np from collections import Counter import requests from simple_salesforce import Salesforce requests.packages.urllib3.disable_warnings() # this squashes insecure SSL warnings - DO NOT DO THIS ON PRODUCTION! Log In to Salesforce¶ I've stored my Salesforce login in a text file however you're free to store them as environmental variables. As a reminder, login details should NEVER be included in version control. Logging into Salesforce is as easy as entering in your username, password, and security token given to you by Salesforce. Here's how to get your security token from Salesforce. with open('salesforce_login.txt') as f: username, password, token = [x.strip("\n") for x in f.readlines()] sf = Salesforce(username=username, password=password, security_token=token) SOQL Queries¶ At this time we're going to write a simple SOQL query to get some basic information from some leads. We'll query the status and Owner from our leads. Further reference for the Salesforce API and writing SOQL queries: SOQL is just Salesforce's version of SQL. leads_for_status = sf.query("SELECT Id, Status, Owner.Name FROM Lead") Now we'll use a quick list comprehension to get just our statuses from those records (which are in an ordered dictionary format). statuses = [x['Status'] for x in leads_for_status["records"]] status_counts = Counter(statuses) Now we can take advantage of Plotly's simple IPython Notebook interface to plot the graph in our notebook. data = [go.Bar(x=status_counts.keys(), y=status_counts.values())] py.iplot(data, filename='salesforce/lead-distributions') While this graph gives us a great overview what status our leads are in, we'll likely want to know how each of the sales representatives are doing with their own leads. For that we'll need to get the owners using a similar list comprehension as we did above for the status. owners = [x['Owner']['Name'] for x in leads_for_status["records"]] For simplicity in grouping the values, I'm going to plug them into a pandas DataFrame. df = pd.DataFrame({'Owners':owners, 'Status':statuses}) Now that we've got that we can do a simple lead comparison to compare how our Sales Reps are doing with their leads. We just create the bars for each lead owner. lead_comparison = [] for name, vals in df.groupby('Owners'): counts = vals.Status.value_counts() lead_comparison.append(Bar(x=counts.index, y=counts.values, name=name)) py.iplot(lead_comparison, filename='salesforce/lead-owner-status-groupings') What's great is that plotly makes it simple to compare across groups. However now that we've seen leads, it's worth it to look into Opportunities. opportunity_amounts = sf.query("SELECT Id, Probability, StageName, Amount, Owner.Name FROM Opportunity WHERE AMOUNT < 10000") amounts = [x['Amount'] for x in opportunity_amounts['records']] owners = [x['Owner']['Name'] for x in opportunity_amounts['records']] hist1 = go.Histogram(x=amounts) py.iplot([hist1], filename='salesforce/opportunity-probability-histogram') df2 = pd.DataFrame({'Amounts':amounts,'Owners':owners}) opportunity_comparisons = [] for name, vals in df2.groupby('Owners'): temp = Histogram(x=vals['Amounts'], opacity=0.75, name=name) opportunity_comparisons.append(temp) layout = go.Layout( barmode='stack' ) fig = go.Figure(data=opportunity_comparisons, layout=layout) py.iplot(fig, filename='salesforce/opportunities-histogram') By clicking on the "play with this data!" you can export, share, collaborate, and embed these plots. I've used it to share annotations about data and try out more colors. The GUI makes it easy for less technically oriented people to play with the data as well. Check out how the above was changed below or you can follow the link to make your own edits. from IPython.display import HTML HTML("""<div> <a href="" target="_blank" title="Chuck vs Bill Sales Amounts" style="display: block; text-align: center;"><img src="" alt="Chuck vs Bill Sales Amounts" style="max-width: 100%;width: 1368px;" width="1368" onerror="this.onerror=null;this.src='';" /></a> <script data-plotly="bill_chambers:21" src="" async></script> </div>""") After comparing those two representatives. It's always helpful to have that high level view of the sales pipeline. Below I'm querying all of our open opportunities with their Probabilities and close dates. This will help us make a forecasting graph of what's to come soon. large_opps = sf.query("SELECT Id, Name, Probability, ExpectedRevenue, StageName, Amount, CloseDate, Owner.Name FROM Opportunity WHERE StageName NOT IN ('Closed Lost', 'Closed Won') AND Amount > 5000") large_opps_df = pd.DataFrame(large_opps['records']) large_opps_df['Owner'] = large_opps_df.Owner.apply(lambda x: x['Name']) # just extract owner name large_opps_df.drop('attributes', inplace=True, axis=1) # get rid of extra return data from Salesforce large_opps_df.head() scatters = [] for name, temp_df in large_opps_df.groupby('Owner'): hover_text = temp_df.Name + "<br>Close Probability: " + temp_df.Probability.map(str) + "<br>Stage:" + temp_df.StageName scatters.append( go.Scatter( x=temp_df.CloseDate, y=temp_df.Amount, mode='markers', name=name, text=hover_text, marker=dict( size=(temp_df.Probability / 2) # helps keep the bubbles of managable size ) ) ) data = scatters layout = go.Layout( title='Open Large Deals', xaxis=dict( title='Close Date' ), yaxis=dict( title='Deal Amount', showgrid=False ) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='salesforce/open-large-deals-scatter') Plotly makes it easy to create many different kinds of charts. The above graph shows the deals in the pipeline over the coming months. The larger the bubble, the more likely it is to close. Hover over the bubbles to see that data. This graph is ideal for a sales manager to see how each of his sales reps are doing over the coming months. One of the benefits of Plotly is the availability of features. References¶
https://plotly.com/python/v3/salesforce/
CC-MAIN-2021-49
en
refinedweb
Sherlock Holmes received a strange note: let's date! 3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm The detective soon understood that the strange random code on the note was actually the date time at 14:04 on Thursday, because the first pair of the same uppercase English letters (case sensitive) in the first two strings was the fourth letter D. On behalf of Thursday; The second pair of identical characters is E , That is the fifth English letter, which represents the 14th hour of the day (so the numbers 0 to 9 and capital letters from 0 to 23 o'clock of the day) A reach N Means); The first pair of identical English letters in the last two strings s Appears on the 4th position (counting from 0), representing the 4th minute. Given two pairs of strings, please help Holmes decode the date. Input format: Input four non empty strings with no spaces and a length of no more than 60 in each of the four lines. Output format: Output the appointment time in one line in the format DAY HH:MM, where DAY Is a 3-character abbreviation for a week, i.e MON Means Monday, TUE It means Tuesday, WED Means Wednesday, THU Means Thursday, FRI Means Friday, SAT Means Saturday, SUN Means Sunday. Topic input ensures that each test has a unique solution. Input example: 3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm No blank lines at the end Output example: THU 14:04 Solution idea: in the process of doing this problem, I felt that because the topic was not so clear, and I saw the pass rate of this problem, the consideration of this problem was too complex. The topic did not make it clear whether the result existed in the first line or in the second line. When I started, I thought of A more comprehensive situation, Maybe if there is A date in the second line, I will start the whole program in an all-round way. The title doesn't say that the letters of his date are from A to G. I'm still taking into account the situation of Z. this messy wrong idea is that the whole program has somehow become so large, but I have to say that there are fewer and fewer bugs in the program now. Come on It is always darkest before dawn //The meaning of this question seems quite complicated, but it's not so complicated in fact //Find the date and hour in the first two lines and the minute in the next line. Here, pay attention to which line is the first and which line is the last #include<iostream> #include<string> #include<vector> #include<cctype> using namespace std; int swaps(string a, string b) { if (a.size() > b.size()) { return 1; } else return 0; } int main() { vector<string>arr(4);//The input must be four strings for (int i = 0; i < 4; ++i) { cin >> arr[i]; } int mide = -1; mide = swaps(arr[0], arr[1]); if (mide == 1) { string middle; middle = arr[0]; arr[0] = arr[1]; arr[1] = middle; } mide = -1; mide = swaps(arr[2], arr[3]);//This is to make the first row of comparison the smallest if (mide == 1) { string middle; middle = arr[2]; arr[2] = arr[3]; arr[3] = middle; } string Day[8] = { "MON","TUE","WED","THU","FRI","SAT","SUN" };//The day of the week is stored here char hour[24] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N' }; //int min = 0;// Used to record minutes int flag = 0;//It is used to record whether you are looking for days, hours or minutes. The title does not say where these three things appear, so use this to count the number. I guess this is the difficulty of this question for (int i = 0; i < arr[0].size(); ++i) { if (arr[0][i] == arr[1][i]) { if ((flag == 0) && (isupper(arr[0][i])))//If you're looking for days { if(arr[0][i]<='G') { flag++; int middle = toupper(arr[0][0][i]>='0')&&(arr[0][i]<='9')||((arr[0][i]>='A')&&(arr[0][i]<='N')))) { flag++; char middle; if (isalpha(arr[0][i])) middle = arr[0][i]; else middle = arr[0][i]; for (int j = 0; j < 24; ++j) { if (middle == hour[j]) { if(j<10) cout <<"0"<< j << ":";//The output hours are judged here else cout << j << ":"; break; } } } else if ((flag == 2) && (isalpha(arr[0][i]))) {//What we're dealing with here is minutes flag++; if (i < 10) { cout << "0" << i; return 0; } else { cout << i; return 0; } } } } for (int i = 0; i < arr[2].size(); ++i) { if (arr[2][i] == arr[3][i]) { if ((flag == 0) && (isupper(arr[2][i])))//If you're looking for days { if(arr[2][i]<='G') { flag++; int middle = toupper(arr[2][2][i]>='0')&&(arr[2][i]<='9')||((arr[2][i]>='A')&&(arr[2][i]<='N')))) { flag++; char middle; if (isalpha(arr[2][i])) middle = arr[2][i]; else middle = arr[2][i]; for (int j = 0; j < 24; ++j) { if (middle == hour[j]) { if(j<10) cout <<"0"<< j << ":";//The output hours are judged here else cout << j << ":"; break; } } } else if ((flag == 2) && (isalpha(arr[2][i]))) {//What we're dealing with here is minutes flag++; if (i < 10) { cout << "0" << i; return 0; } else { cout << i; return 0; } } } } return 0; }
https://programmer.help/blogs/1014-sherlock-holmes-appointment-20-points.html
CC-MAIN-2021-49
en
refinedweb
1. What is a database connection pool Why use connection pooling: When we develop in Java, we need to access the database, but Java can't access the database directly. We have to establish a connection between the program and the database through JDBC. Performing a transaction requires creating a connection. The process of establishing a connection between the program and the database is the most time consuming, and when the program becomes large, Frequent connections between programs and databases can be time consuming, so programmers have the concept of connection pools Connection pool: Stores the channels to connect to the database, that is, Connections in JDBC. n connections are defined beforehand. These connections are initialized when the program starts, taken directly from the connection pool later on, and put back into the connection pool. A large number of repetitive connections and release operations are omitted. 2. Druid Connection Pool Druid: The Druid connection pool was developed by the Alibaba team and introduced the concept of "slow loading". Slow load: When creating a connection pool object, the database is not connected to the number of connection channels that have been defined beforehand. Instead, when the first connection channel is taken from the middle connection pool, the connection pool checks to see if there are any useful connection channels inside, and if so, if there are no connections to the database, it performs n connection channels that have been defined beforehand. 3. jar/dependency of Druid connection pool 1. Download Druid.jar 2. Import Dependency <!-- --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> Either way. 4. Code representation 4.1. Create a properties file Create a properties Files, mainly for Druid Connection pool one constraint driverClassName = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/javaweb?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull username = root password = 123456 initialSize = 5 //Number of Initialized Connection Channels maxActive = 5 //Maximum number of available connection channels maxWait = 3000 //The maximum time, in milliseconds, to wait when all connection channels are occupied 4.2, Create a DruidUtils class Read the configuration file into memory and wait for the connection channel to be fetched public class DruidUtils { private static DataSource dataSource = null; private static Properties properties = null; static{ properties = new Properties(); try { //Load profile into memory using reflection technology properties.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //Get a connection pool object from factory design mode, get a connection pool object, not a connection object dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { throw new RuntimeException("Connection pool profile loading failed"); } } //Open Connection Pool Objects for External Use public static DataSource getDataSource(){ return dataSource; } //Get Connection from Connection Pool Object public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } } 4.3, Testing 1. You need to first get a connection pool object and then get a connection from the connection pool object 2. Once connected, the operation is the same as JDBC operation database 4.3.0, Print, View Connection Pool private static DataSource dataSource = DruidUtils.getDataSource(); //Get Connection Pool Object public static void main(String[] args){ System.out.println(dataSource); } Result analysis 4.3.1, Add User Method private static String addUser(User user){ String sql = "INSERT INTO user VALUES(?,?,?,?,?)";//SQL statement int result = 0; //Results after execution try { //Get Connection Channel from Connection Pool Object Connection connection = dataSource.getConnection(); //The following actions execute the SQL statement as in JDBC PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1,user.getId()); preparedStatement.setString(2,user.getUserName()); preparedStatement.setString(3,user.getPassword()); preparedStatement.setString(4,user.getSex()); preparedStatement.setString(5,user.getPhone()); result = preparedStatement.executeUpdate(); //Be sure to put the connection in the connection pool again after the operation is completed, or the connection pool will remain occupied and cannot be used by other things. connection.close(); } catch (SQLException e) { e.printStackTrace(); } return result > 0 ? "Successfully added user" : "Failed to add user"; } 4.3.1, Get all user information private static List<User> getUserList() { List<User> userList = new ArrayList<>(); ResultSet result = null; String sql = "SELECT * FROM user"; try { //Get Connection Channel from Connection Pool Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql); result = preparedStatement.executeQuery(); User user = null; while (result.next()) { user = new User(result.getString("id"),result.getString("username"), result.getString("password"), result.getString("sex"), result.getString("phone")); userList.add(user); } connection.close(); } catch (SQLException e) { e.printStackTrace(); } return userList; } 4.3.3, Main method public class DruidPoolTest { private static DataSource dataSource = null; public static void main(String[] args) { dataSource = DruidUtils.getDataSource(); //Get Connection Pool Object System.out.println("-----------Add a user to the database-----------------"); User user = new User("6","Boiling in King water","999999","female","13888887878"); System.out.println(addUser(user)); System.out.println("--------------Query all-------------"); List<User> userList = getUserList(); for(User user : userList){ System.out.println(user.toString()); } } } Result There are currently five pieces of user information in the database After performing the operation in the Main method There are six pieces of data, and the data was added successfully. Because of the "slow-loading" technology used by Druid connection pools, N connection channels need to be initialized when the program gets the connection channel for the first time because there is no connection in the connection pool, so it will start slowly. 5. Exception thrown by not returning connection to connection pool The number of connection channel bars I defined in the properties file beforehand is five, and the maximum number of active bars is five. And now I want to get six: public static void main(String[] args) { dataSource = DruidUtils.getDataSource(); //Get Connection Pool Object try { Connection connection1 = dataSource.getConnection();//First Connection Connection connection2 = dataSource.getConnection();//Second Connection Connection connection3 = dataSource.getConnection();//Third Connection Connection connection4 = dataSource.getConnection();//Fourth Connection Connection connection5 = dataSource.getConnection();//Fifth Connection Connection connection6 = dataSource.getConnection();//Sixth Connection } catch (SQLException e) { e.printStackTrace(); } } Direct error Reason Reason 1: There are no available connection channels in the connection pool. Five channels are defined. The maximum available is also five channels. All are not available. Reason 2: I did not release the connection after a transaction, which prevented other transactions from getting the connection channel. Solution Solution 1: Expand the maximum number of connections available in the connection pool initialSize = 5 //Initialize five connection channels maxActive = 10 // Maximum available connection channels are 10 Solution 2: After the transaction is executed, the connection is returned to the connection pool. Solution 2 is recommended because in large projects, it is not recommended to move around and increase the number of connection channels 6. Summary Druid connection pooling is also a popular connection pooling technology, but it only solves the performance optimization of connection channels in connection and release. Other ways of operating databases are the same as JDBC, so there are framework technologies such as MyBatis on the market.
https://programmer.help/blogs/alibaba-druid-database-connection-pool-take-off-directly.html
CC-MAIN-2021-49
en
refinedweb
What is Cloud Computing? Cloud computing is a paradigm that enables access to system resources and services that can be provisioned quickly for users, frequently over the Internet. Nowadays cloud computing is really common depending on the services that we would like to use, from frequently utilized software applications to development environments, virtual machines and storage. Service Models Cloud computing is divided into service models that are represented as layers in a stack. Each layer provides increasing abstraction: Infrastructure as a Service (IaaS) This layer provides high-level APIs to deal with low-level details of the network infrastructure giving you access to the computing infrastructure, physical or virtual machines, object/file-based storage, firewalls, load balancers etc. Platform as a Service (PaaS) The layer provides you with computing platforms such as development environment for application developers, typically including an operating system, programming language execution environment, databases and web servers as well. Software as a Service (SaaS) The layer ensures users can access application software from cloud clients. The software is installed and deployed by a cloud provider, so there is no need to install it on a cloud user’s computer. Examples of Cloud Providers - IaaS: Amazon Web Services (AWS), Google Compute Engine, Microsoft Azure - PaaS: AWS Elastic Beanstalk, Heroku, Google App Engine - SaaS: Email software such as Gmail; Social media: Facebook, Twitter Spring Cloud Integration with Amazon Web Services Let’s demonstrate how cloud computing works by implementing a sample application that will be integrated with Amazon S3 (Simple Storage Service) that is an IaaS object-based storage service and one of multiple services provided by Amazon Web Services. The full list of the Amazon Web Services products is available here. To integrate it, we will use the Spring Cloud AWS module that is one of the projects from the Spring Cloud stack providing integration with Amazon Web Services in an easy and comfortable way. Technology Stack: - Maven - Spring Boot - Spring Cloud and Spring Cloud AWS - React: on the client-side to provide support for the UI and file upload First of all, let’s generate the AWS security credentials: access key and secret key that are used for authentication and authorization in order to interact with the AWS. We can do it by: - Click on your account name -> My Security Credentials. - Visit the Access Key Section and click the Create New Access Key button. Once we’re done with the credentials, we can create a new S3 bucket where our objects (files) will be stored. To do this, simply: - Click the S3 option under the Storage section from the main AWS console webpage (you can see it in the picture below) - Click the Create bucket button. The bucket name will be further used in our application configuration. Implementation of the Sample Application The pom.xml file defining the necessary Maven dependencies is available in the repository mentioned at the end of the article, so you can just copy the necessary dependencies from there. Once we have all the dependencies, we can create a class that will run our application: @SpringBootApplication public class SpringCloudAwsExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudAwsExampleApplication.class, args); } } Now, we can provide the necessary configuration to integrate AWS S3 with our application in application.properties: Let’s clarify what particular properties mean: accessKeyand secretKeyindicate the AWS credentials that we have generated. s3.bucketis the name of your created bucket. region.staticrepresents the location of one of the AWS data centers that provide services for cloud users. Next, let’s create a configuration class to instantiate and configure the necessary Spring beans: @Configuration public class AWSConfiguration { @Value("${cloud.aws.credentials.accessKey}") private String accessKey; @Value("${cloud.aws.credentials.secretKey}") private String secretKey; @Value("${cloud.aws.region.static}") private String region; @Bean public BasicAWSCredentials basicAWSCredentials() { return new BasicAWSCredentials(accessKey, secretKey); } @Bean public AmazonS3Client amazonS3Client(AWSCredentials awsCredentials) { AmazonS3Client amazonS3Client = new AmazonS3Client(awsCredentials); amazonS3Client.setRegion(Region.getRegion(Regions.fromName(region))); return amazonS3Client; } } The fields annotated with the @Value annotation represent the properties defined in application.properties. The basicAWSCredentials bean represents the AWS credentials and the AmazonS3Client bean provides the client for accessing the Amazon S3 web service. Let’s implement a service that will interact with the injected AmazonS3Client bean to integrate with AWS S3: public interface StorageService { List<PutObjectResult> upload(MultipartFile[] multipartFiles); } @Service public class AWSStorageService implements StorageService { private final AmazonS3Client amazonS3Client; @Value("${cloud.aws.s3.bucket}") private String bucket; @Autowired public AWSStorageService(AmazonS3Client amazonS3Client) { this.amazonS3Client = amazonS3Client; } public List<PutObjectResult> upload(MultipartFile[] multipartFiles) { List<PutObjectResult> putObjectResults = new ArrayList<>(); Arrays.stream(multipartFiles) .filter(multipartFile -> !StringUtils.isEmpty(multipartFile.getOriginalFilename())) .forEach(multipartFile -> { try { putObjectResults.add(upload(multipartFile.getInputStream(), multipartFile.getOriginalFilename())); } catch (IOException e) { e.printStackTrace(); } }); return putObjectResults; } private PutObjectResult upload(InputStream inputStream, String uploadKey) { PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, uploadKey, inputStream, new ObjectMetadata()); putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead); PutObjectResult putObjectResult = amazonS3Client.putObject(putObjectRequest); IOUtils.closeQuietly(inputStream); return putObjectResult; } } Here we’re injecting the AmazonS3Client bean to interact with the S3 web service. We also need to specify a bucket to which we’ll upload objects. We’re certainly use the bucket specified in the application.properties file that is injected with the @Value annotation. Once our service is ready, we can write a controller that will accept HTTP requests carrying files to upload, and inject the created service to upload our files. @RestController public class UploadController { private final StorageService storageService; @Autowired public UploadController(StorageService storageService) { this.storageService = storageService; } @RequestMapping(value = "/", method = RequestMethod.POST) public List<PutObjectResult> upload(@RequestParam("file") MultipartFile[] multipartFiles) { return storageService.upload(multipartFiles); } } Now that our file upload components are ready, it is time to deal with the client-side in order to allow file upload via the web browser. To make Spring Boot work with React, let’s create a controller serving a React single-page application (SPA): @Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String index() { return "index.html"; } } The controller returns the index.html document where our React application resides so that it would be able to render when we visit the application root URL:. Finally, let’s implement the client-side code that will be sent with an HTTP response and executed in a client user’s web browser: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spring Cloud AWS Example</title> <script src=""></script> <script src=""></script> <script src=""></script> <script src="" integrity="sha256-</script> </head> <body> <div id="root"></div> <script type="text/babel"> class FormUpload extends React.Component { upload(e) { var formData = new FormData(); formData.append('file', this.refs.file.files[0]); $.ajax({ url: '', data: formData, processData: false, contentType: false, type: 'POST', success (data) { alert('The file has been uploaded.'); } }); e.preventDefault(); } render() { return ( <div> <form ref="uploadForm" className="uploader" encType="multipart/form-data" > <input ref="file" type="file" name="file" className="upload-file"/> <input type="button" ref="button" value="Upload" onClick={this.upload.bind(this)} /> </form> </div> ); } } ReactDOM.render(<FormUpload/>, document.getElementById('root')); </script> </body> </html> Please note that the React JS code written here is not perfect, since I’m not experienced in this library, as I’m rather a newcomer. :) You can compile and run the application with the following Maven command: mvn spring-boot:run By default, the application will run on the port 8080. To see whether the file has been uploaded, visit your S3 bucket in the AWS console that you can refer to by:. The entire project can be found in the following repository:. Summary Spring Cloud AWS simplifies integration of your Spring applications with the AWS in a great way, so I think it is worth trying. There are lots of various AWS products that can speed up the development and deployment of your applications, therefore, I believe everyone will find services that are suitable. The code introduced here is based on Brant Hwang’s example that you can also refer to:.
https://blog.j-labs.pl/2018/05/Cloud-Computing-with-Amazon-Web-Services
CC-MAIN-2021-49
en
refinedweb
Technical Articles SAP Customer Checkout Plugin Development – Part I Part I: Develop your first SAP Customer Checkout Plugin In the first part of this five-part blog series we are going to develop our first SAP Customer Checkout plugin. We are going to learn how to setup our eclipse project, use the cco API and build our plugin. To deep dive into the development, there are some prerequisites: - Eclipse and Maven installed - some experience in Java - SAP Customer Checkout 2.0 FP06 PL02 (with B1 Integration) installed and configured After you started your Eclipse, right click in the package explorer and we will create a new Maven Project. I’ll explain why we use maven later on. Click Next in the „New Maven Project“-wizard until you reach the screen where we need to set the Group Id and the Artifact Id. You can choose whatever namespace you want to use, just make sure it does not collide with any other java packages (e.g. use your surname in the namespace or your company). Click finish. Eclipse will now create a structure for your plugin and also a pom.xml which will be used for external dependencies and also for the creation of the MANIFEST file. Open the pom.xml with a text editor (I strongly recommend using the Spring Web Flow XML Editor which is part of the Spring Tools Suite you install at the eclipse marketplace). The pom.xml should look something like this. We will make some changes to it. Within the <properties> Tag add the following new properties: <sap.scco.pluginClass>com.be1eye.cco.blogpluginpart1.App</sap.scco.pluginClass> <sap.scco.POSVersions>n/a, 2.0 FP06</sap.scco.POSVersions> In the sap.scco.pluginClass enter your namespace (your groupId) followed by the pluginname (your artifactId) and followed by App which will be our main class Eclipse already created for us. In the second property sap.scco.POSVersion you can enter a list for all CCO Versions your plugin can is compatible to. In our case this is 2.0 FP06. After that, we also need some instructions for maven, so that maven will build our plugin correctly. Just copy and paste this part right under the </dependencies> part. <build> <resources> <resource> <directory>resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <artifactSet> <excludes> <exclude>com.sap:scco:*</exclude> </excludes> </artifactSet> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <manifestEntries> <PluginName>${project.name}</PluginName> <CashdeskPOSPlugin>${sap.scco.pluginClass}</CashdeskPOSPlugin> <CashDeskVersions>${sap.scco.POSVersions}</CashDeskVersions> <Version>${project.version}</Version> <Specification-Title>${project.name}</Specification-Title> <Specification-Version>${project.artifact.selectedVersion.majorVersion}.${project.artifact.selectedVersion.minorVersion}</Specification-Version> <Specification-Vendor> ${project.organization.name}</Specification-Vendor> <Implementation-Title>${project.name}</Implementation-Title> <Implementation-Version>${project.version}</Implementation-Version> <Implementation-Vendor-Id>${project.groupId}</Implementation-Vendor-Id> <Implementation-Vendor>${project.organization.name}</Implementation-Vendor> <Implementation-URL>${project.url}</Implementation-URL> </manifestEntries> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> Your pom.xml now should look something like this: These are classes to test your code but writing tests for our plugin is not scope of this blog series so we get rid of them. Now we are going to add the ENV.jar of our SAP Customer Checkout Installation. Right Click your plugin name -> Build Path -> Configure Build Path… Go to the tab Libraries and click on Add External JARs. Navigate to your SAP Customer Checkout installation and add the ENV.jar to your build path. Click on Apply and Close. Now open the App.java file in your project. Remove the static main method and extend the BasePlugin Class from SAP Customer Checkout. Make sure you add the import afterwards. Just hover your mouse over BasePlugin and add the import. Now we have to implement some methods so that SAP Customer Checkout knows how our plugin is called and which version it is. Just add these unimplemented methods by hover with your mouse over App and click add unimplemented methods. You will see, that Eclipse has added 3 Methods getId(), getName() and getVersion(). Change the return values according your pluginid, name and version. Notice the return value of the getVersion(). It will always output the version you set in your pom.xml. Now we just have to build our plugin, copy it into the SAP Customer Checkout installation and we’ll see our first plugin running. Right Click on our plugin folder -> Run as -> Maven Build… Give this build configuration a name, set the goal to package, skip tests, apply and run. You should see the maven output in the bottom of your eclipse windows. If everything went well, you should see a folder named target. In this folder you will see a jar file with your artifactId and your version. When successfull you can start the build from now on from eclipse directly. Sometimes the build is failing, so please right click on your project -> Maven -> Update Project… and update your project. The next build will be successfull eventually. Copy the plugin jar file into the following folder [SAP Customer Checkout Installation folder]/cco/POSPlugins/AP To be able to debug our plugin later, we need to add some parameters to the run.bat. So open run.bat with your prefered editor and search for the following part and the marked lines: The first line will open a socket everytime Customer Checkout starts. The second line prevents cco from closing your browser everytime you restart or close cco. Start your SAP Customer Checkout, log in and click on the cogwheel to open the CCO Backend. In the tab Plug-Ins you will now see, that our plugin successfully connected to Customer Checkout. Congratulations you just developed your first SAP Customer Checkout Plugin! In the next part of this series, we will learn how to store and read our own plugin properties, how to write to the SAP Customer Checkout log and many more. So stay tuned! If you have any questions do not hesitate to contact me. The source is also hosted on gitlab: Very good and detailed blog. Super Robert. Hi Robert, Thank you for the blog. Unfortunately, it does not work for me. Can you please suggest possible solution. If a plugin for CCO was made without Maven, it works like charm. After downloading your repository, this error appears: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project blogpluginpart1: Compilation failure [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? A few strings have been added to pom.xml for fixing: <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.0</version> <configuration> <source>1.8</source> <target>1.8</target> <fork>true</fork> <executable>C:\Program Files\Java\jdk1.8.0_121\bin\javac.exe</executable> </configuration> </plugin> But as result new error: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.0:compile (default-compile) on project blogpluginpart1: Compilation failure: Compilation failure: [ERROR] C:\Projects\RTL\SAP_CCO\Maven_exp\src\main\java\com\be1eye\cco\blogpluginpart1\App.java:[3,29] error: package com.sap.scco.ap.plugin does not exist ENV.jar has been added as external jar. Maven and Java JDK were installed. Hi Sergei, I did not test the build with the maven compiler plugin. Maven normally uses the JAVA_HOME Environment Variable to discover it's JDK. Can you please check, if your JAVA_HOME Environment Variable points to your JDK? Have a look at: Then try to remove the plugin you have added to your pom. Alternatively you could also install the ENV.jar to your local maven repository (which I personally would prefer, but this was not in the scope of this blog). It should work like that: mvn install:install-file -Dfile=<path-to-ENV.jar> -DgroupId=com.sap -DartifactId=scco -Dversion=2.0_FP06_PL02 -Dpackaging=jar (change -Dversion to the version of your ENV.jar) After this you can add your ENV.jar to the maven dependencies like this: <dependencies> <dependency> <groupId>com.sap</groupId> <artifactId>scco</artifactId> <version>2.0_FP06_PL02</version> <scope>compile</scope> </dependency> </dependencies> (Change version in the <version> Tag to the version you set with the mvn install command) Then remove the the ENV.jar from your build path in eclipse. Maven should now automatically look for the ENV.jar in your local repository. With this process you could easily install several ENV.jars with different versions to test your plugin with different CCO Versions. Please let me know if this worked! Regards Robert Hi Robert, Thank you very much for prompt reply. It is very helpful. Maven for CCO works for me. Only one thing, without maven-compiler-plugin your example works, but my plugin shows errors: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project rnz_plugin: Compilation failure [ERROR] /…/Shared.java:[11,65] diamond operator is not supported in -source 1.5 [ERROR] (use -source 7 or higher to enable diamond operator) Which looks like Maven uses Java 1.5 in Eclipse for some reasons, at the same time installed Maven version shows: Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-25T07:41:47+13:00) Maven home: C:\dev\apache-maven-3.6.0\bin\.. Java version: 1.8.0_121, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_121\jre The solution which works for me is adding code below in pom: <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> And after that it works perfectly. Please correct me if did something wrong. Hello Sergei, many roads lead to rome. You did nothing wrong. You could try to remove the compiler plugin and set the compiler target and source in the properties (where you set the sap.scco.pluginClass). So it could look like this: <!-- Properties --> <properties> <sap.scco.pluginClass>your.main.class.of.your.plugin</sap.scco.pluginClass> <sap.scco.POSVersions>n/a, 2.0 FP06</sap.scco.POSVersions> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> But I am happy, that this works for you. If you have any trouble do not hesitate to contact me. Regards Robert Hi Robert, Thank you for advice. I’ve tried, it works and looks better than with additional plugin. I have just one major issue with plugin development for CCO. It is API documentation. There quite a few examples, some learning introduction PDF, which are very helpful. However, it takes time to find appropriate class and method and there is no guarantee, that right way without side effects has been chosen. For example, task1: CCO should show modal message to user if barcode is not found. Solution the task1: @PluginAt(pluginClass=IBarcodeManager.class, method=”findAllByCodeCached”, where=POSITION.AFTER) With UIEventDispatcher.INSTANCE.dispatchAction(“SHOW_MESSAGE_DIALOG”, null, dialogOptions); It works fine, but with API docs it would much faster to find this. Also, BarcodeManager contains methods: findAllByCodeCached(String) findByCode(String) findByCodeCached(String) I found appropriate for my simple scenario with debuger, but I am not fully sure and do not know for what others. Another task with weight barcodes (barcode contains item code and total amount), they are generated externaly, dynamically (depended on weight) and do not exist in database. I think in this case, MaterialEntity can be found manually using MaterialManager class. After that, I should add MaterialEntity and total to sale document… CCO plugin development looks powerful, but quite time-consuming without API docs. Probably, I miss something. Thanks a lot, Sergei Hi Sergei, I know that this is time consuming to find the right classes and methods which may fit your needs, but afaik there is no “real” API doc. But maybe Gunther Sandtner knows more about this topic. Regarding the barcode scan: We already developped a plugin which may meet your requirements. Hit me up if you want to know more. Regards Robert Sergei Zagoskin , the email adress is info@hokona.de . Have a good day, Julian Hi Robert, Thank you for the blog,this is really helpful. I am following your blog step by step but unfortunately,i am facing issues in POM.xml (Maven) and whenever i run the maven build following error message appears Unknown lifecycle phase "Package".] Can you please suggest possible solutions for it or share any sample material for it. Following is the my POM.xml <project xmlns="" xmlns: <modelVersion>4.0.0</modelVersion> <groupId>com.be1eye.cco</groupId> <artifactId>blogpluginpart1</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>blogpluginpart1</name> <url></url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <sap.scco.pluginClass>com.be1eye.cco.blogpluginpart1.App</sap.scco.pluginClass> <sap.scco.POSVersions>n/a, 2.0 FP06</sap.scco.POSVersions> </properties> <build> <resources> <resource> <directory>resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> And can you please suggest a solution if we develop a plugin in java eclipse without using apache maven that how can we connect plugin source code to customer checkout . Hi Idrees, there is a difference between "Package" and "package". This is why maven does not know what to do. Can you please tell me how you start the built? Could you also please try to navigate in your folder where you put the plugin via commandline and type 'mvn package' and see if it works? Please consider to have the mvn binaries added to your environment variables of your operating system. Without maven open your Eclipse, right click on your plugin -> build path -> configure build path.In the tab libraries add an external jar. Choose the ENV.jar. Regards Robert Hi Robert, Thanks for your kind reply. As you described in your blog that Right click on the plugin folder > Run as > Maven build ,a wizard opens and in this wizard i mentioned Package as a goal and run the build but again i am facing same issue that Package lifecycle is not defined. Yes,Maven environment variables added to operating system and command line runs successfully. Hi Idrees, please change then "Package" as goal to "package" in Eclipse like in my screenshot. Package is not a valid goal for the maven-shade-plugin. If you want to build without maven (I would definitely recommend to go this way because it is way more convenient when working with external libraries) you also need to add a manifest file (which is automatically generated when you are using my maven example. So add a Manifest File within the root of your plugin. It should look something like this: Manifest-Version: 1.0 PluginName: [Name of your plugin] CashdeskPOSPlugin: [namespace of your plugin] CashDeskVersions: [versions for which your plugin is intended e.g. 2.0 FP07] Version: 1.0 After this right click on your plugin, choose export -> Java -> Jar file -> select your plugin (choose all necessary files) -> select output destination -> in the JAR Manifest Specification choose your Manifest you just created -> Finish. Regards Robert Hi Robert, I have followed your blog and the build was successful, but the plugin is not connected. What could be the problem ? Regards, Timothy Hi Timothy Mbogo , which CCO Version are you running? I assume you are above > 2.0 FP06? The plugin was built for 2.0 FP06. See pom.xml You may add your version and built the plugin again. Regards Robert Hi Robert, Thanks I have changed and the plugin is now connected. My CCO version is 2.0 FP08 Regards, Timothy. Hi Timothy Mbogo glad to hear that. Regards Robert Hi Robert Zieschang could you please explain us how to debug the plugin? In the documentation I see is added a line in run.bat with the port 4000, but when I try to debug with maven in Eclipse, it is running in port 5005. For me is not clear which are the steps to debug the plugin. I'm new using maven. Regards. Hi Ricardo Renteria did you check part II of this series? In this part I explained what to configure in eclipse to debug cco plugins. Regards Robert I followed all the steps but I got this error, then I compiled it once and then it came out again Do you helpme please, i also followed the suggestions of the answers but nothing [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for com.be1eye.cco:blogpluginpart1:jar:0.0.1-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-shade-plugin is missing. @ line 34, column 13 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] -------------------< com.be1eye.cco:blogpluginpart1 >------------------- [INFO] Building blogpluginpart1 0.0.1-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ blogpluginpart1 --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\Users\siste\eclipse-workspace\blogpluginpart1\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ blogpluginpart1 --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to D:\Users\siste\eclipse-workspace\blogpluginpart1\target\classes [INFO] ------------------------------------------------------------- [ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- symbol: method getClass() location: class com.be1eye.cco.blogpluginpart1.App [INFO] 6 errors [INFO] ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.788 s [INFO] Finished at: 2021-01-28T16:30:43-06:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project blogpluginpart1: Compilation failure: Compilation failure: [ERROR] [ERROR] symbol: method getClass() [ERROR] location: class com.be1eye.cco.blogpluginpart1.App ] Dear Jesus Cruz, it seems, that the ENV.jar from CCO is not correctly added in your eclipse project. This is indicated by the error log: [ERROR] /D:/Users/siste/eclipse-workspace/blogpluginpart1/src/main/java/com/be1eye/cco/blogpluginpart1/App.java:[3,30] package com.sap.scco.ap.plugin does not exist Can you please double check, if the ENV.jar is in your build path? Regards Robert I added from C:\SapCustomerCheckout\env.jar This is example blogpluginpart1 compile correct if i create with a project eclipse is correct or only is correct create plugin with MAVEN project? Thanks Robert!! Hello, Robert I'm working on a project where multiple CCO software connected to single Business One server. New customers can be created on any of these CCO or Business One clients. Standard CCO function is synchronizing all customers which is unnecessary from my point of view. Because some customers will often use specific CCO. I would like to develop plugin where it's possible to sync only specific customers on CCO. So far I able to call Business One service to select customer data. But I don't know the specific class & method which will save/create/sync customer in CCO. Calling this class & method, I like to pass the selected customer from the service which will work like standard CCO function. Any kind of help will be really appreciated.
https://blogs.sap.com/2018/10/16/sap-customer-checkout-plugin-development-part-i/
CC-MAIN-2021-49
en
refinedweb
[RFE] Periodic tasks: Allow passing a function callback to the spacing parameter Bug #1622612 reported by Lucas Alvares Gomes This bug affects 1 person Bug Description We could allow passing a function callback to the "spacing" parameter of the @periodic decorator, that would make it more flexible and would enable things like refreshing the interval values when the service re-loads the configuration file (in case of a SIGHUP). For example: def _sync_states(): return CONF.sync_ class Foo(object): @periodics def sync_states(self): ... Alternatively we could have another parameter for that as well, "spacing_func" maybe?
https://bugs.launchpad.net/futurist/+bug/1622612
CC-MAIN-2021-49
en
refinedweb
DBTextFinder Application, examples of connectors In this post we will look at the data structures and the necessary interfaces to develop connectors for any database to add to the DBTextFinder application, a tool for finding text in registers, stored procedures and views. You can also download sample code, developed with Microsoft Visual Studio 2013 with connectors for SQL Server, Oracle 12c and MySQL. This post is related with the article DBTextFinder application to search text in databases. Here you can download the code of the SQL Server connector, download the project for the MySQL connector and download the Oracle connector project code. All projects refer to the DBTFCommons.dll class library, which contains the definitions of the classes and interfaces used by all of them. This library is installed along with the program. To develop a connector for a particular database, you only have to implement a single interface. Following, we will review this interface and all the classes needed for communication with the application. Data classes used by DBTextFinder All classes used for data exchange between the application and the connectors are in the namespace of DBTFCommons.Data. SearchScope enum With this enumeration you can indicate the scope to which belong the objects in the database that can be selected, there are three different values: - Tables: Tables and Views. - StoredProcs: Stored procedures, functions, triggers, views code and, in the case of Oracle, packages. - All: All objects in the database. ConnectionData class This class contains the data needed to connect: public class ConnectionData { public string StringConnection { get; set; } public SearchScope Scope { get; set; } } StringConnection is the connection string to the database that you must build in the connector. Scope is used to set the type of objects on which it will work. ConnectionOptions class This class is related to the dialog box used by the application to configure the connections: public class ConnectionOptions { public bool SwowInitialCatalog { get; set; } public bool ShowWindowsAuthentication { get; set; } public string UserName { get; set; } public string Password { get; set; } public string DataSource { get; set; } public string InitialCatalog { get; set; } public bool WindowsAuthentication { get; set; } public string StringConnection { get; set; } public string ProviderName { get; set; } public string Error { get; set; } public string Description { get; set; } } ShowInitialCatalog allows hiding the Catalog text box, ShowWindowAuthentication has the same use to hide Windows authentication. Username and Password contain the username and password for the connection. DataSource is the server address, and InitialCatalog is the schema or database at which you access (depending on the connector). WindowsAuthentication is used to configure the access using integrated Windows authentication, StringConnection is the connection string to the database. ProviderName is the name of the access provider, which in this case is the type name of the connector. In the Error property can be returned error messages produced when testing the connection, and Description is the description of the connector that will be displayed to the user in the Connector drop-down list. FieldData class This class is used to store data concerning a field in a table in which a match was found with the search text: public class FieldData : IComparable<FieldData>, IEquatable<FieldData> { public string Name { get; set; } public string Value { get; set; } public bool Selected { get; set; } public string ReplaceEx { get; set; } public int CompareTo(FieldData other); public bool Equals(FieldData other); } Name contains the field name, and Value is for the original value. Selected is used to indicate whether the field has been selected by the user for a replacement operation. ReplaceEx is the expression that will replace the matching string found. CompareTo and Equals are the IComparable and IEquatable interfaces implementation. ObjectResult class It is used to return the search results and to indicate the selected items for text replacement operations: public class ObjectResult { public string Schema { get; set; } public string Name { get; set; } public bool Selected { get; set; } } Schema is the schema to which the object belongs, and Name is the object name. The Selected property indicates whether the object is selected by the user. TableResult class It is an extension of the ObjectResult class, used to return search results on tables. It contains several members with data of the different fields of the table. public class TableResult : ObjectResult { public TableResult(IEnumerable<FieldData> text, IEnumerable<FieldData> keys, IEnumerable<FieldData> all); public FieldData[] TextFields { get; set; } public FieldData[] KeyFields { get; set; } public FieldData[] AllFields { get; set; } public string QueryFields { get; } public int SelectedCount { get; } public FieldData GetField(string name); public void SetValue(string name, string value); public override string ToString(); } The constructor accepts three parameters; in the text parameter is passed a IEnumerable with the text fields of the table, in the keys parameter, the fields that form the primary key, and the all parameter id for all fields of the table. The TextFields, KeyFields and AllFields properties allow retrieving information about the fields that contain text, form part of the primary key, or all fields in the table, respectively. QueryFields is a function that returns the comma-separated list of table fields, to build SQL SELECT statements. With the GetField function you can retrieve information from a given field providing its name, and with SetValue you can change its value. The ToString override is used to display the user the data in the row. ProcMatch class The objects of this class store data about the matches found within the code of a stored procedure or view. public class ProcMatch { public int Index { get; set; } public int Length { get; set; } public bool Selected { get; set; } public string ReplaceEx { get; set; } public override string ToString(); } Index is the index of the first character of the match within the code, and Length their length. The Selected property indicates whether the match has been selected by the user. ReplaceEx contains the replacement string, and the ToString override allows showing the match to the user. CodeType enumeration The values of this enumeration indicate whether a given text is the code of a stored procedure or of a view, with their View or Procedure values. ProcResult class This class extends the search results to the code of procedures and views: public class ProcResult : ObjectResult { public CodeType CodeType { get; set; } public string ProcedureCode { get; set; } public ProcMatch[] Matches { get; set; } public int MatchCount { get; } public int SelectedCount { get; } public void AddMatch(ProcMatch pm); public override string ToString(); } CodeType is used to determine whether the results belong to the code of a view or a procedure, and ProcedureCode contains the complete code. Matches is the collection of all matches found in the code, and MatchCount returns the number of matches found. SelectedCount returns the number of user-selected matches. AddMatch is used to add new matches, and the override of ToString returns the name of the object, qualified with the name of the schema to which it belongs. Interfaces used by the application These interfaces are defined in the DBTFCommons.Interfaces namespace. IDBTFSearchCallback interface This interface is used to return search results when asynchronous versions of the main interface methods are used. public interface IDBTFSearchCallback { bool SearchResult(ObjectResult result); } The only member is the SearchResult function, used to pass to the program the results encountered. The return value indicates whether to cancel the operation. IDBTFConnection interface This is the interface that must implement the connector. All functions have a synchronous and an asynchronous version, which perform the same function. The asynchronous versions must going returning the results to the application using the interface IDBTFSearchCallback discussed above. public interface IDBTFConnection { IDBTFSearchCallback Callback { get; set; } ConnectionOptions GetConnectionOptions(); Task<ConnectionOptions> GetConnectionOptionsAsync(); ConnectionOptions ParseConnectionString(string strconn); Task<ConnectionOptions> ParseConnectionStringAsync(string strconn); ConnectionOptions ValidateConnectionOptions(ConnectionOptions conntest); Task<ConnectionOptions> ValidateConnectionOptionsAsync(ConnectionOptions conntest); string[] GetSchemas(ConnectionData connection); Task<string[]> GetSchemasAsync(ConnectionData connection); string[] GetTables(ConnectionData connection, string schema); Task<string[]> GetTablesAsync(ConnectionData connection, string schema); string[] GetViews(ConnectionData connection, string schema); Task<string[]> GetViewsAsync(ConnectionData connection, string schema); string[] GetProcedures(ConnectionData connection, string schema); Task<string[]> GetProceduresAsync(ConnectionData connection, string schema); ObjectResult[] Search(ConnectionData connection, string tables, string views, string procedures, string searchexpr, bool ignorecase); Task SearchAsync(ConnectionData connection, string tables, string views, string procedures, string searchexpr, bool ignorecase); void Replace(ConnectionData connection, ObjectResult result, string searchexpr, bool ignorecase); Task ReplaceAsync(ConnectionData connection, ObjectResult result, string searchexpr, bool ignorecase); void Delete(ConnectionData connection, ObjectResult result); Task DeleteAsync(ConnectionData connection, ObjectResult result); } The application provides in the Callback property one instance of IDBTFSearchCallback appropriate to communicate the search results in asynchronous operations. With the GetConnection function you must return the appropriate connection for your connector. ParseConnectionString is used to extract connection settings from a connection string, and ValidateConnectionOptions must make a connection test with the user-selected options. In order to obtain the list of objects in the database, you must implement the GetSchemas functions, which returns schema names, GetTables, to return the list of table names, GetViews for views and GetProcedures for stored procedures, functions and triggers. Search starts a search in the specified connection. As parameters you have connection data in connection, and in tables the names of tables separated by commas. These names are qualified with the schema name to which they belong. In views are passed the names of the views in the same format, and the names of procedures in procedures. searchexpr is the search expression, and ignorecase will indicate whether you the search must be case sensitive. Replace perform the replacements of text within a given search result, which is passed in the result parameter. ignorecase and searchexpr have the same meaning as in the Search function. Finally, Delete is called to delete records, procedures, and views, according to the result passed in the result parameter.
http://software-tecnico-libre.es/en/article-by-topic/all-sections/all-topics/csharp-source-code/dbtextfinder-connectors
CC-MAIN-2021-10
en
refinedweb
megrok.rdb 0.12 SQLAlchemy based RDB support for Grok. megrok.rdb Introduction The megrok.rdb package adds powerful relational database support to Grok, based on the powerful SQLAlchemy library. It makes available a new megrok.rdb.Model and megrok.rdb.Container which behave much like ones in core Grok, but are instead backed by a relational database. In this document we will show you how to use megrok.rdb. Declarative models megrok.rdb uses SQLAlchemy's ORM system, in particular its declarative extension, almost directly. megrok.rdb just supplies a few special base classes and directives to make things easier, and a few other conveniences that help with integration with Grok. We first import the SQLAlchemy bits we'll need later: >>> from sqlalchemy import Column, ForeignKey >>> from sqlalchemy.types import Integer, String >>> from sqlalchemy.orm import relation SQLAlchemy groups database schema information into a unit called MetaData. The schema can be reflected from the database schema, or can be created from a schema defined in Python. With megrok.rdb we typically do the latter, from within the content classes that they are mapped to using the ORM. We need to have some metadata to associate our content classes with. Let's set up the metadata object: >>> from megrok import rdb >>> metadata = rdb.MetaData() Now we'll set up a few content classes. We'll have a very simple structure where a (university) department has zero or more courses associated with it. First we'll define a container that can contain courses: >>> class Courses(rdb.Container): ... pass That's all. If the rdb.key directive is not used the key in the container will be defined as the (possibly automatically assigned) primary key in the database. FIXME a hack to make things work in doctests. In some particular setup this hack wasn't needed anymore, but I am unable at this time to reestablish this combination of packages: >>> __file__ = 'foo' Now we can set up the Department class. This has the courses relation that links to its courses: >>> class Department(rdb.Model): ... rdb.metadata(metadata) ... ... id = Column('id', Integer, primary_key=True) ... name = Column('name', String(50)) ... ... courses = relation('Course', ... backref='department', ... collection_class=Courses) This is very similar to the way you'd use sqlalchemy.ext.declarative, but there are a few differences: * we inherit from ``rdb.Model`` to make this behave like a Grok model. - We don't need to use __tablename__ to set up the table name. By default the table name will be the class name, lowercased, but you can override this by using the rdb.tablename directive. - we need to make explicit the metadata object that is used. We do this in the tests, though in Grok applications it's enough to use the rdb.metadata directive on a module-level to have all rdb classes automatically associated with that metadata object. - we mark that the courses relation uses the Courses container class we have defined before. This is a normal SQLAlchemy feature, it's just we have to use it if we want to use Grok-style containers. We finish up our database definition by defining the Course class: >>> class Course(rdb.Model): ... rdb.metadata(metadata) ... ... id = Column('id', Integer, primary_key=True) ... department_id = Column('department_id', Integer, ... ForeignKey('department.id')) ... name = Column('name', String(50)) We see here that Course links back to the department it is in, using a foreign key. Configuration We need to actually grok these objects to have them fully set up. Normally grok takes care of this automatically, but in this case we'll need to do it manually. First we grok this package's grokkers: >>> import grokcore.component.testing >>> grokcore.component.testing.grok('megrok.rdb.meta') Now we can grok the components: >>> from grokcore.component.testing import grok_component >>> grok_component('Courses', Courses) True >>> grok_component('Department', Department) True >>> grok_component('Course', Course) True Once we have our metadata and object relational map defined, we need to have a database to actually put these in. While it is possible to set up a different database per Grok application, here we will use a single global database: >>>>> from z3c.saconfig import EngineFactory >>> from z3c.saconfig.interfaces import IEngineFactory >>> engine_factory = EngineFactory(TEST_DSN) We need to supply the engine factory as a utility. Grok can do this automatically for you using the module-level grok.global_utility directive, like this: grok.global_utility(engine_factory, provides=IEngineFactory, direct=True) In the tests we'll use the component architecture directly: >>> from zope import component >>> component.provideUtility(engine_factory, provides=IEngineFactory) Now that we've set up an engine, we can set up the SQLAlchemy session utility: >>> from z3c.saconfig import GloballyScopedSession >>> from z3c.saconfig.interfaces import IScopedSession >>> scoped_session = GloballyScopedSession() With Grok, we'd register it like this: grok.global_utility(scoped_session, provides=IScopedSession, direct=True) But again we'll just register it directly for the tests: >>> component.provideUtility(scoped_session, provides=IScopedSession) We now need to create the tables we defined in our database. We can do this only when the engine is first created, so we set up a handler for it: >>> from z3c.saconfig.interfaces import IEngineCreatedEvent >>> @component.adapter(IEngineCreatedEvent) ... def engine_created(event): ... rdb.setupDatabase(metadata) >>> component.provideHandler(engine_created) Using the database Now all that is out the way, we can use the rdb.Session object to make a connection to the database. >>> session = rdb.Session() Let's now create a database structure. We have a department of philosophy: >>> philosophy = Department(name="Philosophy") We need to manually add it to the database, as we haven't defined a particular departments container in our database: >>> session.add(philosophy) The philosophy department has a number of courses: >>> logic = Course(name="Logic") >>> ethics = Course(name="Ethics") >>> metaphysics = Course(name="Metaphysics") >>> session.add_all([logic, ethics, metaphysics]) We'll add them to the philosophy department's courses container. Since we want to leave it up to the database what the key will be, we will use the special set method that rdb.Container objects have to add the objects: >>> philosophy.courses.set(logic) >>> philosophy.courses.set(ethics) >>> philosophy.courses.set(metaphysics) We can now verify that the courses are there: >>> for key, value in sorted(philosophy.courses.items()): ... print key, value.name, value.department.name 1 Logic Philosophy 2 Ethics Philosophy 3 Metaphysics Philosophy As you can see, the automatically generated primary key is also used as the container key now. The keys to the container are always integer, even if we're dealing with a primary key: >>> philosophy.courses['1'].name 'Logic' >>> philosophy.courses.get('1').name 'Logic' Custom key with rdb.key Let's now set up a different attribute to use as the container key. We will use the name attribute of the course. We'll set up the data model again, this time with a rdb.key on the Courses class: >>> metadata = rdb.MetaData() >>> class Courses(rdb.Container): ... rdb.key('name') >>> class Department(rdb.Model): ... rdb.metadata(metadata) ... ... id = Column('id', Integer, primary_key=True) ... name = Column('name', String(50)) ... ... courses = relation('Course', ... backref='department', ... collection_class=Courses) >>> class Course(rdb.Model): ... rdb.metadata(metadata) ... ... id = Column('id', Integer, primary_key=True) ... department_id = Column('department_id', Integer, ... ForeignKey('department.id')) ... name = Column('name', String(50)) We grok these new classes: >>> grok_component('Courses', Courses) True >>> grok_component('Department', Department) True >>> grok_component('Course', Course) True We don't need to change the engine, as the underlying relational database has remained the same. Let's set up another faculty with some departments: >>> physics = Department(name="Physics") >>> session.add(physics) >>> quantum = Course(name="Quantum Mechanics") >>> relativity = Course(name="Relativity") >>> high_energy = Course(name="High Energy") >>> session.add_all([quantum, relativity, high_energy]) We'll now add these departments to the physics faculty: >>> physics.courses.set(quantum) >>> physics.courses.set(relativity) >>> physics.courses.set(high_energy) We can now verify that the courses are there, with the names as the keys: >>> for key, value in sorted(physics.courses.items()): ... print key, value.name, value.department.name High Energy High Energy Physics Quantum Mechanics Quantum Mechanics Physics Relativity Relativity Physics Custom query container Sometimes we want to expose objects as a (read-only) container based on a query, not a relation. This is useful when constructing an application and you need a "starting point", a root object that launches into SQLAlchemy-mapped object that itself is not directly managed by SQLAlchemy. We can construct such a special container by subclassing from rdb.QueryContainer and implementing the special query method: >>> class MyQueryContainer(rdb.QueryContainer): ... def query(self): ... return session.query(Department) >>> qc = MyQueryContainer() Let's try some common read-only container operations, such as __getitem__: >>> qc['1'].name u'Philosophy' >>> qc['2'].name 'Physics' FIXME Why the unicode difference between u'Philosophy' and 'Physics'? __getitem__ with a KeyError: >>> qc['3'] Traceback (most recent call last): ... KeyError: '3' get: >>> qc.get('1').name u'Philosophy' >>> qc.get('3') is None True >>> qc.get('3', 'foo') 'foo' __contains__: >>> '1' in qc True >>> '3' in qc False has_key: >>> qc.has_key('1') True >>> qc.has_key('3') False len: >>> len(qc) 2 values: >>> sorted([v.name for v in qc.values()]) [u'Philosophy', 'Physics'] The parents of all the values are the query container: >>> [v.__parent__ is qc for v in qc.values()] [True, True] >>> sorted([v.__name__ for v in qc.values()]) [u'1', u'2'] keys: >>> sorted([key for key in qc.keys()]) [u'1', u'2'] items: >>> sorted([(key, value.name) for (key, value) in qc.items()]) [(u'1', u'Philosophy'), (u'2', 'Physics')] >>> [value.__parent__ is qc for (key, value) in qc.items()] [True, True] >>> sorted([value.__name__ for (key, value) in qc.items()]) [u'1', u'2'] __iter__: >>> result = [] >>> for key in qc: ... result.append(key) >>> sorted(result) [u'1', u'2'] Converting results of QueryContainer Sometimes it's useful to convert (or modify) the output of the query to something else before they appear in the container. You can implement the convert method to do so. It takes the individual value resulting from the value and should return the converted value: >>> class ConvertingQueryContainer(rdb.QueryContainer): ... def query(self): ... return session.query(Department) ... def convert(self, value): ... return SpecialDepartment(value.id) >>> class SpecialDepartment(object): ... def __init__(self, id): ... self.id = id >>> qc = ConvertingQueryContainer() Let's now check that all values are SpecialDepartment: >>> isinstance(qc['1'], SpecialDepartment) True >>> isinstance(qc['2'], SpecialDepartment) True KeyError still works: >>> qc['3'] Traceback (most recent call last): ... KeyError: '3' get: >>> isinstance(qc.get('1'), SpecialDepartment) True >>> qc.get('3') is None True >>> qc.get('3', 'foo') 'foo' values: >>> [isinstance(v, SpecialDepartment) for v in qc.values()] [True, True] The parents of all the values are the query container: >>> [v.__parent__ is qc for v in qc.values()] [True, True] >>> sorted([v.__name__ for v in qc.values()]) [u'1', u'2'] items: >>> sorted([(key, isinstance(value, SpecialDepartment)) for (key, value) in qc.items()]) [(u'1', True), (u'2', True)] >>> [value.__parent__ is qc for (key, value) in qc.items()] [True, True] >>> sorted([value.__name__ for (key, value) in qc.items()]) [u'1', u'2'] Customizing QueryContainer further Sometimes it's useful to define a custom keyfunc and custom method to retrieve the key from the database - these usually are implemented together: >>> class KeyfuncQueryContainer(rdb.QueryContainer): ... def query(self): ... return session.query(Department) ... def keyfunc(self, value): ... return 'd' + unicode(value.id) ... def dbget(self, key): ... if not key.startswith('d'): ... return None ... return self.query().get(key[1:]) >>> qc = KeyfuncQueryContainer() >>> qc.keys() [u'd1', u'd2'] >>> qc[u'd1'].id 1 CHANGES 0.12 (2011-02-02) - Update dependencies and imports to work with Grok 1.2 and 1.3. 0.11 (2010-02-22) - Added a LICENSE.txt file. - Added setupDatabaseSkipCreate. This allows setting up the database without trying to create any tables, just reflection. 0.10 (2009-09-18) - Added to SQLAlchemy to zope.schema adapters so that most of the types in sqlalchemy.types are covered. - Import schema_from_model into megrok.rdb package namespace. - Update buildout to use Grok 1.0b2 versions. - Added a test that demonstrates a common initialization pattern using rdb.setupDatabase` in a IEngineCreatedEvent subscriber. 0.9.1 (2009-08-14) - megrok.rdb 0.9 accidentally had zip_safe set to True, which resulted in a dud release as its ZCML wouldn't be loaded. Set zip_safe to False. 0.9 (2009-08-14) - Initial public release. - Author: Grok Team - Keywords: rdb relational sqlalchemy grok database - License: ZPL - Categories - Development Status :: 4 - Beta - Environment :: Web Environment - Framework :: Zope3 - Intended Audience :: Developers - License :: OSI Approved :: Zope Public License - Operating System :: OS Independent - Programming Language :: Python - Topic :: Database - Topic :: Internet :: WWW/HTTP - Topic :: Software Development :: Libraries - Package Index Owner: faassen, kteague - DOAP record: megrok.rdb-0.12.xml
http://pypi.python.org/pypi/megrok.rdb/0.12
crawl-003
en
refinedweb
strlen - get string length Synopsis Description Return Value Errors Examples Getting String Lengths Application Usage Rationale Future Directions See Also #include <string.h> size_t strlen(const char *s); The strlen() function shall compute the number of bytes in the string to which s points, not including the terminating null byte. The strlen() function shall return the length of s; no return value shall be reserved to indicate an error. No errors are defined. The following sections are informative. .
http://www.squarebox.co.uk/cgi-squarebox/manServer/usr/share/man/man3p/strlen.3p
crawl-003
en
refinedweb
strftime - convert date and time to a string Synopsis Description Modified Conversion Specifiers Return Value Errors Examples Getting a Localized Date String Application Usage Rationale Future Directions See Also #include <time.h> size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr); The strftime() function shall place bytes into the array pointed to by s as controlled by the string pointed to by format. The format is a character string, beginning and ending in its initial shift state, if any. The format string consists of zero or more conversion specifications and ordinary characters. A conversion specification consists of a % character, possibly followed by an E or O modifier, and a terminating conversion specifier character that determines the conversion specifications behavior. All ordinary characters (including the terminating null byte) are copied unchanged into the array. If copying takes place between objects that overlap, the behavior is undefined. No more than maxsize bytes are placed into the array. Each conversion specifier is replaced by appropriate characters as described in the following list. The appropriate characters are determined using the LC_TIME category of the current locale and by the values of zero or more members of the broken-down time structure pointed to by timeptr, as specified in brackets in the description. If any of the specified values are outside the normal range, the characters stored are unspecified. Local timezone information is used as though strftime() called tzset(). The following conversion specifications are supported:If a conversion specification does not correspond to any of the above, the behavior is undefined. If a struct tm broken-down time structure is created by localtime() or localtime_r(), or modified by mktime(), and the value of TZ is subsequently modified, the results of the %Z and %z strftime() conversion specifiers are undefined, when strftime() is called with such a broken-down time structure. If a struct tm broken-down time structure is created or modified by gmtime() or gmtime_r(), it is unspecified whether the result of the %Z and %z conversion specifiers shall refer to UTC or the current local timezone, when strftime() is called with such a broken-down time structure. Some conversion specifiers can be modified by the E or O modifier characters to indicate that an alternative format or specification should be used rather than the one normally used by the unmodified conversion specifier. If the alternative format or specification does not exist for the current locale (see ERA in the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.5, LC_TIME), the behavior shall be as if the unmodified conversion specification were used.%g , %G , and %V give values according to the ISO 8601:2000 standard week-based year. In this system, weeks begin on a Monday and week 1 of the year is the week that includes January 4th, which is also the week that includes the first Thursday of the year, and is also the first week that contains at least four days in the year. If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of the last week of the preceding year; thus, for Saturday 2nd January 1999, %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th, or 31st is a Monday, it and any following days are part of week 1 of the following year. Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01. If a conversion specifier is not one of the above, the behavior is undefined. defined. The following sections are informative. The following example first sets the locale to the users default. The locale information will be used in the nl_langinfo() and strftime() functions. The nl_langinfo() function returns the localized date string which specifies how the date is laid out. The strftime() function takes this information and, using the tm structure for values, places the date and time information into datestring. #include <time.h> #include <locale.h> #include <langinfo.h> ... struct tm *tm; char datestring[256]; ... setlocale (LC_ALL, ""); ... strftime (datestring, sizeof(datestring), nl_langinfo (D_T_FMT), tm); ... .
http://www.squarebox.co.uk/cgi-squarebox/manServer/usr/share/man/man3p/strftime.3p
crawl-003
en
refinedweb
Operating systems, development tools, and professional services for connected embedded systems for connected embedded systems sopenfd() Open for shared access a file associated with a given descriptor Synopsis: #include <unistd.h> int sopenfd( int fd, int oflag, int sflag ); Arguments: - fd - A file descriptor associated with the file that you want to open. - oflag - How you want to open the file; a combination of the following bits: -_TRUNC --: ); Returns: The file descriptor, or -1 if an error occurs (errno is set). Errors: - EBADF - Invalid file descriptor fd. - EACCES - The access mode specified by oflag isn't equal to or more restrictive than the access mode of the source fd. - EBUSY - Sharing mode (sflag) was denied due to a conflicting open.
http://www.qnx.com/developers/docs/6.4.0/neutrino/lib_ref/s/sopenfd.html
crawl-003
en
refinedweb