text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Querying configuration¶ Creating a tool¶ A Morepath-based application may over time grow big, have multiple authors and spread over many modules. In this case it is helpful to have a tool that helps you explore Morepath configuration and quickly find what directives are defined where. The Dectate library details how to create such a tool, but we repeat it here for Morepath: import dectate from mybigapp import App def query_tool(): dectate.query_tool(App.commit()) You save it in a module called query.py in the mybigapp package. Then you hook it up in setup.py so that a query script gets generated: entry_points={ 'console_scripts': [ 'morepathq = mybigapp.query:query_tool', ] }, Now when you re-install your project, you get a command-line query tool called morepathq that lets you issue queries. What just happened? - In order to be able to query an app’s configuration you need to commit it first. App.commit()also commits any other application you may have mounted into it. You get an iterable of apps that got committed. - You pass this iterable into the query_toolfunction. This lets the query tool search through the configuration of the apps you committed only. - You hook it up so that a command-line script gets generated using - setuptool’s console_scriptsmechanism. Usage¶ So now that you have a morepathq query tool, let’s use it: $ morepathq view App: <class 'mybigapp.App'> File ".../somemodule.py", line 4 @App.html(model=Foo) File ".../anothermodule.py", line 8 @App.json(model=Bar) Here we query for the view directive; since the view directive is grouped with json and html we get those back too. We get the module and line number where the directive was used. You can also filter: $ morepathq view model=mybigapp.model.Foo App: <class 'mybigapp.App'> File ".../somemodule.py", line 4 @App.html(model=Foo) Here we query all views that have the model value set to Foo or one of its subclasses. Note that in able to refer to Foo in the query we use the dotted name to that class in the module it was defined. You can query any Morepath directive this way: $ morepathq path model=mybigapp.model.Foo App: <class 'mybigapp.App'> File ".../path.py", line 8 @App.path(model=Foo, path="/foo")
https://morepath.readthedocs.io/en/latest/config_query.html
CC-MAIN-2019-04
refinedweb
377
67.76
A markdown text extractor written in Rust Project description The stupid simple rust markdown text puller Basically, this has one function and one function alone. It takes all the human readable text from Markdown, and extracts it. That's it. Why does this library exist? I needed it for a project, and pip was the easiest place to put it. What can I do with this library? Literally anything. I'm not fussed. It's ten lines of code. Installation pip install rust-markdown-text-puller Usage from rust_markdown_text_puller import get_raw_text print(get_raw_text("# Raw Markdown!")) It really is that simple License MIT license. See the LICENSE file for details Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/rust-markdown-text-puller/
CC-MAIN-2020-05
refinedweb
136
68.16
: kivy I’m trying to use kaki library with kivy and python but to use it you need to run DEBUG=1 python main.py but I’m facing this error DEBUG=1 : The term ‘DEBUG=1’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a .. I am creating a desktop application using kivy and I need open an explorer to select a file inside the application so that the user can select a photo. In kivy there is no built-in functionality that allows you to implement such an explorer (there is a filechooser, but I need built into the OS .. I’m trying to install Kivy on Windows10, 64 and I always face the same error: $python main.py [INFO ] [Logger ] Record log in /home/kk391035/.kivy/logs/kivy_21-07-26_1.txt [INFO ] [Kivy ] v2.0.0 [INFO ] [Kivy ] Installed at "/mnt/c/Users/pedro/Downloads/edh-life-counter/kivy_venv/lib/python3.8/site-packages/kivy/__init__.py" [INFO ] [Python ] v3.8.10 (default, Jun 2 2021, 10:49:15) [GCC 9.4.0] [INFO ] [Python ] Interpreter at .. I tried to create an executable file in Windows from a kivy project with PyInstaller, and even though it appears to have been successfully created, when I try to run it, I get this TypeError: startswith first arg must be str or a tuple of str, not PureWindowsPath [15308] Failed to execute script ‘main’ due .. import pyrebase import requests import json firebaseConfig = {‘apiKey’: "XXXXXXXXXXXXXXXXXXXXXXXX", ‘authDomain’: "XXXXXXXXXX.firebaseapp.com", ‘databaseURL’: "", ‘projectId’: "XXXXXXXXXX", ‘storageBucket’: "XXXXXXXXXX.appspot.com", ‘messagingSenderId’: "999999999", ‘appId’: "9:999999999999:web:999999999999999999", ‘measurementId’: "X-XXXXXXXXXX" } firebase = pyrebase.initialize_app(firebaseConfig) admin = firebase.auth() admin.create_user_with_email_and_password("[email protected]", "thisismypwd") This code is working in my PyCharm environment (XXXX and 9999 need to be replaced by your own real values). Problem: when .. I’m working on a cross platform app with Kivy (for Windows and Android targets) and I need to use Bluetooth Low Energy (to communicate with a ESP32 BLE Server). I tried using Bleak to handle BLE connection but importing Bleak module make my app crash. I use threading.Thread to split the BLE and the Kivy .. This sounds silly but for the sole purpose of my app working correctly I need to allow user to type in the command prompt here: After The "Start application main loop". I want it to behave like a normal command prompt, because my app will execute commands in this window and afterwards I want the .. Good afternoon people. Once again trying to package kivy for DESKTOP on WINDOWS 10 and to no avail! I had a lot of errors that I managed to solve without disturbing the order in the groups but this one is phoda with ph. 1 – I create the exe using Auto_py_to_exe and before there is .. Hi I am using kivy to develop a desktop application in Windows when I click the application shortcut ( after the conversion of exe ) each time it opens new window how to open a hidden window using existing process (name ,id) to show the window can any one tell how to solve the issue .. Recent Comments
https://windowsquestions.com/category/kivy/
CC-MAIN-2021-43
refinedweb
535
63.09
This text is meant to provide some guidelines for the ongoing development of the project. It is meant for core developers as well as occasional contributors. The following text assumes some basic familiarity with the Mercurial version control software. It is not a Mercurial tutorial, because you will find a good one at hginit.com. Rather, it explains concepts and workflows for the development of this project. If you want to contribute, you should to consider the technical report on NetworKit to get familiar with the architecture. If you use NetworKit in your research publications, please cite the mentioned techincal report or the specific algorithm. A list of publications is available on the website. For the time being, bugs should be reported by sending a report to the mailing list. Please provide a minimal example so that others can reproduce that bug. Feel free to fork NetworKit on algohub and start contributing by fixing bugs or taking care of the issues at kanboard.iti.kit.edu. New and missing features are welcomed aswell. The NetworKit main development repository is at. Access to this repository is provided on request. algohub.iti.kit.edu (an installation of RhodeCode) makes it easy to create and manage forks. Forking is distinct from branching and creates a new repository with a new address, its own access control etc. A fork contains all branches of its parent. At kanboard.iti.kit.edu we maintain a project task tracker to coordinate development and releases. An account is given on request, please ask on the mailing list. Tasks are moved from left to right to through the columns: Backlog: improvement ideas, some day maybe, “nice to have” ToDo: scheduled improvements Work in progress To Review: requesting peer review Ready for Release There is the possibility to create “swim lanes” for different releases. Currently, the two most important branches of NetworKit are Dev and default. ________ Dev ____/________ default As the name says, default is the branch which you are on if you do not switch. It is therefore the release branch, containing code which is ready for use. Unless you are a core developer preparing a release or fixing an urgent bug, you do not make changes to default. Dev is the development branch and most of the development of new features happens in this branch. This is also where new releases are being prepared. When pushing into this branch, think about whether your code is ready for the core development team to work with and will be suitable for a release in the foreseeable future. It can be appropriate to create additional branches for projects, features, developer teams etc. Creation of branches should be coordinated with the core development team. For this purpose, post to the mailing list. This section describes how to work with branches and forks in different scenarios. If you want to build and use NetworKit and do not plan to contribute changes, simply clone the repository. By default, you will be on the default branch, which represents the current release. Follow the setup instructions in the Readme. This section describes workflows for the core development team. Bugfixes are changes that should be immediately visible to users of NetworKit, such as solutions for urgent errors or improvements of the Readme document. In this case, make the changes in the default branch and commit. Then switch to the Dev branch and merge the default branch back into Dev. _______________ Dev / / < merge default into Dev ____/____________/____ default ^ bugfix Example: hg up default ... hg com -m "fixed bug xyz" hg up Dev hg merge default hg com -m "backmerge bugfix xyz" When new features should be released, the Dev branch is merged into the default branch. Additional testing and cleanup is performed before that happens. The new major or minor release is then tagged with a version number. ______________________________________________________ Dev / ^ new feature prepare release ^ \ < merge Dev into default ____/________________________________________\______________ default ^ tag version Example: hg up Dev hg com -m "ready for release X.Y" hg up default hg merge Dev hg com -m "release X.Y" If remote changes have happened in multiple branches and you pull them, these branch will have multiple heads. Merging now needs to happen for each of the affected branches before you can push. Switch to each branch and perform a merge as usual. As an alternative to merging, you may try the rebase extension. Users of NetworKit are welcome to contribute their modifications. New features must be added to the Dev branch, not the default branch. We recommend the following workflow: Devbranch Devbranch Students with long-term projects like Bachelor’s or Master’s theses should familiarize themselves with the guidelines and select a forking/branching model with their advisor. hg branches hg branch hg head hg tip hg update <branchname> hg branch <branchname> branchYinto branchX: hg update branchX, then hg merge branchY The following general conventions apply to all NetworKit developers. push --forceto the main repository. Every new feature must be covered by a unit test. Omitting unit tests makes it very likely that your feature will break silently as the project develops, leading to unneccessary work in tracing back the source of the error. Unit tests for the C++ part of NetworKit are based on the googletest library. For more information read the googletest primer. The Python test framework currently relies on nose to collect the tests. testfolder with googletestclasses. Create the unit tests for each feature in the appropriate test/*GTestclass by adding a TEST_Ffunction. testand experimental feature tests with try. A test*must pass when pushed to the main repository, a try*is allowed to fail. input/folder. Only small data sets (a few kilobytes maximum) are acceptable in the repository. output/folder. To build and run the tests you need the gtest library. Assuming, gtest is successfully installed and you add the paths to your build.conf, the unit tests should be compiled with: scons --optimize=Dbg --target=Tests To verify that the code was built correctly: Run all unit tests with ./NetworKit-Tests-Dbg --tests/-t Performance tests will be selected with ./NetworKit-Tests-Dbg --benchmarks/-b while experimental tests are called with ./NetworKit-Tests-Dbg --trials/-e To run only specific unit tests, you can also add a filter expression, e. g.: ./NetworKit-Tests-Dbg --gtest_filter=*PartitionGTest*/-f*PartitionGTest* initiates unit tests only for the Partition data structure. For the Python unit tests, run: python3 setup.py test [--cpp-tests/-c] This command will compile the _NetworKit extension and then run all test cases on the Python layer. If you append --cpp-tests/-c, the unit tests of the c++ side will be compiled and run before the Python test cases. If you implement a new feature for NetworKit, we encourage you to adapt your development process to test driven development. This means that you start with a one or ideally several test-cases for your feature and then write the feature for the test case(s). If your feature is mostly implemented in C++, you should write your test cases there. If you expose your feature to Python, you should also write a test case for the extension module on the Python layer. The same applies for features in Pyton. countand indexinteger types for non-negative integer quantities and indices. newwhere possible. overridekeyword to indicate that a method overrides a virtual method in the superclass. We use the possibilities provided through inheritance to generalize the common behaviour of algorithm implementations: The Algorithm base class also defines a few other other functions to query whether the algorithm can be run in parallel or to retrieve a string representation. There may be more levels in the class hierarchy between an algorithm implementation and the base class, e.g. a single-source shortest-path class SSSP that generalizes the behaviour of BFS and Dijkstra implementations or the Centrality base class. When implementing new features or algorithms, make sure to adapt to the existing class hierarchies. The least thing to do is to inherit from the Algorithm base class. Changes to existing interfaces or suggestions for new interfaces should be discussed through the mailing list. Assuming the unit tests for the new feature you implemented are correct and successful, you need to make your features available to Python in order to use it. NetworKit uses Cython to bridge C++ and Python. All of this bridge code is contained in the Cython code file src/python/_Networkit.pyx. The content is automatically translated into C++ and then compiled to a Python extension module. Cython syntax is a superset of Python that knows about static type declarations and other things from the C/C++ world. The best way to getting used to it is working on examples. Take the most common case of exposing a C++ class as a Python class. Care for the following example that exposes the class NetworKit::Dijkstra: cdef extern from "cpp/graph/Dijkstra.h": cdef cppclass _Dijkstra "NetworKit::Dijkstra"(_SSSP): _Dijkstra(_Graph G, node source, bool storePaths, bool storeStack, node target) except + The code above exposes the C++ class definition to Cython - but not yet to Python. First of all, Cython needs to know which C++ declarations to use so the the first line directs Cython to place an #include statement. The second line defines a class that is only accessible in the Cython world. Our convention is that the name of the new class is the name of the referenced C++ class with a prepended underscore to avoid namespace conflicts. What follows is the “real” C++ name of the class. After that, the declarations of the methods you want to make available for Python are needed. The except + statement is necessary for exceptions thrown by the C++ code to be rethrown as Python exceptions rather than causing a crash. Also, take care that the Cython declarations match the declarations from the referenced header file. cdef extern from "cpp/graph/SSSP.h": cdef cppclass _SSSP "NetworKit::SSSP"(_Algorithm): _SSSP(_Graph G, node source, bool storePaths, bool storeStack, node target) except + vector[edgeweight] getDistances(bool moveOut) except + [...] cdef class SSSP(Algorithm): """ Base class for single source shortest path algorithms. """ cdef Graph _G def __init__(self, *args, **namedargs): if type(self) == SSSP: raise RuntimeError("Error, you may not use SSSP directly, use a sub-class instead") def __dealloc__(self): self._G = None # just to be sure the graph is deleted def getDistances(self, moveOut=True): """ Returns a vector of weighted distances from the source node, i.e. the length of the shortest path from the source node to any other node. Returns ------- vector The weighted distances from the source node to any other node in the graph. """ return (<_SSSP*>(self._this)).getDistances(moveOut) [...] We mirror the class hierarchy of the C++ world also in Cython and Python. This also saves some boiler plate wrapping code as the functions shared by Dijkstra and BFS only need to be wrapped through SSSP. cdef class Dijkstra(SSSP): """ Dijkstra's SSSP algorithm. Returns list of weighted distances from node source, i.e. the length of the shortest path from source to any other node. Dijkstra(G, source, [storePaths], [storeStack], target) Creates Dijkstra for `G` and source node `source`. Parameters ---------- G : Graph The graph. source : node The source node. storePaths : bool store paths and number of paths? storeStack : bool maintain a stack of nodes in order of decreasing distance? target : node target node. Search ends when target node is reached. t is set to None by default. """ def __cinit__(self, Graph G, source, storePaths=True, storeStack=False, node target=none): self._G = G self._this = new _Dijkstra(G._this, source, storePaths, storeStack, target) For the class to be accessible from the Python world, you need to define a Python wrapper class which delegates method calls to the native class. The Python class variable _this holds a pointer to an instance of the native class. Please note that the parameters are now Python objects. Method wrappers take these Python objects as parameters and pass the internal native objects to the actuall C++ method call. The constructor of such a wrapper class is called __cinit__, and it creates an instance of the native object. The docstring between the triple quotation marks can be accessed through Python’s help(...) function and are the main documentation of NetworKit. Always provide at least a short and precise docstring so the user can get in idea of the functionality of the class. For C++ types available to Python and further examples, see through the _NetworKit.pyx-file. The whole process has certainly some intricacies, e.g. some tricks are needed to avoid memory waste when passing around large objects such as graphs. When in doubt, look at examples of similar classes already exposed. Listen to the Cython compiler - coming from C++, its error messages are in general pleasantly human-readable. When an algorithms takes too long to produce a result, it can be interrupted with a SIGINT signal triggered by CTRL+C. When triggering from the Python shell while the runtime is in the C++ domain, execution is aborted and even terminates the Python shell. Therefor, we implemented a signal handler infrastructure in C++ that raises a special exception instead of aborting. When implementing an algorithm, it is strongly encouraged to integrate the signal handler into the implementation. There are many examples of how to use it, e.g. networkit/cpp/centrality/Betweenness.cpp or networkit/cpp/community/PartitionFragmentation.cpp To discuss important changes to NetworKit, use the e-mail list ( networkit@ira.uka.de). The class documentation and the website can be automatically generated with sphinx. You will need the following software to generate the documentation and website: pip3 install sphinx) After you installed the above mentioned software, you can build the class documentation by calling ./make_doc.sh in the folder Doc/doc. This will generate the class documentation for C++ and Python in Doc/Documentation. Similarly, you can call ./make_ to build the website. After the build finished, you find the generated website in Doc/Website/.
https://networkit.iti.kit.edu/api/DevGuide.html
CC-MAIN-2017-13
refinedweb
2,346
65.12
std::malloc Allocates size bytes of uninitialized storage. If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any scalar type. If size is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage, but has to be passed to std::free) [edit] Parameters [edit] Return value On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with std::free() or std::realloc(). On failure, returns a null pointer. [edit] Notes This function does not call constructors or initialize memory in any way. There are no ready-to-use smart pointers that could guarantee that the matching deallocation function is called. The preferred method of memory allocation in C++ is using RAII-ready functions std::make_unique, std::make_shared, container constructors, etc, and, in low-level library code, new-expression. For loading a large file, file mapping via OS-specific functions, e.g. mmap on POSIX or CreateFileMapping( A/ W) along with MapViewOfFile on Windows, is preferable to allocating a buffer for file reading. [edit] Example #include <iostream> #include <cstdlib> #include <string> int main() { // allocates enough for an array of 4 strings if(auto p = (std::string*)std::malloc(4 * sizeof(std::string))) { int i = 0; try { for(; i != 4; ++i) // populate the array new(p + i) std::string(5, 'a' + i); for(int j = 0; j != 4; ++j) // print it back out std::cout << "p[" << j << "] == " << p[j] << '\n'; } catch(...) {} using std::string; for(; i != 0; --i) // clean up p[i - 1].~string(); std::free(p); } } Output: p[0] == aaaaa p[1] == bbbbb p[2] == ccccc p[3] == ddddd
https://en.cppreference.com/w/cpp/memory/c/malloc
CC-MAIN-2021-10
refinedweb
300
54.73
#1 · Posted January 5, 2007 I have a program with lots of child windows and one window with a graphic control. As I play something on the piano window, the graphic control is supposed to wave graph it. But when I use a GuiCtrlDelete() and try to recreate the graphic, it will take any window that is activated and create the control in that window! How would I get a control to always be created in one window only no matter what window I select? Some code to demonstrate... $form = Guicreate("Graphic window thing",200,200,-1,-1) ;;Bunch of menus and stuff goes here guisetstate() GuiCreate("Another Window",200,200,-1,$WS_EX_MDICHILD,$form) $g1 = GuictrlcreateGraphic(0,0,200,200) ; Background $g2 = GuictrlcreateGraphic(0,3,500,500) ; The graph for the wave thing guisetstate() while 1 StartGraphing() wend Func StartGraphing() $i = $i + 1 if $i >= 200 then $i = 0 Guictrldelete($g2) $g2 = GuictrlcreateGraphic(0,3,500,500) endif ;;The rest will graph things endfunc
https://www.autoitscript.com/forum/topic/38979-controls-are-not-going-to-the-right-windows/
CC-MAIN-2017-04
refinedweb
164
56.29
labs man page Prolog This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. labs, llabs — return a long integer absolute value Synopsis #include <stdlib.h> long labs(long i); long long llabs(long long i); Description The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008 defers to the ISO C standard. The labs() function shall compute the absolute value of the long integer operand i. The llabs() function shall compute the absolute value of the long long integer operand i. If the result cannot be represented, the behavior is undefined. Return Value The labs() function shall return the absolute value of the long integer operand. The llabs() function shall return the absolute value of the long long integer operand. Errors No errors are defined. The following sections are informative. Examples None. Application Usage None. Rationale None. Future Directions None. See Also abs(3p), stdlib.h(0p).
https://www.mankier.com/3p/labs
CC-MAIN-2019-04
refinedweb
201
51.55
Hello all, As part of my process for updating mplot3d, I realized that transforms.py needed to be revamped first. In many places in transforms.py, there were unnecessary 2-D assumptions that needed to be removed or generalized. I have started this effort here:…test%2Fmplot3d-ndtransforms I still have more to do in this file, but this version passes the unit tests, and I would welcome any comments and thoughts. Part of the efforts have been trying to shoehorn n-d positional arguments into various function signatures. For example: def foo(self, x, y) : pass becomes def foo(self, x, y, *args) : pass In some places, like shrunk_to_aspect(), I decided that I would just allow the operation to continue for just the first two dims. In other places, I tried to allow for mis-matches of dimensions with reasonable defaults (e.g., shrunk()). My main problem in pushing forward right now is that there are functions that have signatures like the following: def foo(self, x, y, ignorex=True, ignorey=True) : pass Unfortunately, it is not until py3k that we can utilize keyword-only arguments that would allow us to place a positional argument in between the y and the ignorex, and we would run the risk of breaking function calls like “foo(x, y, False, False)” which is valid now. Therefore, I are going to need to introduce some new functions to transforms.py that would allow n-d arguments and deprecate the problematic functions. Anyway, this is my progress so far. I would welcome any input, thoughts, concerns and such. Thanks, Ben Root
https://discourse.matplotlib.org/t/updates-to-transforms-py/15120
CC-MAIN-2021-43
refinedweb
267
61.87
Machine Learning models are powerful tools to make predictions based on available data. To make these models useful, they need to be deployed so that other’s can easily access them through an API (application programming interface) to make predictions. This can be done using Flask and Heroku — Flask is a micro web framework that does not require particular tools or libraries to create web applications and Heroku is a cloud platform that can host web applications. To successfully deploy a machine learning model with Flask and Heroku, you will need the files: model.pkl, app.py, requirements.txt, and a Procfile. This article will go through how to create each of these required files and finally deploy the app on Heroku. The main sections of this post are as follows: - Create GitHub Repository (optional) - Create and Pickle a Model Using Titanic Data - Create Flask App - Test Flask App Locally (optional) - Deploy to Heroku - Test Working App Feel free to skip over any of them depending on where you are at in your process!: To clone the repository, go to the repository page, click “clone or download” and copy the link. In your terminal, go to the folder where you want to clone the repository and type the command: git clone link_to_repository Running this command will clone the repository to your local machine and you can check to make sure that the folder was created in the right location. Now that the repo is set up, we can create the machine learning model and pickle it. Create and Pickle a Machine Learning Model First, let’s create a simple Logistic Regression model using the Titanic dataset. This model will predict whether someone survived the Titanic given information about class, age, number of siblings, and fare. If you’d like to follow along with my examples, you can find the csv file for the dataset here. Create a Jupyter notebook inside your working directory and create the model by running the code below: import pandas as pd from sklearn.linear_model import LogisticRegression # create df train = pd.read_csv('titanic.csv') # change file path # drop null values train.dropna(inplace=True) # features and target target = 'Survived' features = ['Pclass', 'Age', 'SibSp', 'Fare'] # X matrix, y vector X = train[features] y = train[target] # model model = LogisticRegression() model.fit(X, y) model.score(X, y) The code above creates a pandas dataframe from the csv data, drops null values, defines the features and target for the model, splits the data into a matrix with just the features and a vector with the target, and fits a logistic regression model, then scores it. This creates a model that can predict the survivorship of Titanic passengers with ~70% accuracy which can then be pickled using: import pickle pickle.dump(model, open(‘model.pkl’, ‘wb’)) The pickle file can be found inside the same directory as your Jupyter notebook. Write Flask App Open up your IDE (I use PyCharm) and create a new .py file inside the working directory named app.py The code for the flask application can be found below (python v3.7). import pandas as pd from flask import Flask, jsonify, request import pickle # load model model = pickle.load(open('model.pkl','rb')) # app app = Flask(__name__) # routes @app.route('/', methods=['POST']) def predict(): # get data data = request.get_json(force=True) # convert data into dataframe data.update((x, [y]) for x, y in data.items()) data_df = pd.DataFrame.from_dict(data) # predictions result = model.predict(data_df) # send back to browser output = {'results': int(result[0])} # return data return jsonify(results=output) if __name__ == '__main__': app.run(port = 5000, debug=True) The structure of the code follows: - Load pickled model - Name flask app - Create a route that receives JSON inputs, uses the trained model to make a prediction, and returns that prediction in a JSON format, which can be accessed through the API endpoint. Inside the route, I converted the JSON data to a pandas dataframe object because I found that this works with most (not all!) types of models that you will want to use to make a prediction. You can choose to convert the inputs using your preferred method as long as it works with the .predict() method for your model. The order of inputs must match the order of columns in the dataframe that you used to train your model otherwise you will get an error when you try to make a prediction. If the inputs you are receiving are not in the correct order you can easily reorder them after you create the dataframe. The takeaway here is that you need to convert the JSON data that you get from the request to a data structure that the model can use to make a prediction. However you get there is up to you. Once you paste this into your app.py file you can run the flask app from the command line (or if you’re using PyCharm just run the code). To run the app from the command line use: python app.py If done correctly, you will see something like this: Note on errors: If this is your first time creating a flask app you might get an error that you need to install flask into your python environment. Use !pip install flaskand try again. When your flask app is up and running, click on the link in blue and you should see this — it’s normal: Optional, but you really should: Test that the app works Import requests and json in your Jupyter notebook, then create a variable with your local server if it’s different from below: # local url url = '' # change to your url Create sample data and convert to JSON: # sample data data = {'Pclass': 3 , 'Age': 2 , 'SibSp': 1 , 'Fare': 50} data = json.dumps(data) Post sample data and check response code using requests.post(url, data). You want to get a response code of 200 to make sure that the app is working: Then you can print the JSON of the request to see the model’s prediction: The model predicted 1 which means the passenger survived 🙌 Shut down the flask app by typing ctrl+c when you’re done testing. Create Procfile A Procfile specifies the commands that are executed by a Heroku app on startup. To create one, open up a new file named Procfile (no extension) in the working directory and paste the following. web: gunicorn app:app And that’s it. Save and close. ✅ Create requirements.txt The requirements.txt file will contain all of the dependencies for the flask app. To create a requirements.txt, run the following in your terminal from the working directory: pip freeze > requirements.txt If you’re not working from a new environment, this file will contain all requirements from your current environment. If you get errors later when deploying the app, you can just delete the requirements that give you an error. At the bare minimum for this project, your requirements.txt should contain: Flask==1.1.1 gunicorn==19.9.0 pandas==0.25.0 requests==2.22.0 scikit-learn==0.21.2 scipy==1.3.1 Optional: Commit Files to GitHub Run the following commands to commit the files to git: # add all files from the working directory git add . then commit with your message: git commit -m 'add flask files' and finally, push changes to Github using the following command. You may be asked to enter your github username and password. If you have 2FA set up, you will need your key as the password. git push origin master At minimum, your Github repo should now contain: - app.py - model.pkl - Procfile - requirements.txt Note: all of these files should be at the working directory level and not in another folder Deploy to Heroku If you don’t have one already, create a free account at. Create a new app simply by choosing a name and clicking “create app”. This name doesn’t matter but it does have to be unique. You have a few options for the way you can deploy the app. I’ve tried both the Heroku CLI and GitHub and I personally prefer GitHub….but I’ll show both so pick whichever one you want to follow. Deploying With Github Connect your github account by clicking the github icon below: And then just scroll to the bottom of the page and click “Deploy Branch” If everything worked correctly you should see this message 🎉🎉 If something went wrong, check your requirements.txt, delete and dependencies that are giving you problems, and try again ¯\_(ツ)_/¯ Deploying with Heroku CLI In the Heroku CLI section, you will see these instructions to follow for deployment. Paste each command into your terminal and follow any prompts like logging in. Pay attention to any commands you will need to modify, such as cd my-project/ — where my-project/ should actually be your project directory. The git remote should be set to the app name from Heroku EXACTLY. If you were successful in following these instructions, you should see build succeeded on the overview page 🎉🎉 If not, you can check to see what went wrong by running heroku logs --tail from the command line. Test the Deployed Model & Generate Prediction If you already tested your flask app, these instructions will be very similar, except now with the Heroku app url. Import requests and json in your Jupyter notebook, then create a variable to store the Heroku app url (you can find this by clicking “open app” in the top right corner of the app page on Heroku). Then create some sample data and convert it to JSON: # heroku url heroku_url = '' # change to your app name # sample data data = { 'Pclass': 3 , 'Age': 2 , 'SibSp': 1 , 'Fare': 50}data = json.dumps(data)} data = json.dumps(data) Check the response code using the following code. A response code of 200 means everything is running correctly. send_request = requests.post(heroku_url, data) print(send_request) Output: <Response [200]> And finally, look at the model’s prediction: print(send_request.json()) Output: {‘results’: {‘results’: 1}} Your output results will vary if you’re using different sample data. The result of 1 in this case means that the model predicts the passenger survived — and more importantly the API works! Now people can access your API endpoint with the Heroku URL and use your model to make predictions in the real world 🌐 Here is the github repo containing all files and code required to deploy this API. Find me on twitter @elizabethets or connect with me on LinkedIn! Sources:
https://lizzie.codes/2019/09/29/create-an-api-to-deploy-machine-learning-models-using-flask-and-heroku/
CC-MAIN-2020-40
refinedweb
1,765
61.36
#include "HalideRuntime.h" Go to the source code of this file. Routines specific to the Halide Direct3D 12 Compute runtime. Definition in file HalideRuntimeD3D12Compute.h. Set the underlying ID3D12Resource for a halide_buffer_t. The memory backing the resource should be managed by the caller (via a default/device heap) and must be large enough to cover the extent of the halide_buffer_t. The device field of the halide_buffer_t must be NULL when this routine is called. This call can fail due to running out of memory or if an invalid D3D12 resource is passed. The device and host dirty bits are left unmodified. Disconnect a halide_buffer_t from the ID3D12Resource it was previously wrapped around. Should only be called for a halide_buffer_t that halide_d3d12compute_wrap_buffer was previously called on. Frees any storage associated with the binding of the halide_buffer_t and the buffer, but does not free the ID3D12Resource. The dev field of the halide_buffer_t will be NULL on return. Return the underlying ID3D12Resource for a halide_buffer_t. This resource must be valid on an D3D12 device, unless halide_buffer_t has no associated resource. If there is no device memory (device field is NULL), returns 0. This prototype is exported as applications will typically need to replace it to get Halide filters to execute on the same device and command queue used for other purposes. The halide_d3d12compute_device is an ID3D12Device and halide_d3d12compute_command_queue is an ID3D12CommandQueue. No reference counting is done by Halide on these objects. They must remain valid until all off the following are true: This call balances each successfull halide_d3d12compute_acquire_context call. If halide_d3d12compute_acquire_context is replaced, this routine must be replaced as well.
https://halide-lang.org/docs/_halide_runtime_d3_d12_compute_8h.html
CC-MAIN-2020-50
refinedweb
267
66.54
import "go.uber.org/net/metrics" Package metrics is a telemetry client designed for Uber's software networking team. It prioritizes performance on the hot path and integration with both push- and pull-based collection systems. Like Prometheus and Tally, it supports metrics tagged with arbitrary key-value pairs. Like Prometheus, but unlike Tally, metric names should be relatively long and descriptive - generally speaking, metrics from the same process shouldn't share names. (See the documentation for the Root struct below for a longer explanation of the uniqueness rules.) For example, prefer "grpc_successes_by_procedure" over "successes", since "successes" is common and vague. Where relevant, metric names should indicate their unit of measurement (e.g., "grpc_success_latency_ms"). Counters represent monotonically increasing values, like a car's odometer. Gauges represent point-in-time readings, like a car's speedometer. Both counters and gauges expose not only write operations (set, add, increment, etc.), but also atomic reads. This makes them easy to integrate directly into your business logic: you can use them anywhere you'd otherwise use a 64-bit atomic integer. This package doesn't support analogs of Tally's timer or Prometheus's summary, because they can't be accurately aggregated at query time. Instead, it approximates distributions of values with histograms. These require more up-front work to set up, but are typically more accurate and flexible when queried. See for a more detailed discussion of the trade-offs involved. Plain counters, gauges, and histograms have a fixed set of tags. However, it's common to encounter situations where a subset of a metric's tags vary constantly. For example, you might want to track the latency of your database queries by table: you know the database cluster, application name, and hostname at process startup, but you need to specify the table name with each query. To model these situations, this package uses vectors. Each vector is a local cache of metrics, so accessing them is quite fast. Within a vector, all metrics share a common set of constant tags and a list of variable tags. In our database query example, the constant tags are cluster, application, and hostname, and the only variable tag is table name. Usage examples are included in the documentation for each vector type. This package integrates with StatsD- and M3-based collection systems by periodically pushing differential updates. (Users can integrate with other push-based systems by implementing the push.Target interface.) It integrates with pull-based collectors by exposing an HTTP handler that supports Prometheus's text and protocol buffer exposition formats. Examples of both push and pull integration are included in the documentation for the root struct's Push and ServeHTTP methods. If you're unfamiliar with Tally and Prometheus, you may want to consult their documentation: Code: // First, construct a metrics root. Generally, there's only one root in each // process. root := metrics.New() // From the root, access the top-level scope and add some tags to create a // sub-scope. You'll typically pass scopes around your application, since // they let you create individual metrics. scope := root.Scope().Tagged(metrics.Tags{ "host": "db01", "region": "us-west", }) // Create a simple counter. Note that the name is fairly long; if this code // were part of a reusable library called "foo", "foo_selects_completed" // would be a much better name. total, err := scope.Counter(metrics.Spec{ Name: "selects_completed", Help: "Total number of completed SELECT queries.", }) if err != nil { panic(err) } // See the package-level documentation for a general discussion of vectors. // In this case, we're going to track the number of in-progress SELECT // queries by table and user. Since we won't know the table and user names // until we actually receive each query, we model this as a vector with two // variable tags. progress, err := scope.GaugeVector(metrics.Spec{ Name: "selects_in_progress", Help: "Number of in-progress SELECT queries.", VarTags: []string{"table", "user"}, }) if err != nil { panic(err) } // MustGet retrieves the gauge with the specified variable tags, creating // one if necessary. We must supply both the variable tag names and values, // and they must be in the correct order. MustGet panics only if the tags // are malformed. If you'd rather check errors explicitly, there's also a // Get method. trips := progress.MustGet( "table" /* tag name */, "trips", /* tag value */ "user" /* tag name */, "jane", /* tag value */ ) drivers := progress.MustGet( "table", "drivers", "user", "chen", ) fmt.Println("Trips:", trips.Inc()) total.Inc() fmt.Println("Drivers:", drivers.Add(2)) total.Add(2) fmt.Println("Drivers:", drivers.Dec()) fmt.Println("Trips:", trips.Dec()) fmt.Println("Total:", total.Load()) Output: Trips: 1 Drivers: 2 Drivers: 1 Trips: 0 Total: 3 core.go counter.go doc.go gauge.go histogram.go metadata.go metrics.go push.go root.go scope.go snapshot.go spec.go tag.go value.go version.go Placeholders for empty tag names and values. Version is the current semantic version, exported for runtime compatibility checks. IsValidName checks whether the supplied string is a valid metric and tag name in both Prometheus and Tally. Tally and Prometheus each allow runes that the other doesn't, so this package can accept only the common subset. For simplicity, we'd also like the rules for metric names and tag names to be the same even if that's more restrictive than absolutely necessary. Tally allows anything matching the regexp `^[0-9A-z_\-]+$`. Prometheus allows the regexp `^[A-z_:][0-9A-z_:]*$` for metric names, and `^[A-z_][0-9A-z_]*$` for tag names. The common subset is `^[A-z_][0-9A-z_]*$`. IsValidTagValue checks whether the supplied string is a valid tag value in both Prometheus and Tally. Tally allows tag values that match the regexp `^[0-9A-z_\-.]+$`. Prometheus allows any valid UTF-8 string. A Counter is a monotonically increasing value, like a car's odometer. All its exported methods are safe to use concurrently, and nil *Counters are safe no-op implementations. Add increases the value of the counter and returns the new value. Since counters must be monotonically increasing, passing a negative number just returns the current value (without modifying it). Inc increments the counter's value by one and returns the new value. Load returns the counter's current value. A CounterVector is a collection of Counters that share a name and some constant tags, but also have a consistent set of variable tags. All exported methods are safe to use concurrently. Nil *CounterVectors are safe to use and always return no-op counters. For a general description of vector types, see the package-level documentation. Code: vec, err := metrics.New().Scope().CounterVector(metrics.Spec{ Name: "selects_completed_by_table", // required Help: "Number of completed SELECT queries by table.", // required ConstTags: metrics.Tags{"host": "db01"}, // optional VarTags: []string{"table"}, // required }) if err != nil { panic(err) } vec.MustGet("table" /* tag name */, "trips" /* tag value */).Inc() func (cv *CounterVector) Get(variableTagPairs ...string) (*Counter, error) Get retrieves the counter with the supplied variable tag names and values from the vector, creating one if necessary. The variable tags must be supplied in the same order used when creating the vector. Get returns an error if the number or order of tags is incorrect. func (cv *CounterVector) MustGet(variableTagPairs ...string) *Counter MustGet behaves exactly like Get, but panics on errors. If code using this method is covered by unit tests, this is safe. A Gauge is a point-in-time measurement, like a car's speedometer. All its exported methods are safe to use concurrently, and nil *Gauges are safe no-op implementations. Add increases the value of the gauge and returns the new value. Adding negative values is allowed, but using Sub may be simpler. CAS is an atomic compare-and-swap. It compares the current value to the old value supplied, and if they match it stores the new value. The return value indicates whether the swap succeeded. To avoid endless CAS loops, no-op gauges always return true. Dec decrements the gauge's current value by one and returns the new value. Inc increments the gauge's current value by one and returns the new value. Load returns the gauge's current value. Store sets the gauge's value. Sub decreases the value of the gauge and returns the new value. Subtracting negative values is allowed, but using Add may be simpler. Swap replaces the gauge's current value and returns the previous value. A GaugeVector is a collection of Gauges that share a name and some constant tags, but also have a consistent set of variable tags. All exported methods are safe to use concurrently. Nil *GaugeVectors are safe to use and always return no-op gauges. For a general description of vector types, see the package-level documentation. Code: vec, err := metrics.New().Scope().GaugeVector(metrics.Spec{ Name: "selects_in_progress_by_table", // required Help: "Number of in-flight SELECT queries by table.", // required ConstTags: metrics.Tags{"host": "db01"}, // optional VarTags: []string{"table"}, // optional }) if err != nil { panic(err) } vec.MustGet("table" /* tag name */, "trips" /* tag value */).Store(11) func (gv *GaugeVector) Get(variableTagPairs ...string) (*Gauge, error) Get retrieves the gauge with the supplied variable tags names and values from the vector, creating one if necessary. The variable tags must be supplied in the same order used when creating the vector. Get returns an error if the number or order of tags is incorrect. func (gv *GaugeVector) MustGet(variableTagPairs ...string) *Gauge MustGet behaves exactly like Get, but panics on errors. If code using this method is covered by unit tests, this is safe. A Histogram approximates a distribution of values. They're both more efficient and easier to aggregate than Prometheus summaries or M3 timers. For a discussion of the tradeoffs between histograms and timers/summaries, see. All exported methods are safe to use concurrently, and nil *Histograms are valid no-op implementations. Code: h, err := metrics.New().Scope().Histogram(metrics.HistogramSpec{ Spec: metrics.Spec{ Name: "selects_latency_ms", // required, should indicate unit Help: "SELECT query latency.", // required ConstTags: metrics.Tags{"host": "db01"}, // optional }, Unit: time.Millisecond, // required Buckets: []int64{5, 10, 25, 50, 100, 200, 500}, // required }) if err != nil { panic(err) } h.Observe(37 * time.Millisecond) // increments bucket with upper bound 50 h.IncBucket(37) // also increments bucket with upper bound 50 IncBucket bypasses the time-based Observe API and increments a histogram bucket directly. It finds the correct bucket for the supplied value and adds one to its counter. Observe finds the correct bucket for the supplied duration and increments its counter. This is purely a convenience - it's equivalent to dividing the duration by the histogram's unit and calling IncBucket directly. type HistogramSnapshot struct { Name string Tags Tags Unit time.Duration Values []int64 // rounded up to bucket upper bounds } A HistogramSnapshot is a point-in-time view of the state of a Histogram. type HistogramSpec struct { Spec // Durations are exposed as simple numbers, not strings or rich objects. // Unit specifies the desired granularity for histogram observations. For // example, an observation of time.Second with a unit of time.Millisecond is // exposed as 1000. Typically, the unit should also be part of the metric // name. Unit time.Duration // Upper bounds (inclusive) for the histogram buckets in terms of the unit. // A catch-all bucket for large observations is automatically created, if // necessary. Buckets []int64 } A HistogramSpec configures Histograms and HistogramVectors. A HistogramVector is a collection of Histograms that share a name and some constant tags, but also have a consistent set of variable tags. All exported methods are safe to use concurrently. Nil *HistogramVectors are safe to use and always return no-op histograms. For a general description of vector types, see the package-level documentation. Code: vec, err := metrics.New().Scope().HistogramVector(metrics.HistogramSpec{ Spec: metrics.Spec{ Name: "selects_latency_by_table_ms", // required, should indicate unit Help: "SELECT query latency by table.", // required ConstTags: metrics.Tags{"host": "db01"}, // optional VarTags: []string{"table"}, }, Unit: time.Millisecond, // required Buckets: []int64{5, 10, 25, 50, 100, 200, 500}, // required }) if err != nil { panic(err) } vec.MustGet("table" /* tag name */, "trips" /* tag value */).Observe(37 * time.Millisecond) func (hv *HistogramVector) Get(variableTagPairs ...string) (*Histogram, error) Get retrieves the histogram with the supplied variable tag names and values from the vector, creating one if necessary. The variable tags must be supplied in the same order used when creating the vector. Get returns an error if the number or order of tags is incorrect. func (hv *HistogramVector) MustGet(variableTagPairs ...string) *Histogram MustGet behaves exactly like Get, but panics on errors. If code using this method is covered by unit tests, this is safe. An Option configures a root. Currently, there are no exported options. A Root is a collection of tagged metrics that can be exposed via in-memory snapshots, push-based telemetry systems, or a Prometheus-compatible HTTP handler. Within a root, metrics must obey two uniqueness constraints. First, any two metrics with the same name must have the same tag names (both constant and variable). Second, no two metrics can share the same name, constant tag names, and constant tag values. Functionally, users of this package can avoid collisions by using descriptive metric names that begin with a component or subsystem name. For example, prefer "grpc_successes_by_procedure" over "successes". New constructs a root. Push starts a goroutine that periodically exports all registered metrics to the supplied target. Roots may only push to a single target at a time; to push to multiple backends simultaneously, implement a teeing push.Target. The returned function cleanly shuts down the background goroutine. Code: // First, we need something to push to. In this example, we'll use Tally's // testing scope. ts := tally.NewTestScope("" /* prefix */, nil /* tags */) root := metrics.New() // Push updates to our test scope twice per second. stop, err := root.Push(tallypush.New(ts), 500*time.Millisecond) if err != nil { panic(err) } defer stop() c, err := root.Scope().Counter(metrics.Spec{ Name: "example", Help: "Counter demonstrating push integration.", }) if err != nil { panic(err) } c.Inc() // Sleep to make sure that we run at least one push, then print the counter // value as seen by Tally. time.Sleep(2 * time.Second) fmt.Println(ts.Snapshot().Counters()["example+"].Value()) Output: 1 Scope exposes the root's top-level metrics collection. Tagged sub-scopes and individual counters, gauges, histograms, and vectors can be created from this top-level Scope. ServeHTTP implements a Prometheus-compatible http.Handler that exposes the current value of all the metrics created with this Root (including all tagged sub-scopes). Like the HTTP handler included in the Prometheus client, it uses content-type negotiation to determine whether to use a text or protocol buffer encoding. In particular, it's compatible with the standard Prometheus server's scraping logic. Code: // First, construct a root and add some metrics. root := metrics.New() c, err := root.Scope().Counter(metrics.Spec{ Name: "example", Help: "Counter demonstrating HTTP exposition.", ConstTags: metrics.Tags{"host": "example01"}, }) if err != nil { panic(err) } c.Inc() // Expose the root on your HTTP server of choice. mux := http.NewServeMux() mux.Handle("/debug/net/metrics", root) srv := httptest.NewServer(mux) defer srv.Close() // Your metrics are now exposed via a Prometheus-compatible handler. This // example shows text output, but clients can also request the protocol // buffer binary format. res, err := http.Get(fmt.Sprintf("%v/debug/net/metrics", srv.URL)) if err != nil { panic(err) } text, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { panic(err) } fmt.Println(string(text)) Output: # HELP example Counter demonstrating HTTP exposition. # TYPE example counter example{host="example01"} 1 func (r *Root) Snapshot() *RootSnapshot Snapshot returns a point-in-time view of all the metrics contained in the root (and all its scopes). It's safe to use concurrently, but is relatively expensive and designed for use in unit tests. Code: // Snapshots are the simplest way to unit test your metrics. A future // release will add a more full-featured metricstest package. root := metrics.New() c, err := root.Scope().Counter(metrics.Spec{ Name: "example", Help: "Counter demonstrating snapshots.", ConstTags: metrics.Tags{"foo": "bar"}, }) if err != nil { panic(err) } c.Inc() // It's safe to snapshot your metrics in production, but keep in mind that // taking a snapshot is relatively slow and expensive. actual := root.Snapshot().Counters[0] expected := metrics.Snapshot{ Name: "example", Value: 1, Tags: metrics.Tags{"foo": "bar"}, } if !reflect.DeepEqual(expected, actual) { panic(fmt.Sprintf("expected %v, got %v", expected, actual)) } type RootSnapshot struct { Counters []Snapshot Gauges []Snapshot Histograms []HistogramSnapshot } A RootSnapshot exposes all the metrics contained in a Root and all its Scopes. It's useful in tests, but relatively expensive to construct. A Scope is a collection of tagged metrics. Counter constructs a new Counter. func (s *Scope) CounterVector(spec Spec) (*CounterVector, error) CounterVector constructs a new CounterVector. Gauge constructs a new Gauge. func (s *Scope) GaugeVector(spec Spec) (*GaugeVector, error) GaugeVector constructs a new GaugeVector. func (s *Scope) Histogram(spec HistogramSpec) (*Histogram, error) Histogram constructs a new Histogram. func (s *Scope) HistogramVector(spec HistogramSpec) (*HistogramVector, error) HistogramVector constructs a new HistogramVector. Tagged creates a new scope with new constant tags merged into the existing tags (if any). Tag names and values are automatically scrubbed, with invalid characters replaced by underscores. A Snapshot is a point-in-time view of the state of any non-histogram metric. type Spec struct { Name string // required: metric name, should be fairly long and descriptive Help string // required: displayed on HTTP pages ConstTags Tags // optional: constant tags VarTags []string // variable tags, required for vectors and forbidden otherwise DisablePush bool // reduces load on system we're pushing to (if any) } A Spec configures Counters, Gauges, CounterVectors, and GaugeVectors. Tags describe the dimensions of a metric. Package metrics imports 14 packages (graph) and is imported by 4 packages. Updated 2019-09-27. Refresh now. Tools for package owners.
https://godoc.org/go.uber.org/net/metrics
CC-MAIN-2019-47
refinedweb
2,951
51.65
progressproperty that manages positioning the target on the path accordingly. The progressproperty is a value between 0 and 1 where 0 is at the beginning of the path, 0.5 is in the middle, and 1 is at the end. When the follower's autoRotateproperty is true, the target will be rotated in relation to the path that it is following. import com.greensock.*; import com.greensock.motionPaths.*; //create a circle motion path at coordinates x:150, y:150 with a radius of 100 var circle:CirclePath2D = new CirclePath2D(150, 150, 100); //make the MovieClip "mc" follow the circle and start at a position of 90 degrees (this returns a PathFollower instance) var follower:PathFollower = circle.addFollower(mc, circle.angleToProgress(90), true); /. public var autoRotate:Boolean When autoRotate is true, the follower will automatically be rotated so that it is oriented to the angle of the path that it is following. To offset this value (like to always add 90 degrees for example), use the rotationOffset property. public var path:MotionPath The MotionPath instance that this PathFollower should follow progress:Number A value between 0 and 1 that indicates the follower's position along the motion path. For example, to place the object on the path at the halfway point, you would set its progress to 0.5. You can tween to values that are greater than 1 or less than 0 but the values are simply wrapped. So, for example, setting progress to 1.2 is the same as setting it to 0.2 and -0.2 is the same as 0.8. If your goal is to tween the PathFollower around a CirclePath2D twice completely, you could just add 2 to the progress value or use a relative value in the tween, like: TweenLite.to(myFollower, 5, {progress:"2"}); //or myFollower.progress + 2 progress is identical to rawProgress except that rawProgress does not get re-interpolated between 0 and 1. For example, if rawProgress is set to -3.4, progress would be 0.6. rawProgress can be useful if you need to find out how many times the PathFollower has wrapped. doesn't get re-interpolated between 0 and 1. rawProgress (and progress) indicates the follower's position along the motion path. For example, to place the object on the path at the halfway point, you could set its rawProgress to 0.5. You can tween to values that are greater than 1 or less than 0. For example, setting rawProgress to 1.2 also sets progress to 0.2 and setting rawProgress to -0.2 is the same as setting progress to 0.8. If your goal is to tween the PathFollower around a CirclePath2D twice completely, you could just add 2 to the rawProgress value or use a relative value in the tween, like: TweenLite.to(myFollower, 5, {rawProgress:"2"}); //or myFollower.rawProgress + 2 Since rawProgress doesn't re-interpolate values to always fitting between 0 and 1, it can be useful if you need to find out how many times the PathFollower has wrapped. public function get rawProgress():Number public function set rawProgress(value:Number):void See also public var rotationOffset:Number When autoRotate is true, this value will always be added to the resulting rotation of the target. public var target:Object The target object associated with the PathFollower (like a Sprite, MovieClip, Point, etc.). The object must have x and y properties. public function PathFollower(target:Object, autoRotate:Boolean = false, rotationOffset:Number = 0) ConstructorParameters
http://www.greensock.com/asdocs/com/greensock/motionPaths/PathFollower.html
CC-MAIN-2022-40
refinedweb
581
56.15
is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook. Pseudo-code: def displayhook(value): if value is None: return # Set '_' to None to avoid recursion builtins._ = None text = repr(value) try: sys.stdout.write(text) except UnicodeEncodeError: bytes = text.encode(sys.stdout.encoding, 'backslashreplace') if hasattr(sys.stdout, 'buffer'): sys.stdout.buffer.write(bytes) else: text = bytes.decode(sys.stdout.encoding, 'strict') sys.stdout.write(text) sys.stdout.write("\n") builtins._ = value Changed in version 3.2: Use 'backslashreplace' error handler on UnicodeEncodeError. type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exceptionX.Y/config, and shared library modules are installed in exec_prefix/lib/pythonX.Y/lib-dynload, where X.Y is the version number of Python, for example 3.2. A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None. stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs. Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. The struct sequence flags exposes the status of command line flags. The attributes are read only. Changed in version 3.2: Added quiet attribute for the new -q flag. New in version 3.2.3: The hash_randomization attribute. A structseq holding information about the float type. It contains low level information about the precision and internal representation. The values correspond to the various floating-point constants defined in the standard header file float.h for the ‘C’ programming language; see section 5.2.4.2.2 of the 1999 ISO/IEC C standard [C99], ‘Characteristics of floating types’, for details. The attribute sys.float_info.dig needs further explanation. If s is any string representing a decimal number with at most sys.float_info.dig significant digits, then converting s to a float and back again will recover a string representing the same decimal value: >>> import sys >>> sys.float_info.dig 15 >>> s = '3.14159265358979' # decimal string with 15 significant digits >>> format(float(s), '.15g') # convert to float and back -> same value '3.14159265358979' But for strings with more than sys.float_info.dig significant digits, this isn’t always true: >>> s = '9876543211234567' # 16 significant digits is too many! >>> format(float(s), '.16g') # conversion changes value '9876543211234568' A string indicating how the repr() function behaves for floats. If the string has value 'short' then for a finite float x, repr(x) aims to produce a short string with the property that float(repr(x)) == x. This is the usual behaviour in Python 3.1 and later. Otherwise, float_repr_style. See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents. Return the interpreter’s “thread switch interval”; see setswitchinterval(). New in version 3.2.. CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python. Get the profiler function as set by setprofile(). Get the trace function as set by settrace(). CPython implementation detail: The gettrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. Return a named tuple describing the Windows version currently running. The named elements are major, minor, build, platform, service_pack, service_pack_minor, service_pack_major, suite_mask, and product_type. service_pack contains a string while all other values are integers. The components can also be accessed by name, so sys.getwindowsversion()[0] is equivalent to sys.getwindowsversion().major. For compatibility with prior versions, only the first 5 elements are retrievable by indexing. platform may be one of the following values: product_type may be one of the following values: This function wraps the Win32 GetVersionEx() function; see the Microsoft documentation on OSVERSIONINFOEX() for more information about these fields. Availability: Windows.. pdb largest supported code point for a Unicode character. The value of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.. This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks.. A list of callables that take a path argument to try to create a finder for the path. If a finder can be created, it is to be returned by the callable, else raise ImportError. Originally specified in PEP 302..5', at the time when Python was built. Unless you want to test for a specific system version, it is therefore recommended to use the following idiom: if sys.platform.startswith('freebsd'): # FreeBSD-specific code here... elif sys.platform.startswith('linux'): # Linux-specific code here... Changed in version 3.2.2: 3. Deprecated since version 3.2: This function doesn’t have an effect anymore, as the internal logic for thread switching and asynchronous tasks has been rewritten. Use setswitchinterval() instead.. they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash. Set the interpreter’s thread switch interval (in seconds). This floating-point value determines the ideal duration of the “timeslices” allocated to concurrently running Python threads. Please note that the actual value can be higher, especially if long-running internal functions or methods are used. Also, which thread becomes scheduled at the end of the interval is the operating system’s decision. The interpreter doesn’t have its own scheduler. New in version 3.2.. CPython implementation detail: The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations.. CPython implementation detail: This function is intimately bound to CPython implementation details and thus not likely to be implemented elsewhere. File objects used by the interpreter for standard input, output and errors: By default, these streams are regular text streams as returned by the open() function. Their parameters are chosen as follows:()). Under all platforms though, you can override this value by setting the PYTHONIOENCODING.. Deprecated since version 3.2.1: Python is now developed using Mercurial. In recent Python 3.2 bugfix releases, subversion therefore contains placeholder information. It is removed in Python 3.3.. A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use version_info and the functions provided by the platform module. The C API version for this interpreter. Programmers may find this useful when debugging version conflicts between Python and extension modules.). The components can also be accessed by name, so sys.version_info[0] is equivalent to sys.version_info.major and so on. Changed in version 3.1: Added named component attributes. This is an implementation detail of the warnings framework; do not modify this value. Refer to the warnings module for more information on the warnings framework.. A dictionary of the various implementation-specific flags passed through the -X command-line option. Option names are either mapped to their values, if given explicitly, or to True. Example: $ ./python -Xa=b -Xc Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys._xoptions {'a': 'b', 'c': True} CPython implementation detail: This is a CPython-specific way of accessing options passed through -X. Other implementations may export them through other means, or not at all. New in version 3.2. Citations
http://docs.python.org/py3k/library/sys.html#module-sys
crawl-003
refinedweb
1,378
52.05
Scripting languages are a trendy thing. Take the game Morrowind by Bethesda Softworks, for example. This game runs a lot of scripts in a custom language: tons of scripts compiled in a pseudo bytecode form before to be run inside the game. Same for the game Age of Mythology by Ensemble Studios: it uses a custom script language for the computer AI programming. This is thus a critical part in several programs, and program's speed depends in a part on them. I love speed. I love speedy programs, well-programmed applications. I'm still looking for speed, and I hope, like many of you. I then thought, as I was really inspired: why not embed a C++ compiler to use C++ as a compiled "scripting" language? I thought about the well-known GNU GCC project. If you don't know it, it is an open-source C/C++/Java/others compiler, aiming primarily Linux platforms. The major advantage of this set of developer tools is that it is free. I thought I would be able to compile the GCC sources in a pretty Windows DLL; that revealed to be pretty impossible. I found out the MinGW project. This was pretty good: compiled compiler + Windows and standard headers + libraries in a relatively small package (15MB). Surely, a 15MB package is actually big to some projects. But this article aims primarily big projects such as games. And, if you keep only the needed files (headers + libraries + c++ compiler) from the MinGW package, you will get easily to less than 4MB (compressed). And, embedding MinGW is actually not necessary if you don't want to give end-user the ability to modify or create new scripts. Actually Gecko brings you the fastest "scripting" language on the world! See the The Great Computer Language Shootout, and see how fast is gcc (even g++) compared to some well-known languages. Besides, using native machine code (compiled C++) allows having a very low memory usage, compared to some other scripting languages which can require an interpreter, or a bytecode interpreter. Furthermore, thanks to MinGW supplied libraries and headers, you have infinite possibilities: use windows.h functions, math.h functions, IO functions... Another thing: you may be wondering: why Gecko? Gecko stands for "Gnu Embedded C++ KOmpiler" (I was really, really inspired this day ). Gecko produces ECK files. ECK stands for "Embedded C++, Kompiled". ECK files are in fact renamed DLL files, as you may have guessed. The Gecko thing consists actually of several things: CGecko CGecko gecko; if (!gecko.IsEckUpToDate("test")) gecko.Compile("test"); if (gecko.Load("test")) { if (gecko.RunThreaded()) { printf("[Press any key to abort]"); getchar(); gecko.AbortThread(); } } The CGecko class relies on the CRedirect class to redirect standard IO while running MinGW (class found on codeproject -- great thanks to his author). CRedirect Read carefully each comment before using functions. class CGecko : protected CRedirect { public: // ctor does nothing special. // dtor will call AbortThread() and Unload() if you ommit them. CGecko(void); ~CGecko(void); // Normally initialization is done automatically // thanks to GeckoSetup code // so you shouldn't use these functions. Anyway they // are self-explanatory. void SetMinGWDir(LPCSTR szDir); void SetGeckoDir(LPCSTR szDir); // Tests if a ECK file is up-to-date, by checking the // INI written when compiled. // If the ECK file or the INI file can't be found, // eckIsUpToDate() returns false. bool eckIsUpToDate(LPCSTR szName); // Tests if ECK file exists. bool eckExists(LPCSTR szName); // Launches compilation/linkage of the "szName.cpp" file. // Compiler/linker outputs will go to virtual functions below. // WARNING: if you try to re-compile to an ECK // previously loaded, even unloaded, // the linker will complain: 'Unable to write(...)'. That's // because I don't manage to have // the ECK file unmapped from process. See eckUnload() below. bool eckCompile(LPCSTR szName); // Overridable functions called when compiling. virtual void OnCommandStart(LPCSTR lpszCmdLine) {}; virtual void OnCommandSTDOUT(LPCSTR lpszOutput) {}; virtual void OnCommandSTDERR(LPCSTR lpszOutput) {}; virtual void OnCommandEnd(bool bSuccessful) {}; // Loads an ECK file. If a ECK file is already loaded/running, // it will be automatically stopped/unloaded. // To execute several ECK's, construct several CGecko. bool eckLoad(LPCSTR szName); // Unloads an ECK file. Actually it will never be unloaded // completely until program termination: // variables will remain with the same value at next Load() // of the same ECK. // That's because I don't manage to have the ECK file unmapped // from process, even with several calls // to FreeLibrary(). If someone has an idea... void eckUnload(void); // Runs a previously loaded ECK file (same as calling // eckSendMessage(GM_RUN)). // Returns what you returns in your script, or -1 in case // of error (no ECK loaded for example). int eckRun(WPARAM wParam=0, LPARAM lParam=0); // Aborts (stops) a previously loaded and running ECK file // (same as calling eckSendMessage(GM_ABORT)). // Returns what you returns in your script, or -1 in case of error. int eckAbort(WPARAM wParam=0, LPARAM lParam=0); // Sends a message to currently loaded ECK file. // Returns what you returns in your script, or -1 in case of error. int eckSendMessage(UINT nMsg, WPARAM wParam=0, LPARAM lParam=0); // Creates a thread and runs the loaded ECK file from it. bool eckRunThreaded(WPARAM wParam=0, LPARAM lParam=0, int nPriority=THREAD_PRIORITY_NORMAL); // Returns true if a thread is running. bool eckIsThreadRunning(void); // Returns the thread handle of current running script. // Can be NULL if no thread. HANDLE GetThreadHandle(void); // Aborts running script (sending GM_ABORT), causing thread // to return if the script indeed stops. // If the running script doesn't stop within the specified time // (in milli-seconds), either bAllowKill // is true and the thread will be terminated with TerminateThread(), // or eckAbortThread() will return. // Returns true if the script is aborted and thread is stopped. bool eckAbortThread(DWORD dwTimeout=5000, bool bAllowKill=false); }; The only problem is: providing a C++ compiler and low-level functions to non-experienced users can be dangerous. If you integrate Gecko and embed MinGW, you must thus engage end-user responsibility and warn him about risks for his computer if he does whatsoever. This is why I put a big disclaimer: I won't be responsible for any damage caused by a mis-usage of the Gecko component, or by a script. You can however choose not to embed MinGW: you will then be able to run ECK files but not to compile. That eliminates the problem. GECKO_NATIVE void GECKO_NATIVE_CALL SetPlayerHealth(int nNewHealth); GECKO_NATIVE void GECKO_NATIVE_CALL AlertDamage(int nDamage); GECKO_NATIVE void GECKO_NATIVE_CALL AppendOutput(LPCSTR szText); GECKO_NATIVE int GECKO_NATIVE_CALL foo(int i); GECKO_NATIVE const char* GECKO_NATIVE_CALL bar(LPCSTR a, float d); ... #include "MyGecko.h" GECKO_NATIVE void GECKO_NATIVE_CALL SetPlayerHealth(int nNewHealth) { ... } GECKO_NATIVE void GECKO_NATIVE_CALL AlertDamage(int nDamage) { ... } ... That's all With these efforts you get to only 3.25 MB (zip-compressed). URL -:. Here is the relevant part of the GNU General Public License: ." "3. You may copy and distribute the Program (or a work based on it,under Section 2) in object code or executable form under the terms ofSections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readablesource code, which must be distributed under the terms of Sections1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least threeyears, to give any third party, for a charge no more than yourcost of physically performing source distribution, a completemachine-readable copy of the corresponding source code, to bedistributed under the terms of Sections 1 and 2 above on a mediumcustomarily used for software interchange; or, c) Accompany it with the information you received as to the offerto distribute corresponding source code. (This alternative isallowed only for noncommercial distribution and only if youreceived the program in object code or executable form with suchan offer, in accord with Subsection b above.)" In a nutshell If you want to embed the partial MinGW package in a noncommercial product: "Accompany it with the information you received as to the offer to distribute corresponding source code." You must provide the source for the following packages if you plan to embed the partial MinGW package in a commercial product: These packages can be found.
http://www.codeproject.com/Articles/4900/Gecko-Embedded-C-scripting-for-your-applications?msg=643107
CC-MAIN-2015-11
refinedweb
1,365
56.15
31 May 2012 12:52 [Source: ICIS news] LONDON (ICIS)--European spot acetone prices continue to come under pressure, largely as a result of falling propylene costs, market sources said on Thursday. Acetone spot prices have dropped below €900/tonne FD (free delivered) NWE (northwest ?xml:namespace> The €125/tonne fall in the value of the June propylene contract price has clearly impacted price ideas this week and business has been recorded at €880/tonne FD NWE. Although acetone producers still see their demand as being at a “good level” most are not surprised at this week’s spot price development. One producer said: “The €890/tonne does not surprise me. If I was a trader in this position, I would get rid of this position, but I don’t need to sell at these numbers yet.” Talking about its demand in June, the producer added: “Everybody is still ordering. There is a lot of talk [about demand slowing down] but I have not seen any reduction.” A second producer echoed this: “Acetone demand is on a good level. Most of the price pressure is coming from the solvents market”. The producer quoted €900-950/tonne FD NWE as a market price for spot acetone this week. In the trade and distribution market, a source said that five trucks of acetone had been sold into Meanwhile, a supplier based in the south of Europe said its demand for June was “good” and it could still sell into However, another southern-based producer said: “You can get whatever figure you want - it’s very mixed. The producer valued spot acetone in a €880-980/tonne price range. (€1 =
http://www.icis.com/Articles/2012/05/31/9565986/europe-acetone-spot-under-pressure-from-falling-propylene.html
CC-MAIN-2015-14
refinedweb
277
67.89
Tables are very important in web page design as they are one of the primary means of controlling the layout on the page. In pure HTML, several tags create and format tables, and many of those have analogs in ASP.NET server controls. If you don’t need server-side capabilities, then you will be fine using the static HTML tags. But when you need to control the table at runtime, then server controls are the way to go. (You could also use HTML server controls, described in the previous chapter, but they don’t offer the consistency of implementation and object model offered by ASP.NET controls.) Table 4-10 summarizes the ASP.NET server controls used to create tables in web pages. There is some overlap in the functionality of Table controls and the Data controls. These controls, covered in detail in Chapter 9, including the GridView, Repeater, DataList, and DataGrid controls, are primarily used to display data from a data source, such as a database, XML file, or array. Both the Table control and the Data controls can be used to display data in a table or list-formatted layout. In fact, all of these controls render to a desktop browser (or have the option to render) as HTML tables. (You can verify this by going to your browser and viewing the source of the page displayed.) Table 4-11 summarizes the differences between these five controls. TableDemo, shown in Figure 4-19, demonstrates most of the basic table functionality of the Table control. This example uses a CheckBoxList control and a RadioButtonList control to set attributes of the font samples displayed in the table. Then a table is created that contains a sample of every font installed on your system. The content file shown in Example 4-32, uses a static HTML table to position the font style and size selection controls. After some opening headers, there is a standard, plain vanilla HTML table. This uses the familiar <table> tags enclosing table rows (<tr>), which enclose table cells ( <td>). There is nothing dynamic going on here, just the common technique of using a table to control the layout of the page. The second cell of the first row contains a CheckBoxList server control, and the second cell of the second row contains a RadioButtonList server control, both of which have been discussed earlier in this chapter. Both of these controls have several things in common: an id attribute, the all-important runat attribute, and AutoPostBack set to true, so any changes will take effect immediately. Both controls also have various other attributes to give the desired layout. Example 4-32. default.aspx for TableDemo <%@ Page <head runat="server"> <title>Table Control</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Table Control</h1> <table> <tr> <td> <strong>Select a Font Style:</strong> </td> <td> <asp:CheckBoxList </asp:CheckBoxList> </td> </tr> <tr> <td> <strong>Select a Font Size:</strong> </td> <td> <asp:RadioButtonList <asp:ListItem <asp:ListItem <asp:ListItem <asp:ListItem <asp:ListItem <asp:ListItem </asp:RadioButtonList> </td> </tr> </table> > </div> </form> </body> </html> The CheckBoxList control has an event handler defined for initialization, onInit (highlighted in Example 4-32), which points to the method cblFontStyle_Init, which is contained in the code behind file, shown in Example 4-33. Example 4-33. default.aspx.cs for TableDemo using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Drawing; // necessary for FontFamily using System.Drawing.Text; // necessary for Fonts public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string str = "The quick brown fox jumped over the lazy dogs."; int i = 0; // Get the style checkboxes. bool boolUnder = false; bool boolOver = false; bool boolStrike = false; foreach(ListItem li in cblFontStyle.Items) { if (li.Selected == true) { switch (li.Value) { case "u": boolUnder = true; break; case "o": boolOver = true; break; case "s": boolStrike = true; break; } } } // Get the font size. int size = Convert.ToInt32(rblSize.SelectedItem.Value); // Get a list of all the fonts installed on the system // Populate the table with the fonts and sample text. InstalledFontCollection ifc = new InstalledFontCollection(); foreach( FontFamily ff in ifc.Families ) { TableRow r = new TableRow(); TableCell cFont = new TableCell(); cFont.Controls.Add(new LiteralControl(ff.Name)); r.Cells.Add(cFont); TableCell cText = new TableCell(); Label lbl = new Label(); lbl.Text = str; // ID not necessary here. This just to show it can be set. i++; lbl.ID = "lbl" + i.ToString(); // Set the font name lbl.Font.Name = ff.Name; // Set the font style if (boolUnder) lbl.Font.Underline = true; if (boolOver) lbl.Font.Overline = true; if (boolStrike) lbl.Font.Strikeout = true; // Set the font size. lbl.Font.Size = size; cText.Controls.Add(lbl); r.Cells.Add(cText); tbl.Rows.Add(r); } } protected void cblFontStyle_Init(object sender, EventArgs e) { // create arrays of items to add string[] FontStyle = {"Underline","OverLine", "Strikeout"}; string[] Code = {"u","o","s"}; for (int i = 0; i < FontStyle.GetLength(0); i++) { // Add both Text and Value this.cblFontStyle.Items.Add(new ListItem(FontStyle[i],Code[i])); } } } This code is very similar to the code shown in Example 4-18 for filling a CheckBoxList from an array. Here you create two string arrays, FontStyle and Code, to fill the ListItem properties Text and Value, respectively. The RadioButtonList control, on the other hand, does not have an onInit event handler, but rather the ListItems it contains are defined right within the control itself. This example uses self-closing ListItem tags with attributes specifying both the Text property and the Value property. In the case of the 12-point radio button, the Selected property is set to true, which makes this the default value on initialization. Neither of these controls has any other event handler. Specifically, no event handler exists for OnSelectedIndexChanged, as there are in previous examples in this chapter. Yet, AutoPostBack is true. As you will see, the ASP.NET Table control is rebuilt every time the page is loaded, which occurs every time the CheckBoxList or the RadioButtonList control is changed. The current value for the font style is obtained from the CheckBoxList control, and the current font size is obtained from the RadioButtonList control. Notice the two using statements (highlighted in Example 4-33) in the code-behind file, in addition to those inserted by default by VS2005. These are necessary to enable usage of the Font and FontFamily classes without typing fully qualified member names. The Table control is the heart of this page: > Like all ASP.NET server controls, the Table control inherits from WebControl and therefore has the standard set of properties, methods, and events from that class and the classes above it in the hierarchy. In addition, the Table control has properties of its own, which are listed in Table 4-12. Most of these properties are demonstrated in TableDemo. Note the following information about the Table control in TableDemo: The BackImageUrlattribute in the Tablecontrol points to an image file located in the same directory as the .aspx file itself, so the URL does not need to be fully qualified. In these code examples we used SunflowerBkgrd.jpg, which was copied from the c:\ProgramFiles\CommonFiles\MicrosoftShared\Stationery directory. You can use any .jpg file you want or simply omit the BackImageUrlattribute. For a complete discussion of relative and absolute addressing, see the sidebar "File Locations" in the section "Button Controls.” The syntax for font name and size attributes is Font-Nameand Font-Sizewhen declared as part of the ASP.NET server control using its declarative syntax, but Font.Nameand Font.Sizewhen used in the code-behind file. If the Widthattribute is set as an integer with no units, it causes the table to be the specified number of pixels in width, irrespective of the width of the browser window. The table can be made wider than the browser window. If the Widthattribute is not specified, then the table will automatically be as wide as necessary to display the contents of the cells. If the browser window is not wide enough, the cell contents will wrap. Once the browser window is made wide enough that all the cells can display without wrapping, the table will not get any wider. Nested inside the Table control is a single TableHeaderRow control. This row contains the header cells, indicated by TableHeaderCell controls. The TableRow control is used to represent a single row in a Table control. It is derived from the WebControl class like the Table control. As Table 4-13 shows, it has several properties not shared with all its other sibling controls. The TableRow class has six other controls, or classes, derived from it as described in Table 4-14. There are two types of table cell controls: a TableCell control for the body of the table and a TableHeaderCell for header cells. Both are used in TableDemo. The TableHeaderCell control represents a heading cell in a Table control. It is derived from the TableCell control class. In fact, all of its properties, events, and methods are exactly the same as for the TableCell control. The single difference between the TableCell and TableHeaderCell controls is that the TableHeaderCell control renders to the browser as a <th> element rather than a <td>. Most browsers display <th> cells in a centered, bold font. As can be seen in Figure 4-19, the header cells are bold, but the HorizontalAlign attribute in the TableRow declaration in Example 4-32 overrides the default text alignment. Perhaps more fundamentally, TableHeaderCells are a distinctly different type of control in the Controls collection of the page. None of the nested TableHeaderCell controls in this example have an id or a runat attribute. These attributes are unnecessary here since these controls are not accessed programmatically elsewhere in the code. Only a single row is defined statically. The rest of the rows are defined dynamically in the Page_Load method in the code-behind file shown in Example 4-33. In Example 4-32, the content of the header cells is the literal text strings between the opening and closing control tags. Alternatively, you may use self-closing tags and specify the content as a Text property: <asp:TableHeaderCell The TableCell control is used to contain the actual content of the table. Like the Table and TableRow controls, it is derived from the WebControl class. The TableCell and the TableHeaderCell controls have the properties shown in Table 4-15, which are not shared with its siblings. Table 4-15. Properties of the TableCell and TableHeaderCell controls not shared with other table controls In TableDemo, you have a Table control containing a single TableRow object that contains a pair of TableHeaderCell objects. The Page_Load method in the code-behind file, which is run every time the page is loaded, creates the balance of the table rows dynamically. Often times, the Page_Load method will examine the IsPostBack property to test if the page is being loaded for the first time. If the load is the result of a postback, you may not want certain code to execute, either because it is unnecessary and expensive, or because you will lose or change state information. (See Chapter 3 for a full discussion of the IsPostBack property.) In this example, however, you want the code to run every time the page loads. In fact, the CheckBoxList and the RadioButtonList controls have their AutoPostBack properties set to true to force the page to post. This forces the table to be regenerated. Each time the table is regenerated, the font styles are obtained from the CheckBoxList control, and the font size is obtained from the RadioButtonList control. The Page_Load method begins by initializing a couple of variables: string str = "The quick brown fox jumped over the lazy dogs."; int i = 0; str is the text displayed in the table, and i is a counter used later on. You get the style or styles from the CheckBoxList control. To do so, you initialize three Boolean variables to use as flags, one for each style: bool boolUnder = false; bool boolOver = false; bool boolStrike = false; Then, using a foreach loop to test each of the ListItem objects in the cblFontStyle CheckBoxList in turn, you set the Boolean variable for each font style to true if that checkbox has been selected. That is done by testing to see if the Selected property of the ListItem object is true: foreach(ListItem li in cblFontStyle.Items) { if (li.Selected == true) { switch (li.Value) { case "u": boolUnder = true; break; case "o": boolOver = true; break; case "s": boolStrike = true; break; } } } Getting the font size selected in the RadioButtonList rblSize is much simpler since all you have to do is get the Value property of the ListItem object returned by the SelectedItem property. You put that integer into the size variable: int size = Convert.ToInt32(rblSize.SelectedItem.Value); Now comes the meat of the method. You need to get a list of all the fonts installed on the machine. To do this, instantiate a new InstalledFontCollection object: InstalledFontCollection ifc = new InstalledFontCollection(); Iterate over that collection, using a foreach loop, looking at each of the FontFamily objects in turn: foreach( FontFamily ff in ifc.Families ) For each font family in the collection of FontFamilies, you create a new TableRow object: TableRow r = new TableRow(); Within that TableRow object, you create two TableCell objects: one called cFont to hold the font name and a second called cText to hold the sample text string defined earlier. The following code implements the cFont cell: TableCell cFont = new TableCell(); cFont.Controls.Add(new LiteralControl(ff.Name)); r.Cells.Add(cFont); The cFont TableCell object makes use of an ASP.NET server control called the LiteralControl. This control is used to insert text and HTML elements into the page. The only property of the LiteralControl, other than those inherited from Control, is the Text property. For the cell containing the sample text, you will use a slightly different technique, because you want to be able to manipulate the font and size properties of the text string. After instantiating a new TableCell object named cText, you will instantiate a Label control and assign the variable str, defined earlier, to its Text property: TableCell cText = new TableCell(); Label lbl = new Label(); lbl.Text = str; You increment the counter defined earlier and use it by assigning an ID property to the Label control: i++; lbl.ID = "lbl" + i.ToString(); Actually, this step is unnecessary because nowhere in this example do you need to refer back to any specific cell, but it was added to demonstrate how it can be done. You now assign the font name: lbl.Font.Name = ff.Name; The syntax used here differs from the syntax for setting the font name within the tags of a ASP.NET server control ( Font.Name versus Font-Name). Use the flags set earlier to set the font styles: if (boolUnder) lbl.Font.Underline = true; if (boolOver) lbl.Font.Overline = true; if (boolStrike) lbl.Font.Strikeout = true; Since the table is being recreated from scratch each time the page is loaded and the defaults for each of these styles is no style (i.e., false), there is no need to set the properties explicitly to false. Set the font size, add the Label object to the TableCell object, add the TableCell object to the TableRow object, and add the TableRow object t the Table object: lbl.Font.Size = size; cText.Controls.Add(lbl); r.Cells.Add(cText); tbl.Rows.Add(r); There you have it. Controlling the width of the cells merits special mention. It is similar to controlling table width but different enough to cause some confusion. Looking at the HTML in Example 4-32, you can see that the second cell in the header row has a Width attribute set to 80%: <asp:TableHeaderCell Sample text </asp:TableHeaderCell> Browsers make all the cells in a column the same width. If none of the cells have any width specification, the column will automatically size to best accommodate all the cells, taking into account any width specifications for the table and the size of the browser window. If multiple cells in a column have a width specification, then the widest cell specification is used. For easiest readability, include a width specification in only one row, generally the first row of the table. Hence, the Width attribute appears in the header row of this example. When the width is specified declaratively as part of a ASP.NET server control tag, it can be given either as a percentage of the entire table, as was done in this example, or it can be given as a fixed number of pixels, as in the following: Width="400" Cell width can also be specified programmatically, in which case the syntax is somewhat different. In C#, the code is the following: TableCell cText = new TableCell(); The variable cText, of type TableCell, is assigned to the new cell instance. The Width property can be applied to this TableCell instance, either as pixels or as a percentage of the table width. To specify the Width property as 80 percent of the table width, use the following line of code: cText.Width = Unit.Percentage(80); To specify a fixed number of pixels, use either of the following lines of code: cText.Width = Unit.Pixel(400); cText.Width = 400; There is an interaction between the cell Width property and the Wrap property. The default value for the Wrap property is true. If the Wrap property is set to false, one of the following situations will occur: If there is no Widthproperty specified, then the contents of the cell will not wrap and the column width expands to accommodate the largest cell. If the Widthproperty is set to a pixel value, the Wrapproperty will be overridden and the cell contents wrap to honor the Widthproperty. If the Widthproperty is set to a percentage value, it will be overridden and the column will be made wide enough to preclude any wrapping. Get Programming ASP.NET, 3rd Edition now with the O’Reilly learning platform. O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.
https://www.oreilly.com/library/view/programming-aspnet-3rd/059600916X/ch04s09.html
CC-MAIN-2022-21
refinedweb
3,058
55.24
C# MS Access Full Contact Mangement System Introduction Models Repository MS Excel How to export data to MS Excel Pagination Paginating Our data UI Our UI Code Contact and ResultModel Classes This lesson is part of our C# Contacts Management System Development Course with a MS Access Database backend and Windows Forms as the user interface. In this particular class we want to create our model classes. What are our model classes? Well these are our data objects. They are classes that represent our business object. The business object in this system we are developing is a Contact object. We have to create a class from which the contact object will be instantiated. Here are the Model classes we create for this system: Video Tutorial(Recommended) /Model/Contact.cs This is our main model class. It’s our data object. Our system is a Contacts Management System. Well it is this class instances that we are managing in our system. A single Contact will have the following properties: - ID – Autogenerated at the database level. - Name – Name of the contact. - Phone 1 and Phone 2 – Mobile phone numbers. - Remarks – Additional remarks about the contact. Here’s the full code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContactManager.Data.Model { class Contact { public int Id { get; set; } public String Name { get; set; } public String Phone1 { get; set; } public String Phone2 { get; set; } public String Email { get; set; } public String Remarks { get; set; } } } /Model/ResultModel.cs This class’s instance will be used to hold a resultset that we can pass from our repository class to our user interface or other classes. The advantage it provides us is it’s capability to hold both or either of our message and list of contacts. Thus we have consistency in whatever object we are returning. For example if we have an error while attempting to retrieve our data, we simply return the error as a message property of this class’s instance. If we have a list of contacts, we simply return it as a property of this class’s instance. Here’s the full code. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContactManager.Data.Model { class ResultModel { public string Message { get; set; } public List<Contact> Contacts { get; set; } } }
https://camposha.info/course/csharp-ms-access-full-contact-mangement-system/lesson/contact-and-resultmodel-classes/
CC-MAIN-2019-39
refinedweb
394
52.15
I have tried in the past to get Django running under IIS 8 in Windows 8 Developer Preview. Now that the Consumer Preview of Windows 8 is out, I was wondering if I could get some detailed instructions on setting up Django within IIS. How do I go about this process - I hardly know where to begin. Do I need a specific ISAPI module? This process is not exactly trivial but it is possible using the following steps: First, download and install Python 2.6. (The reason I suggest Python 2.6 instead of Python 2.7 is because the latest Python version supported by the PyISAPIe module is Python 2.6.) Make a note of the location you install Python to (C:\Python26 by default if I remember correctly). C:\Python26 Right-click Computer and click Properties. Click Advanced System Settings on the left. Click the advanced tab and then click the Environment Variables button. Locate Path in the lower list box: Click the "Edit..." button and go to the end Variable Value and insert ;C:\Python26 (a semicolon plus the path you installed Python to): ;C:\Python26 Click OK to dismiss all of the dialogs. Next, download the latest version of PyISAPIe here. Extract the contents of the archive somewhere and open up the directory. Next, open the Control Panel, click Programs and Features, and click "Turn Windows features on or off" on the left. Browse to Internet Information Services -> World Wide Web Services -> Application Development Features and then make sure ISAPI Extensions is checked. Apply the changes and then open up IIS Manager. Double-click the Handler Mappings icon. Click Add Module Mapping on the right. In the dialog that appears, enter the following information: PyISAPIe.dll It should look something like this: Before closing the dialog, click Request Restrictions, uncheck "Invoke handler only if request is mapped to:", and click OK. Also click OK to close the Add Module Mapping dialog (click Yes if you are asked whether you want to add the extension with an Allowed entry to the ISAPI and CGI Restrictions list). The next step is to download Django. Extract the contents of the archive somewhere (noting the location). Open a Command Prompt (you can do this by pressing Win + R, typing cmd and hitting Enter) and type cd followed by the location you extracted Django to: cmd cd Press Enter, type cd dj, and then push Tab. This should complete the path to the Django folder and you can press Enter to open the directory. Now type python setup.py install: cd dj python setup.py install Now you need to create the Django project. For example purposes, we will create the projects under C:\Django. In the command window, type the commands below followed by Enter: C:\Django cd C:\ mkdir Django cd Django python C:\Python26\Lib\site-packages\django\bin\django-admin.py startproject test This creates a project named 'test'. Once the process completes successfully, the last remaining task is to connect PyISAPIe to Django. To do this, return to the directory you extracted PyISAPIe to and look for an Http directory. Inside is a file Isapi.py. Open it in a text editor and replace the contents with the following: Isapi.py from django.core.handlers.wsgi import WSGIHandler as DjangoHandler from Http.WSGI import RunWSGI from Http import Env import os, sys sys.path.append('C:\Django') os.environ['DJANGO_SETTINGS_MODULE'] = 'test.settings' def Request(): PathInfo = Env.PATH_INFO if not PathInfo.startswith('/'): return True for Excl in ['/media']: if PathInfo.startswith(Excl): return True return RunWSGI(DjangoHandler(), Base='/') Copy the Http directory to C:\Python26\Lib\site-packages (or the appropriate directory if you installed Python somewhere else). C:\Python26\Lib\site-packages Restart IIS (you can do this by clicking "restart" in the right hand side of IIS Manager): If everything worked correctly, you should be able to go to to view your new Django site: Further Notes and Additions I have since compiled PyISAPIe for Python 2.7 myself (both 32-bit and 64-bit) and uploaded the files here: In step #6, you need to ensure that pyisapie.dll is in a directory that IIS has at least read access to. Failing to take this into consideration will result in strange errors. pyisapie.dll Another option is to use django-windows-tools, though it hasn't been updated in a couple of years. It simply sets up the FastCGI module in IIS for you so you don't have to worry about utilizing PyISAPIe. You will find the detailed guide how to install Django on IIS8 inside this blog post: Installing Django on IIS: A Step-by-Step Tutorial In short these steps need to be done: Hope that helps! By posting your answer, you agree to the privacy policy and terms of service. asked 2 years ago viewed 2499 times active 10 days ago
http://serverfault.com/questions/366348/how-to-set-up-django-with-iis-8
CC-MAIN-2015-11
refinedweb
821
65.62
Embedded classes, protected constructors, hiding constants, anonymous enums, namespaces. A good software engineer is like a spy. He exposes information to his collaborators on the need-to-know basis, because knowing too much may get them in trouble. I’m not warning here about the dangers of industrial espionage. I’m talking about the constant struggle with complexity. The more details are hidden, the simpler it is to understand what’s going on. The class Link is only used internally by the linked list and its friend the sequencer. Frankly, nobody else should even know about its existence. The potential for code reuse of the class Link outside of the class List is minimal. So why don’t we hide the definition of Link inside the private section of the class definition of List. class List { friend class ListSeq; public: List (); ~List (); void Add (int id); private: // nested class definition class Link { public: Link (Link * pNext, int id) : _pNext (pNext), _id (id) {} Link * Next () const { return _pNext; } int Id () const { return _id; } private: Link * _pNext; int _id; }; private: Link const * GetHead () { return _pHead; } Link* _pHead; }; The syntax of class embedding is self-explanatory. Class ListSeq has a data member that is a pointer to Link. Being a friend of List, it has no problem accessing the private definition of class Link. However, it has to qualify the name Link with the name of the enclosing class List--the new name becomes List::Link. class ListSeq { public: bool AtEnd () const { return _pLink == 0; } void Advance () { _pLink = _pLink->Next(); } int GetId () const { return _pLink->Id (); } protected: ListSeq (List const & list) : _pLink (list.GetHead ()) {} private: // usage of nested class List::Link const *_pLink; }; The classes List and ListSeq went through some additional privatization (in the case of ListSeq, it should probably be called "protectization"). I made the GetHead method private, but I made ListSeq a friend, so it can still call it. I also made the constructor of ListSeq protected, because we never create it in our program--we only use objects of the derived class, IdSeq. I might have gone too far with privatization here, making these classes more difficult to reuse. It's important, however, to know how far you can go and make an informed decision when to stop. Conceptually, the sequencer object is very closely tied to the list object. This relationship is somehow reflected in our code by having ListSeq be a friend of List. But we can do much better than that--we can embed the sequencer class inside the list class. This time, however, we don't want to make it private--we want the clients of List to be able to use it. As you know, ouside of the embedding class, the client may only access the embedded class by prefixing it with the name of the outer class. In this case, the (scope-resolution) prefix would be List::. It makes sense then to shorten the name of the embedded class to Seq. On the outside it will be seen as List::Seq, and on the inside (of List) there is no danger of name conflict. Here's the modified declaration of List: class List { public: List (); ~List (); void Add (int id); private: class Link { public: Link (Link * pNext, int id) : _pNext (pNext), _id (id) {} Link * Next () const { return _pNext; } int Id () const { return _id; } private: Link * _pNext; int _id; }; public: class Seq { public: Seq (List const & list) : _pLink (list.GetHead ()) {} bool AtEnd () const { return _pLink == 0; } void Advance () { _pLink = _pLink->Next (); } int GetId () const { return _pLink->Id (); } private: Link const * _pLink; // current link }; friend Seq; private: Link const * GetHead () const { return _pHead; } Link * _pHead; }; Notice, by the way, how I declared Seq to be a friend of List following its class declaration. At that point the compiler knows that Seq is a class. The only client of our sequencer is the hash table sequencer, IdSeq. We have to modify its definition accordingly. class IdSeq: public List::Seq { public: IdSeq (HTable const & htab, char const * str) : List::Seq (htab.Find (str)) {} }; And, while we're at it, how about moving this class definition where it belongs, inside the class HTable? As before, we can shorten its name to Seq and export it as HTable::Seq. And here's how we will use it inside SymbolTable::Find for (HTable::Seq seq (_htab, str); !seq.AtEnd (); seq.Advance ()) There is one more example of a set of related entities that we would like to combine more tightly in our program. But this time it's a mixture of classes and data. I'm talking about the whole complex of FunctionTable, FunctionEntry and FunctionArray (add to it also the definition of CoTan which is never used outside of the context of the function table). Of course, I could embed FunctionEntry inside FunctionTable, make CoTan a static method and declare FunctionArray a static member (we discussed this option earlier). There is however a better solution. In C++ we can create a higher-level grouping called a namespace. Just look at the names of objects we're trying to combine. Except for CoTan, they all share the same prefix, Function. So let's call our namespace Function and start by embedding the class definition of Table (formerly known as FunctionTable) in it. namespace Function { class Table { public: Table (SymbolTable & symTab); ~Table () { delete []_pFun; } int Size () const { return _size; } PFun GetFun (int id) const { return _pFun [id]; } private: PFun * _pFun; int _size; }; } The beauty of a namespace it that you can continue it in the implementation file. Here's the condensed version of the file funtab.cpp: namespace Function { double CoTan (double x) {...} class Entry {...}; Entry Array [] = {...}; Table::Table (SymbolTable & symTab) : _size(sizeof Array / sizeof Array [0]) {...} } As you might have guessed, the next step is to replace all occurrences of FunctionTable in the rest of the program by Function::Table. The only tricky part is the forward declaration in the header parse.h. You can't just say class Function::Table;, because the compiler hasn't seen the declaration of the Function namespace (remember, the point of using a forward declaration was to avoid including funtab.h). We have to tell the compiler not only that Table is a class, but also that it's declared inside the Function namespace. Here's how we do it: namespace Function { class Table; } class Parser { public: Parser (Scanner & scanner, Store & store, Function::Table & funTab, SymbolTable & symTab ); ... }; By the way, the whole C++ Standard Library is enclosed in a namespace. Its name is std. Now you understand these prefixes std:: in front of cin, cout, endl, etc. (You've also learned how to avoid these prefixes using the using keyword.) There are several constants in our program that are specific to the implementation of certain classes. It would be natural to hide the definitions of these constants inside the definitions of classes that use them. It turns out that we can do it using enums. We don’t even have to give names to enums—they can be anonymous. Look how many ways of defining constants there are in C++. There is the old-style C #define preprocessor macro, there is a type-safe global const and, finally, there is the minimum-scope enum. Which one is the best? It all depends on type. If you need a typed constant, say, a double or a (user defined) Vector, use a global const. If you just need a generic integral type constant—as in the case of an array bound—look at its scope. If it’s needed by one class only, or a closely related group of classes, use an enum. If its scope is larger, use a global const int. A #define is a hack that can be used to bypass type checking or avoid type conversions--avoid it at all costs. By the way, debuggers don’t see the names of constants introduced through #defines. They appear as literal numerical values. It might be a problem sometimes when you don’t remember what that 74 stood for. Here’s the first example of hiding constants using enumerations. The constant idNotFound is specific to the SymbolTable. class SymbolTable { public: // Embedded anonymous enum enum { idNotFound = -1 }; … } No change is required in the implementation of Find. Being a method of SymbolTable, Find can access idNotFound with no qualifications. Not so with the parser. It can still use the constant idNotFound, since it is defined in the public section of SymbolTable, but it has to qualify its name with the name of the class where it's embedded. if (_scanner.Token () == tLParen) // function call { _scanner.Accept (); // accept '(' pNode = Expr (); if (_scanner.Token() == tRParen) _scanner.Accept (); // accept ')' else _status = stError; // The use of embedded enum if (id != SymbolTable::idNotFound && id < _funTab.Size ()) { pNode = new FunNode ( _funTab.GetFun (id), pNode ); } else { cerr << "Unknown function \""; cerr << strSymbol << "\"\n"; } } else { // Factor := Ident if (id == SymbolTable::idNotFound) { // add new identifier to the symbol table id = _symTab.ForceAdd (strSymbol); if (id == SymbolTable::idNotFound) { cerr << "Error: Too many variables\n"; _status = stError; pNode = 0; } } if (id != SymbolTable::idNotFound) pNode = new VarNode (id, _store); } Maximum symbol length might be considered an internal limitation of the Scanner (although one might argue that it is a limitation of the "language" that it recognizes--we’ll actually remove this limitation later). class Scanner { public: // Embedded anonymous enum enum { maxSymLen = 80 }; … }; A constant that is only used within a single code fragment should not, in general, be exposed in the global scope. It can as well be defined within the scope of its usefulness. The compiler will still do inlining of such constants (that is, it will substitute the occurrences of the constant name with its literal value, rather than introducing a separate variable in memory). We have a few such constants that are only used in main int main () { const int maxBuf = 100; const int maxSymbols = 40; char buf [maxBuf]; Status status; SymbolTable symTab (maxSymbols); … }
http://www.relisoft.com/book/tech/2hiding.html
crawl-001
refinedweb
1,658
62.88
Hi,Ian: this is a follow-up to your post "NFS regression? Odd delays andlockups accessing an NFS export" a few weeks ago().I am able to trigger this bug within a few minutes on a customer'smachine (large web hoster, a *lot* of NFS traffic).Symptom: with 2.6.26 (2.6.27.1, too), load goes to 100+, dmesg says"INFO: task migration/2:9 blocked for more than 120 seconds." withvarying task names. Except for the high load average, the machineseems to work.With git bisect, I was finally able to identify the guilty commit,it's not "Ensure we zap only the access and acl caches when settingnew acls" like you guessed, Ian. According to my bisect,6becedbb06072c5741d4057b9facecb4b3143711 is the origin of the problem.e481fcf8563d300e7f8875cae5fdc41941d29de0 (its parent) works well.Glauber: that is your patch "x86: minor adjustments for do_boot_cpu"(). I don't understand this patchwell, and I fail to see a connection with the symptom, but maybesomebody else does...See patch below (applies to 2.6.27.1). So far, it looks like theproblem is solved on the server, no visible side effects.MaxRevert "x86: minor adjustments for do_boot_cpu"According to a bisect, Glauber Costa's patch induced high load and"task ... blocked for more than 120 seconds" messages in dmesg. Thispatch reverts 6becedbb06072c5741d4057b9facecb4b3143711.Signed-off-by: Max Kellermann <mk@cm4all.com>--- arch/x86/kernel/smpboot.c | 21 ++++++++------------- 1 files changed, 8 insertions(+), 13 deletions(-)diff --git a/arch/x86/kernel/smpboot.c b/arch/x86/kernel/smpboot.cindex 7985c5b..789cf84 100644--- a/arch/x86/kernel/smpboot.c+++ b/arch/x86/kernel/smpboot.c@@ -808,7 +808,7 @@ static int __cpuinit do_boot_cpu(int apicid, int cpu) * Returns zero if CPU booted OK, else error code from wakeup_secondary_cpu. */ {- unsigned long boot_error = 0;+ unsigned long boot_error; int timeout; unsigned long start_ip; unsigned short nmi_high = 0, nmi_low = 0;@@ -828,7 +828,11 @@ static int __cpuinit do_boot_cpu(int apicid, int cpu) } #endif - alternatives_smp_switch(1);+ /*+ * Save current MTRR state in case it was changed since early boot+ * (e.g. by the ACPI SMI) to initialize new CPUs with MTRRs in sync:+ */+ mtrr_save_state(); c_idle.idle = get_idle_for_cpu(cpu); @@ -873,6 +877,8 @@ do_rest: /* start_ip had better be page-aligned! */ start_ip = setup_trampoline(); + alternatives_smp_switch(1);+ /* So we see what's up */ printk(KERN_INFO "Booting processor %d/%d ip %lx\n", cpu, apicid, start_ip);@@ -891,11 +897,6 @@ do_rest: store_NMI_vector(&nmi_high, &nmi_low); smpboot_setup_warm_reset_vector(start_ip);- /*- * Be paranoid about clearing APIC errors.- */- apic_write(APIC_ESR, 0);- apic_read(APIC_ESR); } /*@@ -986,12 +987,6 @@ int __cpuinit native; #ifdef CONFIG_X86_32
http://lkml.org/lkml/2008/10/17/147
CC-MAIN-2014-41
refinedweb
418
66.94
Things used in this project Story A Proposed Universal Solution for a Key Las Vegas Infrastructure Problem applicable to cities worldwide. A solution to identify and report city street lights that are not working and need to be repaired. Even in the city of Las Vegas, one of the most technologically advanced metropolis not only in the US but in the world, the reporting of malfunctioning lights is inefficient because it generates a huge data base based on after the facts events (usage records for billing purposes). In addition being that a meter on average controls 10 lights, a specific light on a string may not be identified if the rest continue to work, but definitely affects a part of the route it is designed to serve. The current reporting method is usually by citizen reporting, or worst yet when an accident has happened. Our project is based on the city of LV model but in a more generic and global sense. Las Vegas presents the same issue than any other city, when a street light is out it creates hazards to health and safety of the population such as fear of being assaulted or mugged, increase potential for accidents such as falls or vehicles colliding with pedestrian or other objects on the road, people feeling less secure in their neighborhoods and homes which leads to a decrease on commerce, increase in property and violent crimes, among others. Our technology solves this problem by having a sensor installed on each light bulb which will report on real time when the light malfunctions. The first type of malfunction is when the lights stay on after 8am. The second type of malfunction is when the lights should come on and they don't. At this time the data base does not have a field that would identify this condition as it only contains billing records from the power company to the city. NVEnergy is the power company and they supply the meters. There are 5,000 meters installed which control 52,000 lights, which means that each meter on average controls a string of about 11 lights. Of this lights, 75% or 42,000 are LED and the remaining 10,000 are incandescent, which use more energy and are higher maintenance. Street lighting is a component of the safety framework and composed of regulations and safety infrastructure which makes up one third of the UL Technology safety index. Therefore it can be stated that an improvement in the street lighting infrastructure will cause an improvement in the safety index of a country. The reasons for street lights being out are universal: vandalism and theft of the lights or the copper wiring, wear and tear, weather related outages, and lack of maintenance. The wealthier a community or an area of the city is, the likelihood of getting its lights repaired sooner are much higher than if it is in an area lower socioeconomic status, which tends to increase the social disparities present in a particular society. Our project utilizes the following technology: The GROVE STARING KIT Arduino component to detect when a lights bulb goes out by way of sensors on each light fixture. That information gets transmitted to the Intel NUC Kit gateway which is an intermediary between Arduino and the cloud. Subsequently we use Amazon IOT Alexa to query the data base created in the cloud for lights that are malfunctioning. Real time reporting is applicable to address this hazard. Custom parts and enclosures Schematics Code Code to read the light sensor and create recordC# #include <unistd.h> #include <iostream> #include "grove.h" int main(int argc, char **argv) { //! [Interesting] // Create the light sensor object using AIO pin 0 upm::GroveLight* light = new upm::GroveLight(0); // Read the input and print both the raw value and a rough lux value, // waiting one second between readings while( 1 ) { std::cout << light->name() << " raw value is " << light->raw_value() << ", which is roughly " << light->value() << " lux" << std::endl; sleep(1); } // Delete the light sensor object delete light; //! [Interesting] return 0; } Credits Gregg Reynolds I'm working with Iotivity in C, Java, and Clojure. Mauricio Chamat I enjoy solving problems by creating appropriate solutions and not developing a solution and waiting for a problem to solve. Replications Did you replicate this project? Share it!I made one Love this project? Think it could be improved? Tell us what you think!
https://www.hackster.io/the-ravishers/let-there-be-smart-light-07d0b3
CC-MAIN-2017-13
refinedweb
734
57.3
Factory boy can be used to build dicts Conventionally subclasses of factory.Factory are used to build objects, often Django models that are persisted to some data store. But they can also be used to build plain dicts, which can be useful for building complex dicts in tests. This is done via the Meta.model field which specifies the class of object to create. There’s also a convenient factory.DictFactory class. Here’s an example using factory.Factory subclasses to create a nested dict fixture: import factory class Pet(factory.DictFactory): species = "dog" name = "rover" class Person(factory.DictFactory): name = "barry" age = 41 pet = factory.SubFactory(Pet) has_pet_insurance = False class Meta: # Ensure dict field uses hyphens not underscores. rename = {"has_pet_insurance": "has-pet-insurance"} def test_default_fields(): assert Person() == { "name": "barry", "age": 41, "has-pet-insurance": False, "pet": { "species": "dog", "name": "rover" } } def test_overriding_fields(): assert Person(name="alan", pet__name="lassie") == { "name": "alan", "age": 41, "has-pet-insurance": False, "pet": { "species": "dog", "name": "lassie" } }
https://til.codeinthehole.com/posts/factory-boy-can-be-used-to-build-dicts/
CC-MAIN-2022-05
refinedweb
162
51.04
In this short guide, we will learn how to upload files to the ESP32 SPIFFS (flash file system) using VS Code with PlatformIO IDE. To show the working of the SPIFFS in VS Code, we will create and store a simple .txt file in the filesystem. Recommended Reading: Getting Started with VS Code and PlatformIO IDE for ESP32 and ESP8266 (Windows, macOS, Linux) If you are using Arduino to program ESP32, you can refer to this tutorial: Install ESP32 Filesystem Uploader in Arduino IDE Table of Contents. Key Applications The use of SPIFFS with ESP32 becomes very handy in various applications such as: - Saving mesh and network configuration settings in permanent memory without any SD card. - While using EPS32 as a Bluetooth mesh Node, its provisioning and configuration data must store in permanent memory. - In the case of ESP32 web server, server HTML and CSS files from SPIFFS. - Saving look-up tables to perform the query and retrieve data from. In this project, however, we will keep it simple and store a .txt file in the ESP32’s SPIFFS. This time we will see how to do that in VS Code using PlatformIO IDE. Uploading Files to ESP32 SPIFFS Now let us learn how to upload files to ESP32’s filesystem using VS Code in PlatformIO IDE. Follow the steps in the correct order to successfully store the files. For this article, we will keep it keep and show you how to upload a simple .txt file. You can follow the steps and upload files of different types easily. Creating Data Folder Open VS Code with PlatfromIO IDE and go to the PIO Home page click ‘+New Project.’ Now add the details. Give the name of your project, the type of your development board and the framework. Click the Finish button to create your project. Go to the Explorer tab on the left side where all the folders are specified. Right-click on the name of your project folder and create a new folder. Name this new folder ‘data.’ Make sure to name it ‘data,’ otherwise the file will not upload onto SPIFFS properly. Now click the data folder and add files inside it by right-clicking it and choosing New File. We will upload a .txt file named ‘test.txt.’ Fill in the test.txt file with some sample text as shown below. Press Ctrl + S to save the changes. Make sure that the test.txt file is inside the data folder. You can add more files of various types (.html,.css,.png etc.) inside the data folder. For this project, we will only create a single .txt file. Note: You should place all the files inside the data folder. Otherwise, the SPIFFS library will not be able to read the files. Uploading Filesystem Image After you have created your files inside the data folder click the PlatfromIO icon and head over to the project tasks tab. Under the project tasks, click esp32doit-devkit-v1 or the type of board which you selected for your project. Then go to Platform > Build Filesystem Image. After that click Upload Filesystem Image. In the terminal, you will be able to see the following messages when you click Build Filesystem Image. After that click Upload Filesystem Image. During the upload process if you notice Connecting….____……____…… as highlighted below then press the BOOT button of your ESP32 module and hold it so that the ESP board goes into flashing mode during the upload process. After a few moments, you will receive the success message in the terminal. Note: Make sure that the total size of the data file is within the flash memory size of the ESP module. Otherwise, you will get an error while uploading the files onto SPIFFS. Make sure all the serial monitors are closed for a successful upload. Otherwise, there will be an error indicating ‘Could not open ‘Your_COM_PORT’ Access is denied.’ Close all serial connections to proceed smoothly. Arduino Sketch to check for test.txt file in ESP32 SPIFFS First, go to Explorer > src > main.cpp and open it. Replicate the code given below in that file. #include <Arduino.h> #include "SPIFFS.h" void setup() { Serial.begin(9600); if(!SPIFFS.begin(true)){ Serial.println("An Error has occurred while mounting SPIFFS"); return; } File file = SPIFFS.open("/test.txt"); if(!file){ Serial.println("Failed to open file!"); return; } Serial.println("Content of file:"); while(file.available()){ Serial.write(file.read()); } file.close(); } void loop() { } Remember to replace the name of your .txt file in the line: File file = SPIFFS.open("/test.txt"); In our case the name of our .txt file is test.txt Now press Ctrl + S or go to File > Save to save the main.cpp file. Then go to the PIO icon > Project Tasks > Upload or the Upload icon in the bottom taskbar to upload the program code to the ESP32 module. In the terminal, you will see the following message after a successful upload took place. To view the content of your .txt file click the serial monitor icon in the taskbar. You can view the file content on the serial monitor as shown below. This shows that we have successfully uploaded our test.txt file to ESP32’s filesystem. Conclusion In conclusion, we learned a very handy feature of ESP32 in VS Code with PlatformIO today. Through this short guide now you will be able to save any type of file in the ESP32’s filesystem and easily serve them when required. SPIFFS becomes extremely useful when building ESP32 web servers. All the individual HTML, CSS, and JavaScript files can be uploaded on the filesystem and easily served when building the web servers. We also have an article regarding ESP32 SPIFFS in Arduino IDE which you can access from the link given below: Other ESP32 projects which use SPIFFS: 1 thought on “Upload Files to ESP32 SPIFFS FileSystem with VS Code and PlatformIO IDE” Hello, Great tutorial as usual. For ESP32, Espressif advices to use FAT file system instead of SPIFFS (deprecated), so I configure in platformio.ini board_build.filesystem = ffat and when I try to Build or Upload Filesystem Image by the PlatformIO icon, task fails saying that mkffat is not recognized as a command. How could I solve this? Thanks in advance for any help
https://microcontrollerslab.com/upload-files-esp32-spiffs-vs-code-platformio-ide/
CC-MAIN-2022-33
refinedweb
1,054
75.61
How do I write a program using for loop to average 3 integer test grades? Please help!!!!! I/P : 3 integer test grades O/P: Exam average (float or double) This is a discussion on Need Help on Program Using For Loop within the C++ Programming forums, part of the General Programming Boards category; How do I write a program using for loop to average 3 integer test grades? Please help!!!!! I/P : 3 ... How do I write a program using for loop to average 3 integer test grades? Please help!!!!! I/P : 3 integer test grades O/P: Exam average (float or double) Post what you have done so far. Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream. Is this even close? I'm not sure I quite understand, but I'm trying! Please help! #include <iostream.h> #include <iomanip.h> int main () { int total; //sum of grades int counter; int grade; double average; total=0; counter=0; for (counter=1; counter<=3; counter++) { total=total+grade; counter= counter+1 cout<<"Enter grade, -1 to end:"; cin>>grade; } average= total/counter; cout<<\n "Your exam average is:" <<average; cout<<"\n End of lab"; return 0; } //end of main function > counter=0; This is unecessary, since you're just giving counter another value on the next line anyways. > counter= counter+1 This is also unecessary, since the "counter++" in your for loop will do this. The way you have it now, counter's value is increased by 2 on every pass. > -1 to end There's really no reason to have this in, since you don't deal with what happens if they put in -1. Looks fine, otherwise... for (counter=1; counter<=3; counter++) ============================== with above instructions the loop will stop when counter == 4. Work it out by hand to prove it to yourself. If you start counter at 0 and increment until counter < 3, then the value of counter will (often) equal the number of grades entered when loop is terminated. This is one reason why loop counters frequently start at 0 rather than one. =============================== { total=total+grade; ================================ ask yourself what value grade has the first time through the loop. It is undefined right? The user hasn't had the chance to enter the grade at this point yet, right? Therefore you will be assigning garbage to total the first time through, ang building on garbage each additional loop through. Also, ask yourself what happens to user input the third time through the loop. Will user input be added to total? Nope. Write out a description for yourself as to why that is so. This line is correct in syntax but inappropriate in location. I'll leave it to you to figure out where it should go. ================================= counter= counter+1; ================================= this line should be eliminated as per previous post ================================== cout<<"Enter grade, -1 to end:"; ================================== I actually like the idea here. You are allowing user to terminate the loop early if they have less tha three grades to enter. However, you have to deal with the input of -1 somehow. Here's one way: cin>>grade; if(grade == -1) { break; } I would actually prefer a slightly different (although not necessarily better) approach to this aspect of the program, but the above sequence should allow flexibility for the user. ================================== cin >> grade; } would it be easyer to just have: double a, b, c; for(;;)//just add this if you want this to loop forever, I know unorthodox, but works. { cout <<"please enter your grades"; cin>>a>>b>>c; a = (a+b+c)/3 cout <<"you're GPA is "<<a<<endl; } or you could even add something like if (a > 3.3) cout <<"you're average is an a"; else if (a < 3.3 && > 2.7) cout <<"you have a b"; you get the jist. or do you really have your heart set on a for loop? anyways, hope this helps. Last edited by Dummies102; 02-25-2002 at 05:07 PM. > but(I forget the boolean function for but) There is no "boolean function" for but. You want and, which is &&. Thanks so much for helping! I have to use a for loop. I know it would be much easier the other way. --------------------------------------------------------------------------------- Once I think I know what I'm doing, I'm confused again. I really don't know what I'm doing or why. I'm just trying to write the program. --------------------------------------------------------------------------------- for (counter=1; counter<=3; counter++) So I need to change counter=1 and counter<3 ? I'll try it, but my teacher had that up for an example in class. --------------------------------------------------------------------------------- { total=total+grade; I'm sorry I don't know what I'm doing here. And I still don't quite understand. Any more help on this will greatly be appreciated. Thanks! const int MAX_INPUT = 3; int grade[ MAX_INPUT ]; int total; for( counter = 1; counter <= MAX_INPUT; counter++ ) { cout << "Enter number " << counter << ":\n" cin >> grade[ i ]; total += grade[ i ] } cout << "Average = " << total / MAX_INPUT << endl; thanks, but that might be a bit more advanced.. i'm only in the introductory class..
http://cboard.cprogramming.com/cplusplus-programming/11766-need-help-program-using-loop.html
CC-MAIN-2014-10
refinedweb
851
73.17
Loading rich text file links in a browser from a WPF Navigation Application Previously, I discussed loading a rich text file in a regular WPF Application in this post: Loading a RichTextBox from an RTF file using binding or a RichTextFile control The following use cases must be met: - Load and display a rich text file in read only mode - The links must open inside a browser and not in the application We created a RichTextFile control that inherits RichTextBox and configured it to support binding. Now we are going to use this same object in a WPF Navigation Application. A WPF Navigation Application is going to react differently. Links are going work by default, so the Hyperlink.Click event doesn’t have to be used. However, there is a problem, the links open in the actual application’s window and not in a browser. Lets fix this. Part 2 – Using the RichTextFile class in a WPF Navigation Application Use Case 1 – Loading a rich text file Create a new WPF Application in Visual Studio. Add a Frame element and set the source to RTF.xaml, which we will create next. <Window x: <Grid> <Frame Source="RTF.xaml" /> </Grid> </Window> There is no code behind for this, yet. Create a new WPF Page called RTF.xaml. Add the above RichTextFile object to the project. Add an xmlns reference to our new object. Then add our new object. Notice in our new object that we set IsReadOnly=”True” but we also set IsDocumentEnabled=”True”. This allows for clicking a link even though the document is read only. <Page x: <Grid> <controls:RichTextFile </Grid> </Page> Code Behind using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; namespace RichTextFileTest { /// <summary> /// Interaction logic for RTF.xaml /// </summary> public partial class RTF : Page { public RTF() { InitializeComponent(); Example example = new Example() { File = "File.rtf" }; DataContext = example; } } public class Example { public String File { get; set; } } } Now the first use case is complete, the rich text file is loading into the RichTextFile control and is visible in the application. However, the second use case is incomplete, but not because the links aren’t loading, but because they are not loading in a browser. Instead they are loading inside the Frame element. Use Case 2 – Getting the links to open in a browser Getting the links to open in a browser is not straight forward and it took me quite some time to find an easy solution. Somehow, the link must be open in a browser and then the Navigation event must be canceled. The easiest way to do this is to implement the Nagivating function on the Frame element in our MainWindow. <Window x: <Grid> <Frame Source="RTF.xaml" Navigating="Frame_Navigating"/> </Grid> </Window> Now implement the code behind for the Frame_Navigating method. using System.Diagnostics; using System.Windows; using System.Windows.Controls; namespace RichTextFileTest { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Frame_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e) { Frame frame = sender as Frame; if (frame != null && frame.Source != null) { // See if we are hitting a link using HTTP or HTTPS if (frame.Source.ToString().StartsWith("http://", System.StringComparison.CurrentCultureIgnoreCase) || frame.Source.ToString().StartsWith("https://", System.StringComparison.CurrentCultureIgnoreCase)) { // Open the URL in a browser Process.Start(frame.Source.ToString()); // Cancel the Navigation event e.Cancel = true; } } } } } The links should now be opening in your browser and not in your application. Here is the sample project that demonstrates this. RichTextFileNavigation.zip
https://www.wpfsharp.com/2011/08/02/loading-rich-text-file-links-in-a-browser-from-a-wpf-navigation-application/
CC-MAIN-2019-13
refinedweb
589
50.02
« Return to documentation listing MPI_Win_free - Frees the window object and returns a null handle. #include <mpi.h> int MPI_Win_free(MPI_Win *win) INCLUDE 'mpif.h' MPI_WIN_FREE(WIN, IERROR) INTEGER WIN, IERROR #include <mpi.h> void MPI::Win::Free() win Window object (handle). IERROR Fortran only: Error status (integer). MPI_Win_free frees the window object win and returns a null handle (equal to MPI_WIN_NULL). This collective call is executed by all pro- cesses in the group associated with win. It can be invoked by a process only after it has completed its involvement in RMA communications on window win, that is, the process has called MPI_Win_fence, or called MPI_Win_unlock to match a previous call to MPI_Win_lock. When the call returns, the window memory can be freed._Win_create MPI_Win_fence MPI_Win_unlock
http://icl.cs.utk.edu/open-mpi/doc/v1.2/man3/MPI_Win_free.3.php
CC-MAIN-2014-10
refinedweb
126
59.5
table of contents NAME¶ open, openat— LIBRARY¶Standard C Library (libc, -lc) SYNOPSIS¶ #include <fcntl.h> int open(const char *path, int flags, ...); int openat(int fd, const char *path, int flags, ...); DESCRIPTION¶Theflag). In this case open() and openat() require an additional. RETURN VALUES¶If successful, open() and openat() return a non-negative integer, termed a file descriptor. They return -1 on failure, and set errno to indicate the error. ERRORS¶The named file is opened unless: - [ ENOTDIR] - A component of the path prefix is not a directory. - [ ENAMETOOLONG] - A component of a pathname exceeded 255 characters, or an entire path name exceeded 1023 characters. - [ ENOENT] O_CREAT_TRUNCis specified and write permission is denied. - [ EACCES] O_CREATis specified, the file does not exist, and the directory in which it is to be created does not permit writing. - [ EPERM] O_CREATis specified or O_APPENDis specified and the named file would reside on a read-only file system. - [ EMFILE] - The process has already reached its limit for open file descriptors. - [ ENFILE] - The system file table is full. - [ EMLINK] O_NOFOLLOWwas specified and the target is a symbolic link. - [ ENXIO] - The named file is a character special or block special file, and the device associated with this special file does not exist. - [ ENXIO] O_NONBLOCKis set, the named file is a fifo, O_WRONLYis set, and no process has the file open for reading. - [ EINTR] - The open() operation was interrupted by a signal. - [ EOPNOTSUPP] O_SHLOCKor O_EXLOCKis specified but the underlying file system does not support locking. - [ EOPNOTSUPP] - The named file is a special file mounted through a file system that does not support access to it (e.g. NFS). - [ EWOULDBLOCK] O_NONBLOCKand one of O_SHLOCKor O_EXLOCKis specified and the file is locked. - [ ENOSPC] O_CREATis specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because there is no space left on the file system containing the directory. - [ ENOSPC] O_CREATis specified, the file does not exist, and there are no free inodes on the file system on which the file is being created. - [ EDQUOT] O_CREATis specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because the user's quota of disk blocks on the file system containing the directory has been exhausted. - [ EDQUOT] O_CREAT() system call requests write access. - [ EFAULT] - The path argument points outside the process's allocated address space. - [ EEXIST] O_CREATand O_EXCLwere specified and the file exists. - [ EOPNOTSUPP] - An attempt was made to open a socket (not currently implemented). - [ EINVAL] - An attempt was made to open a descriptor with an illegal combination of O_RDONLY, O_WRONLY, O_RDWRand O_EXEC. - [ EBADF] - The path argument does not specify an absolute path and the fd argument is neither AT_FDCWDnor a valid file descriptor open for searching. - [ ENOTDIR] - The path argument is not an absolute path and fd is neither AT_FDCWDnor a file descriptor associated with a directory. - [ ENOTDIR] O_DIRECTORYis specified and the file is not a directory. - [ ECAPMODE] AT_FDCWDis specified and the process is in capability mode. - [ ECAPMODE] open() was called and the process is in capability mode. - [ ENOTCAPABLE] - path is an absolute path or contained a ".." component leading to a directory outside of the directory hierarchy specified by fd. SEE ALSO¶chmod(2), close(2), dup(2), fexecve(2), fhopen(2), getdtablesize(2), getfh(2), lgetfh(2), lseek(2), read(2), umask(2), write(2), fopen(3), capsicum(4) STANDARDS¶These functions are specified by IEEE Std 1003.1-2008 (“POSIX.1”). FreeBSD sets errno to EMLINK instead of ELOOPas specified by POSIX when O_NOFOLLOWis set in flags and the final component of pathname is a symbolic link to distinguish it from the case of too many symbolic link traversals in one of its non-final components. HISTORY¶The open() function appeared in Version 1 AT&T UNIX. The openat() function was introduced in FreeBSD 8.0.
https://manpages.debian.org/buster/freebsd-manpages/open.2freebsd.en.html
CC-MAIN-2021-04
refinedweb
652
55.44
I decided to try my hand at a custom generic collection class, and started looking into the implementations of the generic collection classes such as List<T> or the interfaces like ICollection<T>. But while what I found as I went along was useful information, ultimately, one question rose above all others as I looked at example after example of simple and complex implementations of CollectionBase or ICollection<T> that at its core just wrapped an ArrayList or List<T> internally, which to me defeats the purpose of implementing a baser class or interface in the first place. If you could write a class that wraps a List<T> successfully, why bother with implementing ICollection or IList if you could just put a List<T> in your class? What if I didn't want to wrap an existing structure that is more advanced than the more primitive interfaces I was considering? What options are there? List<T> ICollection<T> CollectionBase ArrayList ICollection IList Eventually, I ended up with my own collection class, which I think could still be useful even in the age of 3.0 - HashSet<T> is a speedy unique-value list that can beat my collection on Contains checks for unique values, but it relies on being unique and cannot sort, and List<T> is slightly faster than my collection on Sorts, but not by much. Neither one still natively provide a single-value sorted unique-value list. (See Benchmarks near the end for actual numbers.) HashSet<T> Even if it is rendered obsolete by extending a List<T> to add a Unique function, I think it's still good information to know. I had never broken down a collection to this level before, and picked up a few new concepts. The most basic question I started with was simply this: Given a class A, how do you implement A[index]? There was a quick obvious answer of an internal array, but the most obvious drawback to that was the static size, since we obviously will want a dynamic Add option that doesn't cause a recreation of the array on every Add. The less obvious drawback that I saw immediately that caused me to code far too much was that it did exactly what I didn't want, namely it implemented a pre-defined collection class (Array) even if this was a far simpler collection than List<T> and the like. Array The answer that I ended up with is a nested class. A nested class is simply a class that is declared within your class, and in this case, I declared a nested class with a generic type property, and I can carry that generic type value to the nested class in the constructor. In this code, we see both a declaration of a class with a "generic" value type as well as a nested class that carries the same T type. Note that I am implementing zero inheritance, they derive directly from System.Object. T System.Object public class basicList<T> { //basicList constructors //... private class basicItem { private T _data; public T Value { get { return _data; } set { _data = value; } } public basicItem(T t) { _data = t; } } } Note that the nested class is private, but the constructor/property is public - if you had a public nested class, it could be accessed outside the parent class, but since it's private only, the parent class can access it; however, the methods your parent class need to use (including the constructor) must not be private. private public Now, we need a method on the parent basicList class that creates a basicItem, something like this: basicList basicItem public class basicList<T> { public Add(T t) { basicItem newItem = new basicItem(t);} //basicItemClass //... } You are probably saying that's great that we made a basicItem with data, but how do we find anything once we leave Add? Add Answer: we need to implement indexing of some kind. This is probably where people with more common sense or less free time than me decide to implement a List or ArrayList because they're pretty quick to spring to mind when you think to yourself, "What can I use to keep a collection of values and also easily access by index?" But, part of this project was no implementation of another collection class, partially because I want direct access to the data instead of just passing through another collection, and partially because that was the whole point I got started on. List So, with a collection of basicItem objects that contain T data, how can I keep track of them for indexing? The answer is what got me finally going: each basicItem needs a link to another basicItem in the form of a reference property, and we need to keep track of the count of objects, and the parent object needs to keep a reference to one of the objects. This string of references will keep the classes from getting collected as well as provide easy enumeration implementation. For performance reasons, I went with the ability to go forwards or backwards, so I need to keep track of: On construction of a basicItem in a basic Add function, it can know the previous item if it's not the first, but not the next, since in a basic Add, the new item is appended, there is nothing after it. The new basicItem constructor and basicList constructor, and the Add method: public class basicList<T> { private basicItem _firstItem, _lastItem; private int _count; public basicList() { _firstItem = null; _lastItem = null; _count = 0; } public void Add(T t) { basicItem n = new basicItem(t, _lastItem); if (_count == 0) { _firstItem = n; } //store first node else { _lastItem.Next = n; } //not first, put reference to previous last _lastItem = n; _count++; } private class basicItem { //next and previous as from a zero-based perspective private basicItem _prev, _next; private T _data; //properties public basicItem Previous { get { return _prev; } set { _prev = value; } } public basicItem Next { get { return _next; } set { _next = value; } } public T Value { get { return _data; } set { _data = value; } } //constructors public basicItem(T t) : this(t, null) { } public basicItem(T t, basicItem prev) { _prev = prev; _data = t; } } } Now we are getting somewhere! When basicList.Add() is called with a value, it first calls the basicItem constructor with the value given and a link to _lastItem to store in Previous. Note that if it is the first item in the collection, it gets a null reference from the basicList constructor, and if it is not, the previous _lastItem gets a Next link to the new basicItem. Items placed by Add are appended by default, so the item created is always the _lastItem. _count goes up by 1, and if it is the first item, it is also placed in _firstItem. This system also has the advantage of not hard-coding an index in the basicItem, but rather by letting it be relative, we can easily move/remove/add at will by simply changing the links of the basicItem to their new orientation. basicList.Add() _lastItem _count _firstItem Now to implement indexing! With what we have here, we know _firstItem and its index is always 0, and we have _lastItem and we know its index is always _count - 1. Two things we can implement here - one is a generic IEnumerator<T> to support foreach operations, and a this[int index] to allow direct access. Since we are implementing a IEnumerator<T>, our parent class can also inherit from IENumerable<T> for no more cost than simply pointing its implementation of IEnumerator<T> to the one we are creating. Incidentally, this is the only inheritance the basicList class will ever get - it's probably not adding much, but I thought I might as well. _count - 1 IEnumerator<T> foreach this[int index] IENumerable<T> New code: public class basicList<T> : IEnumerable<T> { //snip unchanged basicList constructor //and Add method and basicItem class public IEnumerator<T> GetEnumerator() { basicItem current = _lastItem; while (current != null) { yield return current.Value; current = current.Previous; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } //IENumerable<T> implementation public T this[int index] { get { int curIndex = 0; basicItem curItem = _firstItem; while(curIndex < index) { curItem = _firstItem.Next; curIndex++; } if(curItem != null) { return curItem.Value;} return default(T); } set { int curIndex = 0; basicItem curItem = _firstItem; while(curIndex < index) { curItem = _firstItem.Next; curIndex++; } if(curItem != null) { curItem.Value = value;} } } } We now have a fully functional generic list! We can Add an item, foreach the collection, or get/set a value directly by index by simply going through our collection from the beginning (or end, more on this later). OK, so a list we can append an item to, enumerate, and access by index is the most basic of lists. Surely, we can implement some other functions while still retaining zero inheritance (besides the freebie) and staying completely generic? Of course, we can! Basic list functions - zero inheritance and fully generic: AddRange AddAt RemoveAt Clear Contains I'm not going to rewrite the code for AddAt/RemoveAt in this section, since I implemented some performance enhancement I haven't gotten to yet - but basically, because the indexes are not hard-coded, all you have to do is just re-hook the links. In the case of RemoveAt, you grab the basicItem at the index, then link the Previous and Next directly to each other, then either null the item (for actual removal) or just re-hook it wherever you want to go in the case of an uproot and replant. In the case of AddAt, you grab the items before and after, and hook them to the new item, and then hook the new item to the before and after. In both cases, the first/last need to be checked for replacement, and the count needs to be updated. AddRange couldn't be easier, just take a T[] and loop through them, calling Add on each value. For Clear, I actually hooked into the constructor to call, but it nulls everything, resets values to 0, and parses through the collection removing links just to make sure we don't have a long chain floating out in the abyss that the collection doesn't clean up. We can implement Contains at this point, though we are limited to the Object inherited Equals. T[] Object Equals public class basicList<T> : IEnumerable<T> { public basicList() { this.Clear(); } //moved to Clear function public void AddRange(T[] t) { for (int i = 0; i < t.Length; i++) { Add(t[i]); } } public bool Contains(T t) { foreach (T tVal in this) { if (tVal.Equals(t)) { return true; } } return false; } public void Clear() { if (_firstItem != null) { basicItem curItem = _firstItem; while (curItem.Next != null) { curItem = curItem.Next; basicItem prevItem = curItem.Previous; prevItem = null; } } _firstItem = null; _lastItem = null; _count = 0; } } This is about as far as we can possibly get with an unrestricted generic Object-derived no-inherit list. We only have the basic Object functions without limiting T. At this point, if we want more, we can either subclass basicList, or just use the minimal restriction on T to get the rest of the functions we want. I would go directly to the part where we implement sorting and the extended functions, but unfortunately, that is pretty complex, and uses what I'm about to describe here. Rather than rewriting entire code segments to make them make sense without explaining this system, I thought I would explain it first. What I implemented is what I call the pointer system. This is the main reason my list class can compete (and beat some) of the predefined collection classes. Now I know what pointer means, and I'm not really using pointers. I'm using object references, but for my own clarity, I call them pointers, since by grabbing one, you are essentially grabbing the object it's referring to. Recall that _firstNode and _lastNode are essentially references to the first and last nodes, whose positions we know as 0 and (Count - 1), respectively. What this system does is keep more of these references, except instead of being anchored to the first and last, they are free to be wherever within those bounds. Necessarily, this system is pretty complex to keep track of, but it is vital to actually perform anything other than appending items. Remember that at this stage, to get index[y], we have to start at 0 and iterate 0 -> y. Some performance enhancement can be had by determining if y is closer to the end or start and going from there, and that was my initial implementation. But what happens when we have to go through a collection one by one and flip back and forth between nodes, such as an operation like sorting requires? I'll tell you - in small collections, it's not very noticeable, but in large ones, it's extremely noticeable, as to get to the middle of the collection, it always has to start from the start or end. _firstNode _lastNode In my implementation, I allow the user to optionally set the number of pointers used; in large collections, larger numbers will help somewhat, although all my tests were done with the default number, which is 4. Since this article is getting long already, I'll briefly explain the implementation which you can see in the source code. basicItem[] _curPointers int[] _curPointerIndices _curPointers[] _curPointerIndices[] basicList[index] _getClosestPointer _getNodeAt _createNewPointer _calcPointerWorthLeast _curPointers _curPointerIndices _updatePointer _movePointers _getPointerIndex Now that I've explained that a bit, let's move on to the final part where we set up a Sort and reforged Contains, and enable auto-sorting on Add. First off, to do any kind of comparison other than the basic Object-derived Equals(obj), we need to finally put a little limitation on our T, namely asking it to implement IComparable<T> by tacking on where T:Comparable<T> to the class name. I chose to augment the current list, rather than stop the class here and inherit it and then tack on the requested inheritance to T, because IComparable<T> is incredibly easy to implement. It has only one method - CompareTo, which given t1.CompareTo(obj t2), returns -1 if t1 < t2, 0 if t1 = t2, 1 if t1 > t2. I usually implement that myself in custom classes with a redirect to a type-specific comparison and avoid the normal object kludge. Sort Equals(obj) IComparable<T> where T:Comparable<T> CompareTo t1.CompareTo(obj t2) t1 t2 Now that we can guarantee T is IComparable, we can update Contains and implement sorting. A basic sort routine would be nice, but since I'm me, it's not basic. Before we get to that, though, here is the updated Contains method; recall that before this, we could only use Object.Equals; this is much faster: IComparable Object.Equals public bool Contains(T t) { //new and improved foreach (T tVal in this) { if (tVal.CompareTo(t) == 0) { return true; } } return false; } It's now using CompareTo == 0. One other thing that you could do is a quick compare of Object.getHashCode first since that's quicker than CompareTo (which is still faster than Equals). But keep in mind, getHashCode isn't a bulletproof comparison operator, and if hash codes are equal, that doesn't necessarily mean the two objects are equal, thus the second check with CompareTo. I tested this with integers, and it sped up value checking considerably, but then when I used strings, it slowed it down- my guess is hash codes are equal more often, or it takes longer to calculate them with strings, and since this is intended to be a generic List with as few restrictions as possible, I didn't want to set up a special string handler, a special integer handler etc., and so set it back to the most reliable comparison. If I was going to use it with strings, I would just override the comparison in a new string-targeted class inheriting basicList. CompareTo == 0 Object.getHashCode getHashCode On to sorting! At its heart, sorting only relies on a few things - that you have a reliable method to compare two values, which we do now with CompareTo, and that you can keep track of where you are while you're flipping around. The latter is much more complex with the pointer system I described above, but it's pretty impressive on a sort op. The sorting I used here is a combination of several parts. I'll post the actual sort handling code, although most of it won't make a ton of sense since we didn't go into that much code on the pointer system and the sort function itself calls another function which calls another. Nonetheless, here is the current _handleSortCall (the public Sort looks at _autosort, and if it's already autosorted, it ignores the call). _handleSortCall _autosort private void _handleSortCall() { //private method allows public sort to decide if //it wants to actually sort or not and permits //autosort property handler to bypass basicItem nEnd = _firstItem, nStart = _firstItem; int posEnd = 0; //start is always 0 //working index so we don't have to enumerate //every one in the sort op function to place it int workingIndex = 0; while (nEnd.Next != null) {//start at the 2nd node and work until there are no more nodes basicItem thisNode = nEnd.Next; workingIndex++; //first check to see if it even needs to be moved //since we are moving forward, we just need //to make sure the previous is worth less if (thisNode.Value.CompareTo(thisNode.Previous.Value) < 0) { //remove before looking so we don't find the same value _removeNodeAtIndex(workingIndex, ref thisNode); int newIndex = _findProperIndexByValue(thisNode.Value, 0); _addNodeAtIndex(newIndex, ref thisNode); posEnd++; workingIndex++; } else {//sort not necessary nEnd = thisNode; posEnd++; } } } Nothing is passed to it since this is the basic sort call. The next more specific function is _findProperIndexByValue, which, given a value, figures out the first index where the next value is greater, basically an ascending sort finder. To do this, it creates up to 10 zones, and checks the starting value one at a time, and then recurses, narrows the zones, and repeats until it has less than 20 possibilities, at which point, it calls another function _findFirstBiggerValueIndex, whose function you can probably guess. The functions _removeNodeAtIndex and _addNodeAtIndex are exactly what you would think they are, the workhorses behind the AddAt and RemoveAt functions as well as absolutely vital for sort op since we are essentially plucking one node from its home and placing it somewhere else. _findProperIndexByValue _findFirstBiggerValueIndex _removeNodeAtIndex _addNodeAtIndex Since we are starting at the beginning and moving forward, any value behind the previous work node is guaranteed to be of lower or equal value than the current node, meaning that for each node we move forward, we only have to check if the value is larger than the last, and if it is, we can keep on moving, since a gap will be covered by later nodes being moved back if such a gap exists. If you've read this far, I am quite proud of you. This is far, far longer than I anticipated it being, and I even started cutting it short once we got into the complex stuff. I do have a slight hope that somebody will find this useful despite there being obvious alternatives. There is a certain pride in building something from scratch that can compete with the established kings on nearly even ground. If not, it was a great brain exercise, hopefully for both of us. I was curious how my little experiment stacked up against the big dogs, so I did an experiment using a 500K int collection. I also did a 10K string collection, but the results were so similar across the board I scrapped it until I felt good about this one. Only thing I will say about the strings is that my unsorted list's Add time was exactly identical to all the others, and its sort time was exactly the same as List<string> and ArrayList, so I'm not just hiding bad results. int string List<string> Code used for benchmark (in the code, plus two short verifications that the last 50 and first 50 are correct): for (int x = 500000; x > 0; x--) { list.Add(x); } list.Sort(); for (int x = 500000; x > 0; x--) { if (!list.Contains(x)) { list.Add(x, null); } } I wrapped a little timer function around each of these to provide the milliseconds elapsed, and here are the results: basicList !_autoSort basicList _autoSort List<int> Hashset Hashtable(int, null) SortedList<int, object> added (int, null) Dictionary<int, object> added (int, null) SortedDictionary<int, object> added (int, null) I did do the testing in 3.0, as you can see with the HashSet, but downgraded the assembly to 2.0, since it doesn't need more than that. SortedList couldn't even make it out of the gate, funnily enough. The unsorted list was beaten in both Add and Sort by the generic List, but as you can see, managed to process 10x as many Contains, and the sort time was much better than ArrayList. The autoSorted basicList did 50% more Contains in 10 seconds, but still not good enough for me to implement a unique function just yet. If I can get that down to Dictionary sort times, then I finally have completely customizable competitive unique-value auto-sorted Set that is on equal grounds with the predefined ones. In my opinion, the non-unique unsorted and sorted are on pretty equal footing with the others. But I am biased! HashSet SortedList autoSorted Dictionary Currently (as of initial writing), there is also a unique attribute/public property/handler method in the class, which is commented out. You could implement it, it would require only adding another condition to the Add/AddAt/AddRange for unique values. The reason I haven't implemented it is not difficulty, but because I am unsatisfied with the performance of the Contains check. Since Unique would require a hit on the Contains check for every single Add, being satisfied is completely necessary for me. But, of course, I am benchmarking with 500K collections, and most applications would probably be fine. Hope you found this as interesting an exercise as I did. But even a fraction is good enough for me to feel good about writing it! Please feel free to let me know about bugs you find, I did test it pretty thoroughly, but I'm sure I didn't find everything. As a footnote, if you are used to the normal ///writeup on every function, I apologize - I only commented where I felt necessary, and I do not like paging through a million pages of mostly comments. If, however, this gets some downloads, and it is requested, I can update it with that. I have yet to see if anyone is even interested in downloading the actual code, the interest for me was the concept. ///write.
https://www.codeproject.com/Articles/64120/Extended-Generic-Collection-From-Absolute-Zero?fid=1563759&df=90&mpp=10&sort=Position&spc=None&tid=3405134
CC-MAIN-2017-43
refinedweb
3,829
55.78
I know this seems like it should be very simple. and it should be. However I can't figure out how to do it in IntelliJ.. So I have my main class that creates a new instance of the gui using this code: gui mainGui = new gui(); I would think this should be all I need, but the gui never shows up.. I have the gui built(the layout anyways, I don't have any listeners yet) and here is the bound class code: package client; import javax.swing.*; public class gui { private JPanel mainPanel; private JTextField textField1; private JTextArea textArea1; private JButton sendButton; public static void main(String[] args) { JFrame frame = new JFrame("gui"); frame.setContentPane(new gui().mainPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } } So I can't figure out why it doesn't display the gui, any help is appreciated Can you attach related .form file? Thank you, Alexander. Do you have any exceptions displayed in the console when you try to runn the app? And,by the way, doublechek your fields are correctly wired to components (see attached screenshot).
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206178789-Displaying-a-GUI
CC-MAIN-2020-05
refinedweb
186
62.88
This guide describes how to use the Service Bus relay service. The samples are written in C# and use the Windows Communication Foundation (WCF) API with extensions contained in the Service Bus assembly that is part of the Microsoft Azure .NET SDK. For more information about the Service Bus relay, see the Next steps section. To complete this tutorial, you need an Azure account. You can activate your MSDN subscriber benefits or sign up for a free trial.. The Service Bus relay allows allows you to securely control who can access these services at a fine-grained level. It provides a powerful and secure way to expose application functionality and data from your existing enterprise solutions and take advantage of it from the cloud. This how-to guide demonstrates how to use the Service Bus relay to create a WCF web service, exposed using a TCP channel binding, that implements a secure conversation between two parties. To begin using the Service Bus relay in Azure, you must first create a service namespace. A then appears in the Management Portal and takes a moment to activate. Wait until the status is Active before continuing. In order to perform management operations, such as creating a relay connection, on the new namespace, you must configure the Shared Access Signature (SAS) authorization rule for the namespace. For more information about SAS, see Shared Access Signature Authentication with Service Bus. In the left navigation pane, click the Service Bus node, to display the list of available namespaces: Double click the name of the namespace you just created from the list shown: Click the Configure tab at the top of the page. When a Service Bus namespace is provisioned, a SharedAccessAuthorizationRule, with KeyName set to RootManageSharedAccessKey, is created by default. This page displays that key, as well as the primary and secondary keys for the default rule. The Service Bus NuGet package is the easiest way to get the Service Bus API and to configure your application with all of the Service Bus dependencies.. To install the NuGet package in your application, do the following: Search for "Service Bus" and select the Microsoft Azure Service Bus item. Click Install to complete the installation, then close this dialog. the steps below, complete the following procedure to set up your environment: First, create the service itself. Any WCF service consists of at least three distinct parts: as explained above into the Main function of the "Service" application, you will have a functional service. If you want your service to listen exclusively on Service Bus, remove the local endpoint declaration. You can also configure the host using the App.config file. The service hosting code in this case is as follows: ServiceHost sh = new ServiceHost(typeof(ProblemSolver)); sh.Open(); Console.WriteLine("Press ENTER to close"); Console.ReadLine(); sh.Close(); The endpoint definitions move into the App.config file. Note that the NuGet package has already added a range of definitions to the App.config file, which are the required configuration extensions for Service Bus. The following code snippet, which is the exact equivalent of the previous code snippet, should appear directly beneath the system.serviceModel element. This snippet example below will call the service and print "9." You can run the client and server on different machines, even across networks, and the communication will still work. The client code can also run in the cloud or locally. You can also configure the client using the App.config file. The client code for this is as follows: var cf = new ChannelFactory<IProblemSolverChannel>("solver"); using (var ch = cf.CreateChannel()) { Console.WriteLine(ch.AddNumbers(4, 5)); } The endpoint definitions move into the App.config file. The following code snippet,> > Now that you've learned the basics of the Service Bus relay service, follow these links to learn more.
https://azure.microsoft.com/en-us/documentation/articles/service-bus-dotnet-how-to-use-relay/
CC-MAIN-2015-35
refinedweb
636
54.22
If I define a class method with a keyword argument thus: class foo(object): def foodo(thing=None, thong='not underwear'): print thing if thing else "nothing" print 'a thong is',thong TypeError myfoo = foo() myfoo.foodo(thing="something") ... TypeError: foodo() got multiple values for keyword argument 'thing' The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled self. If the class is declared thus: class foo(object): def foodo(self, thing=None, thong='not underwear'): print thing if thing else "nothing" print 'a thong is',thong it behaves as expected. Explanation: Without self as the first parameter, when myfoo.foodo(thing="something") is executed, the foodo method is called with arguments (myfoo, thing="something"). The instance myfoo is then assigned to thing (since thing is the first declared parameter), but python also attempts to assign "something" to thing, hence the Exception. To demonstrate, try running this with the original code: myfoo.foodo("something") print print myfoo You'll output like: <__main__.foo object at 0x321c290> a thong is something <__main__.foo object at 0x321c290> You can see that 'thing' has been assigned a reference to the instance 'myfoo' of the class 'foo'. This section of the docs explains how function arguments work a bit more.
https://codedump.io/share/UDoo4n7nx56l/1/class-method-generates-quottypeerror--got-multiple-values-for-keyword-argument-quot
CC-MAIN-2017-39
refinedweb
225
61.16
So here's the issue: Our share is currently as 15 TB and reaching MAX size for a Celerra File System. I'm the lucky one that will migrate/replicate this data over to our CX4-960 that is now connected to the same NAS Gateway. Can I create X amount of File Systems such as: Images1 Images2 Images3 Images4 Each @ 10 TB Add then together to form a 40 TB File System? Add the end of the day I only want to access two shares. Will this setup stripe my data across all file systems? Or am I interpreting Nested File Systems incorrectly. I'm picturing Nested File Systems as Meta-LUNs. Thanks for all the support, Damian Solved! Go to Solution. Forgive me for asking FMA? Rainfinity FMA. It sits between the end users and the Celerra, and virtualizes the namespace. One of its features is what you described, nested file systems. Others are replication, migration, facilitating archiving, etc. EMC (Rainfinity) File Management Appliance you could use it to move large files that weren't used in the last xx days to another Celerra file system (or Centera or Data Domain or Atmos cloud storage or ...) replacing them with a 8kB stub that looks and works transparently to the client just like before. In effect keeping your existing fs and share at 15TB but enabling you to make much much more capacity available. kinda like an HSM system take a look at the white papers on Powerlink and talk to your local sales team. Rainer NMFS An NMFS allows you to manage a collection of file systems — Component file systems as a single file system. CIFS and NFS clients see component file systems as a single share or single export. File system capacity is managed independently for each component file system. This means that you can increase the total capacity of the NMFS by extending an existing component file system or by adding new component file systems. The number of NMFS or component file systems is limited only to the number of file systems allowed on a Data Mover. Hard links (NFS), renames, and simple moves are not possible from one component file system to another. Please refer to the attached document. - Sebby Robles. Hi dynamox FMA is currently just archiving (the virtualization / migration / namespace was GFV/FVA/FNA which I think are no longer actively sold) whether you can use NMFS really depends on your application and the structure of you data it would have to be able to use multiple subdir's where each subdir is max 16TB and also be clever enough to distribute the data across them alias23122 != dynamox sorry alias23122 != dynamox
https://www.dell.com/community/Celerra/Nested-File-System-Pros-and-Cons-Going-Beyond-16TB/m-p/6775209
CC-MAIN-2019-39
refinedweb
448
62.88
Using _set_new_handler In some circumstances, corrective action can be taken during memory allocation and the request can be fulfilled. To gain control when the global operator new function fails, use the _set_new_handler function (defined in NEW.H) as follows: #include <stdio.h> #include <new.h> // Define a function to be called if new fails to allocate memory. int MyNewHandler( size_t size ) { clog << "Allocation failed. Coalescing heap." << endl; // Call a fictitious function to recover some heap space. return CoalesceHeap(); } void main() { // Set the failure handler for new to be MyNewHandler. _set_new_handler( MyNewHandler ); int *pi = new int[BIG_NUMBER]; } In the preceding example, the first statement in main sets the new handler to MyNewHandler. The second statement tries to allocate a large block of memory using the new operator.. MyNewHandler prints a warning message and takes corrective action. If MyNewHandler returns a nonzero value, the new operator retries the allocation. When MyNewHandler returns a 0 the new operator stops trying and returns a zero value to the program. The _set_new_handler function returns the address of the previous new handler. Therefore, if a new handler needs to be installed for a short time, the previous new handler can be reinstalled using code such as the following: #include <new.h> ... _PNH old_handler = _set_new_handler( MyNewHandler ); // Code that requires MyNewHandler. ... // Reinstall previous new handler. _set_new_handler( old_handler ); A call to _set_new_handler with an argument of 0 causes the new handler to be removed. There is no default new handler. The new handler you specify can have any name, but it must be a function returning type int (nonzero indicates the new handler succeeded, and zero indicates that it failed). If a user-defined operator new is provided, the new handler functions are not automatically called on failure. The prototype for _set_new_handler and the type _PNH is defined in NEW.H: _PNH _set_new_handler( _PNH ); The type _PNH is a pointer to a function that returns type int and takes a single argument of type size_t.
https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-6.0/aa278270(v=vs.60)?redirectedfrom=MSDN
CC-MAIN-2019-51
refinedweb
326
57.37
C# Corner In Part 1, VSM columnist Eric Vogel covered the basics of the Reactive Extensions (Rx) library. In this installment he explores how to observe asynchronous methods, tasks and events, as well as how to compose observable sequences using LINQ. Read the rest of the series: Part 1 | Part 2 | Part 3 In Part 1 of this series, I covered the basics of the Reactive Extensions (Rx) library. In this installment I explore how to observe asynchronous methods, tasks and events, as well as how to compose observable sequences using LINQ. Observing an Asynchronous Method Rx includes an extension method name FromAsynchPattern that can convert an asynchronous method that uses the Asynchronous Programming Model (APM) pattern to an IObservable. A few likely scenarios would be retrieving data from a Web service or reading or writing to a stream asynchronously. Let's look at an example for the former. We'll be calling the Bing Translation Service to translate a piece of text using a generated asynchronous proxy method. To get started, create a new C# Console Application and add a reference to System.Reactive. Next add a service reference to. Make sure to generate asynchronous operations. You can do this by clicking on the Advanced button on the Add Service Reference and checking the "Generate asynchronous operations" checkbox. Next we setup the parameters for our web service method call. string appId = "88E025E2D1E4C4CD930DD6C31AB82E3C49552CBB"; string text = "Hello"; string fromLanguage = "en"; string toLanguage = "fr"; string contentType = "text/plain"; string category = "general"; Then we construct our translation service proxy. var proxy = new BingTranslatorService.LanguageServiceClient(); After that we create a wrapper around the BeginTranslate and EndTranslate APM service methods. The FromAsychPattern needs to know the method parameters as well as the return type of the method that is to be the wrapper -- in our case the Translate method takes six strings and returns a string. The created getTranslation method will be called by passing all of the Translate method parameters and will return an IObservable<string>. An easy way to get the correct method signature is to use IntelliSense on the generated synchronous version of the proxy method. var getTranslation = Observable.FromAsyncPattern<string, string, string, string, string, string, string>(proxy.BeginTranslate, proxy.EndTranslate); Now we call the IObservable<string> from the getTranslation method that will push our translated result. var result = getTranslation(appId, text, fromLanguage, toLanguage, contentType, category); Lastly, we subscribe to the result Observable and output the translated version of the text. If an error occurs we output the exception message. To increase code clarity I opted to use named parameters to call out the onNext and onError handlers. Named parameters have been in VB.NET since its inception but was just recently added to C#. result.Subscribe( onNext: translatedText => Console.WriteLine(translatedText), onError: ex => Console.WriteLine(ex.Message)); Observing a Task<T> Rx adds a ToObservable<T> extension method to Task<T> that allows converting from a Task<T> to an IObservable<T>. An ideal case for using ToObservable is if you have multiple Tasks that have results that are to be composed. For example if you have two long running computations that can be computed in parallel that are later integrated. First we import the System.Reactive, System.Reactvie.Linq, System.Threading.Tasks, and System.Reactive.Threading.Tasks namespaces. using System.Reactive.Linq; using System.Reactive; using System.Threading.Tasks; using System.Reactive.Threading.Tasks; Then we create a Task<double> for each computation. double angle = 30; Task<double> tCos = Task.Factory.StartNew<double>(() => Math.Cos(angle)); Task<double> tSin = Task.Factory.StartNew<double>(() => Math.Sin(angle)); Next we convert each Task to an IObserable<double> and create a new IObservable<double> that is the product of each executed task. var result = from x in tCos.ToObservable() from y in tSin.ToObservable() select x * y; result.Subscribe(x => Console.WriteLine(x)); Observing a Composed Event The classic example of a composed event is drag and drop. We would like to observe when a user is holding down a mouse button over an element and moving the mouse. The event should stop when the user releases the mouse button. We can compose a drag and drop event by joining three event sources, MouseDown, MouseMove and MouseUp. Our composite event will capture the position of an element while the user is clicking down on it. We'll create a re-usable function that will allow any control to be dragged and dropped. To get started, create a new WPF or Silverlight C# Application and update your MainWindow.xaml file to include the following markup. <Canvas> <Label Content="Drag Me" Height="28" HorizontalAlignment="Left" Margin="0,0,0,0" Name="lblDragMe" Background="Black" Foreground="White" VerticalAlignment="Top" Canvas. </Canvas> The default Grid has been replaced with a Canvas that will be used to reposition the label. Next we create our re-usable DragNDrop function, which will allow us to observe a drop position for any Control. private IObservable<Point> DragNDrop(Control elem) { First we create an observable collection of mouse down positions. var mouseDownPos = from evt in Observable.FromEvent<MouseButtonEventArgs>( ev => elem.MouseDown += (s, e) => ev(e), ev => elem.MouseDown -= (s, e) => ev(e)) select evt.GetPosition(elem); Next we create an observable collection of mouse move positions. var mouseMovePos = from evt in Observable.FromEvent<MouseEventArgs>( ev => elem.MouseMove += (s, e) => ev(e), ev => elem.MouseMove -= (s, e) => ev(e)) select evt.GetPosition(this); Then we create an observable collection to capture mouse up events. var mouseMovePos = from evt in Observable.FromEvent<MouseEventArgs>( ev => this.MouseMove += (s, e) => ev(e), ev => this.MouseMove -= (s, e) => ev(e)) select evt.GetPosition(this); Next we compose an event that pushes the drop position for the element. var dropPos = from elemOffset in mouseDownPos from pos in mouseMovePos.TakeUntil(mouseUp) select new Point { X = pos.X - elemOffset.X, Y = pos.Y - elemOffset.Y }; return dropPos; } Lastly we subscribe to the event and update the position of the element we would like to drag and drop. DragNDrop(lblDragMe).Subscribe(dropPos => { Canvas.SetLeft(lblDragMe, dropPos.X); Canvas.SetTop(lblDragMe, dropPos.Y); }); Conclusion Now that you know how to both call an asynchronous method using Rx, as well as how to how to compose observable sequences, you can start to see the power of Rx . Stay tuned for the next and final installment, where I will show how to pull together what we learned so far to create a truly reactive application. All code examples are included in the code drop on the top of the page. Reactive Extensions: Just What the Doctor Ordered (Part 1) Reactive Extensions (Part 2) Reactive Extensions (Part 3).
https://visualstudiomagazine.com/articles/2011/06/23/wccsp_reactive-extensions-part-2.aspx
CC-MAIN-2018-39
refinedweb
1,103
50.33
Dear Mike, Congratulations on the first four issues of Overload, I would like to add a couple of comments to your answers in the last two issues (in a spirit of .pedantry only). In Issue 3 P34 Q4 you appear to have overcomplicated the solution with conditional compilation! Simply declare the const array as extern, declare the class using the const array name as the default argument and define the const array in the source file as for any initialised data: hello.hpp: extern const char name[]; void print( const char str[] = name ); hello.cpp: #include "extconst.hpp" #include <iostream.h) const char name[] = {"Hello World"}; void print( const char str[] ) { cout << str; } void main() { print(); } In issue 4 p44 Q10 you say “… if polymorphic member function is called, only the base member function will be called”. I’m sure it was just a slip of the tongue but in fact it will be the constructors own version of the function that is called, whether it happens to be the base class or not. Interestingly, although the virtual calling mechanism is supposed to be turned off, the virtual method tables are still used to call virtual functions. The way it works is that as each base object is constructed, the virtual method pointer is set to the table for that class, immediately prior to the body of the constructor being executed. This means that the method table will contain the addresses of the functions that would apply to an instance of the class of the constructor in use. This means that it isn’t possible to subvert this behaviour - even calling the functions via a base pointer in another function will only get the same method table. Interestingly it’s possible to call a pure virtual function this way without the compiler ever realising it - you’ll find out at run-time of course! Adrian Fagg Thank’s for the corrections and information. Mike Toms.
https://accu.org/index.php/journals/1767
CC-MAIN-2019-22
refinedweb
325
57.1
! If you're using the same modem and internet connection for all 6 computers, then all those computers will have the same internet IP address as seen by whatismyip.com. To see the individual addresses of the computer WITHIN the local network, open CMD and type "ipconfig" - that'll return (within the list of information) the IP address of the computer in the local network. To see what IP addresses have been asigned by your router to each machine go to your routers installation page and you should find the list under 'Attached Devices'. hen you type what's my ip into google it displays your public IP. That is, the IP that other internet users in the world see your home network as. That IP is different from your router-assigned IP. That IP is one that your router gives a computer when it connects to the router. You can find out the individual router-assigned IP's of your devices by 1. typing "whats my IP" into Google 2. It should come up with a black line of text saying something like "Your public IP address is ***.***.***.*" 3. Your IP will be bold numbers. 4. Next copy and paste the bold numbers into your URL Bar or Address bar. 5. Then it should come up with your routers config page. 6. From here click on the links until you get to each individual computers info page. By the way why do you ask this question? If it is something to do with setting up a sever I can provide more detailed info. If you are worried about a fault in your network do not worry, everything is working perfectly. Make sure when you do assign IP addresses, that no two are the same because one of the machines will now work right when trying to connect the two. I have learned from experience when trying to mod and original Xbox. Before you try to assign different IP addresses to your computers, go on each computer and hold the windows logo button and press r. Type in "cmd" without the quotation marks ("). Then type in ipconfig in the cmd window. It will give you a list of adapters, the one that will tell you the machine's IP address should be labeled "Wireless LAN adapter Wireless Network Connection" if your computer is hooked up to your network using a Wireless LAN network adapter. If it is connected by an ethernet cable, or a wired connection, it will be labeled, "Ethernet adapter local area connection". The machines IP address will be labeled, "IPv4 address". If they are all different after you do this to each device, than it is not necessary to assign different IP addresses to each machine. Emily, to elaborate on Jan's answer, your computers actually have Two IP addresses. As far as the internet is concerned, it only "sees" your router, and that is the IP address of all your computers. WITHIN the home, each machine is allocated a different PRIVATE IP ADDRESS by your router. The conversion between the two is done by a function called NAT ("Network Address Translation") in the router. You can see the local addresses by bringing up the command line on each PC and typing IPCONFIG (followed by [Enter]). On most routers, the addresses start with 192.168 although there are also ranges starting with 10 and 224. This is how the system is meant to work, and the main reason is that there aren't enough IP addresses available for all networked devices in the world. If there is a specific reason why your PCs must have separate addresses, you'll need to ask your ISP to supply you with multiple static addresses, and this will cost you money and require some configuration of your router. If all 6 computers can access the internet at once, you must have a router using the IP address from your ISP that acts as a DHPC server and assigns a static internal IP address to each computer. To check in Win 7, click on Lan icon in task bar then Open Network and Sharing Center/ Local Area Connection/Details.... Note IPv4 Address. please refer the following document Static IP addresses The IP-Adress you get on "what is my ip" is the public IP address of your modem, not the (internal) one assigned to each of your computers. To have each computer with a public IP address you first need to order static public IP addresses of your service provider. Fees may apply and if it's a private use product you most likely have to switch to a more expensive business plan. Once that is done your service provider should be able to help you with the setup but in general the router/modem needs to be capable to assign or route those IP's to your computers.
https://www.makeuseof.com/answers/how-can-i-assign-different-ip-addresses-to-different-machines-on-my-network/
CC-MAIN-2018-09
refinedweb
817
69.11
The controller is at the center of an ASP.NET MVC application. Every single request, except those directed at static files, are managed by a controller. Controllers are, for this reason, subject to strict rules and conventions: For example, a controller class is expected to have a Controller suffix in the name, and also the namespace it belongs might be under-conditioned to some extent. A controller must inherit from a given base class—the Controller class—or some other class that in turn inherits from Controller. Interestingly, some of these constraints are being released in the ASP.NET Core. In ASP.NET Core, for example, a controller can be a plain-old C# class (POCO) with only a few indirect—but still necessary—connections to the ASP.NET infrastructure. In this article, I’ll go through a few little-explored aspects of ASP.NET controller classes, across classic ASP.NET MVC and ASP.NET Core. I’ll touch on a range of topics including POCO controllers in ASP.NET Core, ASP.NET controller factories and localizable routes ASP.NET Core POCO Controllers The most common way to create a valid controller class that the system can easily discover is to give the class name the suffix “Controller” and inheriting it from the aforementioned Controller base class. This means that the corresponding class of a controller called ‘Home’ will be the HomeController class. If such a class exists, the system is happy and can successfully resolve the request. This is the way that things worked in past versions of ASP.NET MVC before ASP.NET Core. In ASP.NET Core the namespace of the controller class is unimportant, although the tradition is maintained by tooling that continues to place controller classes always under a folder named Controllers. In fact, you can now place your controller classes in any folders and any namespaces that you wish. As long as the class has the “Controller” suffix and inherits from Controller, it will always be discovered. In ASP.NET Core, however, the controller class will be successfully discovered even if it lacks the “Controller” suffix. There are a couple of caveats, though. The first caveat is that the discovery process works only if the class inherits from base class Controller. The second caveat is that the name of the class must match exactly the controller name as it resulted from the route analysis. For example, if the controller name extracted from the route is “Home” then it is acceptable for the system if you have a class named Home that inherits from base class Controller. Any other name won’t work. In other words, the system needs two distinct pieces of information to discover a controller. First, the system needs to know if the class can serve as an ASP.NET MVC controller. Second, the system needs to know which controller route the class can serve. A class is recognized as a controller if it inherits from Controller, ends with the suffix “Controller” or is marked with the [Controller] attribute, as below. The controller route parameter is the name of the class or the part of the name that precedes the suffix “Controller”. Therefore, also the following class is acceptable as a controller and its nickname will be “home”. Why is a POCO controller an option within an ASP.NET MVC application? All in all, a POCO controller is a form of optimization that reduces overhead and the memory footprint. Not inheriting from a known base class cuts some functions off that might not be strictly necessary. At the same time, not inheriting from a known base class may preclude some common operations or make them a bit more verbose to implement. Let’s review a few examples where it is acceptable or even recommended to have a POCO controller. A POCO controller works well if you don’t need any dependencies on the surrounding HTTP environment. If your task is creating a super-simple web service that just returns JSON data, then a POCO controller may be a good choice. The following code, in fact, works just fine. A POCO controller also works well if you have a bunch of functions dealing with the content of some files, whether existing or to be created on the fly. Additionally, you can use a POCO controller to return HTML that is composed algorithmically. If you want to generate HTML via the Razor engine instead, it is a different story. In this case, more work is required and, more importantly, it requires more in-depth knowledge of the framework. The aspect of a POCO controller that causes problems is the lack of the HTTP context. In particular, this means that you can’t inspect the raw data that is being posted, including query string and route parameters. However, model binding brings sufficient data your way without the need of direct access to the HTTP context. There’s definitely a way to plug the HTTP context in, but at this point you need to question why you are using a POCO controller. Controller Factory In ASP.NET MVC and in ASP.NET Core, every request that doesn’t result in serving a static file like an image, a CSS or a JavaScript file ends up being mapped to a controller class and produces its output executing one of the controller’s public methods. The instance of the serving controller class is created through a factory class. The factory class is responsible for the following actions: - Getting you a controller instance - Releasing an existing controller instance Both in ASP.NET MVC and ASP.NET Core, there’s a class called DefaultControllerFactory that contains the default implementation used by the system. This class can be replaced if necessary. In ASP.NET Core, you replace it via the internal Dependency Injection (DI) system. Let’s see how to do that in classic ASP.NET MVC. The ideal place for this code is in the Application_Start event handler within global.asax. A custom controller factory, especially if it derives from DefaultControllerFactory can do one more thing. It can determine the actual type being used for a given controller nickname. This opens up at least a couple of interesting opportunities for use, one just fancy and one quite more intriguing. One Fancy Thing You Can Do with the Controller Factory You can use a custom controller factory to change the default rule for controller names. In classic ASP.NET MVC, if you don’t like to have classes named with the Controller suffix, then you can change it to whatever else you like. You can even localize it. Admittedly, this is not one of those things with a concrete application in the real world or, at least, I haven’t found one yet that is really worthwhile. Yet it is a funny thing to try to play with the internal machinery of ASP.NET. The GetControllerType overridable method returns the Type object to be created against the provided controller nickname. If the passed name is, say, “Home” then the above implementation will return a Type object for the YourNS.Controllers.HomeCoordinator class. Needless to say, the HomeCoordinator class will have exactly the same structure of a regular controller class but a quite unusual name. Localizing the Routes of the Application Frankly, I wrote the above demo many years ago while authoring a programming book about a freshly released version of ASP.NET MVC and it never moved out of that old Visual Studio 2010 project. Recently, instead, I got a question from a customer asking another apparently weird thing that, at the end of the day, I could only answer by resorting to a custom factory that just overrides the GetControllerType method. The question was: ‘how can I have localized routes and language-sensitive URLs in my application?’ The customer had a multi-lingual application and wished to present each user with URLs expressed in their own language of choice. For example, the canonical URL home/index had to become hem/index in Swedish and product/catalog was expected to be something like produkt/katalog. The same was needed for a few other supported languages. Needless to say, the customer was willing to have only one controller and only one action implementation. Something had to be created that could manipulate the request and route to the sole existing controller written for the neutral language—in the specific case, the English language. I run into the following project but at first I found it far too intricate to adopt, and possibly expand. Also, it seemed to me that the project was blinking at attribute routing whereas the project was using conventional table-based routing. Whether I was right or wrong, I felt that this project needed an easier, and more direct, way to localize routes and URLs. Immediately, the GetControllerType method of the default controller factory class popped up in my mind, and so I ended up writing a custom factory like this. I made some assumptions about the resource files available in the application and introduced some conventions to keep the code lean and mean. In particular, I assumed that we’d need to have controller and action names localized to a resource file. Let’s say, routes.resx for the neutral language, routes.se.resx for the Swedish language and so forth. The figure below shows the content of the Swedish resource file. As you can see, all action names have the form Action_XXX where XXX is the value for the same entry in the neutral language. Needless to say, XXX is the name of the action method actually implemented. Controller names follow a similar pattern Controller_XXX and XXX is the name of the sole controller actually implemented. The parameter controllerName of the GetControllerType method receives the controller name as the routing system has determined it. If the requested URL is, say, produkt/katalog then the parameter is set to “produkt”. Helper methods GetNeutralControllerName and GetNeutralActionName map the resource value to the resource name and pick up Controller_Product in front of Produkt and Action_Catalog in front of Katalog. In the .NET Framework, it is easy to read the value of a resource. It is trickier to get the key from the value. You must retrieve the resource set dictionary via the ResourceManager embedded in the auto-generated resource object. If an entry is found that matches the localized controller name, its key is taken and the prefix “Controller_” stripped off. Exactly the same code runs for action methods except that a different prefix is stripped off at the end. It should be noted that while the controller name is also passed as an argument, the action name must be read from the RouteData collection. (Also, the controller could be read from there.) More importantly, the RouteData collection must be updated with the neutral controller and action names for the remainder of the ASP.NET infrastructure to successfully invoke the method and locate any related views. If you focus again on the implementation of the GetControllerType method you see that there’s no need for modifying the actual process that produces the actual Type object. Once we changed controller and action name the default behavior can be preserved. Some further comment deserves the following line: This is necessary to properly handle the empty route (i.e.,) and to make the system accept anyway any URLs expressed in the neutral language. The figure shows a few screenshots from a sample application. The first screenshot handles correctly a Swedish URL and maps it correctly to neutral language route parameters. As long as the UI culture remains set to Swedish only Swedish and neutral names will be accepted in the URLs. The central screenshot shows how the system defaults to the neutral language regardless the UI culture set when no URL is explicitly provided. Finally, the third screenshot shows what happens when you switch the language to Italian. If you try to use a Swedish URL when the language is Italian you’ll get a 404 error and vice versa. Summary The article started with an overview of controllers in ASP.NET and ASP.NET Core and ended with a discussion about localized routes and URLs. Frankly, I don’t know how many applications out there have the need of using localized routes but I hope that at least implementing them—even only for fun—contributed to unveiling some interesting internals of ASP.NET MVC.
https://www.red-gate.com/simple-talk/dotnet/asp-net/control-controller-asp-net-mvc/
CC-MAIN-2019-18
refinedweb
2,081
63.29
Let's define a new method in our Circle class. This one tests whether a specified point falls within the defined circle: public class Circle { double x, y, r; // is point (a,b) inside this circle? public boolean isInside(double a, double b) { double dx = a - x; double dy = b - y; double distance = Math.sqrt(dx*dx + dy*dy); if (distance < r) return true; else return false; } . . // Constructor and other methods omitted. . } What's this Math.sqrt() thing? It looks like a method call and, given its name and its context, we can guess that it is computing a square root. But the method calls we've discussed are done through an object. Math isn't the name of an object that we've declared, and there aren't any global objects in Java, so this must be a kind of method call that we haven't seen before. What's going on here is that Math is the name of a class. sqrt() is the name of a class method (or static method) defined in Math. It differs from the instance methods, such as area() in Circle, that we've seen so far. Class methods are like class variables in a number of ways: Class methods differ from instance methods in one important way: they are not passed an implicit this reference. Thus, these this-less methods are not associated with any instance of the class and may not refer to any instance variables or invoke instance methods. Since class methods are not passed a this reference, and are not invoked through an object, they are the closest thing that Java offers to the "normal" C procedures that you may be accustomed to, and may therefore seem familiar and comforting. If you're sick and tired of this object-oriented business, it is perfectly possible to write complete Java programs using only class methods, although this does defeat an important purpose of using the language! But don't think that class methods are somehow cheating--there are perfectly good reasons to declare a method static. And indeed, there are classes like Math that declare all their methods (and variables) static. Since Math is a collection of functions that operate on floating-point numbers, which are a primitive type, there are no objects involved, and no need for instance methods. System is another class that defines only class methods--it provides a varied collection of system functions for which there is no appropriate object framework. Example 3.5 shows two (overloaded) definitions of a method for our Circle class. One is an instance method and one is a class method. public class Circle { public double x, y, r; // An instance method. Returns the bigger of two circles. public Circle bigger(Circle c) { if (c.r > r) return c; else return this; } // A class method. Returns the bigger of two circles. public static Circle bigger(Circle a, Circle b) { if (a.r > b.r) return a; else return b; } . . // Other methods omitted here. . } You would invoke the instance method like this: Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = a.bigger(b); // or, b.bigger(a); And you would invoke the class method like this: Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = Circle.bigger(a,b); Neither of these is the "correct" way to implement this method. One or the other will seem more natural, depending on circumstances. Now that we understand class variables, instance variables, class methods, and instance methods, we are in a position to explore that mysterious method call we saw in our very first Java "Hello World" example: System.out.println("Hello world!"); One hypothesis is that println() is a class method in a class named out, which is in a package named System. Syntactically, this is perfectly reasonable (except perhaps that class names always seem to be capitalized by convention, and out isn't capitalized). But if you look at the API documentation, you'll find that System is not a package name; it is the name of a class (which is in the java.lang package, by the way). Can you figure it out? Here's the story: System is a class. It has a class variable named out. out refers to an object of type PrintStream. The object System.out has an instance method named println(). Mystery solved! Both class and instance variables can have initializers attached to their declarations. For example: static int num_circles = 0; float r = 1.0; Class variables are initialized when the class is first loaded. Instance variables are initialized when an object is created. Sometimes we need more complex initialization than is possible with these simple variable initializers. For instance variables, there are constructor methods, which are run when a new instance of the class is created. Java also allows you to write an initialization method for class variables. Such a method is called a static initializer. The syntax of static initializers gets kind of bizarre. Consider that a static initializer is invoked automatically by the system when the class is loaded. Thus there are no meaningful arguments that can be passed to it (unlike the arguments we can pass to a constructor method when creating a new instance). There is also no value to return. So a static initializer has no arguments and no return value. Furthermore, it is not really necessary to give it a name, since the system calls the method automatically for us. What part of a method declaration is left? Just the static keyword and the curly brackets! Example 3.6 shows a class declaration with a static initializer. Notice that the class contains a regular static variable initializer of the kind we've seen before, and also a static initializer--an arbitrary block of code between { and }. // We can draw the outline of a circle using trigonometric functions. // Trigonometry is slow though, so we pre-compute a bunch of values. public class Circle { // Here are our static lookup tables, and their own simple initializers. static private double sines[] = new double[1000]; static private double cosines[] = new double[1000]; // Here's a static initializer "method" that fills them in. // Notice the lack of any method declaration! static { double x, delta_x; int i; delta_x = (Circle.PI/2)/(1000-1); for(i = 0, x = 0.0; i < 1000; i++, x += delta_x) { sines[i] = Math.sin(x); cosines[i] = Math.cos(x); } } . . // The rest of the class omitted. . } The syntax gets even a little stranger than this. Java allows any number of static initializer blocks of code to appear within a class definition.. One common use of static initializers is for classes that implement native methods--i.e., methods written in C. The static initializer for such a class should call System.load() or System.loadLibrary() to read in the native library that implements these native methods. In Java 1.1, a class definition may also include instance initializers. These look like static initializers, but without the static keyword. An instance initializer is like a constructor: it runs when an instance of the class is created. We'll see more about instance initializers in Chapter 5, Inner Classes and Other New Language Features, Inner Classes and Other New Language Features.
https://docstore.mik.ua/orelly/java/javanut/ch03_04.htm
CC-MAIN-2019-26
refinedweb
1,216
67.15
One of the core concepts of Apache Wicket web framework is the model and IModel as its programming interface. Wicket components rely heavily on models, which makes them important pieces of the architecture. Apache Wicket is stateful framework that stores the pages and their components to a page store that usually resides in the HTTP session. Components create the public facing view from the content of the models. Misusing models can cause awkward side effects, like pages not updating their content or huge memory consumption in your application. And the most issues with new Wicket users, from what I’ve seen, are with the correct use of the models. In this blog post I’ll try to explain how and what kind of models should be used in different use cases. The most basic of the Wicket IModel implementations is the Model class. It is basically a simple placeholder for the model content. This suits fine for situations where the model content does not consume much memory and is more like a constant. A simple String could be a good candidate for Model’s content. IModel<String> name = new Model<String>("John"); You have to understand, that when you create a Model object its content stays the same even if the page containing the model is refreshed. This behavior is caused by the use of a static model. Dynamic models can change the actual content every time the value is asked from the model. Using a static model instead of a dynamic one is quite common mistake by new Wicket users. If the concept of static and dynamic models is not clear to you, you should check chapter 4 Understanding models from the book Wicket in Action. IModel<Date> date = new Model<Date>() { @Override public Date getObject() { return new Date(); } }; The dynamic date model above is created as an anonymous class from Model by overriding the getObject() method. The model will always return a fresh copy of Date that contains the current time. Wicket is stateful web framework and the models are stored usually in the user’s HTTP session. The data in the model is most likely fetched from database or through some web service. If we use the static model approach, we will eat up a lot of memory soon and will not achieve a fresh view from the data source if the page is reloaded. If we decide to use a dynamic model like we did with the Date object, we might end up making a lot of database searches or web service calls within one page load. The anonymous inner class is not nice looking code either. Wicket has a built in solution for this problem, LoadableDetachableModel that caches the content of the model until it is safe to discard, providing an efficient but still dynamic model. public class PersonModel extends LoadableDetachableModel<Person> { private Long id; private PersonService personService; public PersonModel(final Long id, final PersonService personService) { super(); this.id = id; this.personService = personService; } public PersonModel(final Person person, final PersonService personService) { super(person); this.id = person.getId(); this.personService = personService; } @Override protected Person load() { return personService.findById(id); } } The above example constructs a loadable and detachable model for loading a single person by its unique identifier. The model has two constructors for a reason. One to create a lazy loaded model in detached state that will load the content when the getObject() method is called first time, and one to create a model in attached state that does not require a call to PersonService when the getObject() method is called. It is good practice to provide these 2 constructors for all LoadableDetachableModels. You can create a model in attached state when you already have the content or create it in detached state when only the identifier is available. The caveat of loadable detachable models is the private fields of the model. Wicket stores the model along with the components in a page store and that might require serialization of the model. When the model is serialized, also the private fields are serialized (the actual content is detached). Our id field is not a problem because it’s serializable, but the PersonService might be a problem. Usually the service layer’s interfaces are not serializable by default. There are at least two decent solutions to this issue: either make your services serializable, or better one, wrap the service in a serializable proxy. The proxy behavior can be achieved for example with integrations to different dependency injection frameworks, eg. Spring (wicket-spring) or Guice (wicket-guice). The integration modules make sure that the service proxies are serializable when you inject them. public class ProfilePage extends WebPage { @SpringBean private PersonService personService; public ProfilePage(final PageParameters parameters) { super(parameters); Long id = parameters.get("id").toLongObject(); IModel<Person> personModel = new PersonModel(id, personService); add(new ProfilePanel("profilePanel", personModel)); } } The above example uses wicket-spring integration to inject the person service to the desired page. [email protected] provides a serializable proxy, so when we create the person model, we don’t need to worry about the serialization of the service. Wicket does not allow constructor injection, because all the injection magic actually happens when we call the super() constructor. This means that we have the injected values initialized after the base constructor of Component is finished. Just remember to use serializable identifiers or locators for the data and use serializable proxies for the services. Normally in MVC web frameworks the view layer uses some kind of data transfer objects to build the view. DTOs are composed and inherited to create different kind of views. Building the factories or mappers for those objects can be error prone or frustrating. Wicket provides a different solution to this issue. In Wicket, you can think that the IModel interface works like a relational database view that allows you to show the desired parts of the domain in different ways. public class PersonFriendsModel extends AbstractReadOnlyModel<String> { private IModel<Person> personModel; public PersonFriendsModel(final IModel<Person> personModel) { super(); this.personModel = personModel; } @Override public String getObject() { Person person = personModel.getObject(); Iterable<String> friendNames = Iterables.transform(person.getFriends(), new PersonNameFunction()); return person.getName() + "'s friends are " + Joiner.on(", ").join(friendNames); } @Override public void detach() { personModel.detach(); } private class PersonNameFunction implements Function<Person, String> { public String apply(final Person input) { return input.getName(); } } } Here we build a model that could compose the PersonModel we created earlier. We use it as a source to build a nice list of the person’s friends. The model we are extending is the AbstractReadOnlyModel that Wicket offers to us. It is basically a normal model, but does not allow setting the model content. This makes perfect sense, because we are building a joined String and it would be awkward to parse a similar list and set the person’s friends from that list. We only use this model for read only purposes, to show the list of friends in the view. You can see the view analogy here, we are still using the same Person domain model, but exposing a custom view from it with help of a model. Notice that we delegate the detach method to the composed model. This makes sure that if we don’t have direct reference to the composed model in any component, we are still able to detach it from the friends model. Calling the detach() method multiple times does no harm, so it’s safe to use even from multiple components. We created only a simple example of model composing. You should explore the Wicket’s built in model implementations and spend some time figuring how you can create reasonable models from your domain model with them. Just remember one thing: compose and extend models, not the domain objects. The last thing I will talk about is the property models. They are widely used in many Wicket applications, and even Wicket in Action book encourages to use them, but they have some unwanted features. Property models are fast to code and easy to use, but they make your code “stringly typed”. And this is something we don’t want in type safe language like Java. PropertyModel<String> nameModel = new PropertyModel<String>(personModel, "name"); We create a model from the person’s name using a PropertyModel. The name model can use either straight Person object or an IModel that provides us the person. This feature can be achieved by implementing the Wicket’s IChainingModel interface. We have two issues here though. First one is the type of the name model. We define that the name must be String, but actually the compiler cannot make sure that name is bound to a String getName() JavaBean property. The second issue comes from refactoring, we use a String value to define the property name. If you refactor the Person object with your IDE and hange the getName() method to getLastName(), your application will broke and again the compiler cannot notice this. Let’s stop here for a while to look at the IChainingModel interface. Its main purpose is to allow using of a plain object or a chained model as the model’s content. The PropertyModel could be used with a model that provides a person or with plain person object. If you look at the PropertyModel’s source code, you notice that implementing the IChainingModel requires casting and, in my opinion, boiler plate code. The PersonFriendsModel we created earlier could be refactored to implement IChainingModel so that instead of taking only a model in as the content, it would also support taking a person straight in. Is this really necessary? Not really. If we want to use plain person, we could create a new static model from the person providing us the same functionality as IChainingModel would provide. CompoundPropertyModel adds even more magic to the model handling. It serves as root model for many components that can bind automatically to it by matching the property name to the component id. public class PersonForm extends Form<Person> { public PersonForm(final String id, final IModel<Person> personModel) { super(id, new CompoundPropertyModel<Person>(personModel)); add(new TextField<String>("name")); add(new TextField<Integer>("age")); } } Here we create a form to show input fields for the person’s name and age. There is no model attached to either text field, but we are still able to bind the “name” component to the person’s name and the “age” component to the person’s age. The compound property model we created in the constructor is the root model for the form and automatically binds the form components to the object’s properties by the component ids. The same issues apply with the compound property model that apply with the property model, but we even add one more. Now we lock the component id straight to the property name. This means that we have a dependency from the HTML template straight to the domain objects property name. This does not sound very reasonable. It is up to you if you want to use property models, but in my opinion they should be avoided due to the issues explained earlier. There are projects like bindgen-wicket that try to achieve the behavior of property models without losing the type safety. But even bindgen does not work that well with refactoring. How we implement the name model in a type and refactoring safe way then? public class NameModel implements IModel<String> { private IModel<Person> personModel; public NameModel(final IModel<Person> personModel) { this.personModel = personModel; } @Override public String getObject() { return personModel.getObject().getName(); } @Override public void setObject(String object) { personModel.getObject().setName(object); } @Override public void detach() { personModel.detach(); } } The model has a lot more lines than the property model. Yes, that is true, but do you want to lose type safety and refactoring features and potentially break your application very easily. The model is in different file so you can still use it as a one liner, so there is no difference if you use property model or the model we just created. And you can always remember the fact that Java is just very verbose language. Wicket also provides us ResourceModel and StringResourceModel that provide a powerful tool of creating localized content for your components. I will not discuss them in this post, because Wicket in Action book has good reference for those. I tried to bring up some real life examples how to use different kind of models and what their purpose is. I hope this gave you some more knowledge about Wicket models and how they should be used properly. MOAR! Nice to see new post on Wicket again. It seemed like no-one was using this framework anymore. I prefer the lamba4j approach. See here: (somehere near the bttom)
https://www.javacodegeeks.com/2013/09/a-clean-approach-to-wicket-models.html/comment-page-1/
CC-MAIN-2016-40
refinedweb
2,125
54.42
12 July 2012 07:14 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The company signed a framework agreement of PV industry cooperation strategy with local government on 9 July, the company source said. Under the agreement, the company is expected to build 600 megawatt (MW) PV project by investing CNY6bn, and complete 50MW in 2012, 150MW in 2013, 200MW in 2014, and 200MW in 2014 respectively. An additional investment of CNY1.6bn will be spent by the company to build a 150MW PV power project at HT-SAAE was established in May 1998 and it focuses on the development of polysilicon, solar battery and PV power station system and integration. (
http://www.icis.com/Articles/2012/07/12/9577616/chinese-aerospace-firm-to-invest-cny7.6bn-on-pv-project-in-ningxia.html
CC-MAIN-2015-11
refinedweb
110
50.16
In Visual Basic 6, we have a new addition (and a great deal of scope for adding more-a lot of gaps!): vbUserDefinedType 36 User-defined type With some limitations, we can add to this list. For example, we could, with only a small amount of effort, add a new Variant subtype of 42 to represent some new entity by compiling this C code to a DLL named NEWTYPE.DLL: #include "windows.h" #include "ole2.h" #include "oleauto.h" #include <time.h> typedef VARIANT * PVARIANT; VARIANT __stdcall CVNewType(PVARIANT v) { // If the passed Variant is not set yet... if (0 == v->vt) { // Create new type. v->vt = 42; // Set other Variant members to be meaningful // for this new type... // You do this here! } // Return the Variant, initialized/used Variants // unaffected by this routine. return *v; } int __stdcall EX_CInt(PVARIANT v) { // Sanity check - convert only new Variant types! if (42 != v->vt) { return 0; } else { // Integer conversion - get our data and convert it as // necessary. // Return just a random value in this example. srand((unsigned)time(NULL)); return rand(); } } This code provides us with two routines: CVNewType creates, given an already created but empty Variant (it was easier), a Variant of subtype 42; EX_CInt converts a Variant of subtype 42 into an integer value (but doesn't convert the Variant to a new Variant type). "Converts" here means "evaluates" or "yields". Obviously, the implementation above is minimal. We're not putting any real value into this new Variant type, and when we convert one all we're doing is returning a random integer. Nevertheless, it is possible! Here's some code to test the theory: Dim v As Variant v = CVNewType(v) Me.Print VarType(v) Me.Print EX_CInt(v) This code will output 42 and then some random number when executed against the DLL. The necessary DLL declarations are as follows: Private Declare Function CVNewType Lib "NEWTYPE.DLL" _ (ByRef v As Variant) As Variant Private Declare Function EX_CInt Lib "NEWTYPE.DLL" _ (ByRef v As Variant) As Integer Again, we cannot override Visual Basic's CInt , and so I've had to call my routine something other than what I wanted to in this case, EX_CInt for "external" CInt. I could, of course, have overloaded Val: Public Function Val(ByRef exp As Variant) As Variant Select Case VarType(exp) Case 42: Val = EX_CInt(exp) Case Else: Val = VBA.Conversion.Val(exp) End Select End Function Here, if the passed Variant is of subtype 42, I know that the "real" Val won't be able to convert it-it doesn't know what it holds after all-so I convert it myself using EX_CInt. If, however, it contains an old Variant subtype, I simply pass it on to VBA to convert using the real Val routine. Visual Basic has also been built, starting with version 4, to expect the sudden arrival of Variant subtypes about which nothing is known. This assertion must be true because Visual Basic 4 can be used to build ActiveX servers that have methods. In turn, these can be passed Variants as parameters. A Visual Basic 5 client (or server) can be utilized by a Visual Basic 6 client! In other words, because a Visual Basic 6 executable can pass in a Variant of subtype 14, Visual Basic must be built to expect unknown Variant types, given that the number of Variant subtypes is likely to grow at every release. You might want to consider testing for this in your Visual Basic 4 code. Having said all this and having explained how it could work, I'm not sure of the real value currently of creating a new Variant subtype. This is especially true when, through what we must call a feature of Visual Basic, not all the conversion routines are available for subclassing. Why not use a UDT, or better still, a class to hold your new type instead of extending the Variant system? Another limitation to creating a new Variant subtype is because of the way we cannot override operators or define them for our new types. We have to be careful that, unlike an old Variant, our new Variant is not used in certain expressions. For example, consider what might happen if we executed Me.Print 10 + v. Because v is a Variant, it needs to be converted to a numeric type to be added to the integer constant 10. When this happens, Visual Basic must logically apply VarType to v to see what internal routine it should call to convert it to a numeric value. Obviously, it's not going to like our new Variant subtype! To write expressions such as this, we'd need to do something like Me.Print 10 + Val(v). This is also the reason why, in the Val substitute earlier, I had to pass exp by reference. I couldn't let Visual Basic evaluate it, even though it's received as a Variant. Variants also might need destructing correctly. When they go out of scope and are destroyed, you might have to tidy up any memory they might have previously allocated. If what they represent is, say, a more complex type, we might have to allocate memory to hold the representation. Microsoft does not encourage extending the Variant type scheme. For example, 42 might be free today, but who knows what it might represent in Visual Basic 7. We would need to bear this in mind whenever we created new Variant subtypes and make sure that we could change their VarType values almost arbitrarily-added complexity that is, again, less than optimal! All in all, creating new Variant subtypes is not really a solution at the moment. If we get operator overloading and proper access to VBA's conversion routines, however, all of this is a little more attractive. NOTE The code to create Variant subtypes needs to be written in a language such as C. The main reason is that Visual Basic is too type safe and simply won't allow us to treat a Variant like we're doing in the DLL. In other words, accessing a Variant in Visual Basic accesses the subtype's value and storage transparently through the VARIANT structure. To access its internals, it's necessary to change the meaning of Variant access from one of value to one of representation. updated
http://www.brainbell.com/tutors/Visual_Basic/newfile153.html
CC-MAIN-2018-22
refinedweb
1,061
63.19
How To Impress Yoour Girlfriend To have yawned the jansons were newcomers in the the grace of the celestials. And, o bull of the and announced his intention to commence a pistol came to the place with cheerful hearts. And when exhausted, thou mayst refill it by taking wealth. Hello, thank you for yor contribution. Antoine Calando wrote: > It corrects two problems: > - a warning is issued when looking for env var 'HOME' if there is no > such var defined. I applied this patch to the LTP CVS. > -. lcov isn't designed to run on a system with a non-unix filesystem type and I assume that many more places than the once mentioned in your patch make this assumption. Therefore I'll skip this part of your patch until I figured out which other parts will need changing too. Regards, Peter Hi, I made a patch for lcov-1.6. It corrects two problems: - a warning is issued when looking for env var 'HOME' if there is no such var defined. -. Regards, Antoine Hello, Richard Corden wrote: > Firstly, I would like to say how excellent I think lcov is. It has > taken me about a day in total to generate coverage analysis for pretty > much our entire code base, and the results are visually stunning. > (Although the lack of coverage on some of our code base is alarming!). Thanks, it's always good to hear how lcov is of use to people. > 1) Unnamed namespaces: > > Each function in an unnamed namespace is counted twice in the function > coverage analysis. For example: Using your instructions I was able to reproduce the problem. This is actually a bug in geninfo. I fixed this in the CVS version of geninfo (see lcov web page for instructions on how to get that version). > 2) #line directives > [...] > The first is that it would be nice if lcov could somehow determine the > location of that file. Unfortunately it doesn't seem possible to automatically convert all relative #line statements to absolute ones. -fworking-directory will only emit an extra #line-directive containing the current directory - but that one is overwritten again with the actual directive in the source code. > If not, then I think it is > preferable that genhtml, rather than dying, would continue and just > ignore the file. This sounds like a good candidate for an addition to a new version of lcov. There is already an option for lcov to not die when encountering an error - extending this mechanism to genhtml would only be consistent. > 3) Uninitialized HASH > > Unfortunately, I really don't have very much information on the final > issue. The issue manifested itself with perl complaining about using an > undefined HASH in "merge_func_data" on line 1506: It could be that this issue is also fixed with the changes for 1) described above. I'll have another look, but it would help if you could provide instructions on how to recreate this problem. Thanks and regards, Peter ÊÇ·ñ»¹ÔÚÎªÍøÕ¾Òµ¼¨¶ø·³ÄÕ£¬µ¥¾üÈçºÎ¿ìËÙÌáÉýÐÅÏ¢·¢²¼Ð§ÂÊ£¬ÔÚÕâÀï¸æËßÄúÒ»¸ö×î¼ÑµÄ²Ù×÷ģʽ£¬hwdÈÃÄúµÄÒµ¼¨ÌáÉýÊ®±¶²»ÔÙÊÇÃΣ¬ÏêÇéµÇ½£ºwww£¬ctvao£¬com£¬cn£¨£¬»» . ¼´¿É£© I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/ltp/mailman/ltp-coverage/?viewmonth=200902&viewday=9
CC-MAIN-2016-30
refinedweb
564
63.7
I'm assuming the goal of inter-DC comms is it for replication and disaster recovery. Are there other goals for this? On Mon, Jul 18, 2011 at 12:08 AM, Eric Sammer <esammer@cloudera.com> wrote: > A good (and tricky) point. In keeping with the way we've talked about > Flume, there are two systems that are important. One system is the > control plane responsible for node health and status, configuration, > and reporting. The other major system is the data plane, obviously > responsible for data transfer. I see the utility of both being able to > span a wide area but I think it's warrants a discussion as to how it > should work and what guarantees we're interested in making here. > > Major points to cover: > > * If we use ZK sessions and ephemeral nodes for heartbeats and status, > are we killing ourselves long term? I know ZK can span wide areas > (i.e. suffer high latency) but it will certainly impact the time it > takes to detect and recover from errors. I'd like to get input from > phunt or Henry on this. Another option is to have a secondary layer > for controlling inter-DC communication and have discreet ZK and > control planes. > I'd prefer limiting the scope of implementation currently, but having a design that will allow for greater scope in the future. More specifically, I've been thinking that the current flume, with its collectors and agents would be focused on the single DC case. Let's consider the "limits" with ZK and emphemral nodes today. Heartbeating via ephmeral nodes will crap out when ZK cannot handle the # of connections or the amount of writes. Last I've heard this is on the order of 1k writes/s on a laptop. [1] and several 10k's from the zk paper [2]. With 1 second ephemeral node refreshes I think this means we could theoretically have 10k's of nodes. More practically, this means it should be able to handle 1k's of nodes with failures. Right now we use 5s so we could get a 5x bump or more if we make the heartbeats longer. My understanding is that are single-DC clusters today that are already at these scales. It follows that if we ever get into clusters with 10k's or 100k's of machines we'll probably want to have multiple instances. If they are in the same DC they could potentially write to the same HDFS. If they are different we have a different problem -- single source and many destinations. For this I'm leaning towards a secondary layer of Flume, with inter-DC agents and inter-DC collectors would likely have more of a pub-sub model a la facebook's calligraphus (uses hdfs for durability) or yahoo!'s hedwig (bookkeeper/zk for durability). This lets the lume 1.0 goal be solid and scalable many-to-few aggregation a single DC and have a long term flume 2.0 goal being few-to-many inter-dc replication. [1] [2] > * The new role of the master. Assuming we can gut ACK path from the > master and remove it from the critical path, does it matter where it > lives? Based on the discussions we've had internally and what is > codified in the doc thus far, the master would only be used to push > config changes and display status. Really, it just reads from / write > to ZK. ZK is the true master in the proposal. > The master would also still be the server for the shell and along with the web interfaces. A shell could potentially just go to zk directly, but my first intuition is that there should be one server to make concurrent shell access easier to understand and manage. By decoupling the state to ZK, this functionality could be separated. For now, the master would remain the "ack node" that could too also eventually be put into a separate process. Or, collector nodes could actually publish acks into ZK. At the end of the day, if all the state lives in ZK, the master doesn't even need to talk to nodes -- it could just talk to ZK. The master could just watch the status and just manage control plane things like flow transitions and adapting if more nodes are added ore removed. If masters only interact with ZK, I don't think we would even need master leader election. Another ramification of completely decoupling for an inter-dc case is that one master could consults two or more different zk's. * If we're primarily interested in an inter-DC data plane, is this > best done by having discreet Flume systems and simply configuring them > to hand off data to one another? Note this is how most systems work: > SMTP, modular switches with "virtual" fabric" type functionality, JMS > broker topologies. Most of the time, there's a discreet system in each > location and an "uber tool" pushes configurations down to each system > from a centralized location. Nothing we would do here would preclude > this from working. In other words, maybe the best way to deal with > inter-DC data is to have separate Flume installs and have a tool or UI > that just communicates to N masters and pushes the right config to > each. > > I like the idea of messaging/pubsub style system for inter-DC communications. I like the design of Facebook's calligraphus system (treat HDFS as a pubsub queue using append and mulitple concurrent readers for 3-5 second data latency). We don't necessarily have to solve all of these problems / answer all > of these questions. I'm interested in deciding: > * What an initial re-implementation or re-factoring of the master looks > like. > I think the discrete steps may be: 1) nodes use zk ephemeral nodes to heart beat 2) translation/auto chaining stuff gets extracted out of master (just a client to the zk "schema") * What features we'd like to support long term. > Ideally, the zk "schema" for flume data would be extensible so that extra features (like chokes, the addition of flows, the additions of ip/port info etc) can be added on without causing pain. * What features we want to punt on for the foreseeable future (e.g. > 24 > months) > > On Sat, Jul 16, 2011 at 8:10 PM, NerdyNick <nerdynick@gmail.com> wrote: > > The only thing I would like to make sure is that the design allow for > > future work to be done on allowing for multi datacenter. > > > > On Fri, Jul 8, 2011 at 3:08 PM, Eric Sammer <esammer@cloudera.com> > wrote: > >> Flumers: > >> > >> Jon and I had some preliminary discussions (prior to Flume entering > >> the incubator) about a redesign of flume's master. The short version > >> is that: > >> > >> 1. The current multimaster doesn't work correctly in all cases (e.g. > >> autochains). > >> 2. State exists in the master's memory that isn't in ZK (so failover > >> isn't simple) > >> 3. All the heartbeat / RPC code is complicated. > >> > >> The short version of master NG would be: > >> > >> 1. All master state gets pushed into ZK > >> 2. Nodes no longer heartbeat to a specific master. Instead, they > >> connect to ZK and use ephemeral nodes to indicate health. > >> 3. Masters judge health and push configuration by poking state into > >> each node's respective ZK namespace. > >> > >> There's a separate discussion around changing how ACKs work (so they > >> don't pass through the master) but we're going to separate that for > >> now. This is just a heads up that I'm going to start poking bits into > >> the new Apache Flume wiki. The discussion is open to all and both Jon > >> and I would love to hear from users, contrib'ers, and dev'ers alike. > >> I'm also going to try and rope in a ZK ninja to talk about potential > >> issues they may cause / things to be aware of once we have something > >> in the wiki to point at. > >> > >> -- > >> Eric Sammer > >> twitter: esammer > >> data: > >> > > > > > > > > -- > > Nick Verbeck - NerdyNick > > ---------------------------------------------------- > > NerdyNick.com > > Coloco.ubuntu-rocks.org > > > > > > -- > Eric Sammer > twitter: esammer > data: > -- // Jonathan Hsieh (shay) // Software Engineer, Cloudera // jon@cloudera.com
http://mail-archives.apache.org/mod_mbox/incubator-flume-dev/201107.mbox/%3CCAAha9a0jzaWbjCF+uaTFRWLWRR8E2nS6K+Jm7vyehCVsEWV+Cw@mail.gmail.com%3E
CC-MAIN-2015-35
refinedweb
1,358
62.88
GLSL Programming/Unity/Minimal Shader< GLSL Programming | Unity This tutorial covers the basic steps to create a minimal GLSL shader in Unity. Contents Starting Unity and Creating a New ProjectEdit After downloading and starting Unity (Windows users have to use the command-line argument -force-opengl ), you might see an empty project. If not, you should create a new project by choosing File > New Project... from the menu. For this tutorial, you don't need to import any packages but some of the more advanced tutorials require the scripts and skyboxes packages. After creating a new project on Windows, Unity might start without OpenGL support; thus, Windows users should always quit Unity and restart it (with the command-line argument -force-opengl) after creating a new project. Then you can open the new project with File > Open Project... from the menu. If you are not familiar with Unity's Scene View, Hierarchy View, Project View and Inspector View, now would be a good time to read the first two (or three) sections (“Unity Basics” and “Building Scenes”) of the Unity User Guide. Creating a ShaderEdit Creating a GLSL. } #endif // here ends the definition of the vertex shader #ifdef FRAGMENT // here begins the fragment shader void main() // all fragment shaders define a main() function { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // this fragment shader just sets the output color // to opaque red (red = 1.0, green = 0.0, blue = 0.0, // alpha = 1.0) } #endif // here ends the definition of the fragment shader ENDGLSL // here ends the part in GLSL } } } “GLSL. Windows users should make sure that OpenGL is supported by restarting Unity with the command-line argument -force-opengl. Interactively Editing ShadersEdit This would be a good time to play with the shader; in particular, you can easily change the computed fragment color. Try neon green by opening the shader and replacing the fragment shader with this code: #ifdef FRAGMENT void main() { gl_FragColor = vec4(0.6, 1.0, 0.0, 1.0); // red = 0.6, green = 1.0, blue = 0.0, alpha = 1.0 } #endif: #ifdef VERTEX void main() { gl_Position = gl_ModelViewProjectionMatrix * (vec4(1.0, 0.1, 1.0, 1.0) * gl_Vertex); } #endif This flattens any input geometry by multiplying the coordinate with . (This is a component-wise vector product; for more information on vectors and matrices in GLSL, which you can display in the text editor by choosing View > Line Numbers in the text editor menu. > Create Other > material name and choosing the new material from the pop-up window. GLSL, a “shader” is either a vertex shader or a fragment shader. The combination of both is called a “program”. Unfortunately, Unity refers to this kind of program as a “shader”, while in Unity a vertex shader is called a “vertex program” and a fragment shader is called a “fragment program”. To make the confusion perfect, I'm going to use Unity's word “shader” for a GLSL program, i.e. the combination of a vertex and a fragment shader. However, I will use the GLSL terms “vertex shader” and “fragment shader” instead of “vertex program” and “fragment program”. SummaryEdit Congratulations, you have reached the end of this tutorial. A few of the things you have seen are: - How to create a shader. - How to define a GLSL vertex and fragment shader in Unity. - How to create a material and attach a shader to the material. - How to manipulate the ouput color gl_FragColorin the fragment shader. - How to transform the input attribute gl_Vertexin the vertex shader. - How to create a game object and attach a material to it. Actually, this was quite a lot of stuff. Further ReadingEdit If you still want to know more - about vertex and fragment shaders in general, you should read the description in Section “OpenGL ES 2.0 Pipeline”. - about the vertex transformations such as gl_ModelViewProjectionMatrix, you should read Section “Vertex Transformations”. - about handling vectors (e.g. the vec4type) and matrices in GLSL, you should read Section “Vector and Matrix Operations”. - about how to apply vertex transformations such as gl_ModelViewProjectionMatrix, you should read Section “Applying Matrix Transformations”. - about Unity's ShaderLab language for specifying shaders, you should read Unity's ShaderLab reference.
https://en.m.wikibooks.org/wiki/GLSL_Programming/Unity/Minimal_Shader
CC-MAIN-2017-22
refinedweb
700
57.27
"Bad" Perl is perl that is flawed in other ways; such as using fundamentally flawed algorithms; advanced coding techniques used for obfuscation purposes in production code; parsers and lexers built into the code to handle a configuration file that holds only constants; and so forth. In other words, truely bad Perl is perl that would remain bad even if refactored, or translated into a completely different language. "Baby Perl" is just inexperience with Perl idioms; which isn't always a bad thing. I often try to avoid using complicated features of perl when simple features will do the job; the less I have to *think* about the code to make sure that my clever tricks really work; the easier the code is to maintain. I'd rather have three lines I can read than one I can't; but obviously excessively verbose code imposes it's own inherent complexity, so there's a balance to be struck. I try to code to the level of the person who I anticipate will maintain the code. In some respect, my Perl resembles "Baby Perl" by design. I only use features that a novice might misunderstand when it would make the code awkward not to do so, and whenever I do something "clever", I know I'll pay for it later. Six months from now, I'll probably have to explain what I did to a confused maintainer, and while comments help, I'll still have a mini-training excercise on my hands. I do like teaching, but my company is losing money when I give out free training like that, because my time and my co-worker's time could be spent elsewhere more profitably. So, to recap: "Baby Perl" arises out of ignorance, and is solveable. "Bad Perl" arises out of incompetance or malice, and is not. Having dealt with too much bad Perl lately (6,000 line loops with eight levels of indentation, formatted inconsistantly with typically only 2 column indentation is... bad practice. Exporting local package variables into every single namespace instead of using a global variable in the first place is ... bad design. Making your fundamental data structures tied hashes with a rat's nest of internal function calls, with wierd side effects is... bad design. Localizing various sections of a data structure to modify the impact of key function calls is bad design. Putting your date/time handling code into a custom Perl-XS module that's (a) buggy, and (b) incompatible with the perl version in production is bad practice, given the tonnes of date handling routines on CPAN. Failing to "use strict" because you don't know it's there in a ten line perl script is not so bad. Failing to use strict because you're too lazy to use it in a 10,000 line perl project is bad. Just my $0.02 -- Ytrew Q. Uiop P.S.: On martial arts: I disagree with your premise that Martial artists would claim that the arts are about learning that you don't need to fight. Martial arts teach awareness of how you need to fight; including what degree of force is required or appropriate to a given situation. If a little child attacks an adult, we don't try to kill it; we just stop the attack, and scold the child. If an adult attacks a martial arts master with a credible threat, the adult will find that the master will defend him/herself using such violence as is appropriate to the situation. The only difference between "ordinary people" and "enlightened" martial arts masters is that a martial arts master has less risk of being hurt by a given attack due to superior skill; and can risk being more lenient while remaining safe. If the martial arts master was a true pacificfist, (s)he wouldn't have needed to learn how to kill and maim in the first place, before advocating "peace". Remember that the word "martial" means "warlike", and that "martial arts" were the killing tactics used on the battlefields in Asia. Traditions on how to kill with a sword, spear, staff, or with one's bare hands are very insightful, but they were never peaceful in origin or intent. It's easy to romanticize a violent tradition (like "knights in shining armour"), but a history of violence remains violent. In reply to Re: "Baby" Perl versus "Bad" Perl by Anonymous Monk in thread "Baby" Perl versus "Bad"
http://www.perlmonks.org/?parent=514212;node_id=3333
CC-MAIN-2013-48
refinedweb
745
64.95
printf Example Part of TutorialFundamentals You should prefer using writef, but in case you want to use printf you should be aware of a few corner cases. Here's the classic printf example (you have to import core.stdc.stdio to use printf): import core.stdc.stdio; void main() { printf("Hello World\n"); } Here's the equivalent code using writef: import std.stdio; void main() { writef("Hello World\n"); } When using the %s formatting token with printf you must be careful to use it with the embedded length qualifier: %.*s. This is because the difference between C and D is that C strings are zero-terminated character arrays referenced by an address, but in D they are a dynamic array object which is really an eight-byte structure containing a length and pointer: import core.stdc.stdio; void main() { string mystring = "hello"; printf("%.*s\n", mystring); //~ printf("%s\n", mystring); // <<-- This would fail in runtime. } The printf's %.*s will print until the length is reached or an embedded 0 is encountered, so D strings with embedded 0's will only print up to the first 0. When you absolutely must pass a string variable to a C function (such as printf, or maybe an external c function), you can use the std.string.toStringz function. However the string you pass to toStringz should not have an embedded zero, or you will have problems: import core.stdc.stdio; import std.string; void main() { string mystring = "hi\n"; string oops = "I have an embedded \0, oops!"; printf("%s", toStringz("Hello, world!\n")); printf("%s", toStringz(mystring)); printf("%s", toStringz(oops)); } Output: Hello, world! hi I have an embedded
http://dsource.org/projects/tutorials/wiki/PrintfExample/D2
CC-MAIN-2018-30
refinedweb
277
64.51
Would it be possible to use a Swift + Objective-C framework (or a pure Swift framework) with Mocha's loadFrameworkWithName? loadFrameworkWithName Even though a pure Objective-C framework is working nicely, when I add a single Swift file, loadFrameworkWithName fails. Any tricks I should know about, or is it simply not possible? Cheers! berk It's definitely possible, however your code would crash Sketch the second someone else loaded a different version of Swift. matt_sven I see, thanks Matt! matt_sven Have you actually got it to work? Any chance of sharing a sample XCode project? I'm encountering the same issue as berk. markh I think the only thing you need is to set 'Always Embed Swift Standard Libraries' = YES. That worked thanks matt_sven! I'm not sure whether to go with Objective-C or Swift for a plugin framework. I know for apps on iOS and MacOS the Swift runtime is currently embedded in each app which will make them a bit bigger - not sure if the same applies to frameworks. matt_sven You mentioned that Sketch will crash if another app uses a different version of Swift. Can you explain why that occurs? I used Swift to develop Sketch Plugin Manager and export a framework but didn't consider the issue conflicting Swift versions. I'm relatively new to framework development but was under the impression that if the framework embedded the Swift libraries (as matt_sven mentioned) that it would be contained to just my framework. Can someone help me understand why that's not true? markh The main reason right now is because the Swift ABI is still unstable. Because of this, different versions of Swift aren't interoperable. So if someone loads a framework with a different version of Swift, you'll have conflicts and things will crash. Right now the way to go for something like what you're describing is a well-namespaced Objective-C framework. mludowise Frameworks aren't isolated to the code loading them. Any code you load in joins the global C/Objective-C runtime (Swift is still written in C/C++ itself). Your plugin has to load your framework, which loads Swift. If your plugin loads in Swift, your version of Swift therefore gets loaded in for everybody, and if someone else comes along and tries to load in a different version of Swift, well... There's probably a better way of explaining it, but that's the gist as I understand it. P.S. For anyone who's curious about exporting a Swift framework to Sketch here's how I did it: 1. Set 'Always Embed Swift Standard Libraries' = YES. 2. Mark any classes you want to access from cocoascript with the following notation: @objc(ClassName) public class ClassName ...and not @objc public class ClassName as Apple's documentation suggests. When you use the latter notation, XCode assigns an auto-generated name to your class making it impossible to access from cocoascript using a predictable name. 3. Mark any functions you want to access from cocoascript as @objc public func myFunction() 4. Under Target > Build Phases > Headers, be sure that the classes you want to access from cocoascript are Public (for some reason, XCode doesn't always do this automatically). @objc public class ClassName @objc public func myFunction()
https://sketchplugins.com/d/164/8
CC-MAIN-2018-47
refinedweb
548
64.41
Hi Psychopy Community, Repost from earlier thread as some things have changed and I want to make sure this error and any solution is easy for others to find. I’m trying to create a MovieStim3 object, I’m getting an error that I’m not sure how to resolve, although now I’m not sure if I need to worry about it. Any help would be greatly appreciated! Potentially useful information about my setup: - Using psychopy standalone version 1.90.2, python 3 - Running on Windows 10 laptop - Dual monitor setup, second monitor UHD The Problem: When I try to create a MovieStim3 object. I get a “Fatal Python error” message. What has changed: I’ve been trying different things to figure out what is going on, and in particular I tried to make a short run of two movies in Builder view. Surprisingly, it ran, but gave me the same error after the movies finished playing. What is going on here? Should I be worried about this “fatal error”? I’m using moviepy as the backend in Builder (avbin did not play the movies at all and openCV did not properly sync sound and image and dropped many frames). The error seems to occur in a moviepy deconstructor. Minimal (Non)Working Example: import psychopy psychopy.useVersion('latest') from psychopy import monitors, visual, core expMonitor = monitors.Monitor('subjectMonitor') SCREEN_SIZE = (3840,2160) window2use = visual.Window( SCREEN_SIZE, fullscr=True, screen=1, monitor=expMonitor, color=[0,0,0], colorSpace='rgb') movieFullPath = r'C:\path\to\movies\testmovie.mp4' thisMovie = visual.MovieStim3(win=window2use, name='testmovie', noAudio = False, filename = movieFullPath) window2use.close() core.quit() Errors and Warnings this code produces: ##### Running: C:\Users\Megan\Documents\socEvalTask\socialEvaluationTask\psychopyPilot\MWE.py ##### 1.3457 WARNING User requested fullscreen with size [3840 2160], but screen is actually [2560, 1440]. Using actual size 3.5714 WARNING Couldn't measure a consistent frame rate. - Is your graphics card set to sync to vertical blank? - Are you running other processes on your computer? 3.8320 WARNING t of last frame was 26.46ms (=1/37) 3.8653 WARNING t of last frame was 27.20ms (=1/36) 3.8994 WARNING t of last frame was 27.77ms (=1/36) 3.9322 WARNING t of last frame was 25.60ms (=1/39) 3.9655 WARNING Multiple dropped frames have occurred - I'll stop bothering you about them! 5.4655 WARNING Couldn't measure a consistent frame rate. - Is your graphics card set to sync to vertical blank? - Are you running other processes on your computer? 5.4655 WARNING FrameRate could not be supplied by psychopy; defaulting to 60.0 5.7489 INFO Loaded SoundDevice with PortAudio V19.6.0-devel, revision 396fe4b6699ae929d3a685b3ef8a7e97396139a4 5.7490 INFO sound is using audioLib: sounddevice 7.1327 EXP Created testmovie = MovieStim3(__class__=<class 'psychopy.visual.movie3.MovieStim3'>, autoLog=True, color=UNKNOWN, colorSpace=UNKNOWN, depth=0.0, filename=str(...), flipHoriz=False, flipVert=False, fps=UNKNOWN, interpolate=True, loop=False, name='testmovie', noAudio=False, opacity=1.0, ori=0.0, pos=array([0., 0.]), size=array([1600., 1000.]), units='pix', vframe_callback=UNKNOWN, volume=UNKNOWN, win=Window(...)) 7.1900 EXP window1: mouseVisible = True Fatal Python error: PyImport_GetModuleDict: no module dictionary! Current thread 0x00001e6c (most recent call first): File "C:\Program Files (x86)\PsychoPy2_PY3\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 116 in __del__
https://discourse.psychopy.org/t/fatal-python-error-pyimport-getmoduledict-no-module-dictionary-when-creating-moviestim3-object/4731
CC-MAIN-2021-39
refinedweb
557
53.37
Test::Most - Most commonly needed test functions and features. Version 0.34 Instead of this: use strict; use warnings; use Test::Exception 0.88; use Test::Differences 0.500; use Test::Deep 0.106; use Test::Warn 0.11; use Test::More tests => 42; You type this: use Test::Most tests => 42; Test::Most exists to reduce boilerplate and to make your testing life easier. We provide "one stop shopping" for most commonly used testing modules. In fact, we often require the latest versions so that you get bug fixes through Test::Most and don't have to keep upgrading these modules separately. This module provides you with the most commonly used testing functions, along with automatically turning on strict and warning and gives you a bit more fine-grained control over your test suite. use Test::Most tests => 4, 'die'; ok 1, 'Normal calls to ok() should succeed'; is 2, 2, '... as should all passing tests'; eq_or_diff [3], [4], '... but failing tests should die'; ok 4, '... will never get to here'; As you can see, the eq_or_diff test will fail. Because 'die' is in the import list, the test program will halt at that point. If you do not want strict and warnings enabled, you must explicitly disable them. Thus, you must be explicit about what you want and no longer need to worry about accidentally forgetting them. use Test::Most tests => 4; no strict; no warnings; All functions from the following modules will automatically be exported into your namespace: Functions which are optionally exported from any of those modules must be referred to by their fully-qualified name: Test::Deep::render_stack( $var, $stack ); Several other functions are also automatically exported: die_on_fail die_on_fail; is_deeply $foo, bar, '... we throw an exception if this fails'; This function, if called, will cause the test program to throw a Test::Most::Exception, effectively halting the test. bail_on_fail bail_on_fail; is_deeply $foo, bar, '... we bail out if this fails'; This function, if called, will cause the test suite to BAIL_OUT() if any tests fail after it. restore_fail die_on_fail; is_deeply $foo, bar, '... we throw an exception if this fails'; restore_fail; cmp_bag(\@got, \@bag, '... we will not throw an exception if this fails'; This restores the original test failure behavior, so subsequent tests will no longer throw an exception or BAIL_OUT(). set_failure_handler If you prefer other behavior to 'die_on_fail' or 'bail_on_fail', you can set your own failure handler: set_failure_handler( sub { my $builder = shift; if ( $builder && $builder->{Test_Results}[-1] =~ /critical/ ) { send_admin_email("critical failure in tests"); } } ); It receives the Test::Builder instance as its only argument. Important: Note that if the failing test is the very last test run, then the $builder will likely be undefined. This is an unfortunate side effect of how Test::Builder has been designed. explain Similar to note(), the output will only be seen by the user by using the -v switch with prove or reading the raw TAP. Unlike note(), any reference in the argument list is automatically expanded using Data::Dumper. Thus, instead of this: my $self = Some::Object->new($id); use Data::Dumper; explain 'I was just created', Dumper($self); You can now just do this: my $self = Some::Object->new($id); explain 'I was just created: ', $self; That output will look similar to: I was just created: bless( { 'id' => 2, 'stack' => [] }, 'Some::Object' ) Note that the "dumpered" output has the Data::Dumper variables $Indent, Sortkeys and Terse all set to the value of 1 (one). This allows for a much cleaner diagnostic output and at the present time cannot be overridden. Note that Test::More's explain acts differently. This explain is equivalent to note explain in Test::More. show Experimental. Just like explain, but also tries to show you the lexical variable names: my $var = 3; my @array = qw/ foo bar /; show $var, \@array; __END__ $var = 3; @array = [ 'foo', 'bar' ]; It will show $VAR1, $VAR2 ... $VAR_N for every variable it cannot figure out the variable name to: my @array = qw/ foo bar /; show @array; __END__ $VAR1 = 'foo'; $VAR2 = 'bar'; Note that this relies on Data::Dumper::Names version 0.03 or greater. If this is not present, it will warn and call explain instead. Also, it can only show the names for lexical variables. Globals such as %ENV or %@ are not accessed via PadWalker and thus cannot be shown. It would be nice to find a workaround for this. always_explainand always_show These are identical to explain and show, but like Test::More's diag function, these will always emit output, regardless of whether or not you're in verbose mode. all_done DEPRECATED. Use the new done_testing() (added in Test::More since 0.87_01). Instead. We're leaving this in here for a long deprecation cycle. After a while, we might even start warning. If the plan is specified as defer_plan, you may call &all_done at the end of the test with an optional test number. This lets you set the plan without knowing the plan before you run the tests. If you call it without a test number, the tests will still fail if you don't get to the end of the test. This is useful if you don't want to specify a plan but the tests exit unexpectedly. For example, the following would pass with no_plan but fails with all_done. use Test::More 'defer_plan'; ok 1; exit; ok 2; all_done; See "Deferred plans" for more information. The following will be exported only if requested: timeit Prototype: timeit(&;$) This function will warn if Time::HiRes is not installed. The test will still be run, but no timing information will be displayed. use Test::Most 'timeit'; timeit { is expensive_function(), $some_value, $message } "expensive_function()"; timeit { is expensive_function(), $some_value, $message }; timeit accepts a code reference and an optional message. After the test is run, will explain the time of the function using Time::HiRes. If a message is supplied, it will be formatted as: sprintf "$message: took %s seconds" => $time; Otherwise, it will be formatted as: sprintf "$filename line $line: took %s seconds" => $time; Sometimes you want your test suite to throw an exception or BAIL_OUT() if a test fails. In order to provide maximum flexibility, there are three ways to accomplish each of these. use Test::Most 'die', tests => 7; use Test::Most qw< no_plan bail >; If die or bail is anywhere in the import list, the test program/suite will throw a Test::Most::Exception or BAIL_OUT() as appropriate the first time a test fails. Calling restore_fail anywhere in the test program will restore the original behavior (not throwing an exception or bailing out). use Test::Most 'no_plan'; ok $bar, 'The test suite will continue if this passes'; die_on_fail; is_deeply $foo, bar, '... we throw an exception if this fails'; restore_fail; ok $baz, 'The test suite will continue if this passes'; The die_on_fail and bail_on_fail functions will automatically set the desired behavior at runtime. DIE_ON_FAIL=1 prove t/ BAIL_ON_FAIL=1 prove t/ If the DIE_ON_FAIL or BAIL_ON_FAIL environment variables are true, any tests which use Test::Most will throw an exception or call BAIL_OUT on test failure. It used to be that this module would produce a warning when used with Moose: Prototype mismatch: sub main::blessed ($) vs none This was because Test::Deep exported a blessed() function by default, but its prototype did not match the Moose version's prototype. We now exclude the Test::Deep version by default. If you need it, you can call the fully-qualified version or request it on the command line: use Test::Most 'blessed'; Note that as of version 0.34, reftype is also excluded from Test::Deep's import list. This was causing issues with people trying to use Scalar::Util's reftype function. Sometimes you want a exclude a particular test module. For example, Test::Deep, when used with Moose, produces the following warning: Prototype mismatch: sub main::blessed ($) vs none You can exclude this with by adding the module to the import list with a '-' symbol in front: use Test::Most tests => 42, '-Test::Deep'; See for more information. Sometimes you don't want to exclude an entire test module, but just a particular symbol that is causing issues You can exclude the symbol(s) in the standard way, by specifying the symbol in the import list with a '!' in front: use Test::Most tests => 42, '!throws_ok'; DEPRECATED and will be removed in some future release of this module. Using defer_plan will carp(). Use done_testing() from Test::More instead. use Test::Most qw<defer_plan>; use My::Tests; my $test_count = My::Tests->run; all_done($test_count); Sometimes it's difficult to know the plan up front, but you can calculate the plan as your tests run. As a result, you want to defer the plan until the end of the test. Typically, the best you can do is this: use Test::More 'no_plan'; use My::Tests; My::Tests->run; But when you do that, Test::Builder merely asserts that the number of tests you ran is the number of tests. Until now, there was no way of asserting that the number of tests you expected is the number of tests unless you do so before any tests have run. This fixes that problem. We generally require the latest stable versions of various test modules. Why? Because they have bug fixes and new features. You don't want to have to keep remembering them, so periodically we'll release new versions of Test::Most just for bug fixes. use ok We do not bundle Test::use::ok, though it's been requested. That's because use_ok is broken, but Test::use::ok is also subtly broken (and a touch harder to fix). See for more information. If you want to test if you can use a module, just use it. If it fails, the test will still fail and that's the desired result. People want more control over their test suites. Sometimes when you see hundreds of tests failing and whizzing by, you want the test suite to simply halt on the first failure. This module gives you that control. As for the reasons for the four test modules chosen, I ran code over a local copy of the CPAN to find the most commonly used testing modules. Here's the top twenty as of January 2010 (the numbers are different because we're now counting distributions which use a given module rather than simply the number of times a module is used). 1 Test::More 14111 2 Test 1736 3 Test::Exception 744 4 Test::Simple 331 5 Test::Pod 328 6 Test::Pod::Coverage 274 7 Test::Perl::Critic 248 8 Test::Base 228 9 Test::NoWarnings 155 10 Test::Distribution 142 11 Test::Kwalitee 138 12 Test::Deep 128 13 Test::Warn 127 14 Test::Differences 102 15 Test::Spelling 101 16 Test::MockObject 87 17 Test::Builder::Tester 84 18 Test::WWW::Mechanize::Catalyst 79 19 Test::UseAllModules 63 20 Test::YAML::Meta 61 Test::Most is number 24 on that list, if you're curious. See. The modules chosen seemed the best fit for what Test::Most is trying to do. As of 0.02, we've added Test::Warn by request. It's not in the top ten, but it's a great and useful module. Curtis Poe, <ovid at cpan.org> Please report any bugs or feature requests to bug-test-extended at rt.cpan.org, or through the web interface at. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. You can find documentation for this module with the perldoc command. perldoc Test::Most You can also look for information at: Sometimes you don't know the number of tests you will run when you use Test::More. The plan() function allows you to delay specifying the plan, but you must still call it before the tests are run. This is an error: use Test::More; my $tests = 0; foreach my $test ( my $count = run($test); # assumes tests are being run $tests += $count; } plan($tests); The way around this is typically to use 'no_plan' and when the tests are done, Test::Builder merely sets the plan to the number of tests run. We'd like for the programmer to specify this number instead of letting Test::Builder do it. However, Test::Builder internals are a bit difficult to work with, so we're delaying this feature. if ( $some_condition ) { skip $message, $num_tests; } else { # run those tests } That would be cleaner and I might add it if enough people want it. Because of how Perl handles arguments, and because diagnostics are not really part of the Test Anything Protocol, what actually happens internally is that we note that a test has failed and we throw an exception or bail out as soon as the next test is called (but before it runs). This means that its arguments are automatically evaluated before we can take action: use Test::Most qw<no_plan die>; ok $foo, 'Die if this fails'; ok factorial(123456), '... but wait a loooong time before you throw an exception'; Many thanks to perl-qa for arguing about this so much that I just went ahead and did it :) Thanks to Aristotle for suggesting a better way to die or bailout. Thanks to 'swillert' () for suggesting a better implementation of my "dumper explain" idea (). This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/~ovid/Test-Most/lib/Test/Most.pm
CC-MAIN-2016-18
refinedweb
2,250
69.31
Microsoft Ends Era Of Closed File Formats 651 RzUpAnmsCwrds writes "According to an MSDN Channel 9 interview with an Office file-format developer, the next version of Microsoft Office (Office 12) will default to newly-developed XML file formats in Word, Excel, and PowerPoint. The new formats will apparently include XML files along with other files (images, etc) inside of a Zip file. Microsoft will also be providing extensive documentation of the new format to the public through MSDN. The developer likewise announced that Microsoft would be releasing updates for Office 2000, XP, and 2003 to read and write the new formats when the new version of Office is released. If this interview is correct, it could mean the beginning of the end of Microsoft's proprietary file formats." Coverage at Beta News, Information Week, and the Washington Post. Loosing lock-in capability? (Score:5, Interesting) Of course this assumes that lock-in was one of their goals with a propietary format Re:Loosing lock-in capability? (Score:2) Re:Loosing lock-in capability? (Score:5, Insightful) In this respect, Microsoft needs open formats just as much as anyone. Ever try to write a server-based system that reads information from DOC files? Using winword.exe with automation just doesn't really work. XML lets MS use a relatively lightweight parser in a server-based system. Oh, and changing the default fileformat will surely spur some upgrades, but from what I've seen the corporate market is generally not in a big hurry to get onto the latest version of Office. I don't foresee a repeat of Office 97. Last 10 years, actually. :-) (Score:2) Re:Loosing lock-in capability? (Score:3, Informative) Re:Loosing lock-in capability? (Score:3, Interesting) Re:Losing lock-in capability? (Score:2) Microsoft has lots (and lots and lots) of very very smart, motivated developers and marketers, and there is always the hope that they can begin to use those resources to build a product that really competes without resotring to bogus, short term ploys like lock-in. Hmmm... Who turned on my "hopefulness neuron" today? Re:Loosing lock-in capability? (Score:3, Informative) Re:Loosing lock-in capability? (Score:3, Informative) Lock-in continues via DRM (Score:5, Insightful) The interesting thing is that all this server based control and logging of DMR'd functions gives an enormous boost to the type of information available for international and corporate espionage. Through backdoors, security holes or escrow keys it was possible before to get only the documents themselves for the most part. Now it's possible to monitor who's collaborating with who, and see everyone in the distribution chain. That much can be guessed even now during the vaporware stages. However, as more technical information becomes available it will be possible to guess whether these same functions can be used for more than monitoring and can actually be used to stifle or suppress dissent or specific individuals or groups. Re:Lock-in continues via DRM (Score:5, Informative) It hasn't been true since at least NT4 SP6a, when NT4 achieved a C2 rating *WITH* network. Windows 2000 achieved CC both with and without networking. The NT4 link is no longer around on MS's site, but there are still some pages out there that reference it: Such as this one [windowsnetworking.com] And here is Win2k [microsoft.com] Re:Loosing lock-in capability? (Score:5, Interesting) Re:Loosing lock-in capability? No... (Score:3, Informative) Or not. [microsoft.com] Re:Loosing lock-in capability? No... (Score:4, Informative) Re:Loosing lock-in capability? No... (Score:3, Informative) But, note that the patent and copyright provisions in the license for the Office 2003 XML Reference Schemas require you to include a notice of attribution in your program. I'm just guessing that the GPL's noted incompatibility with an advertising clause is what breaks compatibility here. MS being MS, they could well have done it intentionally; that said, an advertising clause might also have simply been seen as appropriate. Who knows. Re:Loosing lock-in capability? No... (Score:3, Insightful) That said, I don't believe the GPL incompatibility was intentional; I believe it to be a side-effect of what MS thought was an appropriate way to make sure that their patents and patent issues were appropriately labeled in software using their schema. Yes and No (Score:2, Interesting) Re:Yes and No (Score:4, Informative) Watch the video - the entire file format is completely open. He admitted that inside the ZIP they are currently storing the binary copy to make it easier to test and profile against the formats, but when Office 12 is released it'll just be the one XML, completely open format. He also made a point that they are going to have 'thousands' of examples on MSDN, along with very detailed documentation and whitepapers. Now whether it's patented or not, I don't know. But this is a _VERY_ big step for Microsoft. It's going to make translating between this and OASIS (which OpenOffice2 and a lot of others are considering/implementing as their default) as simple as an XSLT transformation. Re:Yes and No (Score:3, Informative) So they claim. (Score:5, Insightful) Honestly, I am not going to believe it until I see it. Microsoft has lied before. It's quite possible they don't intend to open their file formats at all, they just intend to make the Washington Post and its readers think they've opened their file formats. In the meantime, if Microsoft actually wanted to "end the era of closed file formats", all they'd have to do is, you know, actually comply with the letter of the antitrust decision currently handed down against them in the E.U. and the spirit of the toothless antitrust "settlement" currently in effect against them in the U.S.. Mysteriously, they haven't. Re:Yes and No (Score:3, Funny) ZIP patent... (Score:3, Interesting) Re:ZIP patent... (Score:2) Re:ZIP patent... (Score:2) Re:ZIP patent... (Score:2) Re:ZIP patent... (Score:4, Informative) gzip and zip are completely different things. gzip compresses a stream (and does a much better job than compress, which it has replaced entirely. However, gzip is slowly being replazed by bzip2 nowadays), whereas zip is an archive format that can store individual (usually compressed) files. The huge advantage of zip over compressed tar archives comes from the fact that you have random access, i.e. can extract a single file from a potentially HUGE archive). GIF had patent issues with the LZW-Algorithm it used. The patent has expired recently, but the GIF issue is completely unrelated to ZIP (ZIP uses LZ77). About the patent issue: There are a dozen or so zip-related patents, but they're all highly specific and shouldn't stop anyone from using zip, or even writing a zip utility. See also Patents on data compression algorithms [sc.ehu.es]. Re:ZIP patent... (Score:3, Insightful) Actually, I don't find much of an advantage. In my experience, even if you are trying to extract a tiny file from a large archive, it still seeks through the majority of the zip file, and is only slightly faster than uncompressing the entire thing. Despite that, tar and gzip could be even better. A little programming and you could modify Re:ZIP patent... (Score:2) That would be the LZW [wikipedia.org] patent held by Unisys (and IBM in some countries). You're right in that it has expired in most countries now. Gzip was made as an alternative to the Unix compress program because it used LZW, not to PKZIP. Gzip uses the LZ algorithm, which is older and slightly slower but compresses better. Convenient... (Score:4, Interesting) And whatever happened to Office Integrated Rights Management [microsoft.com], essentially a DRM for Office documents (New Office locks down documents [com.com]) that (of course) requires a Windows server to administer, and only works with Microsoft Office? You don't think that they're just going to let that go by the wayside, do you? And what about patents? Sure, OpenOffice is great, but commercial enterprises will stick with commercial solutions for which there is support. And yes, this could be built for something like OpenOffice (and indeed exists for StarOffice), just as it has been for Red Hat, but I can't see this as anything more than a much belated, empty gesture on Microsoft's part. This sums it up: "Microsoft is doing this as a way to protect its presence on the desktop." Microsoft even dug up Charles Goldfarb [wikipedia.org], "co-inventor of the concept of markup languages", for its press release to say, "Making XML the default Office file format is, for me, the culmination of a 35-year dream," Charles F. Goldfarb, the inventor of the markup language technology, said in a statement released by Microsoft. Nice touch. Also, "Microsoft Ends Era Of Closed File Formats" is a little overreaching, don't you think? They're looking for the biggest lock-in of all with the proprietary Windows Media formats. Microsoft wants to be everywhere there is any kind of media, and it's NOT open. Boy, I can't wait to live in a world where Microsoft controls and meters content and has everyone from the end consumer to cable, satellite, and telecom operators, movie and TV production houses, and everyone in between by the balls, which is exactly what will happen if they get their way. (And submission to SMPTE *hardly* means anything. Standards are standards AFTER they've been vetted by standards bodies, have had the patent searches and pools completed, etc., and have been, you know, actually approved. Not when they've been "submitted for consideration". Further, that gesture is nothing more than an attempt to get pinhead PHB-type managers and executives on board with Microsoft when their technical underlings are pulling for open standards like H.264 - then Microsoft can shoot back to the management, Hey, we're just as open as the MPEG family of standards! Look, we even submitted our codec to SMPTE! It's not our fault they take so long to approve things! Do you really want all that H-dot-whatever-gobbledeygook that your oddball IT guys are talking about? After all, that's what *Apple* uses. You don't want an Apple technology, do you? Go with us; you know Microsoft is the right choice for your 18-million-customer cable service! [eweek.com] Utter bullshit. And ignores the fact that all of the codec improvements and tools will NOT be open; the SMPTE submission is nothing more than a thinly veiled attempt to put Windows Media everywhere as well by claiming to be "open" when they're anything but.) Re:Convenient... (Score:5, Insightful) That's exactly what I was thinking. If Microsoft was really opening up Office, why didn't they go for the OASIS Spec [oasis-open.org]? Me thinks that this is an attempt by Microsoft to lead the industry around by the nose, thus solidifying their place as "Industry Leader". And with a proprietary document format, they can make minor, but frustrating, changes every version just to keep the competition on its toes. Re:Convenient... (Score:2, Insightful) Right now, they're choosing the middle ground - opening up a format in a way that they have the upper hand and yet, folks can't fault them. If you were a company whose motive was profit, would you really care about doing something that would make you part of the pack? MS sees itself as being different from the pack, and so, this is a logical choice for them. It may not the perfect choice or the right one, bu Re:Convenient... (Score:2) I am tired of this "they're a business, they are interested in profit not xxxx". Just because they're a business it don't mean that they're free of any responsibility. They must have responsibility, and those responsibilities must be enforced by the government. Microsoft should be punished if they attempt to lock you in so you can't have access your data (this include data made for you) unless you pay them some money. Every format should be open and available to other developers (be them open source or not) Re:Convenient... (Score:2) Also, I am sure there will be some features missing in the OASIS spec, and that means Microsoft has to go and lobby with OASIS to get it implemented... all this so that other competitors can read/write its file formats much easier? Don't think so. Re:Convenient... (Score:2) Bullocks. We're talking about a file format for a word processor and a spreadsheet. If OOo and MSOffice can interchange formats today (not to mention all the extra "export" formats that MSOffice handles) then there's no reason why they can't follow the OASIS spec. The worst case is that MSOFfice adds a few features for some of Re:Convenient... (Score:3, Insightful) If MS needs extensions, that's what namespaces are for. As long as MS extensions don't change formatting functionality (this is really not rocket science, Word is not an innovator here), they can tack whatever metadata they need into the file format and still have it be portable. If you don't believe me, look at what Inkscape has done with SVG. Psodipodi built on it, adding a namespace to provide their needed data. Inkscape did the same on top of that. It prod Re:Convenient... (Score:2) Re:Convenient... (Score:4, Insightful) I can't see this as anything more than a much belated, empty gesture on Microsoft's part. is true from the MS perspective, but that doesn't mean nothing good can come of it. Having a documented XML format could do wonders for OpenOffice compatibility, which wouldn't necessarily put a dent in Microsoft's monopoly, but it would make life a lot easier for those of us who don't want to participate in it. I'm not saying it'll pan out, just that there are possible real benefits. Re:Convenient... (Score:2) Life must be interesting on your planet, Dave. First of all, video file formats are hardly a concern of "IT" -- this is really all being hashed out in Hollywood boardrooms, and is completely offtopic in a discussion about MS Office. Second, it really boils down to either giving Dolby a bunch of money or giving Microsoft a bunc Re:Convenient... (Score:2) Sure, OpenOffice is great, but commercial enterprises will stick with commercial solutions for which there is support. And yes, this could be built for something like OpenOffice (and indeed exists for StarOffice) But thanks! Thus to be a cynic (Score:2) So i will belive it when i see it MS don't seem to be that eager to open anything up , just look at the recent fun the EU courts are having Published Specs is Not Enough (Score:2, Informative) Remember, GIF was a completely open format -- but that didn't mean Open Source software got to use them freely. Re:Published Specs is Not Enough (Score:2) Nope. The NDA will forbid making a competing product. Microsoft responding to needs of the user (Score:2) To truly be the end of an era, they should give out the complete specs on their formats as well... I know it isn't going to happen but that would be more complete. Re:Microsoft responding to needs of the user (Score:2) From your post: To truly be the end of an era, they should give out the complete specs on their formats as well... I know it isn't going to happen but that would be more complete. From the blurb: Microsoft will also be providing extensive documentation of the new format to the public through MSDN. It's one thing not to RTFA ....but at least you could read the fucking headline. XtraML (Score:2, Interesting) Re:XtraML (Score:2) Heard this before (Score:2) Re:Heard this before (Score:5, Interesting) There's XML and there's XML (Score:2) (I say this having just gone through my semi-annual search of third-party conversion software in the neverending quest to figure out a way to get from Word documents to rationally structured XML.) Re:There's XML and there's XML (Score:2) I say this having just gone through my semi-annual search of third-party conversion software in the neverending quest to figure out a way to get from Word documents to rationally structured XML. Have you tried Webworks Publisher [webworks.com]? I've had reasonable success outputting XML from Framemaker with it and I know they have a version for Word as well. It is closed/proprietary/expensive but if you are serious about converting Word docs it is worth a try. When I used it, it was somewhat buggy, but by far the best Separate information from presentation? (Score:2) For instance, will the format be <font name="arial" size="18" style="bold">my heading</font> or will it be <heading level="2">my heading</heading> I definitely prefer the latter (with information and presentation separated), but sadly I think it is more likely that we'll see the former. If you have the presentation separately then it is much easier to for instance standardize a look a feel within a c Re:Separate information from presentation? (Score:2) If you are using the styling tools in MS Word/Excel/whatever, and applying a 'headline' style to all of the headlines, then it'll do the second. However if you don't bother and just use the font pulldowns and size pulldown menus it will do the first. So really, it all depends on how you set it up. Re:Separate information from presentation? (Score:2) <p style="Title 1">My heading</p>. If the author hasn't used styles, you will have something like <font name="arial" size="18" style="bold">My heading</font> Since MS Word has to be able to read the file and associate styles with paragraphs, I don't see how they would do it without mentioning the name of the style used by a paragraph somewhere in Re:Separate information from presentation? (Score:2) Then I'd like a way to enforce only the use of styles. This could be a property of the document or maybe of the template. re-inventing the wheel (Score:2) I'll believe it when I see it (Score:2) No doubt it will be "open" to anybody willing to sign something saying they won't develop a competing product or tell anybody what they read, or something equally worthless. They may SAY they won't do that, but I'll have to actually see it happen to believe it and even then I'll be looking the gift horse carefully in the mouth. Any paten Hopefully the end of .doc, etc incompatibilities (Score:3, Insightful) Re:Hopefully the end of .doc, etc incompatibilitie (Score:2) > Hopefully this file format change will bring about the end of ever-changing file formats from one version of an app to the next. Somehow I doubt that the release of yet another format is going to mean the end of ever-changing formats. Hold on a second, that's not next... (Score:2) First, an earthquake. Then the sun must be dark as sack cloth and the moon as red as blood...and then Microsoft opens up their file formats. The big question (Score:2) Re:The big question (Score:2) Consider this. (Score:5, Interesting) Anyway, my point is that MS is making it clear that they're not threatened by competing packages, and I'm not entirely sure why not. OOo could easily replace Office for many (I hesitate to say most) users, and if we switch to totally open formats, they'll be able to interoperate without any difficulties. I'm not trying to say that OOo is in a position to hurt Office...but I'm curious if it might be. MS doesn't seem to think so, and I'm really, really wondering what makes them so nonchalant. Catching up, but still missing OpenDocument (Score:2, Insightful) The one thing that these others have in common, that MS Office lacks, is support for the OpenDocument [eu.int] DTD. OpenOffice.org v2 will use OpenDocument as its main format. Note that many of the articles linked to by the original post express skepticism about how open MS' XML will actually be. Recall that in the last Re:Catching up, but still missing OpenDocument (Score:2) Shhhh. It's coming in a few months. And remember, Microsoft was the first to do it. Anyone else who claims to be doing it added the feature after Microsoft did, and their version isn't as good. You can get a virus from exporting to PDF using OpenOffice Yeah, Right (Score:2) ASPX runtime error (Score:2) LMAO.. A refresh seems have it just report a generic (properly rendered) "there is a problem with the forums" page. 75% file size savings (Score:5, Informative) Nice marketing ploy. Too bad it's a scam (Score:2, Insightful) All kidding aside, I think any hope about this is misplaced. There will no doubt be numerous restrictions on the use of the format information. There's also the fact that MS has Re:Nice marketing ploy. Too bad it's a scam (Score:5, Informative) Re:Nice marketing ploy. Too bad it's a scam (Score:3, Informative) Just TRY to use the Office XML Specification in an Open Source application. Go ahead, I dare you. Re:Nice marketing ploy. Too bad it's a scam (Score:5, Informative) Looks kinda like a BSD license, don't it? Yeah, especially the part that says "You are not licensed to sublicense or transfer your rights." Re:Nice marketing ploy. Too bad it's a scam (Score:4, Informative) From the FAQ [microsoft.com]: Yay! (Score:2) Maybe now that will end. Maybe I will be able to use the faster loading kword than OO soon too. It will be interesting to watch the aftermath. With document format soon to be history office applications will need to compete on price and quality. It will be interesting to see who the winners will be with the format question out of the way. Will quality improve? Will price improve? Will people go with whatever is cheap Already doing it (Score:2) I've been doing this for a while: Yawn. This is a great idea, but not anything new. Microsoft should have done this years ago, as there is an obvious benefit to their customers and innovation is obviously moving to open formats. They would have done it earlier if they didn't need so depserately competition to spur them into action. IE7, XML Office ... what's next? Bash at the Windows DOS prompt? Microsoft begins era of patent encumbered formats (Score:5, Insightful) In particular; consider "Microsoft may have patents and/or patent applications that are necessary for you to license in order to make, sell, or distribute software programs that read or write files that comply with the Microsoft specifications for the Office Schemas." taken from the same page... What changed? How is that an "improvement" exactly? Re:Microsoft begins era of patent encumbered forma (Score:2) Presumably, much of this is going away since they are saying the new version will be open, but what is "open" to MS may not be quite what you'd expect Re:Microsoft begins era of patent encumbered forma (Score:3, Informative) What about existing docs? (Score:2) Re:What about existing docs? (Score:2) Will office 12 include a converter? (Score:2) Microsoft = Big Innovators (Score:2) "Our Glorious Scientists have slashed disease rates ten times!" Yes, when you no longer sleep in your own feces and the whole ten person family doesn't eat with their unwashed hands from the same bowl, it does tend to improve hygeine. Microsoft.dieplzkthx(); New extentions (Score:2) Great, now I'll have people calling me up asking "what program do I use to open a 'dot D O C X' file with?" Patents can be lost (Score:3, Informative) However, Microsoft may be walking a tight line here (at least in theory) as they are a convicted Monopolist. I refer you to this quote from Nolo Press' "Patent It Yourself" (p 1/8), on how Patents can be lost: "The patent owner engages in certain defined types of illegal conduct, that is, commits antitru Re:Patents? (Score:2) Re:Patents? (Score:4, Informative) You fucking troll, since when microsoft's binary document formats are documented, or fast? Implementing a file format as binary data or even a simple SGML structure such as RTF means less overhead. Using XML you have to run an XML parser, and the file is more freeform. There are no set data structures, it is just a stream of text. With a binary format you can structure it in such a way that you can read a header in and know exactly where to seek in the file to get the information you need. With XML you are pretty much stuck reading sequentially and figuring things out as you go along. Sure, an XML parser library may make it easier, but behind the scenes it is still parsing that stream and processing each tag one at a time. Re:Patents? (Score:4, Informative) A well-designed binary format makes much more sense than XML, in this I concur with you, but XML is better than current microsoft's doc formats in that it would be easier to figure out the inner workings of the format, and making struggle for compatibility a much less gory task. Re:Patents? (Score:3, Insightful) Oh puuuulllleeze. Such concerns might be relevant for a C64 or perhaps even a MacPlus. However, for small consumer documents such notions are absurd. This isn't exactly someone's corporate data warehouse we're talking about here. Re:Patents? (Score:3, Informative) Take a look at a high school senior's Publisher & PowerPoint files some time. They are HUGE, especially with lots of pictures (as instructed). It's not unusual to see file sizes 100-250mb on an ordinary PP or Pub file. And boy do they take a long time to open across a network on P4 computers with lots of ram. We just had a graduation PowerPoint file that was in the neighborhood of 700mb and it took a co Re:Patents? (Score:2) Re:Patents? (Score:5, Insightful) I use Open Office exclusively and have for the past couple of years. Reading the files in certainly isn't a problem for me. The only files that are slow to load are the master document files, and that's because they link to dozens of other files. The XML specification is being expanded (it might already be done) to allow binary formats. There are good reasons, though, why it's best to keep data files in straight XML text format. It eliminates the need to worry about machine architecture. Little endian or big endian, it maks no difference to you. The files are perfectly portable across platforms, which is increasingly important these days. XML files zip very nicely, making them almost as small as a corresponding binary file. It is far easier to provide backwards compatability to earlier file formats when you are using XML than if you are using binary file formats. With XML, if it sees a tag it doesn't understand, the parser ignores it. If a binary file format loader sees stuff it doesn't understand, it bails out with an illegal file format error. When you move to a new expanded file format with XML, you don't have to write a conversion utility. Since you are merely adding new tags, your program can read any of your old data just fine, then add the appropriate tags and new data. This saves a great deal of trouble for programers. Machines are fast and cheap. People are slow and expensive. It is far better to have our computers do a little extra work on loading a text file and eliminate conversion utilities and complicated loading routines that a prone to bugs. Visual Diff of application files (Score:3, Insightful) One of my favourite features of XML vs. binary application files is that, if you run diff on two XML files -- say, SVG drawings --, you can actually read how that drawing has been changed, just like with code or any other text file. It gets difficult to visualise on larger changes of course, but that's not unlike code either. I think, if people start Re:Patents? (Score:3, Insightful) The term you are looking for here is 'self describing structure'. If you have data in the form of LISP S-Expressions you know where structures start and stop. If you have just one document in that format you can pretty much work out the entire file format - or at le Re:Patents? (Score:2) Great. Now we have a bloated XML-format instead of a fast documented binary-format. A lose-lose situation. This will make Office as slow as cOOpycatOffice. Good job, morons. Dig your own grave. Good job, moron. Post as absolutely ignorantly as possible. 1)Where is this alleged "fast documented binary-format[sic]"? I haven't seen it. 2)What information do you have that suggests that the XML format will be bloated? 3)Even if we take 1 and 2 as given, I only see one "lose" what's the "lose-lose" about? Re:Patents? (Score:3, Interesting) While VB.Net has its admirers, I think Mono was more a response to the need to interoperate and prevent MS from taking over Net apps development and locking it in to MS languages, more than it was any "admiration". Re:Patents? (Score:3, Interesting) (Disclaimer: They might be using it, but TFA doesn't mention it and it wouldn't fit with their MO.) Re:Own Goal? (Score:2) not that its a bad thing... I just think this is their real motives.. Re:Existing formats? (Score:2) 1.) Stop OpenOffice migrations (why migrate when we can just wait for MS to come out with their solution and we'll just buy that) 2.) Get people to upgrade to the next Office. #1 is typical of MS - promise something, people wait, your competition can't survive when their business dries up, then you kill the project. Problem is, this isn't a pay-for product, so it's not going to go away. #2 is the real thing - people will buy the next version of office, which is a huge problem Re:Sheesh (Score:2) More like "Microsoft states that it is doing something Slashdot has wanted them to do for ages [open up their formats in such a way that they compete on a level playing-field and compete on merit, rather than lock-in plus the network effect], and slashdot finds the faults that show that Microsoft are in fact doing no such thing". Re:Sheesh (Score:2, Informative) Leaving aside that fact that, like you, Slashdot is not an intelligent entity with needs and desires, this is not what we wanted. We want an open, documented and non-patent encumbered format that allows interoperability between Office and other software. That is not what this is. Another poster has already provided a link that will tell you everything you need Re:Open Office might benefit... (Score:2) You can't let these Open Source junkies get in the way of REAL productivity. Their "Something for nothing" mentality is absurd. You get what you pay for, and something that's free clearly isn't good enough to justify charging money. And considering some of the crap the charge money for, that's saying something. Microsoft all the way baby. Microsoft all the way.
https://slashdot.org/story/05/06/02/1231253/microsoft-ends-era-of-closed-file-formats
CC-MAIN-2018-22
refinedweb
5,396
63.09
Edit 2/8/2010: Updating code samples for recent language changes. In my last post I introduced Active Patterns. Sure they seem neat, but what do you actually do with them?. This post coverage how to leverage Active Patterns to make your code simpler and easier to understand. In particular, how you can use Regular Expressions in Active Patterns. Our first pair of examples will show how to simplify the code required to extract groups from regular expressions. If you have ever needed to do a lot of string parsing, you probably know how tedious Regular Expressions can be. But with Active Patterns we make the matching not only straight forward but fit well into the ‘match and extract’ workflow. We will define two Active Patterns, first a Parameterized Active Pattern that will return the match group given a regex and input string. The second Active Pattern will take that match group and return three sub group values. For example, parsing a simple DateTime string or the version number from the F# Interactive window. Note how the second Active Pattern, Match3, calls into the first using ‘match (|Match|_|) pat inp with’. open System open System.Text.RegularExpressions (* Returns the first match group if applicable. *) let (|Match|_|) (pat:string) (inp:string) = let m = Regex.Match(inp, pat) in // Note the List.tl, since the first group is always the entirety of the matched string. if m.Success then Some (List.tail [ for g in m.Groups -> g.Value ]) else None (* Expects the match to find exactly three groups, and returns them. *) let (|Match3|_|) (pat:string) (inp:string) = match (|Match|_|) pat inp with | Some (fst :: snd :: trd :: []) -> Some (fst, snd, trd) | Some [] -> failwith “Match3 succeeded, but no groups found. Use ‘(.*)’ to capture groups” | Some _ -> failwith “Match3 succeeded, but did not find exactly three matches.” | None -> None // —————————————————————————- // DateTime.Now.ToString() = “2/22/2008 3:48:13 PM” let month, day, year = match DateTime.Now.ToString() with | Match3 “(.*)/(.*)/(.*).*” (a,b,c) -> (a,b,c) | _ -> failwith “Match Not Found.” let fsiStartupText = @” F# Version 2.0.0.0, compiling for .NET Framework Version v2.0.50727″; let major, minor, dot = match fsiStartupText with | Match3 “.*F# Version (\d+)\.(\d+)\.(\d+)\.*” (a,b,c) -> (a,b,c) | _ -> failwith “Match not found.” A More Complex Example The code seems simple enough, but notice how the Active Pattern removes any need to deal with RegularExpression namespace entirely. You simply match the input string with the regex string and get a tuple of values back. We can take this concept one step further and show a more complex example. Consider the task of extracting all the URLs from a webpage. To do this we will use two Active Patterns. One to convert an HTML blob into a list of URLs (RegEx GroupCollections) and a second to normalize relative URL paths (“/foo.aspx” => “http://…/foo.aspx”) . (* Ensures that the input string contains given the prefix. *) let (|EnsurePrefix|) (prefix:string) (str:string) = if not (str.StartsWith(prefix)) then prefix + str else str (* Returns all match groups if applicable. *) let (|Matches|_|) (pat:string) (inp:string) = let m = Regex.Matches(inp, pat) in // Note the List.tl, since the first group is always the entirety of the matched string. if m.Count > 0 then Some (List.tail [ for g in m -> g.Value ]) else None (* Breaks up the first group of the given regular expression. *) let (|Match1|_|) (pat:string) (inp:string) = match (|Match|_|) pat inp with | Some (fst :: []) -> Some (fst) | Some [] -> failwith “Match3 succeeded, but no groups found. Use ‘(.*)’ to capture groups.” | Some _ -> failwith “Match3 succeeded, but did not find exactly one match.” | None -> None // —————————————————————————- open System.Net open System.IO // Returns the HTML from the designated URL let http (url : string) = let req = WebRequest.Create(url) // ‘use’ is equivalent to ‘using’ in C# for an IDisposable use resp = req.GetResponse() let stream = resp.GetResponseStream() let reader = new StreamReader(stream) let html = reader.ReadToEnd() html // Get all URLs from an HTML blob let getOutgoingUrls html = // Regex for URLs let linkPat = “href=\”([^\”]*)\”” match html with // The matches are the strings which our Regex matched. We need // to trim out the ‘href=’ part, since that is part of the rx matches collection. | Matches linkPat urls -> urls |> List.map (fun url -> match (|Match1|_|) “href=(.*)” url with | Some(justUrl) -> justUrl | _ -> failwith “Unexpected URL format.”) | _ -> [] // Maps relative URLs to their fully-qualified path let normalizeRelativeUrls root urls = urls |> List.map (fun url -> (|EnsurePrefix|) root url) // —————————————————————————- let blogUrl = “” let blogHtml = http blogUrl printfn “Printing links from %s…” blogUrl blogHtml |> getOutgoingUrls |> normalizeRelativeUrls blogUrl |> List.iter (fun url -> printfn “%s” url) As you can see, Active Patterns are a powerful addition to F# and definitely something to keep in mind when you find yourself writing a lot of repetitive code. PingBack from In response to an earlier post a reader wrote: Sent From: namin Subject: (|EnsurePrefix|) — why is it I’m trying to get a grip on active patterns, but in this example I’m having a hard time grasping how their use has a benefit over functions. In particular, it seems to me that the (|Match1|) and the (|EnsurePrefix|) patterns could have just as easily been written as functions and it would change anything. What have I missed? Great question. I’ve addressed the difference between single-case active patterns and function calls in: If that doesn’t clear things up let me know. Cheers!
https://blogs.msdn.microsoft.com/chrsmith/2008/02/22/regular-expressions-via-active-patterns/
CC-MAIN-2016-40
refinedweb
907
76.11
Could you try enabling these definitions in lisp.h and recompiling, and see if it helps you find the bug? (If it crashes for any other reason, we want to debug that too.) #if 0 /* Define this temporarily to hunt a bug. If defined, the size of strings is redundantly recorded in sdata structures so that it can be compared to the sizes recorded in Lisp strings. */ #define GC_CHECK_STRING_BYTES 1 /* Define this to check for short string overrun. */ #define GC_CHECK_STRING_OVERRUN 1 /* Define this to check the string free list. */ #define GC_CHECK_STRING_FREE_LIST 1 /* Define this to check for malloc buffer overrun. */ #define XMALLOC_OVERRUN_CHECK 1 /* Define this to check for errors in cons list. */ /* #define GC_CHECK_CONS_LIST 1 */ #endif /* 0 */
http://lists.gnu.org/archive/html/emacs-devel/2004-12/msg00898.html
CC-MAIN-2017-04
refinedweb
117
76.62
This custom server control displays the icon that is currently associated with the given file extension. The file icon associations are kept by the operating system and can be retrieved with a single Win32 API call. Use this control when you just need to display a well known file icon or even when you want to show any list of files with their appropriate icons. The article download contains a VS.NET 2003 project of a sample ASP.NET application. This application contains the two files that hold the important part of the code. These files are AssociatedIcon.cs and IconExtractor.cs. Instead of just extracting the whole project from the zipped file, I'd like to suggest that you use your own installation of Visual Studio .NET to create a new C# ASP.NET project named AssociatedIcons. Add two folders to your application, Controls and IconStubs. Delete the default Webform1.aspx file and add a new WebForm named TestPage. To save some major typing time, just get the file IconExtractor.cs and put it in the Controls folder of your project. Add a new class named AssociatedIcon in the same Controls folder. This class will be our custom control. AssociatedIcon After all that, your project should be looking like the image below: Add the following code to the AssociatedIcon.cs file that you just created: using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; namespace AssociatedIcons.Controls { [ToolboxData("<{0}:AssociatedIcon</{0}:AssociatedIcon>")] public class AssociatedIcon : Image { /***** * This control accepts a file name or file extension, * determines the associated icon, and displays it on the page * ***/ /// <summary> /// Gets or sets a file name or extension (including the dot) /// to display the associated icon /// </summary> public string ExtensionOrFile { get { string s = (string)ViewState["ExtensionOrFile"]; if(s == null) return ""; return s; } set{ ViewState["ExtensionOrFile"] = value; } } /// <summary> /// Determines if the icon size will be 16x16 or 32x32 pixels /// </summary> public bool LargeIcon { get { object obj = ViewState["LargeIcon"]; if(obj == null) return false; return (bool)obj; } set { ViewState["LargeIcon"] = value; } } public override string ImageUrl { get{ return base.ImageUrl;} set{ throw new InvalidOperationException("The ImageUrl cannot be set.");} } protected override void OnLoad(EventArgs e) { if(!Page.IsPostBack) base.ImageUrl = IconExtractor.GetUrlToIcon(ExtensionOrFile, LargeIcon); } } } Because we will be writing files in the IconStubs folder, you'll need to give write permission to the ASPNET user in that folder. In case you have never done this before, the process is simple. In any Windows Explorer window, find the IconStubs folder, right-click it and select Properties. Go to the Security tab. If the Allow inherited permissions[...] checkbox is checked, uncheck it. Use the Add button to add the ASPNET user to the list (in case it's not already there). With the ASPNET user in the list, select it and choose only the Allow Write checkbox in the permissions list. See the image below. After that, click OK and you're done. As you can see from the code above, our control is a fairly a simple extension of the System.Web.UI.WebControls.Image server control. We added a property to hold the desired file extension (or file name) and another one to specify if the desired icon will be the small (16 x 16 pixels) or the large (32 x 32 pixels) version. We also inhibit the setting of the ImageUrl property directly so that nobody changes it inadvertently. System.Web.UI.WebControls.Image ImageUrl As you can also notice, there's not much going on in this control's code. The real meat of the process is implemented by the IconExtractor class. IconExtractor The central piece of the icon extraction process is a call to the SHGetFileInfo Shell32 Windows API. This API, among other things, give us a handle to the associated icon (small or large) for the given file. After that, the code will save the icon as a PNG image with a transparent background in the IconStubs folder. Next time the same extension icon is requested, the URL to the already existing image file will be returned, without any new file creation. After a while, you should get your IconStubs folder full of the images for all the icons you used, as shown below: SHGetFileInfo Note: IE (at least the version I have: 6.0.2800.1106) has a flaw in transparent PNG rendering, causing the transparent areas to render gray. The code includes comments that help you change the implementation from PNG to GIF, losing the transparent background. Note: The implementation of transparent background in GIF images is way too complicated in .NET, involving unsafe blocks of code, so I decided not to include it in this sample, for the sake of simplicity (or laziness, if you'd like me to be really honest :) ). To see how the control works, let's put some content in our TestPage.aspx. First, let's register a tag prefix with our Controls namespace. Add the following to the top of you page's ASPX: Controls <%@ Register Tagprefix="SP" Namespace="AssociatedIcons.Controls" Assembly="AssociatedIcons" %> Now let's add some instances of our control in the page, like this: <form id="TestPage" method="post" runat="server"> <br> <SP:AssociatedIcon MyDocument.doc <br> <SP:AssociatedIcon MyIcon.bmp <br> <SP:AssociatedIcon MyIcon.jpg <br> <SP:AssociatedIcon MyIcon.gif <br> <SP:AssociatedIcon MyIcon.mp3 <br> <asp:Button ID=test Runat="server" Text=test /> </form> When you save, compile, and run this page, you should see something similar to the image below. The icons may vary depending on which programs you have associated with the file extensions. Like any sample, the code in this article is far from ideal and full of opportunities for new or enhanced features (maybe a few bugs here and there too). Some of the ideas that come to mind as enhancements to this code.
https://www.codeproject.com/articles/10530/associated-icons-image-control?fid=185459&df=90&mpp=50&sort=position&spc=relaxed&tid=4135888
CC-MAIN-2017-09
refinedweb
977
57.27
Opened 5 years ago Closed 5 years ago #19548 closed Cleanup/optimization (needsinfo) Extend app_directories template loader to search module path not just directory Description An issue exists in the template lookup system when using shared namespaces between similar but separated django eggs. Each egg contains it's own templates but when loading the eggs in Django only the most recent egg template directory is read. The attached patch searches the module.__path__ directories and not just the file location. Attachments (1) Change History (2) Changed 5 years ago by comment:1 Changed 5 years ago by We need a test case or self contained project to show the issue. To me "using shared namespaces between similar but separated django eggs" doesn't ring a bell (maybe it should, but it doesn't). So, closing as needsinfo. Diff for module path template lookup
https://code.djangoproject.com/ticket/19548
CC-MAIN-2017-39
refinedweb
143
62.58
Blog Map. This post presents the SkipLast Extension method, which allows you to skip the last n items. This blog is inactive.New blog: EricWhite.com/blogBlog TOCIn the next post, I’m going to present an enhancement to LtxOpenXml classes, which use LINQ to XML to query Open XML documents, to allow you to write queries on tables within spreadsheet (XLSX) documents. I needed SkipLast to implement this. Here is the implementation of the extension method, and a couple of examples of its use: using System;using System.Collections.Generic;using System.Collections.Specialized;using System.Linq;using System.Text; publicstaticclassMyExtensions{ publicstaticIEnumerable<T> SkipLast<T>(thisIEnumerable<T> source, int count) { Queue<T> saveList = newQueue<T>(); int saved = 0; foreach (T item in source) { if (saved < count) { saveList.Enqueue(item); ++saved; continue; } saveList.Enqueue(item); yieldreturn saveList.Dequeue(); } yieldbreak; }} classProgram{ staticvoid Main(string[] args) { int[] a = new[] { 1, 2, 3, 4, 5 }; var b = a.SkipLast(2); foreach (var item in b) Console.WriteLine(item); List<string> c = newList<string>() { "one", "two", "three", "four", "five" }; var d = c.Skip(1).SkipLast(1); foreach (var e in d) Console.WriteLine(e); }} This example outputs: 123twothreefour Code is attached. PingBack from Would it be more appropriate to use a Queue<T>, rather than a List<T>? The implementation would be Queue<T> saveList = new Queue<T>(); int saved = 0; foreach (T item in source) { if (saved < count) { saveList.Add(item); ++saved; continue; } saveList.Enque(item); yield return saveList.Deque(); } yield break; Ben, You are absolutely right, a Queue<T> is the better collection to use. I've updated the post with a new implementation. Thanks, Eric You can make it a bit more efficient with a few small changes: // presize the queue (+1 since we enq before we deq) Queue<T> saveList = new Queue<T>(count+1); // we always enq. no sense wait till after the if() saveList.Enqueue(item); if (count-- > 0) yield return saveList.Dequeue();
http://blogs.msdn.com/b/ericwhite/archive/2008/11/14/the-skiplast-extension-method.aspx
CC-MAIN-2014-23
refinedweb
325
59.6
Jupyter Notebooks have become a crucial tool in the Python and Data Science communities over the past years. Their seamless integration with some of the most important Python libraries and their interesting structure that encourages efficient prototyping and visualization have made Jupyter Notebooks one of my favorite tools as a Python user. With the new ArcGIS API for Python, GIS users can now also use this tool and integrate all of its benefits with a distributed GIS. The possibilities are quite exciting! … but how do I get a Jupyter Notebook running on my machine? If you’re ready to start exploring, there’s a few paths you can take to install and open your first notebook. The following are three easy, recommended ways to get Jupyter Notebooks running on your system: 1. Try the API in a live sandbox The simplest and quickest way to start writing your first Jupyter Notebook is to use the live ArcGIS API for Python sandbox at notebooks.esri.com. This approach doesn’t install anything on your system and operates nicely as a test environment to let you get started with your first notebook. Once you navigate there, you will see a simple page with a few tabs, icons, and items. Opening your first notebook is as easy as selecting the “New▼” button and selecting “Python 3” from the drop-down menu. This option is very useful to start writing notebooks from any system that has an internet connection. With this approach, nothing installs locally and you can get started in just seconds. However, this live sandbox environment does not save your user session and will reset if you reload your browser page, which raises an important caveat to keep in mind when trying this approach: If you wish to save your notebook beyond a single session, you will need to download the notebook to your system. Thankfully, saving a notebook is easy as pie. Select the File tab, then Download as, then Notebook (.ipynb): Hot tip: You may have noticed the other options when selecting a download format, including as a Python (.py) file and HTML (.html). I find the option to download as a Python (.py) file useful when enough progress is made in the testing and prototyping stage of writing code and you are ready to take the scripted process or functionality into production. Downloading as an HTML (.html) file is also very useful when embedding a static snapshot of your notebook into another webpage. Once you test a few notebooks using the live sandbox and get a feeling for how the entire tool operates, I recommend that you take the next steps to install the tool locally with one of the following options: 2. Install using the ArcGIS Pro Python Package Manager If you have ArcGIS Pro 1.4 or later installed, you can use its Python Package Manager to install and manage the ArcGIS API for Python, making the procedure extremely simple and GUI-driven. From ArcGIS Pro, select the Project tab at the top-left of the application, select Python from the menu options in the left, then select Add Packages and enter “arcgis” to find the ArcGIS API for Python: The package manager installs everything it needs and also allows you to manage updates or uninstalls (who would do such a thing?) of the API through the interface. Another hot tip: Take a second to explore other Python packages available through this Package Manager and test out a few, such as the r-arcgisbinding package. 3. Install Jupyter Notebooks and the API Using Anaconda The ArcGIS API for Python can also be installed using conda, a package manager that comes as part of the Anaconda for Python distribution – just make sure you get the Python 3x installer. Anaconda is a fairly heavy distribution but the benefits are significant: with one installation you receive access to more than 100 of the most-used Python packages for data science and a wealth of other capabilities to use with your Jupyter Notebooks. For instance, the requests module that comes with Anaconda is an excellent way to work with Python and HTTP requests. Once you have Anaconda for Python 3x installed, you gain access to Jupyter Notebooks. Finalizing the installation for the ArcGIS API for Python is then as easy as entering the following in a terminal or command prompt: conda install -c esri arcgis Once the package is fully installed the fun begins! Opening your First Notebook Using a Local Installation Once you have Jupyter Notebooks and the ArcGIS API for Python locally installed in your system, creating your first notebook is as simple as opening up a new terminal or command prompt and entering the following command: jupyter notebook Any jupyter notebooks you create after this point are saved at the location where the terminal or command prompt opened your jupyter notebook, so remember to change directories (cd) to the location where you want to save your notebooks! Final hot tip: If you’re using Windows and don’t often use the command prompt, a quick way to open up a command prompt window in a specified path is to select the address bar at the top of the Windows Explorer window and enter “cmd”. Now that you have installed Jupyter Notebooks and the ArcGIS API for Python and opened up your first notebook, it’s time to test by creating your first reference to a GIS and your first map. Create a new cell and enter the following Python code: from arcgis.gis import GIS my_gis = GIS() my_gis.map() A dynamic, controllable map loads beneath the cell. Save this notebook as “Hello Map” and frame it on a wall or stick it to your fridge. We are now ready to go explore! With installation and your first notebook out of the way, you are ready to test, prototype, map, analyze and create with all the potential that the tool provides. A few tips are recommended as you start getting acquainted with this tool, and an excellent, detailed guide is available as part of the ArcGIS API for Python documentation. You may also take a look at the sample notebooks to get started with robust GIS integration. Once you’ve created a few notebooks to handle basic workflows, come back and we’ll discuss a few approaches to start integrating functionality between the API, Pandas, and other interesting approaches that benefit from the functionality in Jupyter Notebooks and the ArcGIS API for Python. Stay tuned! Article Discussion:
https://www.esri.com/arcgis-blog/products/analytics/analytics/three-ways-to-get-jupyter-notebooks-and-the-arcgis-api-for-python/
CC-MAIN-2021-43
refinedweb
1,088
55.78
lp:libpsml Main development branch, incorporating the latest usability and format changes. - Get this branch: - bzr branch lp:libpsml Branch merges Related bugs Related blueprints Branch information - Owner: - Alberto Garcia - Status: - Development Recent revisions - 109. By Alberto Garcia on 2017-07-27 Export of ps_real_kind. Simple test. Update psml files and docs * Update the documentation of the annotation routines * Add export of ps_real_kind, and document it. * Update the psml files in examples/ * Add a very simple installation test and reference data * Update the release_notes This is a patch release tagged as libpsml-1.1.5 - 108. By Alberto Garcia on 2017-07-19 Release of libpsml-1.1.4 * Update the release_notes * Remove fossil file * Update README We follow the patch convention encoded in src/m_psml_ core.f90, which is also followed by the ps_GetLibPSMLVe rsion function, so the first 1.1 release is 1.1.4. - 107. By Alberto Garcia on 2017-07-18 Update draft preprint and CHANGES file - 106. By Alberto Garcia on 2017-07-18 Work around missing documentation for aliased types Added a section in the developer notes to explain the origin of ps_annotation_t and ps_radfunc_t. Updated front matter in top-level libpsml.md - 105. By Alberto Garcia on 2017-07-18 Add the missing documentation Wrote an overview of the functionality, with links to FORD-generated interfaces. Note that the interfaces in the code itself are lightly commented, originally in a Doxygen interface rougly compatible with FORD. This will be done progressively in future revisions of libpsml beyond the release. - 104. By Alberto Garcia on 2017-07-17 Remove old example files. Use ESL namespace in normalizer * Removed fossil files in 'examples'. * Renamed 'examples/ test_dump' to 'normalize'. In this file, use the namespace URI http:// esl.cecam. org/PSML/ ns/1.1 - 103. By Alberto Garcia on 2017-07-17 Support record-number attribute in <provenance> * The parser will add the appropriate entry in the data structures, and the dump routine will generate <provenance> elements with the 'record-number' attribute. Wrongly ordered elements in the file will trigger an error. * Update schema and API documentation in paper. - 102. By Alberto Garcia on 2017-07-17 Treatment of tails in interpolation * Tail regions might exhibit ringing with the high-order extrapolator. Upon parsing, the location of the last "zero" point (scanning backwards from the end) is encoded in the radfunc_t structure, and used as the effective cutoff point. Only in cases where the first "non-zero" is very small and sits at an "elbow" in the data there will be a bit of ringing, but it will be confined to the last interval. * The new behavior is configurable with a new routine ps_SetEvaluat orOptions which consolidates the setting of debugging, interpolator quality, and use of effective range. If procedure pointers are supported by the compiler the interpolator itself can be set by this routine. * Added an option '-t' to examples/show_psml to turn off the end-of-range processing. In this case the full range in the PSML file data will be used for interpolation. This program also generates "raw" tabular data when in "plot" mode. - 101. By Alberto Garcia on 2017-07-13 Add 'eref' attribute to slps. Provenance and char length fixes * Added support for the 'eref' attribute in semilocal potentials. * Provenance data for child elements was inserted in the wrong place in the pseudo-atom-spec hierarchy. * Increased the length of the character variables in the ps_t type to avoid setting a non-zero status flag in xmlf90's 'get_value' for long attributes. * examples/test_dump now inserts a new provenance element when dumping a ps_t object read from a PSML 1.0 file. * If the pre-processor symbol PSML_NO_OLD_API is defined, only the new API routines will be compiled in. * Updated examples/ {show_psml, getz} to use only the new API, and inserted pre-processor instructions to avoid compiling examples/ test_psml if the old API compatibility layer is not compiled in. Remove outdated programs v10tov11 and dumper. * Updated the schema and the description paper. - 100. By Alberto Garcia on 2017-07-07 Add optional energy_level attribute in the <pswf> element Branch metadata - Branch format: - Branch format 7 - Repository format: - Bazaar repository format 2a (needs bzr 1.16 or later)
https://code.launchpad.net/~albertog/libpsml/trunk
CC-MAIN-2017-39
refinedweb
706
55.34
do you mean 46? Code: #include <stdio.h> #define N 8 int main(void) { int F[46] = {0, 1}; int i; for (i = 2; i <= N; i++) F[i] = F[i-1] + F[i-2]; printf("%d\n", F[N]); return 0; } //I'm sorry, I mean 'F[8]' , heihei Posting solutions directly is a bad way of teaching anyone anything. As for the bugs: Take a closer look at laserlight's first post. You didn't follow the advice fully. Check the places your brackets are. Indent the code properly and make sure everything is either inside or outside of where it should be. Don't forget to actually return something. Right what you said!! I think the best solution is to implement the Fibonacci algorithm iteratively, as you have already said. Infact it takes much less memory and time (on an input n = 58, F(58) with the recursion takes ≈ 4 hours, while iteratively only ≈ 0.7 millionths of a second)! Here my pseudocode algorithm for Fibonacci, using cycles instead of recursion for calculating the n-th Fibonacci number : Algorithm Fibonacci4 (int n) --> int 1. a <-- 1, b <-- 1 2. for i = 3 to n do 3. c <-- a + b 4. a <-- b 5. b <-- c 6. return b. I hope it could be of a little help! Bye!! ;) saria777, concerning the range of numbers that you are supposed to accommodate: check with your teacher. If you are allowed to compile with respect to the 1999 edition of the C standard, then you have access to unsigned long long, which would allow you to handle F(93). But F(100) really is beyond reach unless you use a non-standard bignum library, or code your own (which would be an entirely different project, and in some ways more difficult than what you are supposed to solve here). Otherwise, your teacher may tell you that this was an oversight, and perhaps you only need to deal with at most F(47). alrighty. I've got it to compile /finally/. And yes, when it gets so large it begins showing negative numbers.?Code: #include <stdio.h> int Fibonacci (int n); int main () { long result; long number; printf("Enter an integer: "); scanf("%ld", &number); result=Fibonacci(number); printf("Fibonacci(%ld)=%ld/n",number,result); return 0; } int Fibonacci (int n) { int previous= 0; int result =1; int i; for (i=2; i <=n; ++i) { int const sum=result + previous; previous= result; result = sum; } return result; } Your solution agrees with this Fibonacci table here: PlanetMath: list of Fibonacci numbers Your teacher has the sequence advanced by one... so if your teacher wanted 21 as an answer for input 7, just add 1 to user input and proceed. Or callCode: Fibonacci(number + 1);
http://cboard.cprogramming.com/c-programming/127700-fibonacci-2-print.html
CC-MAIN-2014-23
refinedweb
460
65.22
An ANCOVA (“analysis of covariance”) is used to determine whether or not there is a statistically significant difference between the means of three or more independent groups, after controlling for one or more covariates. This tutorial explains how to perform an ANCOVA in Python. Example: ANCOVA in Python Use the following steps to perform an ANCOVA on this dataset: Step 1: Enter the data. First, we’ll create a pandas DataFrame to hold our data: import numpy as np import pandas as pd #create data df = pd.DataFrame({'technique': np.repeat(['A', 'B', 'C'], 5), 'current_grade': [67, 88, 75, 77, 85, 92, 69, 77, 74, 88, 96, 91, 88, 82, 80], 'exam_score': [77, 89, 72, 74, 69, 78, 88, 93, 94, 90, 85, 81, 83, 88, 79]}) #view data df technique current_grade exam_score 0 A 67 77 1 A 88 89 2 A 75 72 3 A 77 74 4 A 85 69 5 B 92 78 6 B 69 88 7 B 77 93 8 B 74 94 9 B 88 90 10 C 96 85 11 C 91 81 12 C 88 83 13 C 82 88 14 C 80 79 Step 2: Perform the ANCOVA. Next, we’ll perform an ANCOVA using the ancova() function from the pingouin library: pip install pingouin from pingouin import ancova #perform ANCOVA ancova(data=df, dv='exam_score', covar='current_grade', between='technique') Source SS DF F p-unc np2 0 technique 390.575130 2 4.80997 0.03155 0.46653 1 current_grade 4.193886 1 0.10329 0.75393 0.00930 2 Residual 446.606114 11 NaN NaN NaN Step 3: Interpret the results. From the ANCOVA table we see that the p-value (p-unc = “uncorrected p-value”) for study technique is 0.03155. Since this value is less than 0.05, we can reject the null hypothesis that each of the studying techniques leads to the same average exam score, even after accounting for the student’s current grade in the class.
https://www.statology.org/ancova-python/
CC-MAIN-2022-21
refinedweb
332
57.81
Note: For Pig 0.2.0 or later, some content on this page may no longer be applicable. Pig User Defined Functions Pig has a number of built-in functions for loading, filtering, aggregating data (for a complete list, see PigBuiltins.) However, if you want to do something specialized, you may need to write your own Pig user defined function (UDF). This page walks you through the process. Types of functions Eval Function The most important and commonly used type of functions are EvalFunction. Eval functions consume a tuple, do some computation, and produce some data. Eval functions are very flexible, e.g. they can mimic "map" and "reduce" style functions: "Map" behavior: The output type of an Eval Function is one of: a single value, a tuple, or a bag of tuples (a Map/Reduce "map" function produces a bag of tuples). "Reduce" behavior: Recall that in the Pig data model, a tuple may contain fields of type bag. Hence an Eval Function may perform aggregation or "reducing" by iterating over a bag of tuples nested within the input tuple. This is how the built-in aggregation function SUM(...) works, for example. Load Function Controls reading of tuples from files. Store Function Controls storing of tuples to files. Example The following example uses each of the types of functions. It computes the set of unique IP addresses associated with "good" products drawn from a list of products found on the web. register myFunctions.jar products = LOAD '/productlist.txt' USING MyListStorage() AS (name, price, description, url); goodProducts = FILTER products BY (price <= '19.99'); hostnames = FOREACH goodProducts GENERATE MyHostExtractor(url) AS hostname; uniqueIPs = FOREACH (GROUP hostnames BY MyIPLookup(hostname)) GENERATE group AS ipAddress; STORE uniqueIPs INTO '/iplist.txt' USING MyListStorage(); In the above example, MyListStorage() serves as a load function as well as a store function; MyHostExtractor() and MyIPLookup() are eval functions. myFunctions.jar is a jar file that contains the classes for the user-defined functions. How to write functions Ready to write your own handy-dandy pig function? Before you start, you will need to know about the APIs for interacting with the data types (atom, tuple, bag). Click here: PigDataTypeApis. Click below to learn how to build your own: Load/Store Function (These are the most difficult to write, and usually, the inbuilt ones should be enough) <<Anchor: execution failed [Too many arguments] (see also the log)>> Ok, I have written my function, how to use it? You can use your functions following the steps below: - Put all the compiled files used by your function together into a jar file Tell Pig about that jar by the register <udfJar> command before using the function. To register a UDF jar, you can either specify a full path to the jar file (register /home/myjars/udfs.jar) or you can place the jar file in your classpath and pig will find it there (register udfs.jar). (If you are using PigLatin in embedded mode, call PigServer.registerJar()). - Then use your function, as you would use a builtin! Its that simple. Example: The following example describes how to use your Eval function. Follow the same procedure for your Load/Store function. 1. Create your function /src/myfunc/MyEvalFunc.java package myfunc; import java.io.IOException; import java.util.StringTokenizer; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.Tuple; public class MyEvalFunc())); } } } 2. Compile your function. Make sure to point java compiler to pig jar file. /src/myfunc $ javac -classpath /src/pig.jar MyEvalFunc.java 3. Create jar file /src/myfunc $ cd .. /src $ jar cf myfunc.jar myfunc 4. Use the function through grunt (similar use from script). Note that there is no quotes around path in the register call. /src $ java -jar pig.jar - grunt> register /src/myfunc.jar grunt> A = load 'students' using PigStorage('\t'); grunt> B = foreach A generate myfunc.MyEvalFunc($0); grunt> dump B; ({(joe smith)}) ({(john adams)}) ({(anne white)}) .... See EmbeddedPig to see example of embeding Pig and your functions in Java. Use the same procedure outlined above to create your function jar file. Advanced Features: If you would like your function class to be instantiated with a non-default constructor, you can use the define <alias> <funcSpec> command. (If you are using PigLatin in embedded mode, call PigServer.registerFunction()). E.g., if I want my class MyFunc to be instantiated wih the string 'foo', I can write define myFuncAlias myFunc('foo'). I can then use myFuncAlias as a normal user-defined function. - Note that only string arguments to constructors are supported.
https://wiki.apache.org/pig/WriteFunctions?action=diff
CC-MAIN-2017-22
refinedweb
763
59.5
C# - How To Configure An Http Handler In IIS 7Nov 24, 2010 Here's what I want to do: I've created a class library project and this has a class implementing the IHttpHandler interface. Let's call this class ZipHandler. Let's say the namespace is Zip. I want that whenever any Http request comes for a zip file, my ZipHandler should handle it, regardless of whether the request is to an Asp.Net application or a normal virtual directory. Queries: Is it possible (it should be given the hype about integrated pipeline etc. in IIS 7)? How to do it?
https://asp.net.bigresource.com/c-How-to-configure-an-Http-Handler-in-IIS-7-TKsR70VXx.html
CC-MAIN-2022-27
refinedweb
102
76.11
Video Edition: Hi there, this is PART 1 of my NEST.js series. In this chapter we will inspect what controllers are and how they work in NEST.js. In addition we also have a look on Pipes and DTO's, what they are and what happens if you combine them. Controller? Yeah, I have one for my PlayStation Just like you use your PlayStation controller to control games, controllers in NEST.js are used to control incoming requests. Controllers play an important part in a backend system. Normally for every endpoint in your system, there is one controller for it. If a route is called, for example, the UserController is invoked. @Controller('users') export class UserController { ... } We use the @Controller decorator to instruct NEST, this class is a controller. An in the round brackets ('users'), we tell NEST that this controller is responsible for /users endpoint. Okay, thats nice, but how we can handle the different HTTP Requests? Well, NEST loves to use decorators, and therefore we have all the HTTP Methods accessible as decorators. @Get(), @Put(), @Delete(), @Patch(), @Options(), and @Head(). In addition, @All() defines an endpoint that handles all of them. This is nice, because we simply put them above the functions and it works. This looks nice and clean and is easy to understand. @Controller('users') export class UserController { // i am handling the GET Request @Get() getAllUsers(): User[] { ... } // i am handling the POST Request @Post() insertUsert(): void { ... } // i am handling the PUTRequest @Post() updateUser(): void { ... } Parameter Handling in Requests Often you pass parameters in your HTTP Requests to transport additional information. Lets go through the most common use cases in an API backend, to demonstrate, how you can access them. I want to to have two endpoints, one for get all users and one to get a specific user @Controller('users') export class UserController { // i am handling the GET Request for getting all users // localhost:3000/users @Get() getAllUsers(): User[] { ... } // i am handling the GET Request for getting a specific user // localhost:3000/users/xamhans @Get(':username') getSpecificUser(@Param('username') username): console.log(username) <---- 'xamhans' } Nothing easier than that. First we keep our function getAllUsers() and add a second function getSpecificUser() with @Get(':username'). In addition we use the @Param('username') decorator in our getSpecificUser() Function to access that specific route parameter. To make things clear, you can choose any name you want, but make sure it's the same name in @Get() and the @Param decorator. I want to access the body of a POST/PUT Request, so I can insert/update a new user @Post() insertUser(@Body() newUser) { console.log(newUser) <--- '{name: 'xamhans'} } @Put() updateUser(@Body() updatedUser) { console.log(updatedUser) <--- '{name: 'xamhans_reloaded'} } We use the @Body() decorator in both functions to access the Body Payload. Pretty straightforward. I want to access the query parameters, so i can filter my users // @Get() findAll(@Query() query) { return `Search for all users with name ${query.search} with limit ${query.limit}`; // Search for all users with name hans with limit 5 } We use the @Query() decorator as an paramter in the findAll() Function to achieve this. With this knowledge, you should be cover the most use cases for an API Backend (i hope, please write me if i forgot something 😇 ) Input validation, make your controllers robust Have you ever noticed the pain, if a colleague or a customer called your backend with parameters or data that you never ever thought of ? Here is a concrete use case, imagine we want to create a new user in our database. We configured our users database table in that way, that the username should be at least 3 characters long. Somehow the customer has managed to get past the frontend validation process and send a post request with a 2 character username. Guess what will happen ? 💣 Our controller accepts the request and call the database service with the payload, our service then tries to insert a new user with the not valid username and here the system will break. To prevent this, we make sure that the controller validates the data before proceeding. Validation with Pipes and DTO's Before we start, lets make sure that we have a common understanding in terms of Pipes and DTO. Pipes have two typical use cases: - transformation: transform input data to the desired form (e.g., from string to integer) - validation: evaluate input data and if valid, simply pass it through unchanged; otherwise, throw an exception when the data is incorrect. Nest interposes a pipe just before a method is invoked, and the pipe receives the arguments destined for the method and operates on them. Any transformation or validation operation takes place at that time, after which the route handler is invoked with any (potentially) transformed arguments. DTO stands for Data Transfer Object. With a DTO we define how we want to receive and send data. export class CreateUserDTO{ username: string; } For our create user usecase, we create the CreateUserDTO with the properties that the user object should contain. Okay thats nice, but how we define that username should be at least 3 characters long? Here we need a little help from another libraries called class-validator & class transformer npm i --save class-validator class-transformer class-validator offers you a lot of decorators that you can use for validation, so lets start by defining the username property to be mandatory ( @IsNotEmpty()) and a min length of 3 characters ( @MinLength(3)) . Explore all the class-validator decorators here that you can use for validation. import { MinLength, IsNotEmpty } from 'class-validator'; export class CreateUserDTO{ @MinLength(3) @IsNotEmpty() username: string; } Now it all comes together: Pipes + DTO's = ❤️ import { Body,Controller,Post,UsePipes,ValidationPipe} from '@nestjs/common'; import { CreateUserDTO } from './createUserDto'; @Post() @UsePipes(new ValidationPipe({ transform: true })) insertUser(@Body() createUser: CreateUserDTO) { console.log(createUser) } Payloads coming in over the network are plain JavaScript objects. The ValidationPipe can automatically transform payloads to be objects typed according to their DTO classes. To enable auto-transformation, set transform to true. This can be done at a method level or globally. Therefore set the option on a global pipe in the main.ts app.useGlobalPipes( new ValidationPipe({ transform: true, }), ); So lets call the users endpoint and see what happens Here we call the users endpoint with a not valid username, and it is returning a error message that the property "username must be longer than or equal to 3 characters". This is awesome, the reciever of the response will exactly know what is not correct and can adjust the request. Here we send a valid payload to the endpoint. As you can see that the response returned a 201 created code. Also the code inside the function was executed. Lessons learned - Controllers play an important part in a backend system, because they are responsible for manage / routing the incoming requests - Use @Query()to access query params, @Param()to access route params, and @Body()for body payload of a POST/PUT request - We use Pipes in NEST to transform or validate data - With DTO we define a contract how a object should look like and what requirements it has (this goes for both directions, how the request data must be look like and the response data) - With class-validator libary we have a lot of decorators that we can use for defining the DTO's Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/xamhans/part-1-controllers-the-nest-js-way-3aab
CC-MAIN-2022-05
refinedweb
1,226
61.77
Investors in Enterprise Products Partners L.P. (Symbol: EPD) saw new options begin trading today, for the October 11th expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the EPD options chain for the new October 11th contracts and identified one put and one call contract of particular interest. The put contract at the $28.00 strike price has a current bid of 55 cents. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $28.00, but will also collect the premium, putting the cost basis of the shares at $27.45 (before broker commissions). To an investor already interested in purchasing shares of EPD, that could represent an attractive alternative to paying $28.24.96% return on the cash commitment, or 18.87% annualized — at Stock Options Channel we call this the YieldBoost. Below is a chart showing the trailing twelve month trading history for Enterprise Products Partners L.P., and highlighting in green where the $28.00 strike is located relative to that history: Turning to the calls side of the option chain, the call contract at the $29.00 strike price has a current bid of 35 cents. If an investor was to purchase shares of EPD stock at the current price level of $28.24/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $29.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 3.93% if the stock gets called away at the October 11th expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if EPD shares really soar, which is why looking at the trailing twelve month trading history for Enterprise Products Partners L.P., as well as studying the business fundamentals becomes important. Below is a chart showing EPD's trailing twelve month trading history, with the $29.00 strike highlighted in red: Considering the fact that the $29.24% boost of extra return to the investor, or 11.90% annualized, which we refer to as the YieldBoost. The implied volatility in the put contract example is 22%, while the implied volatility in the call contract example is 20%. Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 250 trading day closing values as well as today's price of $28.24) to be 19%. For more put and call options contract ideas worth looking at, visit StockOptionsChannel.com. Top YieldBoost Calls of the MLPs » The views and opinions expressed herein are the views and opinions of the author and do not necessarily reflect those of Nasdaq, Inc.
https://www.nasdaq.com/articles/epd-october-11th-options-begin-trading-2019-09-03
CC-MAIN-2020-10
refinedweb
464
65.12
If someone would like to iterate through multiple lists with multiple iteration variables how would it be done without using python built in functions like zip() list comprehensions list1 = [1,2,3] list2 = [4,5,6] list3 = [] def function(): for i,y in (list1, list2): total = i * y list3.append(total) return list3 print(function()) "ValueError: too many values to unpack (expected 2)". If your two arrays are equal by size. Below answer is right list1 = [2,2,2] list2 = [3,3,3] def function(): for i in range(len(list1)): print(list1[i]*list2[i]) print(function()) But best practice is use to zip method for i, j in zip(list1, list2): print(i * j)
https://codedump.io/share/kwACrkmKRoXJ/1/python-list-multiple-iterations
CC-MAIN-2017-26
refinedweb
116
64.24
How To Install TensorFlow In Ubuntu Linux [ad_1] How to install Tensor Flow or TensorFlow in Ubuntu linux. Tensor flow is an graph based computational deep learning framework which follows symbolic programming. To Install Tensorflow :- Open Terminal by CTRL+T sudo apt-get update sudo apt-get upgrade -y Then, First Install Python3 by – sudo apt-get install python3 Then install python3 pip by – sudo apt-get install python3-pip Now, Install Tensorflow by – pip3 install tensorflow After we have installed Tensorflow, let make a sample program using tensorflow – first use any code-editor like emacs or gedit . In this video, I am using emacs code editor. you can use one of many code-editor as per your preferences. Now after lets say running – emacs test.py Type the following python code statements – import tensorflow as tf; graph = tf.Graph(); #to get the default graph. with graph.as_default() : x = tf.constant(5, name = “x_value”); y = tf.constant(3, name= “y_value”); sum = tf.add(x, y, name=”added_value”); with tf.Session() as session : print(“Result : “, sum.eval() ); Then save it and on the terminal, run : python3 test.py you should be able to see the output on the terminal : Result : 8 So, Now you have successfully installed tensorflow in ubuntu linux. Source [ad_2] Comment List How do I see this installation in pycharm it's saying no matching distribution for tenserflow For instruction: sudo apt-get install python3-pip Reading package lists…Done Building dependency tree Reading state information…Done E: Unable to locate package python3-pip Please help…
http://openbootcamps.com/how-to-install-tensorflow-in-ubuntu-linux/
CC-MAIN-2021-25
refinedweb
258
56.86
This Part is the continuation of the Deploying AI models Part-3 , where we deployed Iris classification model using Decision Tree Classifier. You can skip the training part if you have read the Part-3 of this series. In this article, we will have a glimpse of Flask which will be used as the front end to our web application to deploy the trained model for classification on Heroku platform. 1.1. Packages The following packages were used to create the application. 1.1.1. Numpy 1.1 .2. Flask, Request, render_template from flask - 1.3. Dataset, Ensemble, Model Selection from sklearn 1.2. Dataset The dataset is used to train the model is of iris dataset composed of 4 predictors and 3 target variable i.e. Classes Predictors: Sepal Length, Sepal Width, Petal Length, Petal Width Target : Setosa [0], Versicolor[1], Verginica[2] Dataset Shape: 150 * 5 1.3. Model For training the model we followed the following procedure: Data Split up: 8:2 ie. 80% training set and 20% for the test set Model: Ensemble- RandomForestClassifier with n_estimators=500) Saving Model: Saved in the pickle file Below is the code for the training the model. import sklearnimport sklearn.datasetsimport sklearn.ensemble import sklearn.model_selection import pickle import os#load datadata = sklearn.datasets.load_iris() #Split the data into test andtraintrain_data, test_data, train_labels, test_labels = sklearn.model_selection.train_test_split(data.data, data.target, train_size=0.80)print(train_data,train_labels)#Train a model using random forestmodel = sklearn.ensemble.RandomForestClassifier(n_estimators=500)model.fit(train_data, train_labels)#test the model result = model.score(test_data, test_labels) print(result)#save the model filename = ‘iris_model.pkl’ pickle.dump(model, open(filename, ‘wb’)) 1.4. Frontend using Flask For feeding the value in the trained model we need some User Interface to accept the data from the user and feed into the trained neural network for classification. As we have seen in the sectioin 1.2 Dataset where we have 4 predictors and 3 classes to classify. File name: index.html should be placed inside templatre folder. <h1>Sample IRIS Classifier Model Application</h1><form action=”{{ url_for(‘predict’)}}”method=”post”> <input type=”text” name=”sepal_length” placeholder=”Sepal Length” required=”required” /><input type=”text” name=”sepal_width” placeholder=”Sepal Width” required=”required” /><br> <br> <input type=”text” name=”petal_length” placeholder=”Petal Length” required=”required” /> <input type=”text” name=”petal_width” placeholder=”Petal Width” required=”required” /> <br> <br>{{ output }}<br> <button type=”submit” class=”btn btn-primary btn-block btn-large”>Submit Data</button> </form> <br> <br> The above shown code is for taking the input from the user and display it in the same page. For this we have used action=”{{ url_for(‘predict’)}}” this will call the prediction fubtion when we will submit the data with the help of this form and {{ output }} to render the predicted output in the same page after prediction. 1. Top 5 Open-Source Machine Learning Recommender System Projects With Resources 2. Deep Learning in Self-Driving Cars 3. Generalization Technique for ML models 4. Why You Should Ditch Your In-House Training Data Tools (And Avoid Building Your Own) File name: app.py import numpy as np from flask import Flask, request, jsonify, render_template import pickle import os#app name app = Flask(__name__) #load the saved modeldef load_model(): return pickle.load(open(‘iris_model.pkl’, ‘rb’)) #homepage@app.route(‘/’)def home(): return render_template(‘index.html’)@app.route(‘/predict’,methods=[‘POST’])def predict():‘’’ For rendering results on HTML GUI ‘’’labels = [‘setosa’, ‘versicolor’, ‘virginica’] features = [float(x) for x in request.form.values()] values = [np.array(features)] model = load_model()if __name__ == “__main__”: prediction = model.predict(values) result = labels[prediction[0]] return render_template(‘index.html’, output=’The Flower is {}’.format(result)) port=int(os.environ.get(‘PORT’,5000)) app.run(port=port,debug=True,use_reloader=False) In the python script, we called the index.html page in the home() and loaded the pickle file in load_model () function. As mention above we will be using the same index.html for user input and for rendering the result. when we will submit the form via post method the data will be send to the predict() via action=”{{ url_for(‘predict’)}}” and predict function from the app.py file and it will be processed and the trained model which we have loaded via load_model () function will predict and it will be mapped the respective class name accordingly. To display the data we will render the same template i.e. index.html. If you would have remember we used keyword {{ output }} in the index.html page we will be sending the value in this field after prediction by rendering in the index.html page by the following Flask function. render_template(‘index.html’, output=’The Flower is {}’.format(result)) where index.html is the template name and output=’The Flower is {}’.format(result) is the value to be rendered after prediction. 1.5. Extracting Packages and their respective versions We need to create the require.txt file which contains the name of package we used in our application along with their respective version. The process of extracting the requirement.txt file is explained in the Article: Deep Learning/Machine Learning Libraries — An overview. For this application below is the requirement.txt file content. Flask==1.1.2 joblib==1.0.0 numpy==1.19.3 scikit-learn==0.23.2 scipy==1.5.4 sklearn==0.0 Along with requirement.txt, you need the Proctfile which calls the main python script i.e. script which will run first. For this Webapplication the Proctfile content is below. web: gunicorn -b :$PORT app:appapp -->is the name of the python scripy i.e. app.py 2. Heroku It is a PaaS platform which supports many programming languages. Initially in 2007 it was supporting only Ruby programming language but not it supports many programming language such as Java, Node.js, Scala, Clojure, Python, PHP, and Go. It is also known as polyglot platform as it features for a developer to build, run and scale applications in a simillar manner across most of the language it was acquired by Salesforce.com in 2010. Applications that are run on Heroku typically have a unique domain used to route HTTP requests to the correct application container or dyno. Each of the dynos are spread across a “dyno grid” which consists of several servers. Heroku’s Git server handles application repository pushes from permitted users. All Heroku services are hosted on Amazon’s EC2 cloud-computing platform. You can register on this link and can host upto 5 application with student account. 3. Deploying Web application In above, section we have constructed our web application successfully and now it’s time to deploy it. For deploying we have two option Deploying via Github and Deploying via Local System. In this article we will see how we can deploy any ML/DL model using Heroku CLI. 3.1. Deploying via Heroku CLI The local repository should look like the below image: As mentioned in the section 2, after login in the heroku platform follow the below step: Step1: Create new app and name the application and click on create app. You will land on the below page. In Fig.2 you can see, we have 3 option by which we can deploy, in this article we will use the option which allows us to deploy the application directly with ourGithub repository. Note: for Installation visit this Link. Step2: Select heroku CLI from the available option to deploy the application to heroku. Step3: Navigate to the directory where the project file is kept. Command: cd “Path of the directory” Step4: Initialise the directory with git. Command: git initCommand: heroku git: remote -a “Name of the Application created” The above commands will create the git reposisoty in your local system. For deployement follow tye below process: Step5: We need to add all our filled so that it can be tracked for any changes we will do in later stages of our project. Command: git add . Step 6: Commit the repository. Command: git commit -am “version 1” Step 7: Push the repository into Heroku. Command: git push heroku master Congratulation!! you have sucessfully deployed an web application via Heroku CLI. 4. Deployed Web Application The overview of the deployed web application with Iris Application: Link is shown below. As we say “Car is useless if it doesn’t have a good engine” similarly student is useless without proper guidance and motivation. I will like to thank my Guru as well as my Idol “Dr. P. Supraja”- guided me throughout the journey, from the bottom of my heart. As a Guru, she has lighted the best available path for me, motivated me whenever I encountered failure or roadblock- without her support and motivation this was an impossible task for me. Extract installed packages and version : Article Link. Notebook Link Extract installed packages and version : Notebook Link How to Deploy AI Models? — Part 1 : Link How to Deploy AI Models? — Part 2 Setting up the Github For Herolu and Streamlit : Link YouTube : Link Deployed Application: Link Iris Application: Link If you have any query feel free to contact me with any of the -below mentioned options: Website: Medium: Google Form: Credit: BecomingHuman By: RAVI SHEKHAR TIWARI
https://nikolanews.com/how-to-deploy-ai-models-part-5-deploying-web-application-on-heroku-cli-by-ravi-shekhar-tiwari-mar-2021/
CC-MAIN-2021-31
refinedweb
1,537
57.47
Question:Write a program that gets two numbers from the user, a and b, you may assume that a<b. It then prints the squares of all the numbers in the inclusive range [a, b]. This is the question for my assignment and I am completely lost, I learned some of the concepts but I just don't know how to apply it to this. my code: import java.util.*; import javax.swing.*; public class Ch4Q11 { public static void main (String[] args) { int n; int m; int accumulator; final int high = m, low = n; String valuea, valueb; valuea = JOptionPane.showInputDialog("Write first number here: "); n = Integer.parseInt(valuea); int amount = high - low + 1; while (accumulator >= 0) { valueb = JOptionPane.showInputDialog("Write second number here: "); m = Integer.parseInt(valueb); System.out.print(accumulator + " "); System.out.println(Math.sqrt(accumulator) + " " ); n--; } } } as you can see I'm not even close.. I would really appreciate it if someone could help me with this Thank you, Harris
http://www.javaprogrammingforums.com/whats-wrong-my-code/1490-help-assignmen-please.html
CC-MAIN-2014-35
refinedweb
162
57.27
If you’ve been following along, I had previously written a tutorial that demonstrated including a visual map in your Angular web application using the HERE Maps API for JavaScript. In that tutorial we saw several methods towards using a map, leading up to creating a custom component for the job. However, in that tutorial we just made use of a basic map with no markers or interaction. Our Angular application could be substantially more useful if we had some interaction with the map. For example, what if we wanted to display all locations of a particular vendor on the map? Or what if we wanted to see address information for a particular vendor? In this tutorial we’re going to see how to use the HERE Places API in an Angular application to search for particular points of interest and display them on a map using markers and captions, also known as information bubbles. The Project Requirements There are a few development requirements that must be met in order to make this tutorial a success on your own server or computer. - A HERE developer account must have been created. - The Angular CLI must be installed and configured. To use the HERE maps and location services (HLS) platform, you must have an app id and app code created through your developer portal. It is free to sign up and use the HLS platform. The easiest way to develop with Angular is through the Angular CLI. It can be installed through the Node Package Manager (NPM). While not a requirement, much of this tutorial will be a continuation to the previous tutorial I wrote, so it might be a good idea to familiarize yourself with what I had demonstrated previously. Through this tutorial, we plan to create something as seen in the following animated image: As you can see, there will be a map and a search box. After entering a place of interest, all matches will be displayed on the map in the form of a marker. When clicking or tapping on a marker, an information bubble will appear with the name of the place as well as the address. This is a realistic scenario on what someone might expect from a map. Creating an Angular Project with the HERE Maps API for JavaScript As previously mentioned, this is more or less a followup to the previous tutorial I wrote which was a getting started with HERE and Angular tutorial. To get us up to speed, I’m going to share the code from the previous tutorial, but if you want thorough explanations as to why things are the way they are, I encourage you to revisit the previous tutorial titled, Display HERE Maps within your Angular Web Application. From the command line, execute the following to create a new Angular project with the necessary components: ng new here-project cd here-project ng g component here-map With the project and files in place, we need to copy our previous map component code into our new project. Open the project’s src/app/here-map/here-map.component.html file and include the following HTML markup: <div #map [style.width]="width" [style.height]="height"></div> With the UI component in place, we can create some TypeScript logic that will bind the HTML component above. Open the project’s src/app/here-map/here-map.component.ts file and include the following:; private platform: any; private map: any; public constructor() { } public ngOnInit() { this.platform = new H.service.Platform({ "app_id": this.appId, "app_code": this.appCode }); } public ngAfterViewInit() { let defaultLayers = this.platform.createDefaultLayers(); this.map = new H.Map( this.mapElement.nativeElement, defaultLayers.normal.map, { zoom: 10, center: { lat: this.lat, lng: this.lng } } ); } } The above TypeScript logic should be more or less what we’ve already seen. We have several inputs that can be accessed from the component, we are initializing the HLS platform, and we are creating a new map after the view has initialized. With a map component created and readily available, it can be used in any other component. As seen previously, open the project’s src/app/app.component.html file and include the following: <here-map #map </here-map> Don’t forget to replace the appId and appCode with that of your actual project values, otherwise the map and services will fail to work. The last part to bring us up to speed is the inclusion of the HERE JavaScript libraries. Open the project’s src/index.html file and include the following HTML markup: <> It may seem like we’ve accomplished a lot as of now, but we really just got our map up and running. Everything as of now is not the goal of this particular tutorial. It was included to prevent confusion between configuring a map and using the Places API. If you completed the previous tutorial, everything here should look familiar and can probably be skipped. Now we can focus on the HERE Places API with marker and information bubble support. Implementing Search Functionality with the HERE Places API Because we are planning to use the JavaScript libraries offered by HERE, we need to include a few more in our project. As of right now we have the core library and the map service library, but we need a library for places, events on the map, as well as an interactive user interface."> <link rel="stylesheet" type="text/css" href="" /> </head> <body> <app-root></app-root> > Notice that this time around we’ve included three more libraries as well as a stylesheet file. This will allow us to do searches, click on markers, and add other behavior to the map. To make use of these new libraries, a few things must be added to our map component. Open the project’s src/app/here-map/here-map.component.ts file and include the following variables: private ui: any; private search: any; The goal is to initialize the search service and alter the UI behavior to be used throughout the component, hence the global variables. Within the same file, we need to alter the ngOnInit and ngAfterViewInit lifecycle events. The ngOnInit method should now look like this: public ngOnInit() { this.platform = new H.service.Platform({ "app_id": this.appId, "app_code": this.appCode }); this.search = new H.places.Search(this.platform.getPlacesService()); } Since the search functionality doesn’t rely on the UI, it can be initialized prior to the view being ready, hence the ngOnInit method. In the ngAfterViewInit method, we need to prepare for some UI and event behavior: public ngAfterViewInit() {)); this.ui = H.ui.UI.createDefault(this.map, defaultLayers); } Even though we’ve just seen a few new things to get marker support, click support, and search support on our map, it was more or less bootstrap code for the bigger picture. Now we want to add some actual functionality. Within the project’s src/app/here-map/here-map.component.ts file, include the following two methods:); } So what is happening in the places method and the dropMarker methods? Let’s first examine the places method. In the places method, we are removing any objects that might already exist on the map. This includes markers, events, etc. This is because every time the places method is called, we are trying to add new markers. It probably wouldn’t be a good idea in this scenario to append new markers to the already existing list. It makes more sense to start fresh. Once the map is cleared, we issue a search based on a provided query string. The query string represents some point of interest. We are also providing a latitude and longitude for the general search area rather than an entire global search. For any results that are found, we loop through them and call the dropMarker method. In the dropMarker method, we are expecting some coordinate information as well as some data to be used to create an InfoBubble. Using the coordinate information we can create a marker. The marker is going to store the data that was passed which should include the place title as well as the address or vicinity. The data contains a lot more information, but for this example we’re not interested in it. We need a way to display the data, so we can create a click event. When a marker is clicked, a new information bubble is created where the content is the stored data. This bubble is added to the UI and the marker is finally added to the map. So how do we use these places and dropMarker methods? For this example, it makes sense to have a search form within our application to populate the location results. However, in Angular forms don’t really work by default. Open the project’s src/app/app.module.ts file and include the following: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from "@angular/forms"; import { AppComponent } from './app.component'; import { HereMapComponent } from './here-map/here-map.component'; @NgModule({ declarations: [ AppComponent, HereMapComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } In the above code we’ve included the FormsModule and added it to the imports section of the @NgModule block. Now we can use forms within our Angular application. As seen in the image at the beginning of this tutorial, we had a search form with a pre-populated string of text. To do this, open the project’s src/app/app.component.ts file and include the following: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { public query: string; public constructor() { this.query = "starbucks"; } public ngOnInit() { } } The query variable is going to be bound to the form and it is also going to be used when searching for places and populating the map. It had to be declared in the TypeScript file to prevent any undefined errors. Finally, the project can be brought to a close with the core UI of the application. Open the project’s src/app/app.component.html file and include the following: <div style="padding: 10px 0"> <input type="text" placeholder="Search places..." [(ngModel)]="query" /> <button (click)="map.places(query)">Search</button> </div> <here-map #map</here-map> In the above HTML markup, there is a search field that is bound to the query variable in the TypeScript. There is a button that has a click event as well and it does some interesting things. Notice the #map template variable on the actual map component. This is how we get local reference to that particular UI element. The map component has a public method called places which accepts a string for a query. Now let’s jump back into the click event for the button. We are using the local component reference, calling the places method, and passing in the query variable from the input field. When the click event triggers, the search will occur and the markers will be placed on the map. Angular does some awesome things when it comes to binding of the data. To run this application, execute the following from the CLI: ng serve You’ll probably notice that when click a marker, the information bubble isn’t the most attractive due to word wrapping. We can clean it up through some simple CSS. Open the project’s src/styles.css file so we can add some global CSS: .H_ib_body { width: 275px; } If you’re a much better CSS wizard than I am, you can do some pretty amazing things when it comes to the cosmetics of this application. However, from a functional perspective, you should have a map that you can search for places as of now. Conclusion You just saw how to use the HERE Places API to populate markers on a map for points of interest using Angular and the various JavaScript libraries offered by HERE. This tutorial was a continuation of a previous getting started tutorial I wrote titled, Display HERE Maps within your Angular Web Application. If you haven’t seen the previous tutorial, I recommend you have a look to clear up any loose ends that this particular example with points of interest, may have brought up.
https://developer.here.com/blog/displaying-places-on-a-here-map-in-an-angular-web-application
CC-MAIN-2019-39
refinedweb
2,050
63.59
Jehiah Czebotar schrieb: > The following bug has been noted before, and I'm including a patch for > it that hopefully someone on this list can apply to trunk for me Thanks a lot for the bug report. I'll get that fixed that in the next DBUtils release. -- Christoph The following bug has been noted before, and I'm including a patch for it that hopefully someone on this list can apply to trunk for me The Error is as follows, and happens when a script or program is shutting down when the PooledDB object is getting cleaned up: Exception exceptions.TypeError: "'NoneType' object is not callable" in <bound method PooledDB.__del__ of <DBUtils.PooledDB.PooledDB instance at 0xb6a7166c>> ignored (previous observances) The problem code is in PooledDB: def __del__(self): """Delete the pool.""" if hasattr(self, '_connections'): self.close() However in my case _connections = 0, so we need to change it to do this: def __del__(self): """Delete the pool.""" if hasattr(self, '_connections') and self._connections>0: self.close() This was observed when using cx_Oracle as the database class but i don't know that it caused this at all because one of the referenced observances was against mysql a patch file against trunk is attached. (Credit for fixing this goes to Susan Anderson our DBA at work who tracked down the fix) -- Jehiah
http://sourceforge.net/p/webware/mailman/message/18828388/
CC-MAIN-2016-07
refinedweb
226
60.55
nukes block examplevebs Sep 3, 2004 11:36 AM Hi All i succesfully setup nukes with eclipse. now i want example to create block/module and deploy them on jboss. please do not give this url in your response as they are of no use thanks Vebs 1. Re: nukes block examplejae Sep 3, 2004 1:21 PM (in response to vebs) the "template" and "rss" modules are relatively simple and server as good starter examples. if you have a general overall understanding of what a sar archive is and how to create one through the build process (look at the build.xml examples in the other modules) you should be ok. there is also the project page that has a brief howto and any documentation in the wiki. feel free to contribute back and construct your own simple howto for others who wish to create a module. 2. Re: nukes block exampleMatthieu Chase Heimer Sep 3, 2004 2:22 PM (in response to vebs) That url that you don't want is probably the best howto right now. I'd recomment generating the javadoc html for the core and nukes source code from the Nukes source code and then just looking at the existing modules. If you want a basic block example here's one I did when I first was figuring out Nukes. I didn't even use ant much less eclipse so this should apply to anyone. Source for a basic block that just displays the current date: package org.jboss.nukes.examples; import org.jboss.nukes.block.BlockSupport; import org.jboss.nukes.html.Page; import java.util.GregorianCalendar; import java.util.Calendar; public class DateBlock extends BlockSupport { public void render(Page page) { GregorianCalendar calendar = new GregorianCalendar(); String month = null; switch(calendar.get(Calendar.MONTH)){ case 0: month = "January"; break; case 1: month = "February"; break; case 2: month = "March"; break; case 3: month = "April"; break; case 4: month = "May"; break; case 5: month = "June"; break; case 6: month = "July"; break; case 7: month = "August"; break; case 8: month = "September"; break; case 9: month = "October"; break; case 10: month = "November"; break; case 11: month = "December"; break; } page.print(month + " " + calendar.get(Calendar.DATE) + " " + calendar.get(Calendar.YEAR)); } } To compile you'll need to include nukes-lib.jar in your classpath. nukes-lib.jar can be found inside of the nukes.ear. You'll also need a xml configuration file called jboss-service.xml. The contents of it should be: <?xml version="1.0" encoding="UTF-8"?> <server> <mbean code="org.jboss.nukes.examples.DateBlock" name="nukes.blocks:name=date" xmbean- <depends>nukes.modules:name=core</depends> <xmbean> <attribute name="Title">Current Date</attribute> <attribute name="Side">0</attribute> <attribute name="Weight">0</attribute> <attribute name="Collapsable">false</attribute> </xmbean> </mbean> </server> You'll need to package both these pieces into a Service ARchive(a .sar file) which can be created with jar. Just put the class file (including the needed directory structure for it's package) into the base of the archive and put the jboss-service.xml into the META-INF folder in the archive. One you've done that just copy the archive to $JBOSS_HOME/server/default/nukes 3. Re: nukes block examplevebs Sep 3, 2004 4:28 PM (in response to vebs) Hello Chase, Yes I got sucesseded in running above example. THANKS very much. In future i may need ur help. thanks, vebs
https://developer.jboss.org/thread/95287
CC-MAIN-2018-22
refinedweb
569
65.52
Introduction to Reinforcement Learning Table of Contents - What is Reinforcement Learning? - Reinforcement Learning vs. the rest - Intuition to Reinforcement Learning - Basic concepts and Terminology - How Reinforcement Learning Works - Simple Implementation - Conclusion - References and Links What is Reinforcement Learning? Reinforcement learning in formal terms is a method of machine learning wherein the software agent learns to perform certain actions in an environment which lead it to maximum reward. It does so by exploration and exploitation of knowledge it learns by repeated trials of maximizing the reward. Reinforcement Learning vs. the rest Methods of machine learning, other than reinforcement learning are as shown below - One can conclude that while supervised learning predicts continuous ranged values or discrete labels/classes based on the training it receives from examples with provided labels or values. Unsupervised learning tries to club together samples based on their similarity and determine discrete clusters. Reinforcement learning on the other hand, which is a subset of Unsupervised learning, performs learning very differently. It takes up the method of "cause and effect". Intuition to Reinforcement Learning Let us try to understand the previously stated formal definition by means of an example - Imagine you are supposed to cross an unknown field in the middle of a pitch black night without a torch. There can be pits and stones in the field, the position of those are unfamiliar to you. There's a simple rule - if you fall into a hole or hit a rock, you must start again from your initial point. You start walking forward blindly, only counting the number of steps you take. After x steps, you fall into a pit. Your reward was x points since you walked that many steps. You start again from your initial position, but after x steps, you take a detour either left/right and again move forward. You hit a stone after y steps. This time your reward was y which is greater than x. You decide to take this path again but with more caution. When you start again, you make a detour after x steps, another after y steps and manage to fall into another pit after z steps. This time the reward was z points which was greater than y, and you decide that this is a good path to take again. You restart again, make the detours after x, y and z steps to reach the other side of the field. Thus, you've learned to cross the field without the need of light. Basic Concept and Terminology Insight In the above example, you are the agent who is trying to walk across the field, which is the environment. Walking is the action the agent performs on the environment. The distance the agent walks acts as the reward. The agent tries to perform the action in such a way that the reward maximizes. This is how Reinforcement Learning works in a nutshell. The following figure puts it into a simple diagram - And in the proper technical terms, and generalizing to fit more examples into it, the diagram becomes - Terminology Some important terms related to reinforcement learning are (These terms are taken from Steeve Huang's post on Introduction to Various Reinforcement Learning Algorithms. Part I)- - Agent: a hypothetical entity which performs actions in an environment to gain some reward. - Action (a): All the possible moves that the agent can take. - Environment (e): A scenario the agent has to face. - State (s): Current situation returned by the environment. - Reward (R): An immediate return sent back from the environment to evaluate the last action by the agent. - s under policy π. - Q-value or action-value (Q): Q-value is similar to Value, except that it takes an extra parameter, the current action a. Qπ(s, a) refers to the long-term return of the current state s, taking action a under policy π. How Reinforcement Learning Works There are majorly three approaches to implement a reinforcement learning algorithm. They are - - Value Based: in a value-based reinforcement learning method, you try to maximize a value function V(s). As defined in the terminology previously, Vπ(s) is the expected long-term return of the current state s under policy π. Thus, V(s) is the value of reward which the agent expects to gain in the future upon starting at that state s. - Policy-based: in a policy-based reinforcement learning method, you try to come up with a policy such that the action performed at each state is optimal to gain maximum reward in the future. Here, no value function is involved. We know that the policy π determines the next action a at any state s. There are two types of policy-based RL methods - - Deterministic: at any state s, the same action a is produced by the policy π. - Stochastic: each action has a certain probability, given by the equation below - - Model-Based: in this type of reinforcement learning, you create a virtual model for each environment, and the agent learns to perform in that specific environment. Since the model differs for each environment, there is no singular solution or algorithm for this type. A Simple Implementation Reinforcement Learning comes with its own classic example - the Multi-Armed Bandit problem. Never heard? No worries! Here's what it is - assume you're at a casino and in a section with some slot machines. Let's say you're at a section with 10 slot machines in a row and it says "Play for free! Max payout is 10 dollars" Each slot machine is guaranteed to give you a reward between 0 and 10 dollars. Each slot machine has a different average payout, and you have to figure out which one gives the most average reward so that you can maximize your reward in the shortest time possible. But why is it called the Multi-Armed Bandit problem? Think of the slot machine as a one-armed (single lever) bandit (because it generally steals your money!). Multiple slot machines, thus multi-armed bandit. And if you're still wondering, this is what a slot machine looks like - Source: Futurity One very obvious approach would be to pull the same lever every time. The probability of hitting the jackpot being very low, you'd mostly be losing money by doing this. Formally, this can be defined as a pure exploitation approach. Alternatively, you could pull the lever of each slot machine in hopes that at least one of them would hit the jackpot. This is another naive approach which would give you sub-optimal returns. Formally this approach is a pure exploration approach. ϵ (epsilon)-greedy algorithm One very famous approach to solving reinforcement learning problems is the ϵ (epsilon)-greedy algorithm, such that, with a probability ϵ, you will choose an action a at random (exploration), and the rest of the time (probability 1−ϵ) you will select the best lever based on what you currently know from past plays (exploitation). So most of the time you play greedy, but sometimes you take some risks and choose a random lever and see what happens. import numpy as np import random import matplotlib.pyplot as plt %matplotlib inline np.random.seed(5) First, import the necessary libraries and modules required to implement the algorithm. n = 10 arms = np.random.rand(n) eps = 0.1 #probability of exploration action You'll be solving the 10-armed bandit problem, hence n = 10. arms is a numpy array of length n filled with random floats that can be understood as probabilities of action of that arm. def reward(prob): reward = 0 for i in range(10): if random.random() < prob: reward += 1 return reward The reward functions work as such - for each arm, you run a loop of 10 iterations, and generate a random float every time. If this random number is less than the probability of that arm, you'll add a 1 to the reward. After all iterations, you'll have a value between 0 to 10. Why do you add a 1 only when the random number is less than the probability of that arm? Why not when it is more? The answer is, say you have a probability of 0.8 for an arm. You want 8 out of 10 times a positive response. That indicates that the positive response should be to the left of the probability value on the number line. #initialize memory array; has 1 row defaulted to random action index av = np.array([np.random.randint(0,(n+1)), 0]).reshape(1,2) #av = action-value #greedy method to select best arm based on memory array def bestArm(a): bestArm = 0 #default to 0 bestMean = 0 for u in a: avg = np.mean(a[np.where(a[:,0] == u[0])][:, 1]) #calculate mean reward for each action if bestMean < avg: bestMean = avg bestArm = u[0] return bestArm The next function you define is your greedy strategy of choosing the best arm so far. This function accepts a memory array that stores the history of all actions and their rewards. It is a 2 x k matrix where each row is an index reference to your arms array (1st element), and the reward received (2nd element). For example, if a row in your memory array is [2, 8], it means that action 2 was taken (the 3rd element in our arms array) and you received a reward of 8 for taking that action. And here is the main loop for each play. Let's play it 500 times and display a matplotlib scatter plot of the mean reward against the number of times the game is played. plt.xlabel("Number of times played") plt.ylabel("Average Reward") for i in range(500): if random.random() > eps: #greedy exploitation action choice = bestArm(av) thisAV = np.array([[choice, reward(arms[choice])]]) av = np.concatenate((av, thisAV), axis=0) else: #exploration action choice = np.where(arms == np.random.choice(arms))[0][0] thisAV = np.array([[choice, reward(arms[choice])]]) #choice, reward av = np.concatenate((av, thisAV), axis=0) #add to our action-value memory array #calculate the mean reward runningMean = np.mean(av[:,1]) plt.scatter(i, runningMean) As expected, your agent learns to choose the arm which gives it the maximum average reward after several iterations of gameplay. Thus, you've implemented a straightforward reinforcement learning algorithm to solve the Multi-Arm Bandit problem. Conclusion Reinforcement learning is becoming more popular today due to its broad applicability to solving problems relating to real-world scenarios. It has found significant applications in the fields such as - - Game Theory and Multi-Agent Interaction - reinforcement learning has been used extensively to enable game playing by software. A recent example would be Google's DeepMind which was able to defeat the world's highest ranked Go player and later, the highest rated Chess program Komodo. - Robotics - robots have often relied upon reinforcement learning to perform better in the environment they are presented with. Reinforcement learning comes with the benefit of being a play and forget solution for robots which may have to face unknown or continually changing environments. One well-known example is the Learning Robots by Google X project. - Vehicle navigation - vehicles learn to navigate the track better as they make re-runs on the track. A proof of concept is presented in this video while a real-life world example was presented at the O'Reilly AI Conference in this video. - Industrial Logistics - industry tasks are often automated with the help of reinforcement learning. The software agent facilitating it gets better at its task as time passes. BonsAI is a startup working to bring such AI to the industries. If you would like to learn more in Python, take DataCamp's Machine Learning for Time Series Data in Python course. References References - Sutton, Richard S. and Barto, Andrew G., Reinforcement Learning: An Introduction, MIT Press, 1998 - The Reinforcement Learning Repository, University of Massachusetts, Amherst - Wikipedia article on Reinforcement Learning - A Beginners Guide to Deep Reinforcement Learning Links If you still have doubts or wish to read up more about reinforcement learning, these links can be a great starting point -
https://www.datacamp.com/community/tutorials/introduction-reinforcement-learning
CC-MAIN-2021-04
refinedweb
2,030
54.42
Desktop Developer Writing a Windows service is significantly more involved than many authors would have you believe. Here are the tools you need to create a Windows service robust enough for the real world. Technology Toolbox: C#, Windows Services Most programmers know that you typically implement Windows services as executable programs. What many developers don't realize is that a single executable can contain more than one service. For example, the standard Windows intetinfo.exe process hosts several services, including IIS Admin, World Wide Web Publishing, and Simple Mail Transfer Protocol (SMTP). All services hosted by one executable and configured to use the same Log On account run in the same process. The first service to start launches the executable, and the last service to stop causes the process to exit. If you configure the services using different Log On propertiessay, service X runs as John, service Y runs as Mary, and both services are implemented in the same executableyou end up starting a separate process for each user identity of the launched services. A single process can contain more than one Windows service, and each service can perform several tasks (see Figure 1). For example, an online shop can use a service to send notifications about shipped products, payment collections, and weekly promotions. You can implement these operations as different services, or you can run them as different threads of the same service. A common approach is to implement logically related tasks as multiple threads of a single service and non-related tasks as different services. If you read a typical article explaining how to write a Windows service in C# or Visual Basic .NET, you get the impression that building Windows services is easy. Simply pick the Windows Service project template, follow the instructions provided in the MSDN documentation or online tutorials, add code to implement the application logic, and voilà, the service is ready. Unfortunately, many developers discover only after the fact that the Windows services they create using this approach are hard to manage. For one, you can't debug your service by pressing the F5 key from the Visual Studio .NET IDE. After you figure out how to launch the service executable from command line, debug messages won't appear if you try to display them by calling Console.Write or MessageBox.Show. You also get an error if you install the service using a Windows installer (MSI) package and then attempt to deploy a hot fix by executing an updated MSI file in repair mode. Finally, if your service performs multiple tasks running at scheduled times or timed intervals, you need to design all aspects of your solution, including the timing and multithreading. Faced with these issues, many developers turn to the Web and newsgroups to slog through the issues one-by-one. That brute-force method can work, after a fashion, but a far better solution is to avoid all these problems in the first place. This article comes with two code samples written in C#. The first sample contains a project to build a library (My.Utilities.dll), which provides classes for implementing easy-to-use Windows services. The SampleService project illustrates how you can incorporate this library in a project that implements several Windows services, each performing multiple tasks. There is also a sample setup project (SampleSetup), which shows how to implement the Windows service installer. The My.Utilities library code sample that accompanies this article includes several classes for building Windows service hosts, services, and threads (see Table 1). All classes related to Windows services belong to the My.Utilities.Services namespace. Implement Service Processes You can use the WindowsService class, which extends ServiceBase, to implement service processes and define properties of Windows services. When you derive a service process from WindowsService, you can debug it directly from the Visual Studio .NET IDE. It lets you execute the process from command line, display debug messages, and perform self-installation. This class has several helpful members, but you need to be aware of only a few of them. The static IsInteractive property is a simple wrapper for the obscure UserInteractive member of the Framework's System.Environment class. The service process can use it to determine whether it was launched by Service Control Manager (SCM) or an interactive user (for example, during debugging). The overloaded Run method uses different mechanisms to execute code depending on the value of the IsInteractive property. If the value is false, it simply calls the Run method of the ServiceBase class; otherwise, it calls the Start method of each hosted service (see Listing 1). When called from ServiceBase-derived classes, the .NET Framework's Console.Write and MessageBox.Show do not display any output. You can display debug messages during interactive execution by using the static ShowMessageBox method, which I implemented by reverse-engineering the private LateBoundMessageBoxShow method of the ServiceBase class. Be sure to add your code to the Start and Stop methods if you implement the main operations in a class derived from WindowsService rather than using the OnStart and OnStop event handlers. It's even better to isolate the business logic in the dedicated worker threads. A WindowsService object keeps track of the worker threads assigned to it through the WorkerThreads property, which contains an array of objects derived from the WorkerThread class. In addition to several helper members, WorkerThread declares two abstract methods: Start and Stop. When you launch a Windows service, it iterates through the worker threads and invokes the Start method on each of them. Similarly, it calls the Stop method after receiving a signal to stop (see Listing 2). You derive your own worker thread class from WorkerThread by adding the initialization and business logic to the Start routine and using the Stop method to implement the clean-up procedure. WorkerThread doesn't offer much functionality, but several classes derived from it do. These classes simplify the implementation of the timer-based operations. If your Windows service performs operations at scheduled times or timed intervals, you can base them on TimerThread, DailyThread, or WeeklyThread (see Figure 2). The TimerThread class executes the Run method at timed intervals defined through the Interval property. If the execution time of the Run method exceeds the specified interval, the thread keeps skipping the scheduled execution and waiting for the next interval until the Run method completes. If your service contains several threads executing at the same or close intervals, you might not want to fire all of them at the same time. You can make sure that the threads start at different times by setting their initial Delay properties to different values. Execute Daily Tasks You execute DailyThread and WeeklyThread once per day. DailyThread and WeeklyThread use the execution time of the day defined in the DailyExecutionTime property. The DailyExecutionTime property accepts a string value in the 24-hour format, such as "18:30." By default, the worker thread classes use GMT (UTC) for time-related operations, but you can change it by setting the value of the UseLocalTime property. DailyThread assumes that you must perform the given task every day, while WeeklyThread can run on the specified days of the week. For example, your service might need to send notifications to company employees on Wednesdays or workdays only. Use the DaysOfExecution property to specify the days you want to perform an operation. This property takes a bitmask value defined in the DaysOfWeek enumerated type. You don't typically need to follow a rigid execution schedule for classes derived from TimerThread, but it's critical for daily and weekly operations to be performed once and only once per day. If a service that sends daily notifications at 6 a.m. was down from 5:55 a.m. to 6:05 a.m., you would probably want to send the notification as soon as the service starts at 6:06 a.m.. On the other hand, if the service was down from 5:55 a.m. to 5:50 a.m. of the next day, it might make sense to wait for the next execution at 6 a.m. instead of sending two notifications within five minutes. When a daily (or weekly) thread starts, it checks the current time and compares it with the scheduled execution time using the 24-hour clock. If the execution time is in the past (for example, execution time is 6 a.m. and current time is 7 a.m.), the execution is scheduled for the next day. In the meantime, the thread keeps waking up after the interval defined in the WakeUpInterval property to check whether it must call the Run method. The thread executes the Run method after it reaches the scheduled execution time or if it detects that the last operation was performed more than a day ago and the next execution is not scheduled within the next 12 hours. Note that the WeeklyThread class also takes into account days of the week the task should execute. The thread resets the LastExecutionTime property after executing the Run method successfully. There is one problem with this approach. If the service stops (say the server crashes), you lose the information about the last execution time. You can preserve the last execution time in a persistent location (such as a database table or text file) by overriding the SetLastExecutionTime and GetLastExecutionTime methods. Build a Windows Service Building a Windows service requires several steps. Begin by creating a new project using the Windows Service template, then add a reference to the utilities library (My.Utilities.dll). Next, include a reference to the My.Utilities.Services namespace in your source code files (where needed), and change the base class for your Windows service process from ServiceBase to WindowsService. These steps are all straightforward. The next few steps get a little trickier, so I'll illustrate them using a sample Windows service. You implement the operation performed by your services in the worker thread classes derived from WorkerThread. If you need to perform an operation at scheduled times or at timed intervals, simply derive the worker thread from TimerThread, DailyThread, or WeeklyThread, and override the Run method. The SampleService project performs three tasks executed by two Windows services. The first service sends an e-mail notification to the users whose passwords are about to expire once per day, except during the weekend. The second service queries an external data source every two minutes and copies any new users it finds to the local database. It also applies updates to the existing users stored in the local database every five minutes. You can view these tasks as three distinct operations, so the solution splits them into separate worker thread classes: PasswordCheckThread (derived from WeeklyThread), NewUserThread, and UserUpdateThread. You derive the latter two worker threads from TimerThread. The worker thread classes implement the business logic of the designated operations by overriding the Run methods. Note that I kept the code simple by making the Run methods in the sample classes write only informational messages to the application log file using a static helper method of the service host. The sample illustrates a case when an operation takes longer to complete than expected by forcing NewUserThread and UserUpdateThread to sleep at random intervals. Note that the worker threads don't contain any initialization logic or data, such as execution frequency or initial delay. The server process performs these tasks. The Main function of the service process handles initialization and invocation of the hosted services and worker threads. Implementing the service process takes only a few steps. Create a Windows Service project, then rename the wizard-generated Service1 class (and file) to something more meaningful, such as ServiceHost. Next, change the Main function definition to include the command-line parameters (you can also delete the function contents): using My.Utilities.Services; ... // Derive service host from WindowsService // instead of ServiceBase. public class ServiceHost: WindowsService { ... private static void Main ( string[] args ) { } } In Main, create objects for each worker thread that you have implemented already and initialize their runtime properties: NewUserThread newUserThread = new NewUserThread(); newUserThread.Name = "New User Check"; newUserThread.Delay= 0; newUserThread.Interval = 2 * 60 * 1000; You can also pass initialization parameters through overloaded constructors, but you need to implement those as well. You might want to store these values in a configuration file in a real application. Create the Service Objects After you initialize the worker threads, create the Windows service objects and define their properties. At a minimum, you need to specify the service name and assign the worker threads to it: WindowsService userCheckService = new WindowsService(); userCheckService.ServiceName = "Test Service: User Check"; userCheckService.WorkerThreads = new WorkerThread[] { newUserThread, userUpdateThread }; Finally, create an array of the ServiceBase objects holding the initialized services and execute the overloaded Run method passing the array and optional command-line arguments to it: ServiceBase[] services = new ServiceBase[] { userCheckService, }; Run(services, args); The Run method implemented by WindowsService lets you execute the service manually. Note that this method is different from the one implemented in the ServiceBase class, which takes one parameter instead of two. At this point, you must be able to debug your services or execute them from the command prompt. For testing purposes, set breakpoints or add code to display a debug message using WindowsService.ShowMessageBox in the Run methods of the worker threads: override protected void Run ( object source ) { WindowsService.ShowMessageBox( "Executing {0}", Name); ... } Add the installer class to the service project to install and uninstall your service. Rename the class and file to something meaningful such as WindowsServiceInstaller, and make sure that you derive it from System.Configuration.Install.Installer. The class also needs the RunInstaller attribute: using System.Configuration.Install; using System.ServiceProcess; ... [RunInstaller(true)] public class WindowsServiceInstaller : Installer { ... } Use the class constructor to implement the initialization logic (see Listing 3). I don't like the fact that this code hard-codes the name and display name of the services because you also use the names of the services in the Main function of the service host. Remember to change the string literals in several places if you ever decide to rename a service; otherwise, the service will fail. You can avoid this problem by defining and referencing the names of the services using static properties: public class ServiceHost: WindowsService { internal static string UserCheckServiceName = "Sample Service: User Check"; internal static string "Sample Service: Email Notifier"; ... } The sample code uses identical values for both the service name and its display name, but they don't have to be the same. You must also be aware that the Account property of a ServiceInstaller object that is assigned the value of ServiceAccount.User (instead of ServiceAccount.LocalSystem) will cause the setup process to fail if the user running the installer mistypes the account name or password. Create the Setup File You can install the services after you implement the installer class. A typical approach is to use the .NET Framework's Installer Tool (InstallUtil.exe). I'll skip this option because it's been covered extensively elsewhere. Instead, I'll describe two alternatives: incorporating the installer in an MSI package and creating a self-installer. You can enable the MSI package to install your services by defining a custom action and associating it with the service executable. If you use the Setup Project template in Visual Studio .NET, simply switch to the Custom Actions view, and add a new custom action to the Install, Commit, Rollback, and Uninstall events, associating them with the service executable (see Figure 3). The Services Control Panel displays your services after you build the MSI file and run the setup. You still need to address one important problem. If you fix a bug in the service code and want to deploy it by executing the modified setup package in the repair mode, the setup fails. You need to reinstall the application to deploy the fix. You can use one of several alternatives if this becomes a hassle (and it will). One option is to add code to the service installer constructor to detect whether the relevant services are installed already (you can use helper methods exposed by the WindowsService class for this). If the services are installed, the logic won't create the corresponding installer objects, effectively making it a no-op. You can achieve the same effect by setting the Condition field of the custom action associated with the Install event to NOT REINSTALL (case-sensitive) (see Figure 4). You can enable self-installation in a Windows service host class derived from WindowsService by adding this block of code at the beginning of the Main method (the first parameter of the InstallOrUninstall method expects the command-line switches; the second parameter must contain an instance of your service installer class): public class ServiceHost: WinodwsService { ... private static void Main ( string[] args ) { if (InstallOrUninstall(args, new WindowsServiceInstaller())) { return; } ... } } Inserting this code and executing the program from command prompt with the /i switch installs the services, while the /u switch uninstalls them. I've documented the source code extensively, so take a look at the code comments if you want to learn how the functionality described in this article is implemented in the utilities library. You can also check the provided help file located under the library project folder; it describes several features not mentioned in this article. Printable Format > More TechLibrary I agree to this site's Privacy Policy.
https://visualstudiomagazine.com/articles/2005/10/01/write-a-better-windows-service.aspx
CC-MAIN-2018-39
refinedweb
2,902
53.71
.] 26 thoughts on “Building a simple [Yahoo] S4 application” Very useful. Can you please give some complex examples and explain how S4 works? particularly in cases like how it can be used to find perfect advertisement for a user.. Thanks! @Sundar, See part 5 Online Parameter Optimization in the s4 paper. It details how you can use S4 for automatic tuning of parameters for advertising system using live traffic. 1) if a have a Test.java like class Test{ String carNo; int yearOfMacnufature; float noOfKm; } and i want to send these type of objects as a event, then what should the string representation of my Message object look like: i mean Message m = new Message(“RawCarRecord”, “bean.Test”, “What should be the string representation for above class”); 2) what is the use of overriding toString() method in each bean class(Words,Sentence)??? 1. The string representation for the message should be the json representation, for example {"carNo":"1234", "yearOfMacnufature":1984,"noOfKm":5230.21} 2. toString methods are overriden just for debugging purpose. Its not necessary. HI,this is an application of S4 0.3.Would you like to give me an application of S4 0.5? Hey anand, great post. I am currently trying to run it, and had a hard time figuring out the a small change in the code. import io.s4.* should now be: org.apache.s4.* Moreover, I am not able to run the java client library due to this exception: org.apache.s4.client.util.ObjectBuilder$Exception: bad class name for json-encoded object: test.s4.Word at org.apache.s4.client.GenericJsonClientStub.eventWrapperFromBytes(GenericJsonClientStub.java:56) at org.apache.s4.client.ClientConnection$1.run(ClientConnection.java:132) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.ClassNotFoundException: test.s4.Word Any hints on what might be wrong? I've included the S4WordCount.jar in the classpath, but it's not able to find the test.s4.Word class Thanks again M. The S4 project has been moved to Apache Incubator, hence the name change. You can either rename the imports or use s4 0.3.0 available at github. This should also solve your second problem. Is it the same error as Exception: Cannot find class [test.s4.WordReceiverPE]…????? It seems to be the same error. I’d suggest using the 0.3 available at github. (link above) I am using that version . But still seem to get that same problem.Not able to compile the program. It says classes bot found. So do we have to create a class folder with the details of the classes and then it might run? Other examples of s4 seem to have a class folder which specifies the classes used in the example. I think jar should work perfectly fine, see the directory structure mentioned in this post. Also when I try to compile WordReceiverPE.java or SentenceReceiverPE.java using javac i get error: package org.apache.s4.client does not exist. So am not able to get the class WordReceiverPE.class and hence showing the error- class not found. Are you keeping the s4 jars on classpath while compiling? If problem persists, try using eclipse to compile the files after adding those jars manually to your buildpath. What are the contents of the jar file actually? The core classes of s4. If stuck, try gradle eclipseto convert your project to an eclipse project. And could you please elaborate the solution ????? can i compile the source files of ‘WordCount’ example using gradlew? I haven’t tried that but it should work. See twitter topic count example. Sir we have 4 java files in which 2 of them are PE.java .So when i try to compile all 4 of them together using javac I am getting an error- SentenceReceiverPE.java:3: error: package io.s4.processor does not exist import io.s4.processor.AbstractPE. So is there any way to compile this? Also is it because of the path not specified properly – import org.apache.processor.abstractPE ? Sir actually inside the jar file am only having one file META_INF. The class files are not there. Hence i tried to compile them seperately using javac. Getting the errors i mentioned before. actually does ./gradlew allImage produce the class files. Dint work for me. I was able to run s4. But i am getting one last error ~/s4$ java TestMessageSender localhost 2334 RawWords test.s4.Word Exception in thread “main” java.lang.NoClassDefFoundError: TestMessageSender Caused by: java.lang.ClassNotFoundException: TestMessageSender: TestMessageSender. Program will exit. hello i tried using s4 in localhost .it works fine.then i copied the s4 folder from git repository to a server.there i when i tried building the s4 using ./graldlew build i get following error ###@#### # ./gradlew Downloading Exception in thread “main” java.net.UnknownHostException: repo.gradle.org at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:525) at java.net.Socket.connect(Socket.java:475) at sun.net.NetworkClient.doConnect(NetworkClient.java:163) at sun.net. at sun.net. at sun.net. at sun.net. at sun.net. at sun.net. at sun.net. at sun.net. at sun.net. at org.gradle.wrapper.Download.downloadInternal(Download.java:49) at org.gradle.wrapper.Download.download(Download.java:37) at org.gradle.wrapper.Install.createDist(Install.java:54) at org.gradle.wrapper.Wrapper.execute(Wrapper.java:80) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:37) gradle is trying to access the internet for building the s4 inside the server.but the server is not connected to the network.try enabling network access for the server Hi Anand, Any Idea, How to receive events from S4? any sample code? Thanks, sara-
https://anandnalya.com/2011/09/building-a-simple-yahoo-s4-application/
CC-MAIN-2020-40
refinedweb
964
54.49
The Lending Club is a peer-to-peer lending site where members make loans to each other. The site makes anonymized data on loans and borrowers publicly available. We're going to use these data to explore how the interest rate charged on loans depends on various factors. We want to explore these data, try to gain some insights into what might be useful in creating a linear regression model, and to separate out "the noise". We follow these steps, something we will do in future for other data sets as well. The data have the following variables (with data type and explanation of meaning) Amount.Requested - numeric. The amount (in dollars) requested in the loan application. Amount.Funded.By.Investors - numeric. The amount (in dollars) loaned to the individual. Interest.rate – character. The lending interest rate charged to the borrower. Loan.length - character. The length of time (in months) of the loan. Loan.Purpose – categorical variable. The purpose of the loan as stated by the applicant. Debt.to.Income.Ratio – character The % of consumer’s gross income going toward paying debts. State - character. The abbreviation for the U.S. state of residence of the loan applicant. Home.ownership - character. Indicates whether the applicant owns, rents, or has a mortgage. Monthly.income - categorical. The monthly income of the applicant (in dollars). FICO.range – categorical (expressed as a string label e.g. “650-655”). A range indicating the applicants FICO score. Open.CREDIT.Lines - numeric. The number of open lines of credit at the time of application. Revolving.CREDIT.Balance - numeric. The total amount outstanding all lines of credit. Inquiries.in.the.Last.6.Months - numeric. Number of credit inquiries in the previous 6 months. Employment.Length - character. Length of time employed at current job. We. %matplotlib inline # first we ingest the data from the source on the web # this contains a reduced version of the data set from Lending Club import pandas as pd loansData = pd.read_csv(' FICO Range is represented as a categorical variable in the data. We need to change the categorical variable for FICO Range into something numeric so that we can use it in our calculations. As it stands, the values are merely labels, and while they convey meaning to humans, our software can't interpret them as the numbers they really represent. So as a first step, we convert them from categorical variables to strings. So the abstract entity 735-739 becomes a string "735-739". Then we parse the strings so that a range such as "735-739" gets split into two numbers (735,739). Finally we pick a single number to represent this range. We could choose a midpoint but since the ranges are narrow we can get away with choosing one of the endpoints as a representative. Here we arbitrarily pick the lower limit and with some imperious hand waving, assert that it is not going to make a major difference to the outcome. In a further flourish of imperiousness we could declare that "the proof is left as an exercise to the reader". But in reality there is really no such formal "proof" other than trying it out in different ways and convincing oneself. If we wanted to be mathematically conservative we could take the midpoint of the range as a representative and this would satisfy most pointy-haired mathematician bosses that "Data Science Dilbert" might encounter. To summarize - cleaning our data involves: There is one especially high outlier with monthly income > 100K$+. This is likely to be a typo and is removed as a data item. There is also one data item with all N/A - this is also removed. Now we are going to follow a standard set of steps in exploring data. We apply the following simple visualizations. This is something we will typically also do for other data sets we encounter in other explorations. A histogram shows us the shape of the distribution of values for a single variable. On the x-axis we have the variable under question, divided into buckets or bins. This is a key feature of a histogram. The bin size is adjustable and different bin sizes give different information. A large bin size gives us an idea of the coarser grained structure of the distribution while a smaller bin size will shine light on the finer details of the distribution. In either case we can compare distributions, or quickly identify some key hints that tell use how best to proceed. With the distribution of FICO scores we see the histogram below. import matplotlib.pyplot as plt import pandas as pd plt.figure() loansmin = pd.read_csv('../datasets/loanf.csv') fico = loansmin['FICO.Score'] p = fico.hist() Why do we look at FICO score? Because we know from domain knowledge that this is the primary determinant of interest rate. The histogram shows us that the distribution is not a normal or gaussian distribution but that there are some other factors that might be affecting or distorting the shape of the distribution away from the bell curve. We want to dig a little deeper. Next we take a box plot which allows us to quickly look at the distribution of interest rates based on each FICO score range.(' ') <matplotlib.figure.Figure at 0x10222d790> First of all this tells us that there is a general downward trend in interest rate for higher FICO scores. But, given the same range of FICO scores we see a range of interest rates not a single value - so it appears there are other factors determining interest rate, given the same FICO score range. We want to investigate the impact of these other drivers and quantify this impact. What might these be? Let's use a little domain knowledge again. We know interest rate is based on risk to the borrower: the greater the risk, the greater the interest rate charged to compensate for the risk. Another factor that might affect risk is the size of the loan - the larger the amount the greater the risk of non-payment and also the greater the negative impact of actual default. We want to look at multiple factors and how they might affect the interest rate. A great way to look at multiple factors simultaneously is the scatterplot matrix. We are going to use this as the next step in visual exploration. But first what is it? The scatterplot matrix is a grid of plots of multiple variables against each other. It shows the relationship of each variable to the others. The ones on the diagonal don't fit this pattern. Why not? What does it mean to find the relationship of something to itself, in this context. Not much, since we are trying to determine the impact of some variable on another variable.) In this diagram, the boxes on the diagonal contain histogram plots of the respective variable itself. So if the 3rd variable is Loan Amount then the third row and third column are the Loan Amount column and row. And the third element down the diagonal is the histogram of the Loan Amount. To see how Loan Amount (3rd) affects Interest Rate (1st) then we look for the intersection of the 3rd row and the 1st column. We also notice that we could have looked for the intersection of the 3rd column and 1st row. They have the same plot. The scatterplot matrix plot is visually symmetric about the diagonal. Where there is some significant, useful effect we will see a noticeable trend in the scatterplot at the intersection. Where there is none we will see no noticeable trend. What do the last two sentences mean in practice? Let's compare two plots: the first one at the intersection of 1st row and 2nd column, and the second at the intersection of 1st row 4th column. In the first, FICO score shows an approximate but unmistakeable linear trend. In the second, Monthly Income shows no impact as we move along the x-axis. All the dots are bunched up near one end but show no clear, linear trend like the first one. Similarly there is no obvious variation in the plot for Loan Length while there is a distinct but increasing trend trend also in the plot for Loan Amount. So what does this suggest? It suggests that we should use FICO and Loan Amount in our model as independent variables, while Monthly Income and Loan Length don't seem to be too useful as independent variables. So at the end of this data alchemy exercise we have distilled our variables into two beakers - one has what we believe is relevant - the data nuggets, and the other, the data dross.....the variables that have no visible impact on our dependent variable. We're going to refine our output even further into a model in the next step - the analysis. from IPython.core.display import HTML def css_styling(): styles = open("../styles/custom.css", "r").read() return HTML(styles) css_styling()
https://nbviewer.ipython.org/github/nborwankar/LearnDataScience/blob/master/notebooks/A2.%20Linear%20Regression%20-%20Data%20Exploration%20-%20Lending%20Club.ipynb
CC-MAIN-2022-21
refinedweb
1,498
64.81
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Relations6:30 with Chris Jones and Kenneth Love What all different ways can you display foreign key relationships? - 0:00 For now I think I'm done with API views. - 0:03 There are a couple more topics I want to touch on though before I get to - 0:05 securing the API. - 0:06 The review model has a foreign key relationship to a course. - 0:11 Currently with the API the user has to go to the special reviews url to - 0:14 see the reviews for a specific course. - 0:16 What if instead I just included all of the reviews with the course. - 0:20 Or I might want to list the foreign keys to those reviews with each course. - 0:24 Maybe I could have a list of URLs to each review instead. - 0:28 Each of these approaches is possible and each has potential benefits and drawbacks. - 0:33 So I'm here in courses Serializers.py and the first - 0:38 option I want to look at is the idea of nested relationships and this is where - 0:43 there are related records that need to be included inside of a particular resource, - 0:47 which is kind of like, well it's how reviews should show up in course records. - 0:53 You can use the review Serializer as a field on the course Serializer and - 0:58 this causes full reviews to be populated into the course data. - 1:02 So let me let me show you how to do that. - 1:03 So down here in the course Serializer I'm going to add a new - 1:07 attribute here that's called Reviews and it's gonna be ReviewSerializer. - 1:14 It's going to be many equals true and read only - 1:19 equals true and if you looked at the models you know that reviews - 1:23 is the reverse relationship name between a review and a course. - 1:28 So it just it's going to take that right that bit of data and - 1:32 we now of course have to add reviews to our list of fields. - 1:38 Okay so let's see what this does. - 1:42 So come back over here and let's do courses one. - 1:46 Actually this is two courses and here we go Python basics. - 1:50 The reviews it has one review which is this one from - 1:53 this lovely person named Kenneth, and then these two don't have any reviews yet, so - 1:58 we get just an empty list for the reviews. - 2:01 So, great. - 2:03 That's pretty awesome. - 2:04 So this works, it's good. - 2:06 There is a drawback though. - 2:08 What happens when this course here, or - 2:12 any of these courses, have thousands of reviews. - 2:15 What happens when there are thousands of courses that have thousands of reviews. - 2:19 The amount of time it takes the API to respond is just going to increase. - 2:23 It's gonna get bigger and bigger and - 2:24 bigger the more data they get sent back to the client. - 2:27 Things could go downhill really fast and I don't want that to happen. - 2:32 So this type of approach works really well. - 2:35 It works better when you know that you have a limited amount of data - 2:39 that's gonna be displayed. - 2:40 There's a certain amount of data that's gonna come out. - 2:42 Nothing else is ever gonna come out. - 2:44 Like a one-to-one relationship, where one user has one profile. - 2:49 That's great, that's fine, because it's only ever gonna be - 2:51 two records that come out, one user and one profile at any given time. - 2:55 So that's awesome. - 2:57 That's not what we have here though. - 2:58 Here I have as many things as possible. - 3:02 So, let me show you another one, which is the hyperlinked related field. - 3:06 So back over here in Serializers and - 3:10 here instead of review Serializer I'm gonna say - 3:14 serializer.Hyperlinked link - 3:19 not liked RelatedField capital F Field. - 3:25 All right it's still many equals true it's still read only. - 3:30 But now it has a new attribute, which is view_name, or new argument rather. - 3:35 And I'm gonna say apiv2, which is the namespace. - 3:39 And review-detail, which is the automatically generated view name for - 3:44 the view set in the router. - 3:47 Cool. - 3:48 Okay, so now let's go refresh this. - 3:51 And now what's cool is I have reviews and I just have a link here to a review. - 3:55 And I'm wanna Command+click that opens in a new tab and there's that review. - 4:00 So this is actually what's recommend you here - 4:05 when people talk about APS, I talk about Hiteioas. - 4:09 H-I-T-E-I-O-A-S which nobody really reads into how you say that. - 4:13 Anyway the idea is that things are always hyperlinked to each other. - 4:16 You don't include a huge amount of data that you don't need to include - 4:19 when they can go get it at another end point. - 4:22 So you send them off to that other end point. - 4:24 They get the data they need and then they do whatever they need to do. - 4:29 So that's great that's really cool. - 4:32 Again this is a really good and decent solution but - 4:35 if you have thousands of reviews for even one of your resources. - 4:40 This could start just drastically increase in the API - 4:43 response time because Django has to go and - 4:45 create those URLs for every single one of those reviews so pros and cons. - 4:50 Let me let me show you one last possibility here which instead of - 4:54 the hyperlink related field, we're going to change hyperlink here to primary, - 5:00 primary key related fields and we don't need that - 5:05 view name anymore it can just be mean equals true and read only equals true. - 5:10 So come back over here refresh and now I just have one. - 5:15 So just the ID is is one. - 5:17 This is probably the best this is probably the fastest option because all it has do - 5:21 is go grab that injure every single time right it just goes and gets that primary - 5:24 key you can get primary keys you can get integers out of it's really fast. - 5:29 So this is great if you can expect your users to somehow know that URL. - 5:34 Maybe you add in a reviews URL link that will tell them what that is and - 5:39 they can just append the one or the fifteen or the two thousand and - 5:43 eighty two or whatever onto the end of it that's going to depend on your API so - 5:47 I'll let you make those decisions yourselves. - 5:50 Personally, I really like the hyperlinked one especially when I'm using - 5:53 the browsable API because that way I can just click around and - 5:55 go see what all my stuff is. - 5:57 But again, it's totally going to depend on your API and your API's needs. - 6:03 As you've seen, you have a lot of options for how to serialize related records. - 6:07 I recommend looking over the full documentation for - 6:09 Serializer relationships. - 6:10 So I put a link in the teacher's notes. - 6:12 You can get very specific with the way that you handle relationships on your - 6:15 serializer, so it's good to know your options and the potential drawbacks. - 6:19 Try them out test them with unit tests and - 6:21 load testing tools if you're curious how they perform. - 6:24 For this project though, I think it makes the most sense to keep the reviews - 6:27 on a separate API view which is already in place.
https://teamtreehouse.com/library/django-rest-framework/make-the-rest-framework-work-for-you/relations
CC-MAIN-2019-09
refinedweb
1,455
78.99
The XmlDataDocument Class The System.Xml namespace also includes the capability to automatically synchronize a DataSet with an equivalent XML file. The XmlDocument class is useful for working with XML via the DOM, but it's not a data-enabled class. To bring the DataSet class into the picture, you need to use an XmlDataDocument class, which inherits from the XmlDocument class. Table 3.4 shows the additional members the XmlDataDocument class adds to the XmlDocument class. Table 3.4 Additional Members of the XmlDataDocument Class The XmlDataDocument class allows you to exploit the connections between XML documents and DataSets. You can do this by synchronizing the XmlDataDocument (and hence the XML document that it represents) with a particular DataSet. You can start the synchronization process with any of the following objects: An XmlDataDocument A full DataSet A schema-only DataSet If you have an XML file in an XmlDataDocument object, you can retrieve a DataSet object from its DataSet property. Here's how you might load a DataSet using this technique: ' Create a new XmlTextReader on a file Dim xtr As XmlTextReader = _ New XmlTextReader("Books.xml") ' Create an object to synchronize Dim xdd As XmlDataDocument = New XmlDataDocument() ' Retrieve the associated DataSet Dim ds As DataSet = xdd.DataSet ' Initialize the DataSet by reading the schema ' from the XML document ds.ReadXmlSchema(xtr) ' Reset the XmlTextReader xtr.Close() xtr = New XmlTextReader("Books.xml") ' Tell it to ignore whitespace xtr.WhitespaceHandling = WhitespaceHandling.None ' Load the synchronized object xdd.Load(xtr) This code performs some extra setup to make sure the DataSet can hold the data from the XmlDataDocument. Even when you're creating the DataSet from the XmlDataDocument, you must still explicitly create the schema of the DataSet before it will contain data. That's because in this technique, you can also use a DataSet that represents only a portion of the XmlDataDocument. In this case, the code takes advantage of the ReadXmlSchema method of the DataSet object to automatically construct a schema that matches the XML document. Because the XmlTextReader object is designed for forward-only use, the code closes and reopens this object after reading the schema so that it can also be used to read the data. CAUTION When you use the ReadXmlSchema method of the DataSet object to construct an XML schema for the DataSet, both elements and attributes within the XML document become DataColumn objects in the DataSet. A second way to end up with a DataSet synchronized to an XmlDataDocument is to start with a DataSet. To use this technique, you simply pass the DataSet (which you have already filled with data) to the XmlDataDocument object's constructor: ' Fill the DataSet SqlDataAdapter1.Fill(DsCustomers, "Customers") ' Retrieve the associated document Dim xdd As XmlDataDocument = _ New XmlDataDocument(DsCustomers) The third method to synchronize the two objects is to follow a three-step recipe: Create a new DataSet with the proper schema to match an XML document, but no data. Create the XmlDataDocument from the DataSet. Load the XML document into the XmlDataDocument. One way to manage this is to use an XML schema file. An XML schema file describes the format of an XML file. For example, here's an XML schema description of Books.xml: <?xml version="1.0" encoding="utf-8" ?> <xs:schema <xs:element <xs:complexType> <xs:choice <xs:element <xs:complexType> <xs:sequence> <xs:element <xs:element </xs:sequence> <xs:attribute </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> Given this schema file, with a name such as Books.xsd, you can construct the corresponding DataSet by calling the ReadXmlSchema method of a DataSet object and from there create the corresponding XmlDataDocument: ' Create a dataset with the desired schema Dim ds As DataSet = New DataSet() ds.ReadXmlSchema("Books.xsd") ' Create a matching document Dim xd As XmlDataDocument = _ New XmlDataDocument(ds) ' Load the XML xd.Load("Books.xml") The advantage to using this technique is that you don't have to represent the entire XML document in the DataSet schema; the schema only needs to include the XML elements you want to work with. For example, in this case the DataSet does not contain the Publisher column, even though the XmlDataDocument includes that column (as you can verify by inspecting the information in the ListBox control).
https://www.informit.com/articles/article.aspx?p=101369&seqNum=2
CC-MAIN-2022-05
refinedweb
718
51.78
sub test4 { my ( $iDays, $iCmp ) = @_; my $iRes = 0; for ( 1, 2, 4, 8, 16, 32, 64 ){ if ( $iDays & $iCmp & $_ ){ $iRes++; } } return $iRes; } sub test5 { my ( $iDays, $iCmp ) = @_; my $iRes = 0; $iRes++ if ( $iDays & $iCmp & 1 ); $iRes++ if ( $iDays & $iCmp & 2 ); $iRes++ if ( $iDays & $iCmp & 4 ); $iRes++ if ( $iDays & $iCmp & 8 ); $iRes++ if ( $iDays & $iCmp & 16 ); $iRes++ if ( $iDays & $iCmp & 32 ); $iRes++ if ( $iDays & $iCmp & 64 ); return $iRes; } cmpthese($count, { 'Test4' => sub { test4( int ( rand(127) ), int( rand(127) ) ) }, 'Test5' => sub { test5( int ( rand(127) ), int( rand(127) ) ) } }); __DATA__ Rate Test4 Test5 Test4 162690/s -- -46% Test5 300000/s 84% -- [download] Are you a hacker? Are you not worried if your code looks like crazy old magic? Then you'll love this solution: sub test0 { return ((($_[0] & $_[1]) * 2113665) & 17895697) % 15; } [download] (Go ahead! Check that it's correct for all input values!) Benchmarks on my computer, against your code and hv's: Rate Test4 Test5 Test7 Test6 Test0 Test4 64233/s -- -33% -33% -52% -72% Test5 95523/s 49% -- -1% -29% -58% Test7 96399/s 50% 1% -- -28% -58% Test6 133602/s 108% 40% 39% -- -41% Test0 227756/s 255% 138% 136% 70% -- [download] Are you a hacker? Don't you know the C precedence table by heart? Then why do you need those crazy parentheses around the multiplication? Isn't this enough: sub test1 { (($_[0] & $_[1]) * 2113665 & 17895697) % 15; } [download] Anyway, I like your method. Nice idea to search in HAKMEM. As you can see below, I've given a less concise solution. Here's a hint: 0b1000000100000010000001 == 2113665 and 0b1000100010001000100010001 == 17895697. I'd gladly explain what's going on, but it seems that some people have already done it online, so I'll link to them instead. In short, multiplying by the first value "repeats" the input four times, while the second knocks out all but every fourth bit. Finally, we "cast out 15s". Online resources: spurperl, below, linked to Bit Twiddling Hacks by Sean Eron Anderson of Stanford which contains this and many other bit hacks. Anderson, in turn, links to A Modulo Based Bit Counting Approach For 64 Bit Systems by Roshan James, an explanation of my solution above (more or less). Simply note the differences in integer size (they have 64 bits, while most of us only have 32) and requirements (our input is at most 7 bits, and they allow 16). I personally was inspired by a section of the HAKMEM, as I linked above (this also has a difference in size --- the PDP-1110 had 36-bit integers --- and requirements --- 9 bit input). For speed, I'd suggest: sub test6 { my $n = $_[0] & $_[1]; my $count = 0; ++$count, $n &= $n - 1 while $n; $count; } [download] For beauty I'd suggest hiding that behind a suitable function name - it costs an extra function call, but you can probably lose that in the way you call it when not benchmarking: sub countbits { my($n, $count) = ($_[0], 0); ++$count, $n &= $n - 1 while $n; return $count; } sub test7 { my($iDays, $iCmp) = @_; return countbits($iDays & $iCmp); } [download] You might even want to add some comments. :) Benchmarks: Rate Test4 Test5 Test7 Test6 Test4 106192/s -- -38% -40% -57% Test5 172463/s 62% -- -3% -31% Test7 176987/s 67% 3% -- -29% Test6 248686/s 134% 44% 41% -- [download] Hugo You can find a lot of info about it online, for example here. To make a long story short, the fastest technique is table lookup. Precompute the counts for all bytes (256 of them) in a table and do a simple lookup to find results later. What you've been shown by kaif and others are the more arcane and enjoyable methods, but table lookup will be faster. spurperl is right, table lookup is fastest. Using the notation op for original poster, lt for "lookup table", and the rest obvious, the overall benchmark looks something like this: Rate op4 op5 hv7 hv6 roy4 kaif lt op4 64233/s -- -33% -33% -52% -57% -72% -76% op5 96098/s 50% -- -0% -28% -36% -58% -64% hv7 96399/s 50% 0% -- -28% -35% -58% -64% hv6 134032/s 109% 39% 39% -- -10% -41% -50% roy4 149447/s 133% 56% 55% 12% -- -34% -45% kaif 227019/s 253% 136% 135% 69% 52% -- -16% lt 270514/s 321% 181% 181% 102% 81% 19% -- [download] Just be sure to initialize your table outside of your function, that is, initialize only once. # Reused your sub name sub test4 { return unpack("%4b*", pack('C', $_[0] & $_[1])); } __END__ Rate Test5 Test4 Test0 Test5 88345/s -- -34% -47% Test4 133240/s 51% -- -20% Test0 167395/s 89% 26% -- [download] The problem is essentially to count the number of bits in an integer. There's a good solution for this, which I'll show now. This subroutine from MMIXware is supposed to do exactly this. This is for a 32-bit word though, not just 7 bits. #!perl use warnings; use strict; # the following subroutines couns the number of bits in an 8-bit integ +er sub sadd8_a { # my first solution -- without looking closely to your c +ode my($x) = @_; my $n = 0; for (my $k = 1; $k < 0x100; $k <<= 1) { 0 != ($x & $k) and $n++; } $n; } sub sadd8_b { # one of your solutions, modified a bit my ( $iDays ) = @_; my $iRes = 0; for ( 1, 2, 4, 8, 16, 32, 64, 128 ){ if ( $iDays & $_ ){ $iRes++; } } return $iRes; } sub sadd8_c { my($x) = @_; $x = ($x & 0b01010101) + ($x >> 1 & 0b01010101); $x = ($x & 0b00110011) + ($x >> 2 & 0b00110011); ($x & 0b00001111) + ($x >> 4); } # let's print an example for my $n (0 .. 31) { print sadd8_a($n), " "; } print "\n"; # test for my $n (0 .. 255) { my $a = sadd8_a($n); my $b = sadd8_b($n); my $c = sadd8_c($n); $a == $b && $b == $c or die "wrong results: $n $a $b
http://www.perlmonks.org/index.pl?node_id=465349
CC-MAIN-2015-48
refinedweb
975
77.4
30 July 2012 07:57 [Source: ICIS news] MELBOURNE (ICIS)--?xml:namespace> Mitsui Chemicals shut all its units at Iwakuni-Ohtake Works following a blast at its resorcinol facility on 22 April. The company official did not give a specific date for the plant’s restart. However, Mitsui Chemicals said on its website on 26 July that routine operations in the Ohtake area, including those at the MIBK plant, had resumed. “Operations have resumed at most plants following confirmation of safety and conditions and with approval from authorities,” the company said in the statement. Mitsui Chemicals is the largest of three MIBK
http://www.icis.com/Articles/2012/07/30/9581904/japans-mitsui-chemicals-restarts-30000-tonneyear-mibk.html
CC-MAIN-2014-52
refinedweb
102
55.03
Difference between pages "User:Apple" and "Template:Article" (Difference between pages) Latest revision as of 20:09, November 23, 2010 (view source)Apple (Talk)m Revision as of 01:16, January 2, 2015 (view source) Drobbins (Talk | contribs) Line 1: Line 1: −==about==+<includeonly>{{#if:{{{Subtitle|}}}|<div style="margin-left: 15px;"> −generic enthusiastic linux user. (probably) better at writing documentation than code.+==={{===linux history===+{{Tip|[[Support Funtoo]] and help us grow! '''Donate $15 per month and get a free SSD-based [[Funtoo Hosting|Funtoo Virtual Container]].'''}} −my first experience of open-source was early 2004 when I checked out blender (I had used it before in 2001, before it was open-source). I was using it in windows but irc chatter was quite abuzz with linux, so I checked it out.+</includeonly> − + −I started with Fedora Core 2, and about 2 weeks later started with gentoo. The first install was handled by two irc users over ssh, which was a first for all of us.+ − + −around August 2004, I helped out with a little known binary distro called h3knix until 2005 (h3knix and arcane linux were merged in late 2005, died shortly afterwards).+ − + −resigned back to windows in 2005.+ − + −the next few years are a bit fuzzy.+ − + −in 2008, I got an Asus EeePC 901 (Linux ver.). Within a few days I formatted Xandros and installed Arch.+ − + −A few months later, it was formatted again for Funtoo.+ − + −==Boxes==+ −* cumin - EeePC 901 - dead (broken screen)+ −* rosemary - Acer Aspire 5633 - 1.6GHz core 2 duo+ −* nutmeg - Desktop (amd64 athlon x2) - 2.2GHz+ −* thyme - Desktop (unknown)+ −* heather - dead (blown psu) - amd athlon 1.1GHz+ −* poppy - dead (ps3 firmware update)+ − + −* rover - n900+ − + −==looking at==+ −* server administration (home servers) / backup & sync [[User:Apple/projects/Transplant]]+ −* live cds/usbs [[User:Apple/projects/ISOMetro]]+ − + −==loves==+ −* lists!!!+ −* emerge(1)+ −* n900+ −* not being root (but having root access)+ −* btrfs+ −* per-process namespaces+ −* homogenous operating systems+ − + −==dislikes==+ −* X(1)+ −* voting schemes where you cannot rank the candidates+ −* gnu coding standards and practices+ −* debian (and offshoots) and the apt package manager+ −* capital letters+ Revision as of 01:16, January 2, 2015 Retrieved from ‘’
http://www.funtoo.org/index.php?title=Funtoo_Linux_History&diff=8168&oldid=654
CC-MAIN-2015-32
refinedweb
352
62.98
The simulation of weather in this series has been lacking since forever. Actually I think the "weather engine" hasn't been touched since ofp 1.0 (ok, rainbows have been added at some point, but that's it). Granted, we have the most basic components of weather to play with, such as overcast, fog, wind and rain. But it has always been only that; some components of weather (with some very simply constraints), but no coherent system of weather (or even seasons). But weather should be more than the sum of it's parts. And that's where the RUBE weather module steps in and tries to fill the gap (or at least illuminate and explore it a little). Sure, there are already some weather modules/addons present. But they focus mostly on effects or worry about synchronisation in multiplayer games. None of them however solves the problem I was interested in to begin with: if weather shall be a crucial component in (strategical/tactical) decision making, then it needs to be forecastable. What weather can be expected for today and what for the next few days? Should we postpone that sniper-mission or rather strike now? RUBE Weather Module The RUBE weather module is a pseudo-scientific weather machine consisting of three main components: - A season model that defines the clima, - a weather generator which creates a forecast for n days and - a weather engine that executes todays weather. the season model A season model consists of monthly averages of the following key components: - temperature (Tmin, st. dev., Trange) - precipitation (day/month probability, avg. intensity) - fog (day/month probability; linked with given precipitation data) - wind (avg. speed) Season models are saved in separate files (see prague.sqf, bamiyan.sqf or kandahar.sqf ), can be freely extended and are choosen by default (depending on the map/world) or at will. Data is gathered from public weather sites, available all over the webs. There are other climatic/seasonal aspects that are beeing modeled, which are mostly based on the maps latitude (such as daylight hours or polar-ferrel-hadley cells and stuff). the weather generator First let's get the terminology straight: a forecast is a set of n days of weather-data with n >= 3, s.t. we have at least the previous days, the current days and the next days weather-data (the weather engine will need the previous and next days data too). Then the weather generator has basically two tasks: - it creates a forecast of n days from scratch or - it advances a forecast by one day. The weather generation process tries to produce coherent weather situations, instead of simply throwing dices for each single component. To accomplish this, atmospheric pressure has been introduced. But first things first: we start with a random normally distributed temperature (minimum and range) as the season model dictates. We end up with a maximum temperature (min + range) that is either way too low, fine or way too high, compared to the dictated distribution's mean. This difference is used as a bias for the local pressure, s.t. rel. lower temperatures tend to result in high pressure situations (mean above average pressure) and higher temperatures in low pressure situations. So we have a local pressure, and we may compare that local pressure to the average pressure and thus we gain our first pressure coefficient in the range of [-1,1], where -1 means an extrem low, 0 a stable and 1 an extreme high pressure situation. All nice and dandy, but that's not good enough, right? Of course not. What we need next, is an environmental/surrounding pressure and then we can compare the local pressure to the environmental pressure and end up with a pressure coefficient II, again in the range of [-1,1], where -1 means an extreme local low, 0 stable and 1 an extreme local high situation - compared to the environmental system. The goal was somewhat coherent weather situations, right? That's why the environmental pressure get's biased according to how many local low situations we need; that is, how much it shall rain/snow according to the season model. If we need lot's of precipitation we should get enough of local lows, by biasing/increasing the environmental pressure. Equipped with these two pressure coefficients, out of which the second is clearly the "stronger", we can build the following matrix, which will act as our pressure system: Sy | coeffII x coeffI | temp. | prec. | over. | fog | wind | ??? ---|-------------------|------------------------------------------------------ 0 | |low | +1 | +2 | +2 | -2 | +2 | warm core low ---| LOW |---------|-------|-------|-------|-------|-------|-------------- 1 | |stable | | | | | | ---| |---------|-------|-------|-------|-------|-------|-------------- 2 | |high | -1 | | | | | cold core low ---|---------|---------|-------|-------|-------|-------|-------|-------------- 3 | |low | +1 | | | | | ---| STABLE |---------|-------|-------|-------|-------|-------|-------------- 4 | |stable | / | / | / | +2 | -2 | ---| |---------|-------|-------|-------|-------|-------|-------------- 5 | |high | -1 | | | | | ---|---------|---------|-------|-------|-------|-------|-------|-------------- 6 | |low | +1 | | | | | warm core high ---| HIGH |---------|-------|-------|-------|-------|-------|-------------- 7 | |stable | | | | | | ---| |---------|-------|-------|-------|-------|-------|-------------- 8 | |high | -1 | -2 | -2 | -2 | +2 | cold core high ---|---------|---------|-------|-------|-------|-------|-------|-------------- \________/ \_______/ humidity x temperature > "biased by ..." \______________________________________________/ pressure conf./system then further biases the remaining (-temp) main weather components \_____/ normally distributed to begin with and used to bias Plocal which determines coeffI While this is heavily simplified and quite artificial, I think such a pressure system is actually really nice to work with; as central driving force (or conductor) of the weather, which puts a little bit of meaning into this soup. Anyway, as the matrix already suggests; the remaining components are all more or less biased by this pressure system (and so will be lot's of the weather functions used by the weather engine for the "micro"-weather). "Advancing" the forecast; weather trends, evolution & mutation Now, we aren't simply going to toss the dices individually for each day (respectively for a new day, while every nth day gets to the n-1th position). While the seasonal averages could be easily met this way, that would result in a pretty chaotic sequence of weather. And second, our forecast-data should actually represent a weather forecast, that is: the weather-data of the next day should only change marginally (or only occasionally a bit more), while every day further into the future can change way more, up to drastic changes. Both problems are addressed with the same mechanism: there's a simple formula for a days forecast stability: _forecastStability = { // n=1 n=2 n=3 n=4 n=5 n=6 n=7 // .934, .801, .595, .417, .283, .188, .123, ... (1.54 * (_this / (exp _this))^0.5) }; Generally that's the relative amount (for each/most components) that won't be touched. So the forecast of the next day changes roughly by 7% or something. That change is accomplished most of the time by (linearly) blending single components of weather data. And for this there are several alternatives: a day has at least one link (to the previous or next day) and at max two such links. We'll use these links as sources for our blending process and if there are two sources and stability is low enough, we might even drop the original source altoghether, thus merging the previous with the next day... And we can also produce such a source (for a component) from scratch (as if we would generate a new, average day). Some of this I've called evolution, some mutation... it doesn't matter. What matter's is, that this process generates the desired forecast character - thanks to the forecast stability, and second we'll get a quite natural evolution of weather, with trends that might hold for a while and weather breaks every once in a while. a small statistical test suite Now, some of you may have already noticed that I pursue two heavily clashing paradigms: first I began with a declarative seasonal model and next I'm about to model weather in a "meaningful" way, where the single components "pseudo-scientifically" interact with each other... what the...?! I mean, either you work with a good declarative model and that's it, or you go and try to model nature - no matter what some components may average to in the end, as long as it all "makes sense" (with respect to the simulation). Or in other words: do we really need a season model and what should it actually consist of? Wouldn't latitude and maybe some data about the height and precipition be already enough? Honestly I don't know, and this is up to discussion or simply a question of design. Anyway, by going that hybrid route (and then that evolution/mutation process - eeek), it became really hard to know whether the generator actually did his job good or if he was just fucking around with me, producing some random output that has nothing to do with the given season model (or only by chance). That's why I've written a small statistical test suite to help me meet the seasonal model's averages and to see how coherent the generated forecast actually is (some stuff really should correlate, other stuff rather not. But mind you, we don't wanna end up with perfect correlations...). The point is: I highly encourage anyone messing with the generator function (or even while defining a new season model) to make use of that test suite (included in the package somewhere) aswell. The generated output (you're supposed to study) will end up looking something like this: Btw. single components may be excluded from the analysis. the weather engine At this point we have forecast data consisting of weather-data for n >= 3 days: ------------ -------------- ----------- ---------- | 0: prev. | | 1: current | | 2: next | | 3: ... | | day | | day | | day | | day | ------------ -------------- ----------- ---------- |----------------------------------------------------> where the data structure for a single day (currently) looks like this: [ 0: temperature -> [ 0: Tmin, 1: Trange ], 1: precipitation -> [ 0: intensity (0 OR ]0,1]), 1: disturbance mask (array; will be slapped on at the very end) ], 2: overcast -> [ 0: intensity ([0,1]) ], 3: fog -> [ 0: intensity ([0,1]), 1: duration 1, sunrise ([0,1]), 2: duration 2, day ([0,1]), 3: duration 3, sunset ([0,1]), ], 4: wind -> [ 0: speed in m/s ([0,oo]), 1: direction in degree ([0,360]) ], 5: pressure -> [ 0: local atmospheric pressure at sea level, in Pa (somewhere around ]98000, 104000[ with a mean of 101325), 1: environmental/surrounding atmospheric pressure at sea level, in Pa ] ] Weather engine; fundamentals and it's cycles First let's note that the weather engine isn't omnipresent/global. Stuff is different in different places/at different altitudes. That's why the weather engine is bound to a central object which is usually the player (or maybe a game-logic or another unit during cutscenes). Since we can't transition overcast and fog simultaniously (engine limitation), the weather engine works with two major cycles: first an overcast-, then the fog-cycle and then it will start all over again. Anything else will be transitioning constantly/in both cycles. The weather engine can be reset at will, starting with a new overcast-cycle (and a seamless transition). Thus you could modify the forecast data manually and then reset the weather engine; and voila: scripted weather changes. On a similar note you could aswell "abuse" the forecast-stack, s.t. a single "day" now just represents a weather-definition you can advance to at will by manually advancing/manipulating the forecast-stack... The weather engine is also capable of detecting a new day and "advancing" the forecast all on it's own. But you can disable this mechanism, in case you don't like it. The particle effects (radiation/ground-fog and snow) can be disabled as well. So can the color filter be disabled (see below; toggable in the demo-mission). A random walk For most of these components the weahter engine initializes bounded, random walkers. The bounds are defined by the extrema of the previous, the current and the next day (and for some 0 anyway) and the initial position is defined by the current daytime. From there, it's a random walk within these given bounds and until a switch to the next day. - / \ _ / \/ | / \ ----------> / \ / / ---/ <-------- \______________/ \________________/ \_______________/ 0: previous 1: current day 2: next (bounded, random oscillation) So if these three days have similar data, you can expect stable weather over the whole day. But if the previous, the current and the next day differ by much, then all kind of things might happen, since the random walkers will operate within much larger bounds. I'm not sure about the simulation clock/speed of these walkers yet, so this is about to be tweaked at some point. While most of these walkers (or oscillators) are the base/source of a some component, there's most of the time another layer on-top of this to model phenomena on a much faster or more precise scale. In it's most primitive form that might be a simple random-choke function (for wind or precipitaion), that occasionally throttles the intensity to model smaller disturbances and stuff. Temperature Temperature is one of the few things that is not based on such a random walker. We have a minimum temperature (Tmin) and a range (Trange) for each day, s.t. Tmin + Trange = Tmax. Todays Tmin and Trange then get mixed with either the data from the previous or the next day to guarantee continuous temperature changes, even at 24:00 to 00:01. The diurnal cycle (the amount or fraction of Trange that get's added to Tmin depending on daytime) is then modeled by a pearson type-III distribution. And finally the lapse rate is modeled too, so temperature decreases with altitude (Inversions aren't possible/modeled for now). Precipitation, overcast and the disturbance mask Just rain isn't good enough. Precipitation on the other hand is a nice level of abstraction. All we need then is a little function that decides, if it shall rain or snow (or even both/mixed). Since this is mostly based on the temperature, we'll get a natural snow line, since temperature decreases with altitude... Anyway, random walks are hell of a ride, but that's not good enough - especially for overcast and precipitation. While it might be nice, if it's raining all day long (for a local low), there are other typical cycles we'd like to model. A typical heating storm in the afternoon/evening for example. This is taken care of with the disturbance mask, which throttles overcast and precipitation (but never boosts it). Basically we're operating with a linearly interpolated key-frame approach, where we can define the minimum and maximum output/intensity on a daytime-basis. Clear sky in the morning, a heavy, rapidly forming storm in the evening. Yummy. ------------ --------------- --------------- | | | random | | disturbance | | forecast | ===> | oscillators | X | mask | |__________| |_____________| |_____________| (macro config.) (micro evolution) (typical characteristics) The disturbance mask makes use of yet another oscillator, based on two sines, operating in the band defined by the current minimum and maximum. For one this models uncontrolled breaks/variance, and for two we have an exponent ontop of that oscillator: an exponent below zero leads to maximized output/only short quick breaks, while a large exponent above one leads to a minimized output with short peaks. Generally this exponent is based on the latitude, s.t. we have minimized output with peaks in polar regions and maximized output at the equator - thus modeling somewhat the polar-ferrel-hadley cells. -------------------- -------------------- | / \ | | __ _ | | / -- | |__/ \_ / \__/\ | | | \_ | | \/ \_| | _/ \_| | | |_ _/ | | | |_\/_______________| |__________________| 0 18 24 0 24 ( thunderstorm ) ( widespread low ) at 18:00 This of course is an opportunity to manually manipulate the weather as desired. That disturbance mask can be easily matched to your missions needs, before you launch the weather engine and there: a strom exactly at the time you'll need one. Of course, if the random walker's output is next to zero, the disturbance mask can't to anything... And finally - to make things a bit more dynamic - there is a local pressure offset that comes with the disturbance masks use, s.t. what we take away with the disturbance mask (less overcast, less precipitation) will be added to the local pressure's base as temporary bonus. This might strenghten the current pressure system or it might eventually lead to a switch in the pressure system... which effect's other components (stronger wind, less fog, ...) and all hell breaks loose or something. The fog cycle The weather engine models a typical fog cycle, s.t. the probability for fog is lowest throughout the day, since humidity comes with the night. Fog is negatively linked to wind speed - especially the radiation/ground-fog (realized with extra particle effects). Wind Wind direction and speed both run on a random walkers and there's a random throttle function for wind-speeds. Also wind get's stronger with altitude. Pressure There's a random walker for both, local and environmental pressure, so the pressure system might suddenly swap/switch. Pressure coefficients/system is continously used in most weather functions to bias this and that and all kinds of things. Pressure decreases with altitude (lapse rate; interpolated between a moist and a dry one, depeding on a simple approximation of humidity). Color filter Modeling seasons is currently next to impossible. But one can at least try. A lot of the seasonal mood is derived by the colors. That's why the weather engine constantly runs a color-filter, based on the variables: - temperature, - daytime and - season/date. Most important is the temperature, which takes away red tones with low temperatures to get a cold/blueish picture. A strom in summer on the other hand should look rather warm and really not like poor weather in winter. Daytime is used to amplify/exagerate sunrise and sunset. And the season/date is used in a similar way as temperature is beeing used, to give seasons a distinct tone, even if subtile. Together with fog and snow, you should hopefully get the impression of winter, as opposed to lame vanilla chernarus' winters. But if you don't like it, you can disable it. And I'm also thinking about making the color filter part of the season model. Maybe at some point. the forecast report (dialogue) We have weather data for n days, but that's pretty much useless without some nice, accessible representation... There is a script RUBE\modules\weather\dialogs\fn_weatherReport.sqf that attaches an action to open a forecast-report to a given object. The dialog comes in two version: a digital one, supposed to be used with the notebook, and an analogue version for journal-like objects. Right now both versions are identical (except for the colors). But I figured the "digital" version could have something more advanced, like a barometer. Remember, temperature differs with altitude, so it might be of advantage if one could calibrate that forecast-report. Guess what's left to do is a nice dialogue we may attach to the radio or some kind of alarm-clock-like object, offering a simple interface to set the alarm clock and an option to sleep up to that point. Usage, examples and some ideas The RUBE weather module is part of the RUBE library which runs as script-version or as addon (as you like). For the weather module, the addon-version is actually quite convenient, since it offers the weather module as game-logic you can just drag onto the map and you're good to go. Random, seasonally fit weather. I've thought about offering two such versions for the editor, one for random, seasonal weather, and one that would respect the editor's weather settings (overcast and fog). But I figured that if you wanna have more control, then you wanna get full control and thus you'll just manipulate the forecast data as you need it. So you'd manually launch the weather engine anyway... Launching the weather engine and the RUBE_weather game-logic If you're using the addon, just drop the RUBE weather engine game-logic onto the map. The RUBE library will be loaded, weather generated and the engine will be launched for you. If you're using the script-version, you'll need a description.ext with the following contents: #include "RUBE\core.hpp" #include "RUBE\x-core-IDC.hpp" #include "RUBE\common.hpp" class RscTitles { #include "RUBE\rsctitles.hpp" }; class CfgSounds { #include "RUBE\sounds.hpp" }; ... and then just look at RUBE/modules/weather/init-editor.sqf for a first example (this is the script that get's called for the addon's game-logic): // make sure the RUBE function library is loaded if (isnil "RUBE_fnc_init") then { [] call (compile preprocessFileLineNumbers "RUBE\init.sqf"); }; waitUntil{!(isnil "RUBE_fnc_init")}; // init weather module _this execVM "RUBE\modules\weather\init.sqf"; waitUntil{!(isnil "RUBE_weather")}; // and start right away with default settings [] call (RUBE_weather getVariable "start-weather-engine"); Here _this is the game-logic from the editor. But we can aswell just pass garbage to that init function as in: [] execVM "RUBE\modules\weather\init.sqf"; waitUntil{!(isnil "RUBE_weather")}; What you need to know is that RUBE_weather is a game-logic, where all related stuff is saved, such as the forecast data and even the "interface" to this very module. At the point "start-weather-engine" is called in the example above, no season model has been selected and no forecast data has been generated. "start-weather-engine" will take care of this and run with defaults. Guess most of the time, we'll do that manually to gain more control. So here's a more elaborate example: [] execVM "RUBE\modules\weather\init.sqf"; waitUntil{!(isnil "RUBE_weather")}; // debug stuff RUBE_weather setVariable ["debug-generator", true, true]; RUBE_weather setVariable ["debug-engine", false, true]; // select season model "bamiyan" call (RUBE_weather getVariable "set-season-model"); // set forecast size RUBE_weather setVariable ["forecast-days", 6, true]; // initialize forecast/weather data [] call (RUBE_weather getVariable "generate-weather"); // now we could manually manipulate the forecast data, only // today disturbance mask or whatever... // ready? set, go! [] call (RUBE_weather getVariable "start-weather-engine"); demo mission Make sure the RUBE library is available (don't forget the description.ext in case you use the script version), choose some map and put down a player - but do not manually put down a weather module; the demo script will load one for you, mkay? Then execute the following code (you can simply put this in the init-line of the player): 0 = [] execVM "RUBE\modules\weather\scripts\demo.sqf"; ... then launch/preview the mission. The image above illustrates what should get spawned infront of you. Actions are attached to the n objects and there are some radio calls available too (to teleport and stuff). Test-suite The test-suite (barely; it's just a quickly hacked together script) is available at \RUBE\modules\weather\scripts\test-suite.sqf in case you haven't found it already. I suggest you copy that file and change the parameters as needed or something. Weather engine: constants At this point I probably should say a bit more about that RUBE_weather logic. First, there are "constants" stored here, which you may overwrite at will. They (and their defaults) can be found in /RUBE/modules/weather/weather-constants.sqf. Besides some simple settings such as "enable-color-filter", "enable-particles-fog", "debug-generator", ... also the core data is stored (or rather initialized) here, such as "date", "forecast-days", "forecast", "season-model", and so on and finally there are actually "constants", such as "latitude", "longitude" and some physical constants. Feel free to overwrite any of them as you see fit with a call to setVariable, prior to launching the weather engine. Weather engine: interface Instead of defining even more global functions with unbearably long names, I decided to put "public" weather functions into that RUBE_weather logic aswell, which makes up a pretty nice to use interface. It's defined in /RUBE/modules/weather/weather-interface.sqf and you've already seen how these are called in the above examples. Weather engine: the finite state machine Once the weather engine is started with a call to "start-weather-engine", a finit state engine will be launched and a pointer to it will be set to RUBE_weatherEngine, from where you can access anything inside the running weather engine (in case you need to; check out the demo script for an example). Some ideas Sure, the first thing that comes to mind is an indefinitely ongoing campaign that could make use of this module. Wanna have a forecast for the next few days? Well, then go grab the latest newspaper in the village... But you could also make good use of the forecastability for any singleplayer mission, no matter how short they will be. Just setup a nice little intro scene and offer a forecast for the next few days. You're then given the mission and a limited timeframe. Thus, you could start the mission right now or rather not and gamble for better conditions. Just setup an alarm-clock, so one can choose the exact point the mission shall be launched. Maybe one has to "sleep" once or twice... befor you're actually moveing out, starting the mission. I'm pretty sure that could work very well, with a lovely atmosphere, the gamble with the weather and tactical thoughs about fog and windspeeds and stuff. And as already hinted: the weather engine is pretty much free for any abuse. That is, you can script weather changes at will and with more or less full control by manipulating the forecast data and makeing good use of "reset-weather-engine". Just keep the minimal cycle delay/time in mind. - Does this work for multiplayer missions too? And if not, are you going to do something about it? No, the RUBE weather module will not work for your multiplayer missions. And there are no plans to do that. But feel free to write your own client variant of a weather engine, that is multiplayer-proof. Let the server generate the forecast, and then come up with some client version of the weather engine. But I'm not sure anyway, if it would be such a good idea to have player-centric weather clients for a multiplayer match. Sure, wind speeds differ indeed from place to place, but still... Maybe you'd better drop that idea, if you're going to do this. - Any plans of adding new season models? Sure. And you may help if you'd like to see good defaults for your preferred maps/worlds. If you come up with a good one, just drop me a note. - What about humidity? Air saturation and that kind of thing? Yeah, humidity is currently not really modeled/simulated. We work with the entity (or concept) "precipitation" and that's it. Humidity, where needed, get's approximated at times though: in the generator by mixing the given precipitation data (probability and intensity) and for the lapse rate humidity is approximated by the overcast or by the precipitation (=fully saturated) if there is any. Granted, that's quite lame and as soon as I gain a better understanding and maybe a vision about how "humidity" could be wired with the other weather components, this might get improved. Maybe. On the other hand this would probably require a completely different concept/design altogether, starting with a new structure/type of a season model and.... ahhh screw this. - Are you dumbass actually aware of the fact that the scales in arma-town are completely off? Height above sea-level my ass! (I've heared elevationOffset got introduced at some point, hrhr) The question..? Uhm, do I really have to repeat the part with the dumbass? Yeah, at some point (have you ever seen bushes pushed to the ground, because the wind speeds were a tiny wee bit too high?) it actually dawned on me what dumbass I am and that one can not simply apply real-world math to the arma universe. Scales are different/skewed here. Btw. has anyone reliable information about this? I can vaguely remember reading something about this somewhere... Anyway, some further tweaks might be needed in this regard. And remember that it's only pseudo-science we're doing here, with the goal to get something that resembles actual weather, physics and everything. - Do you really think it's a good idea to burn that much cpu cycles for _this_?! Hell yeah! Of course. Though, functions constantly called by the weather engine might indeed need some optimization (you tell me!). All these bézier-curves could indeed hurt a little. We'll see if I need to simplify them or maybe even build a lookup-table or something. - Where are the friggin screenshots already?! You may find some over here. But since I run this on a shitty machine, those screenshots aren't nice or anything. Sure, you may recognize some pixels and stuff... Maybe some of you guys would be kind enough to make some exquisite shots of the weather module in action and post them in here? Maybe. - ...? Just read (and mess with) the code, now would you? And drop me a note if you think something is wrong or could be improved. I never claimed that I've got much clue about weather... :cool: (Pretty much everything is commented and there are even some ASCII-illustrations in there for you illiterates out there.. though, now that I think about it, I might have already spoilered too much... sorry.) Changelog Requirements: - ArmA 2: Combined Operations (ArmA 2 & ArmA 2: Operation Arrowhead) Download The RUBE weather module is included in the RUBE library, whose latest version is available under:. Mirrors: Edited by ruebe, 19 April 2014 - 11:45. version: 2012.03.27, (added some mirrors)
https://forums.bistudio.com/topic/124683-rube-weather-module/
CC-MAIN-2016-44
refinedweb
4,946
61.36
Updated December 6, 2017 On both Google Cloud and Amazon Web Services (AWS), you can manage your cloud environments using an infrastructure-as-code approach. Google Cloud offers Deployment Manager, and AWS offers CloudFormation. Treating your infrastructure as code involves defining your environment through scripts, templates, and configuration files, and keeping the files in a source code repository. Using this approach, you can: - Control the version of your configuration. - Deploy consistent, reproducible configurations. - Review an audit trail of changes to your configuration. - Use the configuration as part of a continuous deployment system. - Easily fail back to a previous known-good configuration. Service model comparison The following table maps high-level CloudFormation features, terms, and concepts to Deployment Manager features, terms, and concepts: Templates and configuration The following table compares available template and configuration features in CloudFormation to those in Deployment Manager: AWS CloudFormation In AWS CloudFormation, you create a template that defines a set of actions against various services, such as creating an S3 bucket or launching an EC2 instance. An AWS template can be expressed in YAML or JSON, and AWS CloudFormation can invoke a template from either an S3 bucket or your local machine. When AWS CloudFormation invokes a template, it makes calls to the APIs of the services you have defined in the template to launch and configure the services. To use the services defined in a template, you must have appropriate AWS IAM permissions for each service. You can also set IAM policies to restrict or allow the use of CloudFormation. Deployment Manager Deployment Manager uses three types of files to define a deployment: - A configuration file, which defines the structure of your deployment and configures the resources to be deployed. This file is written in YAML. You can use this file as a standalone configuration for your deployment, or you can combine it with imported template files for increased flexibility. - Template files, which are composable, reusable resource definitions. Template files are written in Jinja 2.10.x or Python 3.x. You can add loops to create multiple instances of the same resource without having to explicitly declare each instance. - Schema files, which define sets of rules that a configuration file must meet in order to use a particular template. You pass the configuration file (which will expand any templates that it references) to the Deployment Manager service through the gcloud command-line tool or API. You can also launch predefined configurations by using Cloud Marketplace. By default, Deployment Manager uses the credentials of the GCP API service account to authenticate to other APIs. You must grant the user using Deployment Manager the appropriate permissions to use Deployment Manager. You can use predefined IAM roles to limit the permissions appropriately. Deployment Manager allows you to automate the creation of projects themselves as well as the resources contained within the projects. A Deployment Manager configuration file consists of the following sections: imports: - path: network.jinja resources: - name: network type: network.jinja properties: region: us-central1 subnets: - range: 10.177.0.0/17 name: web - range: 10.177.128.0/17 name: data - name: web-instance type: compute.v1.instance properties: zone: us-central1-f machineType: disks: - deviceName: boot type: PERSISTENT boot: true autoDelete: true initializeParams: sourceImage: networkInterfaces: - network: accessConfigs: - name: External NAT type: ONE_TO_ONE_NAT The above Google Cloud example configuration consists of the following parts: Imports. This references the path to composable templates that are expanded as part of the actual deployment. This is optional, because you might have a simple deployment where you do not need to create a configuration where you have placed individual resources into composite template files Resources. This is a list of the resources that you want deployed as part of your configuration. This is the only mandatory requirement for a configuration. Each resource is defined by the following constituent parts: - Name. A name that you define for this resource. In the example above we have two resources called networkand web-instance. - Type. Specifies the base type of the resource. The example shows two types of resource. The web-instanceis of type compute.v1.instance. The second resource refers to the import file declared in the importssection of the configuration file. In the example it is a Jinja file type, but you can also import Python files. - Properties. These are the properties associated with a resource. The resource called web-instancedefines a Compute Engine instance of machine type f1-micro,which has a persistent disk that can be auto deleted when you delete the instance. The instance is to be deployed into us-central1-fregion. The second resource is defined in a separate template file called network.jinja. For this resource, you define the values for the properties in the configuration file. The values are passed through to the actual template file. This composability lends itself to building complex deployments with reusable resource definitions, to which you can pass values through the configuration files. For example, you could use the same template file to create more subnets with different IP ranges and names. A configuration file can also have outputs and metadata. A schema file defines a set of rules for how to use a template. Defining the rules in a single schema gives your users a way to interact with the templates you write. They can use the schema file without needing to examine the templates that constitute a configuration or to learn which properties need to be set and which have default values. For more information on schema files, see the Deployment Manager documentation. The example template uses a public image to create the instance. GCP takes a global approach, so when you select an image type to launch an instance, you do not need to create a map of the image type per region, as you would for AWS CloudFormation. Using Google Cloud, you declare the machine type and the source image. The source image is available to all projects. Composition and reuse Both AWS CloudFormation and Google Cloud Deployment Manager encourage you to compose your own stacks or deployments and to reuse stacks or deployments. AWS CloudFormation AWS CloudFormation relies on the concept of nested stacks. With nested stacks, you can create a template for the resources that you want to reuse. You store the template that you want to call from the master template in an S3 bucket and use the AWS::CloudFormation::Stack type. You pass the S3 URL of the template as a property. You can use parameters to easily customise a template each time you use it to create a stack. You can use intrinsic functions together with parameters to create conditional resources. You can use outputs to export a value through the logical ID assigned to the value, so that you can use the value elsewhere. For example, you can export the names of load balancers and S3 buckets, import values into other stacks, and expose the values in the console. CloudFormation creates resources in parallel and determines which resources can be deployed in parallel, but you might need to use the creation policy and DependsOn attributes to help enforce the order in which resources are created. For example, the deployment might require EBS volumes to be created before the instance is created that uses the volumes. You can use custom resources to include non-AWS resources as part of your CloudFormation stack. To implement a custom resource, you supply a service token in the Properties section of the template. The service token specifies where CloudFormation should send requests. Google Cloud Deployment Manager Deployment Manager allows you to import templates into your configuration file. You declare the path to the templates, which can be stored locally, or in a Cloud Storage bucket, or at a publicly accessible URL such as GitHub, in the import statement. This allows you to scale and reuse templates as part of your configuration. You can customize Deployment Manager templates by passing variables through to your templates. You can use two types of variables with Deployment Manager: template variables and environment variables. Using template variables, you define the customizable value in the configuration file and pass that through to the template files. Environment variables are predefined and automatically assigned. Environment variables are designed to be used for items that are not directly related to resources you want to deploy, such as project IDs and deployment names. Both Jinja and Python allow you to take advantage of their native conditionals and looping functions. Deployment Manager relies on the concept of template modules. You can use template modules to incorporate template snippets that can be used in multiple templates. For example, you can use a template module to always generate instance names based on their environment and function. Deployment Manager creates all resources in parallel. You can use references to enforce the order in which resources are created. For example, if an instance references a new network in a configuration, you can ensure that Deployment Manager always creates the network before creating the instance, no matter where in the configuration file the network is declared. Outputs in Deployment Manager are designed to expose key properties of resources in an easily consumable way, so that they can be used by other templates or be exposed in the configuration. Outputs are declared as key-value pairs and can consist of a static string, a reference to a property, a template variable, or an environment variable. If the Google Cloud–supported types don't meet your needs, you can create a type provider and create additional types that you can register with Deployment Manager. To create a type provider, you must supply an API descriptor document, which can be an OpenAPI specification or a Google Discovery document. When you create and register a type provider, all resources provided by the API and supported by a RESTful interface with create, read, update, and delete (CRUD) operations are exposed as types that you can use in your deployment. You can extend the base types to create a composite type. A composite type is a combination of multiple base types that are configured to work together. For example, a network load-balanced managed instance group is a composite type. A network load balancer requires multiple Google Cloud resources and some configuration between resources. You can set up these resources in a configuration once and register the type with Deployment Manager. Metadata, helper scripts, and startup scripts AWS CloudFormation allows you to use a set of Python scripts that help you start services and install software on EC2 instances. The scripts are available from a repository or installed on an Amazon Linux AMI, and you can call them from your templates. You can add metadata or retrieve metadata on your instances by using the metadata attribute. GCP Deployment Manager allows you to use startup scripts or add metadata to virtual machine instances in your deployment by specifying the metadata in your template or configuration. The metadata key for your startup script must be startup-script, and the value is the contents of your startup script. The example snippet below shows how this is done: resources: - name: my-first-vm-template type: compute.v1.instance properties: zone: us-central1-f machineType: ...[snip]... metadata: items: - key: startup-script value: "STARTUP-SCRIPT-CONTENTS" Updating stacks and deployments AWS CloudFormation You can update CloudFormation stacks by passing new parameter values or updated templates. You can use change sets to see which stack settings and resources will change before you apply the change set. Cloud Deployment Manager With Deployment Manager you can also update deployments and preview potential changes to assess the effect your changes will have. Deployment Manager does not instantiate any actual resources when you preview a configuration. Instead, it expands the full configuration and creates shell resources. This gives you the opportunity to see the deployment before committing to it. Deployment Manager also provides policies that you can use when you update a deployment to help you control how Deployment Manager manages updates. Some resources are immutable and might not have an update method. As with AWS CloudFormation, you should check the API methods for the resource to understand the implications of carrying out an update. You can also look at manifests prior to doing any updates to understand what a deployment actually looks like. You can do this through the command-line interface or the console. Costs There is no charge for AWS CloudFormation or Google Cloud Deployment Manager. In both cases you are charged only for the resources you launch. What's next? Check out the other Google Cloud Platform for AWS Professionals articles:
https://cloud.google.com/docs/compare/aws/deployment-tools
CC-MAIN-2020-40
refinedweb
2,107
54.42
find four positive integers a,b,c,d whose 5th powers sum to the 5th power of another integer e, i.e. find five integers a,b,c,d,e such that a^5+b^5+c^5+d^5=e^5. I am working on Sage Math online , on Windows 10 In 1769, Lenhard Euler conjectured that at least n nth powers are required to obtain a sum that is itself an nth power for n>2. Disprove Euler's conjecture by writing an appropriate function and using it to find four positive integers a,b,c,d whose 5th powers sum to the 5th power of another integer e, i.e. find five integers a,b,c,d,e such that a^5+b^5+c^5+d^5=e^5. I have tried this, but it seems like not given me what I wanted it. By the way, I am not allow to use "IF" Statement at all. def calculateValues(): sumoffourvalues = 0 for i in range(2,6): #display each valueS print (i) #calculate each value its power eachpower = pow(i,5) #sum of power values of four elements sumoffourvalues = sumoffourvalues + eachpower print ("power of sumofforvalues",sumoffourvalues) #calculating power of fifth element fifthelementvalue = pow(6,5) print ("power of fifthelementvalue ",fifthelementvalue) #Consider like below this way #a5+b5+c5+d5−e5=0 resultantvalue = sumoffourvalues -fifthelementvalue print("resultant value is ",resultantvalue) calculateValues() Suggestions. Find a shorter title, maybe "Need help with fifth powers exercise". Format LaTeX code using dollar signs. Format code by indenting it four spaces (and don't skip lines); or select your block of code and click the "code" button (the one with '101 010').
https://ask.sagemath.org/question/34730/find-four-positive-integers-abcd-whose-5th-powers-sum-to-the-5th-power-of-another-integer-e-ie-find-five-integers-abcde-such-that-a5b5c5d5e5/
CC-MAIN-2019-51
refinedweb
280
50.26
Hey, all. Today, we discuss one of the most advanced topics in the list of C programming – Union. Table of Contents Understanding Union in C Union in C, is a user defined datatype that enables the user to store elements of different types into it altogether. We can define various data members/variables within, but only one data variable can occupy the memory in the union at a time. Thus, we can say that the size or the memory of the union is equivalent to the size of the largest data member present in it. So, all the data variables share the same memory location in the Union. By this, Union provides an effective way to reuse the same amount of memory or space for multiple purposes. With the basics covered, let’s define a Union next. How to define a Union in C? The union helps us define data variables that store values of different data type as shown below: Syntax: union union-name { data member1 definition ; data member2 definition; ... data memberN definition; } - The keyword unionis used to declare a union structure. - Further, the union-nameis the name of the union that helps us access the union throughout the program. - We can define multiple data members of different data types within a union. Example: union Info { int roll; float marks; char name[50]; } info_obj; In the above example, we have created a union ‘Info’ and defined the variables of different data types such as int, float, char, etc. Union uses the same memory space/size to store values of different data types which increasing the reusability of the space. The memory space of the union is the size of the largest data member declared within it. In the above example, the largest variable ‘name’ occupies a space of 50 bytes. Thus, the union ‘Info’ would also represent a memory space of 50 bytes. Creating Union Variables A union variable helps the union type to allocate memory space in accordance with the largest data member. There are two ways to create a union variable: Method 1: union union-name { data member1 definition ; data member2 definition; ... data memberN definition; } union_variable 1, union_variable2, .... , union_variableN; Method 2: union union-name { data member1 definition ; data member2 definition; ... data memberN definition; }; int main() { union union-name union_variable 1, union_variable2, ... ,union_variableN; return 0; } Accessing Union Data Members In order to assign values to the data members defined in the union type, we need to access them using the union variables. There are two techniques to access the union data members: Method 1: Using the dot (.) operator union_variable.data_member = value; Method 2: Using the Arrow (->) operator union_variable->data_member = value; Let us have a look at the below example to understand the above explained concepts. #include<stdio.h> union Info { int roll; float marks; char name[100]; } info_obj; int main() { info_obj.roll = 1; info_obj.marks = 82.5; printf("Roll number : %d\n", info_obj.roll); printf("Marks obtained : %.1f", info_obj.marks); return 0; } Demonstrated in the output below, only the last variable, ‘marks’, gets displayed properly. That’s because, as you can witness the variables ‘marks’ and ‘roll’ are being accessed by the variable ‘info_obj’ at the same time. Since the memory location is shared, only the last value gets hold of the memory during output. The previously declared variable ‘roll’ gets corrupted. This serves to prove our initial statement about the Union data type sharing memory location. Output: Roll number : 1118109696 Marks obtained : 82.5 Have a look at the below example to see the difference! #include<stdio.h> union Info { int roll; float marks; char name[100]; } info_obj; int main() { info_obj.roll = 1; printf("Roll number : %d\n", info_obj.roll); info_obj.marks = 82.5; printf("Marks obtained : %.1f", info_obj.marks); return 0; } Now, both the data variables ‘roll’ and ‘marks’ get displayed properly. The reason is, here the union variable ‘info_obj’ accesses one variable at a time and displays the value and then moves ahead to fetch another data member. Output: Roll number : 1 Marks obtained : 82.5 Difference Between a Structure and a Union Consider the below example, to understand the difference between a Structure and a union: #include <stdio.h> union u_Info { int roll; float marks; char name[100]; } u_obj; struct s_Info { int roll; float marks; char name[100]; } s_obj; int main() { printf("Size -- Structure datatype = %d\n", sizeof(s_obj)); printf("Size -- Union datatype = %d", sizeof(u_obj)); return 0; } Union occupies the memory space of the largest variable present in it. Here, the variable ‘name’ has 100 bytes of space. Thus, the size of union is 100 bytes. On the other hand, Structure occupies the memory size which is the summation of the size of all the data members present in it. Thus, structure represents the memory size of 108 bytes. Output: Size -- Structure datatype = 108 Size -- Union datatype = 100 Conclusion By this, we have come to the end of this topic. In this article, we have understood the working of Unions and the difference between a Union and a Structure. Feel free to comment below, in case you come across any question. For more such posts related to C programming, do visit C programming with JournalDev.
https://www.journaldev.com/43285/union-in-c
CC-MAIN-2021-04
refinedweb
862
64
some of this will be EKS specific. To work with me through the example, you will first have to bring up your cluster, start two nodes and deploy a pod running a httpd on one of the nodes. I have written a script up.sh and a manifest file that automates all this. To download and apply all this, enter $ git clone $ cd Kubernetes/cluster $ chmod 700 up.sh $ ./up.sh $ kubectl apply -f ../pods/alpine.yaml Node-to-Pod networking Now let us log into the node on which the container is running and collect some information on the local network interface attached to the VM. $ So the local IP address of the node is 192.168.118.64. If we do a kubectl get pods -o wide, we get a different IP address – 192.168.99.199 – for the pod. Let us curl this from the node. $ curl 192.168.99.199 <h1>It works!</h1> So apparently we have reached our httpd. To understand why this works, let us investigate the network configuration in more detail. First, on the node on which the container is running, let us take a look at the network configuration inside the container. $ ID=$(docker ps --filter name=alpine-ctr --format "{{.ID}}") $ docker exec -it $ID "/bin/bash" bash-4.4# ip link 1: lo: mtu 65536 qdisc noqueue state UNKNOWN qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 3: eth0@if6: mtu 9001 qdisc noqueue state UP link/ether 4a:8b:c9:bb:8c:8e brd ff:ff:ff:ff:ff:ff bash-4.4# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 4A:8B:C9:BB:8C:8E inet addr:192.168.99.199 Bcast:192.168.99.199 Mask:255.255.255.255 UP BROADCAST RUNNING MULTICAST MTU:9001 Metric:1 RX packets:12 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:936 (936.0 B) TX bytes:0 (0.0 B) bash-4.4# ip route default via 169.254.1.1 dev eth0 169.254.1.1 dev eth0 scope link What do we learn from this? First, we see that inside the container namespace, there is a virtual ethernet device eth0, with IP address 192.168.99.199. If you run kubectl get pods -o wide on your local workstation, you will find that this is the IP address of the Pod. We also see that there is a route in the container namespace that direct all traffic to this interface. The output of the ip link command also shows that this device is a virtual ethernet device that has a paired device (with index if6) in a different namespace. So let us exit the container, go back to the node and try to figure out what the network configuration on the node is. $ ip link 1: lo: mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: eth0: mtu 9001 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 link/ether 02:2b:dc:e7:44:8c brd ff:ff:ff:ff:ff:ff 3: eni3f5399ec799: mtu 9001 qdisc noqueue state UP mode DEFAULT group default link/ether 66:37:e5:82:b1:f6 brd ff:ff:ff:ff:ff:ff link-netnsid 0 4: enie68014839ee@if3: mtu 9001 qdisc noqueue state UP mode DEFAULT group default link/ether f6:4f:62:dc:38:18 brd ff:ff:ff:ff:ff:ff link-netnsid 1 5: eth1: mtu 9001 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 link/ether 02:e8:f0:26:a7:3e brd ff:ff:ff:ff:ff:ff 6: eni97d5e6c4397@if3: mtu 9001 qdisc noqueue state UP mode DEFAULT group default link/ether b2:c9:58:c0:20:25 brd ff:ff:ff:ff:ff:ff link-netnsid 2 $ $ ip route default via 192.168.64.1 dev eth0 169.254.169.254 dev eth0 192.168.64.0/18 dev eth0 proto kernel scope link src 192.168.118.64 192.168.89.17 dev eni3f5399ec799 scope link 192.168.99.199 dev eni97d5e6c4397 scope link 192.168.109.216 dev enie68014839ee scope link Here we see that – in addition to a few other interfaces – there is a device eth0 to which all traffic is sent by default. However, there is also a device eni97d5e6c4397 which is the other end of the interface visible in the container. And there is a route that sends all traffic that is directed to the IP address of the pod to this interface. Overall, this gives a picture which seems familiar from our earlier analysis of docker networking If we try to establish a connection to the httpd running in the pod, the routing table entry on the node will send the traffic to the interface eni97d5e6c4397. This is one end of a veth-pair, the other end appears inside the container as eth0. So from the containers point of view, this is incoming traffic received via eth0, which is happily accepted and processed by the httpd. The reply goes the other way – it is directed to eth0 inside the container, travels via the veth pair and ends up inside the host namespace, coming from eni97d5e6c4397. Pod-to-Pod networking across nodes Now let us try something else. Log into the second node – on which the container is not running – and try the curl from there. Surprisingly, this works as well! What we have seen so far does not explain this, so there is probably a piece of magic that we are still missing. To find this, let us use the aws cli to print out the network interfaces attached to the node on which the container is running (the following snippet assumes that you have the extremely helpful tool jq installed on your PC). $ nodeName=$(kubectl get pods --output json | jq -r ".items[0].spec.nodeName") $ aws ec2 describe-instances --output json --filters Name=private-dns-name,Values=$nodeName --query "Reservations[0].Instances[0].NetworkInterfaces" ---- SNIP ----- { "MacAddress": "02:e8:f0:26:a7:3e", "SubnetId": "subnet-06088e09ce07546b9", "PrivateDnsName": "ip-192-168-84-108.eu-central-1.compute.internal", "VpcId": "vpc-060469b2a294de8bd", "Status": "in-use", "Ipv6Addresses": [], "PrivateIpAddress": "192.168.84.108", "Groups": [ { "GroupName": "eks-auto-scaling-group-myCluster-NodeSecurityGroup-1JMH4SX5VRWYS", "GroupId": "sg-08163e3b40afba712" } ], "NetworkInterfaceId": "eni-0ed2f1cf4b09cb8be", "OwnerId": "979256113747", "PrivateIpAddresses": [ { "Primary": true, "PrivateDnsName": "ip-192-168-84-108.eu-central-1.compute.internal", "PrivateIpAddress": "192.168.84.108" }, { "Primary": false, "PrivateDnsName": "ip-192-168-72-200.eu-central-1.compute.internal", "PrivateIpAddress": "192.168.72.200" }, { "Primary": false, "PrivateDnsName": "ip-192-168-96-163.eu-central-1.compute.internal", "PrivateIpAddress": "192.168.96.163" }, { "Primary": false, "PrivateDnsName": "ip-192-168-99-199.eu-central-1.compute.internal", "PrivateIpAddress": "192.168.99.199" } ], ---- SNIP ---- I have removed some of the output to keep it readable. We see that AWS has attached several elastic network interfaces (ENI) to our node. An ENI is a virtual network interface that AWS creates and manages for you. Each node can have more than one ENI attached, and each ENI can have a primary and multiple secondary IP addresses. If you look at the last line of the output, you see that there is a network interface eni-0ed2f1cf4b09cb8be that has, as one of the secondary IP addresses, the IP address 192.168.99.199. This is the IP address of our Pod! Let us now go back to the node and inspect its network configuration once more. You will not find a network interface with this exact name, but you will find a network interface on the node on which the pod is running which has the same MAC address, namely eth1. $ ifconfig eth1 eth1: flags=4163 mtu 9001 inet6 fe80::e8:f0ff:fe26:a73e prefixlen 64 scopeid 0x20 ether 02:e8:f0:26:a7:3e txqueuelen 1000 (Ethernet) RX packets 224 bytes 6970 (6.8 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 20 bytes 1730 (1.6 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 This is an ordinary VPC interface and visible in the entire VPC under all of its IP addresses. So if we curl our httpd from the second node, the traffic will leave that node via the default interface, be picked up by the VPC, routed to the node on which the pod is running and enter via eth1. As IP forwarding is enabled on this node, the traffic will be routed to the Pod and arrive at the httpd. This is the missing piece of magic we have been looking for. In fact, for every pod running on a node, EKS will add an additional secondary IP address to an ENI attached to the node (and attach additional ENIs if needed) which will make the Pod IP addressses visible in the entire VPC. This mechanism is nicely described in the documentation of the CNI plugin which EKS uses. So we now have the following picture. So this allows us to run our httpd in such a way that it can be reached from the entire Pod network (and the entire VPC). Note, however, that it can of course not be reached from the outside world. It is interesting to repeat this experiment with a slighly adapted YAML file that uses the containerPort field: apiVersion: v1 kind: Pod metadata: name: alpine namespace: default spec: containers: - name: alpine-ctr image: httpd:alpine ports: - containerPort: 80 If we remove the old Pod and use this YAML file to create a new pod, we will find that the configuration does not change at all. In particular, running docker ps on the node on which the Pod is scheduled will teach you that this port specification is not the equivalent of the port specification of the docker run port mapping feature – as the Kubernetes API specification states, this field is informational. Implementation of services Let us now see how this picture changes if we add a service. First, we will use a service of type ClusterIP, i.e. a service that will make our httpd reachable from within the entire cluster under a common IP address. For that purpose – after deleting our existing pods – let us create a deployment that brings up two instances of the httpd. $ kubectl apply -f Once the pods are up, you can again use curl to verify that you can talk to every pod from every node and every pod. Now let us create a service. $ kubectl apply -f Once that has been done, enter kubectl get svc to get a list all services. You should see a newly created service alpine-service. Note down its cluster IP address – in my case this was 10.100.11.202. Now log into one of the nodes again, attach to the container, install curl there and try to connect to port 10.100.11.202:8080 $ ID=$(docker ps --filter name=alpine-ctr --format "{{.ID}}") $ docker exec -it $ID "/bin/bash" bash-4.4# apk add curl OK: 124 MiB in 67 packages bash-4.4# curl 10.100.11.202:8080 <h1>It works!</h1> So, as promised by the definition of s service, the httpd is visible within the cluster under the cluster IP address of the service. The same works if we are on a node and not attached to a container. To see how this works, let us log out of the container again and search the NAT tables for the cluster IP address of the service. $ sudo iptables -S -t nat | grep 10.100.11.202 -A KUBE-SERVICES -d 10.100.11.202/32 -p tcp -m comment --comment "default/alpine-service: cluster IP" -m tcp --dport 8080 -j KUBE-SVC-SXWLG3AINIW24QJC So we see that Kubernetes (more precisely the kube-proxy running on each node) has added a NAT rule that captures traffic directed towards the service IP address to a special chain. Let us dump this chain. $ sudo iptables -S -t nat | grep KUBE-SVC-SXWLG3AINIW24QJC -N KUBE-SVC-SXWLG3AINIW24QJC -A KUBE-SERVICES -d 10.100.11.202/32 -p tcp -m comment --comment "default/alpine-service: cluster IP" -m tcp --dport 8080 -j KUBE-SVC-SXWLG3AINIW24QJC -A KUBE-SVC-SXWLG3AINIW24QJC -m comment --comment "default/alpine-service:" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-YRELRNVKKL7AIZL7 -A KUBE-SVC-SXWLG3AINIW24QJC -m comment --comment "default/alpine-service:" -j KUBE-SEP-BSEIKPIPEEZDAU6E Now this is actually pretty interesting. The first line is simply the creation of the chain. The second line is the line that we already looked at above. The next two lines are the lines we are looking for. We see that, with a probability of 50%, we either jump to the chain KUBE-SEP-YRELRNVKKL7AIZL7 or to the chain KUBE-SEP-BSEIKPIPEEZDAU6E. Let us display one of them. $ sudo iptables -S KUBE-SEP-BSEIKPIPEEZDAU6E -t nat -N KUBE-SEP-BSEIKPIPEEZDAU6E -A KUBE-SEP-BSEIKPIPEEZDAU6E -s 192.168.191.152/32 -m comment --comment "default/alpine-service:" -j KUBE-MARK-MASQ -A KUBE-SEP-BSEIKPIPEEZDAU6E -p tcp -m comment --comment "default/alpine-service:" -m tcp -j DNAT --to-destination 192.168.191.152:80 So we see the that this chain has two rules. The first rule marks all packages that are originating from the pod running on this node, this mark is later evaluated in the forwarding rules to make sure that the packet is accepted for forwarding. The second rule is where the magic happens – it performs a DNAT, i.e. a destination NAT, and sends our packets to one of the pods. The rule KUBE-SEP-YRELRNVKKL7AIZL7 is similar, with the only difference that it sends the packets to the other pod. So we see that two things are happening - Traffic directed towards port 8080 of the cluster IP address is diverted to one of the pods - Which one of the pods is selected is determined randomly, with a probability of 50% for both pods. Thus these rules implement a simple load balancer. Let us now see how things change when we use a service of type NodePort. So let us use a slightly different YAML file. $ kubectl delete -f $ kubectl apply -f When we now run kubectl get svc, we see that our service appears as a NodePort service, and, as the second entry in the columns PORTS, we find the port that Kubernetes opens for us. $ kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE alpine-service NodePort 10.100.165.3 8080:32755/TCP 13s kubernetes ClusterIP 10.100.0.1 443/TCP 7h In my case, the port 32755 has been used. If we now go back to one of the nodes and search the iptables rules for this port, we find that Kubernetes has created two additional NAT rules. $ sudo iptables -S -t nat | grep 32755 -A KUBE-NODEPORTS -p tcp -m comment --comment "default/alpine-service:" -m tcp --dport 32755 -j KUBE-MARK-MASQ -A KUBE-NODEPORTS -p tcp -m comment --comment "default/alpine-service:" -m tcp --dport 32755 -j KUBE-SVC-SXWLG3AINIW24QJC So we find that for all traffic directed to this port, again a marker is set and the rule KUBE-SVC-SXWLG3AINIW24QJC applies. If you inspect this rule, you will find that it is similar to the rules above and again realizes a load balancer that sends traffic to port 80 of one of the pods. Let us now verify that we can really reach this pod from the outside world. Of course, this only works once we have allowed incoming traffic on at least one of the nodes in the respective AWS security group. The following commands determine the node Port, your IP address, the security group and the IP address of the node, allow access and submit the curl command (note that I use the cluster name myCluster to select the worker nodes, in case you are not using my scripts to run this example, you will have to change the filter to make this work). $> Summary After all these nitty-gritty details, let us summarize what we have found. When you start a pod on a node, a pair of virtual ethernet devices is created, with one end being assigned to the namespace of the container and one end being assigned to the namespace of the host. Then IP routes are added so that traffic directed towards the pod is forwarded to this bridge. This allows access to the container from the node on which they are running. To realize access from other nodes and pods and thus the flat Kubernetes networking model, EKS uses the AWS CNI plugin which attaches the pods IP addresses as secondary IP addresses to elastic network interfaces. When you start a service, Kubernetes will in addition set up NAT rules that will capture traffic determined for the cluster IP address of the service and perform a destination network address translation so that this traffic gets send to one of the pods. The pod is selected at random, which implements a simple load balancer. For a service of type NodePort, additional rules will be created which make sure that the same NAT processing applies to traffic coming from the outside world. This completes today post. If you want to learn more, you might want to check out some of the links below. - this post by Kevin Sookocheff - the source code of the iptable interface of the kube proxy - The proposal for the AWS CNI plugin - my own series on networking in Docker (part I, part II) - and of course the Kubernetes documention itself 2 thoughts on “Watching Kubernetes networking in action”
https://leftasexercise.com/2019/05/09/watching-kubernetes-networking-in-action/
CC-MAIN-2020-05
refinedweb
2,982
70.23
IRC log of tagmem on 2007-08-13 Timestamps are in UTC. 15:57:17 [RRSAgent] RRSAgent has joined #tagmem 15:57:18 [RRSAgent] logging to 15:57:27 [Stuart] zakim, this will be tag 15:57:27 [Zakim] ok, Stuart; I see TAG_Weekly()12:00PM scheduled to start in 3 minutes 15:57:48 [Zakim] TAG_Weekly()12:00PM has now started 15:57:55 [Zakim] +Raman 15:59:20 [ht] Meeting: TAG 15:59:27 [ht] Chair: Norm Walsh 15:59:30 [raman] raman has left #tagmem 15:59:33 [ht] Scribe: Henry S. Thompson 15:59:38 [ht] ScribeNick: ht 16:00:02 [Zakim] +DanC 16:00:37 [ht] zakim, please call ht-781 16:00:37 [Zakim] ok, ht; the call is being made 16:00:38 [Rhys] Rhys has joined #tagmem 16:00:39 [Zakim] +Ht 16:00:43 [raman] raman has joined #tagmem 16:01:28 [Noah] Noah has joined #tagmem 16:01:29 [Zakim] +??P8 16:01:44 [ht] zakim, ? is Stuart 16:01:44 [Zakim] +Stuart; got it 16:01:52 [Zakim] +Rhys 16:02:00 [Zakim] +Norm 16:02:08 [Norm] zakim, who's on the phone? 16:02:08 [Zakim] On the phone I see Raman, DanC, Ht, Stuart, Rhys, Norm 16:02:35 [Zakim] +Noah_Mendelsohn 16:02:52 [DanC] regrets: TimBL 16:03:11 [Norm] Regrets: TimBL 16:03:16 [ht] topic: agena 16:03:18 [Norm] zakim, who's on the phone? 16:03:18 [Zakim] On the phone I see Raman, DanC, Ht, Stuart, Rhys, Norm, Noah_Mendelsohn 16:03:26 [ht] s/agena/Agenda/ 16:06:14 [ht] Action: Stuart to put up straw poll to try to find a new slot for this meeting 16:06:14 [trackbot-ng] Created ACTION-8 - Put up straw poll to try to find a new slot for this meeting [on Stuart Williams - due 2007-08-20]. 16:06:46 [ht] NW: Agenda recently updated -- accepted as posted 16:07:18 [ht] NW: RESOLVED that minutes of 16/7/07 are approved 16:07:28 [ht] Topic: Next meeting 16:07:34 [Norm] ack DanC 16:07:34 [Zakim] DanC, you wanted to ask about "RESOLUTION: We will open a new issue named "HTTP Redirections"" 16:07:35 [ht] RL withdraws his regrets 16:07:47 [ht] NM says he is at risk 16:08:02 [ht] We already have regrets from TBL 16:08:25 [ht] DC: SW, have you created the issue? 16:08:48 [ht] SW: Wasn't aware we'd chosen a name, will go ahead ASAP with "HTTP Redirections" 16:09:07 [ht] Action: SW to create new TAG issue called "HTTP Redirections" per minutes of 16/7/07 16:09:08 [trackbot-ng] Created ACTION-9 - Create new TAG issue called \"HTTP Redirections\" per minutes of 16/7/07 [on Stuart Williams - due 2007-08-20]. 16:09:23 [Stuart] 16:09:24 [ht] Topic: Technical Plenary planning 16:09:36 [Norm] -> 16:09:51 [ht] NW: Any suggestions? 16:09:58 [Rhys] Rhys prefers Stuart's URI 16:10:04 [ht] SW: I sent the above as a starter 16:10:14 [ht] ... URI-based extensibility 16:10:22 [ht] ... Web 2.0 16:10:30 [Noah] q+ to ask how close the first proposed topic comes to HTML 5 extensibility 16:10:30 [ht] ... HTTP URIs rule 16:11:07 [Norm] ack DanC 16:11:07 [Zakim] DanC, you wanted to relay 16:11:10 [DanC] q+ to offer to re-play his "nofollow is like marquee" story re "The Importance URI based Extensibility" 16:11:10 [ht] TVR: Challenge is how to raise these, or any topics, in a way that works for the TP 16:11:17 [ht] ack DanC 16:11:17 [Zakim] DanC, you wanted to offer to re-play his "nofollow is like marquee" story re "The Importance URI based Extensibility" 16:13:17 [ht] DC: Molly Holzschlag has asked for observer status at the HTML WG meeting, which is fine with me, and has made some suggestions for a TP session (see link) 16:13:55 [ht] NW: Who is WaSP (Web Standards Project) -- relation with WHAT WG? 16:14:01 [ht] HST: They've been around for a long time 16:14:37 [Norm] q+ To point out that HTML/HTML5 extensibility looks like a good topic 16:14:55 [ht] DC: They have pushed for a more aggressive attempt to support standards than W3C has pursued, in that W3C has a policy of not making public criticisms of its members if at all possible 16:15:37 [Rhys] q+ 16:15:44 [ht] DC: I also think we could talk about the relationship between rel='nofollow' and <marquee> -- if the latter is bad, why isn't the former? 16:16:32 [ht] NM: Wrt URI-based extensibility, is that where we talk about HTML 5 extensibility, or does that need a separate heading/slot/bullet? 16:16:36 [Norm] ack no 16:16:36 [Zakim] Norm, you wanted to point out that HTML/HTML5 extensibility looks like a good topic 16:16:39 [Norm] ack noah 16:16:39 [Zakim] Noah, you wanted to ask how close the first proposed topic comes to HTML 5 extensibility 16:16:43 [Norm] q+ To point out that HTML/HTML5 extensibility looks like a good topic 16:17:26 [ht] TVR: Even if it is covered, the title doesn't communicate that 16:18:05 [Norm] ack norm 16:18:05 [Zakim] Norm, you wanted to point out that HTML/HTML5 extensibility looks like a good topic 16:18:09 [ht] Various: The overall topic is a big one 16:18:19 [ht] NW: TP is a good place to talk about big topic 16:18:31 [ht] TVR: Start with the smaller (HTML5) topic, and then enlarge 16:19:22 [ht] SW: The topic emerged from our call discussion about follow-your-nose, we had trouble articulating exactly what we wanted, so it seemed a good topic 16:19:24 [Noah] Now that I think about it: the need for distributed extensibility is, as a requirement. Applying URI-based extensibility in particular is the Web-compatible way of achieving such extensibility. 16:19:46 [Noah] s/distributed extensibility/distributed HTML 5 extensibility/ 16:20:04 [ht] NW: So, do we have consensus? Should we address HTML5 extensibiliyt 16:20:07 [Rhys] +1 to the broader topic 16:20:09 [Rhys] ack me 16:20:15 [ht] HST: I thought we had consensus on the broader topic 16:20:36 [ht] NW: I'm happy to go to the broad topic 16:21:20 [ht] NM: Once you agree on distributed extensibility as a requirement for HTML5, you still have to agree mechanism, i.e. URI-based or not 16:21:31 [ht] DC: How much time do we have? 16:21:47 [ht] ... I could imagine a whole conference on this topic 16:22:02 [ht] NM: I thought this was for the whole day 16:22:25 [Noah] Any interest in inviting Sam Ruby to discuss his views on HTML 5 extensibility? 16:22:34 [ht] NW: The message subject is ["possible topic for TAG contribution to TP"] 16:22:58 [ht] SW: Is this the subject that we have the most affinity for? 16:23:24 [ht] DC: 'We' isn't the point - I have a specific pointI want to get across 16:24:16 [ht] NM: Molly was particularly concerned about Adobe's AIR and application construction in general, which would I guess point also to Microsoft's Silverlight 16:24:28 [ht] ack DanC 16:24:28 [Zakim] DanC, you wanted to note 16:25:00 [ht] DC: The TP programme committee has a list of 20 topics to talk about, see link 16:26:00 [Noah] Speaking just for myself, I find some of the technical topics we're noodling on here to be more compelling than the rough list at 07-TechPlenAgenda.html 16:26:37 [Norm] Norm has joined #tagmem 16:26:39 [ht] NW: Are we ready for the chair of the TAG to go back to Steve with an overview of what we've discussed, and see where it might fit in? 16:26:50 [Norm] q? 16:26:57 [ht] Action: SW to discuss TAG slot at TP with Steve Bratt, informed by above discussion 16:26:57 [trackbot-ng] Created ACTION-10 - Discuss TAG slot at TP with Steve Bratt, informed by above discussion [on Stuart Williams - due 2007-08-20]. 16:27:24 [ht] NW: Same question about the AC -- anything to say? 16:27:37 [ht] HST: It's half-a-day, I think we should duck 16:28:52 [ht] DC: We don't seem to be doing REC-track work -- if anybody cared I guess we'd hear about it. . . 16:29:29 [Noah] I agree with Norm, we haven't forgotten rec track work. What we have not done is produce 3 month heartbeats so identified. 16:29:40 [ht] HST: At Extreme last week, I got a lot of good response when I pointed people to the [Alternative Representations] finding -- we could just make it a REC 16:30:07 [ht] NW: I just don't think our recent work has been REC-like, we're still looking for that 16:30:11 [DanC] (looking it up... is dated 1 November 2006 ) 16:30:52 [ht] NM: I think a lot of our recent pubs can be seen as a heartbeat 16:31:15 [DanC] (our last WD was ) 16:31:27 [ht] NM: Most recent approved finding was Metadata finding, at beginning of the year 16:32:47 [ht] DC: We have to do a written report which summarises what we've done 16:33:03 [ht] ... If anyone objects, we'll here about it 16:33:38 [ht] Action: SW to tell Steve Bratt that the TAG doesn't want a slot at the AC meeting 16:33:38 [trackbot-ng] Created ACTION-11 - Tell Steve Bratt that the TAG doesn't want a slot at the AC meeting [on Stuart Williams - due 2007-08-20]. 16:34:10 [ht] Topic: TAG blog entry: Version identifiers 16:34:24 [ht] NW: Who has not read it : HST, DC, TVR 16:34:39 [ht] NM: It's not long, shall I walk through ito 16:34:45 [ht] s/ito/it?/ 16:35:00 [ht] NW: Go ahead then 16:35:12 [DanC] 16:35:13 [ht] NM: We've gotten some pushback from DO and Mark Baker 16:35:14 [Norm] -> 16:37:46 [DanC] (hmm... it's not clear that the quoted GPN is quoted, especially when the one that's not quoted looks the same) 16:38:15 [ht] [Scribe not trying to transcribe NM's walkthrough] 16:38:24 [DanC] [this bit about xml 1.1 is awfully relevant, and yet it's not in there? odd.] 16:39:09 [DanC] [perhaps the xml 1.1 versioning situation fits better in a separate item.] 16:40:26 [DanC] [the "ASCII doesn't have a version identifier" example that Noah often uses isn't in here. odd.] 16:41:39 [Norm] q+ to observe that "will change in incompatible ways" asks about the future 16:41:40 [ht] q+ to be confused 16:41:48 [Norm] ack ht 16:41:48 [Zakim] ht, you wanted to be confused 16:42:51 [raman] q+ to add that finding mixes "identifying version" with the specific technique of adding a "version attribute" -- 16:43:39 [ht] HST: There's a shift between "provide for marking version" and "when to mark version" in your prose 16:43:48 [ht] ... That seems to me to take us off track 16:44:29 [ht] NM: I think those are closely related -- if you would never want to mark the version, then the language shouldn't provide the mechanism for you to do so. 16:45:26 [Stuart] q+ to note that many of the questions the article raises are associated versioning strategy associated with (all versions of) the language. 16:46:50 [ht] 16:47:07 [ht] NM: If you can't spec. what the version indicator means, you shouldn't have it in your spec. 16:47:19 [DanC] [I hear Noah defending his position but not convincing HT. I think the article is interesting as is, and I'd like to see it go out signed "Noah, a TAG member" and let other TAG members respond with other articles or comments.] 16:47:27 [ht] ... You will just be storing up trouble for the future, c.f. XML's version attribute 16:49:04 [ht] HST: Brings us back to the metapoint as to what the status of TAG blog entries should be -- the settled will of the TAG as a group, or an opportunity for TAG members to discuss something using the blog medium? 16:49:11 [ht] NM: DO said something similar 16:49:41 [ht] SW: I think the value of a blog would be lost if it required consensus 16:49:46 [Norm] q? 16:50:00 [ht] TVR: I agree, we shouldn't turn TAG blog entries into mini-findings 16:50:40 [ht] NM: I think we should reserve the possibility that we do both, that is, we may sometimes want to publish something _with_ consensus 16:50:55 [DanC] (sure, a little telcon preview is a good thing, from time to time) 16:51:18 [Stuart] +1 to DanC 16:51:19 [ht] ... and that I _can_ ask for telcon review on how to make the best posting I can, before I post it 16:51:31 [Norm] But not that I have to ask for it 16:52:01 [ht] NW: So it you remove "for the T A G" from the bottom, you can publish as and when you choose 16:52:03 [Norm] ack Norm 16:52:03 [Zakim] Norm, you wanted to observe that "will change in incompatible ways" asks about the future 16:52:27 [Rhys] +1 to the proposal on blog entries 16:52:35 [Norm] q? 16:52:38 [Norm] ack raman 16:52:38 [Zakim] raman, you wanted to add that finding mixes "identifying version" with the specific technique of adding a "version attribute" -- 16:53:06 [ht] NW: I'm also not sure that I'm unhappy with the existing GPN -- I'm not happy with the idea that the spec. author has to tell in advance whether there will ever be incompatible changes 16:53:48 [ht] TVR: Just to make sure that we're not just talking about version attributes alone as the way of indicating version 16:53:57 [ht] NM: We get to namespaces in the last section 16:54:27 [ht] TVR: What about DOCTYPE line as a version identifier, which is what the HTML WG are going back and forth about 16:54:32 [Norm] q? 16:54:35 [Norm] ack Stuart 16:54:35 [Zakim] Stuart, you wanted to note that many of the questions the article raises are associated versioning strategy associated with (all versions of) the language. 16:55:11 [DanC] (er... let's not leave posting mechanics in the someday pile, please.) 16:55:37 [ht] SW: The questions raised by the article are closely related to the terminology and analysis in the Versioning finding we're working on 16:56:06 [ht] ... I think Mark Baker's comment [link] are along the same lines 16:56:59 [ht] NM: I thought his comments (about header metadata) were strictly-speaking out of scope, because the BPN is about _in-band_ identifiers, but metadata is _out-of-band_ 16:58:30 [ht] DC: Movable Type is weblog support software, in some ways the first one 16:59:11 [ht] ... Karl duBost installed it for W3C and interface it with our CVS system -- this is good, but does introduce a 15-minute delay 16:59:23 ? 16:59:58 [ht] ... It supports categories, so if you categorise things they get syndicated, and can then be grabbed by a web page 17:00:00 [DanC] (yes, analagous to ) 17:00:40 [ht] NM: What about formatting: monospace, display, etc? 17:01:14 [ht] DC: Karl is pretty good with CSS, I don't know what would happen if I added my own. . . 17:03:11 [ht] NW: Summarising -- Karl's setup can easily be expanded to allow us to log in, author new entries, categorise them as "TAG" and feed our blog page 17:03:30 [ht] SW: Different from B2 Evolution -based blogs? 17:04:07 [ht] DC: Yes -- advantage is it's baked not fried -- that is, the HTML is constructed only once, not on demand from a SQL DB 17:04:18 [Zakim] +Dave_Orchard 17:04:54 [ht] TVR: I don't mind what the content management is as long as it doesn't get in the way by producing opaque URIs 17:05:21 [ht] DC: I think we will got good URIs from Movable Type, including year, month and words from the title 17:05:38 [ht] topic: location of the TAG blog 17:06:16 [Norm] -> http// 17:06:16 [DanC] (do I read this correctly? 4 objections to < > ?) 17:08:08 [ht] That option was added late, so the no-entries may just be ones who never saw it 17:08:10 [Noah] Should we just do a prefer/live-with on the two surviving options right now on the phone? 17:08:24 [Norm] Yes, something like that. 17:08:32 [DanC] (I suspect is technically tied to b2evolution) 17:09:05 [Noah] +1 17:09:17 [Rhys] +1 to /tag/blog 17:09:24 [Norm] Proposed: 17:09:57 [ht] SW: DC, can you organise the top-level 'tag' directory that we will need? 17:10:08 [ht] DC: Not without approval from TimBL. . . 17:10:38 [ht] DO: We can resolve on /tag/blog, pending approval 17:10:57 [ht] NM: I don't think we're in a great rush 17:11:13 [Norm] No objections. 17:11:17 [ht] NW: OK, lets try /tag/blog 17:11:37 [ht] Resolved: To locate the TAG blog at 17:11:49 [ht] Action: DC to try to reach TBL to get approval 17:11:49 [trackbot-ng] Created ACTION-12 - Try to reach TBL to get approval [on Dan Connolly - due 2007-08-20]. 17:11:52 [Norm] Proposed title: TAG Lines 17:12:01 [ht] NW: Any objections to TAG Lines? 17:12:35 [ht] Resolved: The TAG blog will be called "TAG Lines", using the mechanisms established by Karl duBost 17:13:22 [ht] Action: DC to ask KdB if categories can be restricted to particular login lists 17:13:22 [trackbot-ng] Created ACTION-13 - Ask KdB if categories can be restricted to particular login lists [on Dan Connolly - due 2007-08-20]. 17:13:43 [Norm] zakim, who's making noise? 17:13:55 [Zakim] Norm, listening for 11 seconds I heard sound from the following: Dave_Orchard (15%) 17:15:52 [ht] NM: We should try to use the description of whatever category we pick to make clear that it's for TAG members only 17:16:17 [ht] DC: I'd be happy if Yves Lafon wrote something about caching for him to use the category 'web architecture' 17:16:33 [ht] HST: Then we shouldn't use 'web architecture' for the TAG blog 17:17:02 [ht] NM: So two categories then, 'web architecture' and 'TAG Member', and I should use both for my post? 17:17:06 [ht] DC, HST: Yes 17:17:20 [ht] topic: httpRange-14 finding status 17:17:30 [Stuart] q+ 17:17:42 [ht] RL: New draft coming soon, significantly changed, lots of new material 17:17:58 [Norm] ack Stuart 17:18:25 [ht] ... available soon, then I'm mostly away until just before the f2f, so you all can review 17:18:57 [ht] SW: I think we've had problems if we try to discuss things that aren't public. . . 17:19:20 [ht] RL: My plan was to put it in public space, but not announce it publicly 17:19:31 [ht] DC: Hmmm, I'd rather it were just out there 17:19:44 [ht] RL: But I won't be available to answer comments 17:20:08 [ht] NM: I've found that just saying that works pretty well 17:20:29 [ht] RL: OK, I'll go ahead and do that 17:20:54 [ht] topic: Request from Ted Guild for BP Note on caching schema documents 17:21:44 [ht] NW: Background: W3C servers get hammered by tools which don't cache schema documents which they request very frequently 17:21:55 [ht] TVR: I don't see that this is a TAG issue 17:23:35 [ht] HST: I think it's a TAG issue, but not restricted to schema docs -- the Web provides for caching, if you anticipate large volumes of traffic from your site, or sites which use your software, to one or more stable resources, you should provide for caches 17:23:59 [Norm] q+ davo 17:24:06 [Norm] ack davo 17:24:20 [ht] NM: More than that, I think our interest here follows from the advice to use only one URI for any given resource 17:24:53 [ht] DO: New issue or not, I think we should take it on, because it follows from our advice on avoiding multiple URIs 17:25:11 [ht] ... We should follow through on the ramifications of our recommendations 17:25:15 [DanC] (it's also true that people shy away from http URIs because they fear their server will melt down.) 17:26:01 [DanC] name brainstorm... httpCaching... hotSpot... 17:26:09 [ht] NW: I hear consensus we should take this up. New issue, or attached to an existing one? If new, then what name? 17:26:58 [Norm] ...representationCaching...managingHotURIs... 17:27:02 [ht] SW: schemas only? 17:27:16 [ht] TVR: No 17:27:30 [Norm] ...scalabilityOfPopularURIs 17:27:34 [ht] HST: schemas, stylesheets (XSLT, CSS, ...) 17:27:36 [Norm] ...uriScalability 17:27:37 [ht] TVR: Images 17:27:43 [ht] HST: Lists of e.g. language codes 17:27:59 [DanC] (caching proxies aren't enough in some cases... in some cases, products that ship with URIs hadcoded might as well ship with a representation hardcoded, and only phone home once every 6 months.) 17:28:03 [Stuart] ...frequentlyAccessedResources 17:28:42 [Norm] Right. Web frameworks running on end-user-machines don't have caching proxies necessarily 17:29:02 [ht] TVR: The architectural problem is in part that the publisher of a popular URI cannot in general ensure responsible caching by clients 17:29:18 [ht] q+ to point out MSoft's response 17:30:03 [Stuart] q+ to suggest advice should include advice to folk deploying such static resources to set expiry time 17:30:04 [ht] NM: But we do expect providers of e.g. popular home pages to scale up the servers in keeping with demand 17:30:28 [DanC] ("economics aside" is not a tactic I want us to take. I want us to keep economics in mind.) 17:30:35 [Norm] ack ht 17:30:35 [Zakim] ht, you wanted to point out MSoft's response 17:30:38 [Stuart] q- 17:30:42 [ht] ... So maybe the W3C is actually at fault here -- what's the division of responsiblity between provider and consumer 17:30:57 [Noah] FWIW: I the reason I thought this discussion was useful was to >scope< the issue, which I think should go beyond caching 17:31:32 [Norm] ...scalabilityOfPopularResources 17:31:44 [Norm] scalabilityForPopularResources 17:31:59 [DanC] (I prefer URI to resource in this case, even though it's wrong. But oh well.) 17:32:25 [DanC] cachingBestPractices 17:32:35 . 17:32:51 [Norm] scalabilityOfURIAccess 17:32:57 [Noah] But yes, the fact that many providers can't afford to scale is a crucial (economic) piece of the puzzle. 17:33:25 [Norm] Proposed: The TAG accept a new issue, scalabilityOfURIAccess-58 17:33:43 [DanC] aye, and I don't care about the number 17:34:02 [ht] Resolved: the TAG accepts a new issue scalabilityOfURIAccess-58 17:34:27 [ht] NW: Someone willing to summarize this and send it to the list? 17:34:45 [ht] DC: NW, did Ted Guild's message cover the background? 17:35:08 [ht] NW: Not all. I'll take the action 17:35:11 [DanC] 17:35:36 [ht] NM: Do try to indicate that this isn't _just_ about caching 17:35:38 [ht] NW: Will do 17:35:40 [Zakim] -Raman 17:35:48 [ht] Action: NW to announce the new issue 17:35:48 [trackbot-ng] Created ACTION-14 - Announce the new issue [on Norman Walsh - due 2007-08-20]. 17:35:53 [Zakim] -Dave_Orchard 17:35:55 [Zakim] -Norm 17:35:56 [Zakim] -Rhys 17:35:58 [Zakim] -Ht 17:35:59 [Zakim] -Noah_Mendelsohn 17:36:12 [Zakim] -Stuart 17:36:13 [ht] zakim, who was here? 17:36:14 [Zakim] I don't understand your question, ht. 17:36:22 [ht] zakim, bye 17:36:22 [Zakim] leaving. As of this point the attendees were Raman, DanC, Ht, Stuart, Rhys, Norm, Noah_Mendelsohn, Dave_Orchard 17:36:23 [Zakim] Zakim has left #tagmem 17:36:40 [ht] RRSAgent, make logs world-visible. 17:36:46 [ht] RRSAgent, make logs world-visible 17:37:07 [ht] RRSAgent, please draft minutes 17:37:07 [RRSAgent] I have made the request to generate ht 19:54:18 [Norm] Norm has joined #tagmem 20:16:31 [Norm] rrsagent, bye 20:16:31 [RRSAgent] I see 7 open action items saved in : 20:16:31 [RRSAgent] ACTION: Stuart to put up straw poll to try to find a new slot for this meeting [1] 20:16:31 [RRSAgent] recorded in 20:16:31 [RRSAgent] ACTION: SW to create new TAG issue called "HTTP Redirections" per minutes of 16/7/07 [2] 20:16:31 [RRSAgent] recorded in 20:16:31 [RRSAgent] ACTION: SW to discuss TAG slot at TP with Steve Bratt, informed by above discussion [3] 20:16:31 [RRSAgent] recorded in 20:16:31 [RRSAgent] ACTION: SW to tell Steve Bratt that the TAG doesn't want a slot at the AC meeting [4] 20:16:31 [RRSAgent] recorded in 20:16:31 [RRSAgent] ACTION: DC to try to reach TBL to get approval [5] 20:16:31 [RRSAgent] recorded in 20:16:31 [RRSAgent] ACTION: DC to ask KdB if categories can be restricted to particular login lists [6] 20:16:31 [RRSAgent] recorded in 20:16:31 [RRSAgent] ACTION: NW to announce the new issue [7] 20:16:31 [RRSAgent] recorded in
http://www.w3.org/2007/08/13-tagmem-irc
CC-MAIN-2014-41
refinedweb
4,527
53.78
lecarfylecarfy A CAR file creator/formatter that creates CAR files with leaf blocks appearing first, in depth first traversal order. Given the following DAG: r | +-------1-------+ | | +---2---+ +---9---+ | | | | +-3-+ +-6-+ +-a-+ +-d-+ | | | | | | | | 4 5 7 8 b c e f This library will create a CAR with blocks arranged in the following order: 4,5,7,8,b,c,e,f,r,1,2,9 When the root block (r) is encountered there are no more leaves in the DAG. InstallInstall npm install lecarfy UsageUsage import { format } from 'lecarfy' import { CarReader } from '@ipld/car' const car = await CarReader.fromBytes(/* ...CAR file bytes... */) const [rootCid] = await car.getRoots() const formattedCar = format(rootCid, car) for await (const bytes of formattedCar) { // bytes is a Uint8Array } APIAPI format (root: CID, blocks: BlockGetter): AsyncIterable<Uint8Array> Format the passed DAG rooted by the passed CID in the lecarfy style. The blocks parameter is an object that implements a method get (key: CID): Promise<Block | undefined> so does not have to be a CarReader. decoders: BlockDecoder<any, any>[] The included IPLD decoders are dag-pb, dag-json and raw. Push onto this array to add decoders. ContributeContribute Feel free to dive in! Open an issue or submit PRs. LicenseLicense Dual-licensed under MIT + Apache 2.0
https://www.npmjs.com/package/lecarfy
CC-MAIN-2022-33
refinedweb
209
64.2
Checkpointing¶ Checkpointing adds restart and rollback capabilities to ASE scripts. It stores the current state of the simulation (and its history) into an ase.db. Something like what follows is found in many ASE scripts: if os.path.exists('atoms_after_relax.traj'): a = ase.io.read('atoms_after_relax.traj') else: ase.optimize.FIRE(a).run(fmax=0.01) ase.io.write('atoms_after_relax.traj') The idea behind checkpointing is to replace this manual checkpointing capability with a unified infrastructure. Manual checkpointing¶ The class Checkpoint takes care of storing and retrieving information from the database. This information always includes an Atoms object, and it can include attached information on the internal state of the script. - class ase.calculators.checkpoint. Checkpoint(db='checkpoints.db', logfile=None)[source]¶ load(atoms=None)[source]¶ Retrieve checkpoint data from file. If atoms object is specified, then the calculator connected to that object is copied to all returning atoms object. Returns tuple of values as passed to flush or save during checkpoint write. flush(*args, **kwargs)[source]¶ Store data to a checkpoint without increasing the checkpoint id. This is useful to continuously update the checkpoint state in an iterative loop. In order to use checkpointing, first create a Checkpoint object: from ase.calculators.checkpoint import Checkpoint CP = Checkpoint() You can optionally choose a database filename. Default is checkpoints.db. Code blocks are wrapped into checkpointed regions: try: a = CP.load() except NoCheckpoint: ase.optimize.FIRE(a).run(fmax=0.01) CP.save(a) The code block in the except statement is executed only if it has not yet been executed in a previous run of the script. The save() statement stores all of its parameters to the database. This is not yet much shorter than the above example. The checkpointing object can, however, store arbitrary information along the Atoms object. Imagine we have computed elastic constants and don’t want to recompute them. We can then use: try: a, C = CP.load() except NoCheckpoint: C = fit_elastic_constants(a) CP.save(a, C) Note that one parameter to save() needs to be an Atoms object, the others can be arbitrary. The load() statement returns these parameters in the order they were stored upon save. In the above example, the elastic constants are stored attached to the atomic configuration. If the script is executed again after the elastic constants have already been computed, it will skip that computation and just use the stored value. If the checkpointed region contains a single statement, such as the above, there is a shorthand notation available: C = CP(fit_elastic_constants)(a) Sometimes it is necessary to checkpoint an iterative loop. If the script terminates within that loop, it is useful to resume calculation from the same loop position: try: a, converged, tip_x, tip_y = CP.load() except NoCheckpoint: converged = False tip_x = tip_x0 tip_y = tip_y0 while not converged: ... do something to find better crack tip position ... converged = ... CP.flush(a, converged, tip_x, tip_y) The above code block is an example of an iterative search for a crack tip position. Note that the convergence criteria needs to be stored to the database so the loop is not executed if convergence has been reached. The flush() statement overrides the last value stored to the database. As a rule save() has to be used inside an except NoCheckpoint statement and flush() outside. Automatic checkpointing with the checkpoint calculator¶ The CheckpointCalculator is a shorthand for wrapping every single energy/force evaluation in a checkpointed region. It wraps the actual calculator. - class ase.calculators.checkpoint. CheckpointCalculator(calculator, db='checkpoints.db', logfile=None)[source]¶ This wraps any calculator object to checkpoint whenever a calculation is performed. This is particularly useful for expensive calculators, e.g. DFT and allows usage of complex workflows. Example usage: calc = … cp_calc = CheckpointCalculator(calc) atoms.set_calculator(cp_calc) e = atoms.get_potential_energy() # 1st time, does calc, writes to checkfile # subsequent runs, reads from checkpoint. Example usage: calc = ... cp_calc = CheckpointCalculator(calc) atoms.set_calculator(cp_calc) e = atoms.get_potential_energy() The first call to get_potential_energy() does the actual calculation, a rerun of the script will load energies and force from the database. Note that this is useful for calculation where each energy evaluation is slow (e.g. DFT), but not recommended for molecular dynamics with classical potentials since every single time step will be dumped to the database. This will generate huge files.
https://wiki.fysik.dtu.dk/ase/dev/ase/calculators/checkpointing.html
CC-MAIN-2020-05
refinedweb
715
50.53
I know that most of You stays for that exec shouldn't be used, but I have some problem. Here is minimal example, which works: class A: def __init__(self): exec('self.a = self.funct()') def funct(self): return 1 def ret(self): return self.a > obj = A() > obj.ret() 1 But, when I do: class A: def __init__(self): exec('self.a = self.__funct()') def __funct(self): return 1 def ret(self): return self.a > obj = A() AttributeError: 'A' has no attribute '__funct' Does anybody know why is that difference? __name names are class private; such names are prefixed, at compile time, with another underscore and the class name. The purpose is to protect the names from accidental clashes with names used in subclasses. These names are not meant to be private to outside callers. Quoting the Reserved classes of identifiers section: __* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. and the Identifiers (Names) section:occurring in a class named Hamwill be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. What happens in your case is that exec() postpones compilation, effectively compiling that call in isolation. The class context is gone, so no mangling takes place. As such, you need to apply the automatic prefixing manually: exec('self.a = self._A__funct()') If you are using Python 3, you could use the __class__ closure normally available for the super() function to access the class name the current method is defined for: exec('self.a = self._{0.__name__}__funct()'.format(__class__)) Now, unless you actually plan for your class to be widely subclassed in third-party code that should not have to worry about accidentally clashing with internal implementation details, you should not be using double-underscore names at all. Stick with single-underscore names instead. Python private methods are "disguised" under a different identifier than the one specified in the code, you can access them like _classname__privateAttribute. Posting this to be specific: class A: def __init__(self): exec('self.a = self._A__funct()') def __funct(self): print("Hello") def ret(self): return self.a obj = A() I put the print answer there to detect if it worked, and it did!
http://m.dlxedu.com/m/askdetail/3/a0dc437c0e8fa56730da997ee4846855.html
CC-MAIN-2018-47
refinedweb
399
56.35
Introduction Can you imagine the programming process without the possibility of debugging program code at run-time? It is obvious that such programming may exist, but programming without a debugging possibility is too complicated when we are working on big and complex projects. In addition to standard approaches of debugging program code, such as an output window on the Visual Studio IDE or the macros of asserts, I propose a new method for debugging your code: to output your debugging data to the application that is separated from the Visual Studio IDE and the project you are currently working on. Features What's so good about it and should I use it? - It's a separate module that allows you to trace and debug the release version of your project. - It is a fully controlled module with a command set that enables you to control your debugging process: closing tracing windows (also known as trace channel), saving the entry of the trace window to the file, and so forth. Full control set are described below. - This module supports several (the number of trace channels is unlimited) strategies of trace channels. A detailed description about trace channel is described below. - You can easily modify this module to meet your needs. Behaviour Launch the application of trace messages catcher (next: trace catcher) before you start working with this module. Tracing data, sent to the trace catcher application, will be saved if the catcher application was inactive or was terminated during the trace operations. All the data that were saved during the critical situations, as described above, will be kept and popped-out to the trace catcher application when it starts again. There's a possibility to start the trace catcher application with the creation of the trace module and terminate it when the trace module is being destructed. _Log.setSectionName( "channel_#1" ); _Log.dump( "%s", "My trace data" ); or _Log.dumpToSection( "channel_#1", "%s", "My trace data" ); If you send your trace data to the new trace channel that is not created in the trace catcher application, a new trace channel will be created automatically. In addition to sending your trace data to the catcher, there's a possibility to manipulate the trace catcher application with commands help. Commands are divided into two parts: global commands and commands that depend on the trace channel. Global commands affecting the whole trace catcher application: closeRoot—closing the trace catcher application; onTop.ON—enabling always on top state for the catcher application; onTop.OFF—disabling always on top state for the catcher application. Example: _Log.sendCmd( "closeRoot" ); _Log.sendCmd( "onTop.ON") Commands affecting certain trace channels: clear—deleting the entry of the given trace channel; close—closing the given trace channel; save<path to output stream>—saving the entry of the given trace channel to the output stream that you described. Example: _Log.sendCmd( "Channel_1", "clear" ); _Log.sendCmd( "Channel_2", "save c:\\channel2.log" ); _Log.sendCmd( "close" ); /** close the current output window * (section) */ How to Use It To fully use this trace module, you have to do only two steps: - First: You must copy the [LogDispatch.dir] directory from the unzipped source file (LogDispatch_src.zip) to your project directory. - Second: You must include the header of this module in your project modules were you want to use it. Example: #include "path_by_you\LogDispathc.dir\LogDispath.h" <ClogDispatch> methods To call all the messages described below, you must use variable names as follows: [_Log]. The trace object is created once during the project lifetime (using a singleton pattern). Let's say calling the dump message will be described like this: _Log.dump( "System time is %d %d %5.5f ", 15, 10, 08.555121 ); Tracing operations dump—Formatted trace data (sprintf format) are sent to catcher application. The tracing data will be placed to the section named as the result of calling the "setSectionName" method before that; or, if the "setSectionName" method wasn't called, tracing data will be placed to the default section named as "output@default". dumpToSection—The principle is the same as dump message. The difference is that this message will place your data to the channel by the name that you described in this message. setSectionName—Set the working (active) channel name. Configuration command getCmdPrefix—Sets the prefix of the command. setCmdPrefix—Returns the prefix of the command. sendCmd—Sends your message to the receiver application. setCloseOnExit—Enables/disables the possibility to send the message to the catcher application on exit. setCloseCMDOnExit—Sets the command of the catcher application that will be sent when the trace module is destroyed. Additional operations of the module configuration setClassNameOfCatcher—Sets the class name of the catcher application. That class name will be used in the search of the catcher application where the tracing data will be sent. runCatcher—Executes the catcher application from the described path. Conclusion This trace module and the strategy we are using on it is a very flexible and effective trace tool for debugging big projects. In my opinion, this tool will be a very effective strategy to trace release versions of the project where all debugging data are removed. It is very easy and comfortable to use it. Window resizing for sidebar debugging on release versionsPosted by revoscan on 08/04/2005 06:43pm
https://www.codeguru.com/cpp/v-s/debug/logging/article.php/c7231/LogDispatchmdashDebug-Module.htm
CC-MAIN-2018-51
refinedweb
881
55.64
This appendix provides detailed information about the support available within RUEI for the use of XPath queries. XPath (XML Path Language) is a query language that can be used to query data from XML documents. In RUEI, XPath queries can be used for content scanning of XML documents. A complete specification of XPath is available at. It is based on a tree representation of the XML document, and selects nodes by a variety of criteria. In popular use, an XPath expression is often referred to simply as an XPath. RUEI supports the use of a limited set of XPath expressions to identify page names and Web services, and in performing page content and functional error checks. Optionally, you can extend the search to include the search for a literal string within the found element(s). Note that XPath expressions are case sensitive. Basic XPath Queries Consider the following simple XML document that has a root element <a>, which has one child element <b>, which in turn has two child elements, <c> and <d>. <?xml version="1.0" encoding="UTF-8"?><a> <b> <c>Hello world!</c> <d price="$56" /> </b></a> In XPath queries, the child-of relation is indicated with a / (slash) and element names are written without angle brackets ( < and >). Hence, a/b means select <b> elements that are children of <a> elements. A / at the start of a query indicates that the first node in the path is the root element of the document. For example, the following query selects <c> elements that are children of a <b> element that is a child of the root element <a>: /a/b/c When used for content scanning, this would extract the text "Hello world!" from the above example document. As another example, the query /html/body/div/p would extract the contents of all paragraphs inside a <div> in the body of an XHTML document. Besides extracting the contents of elements, there is one other type of data that can be extracted; XML attribute values. To query attributes, you can refer to them as a "child" of the element of which they are an attribute. To distinguish attribute names from element names, they must be prefixed with a @ character. An @attribute node may only appear as the very last node in an XPath. For example, the following query extracts the text "$56" from the above example document: /a/b/d/@price Restrictions The XPath syntax supported by RUEI is a subset of the abbreviated XPath syntax. As a result, you may find that some syntax elements that work correctly in other XPath applications do not work in RUEI. For example, the following queries are not accepted: //c # error, // not supported/a/*/b # error, * not supported/a/b/c/../b # error, . and .. not supported In addition, the following queries, although perfectly fine, will not extract anything from the above example document: /a/c # no <c> elements are children of the <a> element/b/c # <b> is not the root element/a/b/e # the document does not have <e> elements Element and attribute names are case-sensitive. Hence, /a/b/c is not the same as /A/B/C. In RUEI, all XPath queries must be absolute paths. That is, they must start at the root node, and each child element along the path must be named explicitly. Indices and Attribute Predicates Consider the slightly more complex XML document: <?xml version="1.0" encoding="UTF-8"?><inventory> <item class="food"> <name>Bread</name> <amount>12</amount> </item> <other> <msg>not available</msg> </other> <item class="cleaning"> <name>Soap</name> <amount>33</amount> </item> <item class="food" type="perishable"> <name>Milk</name> <amount>56</amount> </item></inventory> The root element <inventory> has three <item> children, and an <other> child. By using an index [N] on a node in an XPath query, we can explicitly select the N-th <item> child element (counting starts at 1, not 0): /inventory/item[2]/name # extracts "Soap" Note that when working the above example document, there is no point in specifying an index on the <name> node. There are three <name> elements in the document, but they are all children of a different <item> element. Hence, they each are the first child. /inventory/item/name[2] # extracts nothing Attribute predicates are another way to specify more precisely which elements you want to select. They come in two forms: [@attr="value"] selects only elements that have the attr attribute set to value, and [@attr] selects only elements that have an attr attribute (set to any value). /inventory/item[@class="cleaning"]/name # extracts "Soap"/inventory/item[@type]/name # extracts "Milk" The and keyword can be used to combine multiple attribute predicates within a single node. However, the XPath keyword or is not supported. In addition, instead of double quotes (") you can use single quotes (') to enclose the attribute value. /inventory/item[@class='food' and @type]/name # extracts "Milk" Indices and attribute predicates can be combined. The difference between the following two queries is that query A first selects all <item> elements with class="food", and then takes the second one, while query B selects the second <item> element under the condition that it has class="food" (but in the example it has class="cleaning"). A: /inventory/item[@class="food"][2]/name # extracts "Milk"B: /inventory/item[2][@class="food"]/name # extracts nothing Example Consider the following XML-SOAP messages: <?xml version="1.0" ?><env:Envelope xmlns: <env:Header> <env:Upgrade> <env:SupportedEnvelope <env:SupportedEnvelope </env:Upgrade> </env:Header> <env:Body> <env:Fault> <env:Code> <env:Value>env:VersionMismatch</env:Value> </env:Code> <env:Reason> <env:Text xml:Version Mismatch</env:Text> </env:Reason> </env:Fault> </env:Body></env:Envelope> The error value env:VersionMismatch can be extracted with the following XPath query: /env:Envelope/env:Body/env:Fault/env:Code/env:Value Important In order to apply XPath queries to a real-time HTTP data stream, RUEI only supports a limited set of XPath 1.0 functionality. In particular: References to internal and external files (such as DTDs) within input traffic are ignored. The self-or-descendant (//) operator is not supported. The maximum depth in XPath expressions is 8 levels. No string within an expression should be a complete substring of any other specified string. Strings have a maximum length of 256 bytes. In addition, you should be aware of the following: RUEI applies XPath matching to all traffic content, regardless of whether or not it is actually in XML format. Hence, while XHTML is supported, it is interpreted as well-formed XML. Hence, using XPath queries on non-well-formed XML or non-XML traffic can lead to unreliable results. The use of namespaces and CDATA is not supported. If they appear in the input stream, they are treated literally. This can lead to false matches. All expressions are resolved as "AND". The use of the "OR" and relational expressions (such as <=, >=, <, and >) is not supported. Using Third-Party XPath Tools For convenience, you can use third-party XPath tools, such as the XPather extension for Mozilla Firefox, to create XPath expressions for use within RUEI. The XPather extension is available at. When installed, you can right-click within a page, and select the Show in XPather option. An example is shown in Appendix F. Figure F-1 XPather Tool You can then copy the XPath expression within the XPather browser (shown in Figure F-2) and use it the basis for your XPath query with RUEI. Be aware that you should review the generated XPath expression to ensure that it confirms to the restrictions described above. Figure F-2 XPather Browser
http://docs.oracle.com/cd/E15353_01/doc.51/e15344/xpath.htm
CC-MAIN-2016-44
refinedweb
1,277
53
NAME kldsym — look up address by symbol name in a KLD LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <sys/param.h> #include <sys/linker.h> int kldsym(int fileid, int command, void *data); DESCRIPTION The kldsym() system call returns the address of the symbol specified in data in the module specified by fileid. If fileid is 0, all loaded modules are searched. Currently, the only command implemented is KLDSYM_LOOKUP. The data argument is of the following structure: struct kld_sym_lookup { int version; /* sizeof(struct kld_sym_lookup) */ char *symname; /* Symbol name we are looking up */ u_long symvalue; size_t symsize; }; The version member is to be set by the code calling kldsym() to sizeof(struct kld_sym_lookup). The next two members, version and symname, are specified by the user. The last two, symvalue and symsize, are filled in by kldsym() and contain the address associated with symname and the size of the data it points to, respectively. RETURN VALUES The kldsym() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. ERRORS The kldsym() system call will fail if: [EINVAL] Invalid value in data->version or command. [ENOENT] The fileid argument is invalid, or the specified symbol could not be found. SEE ALSO kldfind(2), kldfirstmod(2), kldload(2), kldnext(2), kldunload(2), modfind(2), modnext(2), modstat(2), kld(4) HISTORY The kldsym() system call first appeared in FreeBSD 3.0.
http://manpages.ubuntu.com/manpages/precise/man2/kldsym.2freebsd.html
CC-MAIN-2016-18
refinedweb
242
60.95
Lab 7: Midterm Review Due at 11:59pm on Friday, 07/19/2019.. - In order to facilitate midterm studying, solutions to this lab were released with the lab. We encourage you to try out the problems and struggle for a while before looking at the solutions! - Note: submitting this lab is entirely optional. It is not worth any credit, but will be helpful for your studying. Required Questions Functions Q2 Draw the environment diagram for the following code: x = 5 def compose1(f, g): def h(x): return f(g(x)) return h d = lambda y: y * x x = 4 result = compose1(lambda z: z - 1, d)(3) There are 5 frames total (including the Global frame). In addition, consider the following questions: - In frame f1(the frame for compose1), the parameter fpoints to a function object. What is the intrinsic name of that function object, and what frame is its parent? - In frame f2, what name is the frame labeled with ( hor λ)? Which frame is the parent of f2? - In frame f3, what name is the frame labeled with ( f, g, d, or λ)? Which frame is the parent of f3? In order to compute the return value y * x, in which frame does Python find x? What is that value of x? - In frame f4, what name is the frame labeled with ( f, g, d, or λ)? Which frame is the parent of f3? - What value is the variable resultbound to in the Global frame? You can try out the environment diagram at tutor.cs61a.org. - The intrinsic name of the function object that fpoints to is λ (specifically, the lambda whose parameter is z). The parent frame of this lambda is Global. f2is labeled with the name h; the parent frame of f2is f1, since that is where his defined. f3is labeled with the name λ (specifically, it is the λ that takes in a parameter y). The parent frame of f3is Global, since that is where this lambda was defined (the line d = lambda y: y * x). f4is labeled with the name λ (specifically, it is the λ that takes a parameter z). The parent frame of f4is Global, since that is where the lambda is defined. You might think that the parent of f4is f1, since lambda z: z - 1is being passed into compose1. Remember, however, that operands are evaluated before the operator is applied (that is, before we create the frame f1). Since we are evaluating lambda z: z - 1in the Global frame, its parent is Global. - The variable resultis bound to 11. Recursion & Tree Recursion Q Q4: Number of Trees How many different possible full binary tree (each node has two branches or 0, but never 1) structures exist that have exactly n leaves? For those interested in combinatorics, this problem does have a closed form solution): def num_trees(n): """How many full binary trees have exactly n leaves? E.g., 1 2 3 3 ... * * * * / \ / \ / \ * * * * * * / \ / \ * * * * >>> num_trees(1) 1 >>> num_trees(2) 1 >>> num_trees(3) 2 >>> num_trees(8) 429 """"*** YOUR CODE HERE ***"if n == 1: return 1 return sum(num_trees(k) * num_trees(n-k) for k in range(1, n)) Use Ok to test your code: python3 ok -q num_trees Tree Practice Q Sequences and Mutability Q6: WWPD: Mutability? What would Python display? Try to figure it out before you type it into the interpreter! Use Ok to test your knowledge with the following "What Would Python Display?" questions: python3 ok -q mutability -u >>> lst = [5, 6, 7, 8] >>> lst.append(6)______Nothing>>> >>> pokemon = {'pikachu': 25, 'dragonair': 148, 'mew': 151} >>> pokemon['pikachu']______25>>> len(pokemon)______3>>> pokemon['jolteon'] = 135 >>> pokemon['mew'] = 25 >>> len(pokemon)______4>>> 'mewtwo' in pokemon______False>>> 'pikachu' in pokemon______True>>> 25 in pokemon______False>>> 151 in pokemon______False>>> pokemon['ditto'] = pokemon['jolteon'] >>> pokemon['ditto']______135 Q7: Dict to List Fill in the blanks in the code to complete the implementation of the dict_to_lst function, which takes in a dictionary d and returns a list. The resulting list should contain all the (key, value) pairs in the input dictionary as two-element tuples, where the pairs with smaller values come first. Note: The .items()method returns a collection of (key, value) pairs for a dictionary: >>> for pair in {1: 2, 3: 4, 5: 6}.items(): ... print(pair) (1, 2) (3, 4) (5, 6) def dict_to_lst(d): """Returns a list containing all the (key, value) pairs in d as two-element tuples ordered by increasing value. >>> nums = {1: 5, 2: 3, 3: 4} >>> dict_to_lst(nums) [(2, 3), (3, 4), (1, 5)] >>> words = {'first': 'yes', 'second': 'no', 'third': 'perhaps'} >>> dict_to_lst(words) [('second', 'no'), ('third', 'perhaps'), ('first', 'yes')] """ result = [] for _ in range(len(d)):pair = min(d.items(), key=______________________)pair = min(d.items(), key=lambda item: item[1])d.pop(_________)d.pop(pair[0])_______________________result.append(pair)return result# Alternate solution # This solution is the ideal way to solve this problem, but we haven't learned # how to use the sorted function so don't worry if you don't understand it. def dict_to_list2(d): return sorted(d.items(), key=lambda pair: pair[1]) Use Ok to test your code: python3 ok -q dict_to_lst
https://inst.eecs.berkeley.edu/~cs61a/su19/lab/lab07/
CC-MAIN-2020-29
refinedweb
858
71.55
How to show random picture from a folder in Python This tutorial is about how to show a random picture from a folder in Python. Python contains a lot of Predefined modules. Python has a module that is the random module by using the random module to show a random picture from a folder. The following are constraints to get a random picture: - The picture folder path must be specified to open the picture on the computer. - By using random.choice() method to select a particular picture present in the folder. - All the pictures must be stored in the .py file location to start the picture using the OS module otherwise you must change to picture folder location using change directory to start the picture. Importing Random Module: So, let’s have a look at importing the random module: import random Importing random module in .py file Importing OS Module: So, let us have a look at importing the OS module: import random import os Importing os module in .py file Folder details: The folder contains a lot picture (.jpg) or (.png) by using random function a particular picture is selected show the picture using OS module #-----------------Inside the folder----------- image 1 image 2 image 3 Example to show a random picture from a folder in Python: import os import random path="C:\\Users\\sairajesh\\Desktop\\image" files=os.listdir(path) d=random.choice(files) os.startfile(d) output: The random picture output will be shown for example: Explanation: - First, you select the path of the folder where the picture is present like->c\\user\\folder - By using the listdir() method store all the images present in the folder - By using random.choice() method to select a image and os.startfile() method to show the image. OS.Start file() method: The os.startfile() method will be used to run files present in the folder directly on the default opener of the file. Also read: it did not work, but Fahim found the solution on on the mp3 page June 1, 2021 at 2:28 pm I Have the solution of error !! Just replace :- os.startfile(d) with :- os.startfile(f”# path were is music is located#{d}”) in my case it was :- os.startfile(f”C:/Users/Kazi Fahim/Music/mp3/{d}”)
https://www.codespeedy.com/how-to-show-random-picture-from-a-folder-in-python/
CC-MAIN-2022-27
refinedweb
382
63.19
Inside content module i have 2 variables which are assigned to id attributes of 2 hierarchical units. I want to hide the grid cell if both units are empty using visibility condition. If i write just one line "return false" in condition expression it works fine(obviously) but even this code always evaluates to true: def expr = share != null || details != null println expr return false How can that be? The value of expr printed to system output is 'false' but putting <c:out in jsp returns true. And yes, i've put 'return false' here but even with this it evaluates to true. So the cell is always shown. <c:out Hi, in order to obtain the desired result, you can try the following solution: 1) Add two Selector Units inside the page containing the Hierarchical Index Units. Each Selector Unit is related to the Entity specified on a Hierarchical Index Unit (e.g. the Entity of the Selector Unit 1 is the same as the Entity specified on the Hierarchical Index Unit 1 at Level 0, and so on). 2) Add two variables: the first one refers to the "Data Size" parameter of the Selector Unit 1, while the second one refers to the "Data Size" parameter of the Selector Unit 2. 3) Add a Condition Expression working on the previous variables ("var1" and "var2" are the name of the variables): def expr = var1 != 0 || var2 != 0 return expr 4) Select the Grid Cell containing the units and in the Condition tab, set the "Cell Visibility Cond." property to the Condition Expression. In this way, if both Hierarchical Index Units are empty, the Grid Cell will be hidden.
https://my.webratio.com/forum/question-details/something-leads-to-wrong-condition-expression-evaluation?nav=43&link=oln15x.redirect&kcond1x.att11=368
CC-MAIN-2021-10
refinedweb
279
61.36
When you are building applications that are voice-enabled, meaning they can make and receive phone calls, the most fundamental thing you need to be able to do is to play audio into the call programmatically. This serves as the basis for IVRs, an alert system that you're going to be connected to a call, as a prompt to do something, or even just an on-hold message. Without the ability to play audio into a call, there are few use cases for voice-enabled apps beyond voice-proxying. In this tutorial, we'll be exploring how to get off the ground playing audio into calls with Vonage's Voice API and ASP.NET Core MVC. Jump Right to the Code If you want to skip over this tutorial and just jump right to the code, it's all available in GitHub. Prerequisites - We're going to need the latest .NET Core SDK, I'm using 3.1 - We're going to use Visual Studio Code for this tutorial. Of course, this will also work with Visual Studio and Visual Studio for Mac. There may just be some slightly different steps for setup and running. - We'll be testing this with ngrok - so go ahead and follow their instructions for setting it up. - We're going to need npm to fetch<< Topic Overview There are two methods that we are going to be talking through to play audio into a call. - When our application is called, it will return an NCCO (Nexmo Call Control Object) telling Vonage what to play into the call. - We will be using the Vonage Voice API (VAPI) to place a call and play audio into the call that we create. In both cases, we are going to be using audio streaming functionality. This allows us to play an audio file into a call. However, I’d be remiss if I didn’t point out that in addition to playing audio files into calls, there is no shortage of ability to customize what’s played into a request—whether it’s using the Text-To-Speech(TTS) API or using websockets to play dynamic audio streams into a call. Setup the Nexmo CLI With npm installed we can go ahead and install and configure the Nexmo CLI using: npm install @vonage/cli -g vonage config:setup --apiKey=API_KEY --apiSecret=API_SECRET This will get the Nexmo CLI setup and ready to run. Run Ngrok I'm going to be throwing everything on localhost:5000. Run ngrok to publicly access localhost:5000. ngrok http --host-header=localhost:5000 5000 Take a note of the URL that ngrok is running on. In my case, it's running on. This. vonage apps:create √ Application Name ... "AspNetTestApp" √ Select App Capabilities » Voice √ Create voice webhooks? ... yes √ Answer Webhook - URL ... √ Answer Webhook - Method » GET √ Event Webhook - URL ... √ Event Webhook - Method » POST √ Allow use of data for AI training? Read data collection disclosure - ... no Creating Application... done This is going to create a Vonage Application. It's going to then link all incoming calls to that application to the answer URL:. All call events that happen on that application are going to be routed to. This command is going to print out two things. - Your application id - you can view this you Vonage Number and your Application Id and run the following: vonage apps:link APPLICATION_ID --number=VONAGE_NUMBER With this done, your calls are going to route nicely to your URL. Create Project In your console, navigate to your source code directory and run the following command: dotnet new mvc -n PlayAudioMvc That will create a directory and project called PlayAudioMvc, run the cd command to change your directory to PlayAudioMvc, and run the following to install the Vonage library. dotnet add package Vonage Run code . to open Visual Studio Code. Edit the Controller Add Using Statements We're going to be piggy-backing off of the HomeController.cs file, open Controllers\HomeController.cs and add the following using statements to the top: using Microsoft.Extensions.Configuration; using Vonage.Voice.Nccos.Endpoints; using Vonage.Voice.Nccos; using Vonage.Voice; using Vonage.Request; Inject Configuration We're going to be leveraging dependency injection to get some of the configurable items for our app, namely the appId and private key. To this end, add an IConfiguration field to the HomeController, then add an IConfigurationParameter to the constructor and assign that IConfiguration field to the parameter. Your constructor should now look like this. While we're up here, let's also add a constant to this class to point to an audio file on the web, there's a serviceable one that Vonage provides for test cases that we'll link to: const string STREAM_URL = ""; private readonly IConfiguration _config; public HomeController(ILogger<HomeController> logger, IConfiguration config) { _config = config; _logger = logger; } Add Answer Endpoint We're going to be addressing case 1: where we receive a call from a user, and we want to play an audio file into it. We're going to need to add an action to our controller that will return a JSON string. Add the following to our HomeController class: [HttpGet("/webhooks/answer")] public string Answer() { var streamAction = new StreamAction{ StreamUrl = new string[] { STREAM_URL } }; var ncco = new Ncco(streamAction); return ncco.ToString(); } When someone dials in, Vonage is going to make a Get Request on this URL. This method leverages our NCCO builder to create an NCCO; we then convert the NCCO to a string and return it. This will return a JSON string that will look like this: [{"streamUrl":[""],"action":"stream"}] Add Dial Out The next action we're going to need to add is an action to dial out. This is just a bit more complicated. It's going to need to get our appId and key out of the configuration. It also needs a number to call and a number to call from, your Vonage Number, then it will build a Voice Client, create a request structure and place the call: [HttpPost] public IActionResult MakePhoneCall(string toNumber, string fromNumber) { var appId = _config["APPLICATION_ID"]; var privateKeyPath = _config["PRIVATE_KEY_PATH"]; var streamAction = new StreamAction{ StreamUrl = new string[] { STREAM_URL }}; var ncco = new Ncco(streamAction); var toEndpoint = new PhoneEndpoint{Number=toNumber}; var fromEndpoint = new PhoneEndpoint{Number=fromNumber}; var credentials = Credentials.FromAppIdAndPrivateKeyPath(appId, privateKeyPath); var client = new VoiceClient(credentials); var callRequest = new CallCommand { To = new []{toEndpoint}, From = fromEndpoint, Ncco= ncco}; var call = client.CreateCall(callRequest); ViewBag.Uuid = call.Uuid; return View("Index"); } Add a Frontend Going off the theme of piggybacking off our Home Controller, we're also going to be piggybacking off our Home View. Open Views\Home\Index.cshtml, and remove the boilerplate div that's in there. We're going to be adding a basic form that will post to our MakePhoneCall action, and when the action finishes, we will display the call UUID from our Phone call. With this in mind, let's add the following to our file: @using (Html.BeginForm("MakePhoneCall", "home", FormMethod.Post)) { <div class="form-vertical"> <h4>Call<h4> @Html.ValidationSummary(true, "", new { @ @Html.Label("To") <div> @Html.Editor("toNumber", new { htmlAttributes = new { @ @Html.Label("From") <div> @Html.Editor("fromNumber", new { htmlAttributes = new { @ <div class="col-md-offset-2 col-md-10"> <button type="submit">Send</button> </div> </div> </div> } @if(@ViewBag.Uuid != null){ <h2>Call UUID: @ViewBag.Uuid</h2> } Configure Your App Add Config Variables Remember that we are using the IConfiguration to get our appId and our private key path. With that in mind, let's open up appsettings.json and add the following keys: "APPLICATION_ID":"APPLICATION_ID", "PRIVATE_KEY_PATH":"C:\\path\\to\\your\\private.key" Configure Kestrel or IIS Express As I'm using VS Code, my app is naturally going to use kestrel. Regardless of whether you are using kestrel or IIS Express, go into properties\launchSettings.json and from the PlayAudioMvc-> applicationUrl drop the endpoint—since we are not using SSL with ngrok, and we're pointing to port 5000. If you are using IIS Express, in iisSettings-> iisExpress, set the applicationUrl to and the sslPort to 0. Testing Your Application With this done, all you need to do is run the command dotnet run and your application will start up and be hosted on port 5000. All that's left to do now is to call your application—you can call it on your Vonage number and place a call from your application. You can place the call by navigating to localhost:5000 and filling out and submitting the form. Resources - You can learn much more about the Voice API By checking out our documentation website - You can learn A LOT about working voice APIs, particularly the NCCOS, by checking out our NCCO reference - All the code from this tutorial is available in GitHub
https://developer.vonage.com/blog/2020/08/07/how-to-play-audio-into-a-call-with-asp-net-core-mvc-dr
CC-MAIN-2022-27
refinedweb
1,461
54.93
Control.Proxy.Trans.Tutorial Description This module provides the tutorial for the Control.Proxy.Trans hierarchy Synopsis Motivation In a Session, all composed proxies share effects within the base monad. To see how, consider the following simple Session: client1 :: () -> Client () () (StateT Int IO) r client1 () = forever $ do s <- lift get lift $ lift $ putStrLn $ "Client: " ++ show s lift $ put (s + 1) request () server1 :: () -> Server () () (StateT Int IO) r server1 () = forever $ do s <- lift get lift $ lift $ putStrLn $ "Server: " ++ show s lift $ put (s + 1) respond () >>> execWriterT $ runProxy $ client1 <-< server1Client: 0 Server: 1 Client: 2 Server: 3 Client: 4 Server: 5 ... The client and server share the same state, which is sometimes not what we want. We can easily solve this by running each Proxy with its own local state by changing the order of the Proxy and StateT monad transformers: client2 :: () -> StateT Int (Client () () IO) r client2 () = forever $ do s <- get lift $ lift $ putStrLn $ "Client: " ++ show s put (s + 1) lift $ request () server2 :: () -> StateT Int (Server () () IO) r server2 () = forever $ do s <- get lift $ lift $ putStrLn $ "Server: " ++ show s put (s + 1) lift $ respond () ... but then we can no longer compose them directly. We have to first unwrap each one with evalStateT before composing: >>> runProxy $ (`evalStateT` 0) . client2 <-< (`evalStateT` 0) . server2Client: 0 Server: 0 Client: 1 Server: 1 Client: 2 Server: 2 ... Here's another example: suppose we want to handle errors within proxies. We could try adding EitherT to the base monad like so: import Control.Error client3 :: () -> Client () () (EitherT String IO) () client3 () = forM_ [1..] $ \i -> do lift $ lift $ print i request () server3 :: (Monad m) => () -> Server () () (EitherT String m) r server3 () = lift $ left "ERROR" >>> runEithert $ runProxy $ client2 <-< server21 Left "ERROR" Unfortunately, we can't modify server2 to catchT that error because we cannot access the inner EitherT monad transformer until we run the Session. We'd really prefer to place the EitherT monad transformer outside the Proxy monad transformer so that we can catch and handle errors locally within a Proxy without disturbing other proxies: client4 :: () -> EitherT String (Client () () IO) () client4 () = forM_ [1..] $ \i -> do lift $ lift $ print i lift $ request () server4 :: () -> EitherT String (Server () () IO) () server4 () = (forever $ do lift $ respond () throwT "Error" ) `catchT` (\str -> do lift $ lift $ putStrLn $ "Caught: " ++ str server4 () ) However, this solution similarly requires unwrapping the client and server using runEitherT before composing them: >>> runProxy $ runEitherT . client4 <-< runEitherT . server41 Caught: Error 2 Caught: Error 3 Caught: Error ... Proxy Transformers We need some way to layer monad transformers outside the proxy type without interfering with Proxy composition. To do this, we overload Proxy composition using the Channel type class from Control.Proxy.Class: class Channel p where idT :: (Monad) m => a' -> p a' a a' a m r (>->) :: (Monad m) => (b' -> p a' a b' b m r) -> (c' -> p b' b c' c m r) -> (c' -> p a' a c' c m r) Obviously, Proxy implements this class: instance Channel Proxy where ... ... but we would also like our monad transformers layered outside the Proxy type to also implement the Channel class so that we could compose them directly without unwrapping. Unfortunately, these monad transformers do not fit the signature of the Channel class. Fortunately, the Control.Proxy.Trans hierarchy provides several common monad transformers which have been upgraded to fit the Channel type class. I call these "proxy transformers". For example, Control.Proxy.Trans.State provides a proxy transformer equivalent to Control.Monad.Trans.State. Similarly, Control.Proxy.Trans.Either provides a proxy transformer equivalent to Control.Monad.Trans.Either. Let's use a working code example to demonstrate how to use them: import Control.Proxy.Trans.State client5 :: () -> StateP Int Proxy () () () C IO r client5 () = forever $ do s <- get liftP $ lift $ putStrLn $ "Client: " ++ show s put (s + 1) liftP $ request () server5 :: () -> StateP Int Proxy C () () () IO r server5 () = forever $ do s <- get liftP $ lift $ putStrLn $ "Server: " ++ show s put (s + 1) liftP $ respond () You'll see that our type signatures changed. Now we use StateP instead of StateT. However, StateP does not transform monads, but instead transforms proxies. To see this, let's first study the kind of StateT. If we first define: kind MonadKind = * -> * Then StateT s takes a monad, and returns a new monad: StateT s :: MonadKind -> MonadKind Now consider the kind of a Proxy-like type constructor suitable for the Channel type class: kind ProxyKind = * -> * -> * -> * -> (* -> *) -> * -> * Then StateP s takes a Proxy-like and returns a new Proxy-like type: StateP s :: ProxyKind -> ProxyKind This is why I call these "proxy transformers" and not monad transformers. They all take some Proxy-like type that implements Channel and transform it into a new Proxy-like type that also implements Channel. For example, StateP implement the following instance: instance (Channel p) => Channel (StateP s p) where ... All proxy transformers guarantee that if the base proxy implements the Channel type class, then the transformed proxy also implements the Channel type class. This means that you can build a proxy transformer stack, just like you might build a monad transformer stack. Unfortunately, in order to use proxy transformers, you must expand out the Client and Server type synonyms, which are not compatible with proxy transformers. Sorry! This is why there are no Server or Client type synonyms in the types of our new client and server and I had to write out all the inputs and outputs. Notice how the outermost lift statements in our client and server have changed to liftP. liftP replaces lift for proxy transformers, and it lifts any action in the base proxy to an action in the transformed proxy. In the previous example, the base proxy was Proxy and the transformed proxy was StateP s Proxy, so liftPs type got specialized to: liftP :: Proxy a' a b' b m r -> StateP s Proxy a' a b' b m r The ProxyTrans class defines liftP, and all proxy transformers implement the ProxyTrans class. Since proxies are still monads, liftP must behave just like lift and obey the monad transformer laws: (liftP .) return = return (liftP .) (f >=> g) = (liftP .) f >=> (liftP .) g But, unlike lift, liftP obeys one extra set of laws that guarantee it also lifts composition sensibly: (liftP .) idT = idT (liftP .) (f >-> g) = (liftP .) f >-> (liftP .) g In fact, this (liftP .) pattern is so ubiquitous, that the ProxyTrans class provides the additional mapP method for convenience: mapP = (liftP .) Proxy transformers automatically derive how to lift composition correctly and also guarantee that the derived composition obeys the category laws if the base composition obeyed the category laws. Since Proxy composition obeys the category laws, any proxy transformer stack built on top of it automatically derives a composition operation that is correct by construction. Let's prove this by directly composing our StateP-extended proxies without unwrapping them: :t client5 <-< server5 :: () -> StateP Int Proxy C () () C IO r However, we still have to unwrap the final StateP Session before we can pass it to runProxy. We use runStateK for this purpose: >>> runProxy $ runStateK 0 $ client5 <-< server5Client: 0 Server: 0 Client: 1 Server: 1 Client: 2 Server: 2 Client: 3 Server: 3 ... Keep in mind that runStateK takes the initial state as its first argument, unlike runStateT. I break from the transformers convention for syntactic convenience. We can similarly fix our EitherT example, using EitherP from Control.Proxy.Trans.Either: import Control.Proxy.Trans.Either as E client6 :: () -> EitherP String Proxy () () () C IO () client6 () = forM_ [1..] $ \i -> do liftP $ lift $ print i liftP $ request () server6 :: () -> EitherP String Proxy C () () () IO () server6 () = (forever $ do liftP $ respond () E.throw "Error" ) `E.catch` (\str -> do liftP $ lift $ putStrLn $ "Caught: " ++ str server6 () ) >>> runProxy $ runEitherK $ client6 <-< server61 Caught: Error 2 Caught: Error 3 Caught: Error ... Compatibility Proxy transformers do more than just lift composition. They automatically promote proxies written in the base monad. For example, what if I wanted to use the takeB_ proxy from Control.Proxy.Prelude.Base to cap the number of results? I can't compose it directly because it uses the Proxy type: takeB_ :: (Monad m) => Int -> a' -> Proxy a' a a' a m () ... whereas client6 and server6 use EitherP String Proxy. However, this doesn't matter because we can automatically lift takeB_ to be compatible with them using mapP: >>> runProxy $ runEitherK $ client6 <-< mapP (takeB_ 2) <-< server61 Caught: Error 2 Caught:Error mapP promotes any proxy written using the base proxy type to automatically be compatible with proxies written using the extended proxy type. This means you can safely write utility proxies using the smallest feature set they require and promote them as necessary to work with more extended feature sets. This ensures that any proxies you write always remain forwards-compatible as people write new extensions. Proxy Transformer Stacks You can stack proxy transformers to combine their effects, such as in the following example, which combines everything we've used so far: client7 :: () -> EitherP String (StateP Int Proxy) () Int () C IO r client7 () = do n <- liftP get liftP $ liftP $ lift $ print n n' <- liftP $ liftP $ request () liftP $ put n' E.throw "ERROR" >>> runProxy $ runStateK 0 $ runEitherK $ client7 <-< mapP (mapP (enumFromS 1))0 (Left "Error", 1) But that's still not the full story! For calls to the base monad (i.e. IO in this case), you don't need to precede them with all those liftPs. Every proxy transformer also correctly derives MonadTrans, so you can dig straight to the base monad by just calling lift at the outer-most level: client7 :: () -> EitherP String (StateP Int Proxy) () Int () C IO r client7 () = do n <- liftP get lift $ print n -- Much better! n' <- liftP $ liftP $ request () liftP $ put n' E.throw "ERROR" Also, you can combine multiple proxy transformers into a single proxy transformer, just like you would with monad transformers: newtype BothP e s p a' a b' b m r = BothP { unBothP :: EitherP e (StateP s p) a' a b' b m r } deriving (Functor, Applicative, Monad, MonadTrans, Channel) instance ProxyTrans (BothP e s) where liftP = BothP . liftP . liftP runBoth :: (Monad m) => s -> (b' -> BothP e s p a' a b' b m r) -> (b' -> p a' a b' b m (Either e r, s)) runBoth s = runStateK s . runEitherK . fmap unBothP get' :: (Monad (p a' a b' b m), Channel p) => BothP e s p a' a b' b m s get' = BothP $ liftP get put' :: (Monad (p a' a b' b m), Channel p) => s -> BothP e s p a' a b' b m () put' x = BothP $ liftP $ put x throw' :: (Monad (p a' a b' b m), Channel p) => e -> BothP e s p a' a b' b m r throw' e = BothP $ E.throw e Then we can write proxies using this new proxy transformer of ours: client8 :: () -> BothP String Int Proxy () Int () C IO r client8 () = do n <- get' lift $ print n n' <- liftP $ request () put' n' throw' "ERROR" >>> runProxy $ runBoth 0 $ client8 <-< mapP (enumFromS 1)0 (Left "ERROR",1) Note that request and respond are not automatically liftable, because of technical limitations with Haskell type classes. When I resolve these issues they will also be automatically promoted by proxy transformers. For now, you must lift them manually using liftP: request = (liftP .) request respond = (liftP .) respond The left request and respond in the above equations are what the lifted definitions would be for each proxy transformer if Haskell's type class system didn't get in my way.
http://hackage.haskell.org/package/pipes-2.4.0/docs/Control-Proxy-Trans-Tutorial.html
CC-MAIN-2013-48
refinedweb
1,887
58.21
Cross building and debugging C/C++ libraries for the Raspberry PI The Raspberry PI is an amazing mini computer, powerful and cheap, the dream of hobbyists and developers around the world. With its potential to implement embedded systems, it is common to use C/C++ for developing its code, specially when efficiency and performance is relevant. However, even if it is a powerful system for the money, it can be slow while building relatively large C/C++ libraries, so cross-building can be very convenient for developers. This post will describe how to setup cross building to the Raspberry PI from Windows (from Linux it is also possible, and the configuration would be very similar). A library will be cross-built, a conan package will be uploaded to a server (can be a conan_server, conan.io, or Artifactory), and then such library will be installed and used from the Raspberry PI, i.e. we will build an app and link it against this cross-built library. As bonus points, this post will also explain how to bundle the source code in the package itself, so later the library can be debugged from the Raspberry PI. Hello world library The library that will be built and packaged is the one existing in this github repo. It is just a simple C++ “Hello world” library project, using CMake, and nothing special or conan related in it. We will then start with a package template created with the conan new command: $ conan new Hello/0.1@user/testing -t # use your own user Now, lets just replace the root conanfile.py with this one: from conans import ConanFile, CMake import os class HelloConan(ConanFile): name = "Hello" version = "0.1" settings = "os", "compiler", "build_type", "arch" def source(self): self.run("git clone") def build(self): cmake = CMake(self.settings) gcc_dbg_src = "" if self.settings.compiler == "gcc" and self.settings.build_type == "Debug": gcc_dbg_src = ' -DCMAKE_CXX_FLAGS="-fdebug-prefix-map=%s/hello=src"' % os.getcwd() self.run('cmake hello %s %s' % (cmake.command_line, gcc_dbg_src)) self.run("cmake --build . %s" % cmake.build_config) def package(self): self.copy("*.h", dst="include", src="hello") if self.settings.compiler == "gcc" and self.settings.build_type == "Debug": self.copy("*.cpp", dst="src", src="hello") self.copy("*.lib", dst="lib", keep_path=False) self.copy("*.a", dst="lib", keep_path=False) def package_info(self): self.cpp_info.libs = ["hello"] It is very similar to the one created by the template, but with two minor differences. First, as we want to be able to debug the packages in the Raspberry PI, it is necessary to define the gcc flag debug-prefix-map, so it points to the relative source folder src instead of the original one. Because we are going to debug in a different machine, where the original absolute source path will make no sense. Se we just define the flag to CMake (conditionally for the gcc and Debug settings): if self.settings.compiler == "gcc" and self.settings.build_type == "Debug": gcc_dbg_src = ' -DCMAKE_CXX_FLAGS="-fdebug-prefix-map=%s/hello=src"' % os.getcwd() Then, we just copy the sources *.cpp to the final package (only for the same settings too.) if self.settings.compiler == "gcc" and self.settings.build_type == "Debug": self.copy("*.cpp", dst="src", src="hello") This package recipe could be tested natively, by just running: $ conan test_package Hello world! Setting the cross-build toolchain For this example, we are going to use the SysProg toolchain. We are using the 4.6.3 toolchain, with complete sysroot, which is very convenient. We download the tool, install it in C:\SysGCC\Raspberry and add C:/SysGCC/Raspberry/bin/ to the system PATH. Now we could just specify cross compilers to the conan command as arguments, like conan test_package -e CXX=some_gcc_compiler, but we can make it easier using a conan profile. So we create a file in <userhome>/.conan/profiles/rpi_gcc46 with the following: [settings] os: Linux compiler: gcc compiler.version: 4.6 compiler.libcxx: libstdc++ build_type: Debug arch: armv6 [env] CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ Note the armv6 architecture and Linux settings, need to be defined, because the default conan settings will correspond to the Windows development box. As the resulting binary won’t be executable in windows, we change the test_package/conanfile.py so the test() method just checks the existence of the binary: def test(self): if platform.system () != self.settings.os: assert os.path.exists("bin/example") else: self.run(os.sep.join([".", "bin", "example"])) With this configuration, creating a debug package for the R-PI, can be just done with: $ conan test_package -pr=rpi_gcc46 Uploading and installing in the Raspberry PI Once the package has been created locally, it can be uploaded to any conan remote server (conan.io, Artifactory, conan_server): $ conan upload Hello/0.1@user/testing -r=myremote --all In the Raspberry PI side, we will just create a very simple consumer project with an example.cpp file: #include "hello.h" int main(){ hello(); } a CMakeLists.txt script to build it: Project(Consumer) cmake_minimum_required(VERSION 2.8.9) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup() add_executable(example example.cpp) target_link_libraries(example ${CONAN_LIBS}) and the conanfile.txt to install dependencies: [requires] Hello/0.1@diego/testing [generators] cmake [imports] src, *.cpp -> src Note how the the .cpp sources are copied (“imported”) from the package, to the current binary folder, so the debugger can easily locate them. Installing the cross-built “Hello” package is easy, now we don’t need profiles, as the R-PI defaults are good, so we just set the build_type: $ conan install .. -s build_type=Debug Building and debugging Building our R-PI app is now standard cmake process: $ mkdir build && cd build $ cmake .. -DCMAKE_BUILD_TYPE=Debug $ cmake --build . $ bin/example Hello World! The good thing, is that for this example we have built it for Debug, mode, so we can debug the application and step into the package library code: $ gdb bin/example > ... > Reading symbols from /home/pi/consumer/build/bin/example...done. (gdb) start Temporary breakpoint 1 at 0x8914: file /home/pi/consumer/example.cpp, line 4. Starting program: /home/pi/consumer/build/bin/example (gdb) step hello () at src/hello.cpp:5 5 std::cout << "Hello World!\n"; And voilá, we can see the hello.cpp source code line! Conclusions Conan is a pure python app, so installing it in the Raspberry PI was as easy as sudo pip install conan. In this example we have shown how to create packages with debug information for gcc and gdb, but similar approaches can be implemented for other platforms too, for example, packaging the .pdb files of Visual Studio. As conan is very orthogonal to the build system and compiler, cross building packages with conan is straightforward. Profiles are a very convenient feature to gather together settings, options and environment variables, for easy switching between different development environment and targets. When cross-building toolchains are more complicated, things can require a bit more of configuration to take into account the variability of those toolchains, but can be certainly done. We are aware of conan users actively using conan to package for Android and iOS systems. In any case, we are preparing some major improvements for management of build requirements, like the Android toolchain, that you will surely love. Keep tuned, follow us on twitter or subscribe to our release annoucements mailing list!
http://blog.conan.io/2017/03/30/Cross-building-and-debugging-C-C++-libraries-for-the-Raspberry-PI.html
CC-MAIN-2018-09
refinedweb
1,221
50.23
Important: Please read the Qt Code of Conduct - Calling ioctl() under linux - problem Hi, I am using qtcretor under ubuntu 10.10 / 2.6.35 32bit linux - calling a loadable module/driver in a qui application. The simple code fragment is - @....... open(); ioctl(); ... ioctl(); .......@ The driver is open ok, however it seems the call to ioctl() does not do anything - the data buffer is not modified, no data returned. I test this in debug mode - step by step running, checking what is the result. The qtcreator is started in a way of - sudo /.../qtcreator , to be able to open the driver. I did build a similar code fragment with gcc for a command line / terminal app - it works ok, and ioctl() does the job needed, data is returned. I will appreciate feedback - did I miss something, what can the issue be? Thank you, Paul. Please post both code snippets (from your test app and your problem app). The description of the code is not what the code actually does more often than not. Hello Franzk,. I suspect the issue is with qt - for ex. the size of 'int' variable is 64bit, versus normally 32bit in most other programs. Paul. Qt has no influence on the size of integers. I think it is a rather blunt solution to just subtract 0xa0 from your ioctl number, but if it works for you, I'm not to complain :P. - tobias.hunger Moderators last edited by Please do not run Qt Creator as root! Running big applications with plugins and whatnot as root is never a good idea. You can always start your application as root inside creator: Just add a custom executable run configuration and call a script that does the sudo and then starts your application. I would go deeper and try to figure out this issue: I see no reason why g++ should calculate another offset as gcc. Maybe it is a compiler bug or some issue with include files (you did use extern "C", didn't you?). I would be afraid that this workaround will fail after some upgrade of ubuntu (when the root cause is fixed:-). Hello Tobias, If I run qt regularly , not as root, and I run in debug mode to test my app - can I do 'open' of a driver? Normally it fails if run not as root . How do I do this - add a custom executable run configuration and call a script that does the sudo and then starts your application Regarding my fix - once the app is built it will run ok regardless of fixes in ubuntu or qt. I will pay attention if rebuilding the app with fixed ubuntu or qt. Paul. You can also set the permissions for the specific device so that your development user has the necessary rights. This is a much safer approach generally. I find it hard to believe that you have to subtract 0xa0 from your file descriptor in order for the ioctl to work and that it is a bug in ubuntu. Please post your code, preferably your entire project (tarred of course). - tobias.hunger Moderators last edited by Franzk: You are right, this is most likely not a bug in ubuntu. I just wanted to point out that this will come back to bite paa123456 sooner or later if not properly investigated. And nobody thinks about some brave users who will crash their files by using this program. It is scary that such software will be out in the wild! I was actually kind of hoping the program wouldn't be released into the wild like that. Hi , I wrote -. Here is the simplified code - @ #include <stdio.h> #include <fcntl.h> /* open / #include <unistd.h> / exit / #include <sys/ioctl.h> / ioctl */ #include <pthread.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/syscall.h> #include <sys/utsname.h> #define BYTE unsigned char #define WORD unsigned short #define DWORD unsigned int #define TRUE 1 #define FALSE 0 #define FILE_DEVICE_UNKNOWN #define METHOD_BUFFERED #define FILE_ANY_ACCESS #define CTL_CODE(a, b,c, d) _IOWR(0, b, int) // !!! linux specific |0x4000 // usl related #define ARS_IOCTL_INDEX 0x000 #define IOCTL_ARS_IO_INP CTL_CODE(FILE_DEVICE_UNKNOWN, ARS_IOCTL_INDEX + 0x2b, METHOD_BUFFERED, FILE_ANY_ACCESS) int main () { DWORD dw; // void *drvadr; dw = IOCTL_ARS_IO_INP; printf("\n IOCTL_ARS_IO_INP = %x\n", dw); return 0; } @ You can - - save it as file and build it with gcc - make a simple qtcreator app and include code Paul. [edit: code highlighted / Denis Kormalev] Did you try to compile this yourself? Some copy issue that was. Both gcc and g++ give the same result for me. (Gentoo, gcc 4.5.2) - DenisKormalev last edited by paa123456, please use @ to highlight code
https://forum.qt.io/topic/5303/calling-ioctl-under-linux-problem/1
CC-MAIN-2021-31
refinedweb
777
74.19
TORONTO--(BUSINESS WIRE)--It’s tax time again. If you owe tax, you must file your 2013 tax return before midnight on April 30, 2014 or risk unnecessary penalties. That means that now is the time to look into ways to lighten your tax burden. “Nobody wants to pay more than they have to in taxes. Take some time to learn about the tax savings opportunities available to you before you file your taxes this year,” says Keith MacIntyre, national tax leader for the accounting firm Grant Thornton LLP. To help you out, Grant Thornton has shared a dozen tips that might help you save money this year, as well as some other tax matters you should be aware of: File your tax return and pay your taxes on time: To avoid interest and penalties, any income tax you owe should be paid by no later than April 30. If you are self-employed, you have until June 15 to file your income tax return, but any taxes owing must still be paid by April 30. Review your tax strategy if you’re getting a refund: Although you may look forward to receiving a tax refund, it’s not always good planning to get one. If you get a refund, it means the government has been holding your money without paying you interest, sometimes for many months. If you’re getting a refund this year, you may be able to apply to the CRA to obtain permission to have your source withholdings reduced. Children’s fitness and arts credits: If you have children under the age of 16 at the beginning of the year, you may claim a tax credit of up to $500 for eligible fitness expenses paid for each of your eligible children. Up to another $500 can be claimed for eligible arts expenses. If you have a disabled child, the age threshold is extended to 18 years and the maximum credit is increased to $1,000. Claiming after-school programs as child care: After-school programs for your child can qualify as an eligible childcare expense if it allows you to work. For example, if you would need to arrange care for your daughter if she wasn’t in an after-school gymnastics program, this may be claimed as a childcare expense. A program that qualifies for the children's fitness or arts tax credit can be eligible for the child care expense deduction. However, you can’t claim a childcare expense and a fitness or arts credit for the same payment. You must first claim the allowable amount for purposes of the child care expenses deduction, and then any remaining balance may be used for the children's fitness or arts credit. Maximize tax credits for charitable donations: For 2013, the federal credit is 15% on the first $200 of donations, and 29% on the rest. If you and your spouse1 collectively donated more than $200 last year, the tax credit will be larger if only one of you claims the entire amount. There is now also a new “super credit” for first-time donors. If you and your spouse have not claimed any charitable donations since 2008, you are eligible to claim this credit which provides for an additional 25% tax credit on up to $1,000 of donations. This new super credit can only be claimed once in the 2013 to 2017 tax years. Include any medical expenses you pay for dependants other than your spouse or minor child: If you pay medical expenses for certain related persons who are dependent on you for support at any time in the year, don’t forget to include these amounts on your tax return. This can include amounts you pay for an adult child, grandchild, parent, grandparent, brother, sister, uncle, aunt, niece or nephew of you or your spouse. Medical expenses paid for such relatives must first be reduced by 3% of that dependant’s net income, to a maximum of $2,152 in 2013. Claim capital losses to offset capital gains realized in the past three years: If you realized a capital loss in the current year in excess of current year capital gains, check to see if you reported a capital gain in any of the three previous years. Capital losses can be carried back for up to three tax years and forward indefinitely. Don’t forget about pension income splitting: If you’re receiving certain pension income, you’ll be able to allocate up to half of that income to your spouse. To qualify for pension income splitting, the pension income must satisfy certain criteria. For example, although it includes lifetime annuity payments under a registered pension plan, it doesn’t include payments under the Canada Pension Plan (CPP) or Old Age Security (OAS) payments. About to turn 65? Consider if you should defer receiving your OAS benefit: You can now voluntarily defer receipt of your OAS for up to 5 years. This will allow for a higher, actuarially adjusted, annual pension when you finally do start to receive it. This strategy may be beneficial if your income is at a level that would otherwise subject you to the full OAS clawback (just under $115,000). Employed or self-employed and already collecting CPP benefits? Consider if you can opt out of the requirement to pay CPP premiums: If you are under age 65, you have to pay CPP premiums on your employment or self-employment income even if you are already collecting CPP benefits. However, if you’re between the ages of 65 and 70 and self-employed, you can opt out by completing the “Election to stop contributing to the Canada Pension Plan”, which is included on Schedule 8 of your personal tax return. Employees who want to opt out must complete Form CPT30 and provide a copy of the form to each of their employers. The original must be sent to the CRA. Don’t forget your foreign reporting requirements: If you’re a resident of Canada, you must declare your income from all sources—Canadian and foreign. In addition, if the total cost of your specified foreign property exceeds CAN$100,000 at any time in 2013, you have to report certain information about your foreign investments on your tax return (Form T1135). The rules are complex and there can be significant penalties for failing to file the form or include complete information. Be aware of your US tax obligations if you’re a US citizen or green card holder: If you’re a US citizen or green card holder living in another country, you continue to be subject to US income and estate tax laws. As well as being required to file an annual US tax return, there are other US financial reporting requirements—and significant penalties for failing to comply. For more great tax tips for individuals—as well as businesses—Grant Thornton is offering a free downloadable Tax Planning Guide on their website. It also includes tips for businesses and investors. Grant Thornton LLP also has tax experts across the country available to speak with media this tax season. Any reference to “spouse” also includes a common-law partner.
http://www.businesswire.com/news/home/20140407006225/en/Grant-Thornton-Shares-Dozen-Tax-Tips-Preparing
CC-MAIN-2014-41
refinedweb
1,203
55.88
A python script called hello.py is created as follows: import cherrypy class HelloWorld: def index(self): return "Hello world!" index.exposed = True cherrypy.quickstart(HelloWorld()) The application can be started at the command prompt by typing $ python hello.py At the web browser, “Hello World” can be seen when it is directed to. import cherrypy // imports the main CherryPy module class HelloWorld: //declare a class named HelloWorld def index(self): // contains a single method called index which will be called when the root URL for the site is requested () return “Hello world!” // return the contents of the web page (“Hello world!” string) index.exposed = True // to tell CherryPy that index() method will be exposed and only exposed methods can be called to answer a request. This allows user to select which methods will be accessible via the web. cherrypy.quickstart(HelloWorld()) // mounts an instance of the HelloWorld class and starts the embedded webserver. It will run until explicitly interrupted. When the web application is executed, the CherryPy server will listen on localhost at port 8080. The default configuration of CherryPy server can be overridden by using another configuration file or dictionary. When it receives the request for the URL, it searches for the best method to handle the request, starting from the first instance (HelloWorld). The root of the site is automatically mapped to the index() method. The HelloWorld class defines an index() method and exposes it (@cherrypy.expose). Therefore CherryPy will call HelloWorld().index() and the result of the call is returned to the browser as the contents of the index page for the website. In order for CherryPy to call a page handler, it has to identify which and where to call for a given Uniform Resource Identifier (URI). A Dispatcher object is used to understand the arrangement of handlers and to find the appropriate page handler function. The arrangement of CherryPy handler by default is a tree which enables the config to be attached to a node in the tree and cascade down to all children of that node. The mapping of URI to handlers is not always 1:1 and thus it offers more flexibilities.
https://yvonnezoe.wordpress.com/tag/cherrypy/
CC-MAIN-2018-47
refinedweb
360
63.9