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
|
|---|---|---|---|---|---|
Getting.
1. Introduction to Xamarin
Xamarin is a cross-platform tool that helps building of Android and iOS apps using C# as the language of coding. Xamarin opens up a way for C# programmers to build Android and iOS apps. Xamarin includes Xamarin.iOS for iOS app development and Xamarin.Android for Android app development.
Figure 1: Divisions of Xamarin.
2. iOS app development using Xamarin
Figure 2: Depicting the two IDEs available for Xamarin.iOS app development.
Developing iPhone, iPad, iPod and Mac apps have been made possible using XCode IDE and using Objective-C, from a long time. Building iOS applications i.e. applications for iPhones and iPads using C# language on .NET platform can be made possible by making use of Xamarin.iOS. The only key entity in building iOS apps using Xcode is the use of Objective-C as the language to develop these iOS apps. Currently, C# developers who are interested in iOS development don't have to learn Objective-C to develop iOS apps. They are only required to know the basic concepts of Xamarin.iOS. Xamarin.iOS is a part of Xamarin. Xamarin is a cross-platform mobile application development software which aids in building iOS, Android and Windows apps using C# .NET platform. Xamarin provides Xamarin Studio and Xamarin plugin to Visual Studio to develop applications.
Developing iOS apps using Xamarin.iOS on different platforms
In order to deploy the developed iOS app on iOS devices or to submit it to the app store, you need an Apple Developer Account. Deploying and debugging an iOS app requires generating the development certificate and creating the provision profile for the particular device in which the app will be deployed to. Provisioning is nothing but configuring the app to run on devices. Here, while creating provision profile, you will set the devices that can run your iOS app. Here, you need to provide them with the generated .ipa file.
1. Development in Windows environment
Always remember that we don't have an iOS simulator available for Windows. The iOS simulator works only on Mac OSX and therefore it is a mandate to have a Mac for testing and simulations of apps on a Mac screen using iOS simulator. Therefore, though we are developing iOS apps on Windows, we need a Mac for development. However Mac need not necessarily be placed beside you! You need a Mac on your network (i.e. Network to which your Windows machine is connected to) and you should able to connect to Xamarin Build Host present on the Mac by connecting to the Mac (Assuming that Xamarin development tools and iOS development tools are already installed on the Mac).
If you are planning to develop iOS apps using Xamarin.iOS in Windows environment, then, you have two choices. One is to use Xamarin plugin with Visual Studio and writing the C# programs in Visual Studio IDE to build your iOS apps using Xamarin library. If you are intended to develop Xamarin.iOS application using Visual Studio, then, see to it that you use Visual Studio 2010 or higher versions. Also see to it that you don't use Visual Studio Express edition. Another option is to have Xamarin Studio installed on Windows to develop Xamarin.iOS applications. However, both these options require a Xamarin.iOS Build Host. This Xamarin.iOS Build Host should be installed and setup on the Mac machine. In fact, this certifies that though we don't use the Mac directly to write the code in it, we need a Mac machine for iOS development using Xamarin. We cannot deploy iOS applications without Apple's certificates and the iOS simulator can only be run on Mac. This dependency has led to the fact that though we don't use Mac directly for coding, we still need to rely on Mac for iOS development. Therefore, in this scenario, Mac only acts as a build host.
Some of the key criteria to discuss before you connect your Windows machine enabled with Xamarin (i.e. Xamarin plug-in to Visual Studio or Xamarin Studio) to the Mac (i.e. Mac with Xamarin Build Host) are listed below:.
2. Development in Mac environment
To build applications using Xamarin.iOS in Mac, you need to have Mac OS 10.8 or above. You need to have iOS SDK with XCode installed on Mac as a prerequisite. In order to build user interfaces, you have to select either Storyboard or XIB. Storyboard file will have .storyboard extension and XIB file will have .xib extension. Storyboard and XIB files are purely UI files where you can drag and drop different controls from the toolbox on top of the View Controller placed in the Storyboard or XIB. The toolbox itself contains different View Controllers. Latest version of iOS SDK and XCode IDE can be downloaded from Apple's App Store.
There are two ways to develop iOS apps using Xamarin.iOS in Mac machines. One method is to use Xamarin Studio directly, and another is to use Visual Studio with Xamarin plug-in passively as illustrated below.
Using Xamarin Studio for iOS app development on Mac is pretty simple. It is just a matter of installing the Xamarin Studio for Mac available and installing other necessary software like iOS SDK, XCode IDE etc. Thereafter, directly using Xamarin Studio to develop iOS applications is made possible.
If you are using Visual Studio with Xamarin plug-in for Xamarin.iOS development and you are intended to use the same on Mac machine, then, it's a mandate to install the virtual machine (VM) software for Mac and then install Windows within this Virtual Machine created out of VM software. Thereafter, you can install all the tools including Visual Studio and Xamarin plug-in into the Windows operating system present inside the Virtual Machine. You must have to install the Xamarin.iOS development tools including Xamarin Studio, and other tools like iOS SDK and XCode IDE into the Mac. Setting up the Xamarin.iOS Build Host on the Mac is necessary as the Xamarin plug-in to Visual Studio communicates with Xamarin.iOS Build Host during the build phase of the Xamarin.iOS application..
JIT is Just In Time compiler and AOT is Ahead of Time compiler. Commanding Mono runtime to generate AOT code is possible as AOT is a part of Mono runtime. MonoTouch (which is based on Mono) aids C# developers to create iOS applications using C# language. Remember that MonoTouch deals only with iOS and Mono for Android deals with Android. MonoTouch SDK which is a part of Mono empowers the development of iOS devices including iPhones, iPads, iPods etc. A C# binding to native iOS APIs is nothing but monotouch.dll, which is a part of MonoTouch.
iOS developer library provides Foundation Framework. This Foundation Framework is written in Objective-C as Objective-C classes. Apple's Foundation Framework classes include classes each of which target more functionality such as Object Creation and Disposal, OS services, Data Storage, Texts and Strings, Date and Time etc. All these functionalities are either individual classes or group of classes, which fall under the Foundation Framework. Apple's Foundation Framework offers a root class named "NSObject" class. Along with this, the Foundation framework also offers other group/individual classes that come under this NSObject. As I mentioned before, we have groups of classes or individual classes to perform all the functionalities specified previously. MonoTouch.Foundation mocks Apple's Foundation Framework. The NSObject of Apple's Foundation Framework (In Objective-C) could be utilized into Xamarin.iOS base C# application by utilizing MonoTouch.Foundation.NSObject. Even though we use Objective-C's Foundation Framework functionalities by means of utilizing MonoTouch.Foundation namespace, when it comes to the matter of using data types such as arrays and strings, the namespace (MonoTouch.Foundation) automatically maps to basic .NET types (i.e. arrays and strings in .NET) instead of mapping to the data types of Objective-C's Foundation Framework.
After reading the above paragraph with certain set of facts, we shouldn't consider Xamarin.iOS as just a binding to Objective-C because it mixes C# and Objective-C and extends .NET runtime to bind C# objects to Objective-C objects. A typical scenario is when we don't use NSString provided by NSObject in C# while working with Xamarin.iOS. Rather, we would use C# "string" type. Probably this is the best example which certifies the fact that Xamarin.iOS is not just binding to Objective-C library. Rather, it mixes both Objective-C and C#.
|
https://www.dotnetspider.com/resources/45965-Getting-started-with-iOS-development-using-Visual-Studio.aspx
|
CC-MAIN-2019-30
|
refinedweb
| 1,436
| 57.87
|
Returns the name of the Scene that is currently active in the game or app.
The Scene.name returns a run-time, read-only, string value. The name limits to 244 characters. The Scene name defaults to
scene. The user changes the name during game creation.
The following script example changes the Scene depending on GUI.Button clicks and the name of the Scene. To make this example work:
1. Create a Project with two Scenes,
scene1 and
scene2.
2. Attach the script below to a GameObject added to
scene1.
3. Attach the same script to a GameObject added to
scene2.
4. Click on the GameObject and go to the Inspector.
5. In the
My First Scene field and
My Second Scene fields, enter the names of the Scenes you would like to switch between,
scene1 and
scene2.
6. Select
scene1 by double-clicking it in the Project, and press
Play. The
scene1 scene will appear.
7. Click the
Load Next Scene button and
scene2 will be loaded.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class Example : MonoBehaviour { // These are the Scene names. Make sure to set them in the Inspector window. public string myFirstScene, mySecondScene;
private string nextButton = "Load Next Scene"; private string nextScene; private static bool created = false;
private Rect buttonRect; private int width, height;
void Awake() { Debug.Log("Awake:" + SceneManager.GetActiveScene().name);
// Ensure the script is not deleted while loading. if (!created) { DontDestroyOnLoad(this.gameObject); created = true; } else { Destroy(this.gameObject); }
// Specify the items for each scene. Camera.main.clearFlags = CameraClearFlags.SolidColor; width = Screen.width; height = Screen.height; buttonRect = new Rect(width / 8, height / 3, 3 * width / 4, height / 3); }
void OnGUI() { // Return the current Active Scene in order to get the current Scene name. Scene scene = SceneManager.GetActiveScene();
// Check if the name of the current Active Scene is your first Scene. if (scene.name == myFirstScene) { nextButton = "Load Next Scene"; nextScene = mySecondScene; } else { nextButton = "Load Previous Scene"; nextScene = myFirstScene; }
// Display the button used to swap scenes. GUIStyle buttonStyle = new GUIStyle(GUI.skin.GetStyle("button")); buttonStyle.alignment = TextAnchor.MiddleCenter; buttonStyle.fontSize = 12 * (width / 200);
if (GUI.Button(buttonRect, nextButton, buttonStyle)) { SceneManager.LoadScene(nextScene); } } }
The following example using two scenes, and one of them has a long Scene name with 244 digits. The other is called
testScene. To make this example work:
1. Create a new Project.
2. Change the name of the default scene to
testScene by selecting it and then use Assets->Rename.
3. Next, create a second scene and again select it and use Asset->Rename. Use the name as shown below. (This is the 244 character name "0123456789...0123").
4. Create a C# Script and call it
Example.cs.
5. Add the following script text to
Example.cs.
6. Next add an empty GameObject called
GameObject to each of the two scenes.
7. Finally copy
Example.cs to each of the two GameObjects.
Use the
Game button to launch the
testScene scene. A GUI Button is shown which allows the scenes to swap.
using UnityEngine; using UnityEngine.SceneManagement;
// SceneManagement.SceneManager-name example
public class Example : MonoBehaviour { private Scene scene;
void Start() { scene = SceneManager.GetActiveScene(); Debug.Log("Name: " + scene.name); }
void OnGUI() { if (GUI.Button(new Rect(10, 10, 150, 100), "Change Scene")) { if (scene.name == "testScene") { // The scene to load has a 244 characters name. SceneManager.LoadScene("01"); } else { SceneManager.LoadScene("testScene"); } } } }
|
https://docs.unity3d.com/kr/2019.2/ScriptReference/SceneManagement.Scene-name.html
|
CC-MAIN-2020-50
|
refinedweb
| 563
| 61.93
|
Building a Python monorepo for fast, reliable development
Suman Karumuri | Pinterest technical lead, Visibility & Ruth Grace Wong | Pinterest engineer, Core Site Reliability
More than 200 million people discover and do what they love on Pinterest every month. We rely on several hundred Python services and tools to power these experiences. The code for these services lives in 100+ Git repositories (except for our Python frontend monolith). Overtime, we found that developing Python applications across a growing number of repos was causing friction and slowing down our developers. We built Python commons to provide a seamless experience for our Python developers. In this post, we’ll share a few challenges we encountered managing Python code at scale, and how Python commons provides a fast and reliable code development environment.
Challenges managing Python code at scale
While Python tools work great for managing code in a single repo, the tools aren’t designed for managing code across repos. Even in a single repo, there’s a steep learning curve to correctly set up and use tools and utilities, like requirements, setup.py and tox for a reproducible build and test environment. Given the complexity involved, few developers take the time to do it right. Below, we’ll explain a few issues our developers face when building, testing and deploying Python code across 100+ repos.
Managing virtual environments: Each Python project has its own virtualenv, and the developer needs to be mindful of using the correct virtualenv while working in a project and branch. Using the wrong virtualenv leads to hard-to-trace errors in the development, build and deploy process.
Running unit tests with tox: For test integrity, developers are advised to run their tests in a virtualenv using tox. Given the complexity of managing virtual envs and setting up tox correctly, few projects do this in practice. (Some developers skip writing unit tests entirely.)
Package pinning: If packages aren’t pinned to specific versions they might break in production when their dependencies are upgraded. Even if each repo pinned the version of their packages, reusing code across repos leads to conflicting package versions and breaks the package during deployment.
Deploying security fixes: Upgrading packages to fix a security issue across hundreds of repos is a hard, boring and tedious process.
Pip install: Most of our developers deploy Python packages using
pip install. In practice, we found pip install isn’t a robust deployment mechanism for the following reasons:
- Pip install isn’t atomic. A failed pip install may leave some packages upgraded and others an old version. This occasionally causes deployment outages.
- Pip can fail silently on production machines which leads to production outages.
- Pip’s command line options are inconsistent across minor version changes, which can cause a pip install to fail when pip is upgraded along with new OS versions.
- Pip downloads each dependency recursively. While this is harmless at small scale, doing it across tens of thousands of machines several times every day is inefficient.
- Pip install wasn’t ideal for deploying internal tools because inconsistent dev environments was becoming hard to support. Most tools came with custom scripts that setup virtual envs and deployed the tool there. While this worked, it was a tedious and error-prone process.
Consistent development environment: Since developers set up their own repo, over time there’s little consistency in development, build, test and deployment setups. Several projects didn’t have continuous integration setup for their build process while coding conventions and quality varied across repos. Even minor issues, like failing to correctly namespace a package, led to namespace clobbering issues when the code was reused resulting in complicated workarounds. This additional complexity discouraged code reuse across the repos.
Our takeaway is the standard Python toolchain needs a lot of work upfront to create a consistent and reproducible build environment in a single repo. Even if we set up the tooling carefully, the standard tools can’t ensure a consistent build and deploy pipeline across repos.
Python commons
We had one primary goal as we designed our new solution — we wanted it to be easy to do the right thing while enabling developers to quickly ship code. So we built a monorepo called Python Commons using Pants build tool. To streamline our release process, we use a Python EXecutable(PEX) file as our release primitive.
Python commons monorepo
The first decision was to start using a monorepo for all our tool’s code. This provides a single place for all code and allows us to enforce healthy development practices over a multi-repo solution. A consistent development, build and test environment also encourages modular code and code reuse. A monorepo is a more natural workflow for us since we have several language-specific monorepos, and it’s common for several tools share the same repo.
Since we already have a Python monorepo for our frontend application code, our first instinct was to move the tool’s code into that repo to create a single repo for all Python code. However, that didn’t work, because the development workflow was heavily customized for building our monolithic Python web frontend. So, we decided to build a separate monorepo called “Python commons” for our tools and services.
Pants
While deciding on the monorepo was easy, the hard part was setting up a development workflow suitable for a wide-range of Python applications, from web apps to services, libraries and command line tools. To make managing and using the monorepo easier, we use Pants as our build tool. Pants helps enforce a uniform development workflow for building, testing and packaging apps while keeping our configuration DRY.
The code layout we used in the repo provides a consistent development workflow for every project in the repo.
- The folder structure shown in Figure 1 ensures source and tests are separated, and all internal code is in the Pinterest namespace. This separation safeguards us from shipping tests or their dependencies into production.
- Pants comes with a built-in Python linter that enforces code style for the repo.
- Standard build targets provide an intuitive and consistent development workflow to build, test, run and release packages (as shown in Figure 4).
- The pants repl option provides an interactive repl to play with the code.
- Pants creates a virtualenv for every run based on the dependencies in the BUILD file. If the dependencies change between Git branches, developers don’t have to switch virtualenvs to make sure their code works correctly making virtual env management seamless.
- Since tests are run in a virtualenv, developers don’t have to learn or use tox.
- Pants test target automatically creates a test runner, so there’s no need for a separate script to run tests.
Pants simplifies dependency management across projects using repo and version pinning.
- Pants controls which external repos we download our packages from. When our access to PyPi repo was blocked, we pointed the repo to an internal mirror with a one line configuration change to the pants.ini file.
- We use the same set of pinned dependencies for the entire repo (as shown in Figure 2). This is the only place in the repo for defining our external dependencies and simplifies our dependency management. Pants builds a virtual environment for every build, so any dependency conflicts are detected right away.
- A single place for pinned dependencies allows us to upgrade the package for all the projects in the repo at once. This greatly simplifies doing security audits and package version upgrades.
By enabling fast reproducible builds, Pants simplifies build and release management.
- Pants run target in a BUILD file can be used for running the program locally, eliminating the need for scripts.
- Pants provides fast, reproducible builds for our packages. Pants performs incremental builds on its targets, so only changed modules are rebuilt which speeds up the build process. Running all the build targets in a virtual envs ensures builds are reproducible.
- Pants python_library target can include a setup.py definition (as shown in Figure 3). By using this target, developers don’t have to learn setup.py to publish Python eggs.
- Pants binary target generates a standalone pex binary for the project.
PEX
A monorepo with pants streamlined our development and test process. We observed our developers preferred their own repos, because it offers them control over the distribution of their code as a Debian package, Docker container, Python egg or script. To cater to these use cases and streamline our package release and deployment process, we needed a mechanism to easily export packages into various formats. Exporting an egg was easy since Pants natively supports it. To package our code into other formats, we used PEX as a basic packaging primitive for our code. A PEX is a self-contained, cross-platform, Python executable format with packaged dependencies, so it only needs a Python interpreter on the machine it’s running on. A PEX can be packaged into a Debian package, Docker container or uploaded to S3. The last deployment option is great for shipping internal tools, which are hardest to deploy and manage.
Our multi-format package release process is powered by a Jenkins script (as shown in Figure 5). It uses the project name and release type to generate the necessary files (Dockerfile, Debian package, Python egg, PEX binary) and makes the build available for deploy by uploading them to their respective repos. The release process not only relieves our developers of understanding Docker, Debian package management or Python egg format, but it also enforces best hygienic and secure package management practices.
Conclusion
Using this development setup we take care of all the boilerplate code a developer writes before working on a project. This helps our developers focus on code without having to worry about setup.py, tox, virtualenv. It also eliminates the need to create scripts to setup and run the project locally, scripts to release a Docker or Debian packages or scripts to test code locally or in Jenkins. We rolled out Python commons almost a year ago and have already migrated 35 projects to it.
Acknowledgements: We’d like to thank Evan Jones, Yongwen Xu and Nick Zheng for their help and feedback on the project. We’d also like to thank the pants community for their support.
|
https://medium.com/pinterest-engineering/building-a-python-monorepo-for-fast-reliable-development-be763781f67?source=rss-ef81ef829bcb------2
|
CC-MAIN-2022-05
|
refinedweb
| 1,714
| 53.61
|
[SOLVED] Install QtQuick3D for Qt 5.2 in Windows?
I've read that Qt3D and QtQuick3D is not supported for Qt 5.x yet, but was wondering if there's a way to install it and experiment with it. Is there?
Thanks sierdzio.
Seems mine and your last reply got erased after some technical difficulties with qt-project.org.
I tried following the instructions at "qt-project.org/wiki/Qt3D-Installation":, but I get an error at the step that says “Build the project in Release mode.” of Option 1. I’m pressing Ctrl+B to build Qt3D.
The error I get is:
bq. Failed to run: perl -w C:\Qt\5.2.0\mingw48_32\bin\syncqt.pl -module Qt3D -version 5.3.0 -outdir C:/Users/trusktr/src/build-qt3d-Desktop_Qt_5_2_0_MinGW_32bit-Release C:/Users/trusktr/src/qt3d
I’ve installed Strawberry Perl for Windows and it works in cmd.
You told me to try qmake /path/to/qt3d.pro as in Option 2. So I did this:
@C:\Users\trusktr\src\qt3d>qmake qt3d.pro
Info: creating cache file C:/Users/trusktr/src/qt3d/.qmake.cache
C:\Users\trusktr\src\qt3d>@
What do I do after that?
You need to run make:
@
make -j 5
@
Since you are using MinGW, it will be called something like "mingw32-make" or similar. The number after "j" denotes a number of concurrent build jobs that you allow "make" to conduct (it's usually ok to pass the number of cores ini your CPU here).
aaaah, thanks. I thought I had to make, but "make" command was not found. I come from Linux, so Windows is awkward.
Haha, I know exactly what you mean, I'm using mostly Linux, too. But since the rest of the world wants Windows and Mac packages, we need to visit the other OSes sometimes :)
Exactly! :)
So,After running make for a while, I got this error:
@./.obj\release\qglcolladafxeffectfactory.o: file not recognized: File truncated
collect2.exe: error: ld returned 1 exit status
Makefile.Release:524: recipe for target '....\lib\Qt53D.dll' failed
mingw32-make[3]: *** [....\lib\Qt53D.dll] Error 1
mingw32-make[3]: Leaving directory 'C:/Users/trusktr/src/qt3d/src/threed'
Makefile:38: recipe for target 'release-all' failed
mingw32-make[2]: *** [release-all] Error 2
mingw32-make[2]: Leaving directory 'C:/Users/trusktr/src/qt3d/src/threed'
Makefile:40: recipe for target 'sub-threed-make_first-ordered' failed
mingw32-make[1]: *** [sub-threed-make_first-ordered] Error 2
mingw32-make[1]: Leaving directory 'C:/Users/trusktr/src/qt3d/src'
makefile:43: recipe for target 'sub-src-make_first' failed
mingw32-make: *** [sub-src-make_first] Error 2@
Any idea why this might happen?
Sweet! I had to remove the object.o files because I'd interrupted a previous make process, so they were truncated/incomplete. It worked:
@mingw32-make -j 3 install@
Now when I try running the "cubehouse" example, it says
@module "Qt3D" version 1.0 is not installed@
The QML files contain
@import Qt3D 1.0
import Qt3D.Shapes 1.0@
How might I determine if I've actually installed it? Or do I need to change the "1.0" to something else?
EDIT 12:33pm: Nevermind! I had to change them to
@import Qt3D 2.0
import Qt3D.Shapes 2.0@
and that problem is gone. Now assuming that the stock cubehouse example included with Qt Creator in Qt 5.2 was written for Qt3D 1.0, this is why I have new problems... But at least I know Qt3D is installed!
SOLVED
Wow, that was a long journey, for sure :) Congratulations and happy coding.
Oh, and since you are fresh with new experiences, maybe you can update the wiki page you mentioned with your discoveries?
[quote author="sierdzio" date="1389769849"]Wow, that was a long journey, for sure :) Congratulations and happy coding.
Oh, and since you are fresh with new experiences, maybe you can update the wiki page you mentioned with your discoveries?[/quote]
I've updated the wiki. The added steps are for MinGW. Some more details may still be needed for MSVC/VS users.
|
https://forum.qt.io/topic/36571/solved-install-qtquick3d-for-qt-5-2-in-windows
|
CC-MAIN-2017-47
|
refinedweb
| 682
| 61.02
|
Hi guys,
I'm using VS.NET 2003.
I managed to create a XML File .xml, XLST stylesheet .xsl in notepad
to be displayed in my .aspx report.
I will create my .aspx page layout with a panel.
1. I'm not gd with VS.NET but i just installed it, what kind of "new project"
do i create, ASP.NET Web Application or Web Service?
2. How do i add the xml file and xlst sheet i created to this solution?
3. How do i add the data from the xml file using xml control to the .aspx page
4. How do i modify the XML control properties to point to the XML document and XSLT stylesheet.
5. How do i edit my stylesheet or report to make it look better, which controls/settings do i use
help appreciated!
Create an ASP.NET Web application. Put the controls (panel, etc.) you want on the Web form. Use the classes in the System.Xml namespace in the page code to perform your transformation, and assign the resulting output to the appropriate control.
For the look and feel, check out CSS styles. In your transformation, you can assign style classes to the output, and you can build a stylesheet with those styles and include a reference to it in the page.
A. Russell Jones,
Executive Editor,
Internet.
|
https://forums.devx.com/showthread.php?146373-Group-references&s=b78647c01be6b6b8c6cd43ade1d94f3d&goto=nextnewest
|
CC-MAIN-2021-31
|
refinedweb
| 226
| 78.75
|
Topcoder SRM 710
Time: 9:00 pm EST Thursday, March 9, 2017
Calendar:
This round will start in 22 hours!
Will start in 1 hour.
We need CF round :(
oh my god! I am feeling so Stupid! euheuheuh I have no idea about div1 A topcoder! Can anyone explain the DIV1 A solution?
Type-B is reverse of type-A. Do type-A for two sequences to get the same sequence. Example: the first slot get all stones.
me too.but the contest does not end
I was the author for this round. I hope you enjoyed the problems! Here are some short hints to the problems along with the code.
What if there were no magic stones?
What should we do if we take the magic stone?
Take the max of the two cases above.
public class MagicSubset {
public int findBest(int[] values) {
int n = values.length;
int s1 = 0;
for (int i = 1; i < n; i++) s1 += Math.max(0,values[i]);
int s2 = values[0];
for (int i = 1; i < n; i++) s2 += Math.min(0,values[i]);
return Math.max(s1,-s2);
}
}
Choose an arbitrary pile as the "final" pile. What are some strategies to get all the stones in that pile?
Do we have enough moves?
Let's choose pile 0 as our "final" pile. Then, while there exists a non-empty pile that is not pile 0, do a move on that pile. This is guaranteed to terminate in at most (num stones) * (num piles) steps.
import java.util.ArrayList;
import java.util.Arrays;
public class ForwardMancala {
public ArrayList<Integer> find(int[] start) {
ArrayList<Integer> ret = new ArrayList<>();
int n = start.length;
while (true) {
boolean changed = false;
for (int i = 1; i < n; i++) {
if (start[i] > 0) {
changed = true;
int t = i;
int d = start[i];
start[i] = 0;
while (d-->0) {
t = (t+1) % n;
start[t]++;
}
ret.add(i);
}
}
if (!changed) break;
}
return ret;
}
public int[] findMoves(int[] start) {
ArrayList<Integer> ans = find(start);
int[] ret = new int[ans.size()];
for (int i = 0; i < ans.size(); i++)
ret[i] = ans.get(i);
return ret;
}
}
There are two different approaches.
Add the edges in increasing cost.
Fix the largest weight node that we will use. Then, we can do something like Kruskal.
How long does it take to update a single edge? Maybe try amortized analysis also?
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <list>
#include <cassert>
#include <climits>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define FORSZ(i,a,v) FOR(i,a,SZ(v))
#define REPSZ(i,v) REP(i,SZ(v))
typedef long long ll;
class MinMaxMax {
public:
ll findMin(vector<int> a, vector<int> b, vector<int> w, vector<int> v) {
int n=SZ(v),m=SZ(w);
vector<pair<int,int> > ov; REP(i,n) ov.PB(MP(v[i],i)); sort(ov.begin(),ov.end());
vector<pair<int,int> > ow; REP(i,m) ow.PB(MP(w[i],i)); sort(ow.begin(),ow.end());
vector<vector<ll > > d(n,vector<ll>(n,LLONG_MAX));
REP(i,n) {
vector<bool> alive(n,false); REPE(j,i) alive[ov[j].second]=true;
vector<int> comp(n); REP(i,n) comp[i]=i;
REP(j,m) {
int aa=a[ow[j].second],bb=b[ow[j].second];
if(comp[aa]==comp[bb]||!alive[aa]||!alive[bb]) continue;
ll cur=(ll)ov[i].first*ow[j].first;
vector<int> va,vb; REP(k,n) if(comp[k]==comp[aa]) va.PB(k); else if(comp[k]==comp[bb]) vb.PB(k);
REPSZ(ai,va) REPSZ(bi,vb) { int ca=va[ai],cb=vb[bi]; if(cur<d[ca][cb]) d[ca][cb]=cur; if(cur<d[cb][ca]) d[cb][ca]=cur; }
REPSZ(bi,vb) { int cb=vb[bi]; comp[cb]=comp[aa]; }
}
}
ll ret=0; REP(i,n) FOR(j,i+1,n) { assert(d[i][j]!=LLONG_MAX); ret+=d[i][j]; } return ret;
}
};
Add the nodes in increasing cost.
This kind of looks like Floyd Warshall.
Let's change the order that we add nodes in with Floyd Warshall.
import java.util.Arrays;
import java.util.Comparator;
public class MinMaxMax {
static class Pair {
public int a,b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
public long findMin(int[] a, int[] b, int[] w, int[] v) {
int n = v.length, m = a.length;
Pair[] d = new Pair[n];
for (int i = 0; i < n; i++) {
d[i] = new Pair(v[i],i);
}
Arrays.sort(d, Comparator.comparingInt(x -> x.a));
long[][] mn = new long[n][n];
for (long[] x : mn) Arrays.fill(x, 1L << 40);
for (int i = 0; i < m; i++) {
mn[a[i]][b[i]] = mn[b[i]][a[i]] = w[i];
}
long[][] dist = new long[n][n];
for (long[] x : dist) Arrays.fill(x, 1L << 60);
for (int e = 0; e < n; e++) {
int k = d[e].b;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
mn[i][j] = Math.min(mn[i][j], Math.max(mn[i][k],mn[k][j]));
dist[i][j] = Math.min(dist[i][j], 1L * mn[i][j] * Math.max(v[k], Math.max(v[i], v[j])));
}
}
}
long ret = 0;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
ret += dist[i][j];
}
}
return ret;
}
}
The two operations are inverses of each other.
We can bring both of them to any common state.
Read the problem statement for div2 med. Try to get all the stones into one pile.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class ReverseMancala {
public ArrayList<Integer> find(int[] start, boolean rev) {
ArrayList<Integer> ret = new ArrayList<>();
int n = start.length;
while (true) {
boolean changed = false;
for (int i = 1; i < n; i++) {
if (start[i] > 0) {
changed = true;
int t = i;
int d = start[i];
start[i] = 0;
while (d-->0) {
t = (t+1) % n;
start[t]++;
}
if (rev) {
ret.add(t+n);
} else {
ret.add(i);
}
}
}
if (!changed) break;
}
if (rev) Collections.reverse(ret);
return ret;
}
public int[] findMoves(int[] start, int[] target) {
ArrayList<Integer> ans = find(start, false);
ans.addAll(find(target, true));
int[] ret = new int[ans.size()];
for (int i = 0; i < ans.size(); i++)
ret[i] = ans.get(i);
return ret;
}
}
What are some obvious winning or losing states?
All piles have 1 stone. Alice can always win by taking the magic stone then deciding based on parity of remaining stones.
XOR of all stones is equal to zero. Alice can take the magic stone and leave the victory condition alone.
Otherwise, if the xor is nonzero and there exists a pile with at least 2 stones, then it is not optimal to take the magic stone. Since winning conditions of misere and normal nim are the same when there exists a pile with at least 2 stones, you are passing a winning state to the other player by taking the magic stone.
After checking those two cases, we can ignore the lowest bits of all the numbers, as well as the magic stone.
This then becomes a game where a[i] is replaced by a[i]>>1, and the last player who takes a stone loses. This is misere nim.
public class MagicNim {
public String findWinner(int[] a) {
return (Arrays.stream(a).max().getAsInt() <= 3 ? 2 : 1) != Arrays.stream(a).reduce(0, (x,y) -> x^y) ? "Alice" : "Bob";
}
}
Solve the problem when k = 1.
Solve a more general version of the problem when k=1, but we also want certain pairs of hyperboxes to be intersecting (described by a bit-mask with (m choose 2) bits). To restate, for every 2^(m choose 2) choices of bitmasks, compute the number of ways to solve this problem in 1 dimension.
Two hyperboxes intersect if and only they intersect in every single dimension. Thus, they are disjoint if we take the bitwise and of all intersections of each dimension and it equals zero. This can be done efficiently with a Fast Walsh Hadamard transform.
public class Hyperboxes {
public static int mod = 998244353;
public static long[] inv;
static {
inv = new long[20];
inv[1] = 1;
for (int i = 2; i < inv.length; i++) {
inv[i] = (mod - mod / i) * inv[mod % i] % mod;
}
}
public long choose(long n, int k) {
if (k < 0 || k > n) return 0;
long ret = 1;
for (int i = 0; i < k; i++) {
ret = ret * (n-i) % mod;
ret = ret * inv[i+1] % mod;
}
return ret;
}
public int[] t = {0,1,3,6,10,15};
public int getBit(int i, int j) {
if (j > i) {
int w = i; i = j; j = w;
}
return t[i-1] + j;
}
public boolean nextPermutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1; ; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
public long mod_exp(long b, long e, long mod) {
long res = 1;
while (e > 0) {
if ((e & 1) == 1)
res = (res * b) % mod;
b = (b * b) % mod;
e >>= 1;
}
return res;
}
public int n,m,k;
public int[] f1;
public int[] f2;
public void dfs(int next, int closed, int groupopen, int pclosed, int intersections, int groups, long mult) {
if (next == m && closed == (1 << m) - 1) {
f1[intersections] += choose(n, groups) * mult % mod;
if (f1[intersections] >= mod) {
f1[intersections] -= mod;
}
return;
}
if (next < m) {
dfs(next + 1, closed, (1 << next), -1, intersections, groups + 1, mult);
if (pclosed == -1) {
dfs(next + 1, closed, groupopen | (1 << next), -1, intersections, groups, mult * inv[Integer.bitCount(groupopen) + 1] % mod);
}
}
// choose to close, continue same group
for (int x = pclosed+1; x < next; x++) {
if (((closed>>x) & 1) == 1) continue;
if (((groupopen>>x) & 1) == 1) continue;
int ninter = intersections;
for (int w = 0; w < next; w++) {
if (w != x && ((closed>>w) & 1) == 0) {
ninter |= 1 << getBit(x, w);
}
}
dfs(next, closed|(1<<x), groupopen, x, ninter, groups, mult);
}
// start different group
for (int x = 0; x < next; x++) {
if (((closed>>x) & 1) == 1) continue;
int ninter = intersections;
for (int w = 0; w < next; w++) {
if (w != x && ((closed>>w) & 1) == 0) {
ninter |= 1 << getBit(x, w);
}
}
dfs(next, closed|(1<<x), 0, x, ninter, groups+1, mult);
}
}
public void postprocess() {
int[] perm = new int[m];
for (int i = 0; i < m; i++) perm[i] = i;
for (int mask = 0; mask < 1 << t[m-1]; mask++) {
if (f1[mask] == 0) continue;
for (int i = 0; i < m; i++) perm[i] = i;
do {
int nmask = 0;
int c = 0;
for (int x = 0; x < m; x++) {
for (int y = 0; y < x; y++) {
int target = getBit(perm[x], perm[y]);
if (((mask>>c)&1) == 1)
nmask |= 1 << target;
c++;
}
}
f2[nmask] += f1[mask];
if (f2[nmask] >= mod) f2[nmask] -= mod;
} while (nextPermutation(perm));
} while (nextPermutation(perm));
}
public int findCount(int _n, int _m, int _k) {
n = _n; m = _m; k = _k;
f1 = new int[1<<t[m-1]];
// brute force m
// catalan(m) * m! * 2^(2m)
dfs(1, 0, 1, -1, 0, 1, 1);
// post process
// 2^(m choose 2) * m! * m
f2 = new int[1<<t[m-1]];
postprocess();
// FWT
// (m choose 2) * 2^(m choose 2)
int levels = 31-Integer.numberOfLeadingZeros(f2.length);
int len = f2.length;
for (int i = levels-1; i >= 0; i--) {
for (int j = 0; j < len; j++) {
if (((j>>i)&1) == 0) {
f2[j] = (f2[j] + f2[j|(1<<i)]) % mod;
}
}
}
for (int i = 0; i < len; i++) {
f2[i] = (int)mod_exp(f2[i], k, mod);
}
for (int i = 0; i < levels; i++) {
for (int j = 0; j < len; j++) {
if (((j>>i)&1) == 0) {
f2[j] = (f2[j] - f2[j|(1<<i)] + mod) % mod;
}
}
}
return f2[0];
}
}
Nice problems, thank you!
I still don't understand one thing in MagicNim problem solution. Why can we use nim modification with a[i] >> 1? In this case, for example, test with signle pile with 2 stones must have the same answer as test with single pile with 3 stones, but I think it's not true (single pile with 2 stones is loosing, while single pile with 3 stones is winning as we can remove one stone from it and reduce the problem to a pile with 2 stones).
I had a hard time understanding the solution too, and in my opinion the setter hints and solution above lack one specific detail, the last bit of numbers can't simply be 'ignored'. Although the official (and neat) java code is correct :). Hope the following code explains a bit more.
int xxor = 0;
int mx = 0, mx_misere = 0;
for(auto i:arr){
xxor ^= i;
mx = max(mx, i);
mx_misere = max(mx_misere, i >> 1);
}
if(xxor == 0 || mx == 1)
return "Alice";
else{
int xor1 = xxor >> 1;
int low = xxor & 1;
// misere nim subgame result is lose for current player
// reason: some pile with more than one stone
// xor of all numbers is 0
if(mx_misere >= 2 && xor1 == 0){
if(low == 1)return "Bob";
else return "Alice";
}
// misere nim subgame result is lose for current player
// reason: no pile with more than one stone
// number of piles odd
if(mx_misere <= 1 && xor1 == 1){
if(low == 1)return "Alice";
else return "Bob";
}
// misere nim subgame result is win for current player
return "Alice";
}
In your code: "if (mx_misere >= 2 && xor1 == 0)"why does Bob wins only when low == 1?I think Bob always wins in this case(regardless of the value of low) because the only hope for Alice to win is to keep xor1 value equal to zero using an odd number and decreasing it by one, but if she does that the original xor value becomes zero and Bob uses the magic stone and wins.
UPD: Actually the expression(xor1 == 0 && low == 0) will never be true so there is no problem code-wise(it will get AC).
Yes, sorry, I missed one step. In particular, if the misere nim is a losing case for the current player, the current player can only win if there are an odd number of piles with an odd number of stones. They can win by taking a single stone from some pile with an odd number of moves (i.e. a "pass" move). Only the parity of the number of pass moves matters, since our opponent can copy our passes.
:) thank you for the problems anyway. This problem really made me feel the 'Misere' part of game theory :)
Can someone explain how that playing a misere nim game after dividing pile sizes by 2 came up in MagicNim problem? Sorry didn't understood that.
We know that in MagicNim, two positions are for sure winning:
1- all piles with less than two elements: we take the magic stone, and choose the nim if the number of remaining piles is even, otherwise choose misere nim.
2- the xor of all numbers is 0: we take the magic stone and choose to play normal nim.
Moreover, in any other case you cannot take the magic stone, as in both cases, nim or misere nim, you would leave the adversary in a winning position.
Then we can somehow try to simplify the game, and get rid of the magic stone. The first player that after his move leaves the game in one of the two positions above loses (and that's the only way one can lose), so we can define a new game, where there is no magic stone, and the losing positions are the two above. In that new game, we can forget about the last bit in each number, the only thing we need to remember about those bits is the parity. So our new game is a misere nim + (odd-even game with the last bit). And then you get the messy analysis above :)
Why we can ignore last bit in each number? I can't understand it(There could be an even->odd move). Anyway, Nim game probs are too hard :(
I couldn't understand it either, maybe someone has to make some graphics, at least I cant :(.
To answer your question, the last bit can't be ignored. Imagine we are playing the game where losing positions are those whose xor is 0, or all piles have at most 1 stone, and there is no magic stone (the original game reduces to this one, the last one to move loses, so this is by itself misere).
Now the trick for the solution is that in these new game we can define 8 states, following this: each time:
there will be some piles with more than one elements, lets say those piles are represented as its half in the misere nim subgame (observe here we are ignoring the last bit), in this subgame we have at most 4 states (as in misere nim), and every time we make a move we can change the parity of the last bits.
also there are some piles with one stone: we represent all the last bits on all numbers as one, its xor or parity, whatever, so in this subgame we have two states.
in general we have 8 states.
now the possible moves are: take a stone from a pile with one stone: this corresponds to changing the parity of the last bit. take some stones from another pile, this corresponds to a move in the misere subgame, and can always change the parity of the last bit.
The trick and surprise and solution is that with those 8 states is enough for defining winning and losing positions for the whole game, and that can be proven by analyzing all cases, and all possible transitions...
and I can say a lot of problems are too hard :( but wouldn't choose nim games between them :) although this one more than being hard is messy, mostly to explain...
Still can't understand why after dividing all number by 2 it becomes a misere nim. I mean the losing state becomes the xor sum of all number is 0 or all number is less than 2. Why we can still use the same way solving the misere nim to solve this by just forgetting about the last bit?
Talking about hard problem: The last part could be also easily done with Inclusion–exclusion principle. The hardest part is k = 1. What is your asymptotic? Could you please clarify it? I wrote this part also in a different way: I generate number of way to put segments with compressed coordinates. After that, if I know that there are 100 ways of putting segments (6 segments) onto 11 points with some intersection_mask, then I just add to dp[intersection_mask] += 100 * C(n, 11).
I didn't like medium problem: I guess it could only be solved (and very fast, i got ac after writing stupid solution with this approach in a couple of minutes) by looking at a table of numbers.
Easy is a cool problem. But I made a bug, so without a small pretest I spent a lot of time trying to find the mistake in the code.
I can give you some loose bounds; there may be better ways to make it tighter. You can also add counters to code to see exact number of operations.
I fix the order that the intervals open. Since the intervals can be represented by balanced parenthesis, a very loose bound is catalan(6) * 6! * 2^12 ~ 10^7. More specifically, catalan(6) comes from number of ways to form a balanced parenthesis sequence, 6! comes from number of ways to close parenthesis, and 2^12 comes from number of ways to split the elements into groups where they take the same value. In practice, this is smaller, since I don't expand impossible states.
Afterwards, I can do a post-processing step where I can permute the labels. This step takes 2^(m choose 2) * m! * m^2, but actually, if I prune out zero entries (i.e. masks with zero ways), it's actually 2^(m choose 2) + (m!)^2 * m^2. I'm not sure why there are exactly m! nonzero masks before permuting labels.
This approach takes 0.5s for everything for my solution in Java.
I don't want to participate in div1 at all but topcoder pushed me too fast, I do not belong there :(
How silly is it to not be able to see that the two operations in Div1 300 are inverses of each other? In retrospect these things always seem so obvious ... :(
I tried to make that clear with the first two samples. But, I'm not sure how many people read the samples carefully.
Did anyone try div2 600 using dfs with each vector state as a node ?
.
Challenges to write editorials are up, though I didn't note when exactly they appeared.
yes challenge is now up and that is why I just edited my comment but still they mentioned it like this "just after the srm" challenge will be open.
|
http://codeforces.com/blog/entry/50572?locale=en
|
CC-MAIN-2017-30
|
refinedweb
| 3,607
| 70.53
|
How to Charge a Credit Card with Stripe in Node.js
October 8th, 2021
What You Will Learn in This Tutorial
How to use the Stripe NPM package to communicate with the Stripe API and charge a credit card in Node.js. install one additional dependency,
stripe:
Terminal
npm i stripe
Finally, go ahead and start up the development server:
Terminal
npm run dev
With that, we're ready to get started.
Getting a Card Token
In order to process a charge via the Stripe API, we'll need to get access to a Stripe token. For this tutorial, we'll only be focused on the back-end, but it's recommended that you check out our tutorial on How to Build a Credit Card Form Using Stripe.js to learn how to build a user interface to retrieve a Stripe card token.
Once you have a means for getting a card token, we can dig into processing a charge., in order to access the Stripe API, we need to set up an instance of Stripe via the
stripe NPM package.
Wiring Up Access to Stripe
With our secret key set up, now, we need to get access to the Stripe API. Fortunately, the folks at Stripe offer a Node.js package for their API (we installed this earlier), so all we need to do is set up a connection to it.
/lib/stripe.js
import Stripe from 'stripe'; import settings from "./settings"; const stripe = Stripe(settings.stripe.secretKey); export default stripe;
Inside of our
/lib folder, we want to create a file
stripe.js where we'll load in the
stripe package from NPM and initialize it with our
secretKey from Stripe that we just added to our settings file.
Here, we import the appropriate settings based on our environment. We're assuming the current environment is
development, so
settings here will contain the contents of our
settings-development.json file.
On that object, we expect a property
stripe to be defined as an object with its own property
secretKey. Above, we first import
Stripe from the
stripe NPM package we installed earlier and then call that imported value as a function, passing in our
secretKey from our settings file.
In return, we expect to get back an instance of the Stripe API, which we store in a variable
stripe and then export as the default value from this file.
With this, now, whenever we want to communicate with Stripe, we only need to import this one file as opposed to writing all of this code in all of the files where we want to call to Stripe.
Wiring Up an Endpoint for Charges
Next, we're going to wire up an HTTP POST endpoint using Express.js (built-in and pre-configured in the boilerplate we're using). We'll use this endpoint to demonstrate creating the charge via Stripe. It's important to note: you can call the Stripe code we'll see below from anywhere within Node.js. We're just using an Express route as an example.
/api/index.js
import graphql from "./graphql/server"; import stripe from "../lib/stripe"; export default (app) => { graphql(app); app.post("/checkout", (req, res) => { // We'll wire up the charge here... }); };
Inside of the
/api/index.js file already included in our boilerplate, we add a new route
.post() method on the
app argument passed into the function exported from this file. Here,
app represents the Express.js
app that we get in return when calling to
express() (you can see the setup for this in the
/index.js file at the root of the boilerplate—the
api() function we call there is the one we see being exported above).
Here, we use the
.post() method to create an Express route that only accepts HTTP POST requests. As we'll see, we'll send an HTTP POST request later to test this out.
) { // We'll process the charge here... } res .status(400) .send( "Must pass an itemId and source in the request body in order to process a charge." ); }); };
Inside of the callback for our route, before we handle the
request, we set up an array of items to act as a mock database for real items that a customer might purchase from us.
This is important. The reason we show this here instead of passing an amount from the client is that we should never trust the client. For example, if a user figured out that we just pass the amount from the client to the server, they could change an order for $1,000 to $0.01 and the charge would process.
To mitigate this, we track the prices we're going to charge on the server and use a unique ID to tell us which item to get the price for when we receive a charge request.
Here, we do that by saying "this array of
items are for sale with these prices." We expect that the
req.body object we receive will have two properties: an
itemId and a
source. Here,
itemId should match one of the
_id fields on an item if the purchase is valid (in practice, we'd load the same list of items into our UI from the database so the IDs were consistent).
To check, we use
items.find(), looking for an item with an
_id property—inside of our
.find() callback we use JavaScript object destructuring to "pluck" this property off of each item we loop over—that's equal to the
req.body.itemId we received from the client.
If we do find a matching item, we know the purchase is valid. Next, we also get the
source—this is the term Stripe uses to refer to the payment source—from the
req.body.
Assuming that both
item and
source are defined, we want to attempt a charge. If they are not defined, we want to respond with an HTTP 400 status code which stands for a "Bad Request" and send back a message with instructions on how to resolve the problem.
) { return stripe.charges .create({ amount: item.amount, currency: "usd", source, description: item.name, metadata: { ...item, }, }) .then((charge) => { res.status(200).send(charge); }) .catch((error) => { res.status(402).send(error); }); } res .status(400) .send( "Must pass an itemId and source in the request body in order to process a charge." ); }); };
Now we're ready to send our charge request to Stripe. To do it, we're going to call to the
stripe.charges.create() method from the
stripe API instance we set up in the file we imported earlier. Calling that function, we pass an object with the appropriate options for our charge (see what's available in the Stripe documentation here).
For our needs, we want to pass the two required fields
amount (an integer representing the charge in cents—e.g., $5.00 would be 500) and
currency. We also pass our
source (this will be the Stripe token that we retrieve on the client), the name of our item as a
description, and also include all of the data about our charge in the
metadata field as an example of passing miscellaneous data alongside our charge (a convenience option for developers who need to store additional, custom, charge-related data like an internal user ID).
Finally, as we expect all of the methods in the
stripe API instance to return a JavaScript Promise, we chain on a
.then() callback function to handle our success state and a
.catch() callback function to handle an error state.
If the charge is successful, we respond to the original
req with a status code of
200 (the HTTP status code for signaling a successful request) and pass the response we receive from Stripe (an object containing the details of the charge processed).
If the charge fails, we send an HTTP status code
402 (which stands for "Payment Required") and send back the
error object received from Stripe.
That's it! Let's fire up the client to get our Stripe token and then process the request via an HTTP app (I'm using the MacOS app Paw to test our endpoint).
Wrapping Up
In this tutorial, we learned how to charge a credit card using the
stripe API in Node.js. We learned how to create an instance of the Stripe API via their
stripe node package, creating a reusable module for communicating with stripe, and then we learned how to set up an HTTP POST route via Express.js where we could send a charge request to Stripe.
Get the latest free JavaScript and Node.js tutorials, course announcements, and updates from CheatCode in your inbox.
No spam. Just new tutorials, course announcements, and updates from CheatCode.
|
https://cheatcode.co/tutorials/how-to-charge-a-credit-card-with-stripe-in-node-js
|
CC-MAIN-2022-21
|
refinedweb
| 1,460
| 71.24
|
Hi,
Product: IntelliJ IDEA Ultimate 12.1.4
OS: Mac OS X 10.8.4
JDK: JDK 1.6.0_51
When I run a basic JUnit or TestNG test (let's use TestNG in this case), then the final resulting console output is indeterministic -- sometimes all of it is missing, sometime some of it, sometimes none of it. This only happens when one of two Test Runner options are selected (in the Test Runner view's gear icon drop-down menu) : "Track Running Test" and/or "Show Statistics".
Steps:
1) Open the Test Runner Tab and select "Track Running Test" and "Show Statistics" (the issue is actually reproducible even when just one of these is checked).
2) Run this basic TestNG test that outputs 100 lines to stdout:
import org.testng.annotations.Test;
public class QuickTest {
@Test(invocationCount=100)
public void test1() throws Exception {
System.out.println("SampleOutput");
}
}
What I noticed is that when the test runs, all the desired output seems to be displayed for a very brief moment, but is then truncated as soon as the blue "Process finished with exit code 0" message appears (and then even that blue message itself disappears immediately).
What I would expect to see would be all 100 lines, and possibly the blue msg at the end.
Is anyone else able to reproduce this? If so, a fix would be most welcome. Thank you.
~Will
UPDATE: I've actually now seen this problem even without checkmarking "Track Running Test" or "Show Statistics"... the issue sometimes surfaces even with all the options unchecked. But one thing that's consistent is that I'm able to very briefly (less than a second) see the expected console output, which then immediately gets deleted as soon as the blue "Process finished with exit code 0" msg appears. Is there a way to suppress this msg meanwhile a fix is created? Thanks.
The console output with TestNG is pretty buggy, see also. I've had to go back to eclipse until bugs like these are resolved.
|
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206860865-Test-Runner-Tab-console-output-is-unexpectedly-deleted
|
CC-MAIN-2019-26
|
refinedweb
| 339
| 70.53
|
C++ pointers vs arrays
Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. Consider the following program:
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer. ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the next location ptr++; } return 0; }
When the above code is compiled and executed, it produces result something as follows:
Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200
However, pointers and arrays are not completely interchangeable. For example, consider the following program:
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; for (int i = 0; i < MAX; i++) { *var = i; // This is a correct syntax var++; // This is incorrect. } return 0; }
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value. The reason for this is that var is a constant that points to the beginning of an array and can not be used as l-value.
Because an array name generates a pointer constant, it can still be used in pointer-style expressions, as long as it is not modified. For example, the following is a valid statement that assigns var[2] the value 500:
*(var + 2) = 500;
Above statement is valid and will compile successfully because var is not changed.
|
http://www.tutorialspoint.com/cgi-bin/printversion.cgi?tutorial=cplusplus&file=cpp_pointers_vs_arrays.htm
|
CC-MAIN-2014-42
|
refinedweb
| 303
| 50.4
|
Java Keywords – List of 51 Keywords with Examples
Java keywords are reserved words, that have a special meaning associated with them. For easy identification, they are usually highlighted in Java. Out of 50 keywords, 48 are in use while 2 are not.
Let us study some of the important Java Keywords in detail.
List of Java Keywords
- abstract: It is used to achieve abstraction in Java. It is a non-access to modifier relevant for classes and methods.
- enum: Enum contains a fixed set of constants.
- instanceof: instanceof is used to check whether the object is an instance of the class, subclass or interface.
- private: It is an access modifier. If any class or method is declared private then it cannot be accessible by its class.
- protected: It is mainly used in the concept of inheritance to only get accessed by the subclasses.
- public: Anything inside public is publically accessible by any class or variable.
Access Modifiers –
- static: Static can be used to create a (block, method, variable, nested class) which is used itself, without reference to an instance.
- strictfp: As the name says strictfp it is used for restricting floating-point calculations. Using strictfp it ensures the same result on every platform while performing operations using the floating-point variable.
- synchronized: It is applicable to blocks and methods. It is used for synchronization.
- transient: It is a variable modifier used for serialization. During serialization, if we do not want to save the value of a variable in a file, then we use transient.
- volatile: It tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program.
Do you know how can we use Java Static Keywords?
Here, is the list of all keywords used in Java-
enum and strictfp Keywords in Java
1. enum
Enum is a special type of data type which contains a fixed set of constants. An enumeration defines a class type. Enumeration has constructors, methods and instance variables. Enumeration is declared the same as the primitives.
Master the concept of Constructor in Java in a single shot!
1.1 Declaration of enum in Java
- enums cannot be declared inside a method but declare inside or outside a class.
Syntax:
public enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }
Example-
package com.dataflair.keyword; enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } public class EnumExample { Day day; public EnumExample(Day day) { this.day = day; } public void dayIsLike() {) { String str = "SUNDAY"; EnumExample t1 = new EnumExample(Day.valueOf(str)); t1.dayIsLike(); } }
Output-
Constants in the enum are always public static and final. We cannot have child enums as we use final. We can declare the main method inside the enum and hence, we can use a command prompt to call it.
Let’s study in detail the implementation of the Final Keyword in Java.
1.2 Enum and Inheritance
- All enums extend java.lang.Enum class. As a class extends one parent in Java, so an enum can’t extend anything else.
- toString() method is overridden in java.lang.Enum class, which returns enum like a name.
- enum can execute various interfaces.
1.3 values(), ordinal() and valueOf() methods
- These methods are available inside java.lang.Enum.
- values() method in Java is used to restore all qualities exhibited inside enum.
- An order is essential in enums. By using the ordinal() method, each enum file can discover, same as cluster file.
- valueOf() method returns the enum constant of the predefined string values if exists.
2. strictfp
strictfp is a keyword in java used for restricting floating-point values and ensuring the same output on each stage while performing operations on the floating-point variable.
The calculations of the floating-point are platform-dependent there are different outputs using different processors. When any file runs on 16 bit or 32-bit or 64-bit processor then there are chances that the output may differ. To solve this issue strictfp was introduced in JDK 1.2 for the calculations of floating-point.
Important points:
- If we declare a class or interface using strictfp modifier, then all the methods declared inside that class, and the nested types are implicitly strictfp.
- We cannot use strictfp with abstract methods. Though we can use it with abstract classes in Java.
- All the methods of the interface are implicitly abstract so we cant use strictfp with any of them.
Example-
package com.dataflair.keyword; public class StrictFPExample { public strictfp double sum() { double operand1 = 12e+05; double operand2 = 9e+10; return (operand1+operand2); } public static strictfp void main(String[] args) { StrictFPExample sumObject = new StrictFPExample(); System.out.println(sumObject.sum()); } }
Summary
All the Java Keywords are predefined for a compiler, we can’t use them as an identifier. This is just the beginning of keywords. In our next tutorial – Keywords in Java (part – 2) we will learn more about them.
Hope, you liked the explanation. Please share your experience with us!
|
https://data-flair.training/blogs/java-keywords/
|
CC-MAIN-2019-47
|
refinedweb
| 823
| 58.48
|
How to Terminate QtWebEngine Before Exiting
Context: It is very important for our system to be memory-leak free. We build Qt, linking to mfc to ensure a common heap is used. This allows us to work with the _CRTDBG_MAP_ALLOC/_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ) calls to detect memory leaking on exit.
We've recently added a QtWebEngineView as a widget to our system, which brings along all the web engine processes and threads. On exit, it appears that these threads aren't shut down, and all memory resources are (erroneously?) reported as leaks. I've read through the documentation, and I'm struggling to find something to "correctly" terminate and release all web engine content prior to exit. A similar issue happens when working just with an OpenGL widget.
Question: How does one correctly terminate and release all resources - including its OpenGL context - associated with qt web engine?
If the motivation is insufficient, another justification would be how to release all web engine resources during program execution, in the case of limited resources?
A simple example program:
#include <QtCore> #include <QtWidgets\QMainWindow> #include <QtWebEngine\QtWebEngine> #include <QtWebEngineWidgets> #define _CRTDBG_MAP_ALLOC int main( int argc, char * argv[] ) { _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // enable memory leak checking int result = 0; { QApplication app( argc, argv ); QtWebEngine::initialize(); // reports leaks - likely not closed correctly on exit QMainWindow mainWindow; QWebEngineView *webView = new QWebEngineView; // more leaks... webView->load( QUrl( "" ) ); // even more leaks... mainWindow.setCentralWidget( webView ); mainWindow.resize( 800, 600 ); mainWindow.show(); result = app.exec(); } // expected Qt to have finished offloading here return result; }
- A Former User last edited by A Former User
Hi! Your code looks fine to me and my guess would be that this is a known issue. I don't think anyone here can help you with this, so better ask the devs on the mailing list.
Thanks Wieland for taking a look. And thanks for the mailing list suggestion! Good to know of more Qt resources.
I've filed a bug:
|
https://forum.qt.io/topic/72750/how-to-terminate-qtwebengine-before-exiting/3
|
CC-MAIN-2019-43
|
refinedweb
| 325
| 57.27
|
Again, points and directions have arisen. This time, ...in this post ... ,there was a need to place points within a polygon for geocoding based on compass directions. The simplest solution turns out to be to create a centroid, then generate points about it at some distance and angle.
So the solution can be approached using search cursors, but as usual, I like numpy since you can vectorize most operations. The code below, reads in the centroid points of an input polygon theme (r"...\fishnet_label.shp") which in this case was the centroids of a fishnet since they are easy to create. From there, the steps are simple:
- convert the input point file to an array (FeatureClassToNumPyArray
- collect the point coordinates that fall on a circle at a distance and angle from the centroid (_circle def)
- stack the points and convert back to a point file (Numpyarraytofeatureclass)
Of course, you can put in the angles in the table, provide, sub-identifiers and even the compass representation in text form. The points can also be created with random angles and distances with little code modification. A couple of examples are below, followed by the code. See Darren's example in the link for a cursor approach.
-------------------------------------------------------------------
And the code
"""
:Script: createcompass.py
:Author: Dan_Patterson@carleton.ca
: if north angle is needed, you can use this to convert
: ang = np.mod((450.0 - ang), 360.)
"""
import numpy as np
import arcpy
def _circle(radius=10, theta=22.5, xc=0.0, yc=0.0):
"""Produce points around a circle.
: radius - distance from centre
: theta - either a single value to form angles about a circle or
: - a list or tuple of the desired angles
"""
if isinstance(theta, (list, tuple)):
angles = np.deg2rad(np.array(theta))
else:
angles = np.deg2rad(np.arange(180.0, -180.0-theta, step=-theta))
x_s = radius*np.cos(angles) + xc # X values
y_s = radius*np.sin(angles) + yc # Y values
pnts = np.c_[x_s, y_s]
return pnts
# --------------------------------------------------------------------
if __name__ == '__main__':
"""produce some points around a centroid at angles and distances"""
inFC = r"C:\Data\points\fishnet_label.shp"
outFC = r"C:\Data\points\pnts2.shp"
radius = 2
theta = 22.5 # or a list like... theta = [0, 90, 180, 270]
a = arcpy.da.FeatureClassToNumPyArray(inFC, ["SHAPE@X", "SHAPE@Y"])
b = [_circle(radius, theta, a['SHAPE@X'][i], a['SHAPE@Y'][i])
for i in range(len(a))]
c = np.vstack(b)
c.dtype = a.dtype
arcpy.da.NumPyArrayToFeatureClass(c, outFC, c.dtype.names)
See other posts about circles and related things.
circles sectors rings buffers and the n-gons
|
https://geonet.esri.com/blogs/dan_patterson/2017/02
|
CC-MAIN-2017-30
|
refinedweb
| 427
| 68.36
|
In this course, we will study the C Programming Language Basics Introduction and its advantage and disadvantage. So let us start.
C Programming Language Basics Introduction
C is a procedural oriented programming language (POP). This language was developed by Dennis Ritchie in 1972 at the bell laboratory. There was a B language before the C language was invented. The B language was developed by Ken Thompson in1970 at bell laboratories. There were many limitations in the B language. And to remove all the limitations Dennis Ritchie developed C.
C language is a very popular language. C language is believed to be the origin of other programming languages. In order to learn a different programming language, we must have knowledge of the C language first. C is a very simple language. There are many languages like C++, C#, Java, PHP, etc which have adopted the syntax of the C language.
Learn More C Programming Language Basic Introduction
The C language was standardized in 1989 by the American National Standards Institute (ANSI) and after that by the International Standards Organization (ISO).
The latest version of the C language is C11.
What are the advantages and disadvantages of c programming?
Advantages of C Programming
Powerful and efficient language
C is a type of robust language and it contains various data types. To perform various operations it has many operators that provide a vast platform.
Portable language
C is a very flexible language. It is a machine-independent language that helps us to write code in any machine and it can be shared between different machines without any change in the code.
Built-in functions
There are 32 keywords in C. The functions in the C program can be made easier with the help of the keywords.
Quality to extend itself
The c programming language has the ability to extend itself. As we all know that the C library is a set of functions that can be easily used and the functions in the C Standard Library can be added which will help in making the code simpler.
Middle-level language
C is a type of middle-level programming language that means it can support both the high-level programming language and low-level programming language. In this, we support low-level programming kernels and drivers. It supports high-level programming system software applications.
System programming
C follows the system-based programming system that means the programming is done for the hardware devices.
Disadvantages of C Programming
Concept of OOPs
C is a vast language but it supports OOPs (Inheritance, Polymorphism, Encapsulation, Abstraction, Data Hiding). C follows a simply procedural programming approach.
Run-time checking
In the C programming language, we can not find bugs and errors after every line of code. The compiler shows the errors and bugs after the completion of the code. Due to this, the checking of errors in a large code becomes difficult.
Concept of namespace
In C the concept of namespaces is not implemented.
Lack of exception handling
Exception Handling is the most important feature of programming languages. Exception Handling helps us in the detection of the error and to give a correct response to it.
Constructor or Destructor
C does not use a constructor or destructor. Constructors & Destructors only supports Object-Oriented Programming.
Low level of abstraction
C is a small and core machine language in which there are minimum data hiding and exclusive visibility which affects the security of the language.
What are the c programming basics to write a program?
Here are a few commands and syntax used in c programming to write a simple c program. So let us start.
Top comments (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/alimammiya/c-programming-language-basics-introduction-21la
|
CC-MAIN-2022-40
|
refinedweb
| 609
| 57.37
|
. Here are some topics you may want to brush up on: Java Reflection, Factory Design Pattern, and the Singleton Design Pattern.
If you like videos like this, it helps to tell Google with a click here
Code From the Video
Customer2.java
// Replace constructors with factories public abstract class Customer2 { private String custRating; static final int PREMIER = 2; static final int VALUED = 1; static final int DEADBEAT = 0; public String getCustRating(){ return custRating; } public void setCustRating(String custRating) { this.custRating = custRating; } public static void main(String[] args){ // This factory will generate specific subclasses of Customer3 CustomerFactory customerFactory = new CustomerFactory(); // This assigns the methods and fields for the class Premier // This is replaced when I get rid of the Switch // Customer3 goodCustomer = customerFactory.getCustomer(Customer3.PREMIER); Customer2 goodCustomer = customerFactory.getCustomer("Premier"); System.out.println("This Customers Rating: " + goodCustomer.getCustRating()); // This assigns the methods and fields for the class Deadbeat // This is replaced when I get rid of the Switch // Customer3 badCustomer = customerFactory.getCustomer(Customer3.DEADBEAT); Customer2 badCustomer = customerFactory.getCustomer("Deadbeat"); System.out.println("This Customers Rating: " + badCustomer.getCustRating()); } } class Premier extends Customer2{ Premier(){ setCustRating("Premier Customer"); } } class Deadbeat extends Customer2{ Deadbeat(){ setCustRating("Deadbeat Customer"); } } class CustomerFactory{ // This is a poor design because this switch needs updated // every time I make a new subclass /* public Customer2 getCustomer(int custType){ switch (custType){ case 2: return new Premier(); case 0: return new Deadbeat(); default: throw new IllegalArgumentException("Invalid Customer Type"); } } */ public Customer2 getCustomer(String custName){ try { // forName returns a class object with the String that is // passed to it. newInstance() creates an instance of the class return (Customer2) Class.forName(custName).newInstance(); } catch(Exception e){ throw new IllegalArgumentException("Invalid Customer Type"); } } }
Athlete.java
Athlete.java // Create a Factory that creates singletons import java.lang.reflect.Method; public class Athlete { private String athleteName = ""; public String getAthleteName() { return athleteName; } public void setAthleteName(String athleteName){ this.athleteName = athleteName; } public static Athlete getInstance(){ return null; } } class GoldWinner extends Athlete{ // Set to null to signify that an instance of // type GoldWinner doesn't exist private static GoldWinner goldAthlete = null; // Constructor is set to private to keep other // classes from creating an instance of GoldWinner private GoldWinner(String athleteName){ setAthleteName(athleteName); } // Creates 1 instance of GoldWinner (Simple Singleton) public static GoldWinner getInstance(String athleteName){ // If an instance of GoldWinner doesn't exist // create one if(goldAthlete == null){ goldAthlete = new GoldWinner(athleteName); } return goldAthlete; } } class SilverWinner extends Athlete{ private static SilverWinner silverAthlete = null; private SilverWinner(String athleteName){ setAthleteName(athleteName); } public static SilverWinner getInstance(String athleteName){ if(silverAthlete == null){ silverAthlete = new SilverWinner(athleteName); } return silverAthlete; } } class BronzeWinner extends Athlete{ private static BronzeWinner bronzeAthlete = null; private BronzeWinner(String athleteName){ setAthleteName(athleteName); } public static BronzeWinner getInstance(String athleteName){ if(bronzeAthlete == null){ bronzeAthlete = new BronzeWinner(athleteName); } return bronzeAthlete; } } class MedalFactory{ public Athlete getMedal(String medalType, String athleteName){ try { // Define the type of the parameter that will be passed // to the method I create below Class[] athleteNameParameter = new Class[]{String.class}; // forName returns a class object with the String that is // passed to it. getMethod returns the method provided // the second parameter defines the type of parameter passed // to the method Method getInstanceMethod = Class.forName(medalType).getMethod("getInstance", athleteNameParameter); // Create an array with the parameter values that will be // passed to the method getInstance Object[] params = new Object[]{new String(athleteName)}; // Pass the parameters to method getInstance and return // a subclass of type Athlete return (Athlete) getInstanceMethod.invoke(null, params); } catch(Exception e){ throw new IllegalArgumentException("Invalid Medal Type"); } } } class TestMedalWinner{ public static void main(String[] args){ MedalFactory medalFactory = new MedalFactory(); Athlete goldWinner = medalFactory.getMedal("GoldWinner", "Dave Thomas"); Athlete silverWinner = medalFactory.getMedal("SilverWinner", "Mac McDonald"); Athlete bronzeWinner = medalFactory.getMedal("BronzeWinner", "David Edgerton"); Athlete goldWinner2 = medalFactory.getMedal("GoldWinner", "Ray Kroc"); System.out.println("Gold Medal Winner: " + goldWinner.getAthleteName()); System.out.println("Silver Medal Winner: " + silverWinner.getAthleteName()); System.out.println("Bronze Medal Winner: " + bronzeWinner.getAthleteName()); // Even though I tried to create a new Object of type GoldWinner // it was rejected and the original object remained System.out.println("Gold Medal Winner: " + goldWinner2.getAthleteName()); } }
Hi, another great video.
I just though I would put a quick note on this video to help others avoid the heart ache I went through.
Despite your 500+ videos I was swearing about you (sorry) and how crappy your code was (sorry again, lol) when mine did not work.
Note for others: these methods rely on the package qualified class name. If your code sits in a package (com.mypack ) then your classes will all need that slapped onto them. medaltype becomes “com.mypack.”+medaltype.
Thanks for the unexpected homework – as always I learned something.
Cheers,
Neil
Thank you 🙂 Yes, I have to assume that people are using the same setup that I use and that sometimes causes problems. Sorry about that.
I’m very used to getting messages about how my code sucks so that doesn’t bother me. Most of the time the error was caused because of a missing tag, quote or semicolon. Some times it is caused because my improved code sucked that day 🙂
This tutorial has generated more grief than normal because quite literally I’m one of the few people on Earth that ever spent this much time teaching refactoring. Type “code refactoring tutorial” into Google with the quotes. Almost every returned link is either mine or from some website that copied exactly what is on my site. That put a giant bulls eye on my back for every programming expert in the world to attack.
I’m glad you got it fixed and I know you meant no ill will with your comment.
Thanks for the tip
Derek
I was worried, until the last line of the message, that my British sarcasm had been misinterpreted.
Just for absolute clarity I have never had any problems with your approach or your code. And I really appreciate these tutorials.
As you say above everyone else stops at the standard basic Java tutorials which I have done to death. I was having real problems knowing where to go next and where/what/how to improve. As a “noob” I literally didn’t know what questions to ask and I certainly “didn’t know what I didn’t know”. Then you started this series, which is great.
As a student I should not just be copying your code, but should be extending it, and finding its limits. With this comes knowledge of where to go for help when you are not around (be it stackoverflow or the oracle Java site or etc.). The tutorials are pitched at the perfect level for that learning.
Cheers again,
Neil
No reason to worry 🙂 I love any positive criticism. Without it I would never improve. When I first started making videos I figured nobody would ever see them so I didn’t aim to perfect them. It wasn’t until you guys started pointing out every little error that I realized I needed to step up my game.
I still have a long way to go. I still dream about making the perfect math tutorials, but I’m just not good enough yet. Keep me on my toes. I appreciate it!
Derek
Hi Derek,
i have a request if it is possible. Can you get off the number in front of the code please? In this time i am studying code refactoring watching your video. You are running like a Ferrari and i have just a Fiat Panda 🙂
Thnks for your work man!!!
Hi, On the part of the page that has the code, put your mouse over it and click on the button labeled View Source it looks like <>. That will get rid of the line numbers. I hope that helps
Hi derek. Great tutorial. I have watched it quite of in a rush, there are concepts in here that I am yet to learn so I will certainly need to go back into it, maybe search for some knowledge or/and probably go back to your earlier tutorials and learn quite a lot of things that I skipped. Nevertheless I have a question: I had the impression that the if clause inside the singletons breaks the rule “the program isn’t allowed to contain conditional statements”. Am I misunderstanding what was asked by emily’s professor?
I am a brazilian fellow studying computer science in Israel’s OpenUniversity, I love to code and I was feeling somewhat frustrated by the large amount of stuff I have to learn at school and the little amount that is code or direction to actually implement ideas. Your tutorials are amazing to do in parallel, they’ve been giving me back the “rush” of learning and desiring to learn and know more, they give me very strong feeling of purpose on what I’m learning, thank you sooo much.
Thank you very much for the compliment 🙂 At this time I can’t remember what all the rules were, but I know that the code I wrote was accepted by the teacher.
I’m very happy that you enjoy the videos. I do my best to make original ones.
p.s: sorry, the above was meant to the singleton tutorial, hope you can delete it from here and if you desire move it to the right place. thanks again
Thanks again. Just one question. Is this line necessary:
Object[] params = new Object[]{new String(athleteName)};
getInstanceMethod.invoke(null, params);
I was able to get away with it using the string directly like this and it works:
getInstanceMethod.invoke(null, athleteName);
I used that line to point out that invoke receives an Object, but since String is an Object it still works. I tend to point everything out in my code even if it is sometimes not necessary.
My comments On Customer2 :
a) The 3 static PREMIER, VALUED and DEADBEAT should be commented out. No more value.
b) I know that lots of examples are built on the fact that the java default package is used. I don’t think that it is a good idea in this case. Please always make use of a package and certainly at this level because it is not for a beginner anymore. If you use a package name then your code doesn’t work anymore because the name of the class has to be prefixed by the package and you do agree with me that in most of the cases we all use packages.
Refactoring I did :
String packageName = this.getClass().getPackage().getName();
return (Customer2) Class.forName(packageName + “.” + custName).newInstance();
Yes I agree with your input. Some times I get stuck in keeping everything as basic as possible even when I should know that my audience will be far from intermediate programmers.
(I didn’t thank you Mr Banas for the excellent tutorial!)
on Athlete :
Similar to Customer2. As the default package is used the code does not function anymore if a package (not default) is used.
Corrections I did:
String packageName = this.getClass().getPackage().getName();
Method getInstanceMethod = Class.forName(packageName + “.” + medalType).getMethod(“getInstance”, athleteNameParameter);
Another remark. You make use a lot of System.out.println and that is good to display some logging.
I would recommend you at this level to make use of unit tests.
I know that will complicate a little because of the use of JUnit but as it is a tutorial on code refactoring that will demonstrate to the users that after you make some refactoring and you run the tests that no regressions were created.
I use most of the time maven and the archetype quickstart to create a new application and JUnit is already added to the pom (3.8). The maven plugin is now installed and configured in Eclipse by default. It means that if you ship a pom.xml and the code, your readers will be able to run your examples and normally not get any dependencies problems. But I know that the fact to build the examples on the core java packages is a good plus. You have javac then you have everything to make the examples run! My 2 cents. Thanks for your work Mr Banas.
I plan on covering GIT, JUnit and Maven very soon.
|
http://www.newthinktank.com/2013/01/code-refactoring-5/
|
CC-MAIN-2018-34
|
refinedweb
| 2,025
| 54.73
|
tag:blogger.com,1999:blog-170856262017-01-12T04:03:47.382-08:00Jignesh Shah's BlogBlog about evolving Data technologies like PostgreSQLJignesh Shah High Availability in a Containerized World - PGConfSV 2016<div dir="ltr" style="text-align: left;" trbidi="on">My slides from todays talk at PgConf SV 2016 High Availability in a Containerized World">PostgreSQL High Availability in a Containerized World</a> </strong> from <strong><a href="" target="_blank">Jignesh Shah</a></strong> </div></div><img src="" height="1" width="1" alt=""/>Jignesh Shah Docker on Windows<div dir="ltr" style="text-align: left;" trbidi="on">NOTE: 9/8/2016: This is an older post which I wrote few months ago but never not posted.<br /><br />After using docker on Linux for more than a year it was finally time to try it on a different platform. Trying on docker on Windows Server 2016 TP4 was one way to try it out but the experience of that was bit more complicated. However when I heard about docker on Windows 10 I was initially surprised. Why? Well based on what I had seen and figured out that it really needed Hyper-V features to run which I assumed was only available on the Windows Server line.<br /><br />I guess I was wrong. Using Control Panel -> Program & Features -> Turn Windows Features On or Off , there is a feature called Hyper-V which can be turned on.<br />Now before you start searching for it and trying to turn it on wait till you read the following to save you some hassles.<br /><br />1. You need Windows 10 Pro (Sorry Windows 10 does not work)<br />2. You need a CPU which supports Virtualization and <a href="" target="_blank">SLAT</a> aka EPT.<br /><br />With Task Manager -> Performance -> CPU it is easy to figure out if Virtualization is supported or not. But SLAT is another story. systeminfo or coreinfo is required to figure that out. You may be able to turn on some of the components of the Hyper-V on CPUs not supporting SLAT but that will not be enough.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="284" src="" width="320" /></a></div><br /><br />I really had to cycle through few laptops using Intel Core2 Duo and Intel Pentium chips which do support Virtualization but did not support SLAT and finally came across my dusty desktop using AMD Phenom which had Virtualization with SLAT support on it. and running Windows 10 on it.<br /><br />Of course then I applied for the Docker beta program on Windows. The invitation came yesterday and finally got a chance to download the docker binaries and install it.<br /><br />Once the installation (as Administrator of course) finished it gave the option to Launch docker and after it finished launching the daemon in the background it showed a splash image as follows:<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="200" /></a></div><br /><br />Good job Docker on the usability to show me what to do next:<br /><br />Next I deploy an nginx server as follows<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="129" src="" width="640" /></a></div><br /><br />Woha!! If it did not strike you.. I am running Linux images here on Windows!!<br />Now I can access the same in a browser as<br />(This I would say was a bit of struggle since I had not read the doc properly where I was trying with or or but only worked)<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="148" src="" width="320" /></a></div><br /><br />Overall very interesting and game changing for development on Windows!.<br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah another reboot of Application Architecture<div dir="ltr" style="text-align: left;" trbidi="on">Last week I attended Redis Conf 2016 in Mission Bay Conference Center and was excited to see more than 650+ attendees discussing Redis. It is interesting that Redis has grown from a pure caching solution to now support more data use cases of their customer base.<br /><br />If we put the above in perspective we will see how applications are changing over the years.<br /><b><br /></b><b>CHUI Era</b><br /><b><br /></b>Years before leading to Y2K were all monolithic applications where everything was done on a single setup with people either using dump terminals or using Windows or Unix Clients to just open a telnet sessions and use a text-based interface which was often called later as "ChUI" - Character User Interface. Browsers were not popular but Windows was picking up and some "modern" applications at that point had their first Windows Fat Client but it was still all in one Windows "GUI" applications being developed.<br /><br /><b>GUI Era</b><br /><br />While technically the whole decade leading to year 2000, Client-Server technologies became more popular with a centralized database and a front end in either a Windows Rich Client or Java Rich Client or Web Browser based "WebUI" front end. Companies like Oracle, Sun at that time made a killing selling large Centralized servers running databases with essentially a Rich Client or WebUI client accessing the central server. In the later part of the years three tier systems. However majority of the enterprise applications were still "Rich Clients"<br /><br /><b>Java Era</b><br /><br />The era of the middleware was basically rule by Java webapp servers leading to a "classic" three-tier systems: Database layer, Middleware layer, Presentation layer. This is the generation that heavily started the SOA leading to APIs everywhere. Also this is the generation that lead to XML hell where everybody had to understand XML to interconnect everything. However things were still monolithic specially in the Database layer and to lesser extent on the Middleware layer. Scale was more limited to Amdhal's law. To work around some of this scaling issues, more tiers were being introduced like "Caching layer", "Load Proxies", etc.<br /><br /><b>ScaleOut Era</b><br /><br />As databases became hard to scale on a single node, Designs started changing using new kinds of database systems to support smaller boxes leading to a new kind of designs: Sharding, Shared-Nothing, Shared Data based database systems. This was the first reboot in some sense where "Eventual Consistency" paradigms before more popular and applications where now being developed with these new paradigms of multi-node databases. Applications now had to introduce new layers who has knowledge about the "intelligence" of the scale out databases on how to handle sharding, node reconnections, etc. CAP Theorem was more discussed than Amdhal's law. The number of tiers in such a scale out application was already approaching 10 such distinct operation tiers. There were people doing multi data centers but those were primarily for DR use cases.<br /><br /><b>Cloud Era</b><br /><br />With the advent of Amazon Web Services, new refactoring of applications started primarily with the concept of multiple data centers, variable latencies between services and needing real decoupling between tiers. Earlier the tiers were more of "components" rather than services as the assumption was everything will be updated together. Also the notion of "Change management" started changing to be more continuous deployment to production. Applications get started to get more complex as there were some services which were "always" production mode as they were being served from 3rd Party providers. Third party API consumption really became very popular. This really started moving the number of tiers from somewhere around 10 to more like 25-30 different tiers in an app.<br /><br /><b>MicroServices Era</b><br /><br />With the advent of Linux containers like Docker and microservice adoption, yet another reboot of applications is happening and this time at a faster pace than before. This is an interesting on-going era for applications. No longer a tier is a "component" of an application but it is more of a purpose driven "service" by itself. Every service is versioned, API -accessible, fully updatable on its own without impacting the rest of the application. This change is causing the number of tiers in a typical enterprise application to be now growing beyond 100s. I have heard some enterprises having about 300-400 microservices based tiers in thier application. Many of these microservices are 3rd party services. There are advantages like there is no single monolithic "waterfall" release of the application anymore. Things that previously had taken months or years to build, can now be build in hours or days. But on the downside there are just too many moving parts in the application now. Architectural changes of your data flows and use cases are now very expensive. Pre-deployment testing becomes difficult, Canary deployments becomes necessary to avoid risks of introducing bugs and taking down the whole application. While nothing is bad in evolution, it is just that thinking of how to manage applications will have to change based on the changing landscape.<br /><br /><br />In conclusion, applications have changed over the years, adapting the changes is necessary for business to catch up to competition and still retain their technology edge in the market.<br /><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah and Linux Containers: #SouthbayPUG Presentation<div dir="ltr" style="text-align: left;" trbidi="on">It was a great to talk about Linux Containers tonight at Southbay PostgreSQL User Group at Pivotal.<br />The slides are now posted online:<br /> and Linux Containers">PostgreSQL and Linux Containers</a> </strong> from <strong><a href="" target="_blank">Jignesh Shah</a></strong> </div></div><img src="" height="1" width="1" alt=""/>Jignesh Shah Mirror on the wall, Where's the data? In my Vol<div dir="ltr" style="text-align: left;" trbidi="on">When I first started working with docker last year, there was a clear pattern already out there the docker image itself only consists of application binary (and depending on the philosophy - the entire OS libraries that are required) and all application data goes in a volume.<br /><br />Also the concept called "<a href="" target="_blank">Data Container</a>" also seemed to be little popular at that time. Not everyone bought into that philosophy and there were various other patterns emerging out then on how people used volumes with their docker containers.<br /><br />One of the emerging pattern was (or still is) "Data Initialization if it does not exist" during container startup.<br />Let's face it, when we first start a docker container consisting of say PostgreSQL 9.4 database the volume is an empty file system. We then do an initdb and setup a database so that it is ready to serve. <br />The simplest way is to check if the data directory has data in it and if it does not have data, then run initdb and setup the most common best practices of the database and serve it up. <br /><br />Where's the simplest place to do this? In the entrypoint script of docker container of course.<br /><br />I did the same mistake in my jkshah/postgres:9.4 image too. In fact I still see that same pattern in the official <a href="" target="_blank">postgres</a> docker image also where it looks for PG_VERSION and if it does not exists then it runs initdb.<br /><br /><span style="font-family: "Courier New", Courier, monospace;">if [ ! -s "$PGDATA/PG_VERSION" ]; then<br /> gosu postgres initdb</span><br /><span style="font-family: Courier New;"> ...</span><br /><span style="font-family: Courier New;">fi</span><br /><br />This certainly has advantages:<br />1. Very simple to code the script.<br />2. Great Out of the box experience - You start the container up - the container sets itself up and it is ready to use.<br /><br />Lets look what happens next in real life enterprise usages. <br /><br />We got in scenarios while the applications using such databases are running but they lost all data in it. Hmm what's going wrong here? The application is working fine, the database is working fine, but all data is like it was freshly deployed and not something that was running well for 3-5 months.<br /><br />Let's look at various activities that an enterprise will typically do with such a data volume - file system on the host where PostgreSQL containers are running.<br />1. The host location of the volume itself will be a mounted file system coming off SAN or some storage device.<br />2. Enterprise will be backing up that file system on periodic intervals<br />3. On some cases they will be restoring that file system when required.<br />4. Sometimes the backend storage may have hiccups. (No ! That does not happen :-) )<br /><br />In any of the above cases, where a mount fails or mounts a wrong file system or if the restore fails, you could end up with an empty file system for a volume path. (Not all people had checks for this)<br /><br />Now when you start the PostgreSQL docker container on such a volume you will get a new database fully initialized. Most current automations that I have seen works such that in those cases even the application will fully initialize the database with its own schema and initial data and the application moves on like nothing is wrong here.<br /><br />In the above case it might seem that the application is working to all probes till a customer tries to login into the setup and find that they do not exist in the system . <br /><br />For DBAs the anal rule is "No Data" error is better than "Wrong/Lost Data" serviced out of a database (specially PostgreSQL users). For this reason, this particular pattern of database initialization is becoming an ANTI Pattern in my view specially for docker containers. A better approach is to have an entrypoint command specifically to do a setup(initialization) knowingly and then all subsequent starts should be called with another entrypoint command to specifically fail if it does not find the data.<br /><br />Of course again this is a philosophical view on how it should be handled. I would love to hear what people have to say about this.<br /><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah it a privilege to run a container in Docker?<div dir="ltr" style="text-align: left;" trbidi="on">Recently while working with various applications in a <a href="" target="_blank">docker</a> container, we came across few containers that will not run properly unless <a href="" target="_blank">privileged mode</a> is enabled. The privileged mode gives the container the same rights as host which means it can make changes on host where the container runs. (Huge difference compared to VM - Imagine your VM making changes to the hypervisor directly.)<br /><br />Of course privileged mode has its uses and I am definitely glad that it is available. However it is not a general purpose option to be used lightly. So imagine my surprise that one of the most common tools that is used in many enterprises now <a href="" target="_blank">Chef server</a> when running in a docker container also required <a href="" target="_blank">privileged</a> mode to run. There are various versions available but they all required the mode.<br /><br />While investigating Chef Server to see why it requires the mode I found it primarily requires it to set some ulimit parameters and a specific kernel parameter inside the container.<br /><br /><span style="font-family: "Courier New",Courier,monospace;">sysctl -w kernel.shmmax=17179869184</span><br /><br />Now before you say, aha simple lets change the value in the host itself and let the container pick up the value from the host itself.. Let me say been there .. it ain't gonna work. The reason it does not work is due to how Linux namespaces work with CLONEIPC. The net result is everytime a container is created a new namespace of System V IPC is setup with the default shmmax of 32MB. The default will be changed in a later Linux kernel to 4GB but of course like most companies there will not be patience to wait for the Linux kernel to show up let alone a certified Linux distro for production setups.<br /><br />There are few hacks to work it out as <a href="" target="_blank">Jerome</a> indicates in a <a href="" target="_blank">mailing list</a>. But of course none of them was something that was suitable.<br /><br />Now lets go back to the original command that needed to be executed which required. I have worked with those commands for years always to increase shared memory for databases that uses Sys V style of shared memory like Oracle, PostgreSQL (well till 9.2), etc.<br /><br />Guess what doing a little digging I did find PostgreSQL used as an embedded database in $CHEF_SERVER_INSTALL/embedded/bin/postgres. Checking the version of "postgres" binary confirmed it to be 9.2.<br /><br />Checking latest version of Chef server found it to be still using Postgres 9.2. Eventually ended up creating a custom image using Postgres 9.4 and voila got the container running without privileged mode. Thanks <a href="" target="_blank">Robert Haas</a>.<br /><br />It also means that as more and more PostgreSQL based containers are being used in containers, it is better to move to the latest version of PostgreSQL for a better experience.<br /><br /><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah 7, Docker, Postgres and DVDStore kit<div dir="ltr" style="text-align: left;" trbidi="on">Its been a long time since I have posted an entry. It has been a very busy year and more about that in a later post. Finally I had some time to try out new versions of Linux and new OSS technologies.<br /><br />I started to learn by installing the latest version of CentOS 7. CentOS closely follows RHEL 7 and coming from SLES 11 and older CentOS 6.5, I saw many new changes which are pretty interesting.<br /><br />New commands to learn immediately as I started navigating:<br /><span style="font-family: Courier New, Courier, monospace;">systemctl</span><br /><span style="font-family: Courier New, Courier, monospace;">firewall-cmd</span><br /><br />I admit that I missed my favorite files in <span style="font-family: Courier New, Courier, monospace;">/etc/init.d</span> and looking at new location of <span style="font-family: Courier New, Courier, monospace;">/etc/systemd/system/multi-user.target.wants/</span> will take me a while to get used to.<br /><br /><span style="font-family: Courier New, Courier, monospace;">firewall-cmd</span> actually was more welcome considering how hard I found to remember the exact rule syntax of <span style="font-family: Courier New, Courier, monospace;">iptables</span>.<br /><br />There is new Grub2 but honestly lately I do not even worry about it (which is a good thing). Apart from that I see XFS is the new default file system and LVM now has snapshot support for Ext4 and XFS and many more.<br /><br />However the biggest draw for me was the support for Linux Containers. As a Sun alumni, I was always draw to the battle of who did containers first and no longer worry about it, but as BSD Jails progressed to Solaris Containers to now the hottest technology: Docker container, it sure has its appeal.<br /><br />In order to install docker however you need the "Extras" CentOS 7 repository enabled. However docker is being updated faster so the "Extras" repository is getting old at 1.3 with the latest out (as of last week) is Docker 1.5. To get Docker 1.5 you will need to enable "virt7-testing" repository on CentOS 7<br /><div><br /></div>I took a shortcut to just create a file <span style="font-family: Courier New, Courier, monospace;">/etc/yum.repos.d/virt7-testing.repo</span> with the following contents in it.<br /><br /><div style="text-align: left;"><span style="font-family: Courier New, Courier, monospace;">[virt7-testing]</span></div><div style="text-align: left;"><span style="font-family: Courier New, Courier, monospace;">name=virt7-testing</span></div><div style="text-align: left;"><span style="font-family: Courier New, Courier, monospace;">baseurl=</span></div><div style="text-align: left;"><span style="font-family: Courier New, Courier, monospace;">enabled=1</span></div><div style="text-align: left;"><span style="font-family: Courier New, Courier, monospace;">gpgcheck=0</span></div><div><br /></div><div>Then I was ready to install docker as follows</div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;"># yum install docker</span></div><div><br /></div><div>I did find that it actually does not start the daemon immediately, so using the new systemctl command I enabled and then started the daemon</div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;"># systemctl enable docker</span></div><div><span style="font-family: Courier New, Courier, monospace;"># systemctl start docker</span></div><div><br /></div><div>We now have the setup ready. However what good is the setup unless you have something to demonstrate quickly. This is where I see Docker winning over other container technology and probably their differentiator. There is an "AppStore" for the container images available to download images. Of course you need a login to access the Docker Hub as it is called at <a href=""></a> (which is for free fortunately). </div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;"># docker login</span></div><div><br /></div><div>To login to the hub and now you are ready to get new images.</div><div>I have uploaded two images for the demonstration for today</div><div>1. A Standard Postgres 9.4 image</div><div>2. A DVDStore benchmark application image based on kit from <a href="" target="_blank"></a></div><div><br /></div><div>To download the images is as simple as pull</div><div><span style="font-family: Courier New, Courier, monospace;"># docker pull jkshah/postgres:9.4</span></div><div><span style="font-family: Courier New, Courier, monospace;"># docker pull jkshah/dvdstore</span></div><div><br /></div><div>Now lets see on how to deploy them. </div><div>For PostgreSQL 9.4 since it is a database it will require storage for "Persistent Data" so first we make a location on the host that can be used for storing the data.</div><div><br /></div><div><div><span style="font-family: Courier New, Courier, monospace;"># mkdir /hostpath/pgdata</span></div><div><br /></div><div>SELinux is enabled by default on CentOS 7 which means there is an additional step required to make the location read/write from Linux containers</div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;"># chcon -Rt svirt_sandbox_file_t /hostpath/pgdata</span></div><div><br /></div><div>Now we will create a container as a daemon which will map the container port to host port 5432 and setup a database with a username and password that we set. (Please do not use secret as password :-) )</div><div><span style="font-family: Courier New, Courier, monospace;"># docker run -d -p 5432:5432 --name postgres94 -v /hostpath/pgdata:/var/lib/postgresql/data -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=secret -t jkshah/postgres:9.4</span></div><div><br /></div><div><br /></div><div>Here now if you check <span style="font-family: Courier New, Courier, monospace;">/hostpath/pgdata </span>you will see the database files on the host.</div><div> </div><div>Now lets deploy an application using this database container.</div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;"># docker run -d -p 80:80 -–name dvdstore2 -–link postgres94:ds2db –-env DS2DBINIT=1 jkshah/dvdstore</span></div><div><br /></div><div>The above command starts another container based on the DVDStore image which expects a database "<span style="font-family: Courier New, Courier, monospace;">ds2db</span>" defined which is satisfied using the link option to link the database container created earlier. The application container also intiailizes the database so it is ready to serve requests at port 80 of the host. </div></div><div><br /></div><div>This opens up new avenues to now benchmark your PostgreSQL hardware easily. (Wait the load test driver code is still on Windows :-( )</div><div><br /></div><div><br /></div><div><br /></div><div><br /></div></div><img src="" height="1" width="1" alt=""/>Jignesh Shah from my sesion at PgConfEU<div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" style="text-align: left;" trbidi="on">I had recently done a <a href="" target="_blank">session at PgConf.EU</a>.<br /><br />It was interesting and encouraging to see the feedback from it.<br />Thanks to the people who took time to give the feedback. <br /><br /></div><h1>Session feedback: My experience with embedding PostgreSQL</h1><h3>Speaker: Jignesh Shah</h3>A total of 4 feedback entries have been submitted for this session.<br /><h2>Rankings</h2> /><br /><table border="1" cellpadding="3" cellspacing="0" style="font-size: small;"> <tbody><tr><th colspan="2">Topic importance</th></tr><tr><th>Rating</th><th>Count</th></tr><tr><td>1</td><td>0</td></tr><tr><td>2</td><td>0</td></tr><tr><td>3</td><td>1</td></tr><tr><td>4</td><td>0</td></tr><tr><td>5</td><td>3</td></tr></tbody></table>(5 is highest, 1 is lowest)<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="160" src="" width="320" /></a></div><br /><a href="" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"> </a> <br /><table border="1" cellpadding="3" cellspacing="0" style="font-size: small;"> <tbody><tr><th colspan="2"><br /><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><br />Content quality<="160" src="" width="320" /></a></div><br /><br /><br /><br /><br /> /><table border="1" cellpadding="3" cellspacing="0" style="font-size: small;"> <tbody><tr><th colspan="2"><div class="separator" style="clear: both; text-align: center;"></div>Speaker knowledge<" height="160" src="" width="320" /></a></div><br /><br /><table border="1" cellpadding="3" cellspacing="0" style="font-size: small;"> <tbody><tr><th colspan="2">Speaker quality</th></tr><tr><th>Rating</th><th>Count</th></tr><tr><td>1</td><td>0</td></tr><tr><td>2</td><td>0</td></tr><tr><td>3</td><td>0</td></tr><tr><td>4</td><td>1</td></tr><tr><td>5</td><td>3</td></tr></tbody></table>(5 is highest, 1 is lowest)<br /><br /><br /><h2>Comments</h2><ul><li>Very good presentation - IMHO please add Oracle License Costs to your slides. As on the first view - Business people wont understand that they are variable and WAY HIGHER as expected. </li><li>One of the best talks this year.</li></ul></div><img src="" height="1" width="1" alt=""/>Jignesh Shah experience with embedding PostgreSQL - #pgconfeu<div dir="ltr" style="text-align: left;" trbidi="on".<br />We will talk about business reasons,technical architecture of deployments, upgrades, security processes on how to work with embedded PostgreSQL databases. <br /><br /><br /><iframe frameborder="0" height="400" marginheight="0" marginwidth="0" scrolling="no" src="" width="476"></iframe><br /><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah replication? I need temp tables for my reports<div dir="ltr" style="text-align: left;" trbidi="on">One of the frequent things I hear that many times PostgreSQL users avoid running PostgreSQL replication because they want to offload reports that use temporary tables on the slaves. Since PostgreSQL replicas are pure read only, it cannot support temporary tables.<br /><br />There is one way to overcome this with postgres_fdw - PostgreSQL Foreign Data Wrapper which are improved in<a href="" target="_blank"> PostgreSQL 9.3</a> which is <a href="" target="_blank">now released</a>. <br /><ul style="text-align: left;"><li>Create a Master-Slave setup with PostgreSQL 9.3 (with synchronous or asynchronous replication as per your needs). </li><li>On the slave setup, setup another PostgreSQL 9.3 instance (with different port) with postgres_fdw and map all tables from slaves as foreign tables with same names as their remote counterparts.</li><li>Run reports which requires temporary tables using this new instance</li></ul>Of course there are few caveats for this setup<br /><ul style="text-align: left;"><li>Query plans: Currently they are still inefficient but as postgres_fdw improves, this will likely go away. Infact more usage of this use-case scenario will force it to be improved</li><li>Lot of data moving: Most DW reports do read lot of rows. However by setting it up on the same server most of it are loopback and dont go on the wire outside. </li><li>More Resources: This will do require more memory/cpu on the server but it is still cheaper since the management of such a server is still more simpler compared to other complex designs to achieve the same goal</li></ul>I would like to hear about your experiences on the same too so feel free to send me comments.</div><img src="" height="1" width="1" alt=""/>Jignesh Shah to do Postgres Replication and Failover in VMware vFabric Data Director 2.7?<div dir="ltr" style="text-align: left;" trbidi="on"><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">Last week VMware released vFabric Data Director 2.7. Among the<a href="" target="_blank"> many new features</a> for various database, I wish to give a little more insight into my favorite ones which are regarding Postgres. <o:p></o:p></span></div><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">One of the big feature add from a broad perspective is support of Postgres 9.2 based managed database servers along with replication.<span style="mso-spacerun: yes;"> </span>Lets look at how it is done in brief.</span></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;".</span></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">Next once the template is loaded into the system resource pool it will show up in Base DBVMs section in System->Manage and Monor-> Templates-> BaseDBVMs<o:p></o:p></span></div><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">Then you would<span style="mso-spacerun: yes;"> then </span>right click on the base DBVM and select “Convert to Base DB Template”. <span style="mso-spacerun: yes;"> </span>Here you also have a new feature to add more disks (think Tablespaces in PostgreSQL) to the template. In Data Director 2.7, disks are added at the template level.</span></div><span style="font-family: Calibri;"></span><br /><div class="separator" style="clear: both; text-align: center;"><span style="font-family: Calibri;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="" width="624" /></a></span></div><span style="font-family: Calibri;"></span><o:p></o:p><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;".</span></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">Note in the Resource bundle creation steps lies yet another new way to separate out IO on separate datastores since these may need different IO characteristics<o:p></o:p></span></div><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="432" src="" width="640" /></a></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"></div><div style="text-align: left;">The above image shows how the various types of datastores for your OS, Backup, Data and Logs (Data can be multiple location if you need multiple tablespaces)</div><div style="text-align: left;"><br /></div><div class="MsoNormal" style="margin: 0in 0in 10pt; text-align: left;"><span style="font-family: Calibri;">Now all the Orgs/Database groups using the resource bundle will see the new vPostgres 9.2 template.</span></div><div class="MsoNormal" style="margin: 0in 0in 10pt; text-align: left;"><span style="font-family: Calibri;">In a sample demo I created a database called MyDB using </span><span style="font-family: Calibri;">few wizard questions.</span></div><div class="MsoNormal" style="margin: 0in 0in 10pt; text-align: left;"><span style="font-family: Calibri;">Now on the DB List we do a right click on the database to create more replicas <o:p></o:p></span></div><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="481" src="" width="640" /></a></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><br /><span style="mso-no-proof: yes;"></span></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;".</span></div><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">The database dashboard also has a new portlet to show bit more information about the replication.</span></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="161" src="" width="640" /></a></div><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">To make a slave as a new master and it will give an option to move all the other slaves to the new master select as follows:</span></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="209" src="" width="640" /></a></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="129" src="" width="320" /></a></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><br /><span style="mso-no-proof: yes;"></span></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calibri;">After completion of the failover, the status shown will be similar to:</span></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="144" src="" width="640" /></a></div><div class="MsoNormal" style="margin: 0in 0in 10pt;"></div><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"><span style="font-family: Calib.<o:p></o:p></span></div>Of course one of the thing that it does not do is re-purpose the original Master as a slave of the new Master. For more details there is a perfect opportunity to find <a href="" target="_blank">Heikki Linnakangas from VMware at PGCon</a> in Ottawa this week and ask him the question after his session .. WHY??? :-)<br /><br /><div class="MsoNormal" style="margin: 0in 0in 10pt;"></div></div><img src="" height="1" width="1" alt=""/>Jignesh Shah can PostgreSQL 9.3 beta1 help you?<div dir="ltr" style="text-align: left;" trbidi="on"><a href="" target="_blank">PostgreSQL 9.3 beta1</a> is now available. Giving early access to software is always a good idea to test out evolutionary, revolutionary, radical ideas because unless it is field tested, it has not gone through its trial by fire to be proven gold.<br /><br />There are many new changes introduced in PostgreSQL 9.3 beta1 and I do have few favorites in them. <br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />Also new JSON functions help PostgreSQL on its evolution to be the Data Platform not just for relational data but also document data. <br /><br /><br />While I have barely scratched the surface of<a href="" target="_blank"> all the new features</a> in PostgreSQL 9.3 beta1, I am already excited with this release and the possibilities I see going forward in the world of data.<br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah 2013 - HA / Replication for PostgreSQL in Virtualized Environments<div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" style="text-align: left;" trbidi="on"><br />My presentation at PyPgDay 2013 on HA and Replication for PostgreSQL on Virtualized Environments<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" target="_blank"><img border="0" height="300" src="" width="400" /></a></div><br /><br /></div><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah Step Forward<div dir="ltr" style="text-align: left;" trbidi="on">Recently I upgraded my "lab" setup.<br />Now it currently looks as follows:<br /><br />* 2x Physical Hosts running vSphere 5.1 <br />* Controlled by vCenter 5.1 Server Appliance backed with embedded Postgres Database instance<br />* Monitored by vCenter Operations which has two embedded Postgres Database instance in the vApp<br />*To monitor my VMs, I installed vFabric Hyperic 5.0 also running embedded Postgres Database VM.<br />* DBaaS provider vFabric Data Director 2.5 also installed with its embedded Postgres database instance running too<br /><br />Now for my VMs: <br />* vFabric Postgres 9.1.6.0 VM integrated with vSphere HA<br />* My Linux Developer VM running PostgreSQL 9.2.1 <br /><br />If you get everything you need with Postgres, why even QA for other databases anymore?<br /><a href="" target="_blank">Well vFabric Hyperic took the first bold step forward</a>. <br /><br /><br /><br /><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah Oct 2012: DVDStore Benchmark and PostgreSQL<div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" style="text-align: left;" trbidi="on">I presented the DVDStore Benchmark at SFPUG yesterday night.<br />The presentation is available at <a href="" target="_blank"></a><br />The video is located at <a href="" target="_blank"></a><br /><br /></div><iframe frameborder="0" height="561" scrolling="no" src="" width="700"></iframe></div><img src="" height="1" width="1" alt=""/>Jignesh Shah 2012: DVDStore Benchmark and PostgreSQL<div dir="ltr" style="text-align: left;" trbidi="on">My slides to go with the Demo I did with<a href="" target="_blank"> DVDStore Benchmark and PostgreSQL</a> session.<br /><a href=""></a><br /><iframe frameborder="0" height="593" scrolling="no" src="" width="739"></iframe><br /><br />Other session presentations are available at<br /><br /><br /><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah @ VMware<div dir="ltr" style="text-align: left;" trbidi="on">Recently VMware vCenter Server Appliance 5.0 u1a was released with embedded Postgres based distribution. Check out the<a href="" target="_blank"> release notes</a>. <br /><br />Quote from release notes:<br /> "<strong>vCenter Server Appliance Database Support</strong>: The DB2 express embedded database provided with the vCenter Server Appliance has been replaced with VMware vPostgres database. This decreases the appliance footprint and reduces the time to deploy vCenter Server further."<br /><br />vCenter Server Appliance joins the growing list of VMware products embedding and/or supporting Postgres. <br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah 2012: OLTP Performance Benchmarks Overview<div dir="ltr" style="text-align: left;" trbidi="on">The slides from my presentation today.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" target="_blank"><img alt="" border="0" height="300" src="" title="PgCon 2012: OLTP Performance Benchmark Review - Jignesh Shah" width="400" /></a></div><br />or access it on the <a href="" target="_blank">PGCon Website</a>.</div><img src="" height="1" width="1" alt=""/>Jignesh Shah DVDStore with PostgreSQL<div dir="ltr" style="text-align: left;" trbidi="on">We now have support for PostgreSQL in the popular <a href="">DVDStore Benchmark</a> which stresses database using an emulated DVDStore e-Commerce website. DVDStore Benchmark is maintained by Dave Jaffe (Dell) and <a href="">Todd Muirhead</a> (VMware). It is an open source database test kit. The beauty of the benchmark kit is it allows the same web application being deployed either as <br /><ol style="text-align: left;"><li>Java/Tomcat and connect to the database, </li><li>Web Server/PHP and connect to the database, </li><li>IIS/ASP.NET connect to the database or </li><li>Direct connect to the database and invoking the business logic as stored procedures stored on the database itself. </li></ol><br />Currently the PostgreSQL implementation details are as follows<br /><ol style="text-align: left;"><li>Java/Tomcat using PostgreSQL JDBC driver, </li><li>Web Server/PHP using PHP-postgres modules which uses libpq</li><li>Currently there is noIIS/ASP.NET web app implementation for PostgreSQL</li><li> Direct connect to PostgreSQL database and business logic implemented in stored procedures however the driver is implemented using .NET C# and requires Npgsql 2.0.11.0</li></ol><br />Setup instructions for the database are relatively quite easy.<br /><ol style="text-align: left;"><li>Download <a href="">ds21.tar.gz</a> and also <a href="">ds21_postgresql.tar.gz</a> from <a href=""></a></li><li>Unzip them on the system running PostgreSQL</li><li>The default data size is 10MB. If you want a different size execute <span style="font-family: "Courier New", Courier, monospace;">'perl Install_DVDStore.pl'</span> in the ds2 directory. (Expects perl to be available on the system. I used the option 100, MB , PGSQL, LINUX respectively for the options.)</li><li>Assuming you are logged on as the DB Owner and the database is on the localhost at port 5432, execute the script <span style="font-family: "Courier New", Courier, monospace;">pgsql_create_all.sh</span> in the ds2/pgsqlds2 directory. It will create a database "ds2", two users "ds2/ds2" and "web/web", create tables, load tables, create indexes, update sequences and finally run analyze. (The script needs to be modified slighly if the database is already hardened and you want to control the creation of database and the users.)</li></ol><br />Setup for the actual load driver is probably easiest on another Windows platform as follows as it was designed for .NET platform.<br /><ol style="text-align: left;"><li>Download and install Windows SDK v6.1 and .NET 3.5 framework on a Windows Client machine. </li><li>Once installed start the CMD prompt from <span style="font-family: "Courier New", Courier, monospace;">Programs-> Windows SDKv6.1-> CMD Prompt</span>. </li><li>Verify the above CMD prompt has path setup for gacutil in windows (Try <span style="font-family: "Courier New", Courier, monospace;">'gacutil/l'</span>)</li><li>Download Npgsql 2.0.11 for msnet35 and install the dlls using the gacutil.exe (Note other versions of Npgsql may have issues.)</li><ul style="text-align: left;"><li><span style="font-family: "Courier New", Courier, monospace;"> gacutil/i Npgsql.dll </span></li><li><span style="font-family: "Courier New", Courier, monospace;"> gacutil/i Mono.security.dll </span></li><li><span style="font-family: "Courier New", Courier, monospace;"> gacutil/i policy-2.0.Npgsql.dll</span></li></ul></ol><br /><br />With the above setup you can use the <span style="font-family: "Courier New", Courier, monospace;">ds2webdriver.exe</span> in ds2/drivers or the direct <span style="font-family: "Courier New", Courier, monospace;">ds2pgsqldriver.exe</span> in ds2/pgsqlds2. More on running the benchmark driver itself in another post.<br /><div style="text-align: left;"></div></div><img src="" height="1" width="1" alt=""/>Jignesh Shah does PostgreSQL HA works in vFabric Data Director?<div dir="ltr" style="text-align: left;" trbidi="on">Databases go down due to various reasons. Some reasons are known and some unknown.<br />Common reasons are hardware failure, software failure, database unresponsive, etc. What is considered as a failure is actually one of the tasks. Various DBA's use a simple select statement as a test to make sure that the database is up and working. But what does one do if that simple select statement fails. I remembers years ago I worked on a module which will start paging engineers in a sequence (and eventually their managers if the engineers failed to respond back in a certain expected way). In this email/text age, scripts will start sending out emails and text messages. What we are is basically in the Event->React-> Respond mode of operation.<br /><br />However true HA needs to lower downtime which can only be done by having the mode of operation as Event->Respond->React. To explain that when such an event happens, do an automated response first and then React to wake the engineers up :-)<br /><br />How do you set this up in vFabric Data Director? This can be achieved by selecting the database properties, selecting the Database Configuration tab and set "High Availability" to "Enable". This is also refered as One-Click HA setting.<br /><br />Of course this assumes that your virtual Data Cluster is set properly for providing the high availability services. How do you set it up properly? Well you need atleast two ESXi Hosts so if one host fails, the other can cover for it. Also vSphere HA property has been enabled in the Virtual Data Center Cluster. Note these settings are all "required" for vFabric Database setup and a "supported" setup does mandate atleast two ESXi Hosts in order for HA to work.<br /><br />Now that we have gone over the setup requirements, lets go over the scenarios on how the application or user sees it. A user is connected to the database using the connection string. Something happens and the database goes down and the connection drops. Chances are if you reconnect again immediately it may fail. However with certain time which is expected to be less than 5 minutes (which we call our Recovery Time Objective or RTO) by default, if you try again you can connect to the database again. <br /><br />So what happens in the background? Well if it was Magic, we would not tell you. But it is not really magic though it feels like that. Here is what will typically happen in the background.<br />For some reason the PostgreSQL fails to respond anymore it could be a "hung" situation or the PostgreSQL server has died. There is a small heartbeat monitor which figures out the status of the database. If it notices that the hung situation or no DB server process, it will try to restart the database. If the database cannot be restarted (because the whole VM appliance cannot respond anymore), it will in novice terms kill the virtual machine. The vCenter Server which has its own heartbeat on the VM appliance will see that the Virtual Machine has died (irrespective of the Database Monitor which may not be working if the whole host dies), the vCenter Server will restart the VM appliance on another server.<br /><br />Since shared-storage is a requirement, the VM appliance will start on another host and it will feel like a reboot. Once the VM starts, the PostgreSQL server process will be restarted. At this point of time, the PostgreSQL server goes into recovery mode. The biggest question at this point of time typically is how long will the recovery mode take. Typically based on internal tests even with the heaviest workload on 8vCPU, the recovery time can finish within the checkpoint_timeout settings which means our Recovery Time Objective is guided by checkpoint_timeout + heartbeat latency + the time to restart the VM on another hosts. Overall we try to fit that into our Recovery Time Objective of 5 minutes.<br /><br />Great the virtual machine has restarted and the database has done its recovery and working again. Now what? Well dont forget in this cloud setup, the easiest thing is to use DHCP addresses. Unfortunately DHCP addresses are not guaranteed to be same after reboot . Plus rebooting on a different host makes it more complex to get the same IP. This IP address change can cause the Database connectivity to be lost to the actual end user. In order to shield the end users from this complexity, we sort of implemented our own Database Name Server. However this can only work by modifying the clients which references the database using this "Virtual Hosts" format so that the clients can always find their intended database without really worrying about where it is running. A minor change in the PostgreSQL clients but a huge complexity reducer for end users to fix their IP addresses or domain names to the changed location.<br /><br />Aha now this explains why vPostgres ships their own clients and libpq library which is API compatible with standard PostgreSQL libpq library.The libpq library is actually 100% compatible with standard PostgreSQL Libpq library. The only addition it has is the feature of Virtual Hosts which is critical for HA to work seemlessly without the users being concerned about the actual IP of the database. Without the change, HA will not work on the framework. Since it is 100% compatible, if an application works standard libpq it will work with vPostgres libpq. Similar changes are also done in the JDBC driver and ODBC Driver for vPostgres so HA is supported across all supported clients.<br /><br />That said if you use standard libpq/psql and other standard clients and you know the IP Address of the vPostgres database and connect to it via that IP address (and not the virtual host string) it will still work flawlessly. However if the database goes down and restarts with a new IP address then the client will have no ability to figure out the new IP address and will have to bug the Administrator to figure out the new IP address. <br /><br />Though for folks familiar with vSphere terminology, HA is not FT - Fault Tolerant which is a different take on HA to further reduce downtime from minutes to seconds. More on that in future.<br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah PostgreSQL Server on Micro Cloud Foundry<div dir="ltr" style="text-align: left;" trbidi="on">With the recent news that <a href="">PostgreSQL is now available in the Micro Cloud Foundry</a>, I decided to take it for a test spin. I downloaded the <a href="">Micro Cloud Foundry VM</a> zip file which is about 1.0GB big. After downloading it I unzipped it on my MacBookPro and use VMware Fusion 4.0.2 to open the VM. As the VM booted up the console shows a message<br /><div style="font-family: "Courier New",Courier,monospace;"><br /></div><div style="font-family: "Courier New",Courier,monospace;">Micro Cloud Foundry not configured</div><br />I selected the option 1 to configure the Micro Cloud. It asked me to configure my VM user password, Networking (DHCP or Static) and then asked me to enter my Cloud Foundry configuration token which was provided to me after I had created a <span style="font-family: "Courier New",Courier,monospace;">pgtest.cloudfoundry.me</span> domain just before the download.<br /><br />It took about 5 minutes to setup the cloud <br /><br />After the setup: I got my micro cloud foundry setup with my local IP (looked like a bridge connection rather than NAT).<br /><br />Then I installed the VMC tool on my Mac using (Need Ruby)<br />(NOTE: Skip directly to ssh part if you donot want to install Ruby/vmc)<br /><br /><div style="font-family: "Courier New",Courier,monospace;">$ gem install vmc</div><br /><div style="font-family: "Courier New",Courier,monospace;">$ vmc target</div><br />Got me connected to my micro cloud.<br />Then I did a<br /><div style="font-family: "Courier New",Courier,monospace;">$ vmc register</div>to create my user account using a email id and password<br />Then I logged into the MicroCloud using<br /><div style="font-family: "Courier New",Courier,monospace;">$ vmc login</div><br />Now when I do the following I see the PostgreSQL Service available with other databases also.<br /><br /><div style="font-family: "Courier New",Courier,monospace;">$ vmc services<br /><br />============== System Services ==============<br /><br />+------------+---------+---------------------------------------+<br />| Service | Version | Description |<br />+------------+---------+---------------------------------------+<br />| mongodb | 1.8 | MongoDB NoSQL store |<br />| mysql | 5.1 | MySQL database service |<br />| postgresql | 9.0 | PostgreSQL database service (vFabric) |<br />| rabbitmq | 2.4 | RabbitMQ messaging service |<br />| redis | 2.2 | Redis key-value store service |<br />+------------+---------+---------------------------------------+<br /><br />=========== Provisioned Services ============<br /></div>As you can see there are no provisioned services currently.<br /><br /><br />Here if you are like a Java/Spring developer you want to creating an application using Xin Li's post on "<a href="">PostgreSQL for Micro Cloud Foundry- Spring Tutorial</a>".<br /><br />I am not interested in developing Java applications but I want access to the postgresql server directly.<br /><br />Now comes the ssh part. <br /><br />Currently the PostgreSQL server is not exposed externally from the Micro Cloud.<br />But on the console of Micro Cloud VM, you can configure the password of vcap user. Which means now you have ssh access to the Micro Cloud VM.<br /><br /><div style="font-family: "Courier New",Courier,monospace;">$ ssh vcap@mircrocloudip</div><br /><span style="font-family: "Courier New",Courier,monospace;">$ cd /var/vcap/store/postgresql</span><br /><div style="font-family: "Courier New",Courier,monospace;">$ vi postgresql.conf </div><div style="font-family: "Courier New",Courier,monospace;"><br /></div>and edit listen_address to add your database client ip address out there.<br />For my demo setup I just opened it to all<br /><div style="font-family: "Courier New",Courier,monospace;">listen_addresses='*'</div><br />Next assign a Postgres password for the "vcap" user<br /><div style="font-family: "Courier New",Courier,monospace;">$ /var/vcap/packages/postgresql/bin/psql -d postgres<br />psql (9.0.4)<br />Type "help" for help.<br /><br />postgres=# ALTER USER vcap WITH PASSWORD 'secret';</div><div style="font-family: "Courier New",Courier,monospace;">ALTER ROLE</div><div style="font-family: "Courier New",Courier,monospace;">postgres=#\q</div><br />Now I exit from Micro Cloud VM and using the console I restart the services.<br />Now the PostgreSQL service can be accessed from postgres client anywhere.<br /><br />For example from a Macbook Pro<br /><br /><span style="font-family: "Courier New",Courier,monospace;">$ psql -h microcloudip -d postgres -U vcap</span><br /><span style="font-family: "Courier New",Courier,monospace;">Password for user vcap: </span><br /><span style="font-family: "Courier New",Courier,monospace;">psql (9.0.5, server 9.0.4)</span><br /><span style="font-family: "Courier New",Courier,monospace;">Type "help" for help.</span><br /><br /><span style="font-family: "Courier New",Courier,monospace;">postgres=# </span><br /><br /><br />Try it out!<br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah Data Director - All in a Box setup<div dir="ltr" style="text-align: left;" trbidi="on">vFabric Data Director 1.0 is available for download on the <a href="">VMware download website</a>. Generally the question we get a lot is on how to do a "small" setup for either a departmental setup or trial setup which is actually small enough to fit in a beefy workstation or a small server. Often time this helps people to evaluate the features of Data Director before doing the "standard" HA setup. Maybe it is only for tests/dev databases where one does not want to invest too much in the infrastructure setup itself..<br /><br />So here is one such way of doing a "small" setup of vFabric Data Director for test/dev/qa databases.<br />(Note: This is going to be a long blog post)<br /><br /><b>What do you need?</b><br /><ol style="text-align: left;"><li>A beefy Workstation or departmental Server with lots of RAM and lots of Storage and atleast two network adapter (Even though only one need be connected to the departmental network)</li><li>ESXi V5.0 installation CD (Software)</li><li>vCenter Virtual Appliance/Virtual Machine </li><li>DHCP Server Virtual Machine</li><li>vFabric Data Director Virtual Appliance Image</li><li>Preferably atleast one static IP Address on your departmental network for DB Name Server or have Dynamic DNS on your departmental network</li><li>License Keys - Use your VMware contacts.</li></ol><br /><b>Step I: Preparing the Workstation </b><br />On my test setup I had 12GB of RAM with 2x Quad Core x86_64 chips with 5 disks in it. Since this is my whole setup, the more memory I get, the merrier I am with the setup. It is recommended that you have some sort of Raid controller on the setup and have ability to create multiple LUN devices that will be exposed to the ESXi server. On my setup I had about one disk dedicated to ESXi and for other disks I created a RAID-5 LUN (RAID-10 is preferred but I did not have enough space on my demo setup). If I had more Storage available I would do two setups with RAID-10 setup and a RAID-0 setup which can be used as backup datastore. The RAID preferences depends on individual needs on what to trade off (performance , availability, capacity).<br /><br /><b>Step II: Installing ESXi 5.0 </b><br />Using the ESXi V5.0 installation CD, I installed ESXi on the first logical device and eventually setup the RAID protected device as a datastore that ESXi can use.<br /><br /><b>Step III: Install vCenter Virtual Machine</b><br />Here one can use the vCenter Virtual Appliance available also. On my demo setup I had used a vCenter Server based on Windows Server 2003 since that was available. Installation of vCenter Server itself can be its own blog entry and I will leave that to experts. For my purpose I had setup vCenter Server setup done in a virtual machine.<br /><br /><b>Step IV: Setting up vCenter Server for our task</b><br />This is where things are bit different for this special all in a box setup. The idea of setting up is to do vFabric Data Director Appliance which includes the hardware. Hence the idea is only the management console and the databases that it deploys are exposed outside (of course the ESXi also has to be visible outside to set this up) and all other infrastructure related things are hidden within this appliance. This is where two network adapters will come in play. Lets go first with the steps and then a bit of explanation on why do it this way.<br />I am assuming that the ESXi Server and vCenter VM has network connected to the live network adapter.<br /><ul style="text-align: left;"><li>Connect to the vCenter through vSphere GUI or through the webclient. </li><li>Create a new DataCenter. </li><li>Create a new Cluster</li><li>Add the ESXi Host to this cluster</li><li>Edit Settings for the Cluster to Enable</li><ul><li> vSphere HA (even though we cannot do it on a single Host)</li><li>vSphere DRS </li><li>"VM and Application Monitoring" in VM Monitoring</li></ul><li>Create a Distributed vSwitch as follows: </li><ul><li>Go to networking in Inventory you will see your corporate network called probably "VM Network"</li><li>Add a new distributed vSwitch in the section where you have to add a physical Network Adapter, select the Network Adapter which is not plugged into the departmental network (Skip creating an automatic port group for the switch)</li><li>Now for the dvSwitch created, create two port Groups "vCenter Network" and "Internal Network"</li></ul><li>For the ESXi host create a vmKernel port in "vCenter Network" portgroup with a static IP address 192.168.2.2</li><li>For the vCenter VM, create a new network adapter in the "vCenter Network" port group with a static IP of 192.168.2.1</li><li>Change the Managed IP of vCenter Server (Administration->vCenter Server Settings->Runtime Settings) to 192.169.2.1</li><li>Make sure vCenter server can still access the ESXi server through the new "vCenter Network" portgroup</li><li>Setup DHCP Server Appliance such that its LAN network is on "Internal Network"</li><ul><li>I had setup DHCP Server such that its own IP is 192.168.1.1 and it does DHCP on the network from range 192.168.1.5 to 192.168.1.250 (for my demo setup)</li></ul></ul><br /><b>Step V: Deploy vFabric Data Director OVA Template </b><br /><ul style="text-align: left;"><li>Using the vSphere Client (connected to our vCenter Server) deploy the vFabric Data Director OVA template. </li><li>The setup wizard will ask you to select the network for vCenter and the Management console. For the vCenter Network select the "vCenter Network" portgroup and for the Management Console, select the "VM Network" which is the live departmental network</li><li>If your setup is like mine, I do not have access to static IP adddress in the deparmental network so I just leave the next screen at its defaults to use DHCP and finish the deployment. </li></ul>Once the deployment finishes there will be a new vApp called VMware Data Director.<br /><ul style="text-align: left;"><li> Start the vAPP. Once the vAPP starts, expand the "+" sign and select to the Management Server VM. </li><li>Select the "Summary" tab of Management Server and wait till it shows an IP address.</li><li>Enter that IP address in a browser and you should see message "This connection is untrusted" depending on your browse type, add it to your exceptions and then it should take you to License agreement screen. </li></ul><br /><b>Step VI: Setup vFabric Data Director</b><br /><ul style="text-align: left;"><li>Read and accept the License agreement to proceed. </li><li>Next create an administrator account.</li><li>On the next screen since this is a small setup, I selected the Global User Management Mode</li><li>Setup the Branding as required on the next screen </li><li>Setup the SMTP server information if available (needed for user password resets) (You also need outgoing email id for a successful setup of SMTP )</li><li>On the next screen you have to setup vCenter Network Information. Since we dont have any DHCP on our "vCenter Network" portgroup, edit Network adapter settings and select "Static" with netmask information 255.255.255.0</li><li>Set static IP addresses 192.168.2.3 for Management server and 192.168.2.4 for DB Name Server</li><li>On the next screen change Internal Network to select "Internal Network" portgroup and leave DB Name Server Network as the "VM Network" which is the departmental network.</li><li>On the following screen, select the network settings of "Internal Network" DHCP should be already selected. Also check Static and add the network mask as 255.255.255.0</li><li>For Management Server - Internal Network adapter, select static IP address and set it to 192.168.1.3 </li><li>For DB Name Server - Internal Network adapter, select static IP address and set it to 192.168.1.4</li><li> <i>Warning</i>: This next bit is where you use your one static IP address or Dynamic DNS based FQDN requirement. We still have to provide DB Name Server - DB Name Service Network Adapter. If you have any influence on your IT, get a static IP address for this one. If you get the static IP, then click the Departmental "VM Network" setup and select static IP address with the associate Gateway, netmask and DNS Server setup. Then set the static IP address for DB Name Server - DB Name Service Network Adapter with the static IP address that you get from your IT..</li><li>Next enter your Evaluation License keys for vFabric Data Director and vFabric Postgres</li><li>Finally verify information on the summary page and then click Finish</li><li>You should get a login screen if it sets up successfully</li></ul><u><i>Note</i></u>: The most tricky bit is getting the IP address from IT. If for some reasons you do not have a static IP address, fake a fully qualified domain name for DHCP. Once setup and you get a login screen. Figure out the DHCP IP allocated to DB Name Server using vSphere Client (It is first IP address that shows in the Summary tab of DB Name Server VM). Enter using your administrator account credentials, go to "Administration" tab. Select Settings-> Networking setup. Select Edit Network Setup and step through the setup again and change your fakeFQDN with the DHCP IP address and press finish. Of course this is a hack and not recommended since DHCP IP addresses can change anytime if the lease is up or the system is rebooted and other network policies.<br /><br /><b>Step VII: Setting Up an Resource Bundle in vFabric Data Director</b><br />For this we need a special Resource Pool in our Virtual Data Center<br /><ul style="text-align: left;"><li>Using vSphere Client we create a resource Pool "Resource Bundle1" in the data center</li><li>Edit its settings such that it has reservations and limits matching for both CPU and memory</li><li>Also "Unlimited" should not be checked for both CPU and Memory. </li><li>In my demo setup I set CPU reservations and limits to 4096MB and Memory reservations and limits to 4096 MB.</li></ul>Enter the vFabric Management Console using your administrator credentials and go to "Manage & Monitor" tab.<br /><ul style="text-align: left;"><li> Select "Resource Bundle" and create a new resource Bundle "ResourceBundle1".</li><li> If the setup is right the next screen should show you the CPU/Memory Resource Pool that we created "Resource Bundle1" </li><li>Next select the RAID protected datastore and a size chunk off it for Database Storage. Select any alternative or the same datastore for "Backup Storage" with a sizeable chunk. In my demo I selected my Raid5 based datastore and 100GB sizes for both.</li><li>Next select the "VM Network" which is my departmental network through which uses will access the database. </li><li>Click Finish to setup the Resource Bundle.</li></ul><br /><br /><b>Step VII: Setup an Organization in vFabric Data Director</b><br />In "Manage&Monitor" select Organizations and create "+" a new organization called "DataDirectorOrg".<br /><ul style="text-align: left;"><li>On the next screen you could select an new user or in my case I used "Choose an existing user" and used my administrator account to manage the Organization also.</li><li>Next I selected the resource Bundle I just created (need to select "Choose an existing Resource Bundle" to see the resource bundle) </li><li>click Finish.</li></ul>Once created there will be the new Org displayed. If you select it once, the link becomes active. If you then select the active link again it will open a New tab for the Organization for our next step.<br /><br /><br /><b>Step VIII: Setup a Database Group</b><br />Next we have to setup a database group.<br /><ul style="text-align: left;"><li>In the org tab select "Manage&Monitor" tab to see the list of databases (which is empty). </li><li>Select the second tab "Database Groups" to see the empty group list</li><li>Create ("+" ) a new database group "DBGroup1" where I selected half of my datastore resources assigned for this group leaving the rest of the entries at default.</li></ul><br /><br /><b>Step IX: Create a database</b><br /><ul style="text-align: left;"><li>Select and enter the database group we just created.</li><li>Create ("+") a new database "dbtest" with owner credentials "dba" and password.</li><li>Wait till deployment of the database succeeds and "dbtest" is running. </li><li>Once running highlight it , right click to see the properties and get the UUID and Name. The client also needs the IP address of the DB Name server.<br /></li></ul>Here is an image of the distributed vSwitch from vSphere client on my demo box.<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="480" src="" width="640" /></a></div><br /><b><br /></b><br /><b><br /></b><br /><b>Step X: Connect to the database from a client</b><br /><a href="">Download vPostgres Clients for your platform</a>. Then using psql from the client connect to the database similar to the following example <br /><div style="font-family: "Courier New",Courier,monospace;">psql -h {dd9fce1e-db46-4a08-99a1-e9023b8239fe}.129.55.555.55 -d dbtest1 -U dba</div><br />It should prompt for the dba password and now you are connected to the database and the setup is working. Check out my previous blog entry on how to <a href="">use vPostgres Clients</a>. <br /><br />Finally now the setup of vFabric Data Director all in a box setup is working and tested.<br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah 2011 - Using vFabric Postgres - A DB User's Perspective<div dir="ltr" style="text-align: left;" trbidi="on">Here are my slides from my #PGWest 2011 Presentation " Using vFabric Postgres - A DB User's Perspective" for vPostgres Databases as deployed by vFabric Data Director. <br /><br /><iframe frameborder="0" height="506" scrolling="no" src="" width="640"></iframe></div><img src="" height="1" width="1" alt=""/>Jignesh Shah Stop: #PgWest 2011 - San Jose<div dir="ltr" style="text-align: left;" trbidi="on">Returned back from a great #pgopen in Chicago. It was nice to also see and meet again senior VMware executives, PostgreSQL community members and lot of folks (aka customers or potential customers ) who use PostgreSQL as key databases in their IT setup in the conference. <br /><br />Next stop now is #PgWest 2011 in San Jose starting on Septeber 27,2011. This year again #PgWest is in San Jose, California.<br /><br />At this conference, I am presenting my first ever "<a href="">Using vPostgres - A DB User perspective</a>". The gist of this presentation is on how to use the vFabric Postgres client with the vFabric Postgres server deployed by vFabric Data Director. There are some small differences on how the client works compared to community PostgreSQL and we will go over those in the session on exactly how it works, and see on how you use it for running and developing your own applications with it.<br /><br />Also Alex Mirgorodskiy, VMware will be first time presenting in a PostgreSQL conference (that I am aware of at this point of time) on "<a href="">vFabric Postgres Database Internals</a>". In this session Alex will go over the subtle tansparent changes which makes vFabric Postgres so easy to deploy, manage and perform in the vFabric Data Director world. Not to steal his thunder but this will cover the new Elastic Database Memory in detail. <br /><br />Bill Hodak, VMware will present about <a href="">vFabric Data Director</a> itself on how it leverages the features of PostgreSQL and provide a management framework over it to provide enterprise framework and provide self-service features making it easy for even folks who donot know a lot about PostgreSQL database itself to deploy, tune, monitor, backup, restore, clone the database instances. <br /><br />And to give an overview of VMware's commitment to PostgreSQL Community, Charles Fan, Sr.VP - VMware R&D will be presenting the<a href=""> keynote at #PgWest</a> 2011.<br /><br />Overall pretty excited about the conference and to meet lot of new people in the bay area.</div><img src="" height="1" width="1" alt=""/>Jignesh Shah PostgreSQL on Virtual Environments - #pgopen 2011<div dir="ltr" style="text-align: left;" trbidi="on">Slides from my presentation at Postgres Open 2011 (#pgopen11) in Chicago.<br /><br /><iframe frameborder="0" height="506" scrolling="no" src="" width="640"></iframe><br /><br /></div><img src="" height="1" width="1" alt=""/>Jignesh Shah
|
http://feeds.feedburner.com/JigneshShahsBlog?format=xml
|
CC-MAIN-2017-04
|
refinedweb
| 12,267
| 50.16
|
Marketo is a leader in marketing automation. Using our Marketo source, we will load your campaigns, emails, leads and other collections into your data warehouse.
This will allow you to write SQL to analyze your analyze your email marketing campaigns ROI, or join your email data to other data sources like web and mobile events, Salesforce, and Zendesk to tie nurture emails to re-activation rates in your app.
This is an Object Cloud Source which can export data from its third party tool and import it directly into your Segment warehouse.
NOTE: Marketo is currently in beta and this doc was last updated on April 30, 2018. This means that there may still be some bugs for us to iron out and we’re excited to hear your thoughts. If you have any feedback to help us improve the Source and its documentation, and please let us know!
Getting Started
Permissions
You will need Admin permissions to your Marketo account.
Add a new Marketo source
- From your workspace’s
sourcespage, click
add source.
- Choose Marketo.
- Give the source a nickname and a schema name. The nickname will be used to designate the source in the Segment interface, and the schema name is the namespace you’ll be querying against in your warehouse. Both can be whatever you like, but we recommend sticking to something that reflects the source itself, like Marketo for nickname and marketo or marketo_prod for the schema name.
- Configure your Marketo source with the required settings (see section below for details)
Configure your Marketo Source
- Open Marketo
- Go to Admin > Munchkin to find your Munchkin Account ID
- Go to Admin > LaunchPoint a. If you don’t already have a REST service setup, follow these steps. b. Then, copy the “Client ID” and “Client Secret” parameters.
c. Paste the “Client ID” and “Client Secret” into the Segment Marketo source settings.
You’re done! Data should start flowing into your Warehouse in the next few hours.
Components
Sync
The Marketo source is built with a sync component, which means we’ll make requests to their API on your behalf on a 3 hour interval to pull the latest data into Segment. In the initial sync, we’ll grab all the Marketo objects (and their corresponding properties) according to the Collections Table below. The objects will be written into a separate schema, corresponding to the source instance’s schema name you designated upon creation (ie. my_source.charges).
Our sync component uses an upsert API, so the data in your warehouse loaded via sync will reflect the latest state of the corresponding resource in Marketo. For example, if
first_name goes from
Jess to
Jessica between syncs, on its next sync that field will be
Jessica..
Collection Properties
Leads
Campaigns
Landing Pages
Lists
Lead Activities
Lead Activity Attributes
Lead Activity Types
Lead Activity Type Attributes
Programs
Segmentations
Segments
Adding Destinations
Currently, Warehouses are the only supported destination for object-cloud sources
FAQs
How many API calls will the Segment source use?
The Marketo API has different limits for the number of objects returned by different endpoints, but usually 100-300 objects per call.
At setup time, you have the option to specify a cap to the API calls that our source can consume. If no cap is specified, we will by default consume as many API calls that are available to sync the entire source.
We also use the Lead Activities bulk API to reduce the number of requests needed to sync the data; this however, also has a limit of 500MB worth of files downloaded per day.
If your source requires more than 10k calls or over 500MB from the bulk API to sync, we will continue the sync the following day when a new batch of API calls are available.
If you have other applications that use the Marketo API, this can interfere with their ability to make requests.
What Marketo API are you using?
We’re primarily using the REST API, but also use the Lead Activity Bulk API to reduce the number of requests needed to sync.
Can I get other collections not default synced by the source?
Yes! Please contact us to request additional collections.
Can I get other columns not default synced by the source?
Yes! For leads and activities, we’ve introduced a custom fields setting where you can enter comma-separated (no spaces, etc.) custom fields to sync by their REST API name.
By default, we only sync the following fields on the leads collection:
- id
- createdAt
- updatedAt
You can find a full list of standard fields and their REST API names here. If there are other fields you’re interested in, contact us and we’ll get you setup.
If you have any questions, or see anywhere we can improve our documentation, please let us know!
|
https://segment.com/docs/sources/cloud-apps/marketo/
|
CC-MAIN-2018-47
|
refinedweb
| 804
| 59.43
|
Playing the Nut/OS Configuration Game
Initially Nut/OS had been written for a fixed hardware, the Ethernut 1 with an ATmega103 MCU and an RTL8019AS Ethernet controller. And the only supported development environment had been AVRGCC running on the Windows PC. Good old days.
Today we have to support different targets with different CPUs, Ethernet controllers, memory layouts and I/O hardware as well as different development platforms with different compilers. Thus, system configuration became an important part.
Since Nut/OS 3.9, a GUI became available to simplify the configuration task. The Nut/OS Software Manual provides a step by step guide on how to use this tool.
In this paper I will present some more details about the possibilities to configure the system and how the Configurator uses these capabibilities.
The Make Tool
Regardless of which development environment is used to build Nut/OS, GNU Make takes over the top level control. Explaining this tool in detail is beyond the scope of this paper and to many developers of embedded systems it looks like C to PASCAL programmers, quite cryptic. But as often, the number of options make a tool look complicated while the main function is quite simple.
When started without any option, Make will look for a file named Makefile, interpret it and perform the related actions. Some Makefiles may contain weird sequencies of characters, but all of them contain something like
target: dependencies actions
target,
dependenciesand
actionsare required. The three items used here are just placeholders. A real example may look like
simple.hex: simple.c simple.h avr-gcc -c -mmcu=atmega128 simple.c -o simple.o avr-gcc simple.o -mmcu=atmega128 -lnutdev -lnutos -o simple.elf avr-objcopy -O ihex simple.elf simple.hex
You may now argue, that this could be done by a simple batch file or shell script. You are probably right. Now imagine, what a large number of actions would be required to compile all Nut/OS source files for all supported platforms, if we would do it this way. Make simplifies this by allowing us to specify general rules like
%o : %c avr-gcc -c -mmcu=atmega128 $< -o $@ %elf: %o avr-gcc $< -mmcu=atmega128 -lnutdev -lnutos -o $@ %hex: %elf avr-objcopy -O ihex $< $@
simple.hex: simple.c simple.h
simple.hexfrom
simple.cand
simple.h. That's cool, isn't it?
Another nice feature of Make is, that it checks automatically,
which actions are required after you modified something. In other
words, if you edit
simple.h, save your changes and
run Make again, it will run all three steps again. If you modified
anything else but neither
simple.c or
simple.h,
then Make will keep the already existing
simple.hex.
However, the Nut/OS Makefiles are incomplete here, because they do not list all dependencies. All header files are excluded. Thus, if any header file is changed, you need to run
make clean make
cleanis an explicit target given on the command line. Somewhere in the Makefile there is something found like
clean: rm *.o *.hex *.elf
rmis similar to the DOS command
del. To avoid complete Makefile madness, some basic UNIX commands are included in the Windows distribution of Nut/OS as executables. You can find them in the directory
tools/win32. When running Make in a DOS window, make sure that your PATH points to this directory.
When the Configurator builds Nut/OS, it will set the correct path
and will always run
make clean first. The next chapter
will show more details about how the Configurator uses Make.
Make and the Nut/OS Configurator
We assume, that all Configurator settings have been specified by following the Nut/OS Software Manual and that we are ready to create a new Nut/OS build tree.
When selecting
Generate Build Tree from the Configurators
Build menu, then the directory for building Nut/OS
will be created with all required subdirectories. In the top level
directory of the build tree, the Configurator will additionally create
three files, which will be used by the Make tool.
The first of these files is named Makefile. It's a very simple
Makefile with three targets:
all,
install
and
clean.
all: $(MAKE) -C arch ... install: $(MAKE) -C arch install ... clean: $(MAKE) -C arch clean ...
$(MAKE). That's how Make understands definitions similar to C makros. It may be defined somewhere else as
MAKE=make, however, specially
$(MAKE)is internally predefined. The second feature is the command line option
-C directory. This instructs make to change to the specified directory before starting to read the Makefile.
As you can see, for each target Make is called for each Nut/OS module subdirectory with the same target again. Of course, the Configurator also creates the Makefiles in these subdirectories, which are much more interesting than the top level Makefile.
Let's stay at the top level, where the Configurator created
two additional files,
NutConf.mk and
UserConf.mk.
NutConf.mk defines several macros, similar to
the internally defined
$(MAKE), which I explained
above. When building Nut/OS for the ATmega128 using AVRGCC, this
file contains
MCU_ATMEGA128=atmega128 MCU_ATMEGA103=atmega103 MCU=$(MCU_ATMEGA128) HWDEF=-D__HARVARD_ARCH__ CRUROM=crurom include $(top_blddir)/UserConf.mk
$(MCU)appears in a Makefile, Make will replace it with
$(MCU_ATMEGA128), which in turn is replaced by
atmega128.
The last line of NutConf.mk instructs Make to include
UserConf.mk, which initially contains a
single line
HWDEF += -DETHERNUT2
NutConf.mk,
$(HWDEF)will be finally expanded to
-D__HARVARD_ARCH__ -DETHERNUT2. As long as you are using the Ethernut 2 hardware, this is just fine. When building Nut/OS, this compile option is simply ignored. However, the same entry is added by the Configurator when creating the sample directory and should be removed before compiling any of the samples. Hey, wait, we are building Nut/OS. More on the sample applications later.
Each time, when you re-create the build tree, the Configurator
will overwrite existing files in the build tree. Thus, do not
edit them, because your changes will get lost.
UserConf.mk
is an exception. It is initially created, if it doesn't exists. If it
exists, the Configurator will not touch it. You can use it to add
additional compile options, for example.
HWDEF += -g3 -gdwarf-2
Now let's dive into one of the subdirectories and see, what the Configurator created there. We choose subdirectory os, which mostly contains the Nut/OS kernel code. Wonder! It contains nothing but another Makefile.
PROJ = libnutos top_srcdir = c:/ethernut/nut top_blddir = c:/ethernut/nutbld VPATH = $(top_srcdir)/os SRCS = heap.c bankmem.c thread.c timer.c event.c devreg.c confos.c version.c \ semaphore.c mutex.c msg.c osdebug.c tracer.c OBJ1 = nutinit.o OBJS = $(SRCS:.c=.o) include $(top_blddir)/NutConf.mk include $(top_srcdir)/Makedefs.avr-gcc INCFIRST=$(INCPRE)$(top_blddir)/include all: $(PROJ).a $(OBJS) $(OBJ1) install: $(PROJ).a $(OBJ1) $(CP) $(PROJ).a c:/ethernut/nutbld/lib/$(PROJ).a $(CP) $(OBJ1) c:/ethernut/nutbld/lib/$(notdir $(OBJ1)) include $(top_srcdir)/Makerules.avr-gcc .PHONY: clean clean: cleancc cleanedit -rm -f $(PROJ).a -rm -f $(OBJ1)
OBJS = $(SRCS:.c=.o), which is hated so much by Makefile ignorants and which we will not explain here either. Instead we concentrate on those parts, which are relevant to the Nut/OS configuration. Most important is the list of source files
SRCS = heap.c bankmem.c thread.c timer.c event.c devreg.c confos.c version.c \ semaphore.c mutex.c msg.c osdebug.c tracer.c
SRCSline. As a result, the final Nut/OS libraries will contain only those modules, which are available on your target platform.
Not less important lines in
os/Makefile are
... include $(top_blddir)/NutConf.mk ... include $(top_srcdir)/Makedefs.avr-gcc ... include $(top_srcdir)/Makerules.avr-gcc ...
NutConf.mk, which we discussed above. The other two include two files from the Nut/OS source tree. If you look into the top level source directory, you will see a number of files named
Makedefsand
Makeruleswith different file extensions. When building with AVRGCC, the Configurator will add includes of
Makedefs.avr-gccand
Makerules.avr-gcc. When building with ARMGCC, it will use
Makedefs.arm-gccand
Makerules.arm-gccinstead. Again, newbies may consider the contents of these files weird stuff. That's just fine. Under normal circumstances you will have no reason to deal with these. Simply note, that they contain nothing but special definitions for the compiler you are using. If one of the gurus ever passes you a modified version, for example with JTAG debug options, then copy them into the top level source directory with a different extension. The Configurator automatically scans the source directory for such files. Next time you open the second page in the Configurator's settings dialog, you can select the new extension in the platform drop down box.
An important final advice: Each time you changed anything in the Configurator settings, you must recreate the build tree.
Nut/OS Options
Up to this point, configurations were mainly related to the compiler and the target CPU. The majority of configurations is related to hardware specifications and various other build options, though. We will now see, how the Configurator uses C header files to pass these setting to the compiler.
Let's assume, we want to enable floating point support for
printf and
scanf. In the module tree
we expand
C Runtime (Traget Specific) and
File Streams below that. Then we can enable
Floating Point by clicking on the related check box.
If we create a new or re-create an existing build tree, then
the Configurator adds a new header file named
crt.h
in the subdirectory
include/cfg of your build tree,
which contains:
#define STDIO_FLOATING_POINT
include/cfg/crt.hin the source directory does not contain this entry.
Here's a snippet form the Nut/OS source code:
#include
... #ifdef STDIO_FLOATING_POINT /* This is floating point stuff. */ .... #endif ...
include/cfg/crt.hdefines
STDIO_FLOATING_POINT. The one in the build tree does, the one in the source tree doesn't.
Now we are back to the Makefiles of the build tree, in our case
crt/Makefile.
top_blddir = c:/ethernut/icnutbld ... INCFIRST=$(INCPRE)$(top_blddir)/include
Makerules.avr-gcc:
%o : %c $(CC) -c $(CPFLAGS) $(INCFIRST) -I$(INCDIR) $(INCLAST) $< -o $@
include/cfg/crt.hin the build tree first. If it couldn't be found there, the search will continue in the source tree. This way the Configurator is able to overwrite existing default header files in the source tree without any modification of the source tree. This is a real advantage, if you want to build Nut/OS for different targets. You can use the same source tree for each target. And if you later upgrade to a new version of Nut/OS, you can replace the source tree whithout losing your specific configurations, because all of them are located in the build tree.
The Application Tree
Beside the source and the build tree, a third one is used to
build Nut/OS applications. It it created by selecting
Create Sample Directory in the Configurator's
Build menu. There's not much mystery in here,
but it comes quite handy for creating your own applications.
Users of the ImageCraft IDE are lucky people. They can use the GUI to create new project files in the sample directory. Please follow the steps in the Nut/OS Software Manual.
For using GCC on the command line, just copy one of the subdirectories to a new one with a new name within the sample directory. When adding new or removing existing source files, make sure to update the Makefile accordingly. Even if you don't understand Makefiles, this is quite simple. Be aware, that actions in Makefiles are preceded with a TAB character, spaces won't work. Your text editor should preserve tabs.
Remember
UserConf.mk? When running the compiler on
the command line, the default contents created by the Configurator
may hurt now, if we do not intend to run the application on Ethernut 2.
All samples have been written for Ethernut 1 (including Charon II and
other boards using the Realtek Ethernet Controller) and Ethernut 2.
All samples with network code contain the following lines:
#ifdef ETHERNUT2 #include <dev/lanc111.h> #else #include <dev/nicrtl.h> #endif
UserConf.mk, then the application will register the LAN91C111 driver. Otherwise the driver for the RTL8019AS is used. If you want the latter, do not forget to remove the related line in
UserConf.mk. In newer releases
WOLFis another option and uses the AX88796 driver. For this controller simply replace
ETHERNUT2by
WOLFin
UserConf.mk.
Under the Hood
As stated above, the GNU Make Tool controls the top level. The bottom level is controlled by Lua, an interpreter language. Mainly because of compatibility problems with Lua libraries on various Linux platforms, the decision to use Lua had been criticized sometimes. But the author is still convinced, that this had been a good decision. The Lua interpreter is extremely small and the language is extremely powerfull. Right now this is hard to believe, because the Configurator uses Lua in a static way. But one day it will shine brighter than everything else...:-)
Neither Lua nor all Nut/OS options will be described here. Just a few details will be discussed.
All Lua scripts are located in the subdirectory
conf
within the source tree. When the Configurator starts, it will
read
repository.nut first. This file specifies
additional scripts.
{ name = "nutarch", brief = "Target", description = "Select one only.", subdir = "arch", script = "arch/arch.nut" },
arch/arch.nutis specified as an additional script to be included, which contains:
{ macro = "MCU_ATMEGA128", brief = "Atmel ATmega 128", description = "8-bit RISC microcontroller with 128K bytes flash, 4K bytes RAM, ".. "4K bytes EEPROM, 64K bytes data memory space, 2 USARTs, 4 timers, ".. "8-channel ADC, SPI and TWI.", requires = { "TOOL_CC_AVR" }, provides = { "HW_TARGET", "HW_MCU_AVR", "HW_MCU_AVR_ENHANCED", "HW_MCU_ATMEGA128", "HW_NVMEM", "HW_TIMER_AVR", "HW_UART_AVR" }, flavor = "boolean", file = "include/cfg/arch.h", makedefs = { "MCU=$(MCU_ATMEGA128)", "HWDEF=-D__HARVARD_ARCH__" } },
Atmel ATmega 128is activated. In addition, the Configurator will
#define MCU_ATMEGA128in this file.
The last definition
makedefs = looks familiar,
doesn't it? Indeed it specifies a list of entries, which
will be added to
NutConf.mk.
However, before you are able to access the module tree
in the Configurator's main window, you will be asked to
select a configuration file. These files got the extension
.conf and are also located in the
conf
subdirectory of the Nut/OS source tree. They contain simple
assignments. Here's the one, which specifies options for running
Nut/OS on the STK501 with an ATmega128 and the AVRGCC:
AVR_GCC = "" MCU_ATMEGA128 = "" NUTMEM_SIZE = "4096" NUTMEM_START = "0x100" NUTMEM_RESERVED = "64"
macro =entries in the Lua scripts. The first two do not assign any values. The fact, that they appear in this file, sets the related boolean Lua macro definitions to true.
There are other options handled by Lua, but you should have
got the picture. In the current state of the Configurator
this is quite helpful, because this tool is far from being
perfect. For example, radio boxes are not implemented and the
user must take care to enable one CPU or one compiler only and
disable all others. One annoying thing is, that the compiler
needs to be specified at two places, in the Configurator's
setting notebook as well as in the component tree. Furthermore,
not all options seem to make their way into the final build.
If something seems to go wrong, check the
include/cfg
directory in the build tree and further check, wether these
files are actually included in the related Nut/OS code. But before
panic breaks out: The mainstream works fine, exotic options may fail.
Changing Environments
In the previous chapter we learned, that the configuration of the Configurator's settings notebook isn't always syncronized with the Configurators component tree. That's because they are kept in different places.
All modifications of the component tree are manually stored in
platform configuration files with extension
.conf.
All modifications of the settings notebook are automatically
stored in the Windows registry or in
nutconf.ini
when running Linux. This could be quite annoying, when you
regularly have to change your environment. The problem isn't
finally solved, but for now it helps to call the Configurator
with command line option
-s followed by a keyword
of your choice. For example, on Windows you can call
nut\nutconf
nut\nutconf -s arm
More Hints
1. After modifying Lua scripts the component tree never appears again. Check for missing commas. The configurator displays the name of the script and the line number of the error.
2. You can use
UserConf.mk to create a debug
enabled binary with AVRGCC by appending
HWDEF += -g3 -gdwarf-2
3. If you need additional include files to be used by
several of your applications, then create an include directory in
your application tree and add the following line to
UserConf.mk
INCFIRST += $(INCPRE)../include
4. Building Nut/OS fails with something like
Unsupported target.
Probably the settings in the Configurator's notebook and the
component tree specify different compilers.
Harald Kipp
Herne, May 12th, 2005.
|
http://www.ethernut.de/en/documents/ntn-5_config.html
|
CC-MAIN-2022-21
|
refinedweb
| 2,851
| 58.38
|
1. Roll call. Scribe for minutes selected from attached list. Actions to be recorded on IRC. Present 13/10 BEA Systems, Mark Nottingham Canon, Herve Ruellan IBM, Noah Mendelsohn IBM, David Fallside IBM, John Ibbotson IONA Technologies, Suresh Kodichath Microsoft Corporation, Martin Gudgin Oracle, Anish Karmarkar SAP AG, Gerd Hoelzing SeeBeyond, Pete Wenzel (scribe) Sun Microsystems, Marc Hadley Sun Microsystems, Tony Graham W3C, Yves Lafon Excused BEA Systems, David Orchard Canon, Jean-Jacques Moreau Microsoft Corporation, Jeff Schlimmer Oracle, Jeff Mischkinsky SAP AG, Volker Wiechers Absent Nokia, Michael Mahan 2. Agenda review, and AOB The Important Stuff: CR implementation testing and CR issue resolutions 3. Approval of minutes, 11 Aug (840 + 5) No modifications requested; approved without objection. July 28 minutes have been posted, but not yet approved. 4. Review action items, see. These action items are taken from the XMLP member page. 2004/08/04: MarcH Review WSDL Part 3, Due 2004-09-06 DONE, WG to review and decide whether or not to send these comments to WSD WG MarcH: Nothing critical. Introduces a default binding, but does not extend it to interface faults. Would be easy and useful to do that. Relationship between module and feature needs to be cleared up. Other areas lack clarity. HTTP binding did not capture some small items as well. DavidF: Any disagreement with this commentary? No, so we will submit to WSD WG. MarcH will forward his email to them. 2004/08/04: MarkN Review WSDL Part 1, Due 2004-09-06 PENDING Change due date to Sept 22. 2004/08/04: MikeM Review WSDL Part2, Due 2004-09-06 PENDING Change due date to Sept 22. 2004/08/11: Editors Send email regarding change to section 3.2 of MTOM to dist-app DONE 2004/08/11: Editors Change all namespaces from /YYYY/MM/ to /2004/08/ DONE 2004/08/11: Yves Arrange a concall on Zakim for MTOM implementers at 11am PST 2004-08-12 PENDING See agenda item #6 Done. 5. Status reports and misc (9.00 + 10) -- Media types registrations, i.e. "application/soap+xml" and "application/soap_xop+xml" (MarkN) MarkN: It has progressed to "rfc-editor" stage. One more step + 48 hours before it is finally published. Estimate 1-2 weeks to get there. Request W3C Team to review for editorial nits, such as references. Change controller should be updated to the appropriate W3C contact: web-human@w3.org MarkN will verify that this change can be made without reverting to a previous state. Yves: application/xop+xml registration sent to IETF. -- XMLP/WSD Task Force and WSDL Media Type document (Anish) Anish: Nothing to report. -- f2f meeting DavidF: CR period ends Sept 15. We have received 5 comments. Is it still necessary to meet? Noah: Any issues about the WG's future can be discussed by phone. DavidF: Purpose of this meeting is to get us to PR. Unless we get comments that send us back to pre-LC, doesn't seem like we will need to meet F2F again. Leave it pencilled in; will make the decision next week. Noah: Will miss next week's call, but could attend F2F. Feel free to make any decision about whether or not to hold it. MarkN: No problem cancelling hosting arrangements, but personally have already bought ticket. DavidF: Nilo is expecting to attend; will email him a warning that it may be cancelled. -- Primer review,, WG members are asked to review and post comments 6. Candidate Recommendation (9.10 + 50) -- Status of testing: what end-points are available, did the MTOM implementers telcon take place and if so what transpired, have any messages been exchanged, what plans for testing, is there a complete set of tests for all parts of the spec? Gudge: Attended the call with Jean-Jacques. Agreed that the proposed tests were ok. Are being used this week between Canon, Microsoft, White Mesa. All positive tests are working. Microsoft<->Canon, Microsoft<->White Mesa. Failure cases will be attempted later this week. Only issue is that "start-info" parameter was spelled without hyphen, because SOAP example incorrectly excludes it. That has been corrected in the implementations. Herve: Canon has completed all 7 test cases against both Microsoft and White Mesa. Anish: Should complete writing tests for Resource Representation Header over the weekend. Gudge: Implementation can handle resource header, but there is no application-level code that actually uses the data. DavidF: Do we need to retest to capture logs? Gudge: Have complete logs of everything sent & received. DavidF: Send me a complete set of logs; will post on a web page. Gudge: Will have Bob send an email regarding HTTP headers. -- Issues o 500, XOP, (editorial) broken references section, DavidF: Propose that this is editorial, and assign to editors for resolution and closing email. Yves: References section of all 3 documents need to be updated. Gudge: Links disappeared when CR versions were generated. o 504, Rep, (editorial) i18n issues, Editors to fix and send closing email. o 501, Rep, i18n issues - encoding and language, Noah: We tunnel data in a base64 octet stream, and add metadata. MarcH: There is an issue with inheritance of charset. Gudge: To Andrea's point #3, the SOAP document is in a single charset. Our answers to 1-3 would be: Yes, base64 is required. Yes, after decoding the base64 element, its contents may be in a different charset. This is not a problem. Charset of decoded data may be determined in any number of ways. Gudge will draft a response, send to dist-app. What about point #4? MarcH: We allow attribute extensibility. Yves: Is not appropriate to use xml:lang. Gudge: base64 doesn't have a human-readable language. Someone else could write a specification to define how to do this. DavidF: Or use an existing mechanism. Gudge will address this in the proposed response as well. o 502, Rep, i18n issues - URI handling, Noah: We assumed they were IRIs, but Schema says they are URI. The reference is HLink spec, rather than something more normative. We didn't mean to use IRIs here; they are not visible on the web. Noah: Change our spec to read that the attribute value "SHOULD be a URI". MarcH: Why not "MUST"? DavidF polls: Group preference is for "SHOULD". Noah will draft a proposal answering question #5. DavidF: We are over time; meeting is adjourned. o 503, Rep, i18n issues - HTTP semantic, 7. SOAP 1.2 Recommendation maintenance (postponed) -- Issues and proposed resolutions o Issue Rec25, , "media type registration". Issue text describes a couple of ways to proceed. This issue is pending IANA registration of media type.
|
http://www.w3.org/2000/xp/Group/4/09/08-minutes.html
|
CC-MAIN-2015-35
|
refinedweb
| 1,107
| 68.26
|
I’m tinkering with a web application and have a situation where I want to select only elements which are visible on the page. Initially I tried using the is(“:visible”) jQuery (v1.4.2) selector, but it seems to be broken, at least for IE.
My solution was inspired by an old posting, and I created the following extension which checks the styles on the current element, and if it’s inherited, then check the parent element.
$.extend(
$.expr[":"],
{
reallyhidden: function (a) {
var obj = $(a);
while ((obj.css("visibility") == "inherit" && obj.css("display") != "none") && obj.parent()) {
obj = obj.parent();
}
return (obj.css("visibility") == "hidden" || obj.css('display') == 'none');
}
}
);
and use it like this:
if (element.is(':reallyhidden')) return false;
thanks for the nice idea on this nice post mikael. what version of IE you thought it's broken?
.is(":hidden") appears to work fine for me here
I'm using IE8, and have tested it in compatibility mode as well. I'm parsing Japanese pages and making a selection UI, and in IE it would select elements which are hidden.
The problem seems to be with IE and inherited hidden elements. While Chorme and FF will report the style as "hidden", IE says "inherit", and ":hidden" seems not to check what "inherit" actually is.
Yep thanks for the detailed explanation. Somehow I can picture myself on the equation and your code is truly a great solution.
I was just wondering, maybe you can just use display:none; on your selection UI instead of visibility:hidden; and then it will work on IE as well.
from the jQuery document it says;
"Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout."
thanks again
I'm actually creating a GUI where I parse html from arbitrary sources, so I have no control over the styles. And as you say, the docs state that visibility:hidden is not considered the element to actually be hidden (which I missed).
In my case I need to treat elements which are not visible to the user as hidden.
you can just use $(element).is(":visible")
Kevin, did you read the first line of the post? The whole post is about .is(":visible") not working in IE at the time I wrote the post. Read thru the other comments for an explanation.
Your solution is really good as the visible and hidden doesn't work when visibility=hidden is used to hide the element. I faced this situation and after sometime got the solution as well. So thought of sharing with you.
|
https://www.techmikael.com/2010/07/check-if-element-is-truly-hidden-with.html
|
CC-MAIN-2018-39
|
refinedweb
| 436
| 58.18
|
Hello,
I need some help understanding the nonlocal variables and functions. Currently I'm reading "A byte of Python" to ease myself into the language, which so far seems to be fairly straightforward even if the syntax is a little strange coming from C++.
I have copied a small script from the book:
#!/usr/bin/python # Filename: func_nonlocal.py def func_outer(): x = 2 print('x is', x) def func_inner(): nonlocal x x = 5 func_inner() print('Changed local x to', x) func_outer()
If I'm correct the code is read line by line by the interpreter and that When I call
func_outer() it displays the data in the
print(..) by going through the function one line after another. So what is the point of calling the
func_inner() within the
func_outer() since it is already defined inside the said function.
I ran the code after commenting the
func_inner() and it ran fine without a problem.
Also is defining functions within functions advisable as it seems a rather strange concept, and can you call
func_inner() without having to go through
func_outer() first.
Say like
def func_outer(): x = 2 print('x is', x) def func_inner(): nonlocal x x = 5 func_inner() print('Changed local x to', x) func_inner() #Just call this
Thanks.
PS. What's the Python code tag? When I call \ I don't get the formating or syntax highlighting.[code=python\] I don't get the formating or syntax highlighting.
|
https://www.daniweb.com/programming/software-development/threads/190071/understanding-functions
|
CC-MAIN-2017-09
|
refinedweb
| 237
| 70.94
|
On Saturday, May 3, 2003, at 03:22 AM, Stas Bekman wrote:
> shouldn't this be 'goto &$c' ala AUTOLOAD? I guess both ways work.
>
> In any case the calling package is wrong in the above both versions,
> so it gets exported to the wrong namespace.
>
> Either in the caller:
>
> require Apache::TestLoad;
> Apache::Test->import();
>
> but that's ugly. Or:
Yes, I agree it's ugly.
> sub import {
> my $package = shift;
> unshift @_, 'Apache::Test';
> goto &Apache::Test::import;
> }
That wont' work because import() is a method in Exporter; it's not in
the Apache::Test package.
> I don't remember if Exporter relies on the package name in the first
> arg, or the caller() function.
>
> How about:
>
> package Apache::TestLoad;
> ...
> sub import {
> my $package = shift;
> package Apache::Test;
> Apache::Test->import(@_)
> }
>
> Again untested...
No, that won't work, because you would be trying to import the
functions in Apache::Test into the Apache::Test package.
I just took a look at Exporter::import, and it uses both the class name
in the first argument in order to find the subroutines to export and
the caller for the namespace to import them into. I hadn't made this
connection before, and should have looked at import() before. The
upshot is that it never worked because I hadn't changed the first
argument to import() to 'Apache::Test' -- your example above tickled
that for me. So here's the best solution I can see:
sub import {
my $package = shift;
unshift @_, 'Apache::Test';
goto &{Apache::Test->can('import')};
}
This way, the caller is the package that C<use>d Apache::Test (thanks
to the goto), and, because the first argument is 'Apache::Test',
import() now knows where to find the functions to actually import.
> Cool.
>
> Any alternative naming suggestions to TestLoad?
How 'bout Apache::Tester? If it sticks, and people just use that, you
might eventually be able to eliminate Apache::Test and be done with
this problem.
HTH,
David
--
David Wheeler AIM: dwTheory
david@kineticode.com ICQ: 15726394
Yahoo!: dew7e
Jabber: Theory@jabber.org
Kineticode. Setting knowledge in motion.[sm]
|
http://mail-archives.apache.org/mod_mbox/httpd-apreq-dev/200305.mbox/%3C9DBAB16E-7DBD-11D7-98EC-0003931A964A@wheeler.net%3E
|
CC-MAIN-2017-39
|
refinedweb
| 352
| 64.91
|
Get information about a user with a given name
#include <sys/types.h> #include <shadow.h> struct spwd* getspnam( char* name ); struct spwd* getspnam_r( const char* name, struct spwd* result, char* buffer, size_t bufsize );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The getspnam() and getspnam_r() functions allow a process to gain more knowledge about a user name. The getspnam() function uses a static buffer that's overwritten by each call.
A pointer to an object of type struct spwd containing an entry from the shadow file with a matching name, or NULL if an error occurred or the function couldn't find a matching entry.
); }
|
https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/g/getspnam.html
|
CC-MAIN-2022-33
|
refinedweb
| 117
| 55.24
|
Get Familiar with Xcode7:23 with Amit Bijlani
Xcode is known as an integrated development environment or IDE used to create an iPhone app. Learn about the various project templates and the get familiar with layout.
- 0:00
To build an iPhone app, we need a software called Xcode,
- 0:05
which is also known as an integrated development environment, or IDE.
- 0:11
You can download and install Xcode from the Mac App Store for free.
- 0:16
So, go ahead and install it.
- 0:18
When we first open up Xcode, you will notice a link to create a new Xcode project.
- 0:27
On the right, when you have a few projects,
- 0:30
you will see links to your recent projects.
- 0:37
So, let's go head and click on Create a new Xcode project.
- 0:43
It brings up a few template choices—
- 0:47
the first things we see are a few templates to choose from.
- 0:52
Each template provides basic starter files
- 0:54
so that you have some files to work with right away.
- 0:59
Let's briefly go over each project template.
- 1:04
The Master-Detail Application—
- 1:07
This is an example of the Mail app on the iPad or iPhone,
- 1:11
where you have 2 views—a list view and detail view.
- 1:15
When you are building an app for the iPad,
- 1:18
this is a split-view controller,
- 1:20
where you have a narrow left column
- 1:22
and the details on a wide column to the right.
- 1:26
This template also provides data storage capabilities.
- 1:30
The next is OpenGL Game
- 1:33
and, as the name suggests, it helps you build a 3D game
- 1:37
using the 3D framework called OpenGL.
- 1:41
Next, you have the Page-Based Application.
- 1:45
Similar to the Notes application on your iPhone,
- 1:48
this template provides a page-style application.
- 1:53
Next is the Single View Application.
- 1:57
You might use this more often when building your own app
- 1:59
because it provides a single view
- 2:02
and then you can build your app from there.
- 2:07
The Tabbed Application, as the name suggests,
- 2:10
provides tabs to the bottom.
- 2:13
An example of this is the Clock app on your iPhone
- 2:17
or even the Phone application on your iPhone.
- 2:22
The Utility Application is very similar to the Single View Application,
- 2:27
except that it provides a flipped view,
- 2:30
so that you have 2 distinct views—
- 2:33
a main view and a secondary view that flip animates.
- 2:38
An example of the Utility Application
- 2:41
is the Compass app.
- 2:45
Next is the Empty Application.
- 2:48
If you do not want to start with any of these predefined templates
- 2:52
and you don't want any Boilerplate code,
- 2:54
then this is the template for you.
- 2:56
It is the minimal project setup for you to build a customized app
- 3:01
that suits your needs.
- 3:03
Finally, the SpriteKit Game.
- 3:06
SpriteKit is a 2D gaming framework
- 3:09
provided in iOS 7.
- 3:11
So, if you want to build your next hit 2D game,
- 3:14
then SpriteKit is the framework for you.
- 3:18
For our app, we will choose Single View Application—
- 3:23
so select Single View and then hit Next.
- 3:27
Before we even start coding, we have to fill out a few things about our application.
- 3:33
The first thing being the product name—
- 3:36
this is basically the name of your application
- 3:38
and what shows up along with the icon once you install the app.
- 3:43
in our case, our app is called CrystalBall—
- 3:46
pretty simple.
- 3:51
Next is organization name—so this could be your company name or even your own name.
- 3:57
After that you have the company identifier—
- 4:01
this is also known as a namespace—
- 4:04
to prevent apps with exactly the same name.
- 4:07
Imagine if another app in the App Store was called CrystalBall—
- 4:12
the chances of that are pretty high,
- 4:14
so that would create a problem.
- 4:16
But if we have a company identifier,
- 4:18
then it differentiates the other CrystalBall app from our own CrystalBall App.
- 4:24
Common practice is to use your company website's domain name as the identifier,
- 4:29
hence the reason for putting com.teamtreehouse.
- 4:33
Don't worry if you don't own that domain name—
- 4:36
you can even put your own name,
- 4:38
but it's mainly to distinguish your own app from the other apps out there.
- 4:44
The product name combined with the company identifier
- 4:47
makes up the bundle identifier.
- 4:50
This comes in handy when you are deploying your app to a device
- 4:53
or prepping it for the App Store.
- 4:56
It is standard convention to prefix all your app classes,
- 4:59
so that you can distinguish them from other classes.
- 5:03
In our case, I have prefixed it with th for treehouse.
- 5:08
If you don't have a company, then you can add initials of your first and last name.
- 5:13
For example, if I were personally building an app,
- 5:16
I would add a prefix of ab.
- 5:19
Finally, select the device.
- 5:22
I have selected iPhone, but if you click the dropdown,
- 5:25
you have the option of selecting iPad, iPhone, or Universal—
- 5:30
Universal being an app that can be used both on the iPhone and iPad.
- 5:38
Hit Next.
- 5:40
Select a location where you want to save your project.
- 5:44
Then, hit Create.
- 5:46
So, let's take a brief tour of Xcode.
- 5:50
To the left you have the navigation area,
- 5:53
along with tabs that provide different ways of navigating your project.
- 5:59
To the right is the summary page of your application.
- 6:04
To the right is your project summary page—
- 6:06
but once you click on a file on the left,
- 6:10
you will see the file details.
- 6:13
This is a fully functional project,
- 6:16
so if you click the Run button, which also looks like the Play button,
- 6:21
you can see your app in the simulator.
- 6:27
You will notice a blank screen,
- 6:30
and also the app looks rather large,
- 6:32
or rather the simulator looks rather large.
- 6:35
That's because if you don't have a retina display,
- 6:39
then it scales the simulator
- 6:42
because it is sized for a retina display.
- 6:47
Since I don't have a retina display, I can scale this down.
- 6:50
I can click on Window from the menu,
- 6:54
select Scale and select 50%.
- 6:58
I can also use the shortcut keys, which is Command+3.
- 7:03
Now this looks more appropriate
- 7:05
so that we can see the entire screen and we don't have to scroll with it.
- 7:10
So, there's our simulator, and as you can see our app is blank
- 7:13
because we haven't done anything with it yet.
- 7:17
But congratulations! You just set up and ran your very first iOS project.
|
https://teamtreehouse.com/library/build-a-simple-iphone-app-ios7/getting-started/get-familiar-with-xcode
|
CC-MAIN-2016-40
|
refinedweb
| 1,287
| 78.69
|
[Lab] playing with bindings. This is a bit Dr. Frankenstein for me.
Well I went off on a bit of a tangent tonight , yet again. But I was thinking about options to connect my views to Custom Classes as you can with loading a UIFile with bindings. I am sure there are simpler ways, but I wanted to check it out anyway.
So the idea was I could create a simple view using v=ui.View() and bind that to a custom class. Anyway, that was not going to work itself. But I thought what if I create a json Str that ui.load_view_str() expects and pass the bindings. Btw. ui.load_view_str() is not documented as far as I know. But you can see it in the ui module.
Anyway, below is what I come up with. I don't really understand it 100% and maybe it's a horrible idea. I am surprised what it does. Regardless also got me started thinking about a memory ui object to dict -> json str, so it can be written out as a pyui file. As far as I know, no one has written this. If they have, please let me know. Would be so handy to have a function like that.
Anyway, this is what I did, maybe I went around the block 5 times to do something a simple assignment can do...
import ui, json d = \ [ { "selected" : False, "frame" : "{{0, 0}, {600, 800}}", "class" : "View", "nodes" : [], "attributes" : { "custom_class" : "Panel", "enabled" : True, "background_color" : "RGBA(1.000000,1.000000,1.000000,1.000000)", "tint_color" : "RGBA(0.000000,0.478000,1.000000,1.000000)", "border_color" : "RGBA(0.000000,0.000000,0.000000,1.000000)", "flex" : "" } } ] class Panel(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bg_color = 'purple' self.xxxxxxxx = 'dynamic Attr' def h(self): print('hello from Panel class') def pyui_bindings(obj): # JonB def WrapInstance(obj): class Wrapper(obj.__class__): def __new__(cls): return obj return Wrapper bindings = globals().copy() bindings[obj.__class__.__name__]=WrapInstance(obj) return bindings j_str = json.dumps(d) v = ui.load_view_str(j_str, pyui_bindings(Panel)) v.present('sheet') # dir(v) shows the xxxxxxxx attr print(dir(v)) # v links to Panel.h method v.h()
|
https://forum.omz-software.com/topic/3544/lab-playing-with-bindings-this-is-a-bit-dr-frankenstein-for-me
|
CC-MAIN-2017-51
|
refinedweb
| 368
| 79.56
|
I am a javanoob, hence my username. I am currently enrolled in a Java Programming class. We have to create a Java payroll program. I completed part 1 just fine, but I'm having issues with part 2. For part 2, I have to modify my application so that it continues to request user information (this portion works). I also have to make it so that when the user enters "stop" as the employee name, the program ends. Also, if a negative number is entered as hourly pay or hours worked, a prompt comes up asking the user to input a positive number. I am so sorry, but this website is my last hope. Unfortunately, my instructor is not much of a help, he expects me to be an expert after only 2 weeks. Can you guys please take a look at my code and help me out or at least point me in the right direction??? I hope I pasted the code right...thanks!
// Payroll Program Part 2 import java.util.Scanner; // class Scanner public class PayrollProgramTwo { //main method begins execution of Java application public static void main(String args[]) { //create Scanner to obtain input from command window Scanner input = new Scanner(System.in); String cleanInputBuffer; // input String employeename; // Employee Name float hourly; // hourly pay rate float hours; // hours worked this week float product; // weekly pay amount boolean end = false; // is the input name stop? while (end = true) // as long as end is false, proceed { hourly = -1; // this way, both are initiated to be -1; hours = -1; System.out.print("Enter Name of Employee:"); employeename = input.nextLine(); if(employeename.toLowerCase() == "stop") end = false; System.out.print("Enter hourly pay rate:"); // prompt hourly = input.nextFloat(); // input while (hours <= 0) // same as hourly while loop { System.out.print("Enter number of hours worked this week:"); // prompt hours = input.nextFloat(); // input } product = hourly * hours; // * numbers System.out.printf("The employee %s was paid $ %.2f this week.\n\n", employeename, product); cleanInputBuffer = input.nextLine(); //Read a line of text to clean the input buffer } // end outer while } // end method main } // end class PayrollProgramTwo
|
http://www.dreamincode.net/forums/topic/118280-need-help-with-java-payroll-program-if-else-and-while-statements/
|
CC-MAIN-2017-43
|
refinedweb
| 350
| 66.84
|
This is your resource to discuss support topics with your peers, and learn from each other.
05-17-2012 10:47 AM
Trying to get a very simple AIR app working with the BB10 10.0.4 AIR SDK and I get:
ReferenceError: Error #1065: Variable qnx.fuse.ui.skins:
kinAssets is not defined.
at qnx.fuse.ui.theme::ThemeWhite/createCSS()[E:\hudso
at qnx.fuse.ui.theme::ThemeWhite()[E:\hudson\workspac
at qnx.fuse.ui.theme::ThemeGlobals$/getTheme()[E:\hud
at qnx.fuse.ui.theme::ThemeGlobals$/[E:\hudson\workspace\BB10_0_04-AIR_SDK_API\src\qnxui\
at qnx.fuse.ui.core::UIComponent/get css()[E:\hudson\workspace\BB10_0_04-AIR_SDK_API\sr
at qnx.fuse.ui.core::UIComponent/init()[E:\hudson\wor
at qnx.fuse.ui.text::TextBase/init()[E:\hudson\worksp
at qnx.fuse.ui.text::Label/init()[E:\hudson\workspace
at qnx.fuse.ui.core::UIComponent()[E:\hudson\workspac
at qnx.fuse.ui.text::TextBase()[E:\hudson\workspace\B
at qnx.fuse.ui.text::Label()[E:\hudson\workspace\BB10
at bb1()[U:\workspace460\bb1\src\bb1.as:12]
It occurs when creating a label:
import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import qnx.fuse.ui.text.Label; import qnx.fuse.ui.theme.ThemeGlobals; public class bb1 extends Sprite { private var label :Label;// = new ); } }
The exception is thrown when trying to run it as an AIR app on the desktop.
Solved! Go to Solution.
05-17-2012 01:55 PM
This code runs fine for me on the BlackBerry 10 Dev Alpha Simulator. Also opens fine when I click the .swf in my bin directory. My version is slightly different.
package { import flash.display.Sprite; import qnx.fuse.ui.text.Label; import qnx.fuse.ui.theme.ThemeGlobals; [SWF(height="1280", width="768", frameRate="30", backgroundColor="#777777")] public class LabelTest extends Sprite { public var myLabel:Label; public function LabelTest() { ThemeGlobals.currentTheme = ThemeGlobals.BLACK; myLabel = new Label(); myLabel.text = 'Hello World'; myLabel.setActualSize( 200, 50 ); addChild( this.myLabel ); } } }
Using FDT5 free version.
Regards,
Dustin
05-17-2012 02:43 PM
05-17-2012 02:56 PM
I switched over to Flash Builder and I'm getting the same error as you. Seems to work fine in FDT. I will create a bug and follow up with the SDK team.
Has anyone else run into this issue?
05-17-2012 03:14 PM
Thanks. Let me (us) know when it is resolved. Nothing can be developed in Flash Builder at this point with the new SDK.
05-17-2012 03:15 PM
Here is the bug for tracking -
05-17-2012 03:30 PM
05-17-2012 03:51 PM
For BB10.04, skins reside in a native extension, so you have to add it to your project properties.
Unfortunately, FlashBuilder requires two steps to do it:
The project has to have the QNXSkins.ane added to it (Preferences->Build Path->Native Extensions) and marked to be included to the BAR file as well (Preferences->ActionScript Build Packaging->BlackBerry->Native Extensions). For the latter, you might have to expand the window to actually see the checkbox for the ANE.
The native extensions are under frameworks/libs/qnx/ane.
Cheers
05-17-2012 03:57 PM - edited 05-17-2012 04:09 PM
Doh! Was reminded about ANE"s that need to be added.
- Open up your project properties and browse the the Native Extensions tab in the ActionScript Build Path option.
- Click add folder and then add the C:\Program Files\Research In Motion\blackberry-tablet-sdk-3.0.0\frameworks\libs
Make sure it's checked off to be included in your bar as well.
Paulo beat me to it. Thanks Paulo +1
05-17-2012 04:14 PM
Also - case in point why the workflow in FDT is much better than in Flash Builder.
I recommend it
|
https://supportforums.blackberry.com/t5/Adobe-AIR-Development/BB10-Error-1065-SkinAssets-is-not-defined/m-p/1721073/highlight/true
|
CC-MAIN-2017-09
|
refinedweb
| 638
| 54.79
|
RESTful Content
June 18, 2010
Michael Snoyman
I've said many times that Yesod is based on RESTful principles. One example is the 1 resource == 1 URL design. Another is multiple representations. In my last post I described the Handler monad; here I hope to explain why the return type of handler functions usually looks like
Handler MyApp RepHtml.
Files and Enumerators
Yesod is built on top of WAI, so we need to look down at that level a bit to get an understanding of what's going on. WAI is designed for performance, and in particular offers two ways of giving a response body:
- A file path. This allows the web server to use a
sendfilesystem call if it so desires. It can be a massive performance win since the data doesn't need to be copied at all.
- An enumerator. Enumerators are simulatenously the cool new kid on the block, not well understood, and completely non-standard. I'm guessing there's easily a dozen enumerator definitions floating around. WAI uses one of the simplest definitions around. However, I won't really be discussing that design in this post.
Yesod therefore also allows both files and enumerators for the output; this is the
Content data type. Yesod also has a
ToContent typeclass (as of 0.3.0; it used to just be a more general ConvertSuccess) for converting the "usual suspects" like lazy bytestrings or text into
Content.
Representations
A representation of data then really consists of two pieces of information: the
Content and the mime-type. In Yesod 0.3.0, we use a simple
String to represent mime-type:
type ContentType = String. So how do we allow multiple representations? Let's start off with the simplest approach:
[(ContentType, Content)]. Seems perfect: if a handler could return either HTML or JSON content, it would return something like:
return [ ("text/html", toContent "<p>Hi there!</p>") , ("application/json", toContent "{\"msg\":\"Hi there!\"}") ]
So how would Yesod know which representation to serve? RESTfully of course! We parse the
Accept HTTP request header, determine the prioritized list of expected mime-types, and then select the appropriate representation based on that list. If none of our representations match that list, we just serve the first one.
ChooseRep and RepHtml
This is all well and good, and earlier versions of Yesod worked this way. However, you end up losing type information: I can't look at the return type of a handler and know what type of content it has. So instead, let's look at this approach:
type ChooseRep = [ContentType] -> IO (ContentType, Content) class HasReps a where chooseRep :: a -> ChooseRep
This first thing to notice is that
ChooseRep is more powerful than our simple list. It's able to perform IO actions to produce the appropriate representation. This is very useful: perhaps we showing the HTML representation of data, you need to do some expensive database lookups, whereas the JSON version doesn't need that data. You can make sure you only run the IO operations when the user actually wants HTML.
The
HasReps typeclass is the real winner here. It's trivial to now define instances of
HasReps that specify which mime-type they return. Some real-life examples from Yesod:
newtype RepHtml = RepHtml Content instance HasReps RepHtml where chooseRep (RepHtml c) _ = return (typeHtml, c) newtype RepJson = RepJson Content instance HasReps RepJson where chooseRep (RepJson c) _ = return (typeJson, c) data RepHtmlJson = RepHtmlJson Content Content instance HasReps RepHtmlJson where chooseRep (RepHtmlJson html json) = chooseRep [ (typeHtml, html) , (typeJson, json) ]
Notice how that last datatype actually supports two different mime-types. You could create a type that supports XML as well if you like, or anything else. Yesod tries to only offer the most common types, so we've stuck with the HTML+JSON combination.
Coming up
In this mini-series on Yesod under-the-hood stuff, I think I'll attack user sessions next, and some of the built-in functions to help you (ab)use them properly.
|
http://www.yesodweb.com/blog/2010/06/restful-content
|
CC-MAIN-2016-44
|
refinedweb
| 668
| 63.09
|
lseek (2) - Linux Man Pages
lseek: reposition read/write file offset
NAMElseek - reposition read/write file offset
SYNOPSIS#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
DESCRIPTIONl holesSince:
- *
- Btrfs (since Linux 3.1)
- *
- OCFS (since Linux 3.2)
- *
- XFS (since Linux 3.5)
- *
- ext4 (since Linux 3.8)
- *
- tmpfs(5) (since Linux 3.8)
- *
- NFS (since Linux 3.18)
- *
- FUSE (since Linux 4.5)
RETURN VALUEUpon.
- ENXIO
- whence is SEEK_DATA or SEEK_HOLE, and the file offset is beyond the end of the file.
- EOVERFLOW
- The resulting file offset cannot be represented in an off_t.
- ESPIPE
- fd is associated with a pipe, socket, or FIFO.
CONFORMING TOPOSSee.
SEE ALSOdup(2), fallocate(2), fork(2), open(2), fseek(3), lseek64(3), posix_fallocate(3)
COLOPHONThis page is part of release 4.15 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
Linux man pages generated by: SysTutorials
|
https://www.systutorials.com/docs/linux/man/2-lseek/
|
CC-MAIN-2019-43
|
refinedweb
| 168
| 62.85
|
The Android Open Source Project Marshmallow
Brought to you by Jflte DevConnection Team
Code:
#include <std_disclaimer.h> /* * Your warranty is now me and @AntaresOne added some changes from CyanogenMod.
Please do not ask for features to be added because we're not going to add more to keep this ROM small, fast and pure.
JDCTeam
In alphabetical order:
-
- Oliver - @angelcalibur
- Paul Harris - @hawkerpaul
- Paul Keith - @javelinanddart
- Simeon Ivanov - @smstiv
- Stefano Meroni - @smeroni68
- Yannis - @SkL*
Screenshots:
Known issues
- ANT+ (not supported)
- You will tell us
Download
ROM builds are hosted on RomHut
TWRP Recovery v3.0.0-0 with F2FS support (JDC Themed): RomHut
Installation
TWRP Recovery v3.0.0-0 with F2FS support (JDC Themed) is suggested for installation
Device variants supported: I9505, I9505G, I9507, I9508, I337, M919, I545, R970, L720, S970G, S975L (I9515 and I9500 are not supported).
AT&T and Verizon users: since your bootloader is locked, you must be on the UCUAMDB or UCUAMDL bootloader if you own an AT&T phone, otherwise if Verizon you must be on the VRUAMDK bootloader in order to use this ROM. Do getprop ro.bootloader in Terminal Emulator or through ADB shell to find out which bootloader you have
First time or clean install:
- Download the ROM from the link above
- Download GApps package for Marshmallow 6.0
- Download ThemeReady GApps package for MM
Update over an existing previous AOSP MM build !
NOTE: Stable version is dex-preoptimized, so do not wipe cache and Dalvik after rom flash!
First boot after install/update takes a while, wait at least 5 minutes for it to boot.
To convert cache, data and system partitions to F2FS look in post below.
General notes
- Rom is pre-rooted and has SuperSU v2.79 SR3 integrated
- JDC Toolbox app give you the ability to manage LEDs sequence on boot, IR driver selection and more...
- Busybox is pre-installed with Alucard kernel but is located in a separate location. From Stable 6 is possible to install another version of busybox, and this do not interfere with STWeaks.
- Some phones has problems with touch screen sometime not responding (download the Stock kernel from romhut and test with it)
- Theming: rom has from this build the new SUBSTRATUM THEME ENGINE. Use the integrated Substratum app to apply OMS overlays (OverlaysManagerService). RRO layers will not work anymore...
- Theming: to apply OMS overlays to some apps, you need also to flash TBO GoogleApps-ThemeReady-LP-MM-N-v31.0.zip right after your Gapps package from recovery. This means to be clear: ROM + GAPPS + TBO
- We use 5.1 blobs for radio interface. Update your phone to latest Baseband and Bootloader available for your variant (must be a version 5.0 official Baseband)
- We discourage the use of xposed framework, but the rom support it
- For devices with locked bootloader (like Verizon and AT&T), the latest SuperSU package will fail to install. Please after rom flash, provide a manual install of an older SuperSU zip (as version v2.52) and later update from playstore to latest official apk version.
Sources
GitHub
Social
Google+: JDCTeam Community
YouTube: JDCTeam TV
Credits
- JDCTeam
- CyanogenMod
- HITMAN-CREED: Screenshots, Tips&Tricks
Special thanks:
XDA:DevDB Information
AOSP 6.0.1 for Samsung Galaxy S4 (Qualcomm variants), ROM for the Samsung Galaxy S4
Contributors
-+BB+-, AntaresOne, smeroni68, alucard_24, MattBooth, angelcalibur, franzyroy, hawkerpaul, javelinanddart, Jimsilver73, side, smstiv, josegalre
Source Code:
ROM OS Version: 6.0.x Marshmallow
ROM Kernel: Linux 3.4.x
Based On: AOSP
Version Information
Status: Stable
Current Stable Version: Stable 11
Stable Release Date: 2017-03-12
Created 2015-11-18
Last Updated 2017-03-12
|
https://forum.xda-developers.com/galaxy-s4/i9505-orig-develop/jdcteam-android-source-project-mra58v-t3251663
|
CC-MAIN-2017-43
|
refinedweb
| 604
| 62.17
|
Hi there, this is my first python project. I'm new to python but I have experience in a few other languages.
I'm trying to export (to mysql) a list of files and subdirectories from several directories on my hard drive. Basically just so I can have an online database of the files on my hard drive.
Here is my recursive directory walker:
def getlist(path): for file in os.listdir(path): if os.path.isdir(os.path.join(path, file)): print os.path.join(path, file) getlist(os.path.join(path, file)) else: print file return
I was using os.walk beforehand, but couldn't figure out how to go dir->files dir->files, instead it was going dir->dir and THEN dir->files, if you understand.
Now I need some way to be able to keep the directory/file hierarchy while exporting to a mysql db. The only thing I could think of was for each dir to have an id but then I couldn't figure out what to do after that. Once it's done importing to the db, I will make a php/js page that will have a fancy display of all my folders/files. It needs to stay in it's current hierarchy because I will have collapsiblocks inside collapsiblocks (ie: files inside a dir inside a dir)
Thanks for any and all help.
|
https://www.daniweb.com/programming/software-development/threads/204958/maintain-directory-hierarchy
|
CC-MAIN-2019-04
|
refinedweb
| 232
| 73.78
|
Extended auto(un)boxing of primitive types
Sometimes auto(un)boxing occurs only for the purpose of passing an argument through a method. The following is a trivial (uncompilable) example to demostrate what I mean:
<br /> public interface Point {<br /> public void setX(Number x);<br /> public void setY(Number y);<br /> }</p> <p>public class DoublePoint implements Point {<br /> private double x, y;<br /> public void setX(Number x) {<br /> this.x = x;<br /> }<br /> public void setY(Number y) {<br /> this.y = y;<br /> }<br /> }</p> <p>Point p = new DoublePoint();<br /> p.setX(1.3);<br /> p.setY(2.7);<br />
I propose two things:
1) That java can auto(un)box to and from a Number.
2) For the compiler to recognize that auto(un)boxing is not actually required in this case, it is only used to satisfy the interface. So, it should simply pass the primitive values 1.3 and 2.7 through the methods to the x and y arguemtns without actually autoboxing them.
-1
[b]NO[/b], no more auto(un)boxing! It's the worst "feature", that was introduced in Java 5, because it might introduce subtle bugs (NullPointerExceptions).
Tom
Sorry, i accidently must have pressed post message instead of preview. Please see the latest thread instead.
Autoboxing was a mistake. If you want consistent semantics for objects and primitive types, use a modern language like Lisp or Smalltalk. Sun should not have tried to smooth over the primitive/object distinction in the most crappy way imaginable.
|
https://www.java.net/node/643699
|
CC-MAIN-2015-27
|
refinedweb
| 256
| 57.67
|
#include <tcl.h> int Tcl_LinkVar(interp, varName, addr, type) Tcl_UnlinkVar(interp, varName) Tcl_UpdateLinkedVar(interp, varName).:
If the TCL_LINK_READ_ONLY flag is present in type then the variable will be read-only from Tcl, so that its value can only be changed by modifying the C variable. Attempts to write the variable from Tcl will be rejected with errors.
Tcl_UnlinkVar removes the link previously set up for the variable given by varName. If there does not exist a link for varName then the procedure has no effect.
Tcl_UpdateLinkedVar may be invoked after the C variable has changed to force the Tcl variable to be updated immediately. In many cases this procedure is not needed, since any attempt to read the Tcl variable will return the latest value of the C variable. However, if a trace has been set on the Tcl variable (such as a Tk widget that wishes to display the value of the variable), the trace will not trigger when the C variable has changed. Tcl_UpdateLinkedVar ensures that any traces on the Tcl variable are invoked.
|
http://www.linuxmanpages.com/man3/Tcl_UnlinkVar.3.php
|
crawl-003
|
refinedweb
| 176
| 60.65
|
.
I recently wanted some breadboard setups for students. I did end up make a simple PCB that plugs into a breadboard, but looking back the simple circuit would have worked just as well placed directly on a breadboard. Here’s what you need:
- An LPC1114FN28
- A 3.3V power supply
- A 3.3V or 5V USB to serial cable or adapter
- One or two 220 ohm resistors (not absolutely necessary)
- An LED and suitable resistor (optional)
- Two 0.1uF capacitors (not absolutely necessary)
If you have a USB cable that puts out 3.3V, you can probably drive the chip directly with that. Otherwise, you can use an LD1117-3.3 or an LM7833. A bench supply or one of those cheap power supplies that plugs into a breadboard will work too. Just remember, the chip needs between 1.8V and 3.6V to operate.
Building the Hardware
The circuit is so simple, you almost don’t need a schematic. Here’s one anyway:
One reason that this works so well is the chip has a built-in serial bootloader. If you short the PIO0_1 pin to ground and reset the chip, you can easily upload a program to the device. You could probably get away with just shorting both pins to ground (they are internally pulled up). However, I like to put a small (220 ohm) resistor in series in case software is driving the pin as an output for some reason.
Of course, the jumpers (BOOT and RESET) and connectors in the schematic can just be breadboard wires if you don’t want to mount actual pins. The USB “connector” assumes that pin 2 is ground, pin 3 is the PC’s receiver and pin 4 is the transmit (that is, the LPC1114 talks on 16 and listens on pin 15). If that doesn’t match your cable or RS232 converter, change it as needed.
You may also want to adjust the value of the resistor depending on your LED, but you aren’t making a flashlight, so any value that will get a visible glow ought to be fine (or, omit it completely if you don’t want to blink an LED). If you are a real minimalist, you could dump the 220 ohm resistors, too. The capacitors help decouple your power supply, but breadboards have a good bit of capacitance already and if you have a clean supply, you might not need those either.
So if you have a breadboard and a USB to serial adapter, you could build the bare bones version of this for about $6 and maybe break the bank at $15 if you had to buy everything. Of course, if you have another ARM programmer/debugger that you want to use, that could be wired up instead of the USB cable. But I’m guessing if you have that kind of hardware, you’ve already solved your breadboarding problem.
Here’s my (almost) bare bones version:
Not pretty, but effective. I used a switch for the reset and just a wire for the boot jumper. The LED has an internal 5V dropping resistor, but works fine at 3.3V (and I dropped the other two resistors and the capacitors). To work through the software example below, you’ll either need another LED connected to pin 1, or you can just lift up the connection on the breadboard and repurpose the LED. Be aware though: The mbed code assumes you have an LED connected to pin 14 and will blink it if it finds run time errors. If you move the LED you could have an error and won’t get an indication.
Software
You can use any ARM tool chain that can generate code for the LPC1114. There are plenty to choose from, but I’m going to assume you are just getting started, so let’s use the mbed web site. I’ve covered how to program using mbed before, and you might want to check out the video below for that walk through.
Here’s a quick summary of the steps you’ll need to take:
- Go to
- Click on Platforms and find LPC1114FN28 (or go directly to the page)
- Click Add to Your mbed Compiler–if you see a button that says Remove, you’ve already done this
- Now head to the project page and import the project
- Compile the project and download the BIN file
Once you have the BIN file you’ll need to upload the program via your serial port. I’m going to use a utility called lpc21isp to do that. You can usually find this in your Linux repository, and there is a Windows version available, too. If you just hate the command line, you can always use FlashMagic or the official NXP Windows downloader. There are some GUI front ends for lpc21isp, too, but it is simple enough to use the command line.
The file you’ll download from the mbed website will be named HaD1114Demo_LPC1114.bin unless you changed it (I’ll assume it is in directory /tmp). You also need to know the name of your serial port (e.g., COM1 or /dev/ttyUSB8). The last thing you need to know is roughly what clock frequency the CPU is using. In our case it is 48MHz. Here’s the command line:
lpc21isp -verify -bin /tmp/HaD1114Demo_LPC1114.bin /dev/ttyUSB8 115200 48000
You want to engage the boot jumper and reset the chip either right before or right after executing that command line. The 115200 sets the baud rate and the 48000 is required so the software can sync with the bootloader.
Once you get a successful download, lpc21isp will tell you it is launching the new code. Don’t believe it — It isn’t doing anything yet. You’ll need to disengage the boot jumper and then reset the CPU again. If you prefer to do just a blinking LED, start a new project and that’s one of the boilerplate examples you can use in a new project.
Inside the Code
The code is simple. Just like the Arduino has a lot of helper library routines, mbed provides most of what you need to drive the devices on the CPU. There’s also an active community of shared libraries for external devices and example code. Here’s the simple code used for the demo:
#include "mbed.h" PwmOut myled(dp1); int main() { int i,j; while(1) { for (j=0;j<2;j++) for (i=0;i<1000;i+=10) { float pwm=i/1000.0; myled=j?1.0-pwm:pwm; wait(0.01); } } }
The mbed library frequently makes use of floating point numbers. In the example code, the PWM range is from 0.0 to 1.0. The wait call uses seconds, so 0.01 is 10 milliseconds (there is a wait call that takes a millisecond value, by the way).
The j loop keeps track of even or odd passes so the PWM gets reversed on alternate passes. When j is zero, the PWM goes from 0 to 1.0. When j is not zero, the steps go from 1.0 down to 0. Each pass requires 100 steps (0 to 1000, counting by 10s) so the total time per pass is about 100 times 10 millisecond, or one second.
What’s Next?
The mbed library is one place to start, and you can read its documentation online. If you are tied to the Arduino library, there is a port on Github (although I haven’t tried it). However, you can step up to bigger tools and even debugging when you are ready (there’s a good set of examples on Digikey’s eewiki, or you can keep using mbed with your own IDE and debugger). If you want a quick rapid prototyping arrangement, this set up will easily run a pretty nice Forth, too. And if you are concerned that this isn’t really a hack, you could always chop the chip down to size literally (although we don’t recommend it).
145 thoughts on “ARMing a Breadboard — Everyone Should Program an ARM”
I’ve always been surprised people pick Arduino over little Arm cores. There is a ton of code out there for Arms just like there is for Arduino. Personally as long as you can get the toolchain set up then I like the little F051 discovery boards by STmicro. Has a ton of features for an $8 to $9 board.
+1
I have really been enjoying the new msp432 by TI. Its nice having an Arm M4-f with its 32 bit floating point witchcraft in a package that uses less power than most popular 8 bit micros
+1 for MSP432
Worth noting it’s an ARM M4F core and supporting hardware, with MSP430 based peripherals. The LaunchPad version is supported by Energia, an Arduino-like environment, which puts down a version of TI-RTOS to it so you can multi-task sketches fairly easily.
The reason is that an Arduino is a microcontroller. This means it has lots of peripherals onboard that are designed to interact with the outside world – ADC, UART, I2C, Digital I/O with pullups/pulldowns, PWM controllers, timers and more. By comparison traditionally a CPU was just a processor core only, and required additional components.
The lines are blurring with ARM SoC units, but the differentiation still exists for a reason.
Arduino is a hardware/software ecosystem, not a microcontroller. These ARM parts are microcontrollers, also, so I’m not sure what you mean by this distinction. The CPU is an ARM (ARMv6 or ARMv7/v7E depending on the Cortex series), while the microcontroller on (most) Arduino boards features an AVR CPU.
The Raspberry Pi ARM microprocessor SOC (BCM2835/6) also has PWM, Timers, GPIO, UARTs, SPIs and I2C peripherals in the same vain as microcontrollers. The lines between microcontrollers and microprocessors blur only when you look at peripherals..
It’s pretty well defined if you look at whether the CPU core has a Memory Management Unit (MMU) and whether it can run an Operating System like Windows/Linux which uses the MMU to perform memory mappings between virtual and physical addresses. If this is the case then it’s definitely a microprocessor otherwise…it’s a microcontroller.
I sometimes notice that some people mean ‘ARM microprocessors’ when talking about ‘ARM cores’. This is not necessarily true.
ARM cores can be:
i) Microprocessor-based…the Cortex -A family (A5,A7,A8,A9,A15,A53,A???) …used in smartphones, Raspberry Pi, beaglebone blacks, routers, Linux/Android SBC’s e.t.c
ii) Microcontroller-based…with the Cortex-M family (M0, M0+, M3, M4, M4F, M7). These variants are the targets of this article. I believe there’s also a Cortex-R family of ARM microcontrollers intended for safety critical real-time applications…but I rarely see these variants discussed in the hobbyist community.
Uh. The difference between a microprocessor & a microcontroller has nothing to do with having an MMU. In general (there can be some overlap) the difference is that microcontrollers have built-in RAM, ROM & I/O, while microprocessors don’t. The rule of thumb is that if it’s possible to build a useful gizmo out of it without adding any other chips, it’s a microcontroller.
It’s because Arduino is absolutely everywhere and you can be spoon fed. and I understand the attraction. any time I find someone interested in getting in the hobby I point them directly at an Arduino as there is a metric ton of tutorials, howto’s and setting up to write and compile takes zero efforts no matter what platform computer they have.
Working out of the box, FIRST TIME, is a very rare and valuable thing. Often tools of whatever nature need tweaking, they’re made by people who already have a full understanding of the system, and forget about the assumptions implicit in what they do.
Being able to know absolutely, literally nothing about electronics and programming, and being able to construct an Arduino project in however many days, is a miracle. And unlike many other “miracles”, and this is the most important thing, it delivers.
No little tweaks, no “fixes”, no “you have to have xxx”, just plug and literally go. It’s easier than installing some software, and you get tangible results. Of course, from there, you learn, and your abilities grow. But being suitable for a beginner, and doing what it’s supposed to, is the key. No hours trawling the net and giving up. You probably won’t even swear once!
I’m a beginner with no programming experience and Arduino is my first and only choice because it seems much more accessible. I would love to try ARM or AVR programming but the learning curve seems steep.
The Arduino IS an AVR! Except the ones that are ARMs. Far as I know, the chip doesn’t make a difference, they run the same code, and the software manages the different compiling needed. You might not even know if you’re using an ARM.
Thanks!
You’re welcome! Of course the thing about running the same code only applies if they’re both in Arduinos, running the Arduino system, software etc.
That said, much microcontroller programming is done in C anyway. Some code would be transferrable across any processor. But things like on-chip peripherals, and other hardware issues, require some different programming, and of course on the small chips you don’t have a lot of RAM to store variables, so you have to take that into account.
Even on Arduino you need to know what hardware your chip has, but it’s quite well taken care of, not as complex as it could be, thanks to the libraries including the necessary code and keeping it fairly simple. Like I said in a previous post, it’s great how Arduino just works, simple as that!
ARM support in Arudino only left a long beta ~6 months ago.
mBed is a fine idea, but kind of a messy ecosystem. And whoever makes the core libraries *way* over-does the C++ fanciness.
When it comes to 32 bit microcontrollers in DIP packages, Microchip’s PIC32 line (based on the MIPS architecture) can’t be beat. They have at least half a dozen different choices in 28 pin DIPs, and several of them include built-in USB interfaces. They also offer more memory than the LPC1114, and they’re 0.3″ wide instead of 0.6″.
They also have a free, manufacturer-supported tool chain with no code size limitations.
I tried using ARMs, but between the PIC32 DIP chips and the free tool chain that I didn’t have to cobble together piecemeal, I switched to PIC32.
“Microchip’s PIC32 line (based on the MIPS architecture) can’t be beat.”
Yes they can and have already been beaten by ARM’s.
ARMs have beaten PIC32 in the general market. But I qualified my statement with “in DIP packages”. There are lots of ARM uC manufacturers and there is a grand total of one ARM chip in a DIP package. There are 20 PIC32s in DIP packages, and they have more memory and features than the LPC1114.
For hobbyists who want 32 bit microcontrollers in DIP packages, PIC32 is the better choice.
I agree with you Bob
One can get PIC32MX250F128B and program it with ChipKIT DP25 bootloader and use it with breadboard and MPIDE or UECIDE. I even found that chip at tme.eu preprogrammed with DP25 bootloader for less than 4 dollars.
There is also the LPC810 8-pin DIP that I use.
But I agree with you that those 2 are the only ones.
I like the PIC32 also, one thing I love is the additional RAM/Flash. I don’t need speed as much as I need more resources for networking, higher layer protocols and encrypted communications. I haven’t started really worrying about power usage yet but I guess that will come after I finish working the encryption.
I could care less about DIP packages. If I want to put an SMD part on a breadboard/perfboard, 9/10 times there’s a $3 generic breakout board available with the correct footprint and 1/10 times I can whip up one in eagle and get it from OSHpark in a few weeks. if the part already has a following, chances are adafruit or sparkfun sells it already mounted on a breakout.
Microchip has a free IDE that is pretty good, supports all chips, with no sign-up and no code size limit.
That goes A LONG way.
I hate PIC micros with a passion. But emotional baggage aside, they lack a decent free toolchain.
No and 2 main reasons :
– PICs come with no pre-programmed Bootloader.
-The toolchain is EXPENSIVE.
I wish it was not the case though :/
microchip does not sound ‘maker friendly’. their toolchain has issues, its not free, its not gcc-based, it varies a lot based on which chip type you use.
PIC could have been the arduino darling but they did not want to be that open. and so, I actively avoid PIC.
I will get into ARM eventually but I have zero interest in doing PIC work unless I’m being paid and given the tools for free.
their corp view is just not compatible wtih free software. since they are not the only player, I don’t have to agree to their rules. I’ll use other chips.
I routinely use SDCC for 8-bit PIC micros and MIPS GCC for PIC32. It is completely open source, actually both compilers are built from sources on my Linux machine. I program it using open-source PicKit2 programmer (developed by Microchip).
To me, their products are quite open-source friendly. What am I doing wrong?
On the other hand, Microchip doesn’t care much about open-source world (with a few exceptions, like PicKit2), this is mostly volunteers work. Microchip is a big company interested in big bucks, just like Atmel or NXP.
I like the PIC. But my whole point (not just to [jaromirs]) is that if you are working with things like Arduino there’s a lot of reasons you might not want to move up to 32 bit: toolchain set up, SMD, cost…. and so my point here is that this is a gateway drug. Costs too much. Nope. Hard to set up the tools. No. I don’t want to deal with SMD. No problem.
After you get going, you are going to think… “Well… I ought to do a real IDE so I can debug.” Then later you’ll say, “Eh… I guess I should get an SMD part on an adapter board.” But you’ve already got sucked in.
Granted PIC has a lot of package options and can be cheap. But the toolchain is not plug and play (to start) with the rich library/community support you find with Arduino or mBed.
But sure, for those of us who deal with SMD and are used to setting up toolchains, you can take your–no pun intended–pick. I use lots of different processors, but my point here was if you are clinging to an 8 bit Arduino, there are other options (including, of course, the newish 32-bit Arduinos).
Thinking like a salesman overcoming objections ;-)
Al Williams: point taken and I have to agree.
I made my transition to MCUs yars ago, so my point of view is different to that young player with Arduino in his hands and the Arduino (or mbed) ecosystem have much more sense to them, while being not that important to me. I just wanted is to correct the info that you can’t have free and open-source tools for Microchip MCUs. Seems like a lot of people don’t know about it. Another inspiration for next hackaday.io project: how to set up open-source toolchain for Microchip MCUs.
It is fantastic world we live in. So much hardware platform to choose from :-)
You can buy PIC32 with chipkit bootloader preprogrammed, though there is not PIC32 with internal bootloader in ROM.
Toolchain is for free. Can’t be any cheaper. Anyone can avoid Microchip’s toolchain and use MIPS GCC to program PIC32, just like ARM GCC is used to program 32-bit LPC or STM32. Just like chipkit is doing with their PIC32 “arduino compatibles”.
Do you need a Pic-Kit to program a PIC? Could an Arduino you already have be pressed into service? Since Arduinos are much cheaper than Pic-Kits, and often what somebody starts off with, would seem sensible. And I’d guess Pic-Kit itself uses an MCU. Presumably a PIC.
PicKit2 is programmer/debugger – quite handy tool – just like AVR dragon. Unlike it, it is fully open-sourced by Microchip and chinese clones, sold for something like 15 bucks are quite good. But there is more than one way to particular goal.
I’m pretty sure I’ve seen programmers for both 8- and 32-bit PIC micros built around arduino. The programming algorithms are open, I made a few PIC programmers before, it is not very difficult task.
Except for a few ancient PIC devices, all of them can do self-programming, so you can flash bootloader once (by using any method or asking a friend) and use it for further development, just like with arduino. By the way, this is how pinguino.cc project works, I believe you can buy somewhere PIC devices (or complete boards) with bootloader already programmed. Then, using pinugino, you can flash virgin MCUs to contain pinguino bootloader.
The toolchain is free, even without the $$$ optimizer it works well.
PIC32’s in DIP packages aren’t a bad deal. You have the free PINGUINO development suite if you want to do C programming or if you like embedded BASIC there is the Maximite that does video and other stuff. The BASIC is free and you just load it into the flash.
For PIC32s you can always attach the free uncrippled toolchain that comes with the ‘Arduino IDE’-like MPIDE (for chipKit) to the MPLABX IDE. That toolchain should be capable of all GCC optimizations and have full C support (C++ support is limited). Too bad Microchip doesn’t promote this solution for hobbyists.
I love Microchip’s devices but I’ve stopped using them because their development tools are so bad.
Their decision to sell their compilers and make available for free only a crippled version with no optimizations (especially for size you will reach the limit quite quickly) is incredibly short-sighted. I don’t think their compiler department brings in a big revenue to the company, but I’m positive it hurts the sale of hardware a lot.
Even with optimizations their compilers are just terrible and full of limitations, for example their XC8 compiler will use a shift-add loop for multiplication instead of using the hardware multiplier when the device has one. Their function calling mechanism causes problems if you use assembly in a function that is called from both main code and interrupt code. Also the more recent versions of their MPLAB X IDE have stopped supporting the ICD2 debugger that I was using. Why, is that to get me to buy their newer tools ? Which I did, but I ran into other issues, and that’s when I gave up.
The success of Atmel’s chips is in large part due to the availability of the free high quality compiler that is GCC and that allowed to make Arduino, an easy all-in-one package for beginners. Compare that to the confusing mess that is Microchip’s dev tools website. Even the code samples are crippled with a license that forbids reusing them freely. Their CEO should decide if they’re in the business of selling hardware or software and change that policy.
The LPC1114FN28 is getting pretty rare these days.
Almost impossible to source.
No surprise, it is a discontinued product. But the LPC810M is still produced in PDIP-8 and readily available at Digikey.
Apparently word of its death was exaggerated
Not really. It seems from the correspondence there that they discontinued it and then decided to reinstate it.
In my mind, the problem with the LPC1114 is that it is underpowered, memory starved (32KB Flash 4KB RAM) and doesn’t come with a rich peripheral set. Not to mention that unlike the ATMega328p and the PIC32s , the DIP package is the fat 0.6″ one from the 80’s…not the skinny one.
I think that we should all accept that ARM on DIP is really not going to happen (properly). Instead I’d like to see a relatively powerful ARM chip in a 28-SOIC package. SOIC’s are much easier to solder than the other SMD packages thanks to their 1.27mm standard pitch. They’re large when compared to qfp/ssop but significantly smaller than DIP parts and are easier to manufacture.
The SOIC part should have 28 pins with possibly 22-25 GPIOs. This seems to be the sweet spot for IOs. It must come with at least a Cortex-M0 core running at 48MHz, 64KB Flash, 8KB Ram, 2 UARTS, 1 I2C, 1SPI, 1 12-bit ADC, a UART/USB based ROM bootloader, timers, 10 or more PWM channels and a USB device peripheral.
I think if such a part exists it would be a real ‘gateway drug’ for getting hobbyists away from DIP parts. I know I would adopt it immediately.
BTW it is very easy to find soic packages. Go to digikey, search for ARM, then select the far right column “supplier device package”. SOIC28 might be too large, but SOIC20 is common. Personally I like TSSOP as it is pretty easy to route on home brew PCB.
Here are some of the soic: LPC812M101JD20J, CY8C4013SXI-400, ATSAMD09C13A-SSUT, MKE04Z8VWJ4
However the 810 is not in the supported platform list at developer.mbed.org.
Thats true however it’s the same as the 1114 so I wonder why they are not supporting the LPC8xx?
I used LPCXpresso and later ust GCC bare metal and flashmagic.
I believe the resources on the lpc810 are insufficient for the bootloader and core libraries (I last looked at this quite a while ago) – it is very constrained for an ARM core, but very fun to work with on little projects.
I think long term you would do better by simply picking one of the TSOP/SOIC/QFP versions, put it on a cheap SMD->DIP adapter board and be done with it rather than relying on an obscure version of the chip being produced (and stocked).
The SMD versions are often cheaper too.
I agree with this. The adapter boards are usually less than 50 cents on AliExpress, and soldering the chip on takes a few seconds. Not a big deal at all for one-offs or hobby work, and if you want to move up to building a board, you can go right to the standard SMD part without worrying about altered pinouts or whatever.
Great article. I’ll echo the other comments suggesting the STM32F0 eval boards–they’re like $8 or so. Definitely a bit tougher to set up than Atmel stuff, but I found a nice write-up here that got me sorted from the command line:
I’ll jump on this with another question for the masses–I’m working on an STM32F0 project and am running into the inevitable 5vdc –> 3.3vdc question. How does everyone else do it cheaply? I located a few switching supply chips that are fairly low cost in quantity ($0.40-0.60 or so), but they require a decent number of support passives and I’m worried about noise in general. Any other solutions I should keep my eyes on, keeping in mind that I still need to work with a 5vdc supply?
if you look for “level converter circuit” on google, qualifying that often with “3.3v 5.0v level converter circuit” you will find plenty, mostly involving simple diodes and resistors, amazingly. usually these are in the context of RS232 conversion but the exact same principle applies it’s counter-intuitive to use a diode *reversed* against the direction that you *think* should be “transmit”, but it’s because you’re sinking current down to 0v, from the higher voltage, so you want the “transmit” side to be pulled down from its higher voltage… it’s fun. you can get away with a couple of transistors and 3 resistors, as well, one of which is in… what is it… ahhh… it’s a non-obvious mode… ah someone else with more expertise will know what i mean, i’m sure, and chip in here. but, honestly, start from here, man: the simplicity of those circuits should be blindingly obvious, and many of them are part of online tutorials. good luck!
In terms of getting a 3.3V supply rail from a 5V supply rail, a simple lm1117-3.3 voltage regulator will do just nicely. Most GPIO’s on the STM32F0 (STM32’s in general) are 5V tolerant with the exception of the one’s attached to the ADC. For those one’s, you can look up a variety of voltage level translation circuits….there are a tonne out there.
There are $0.54 switch mode power supply modules on Aliexpress. The 3.3V LDO modules are around $0.35. Some of the sellers offer “Free shipping” if you don’t mind the wait or just want to stock up. Add a couple of good quality external caps to them and you are good to go.
For a properly designed SWPS, you’ll be looking at about 50mV or lower output ripples which isn’t much of an issue for digital chips.
I’m a bit leery of using Aliexpress sourcing for a design–I want a somewhat stable BOM over the next 3-5 years if possible. Any thoughts on stuff that’s available from other suppliers?
You don’t happen to have a link or two to modules you’ve tested?
Can you trust Aliexpress enough for that? Tried sourcing some ARM chips a while back and I wasn’t seeing good signs there.
Aliexpress is the escrow. If the individual sellers on there don’t ship, they get bad reviews and don’t get paid.
We are talking about prototyping here as it is more expensive to go production with DIP parts. For one, you won’t use a breakout board for production. You do want a more legit/trust worthy supplier.
The ARM product lines are going to be around for a bit. They have a 10 year commitment for the parts till 2025. :)
FYI: 3.3V LDO on Aliexpress
The most popular one seems to be the AMS1117-3.3 as that’s on a lot of the stuff coming from China. These have the same footprint (SOT223) as LM1117-3.3V, and there are plenty of alternate sources.
I bought mine here. There are no doubt other suppliers too. I paid $0.40 for a batch of 10 with “Free shipping”, so not going to spend a lot of time looking for cheaper. They come in on cut tape.
For french readers I have written a series of articles on using LPC810.
goto and search for LPC810
beginninng with:
You can get STM32F103 breadout boards at around $3 from China and use those jumper cables to interface to your stuff on a breadboard. You’ll save some breadboard space too. Why limit yourself to limited selection of DIP packages
Rather than forcing everything to be 5V, just use 3.3V as almost every new parts out there is 3.3V or lower these days.
You only handle the special cases where you have to take a 5V input. For ADC, use a voltage divider. For low speed digital inputs, you can get away with a 1K or so series resistor. As for output, 3.3V is above 5V TTL threshold, so no translation going that direction.
What kind of bread ;-?
Chinese bread
I love those green onion pancakes. :)
The little STM32F103 boards are pretty sweet to use. These is actually a community that has been porting the old maple libraries and is building decent support for there F103 in the Arduino IDE over at stm32duino.com.
I agree that ARM is the way to go in a lot of cases, especially due to the capabilities of DMA. It makes driving those touch screen boards with SD card readers a bit easier.
Of course, there is no need to use the Arduino IDE, but it is just another option for people to expand into ARM at a cheaper price point. The STM32F103 series chips are also pretty easy to source to be designed into a customer PCB so you could add in sutff like DACs.
USB @ 3.3v? Doesn’t the USB specification call for 5v, besides dropoff from crap cables?
Seems like a lot of USB power sources are incredibly noisy. The USB spec doesn’t have any explicit requirement for “clean” power over USB so it’s up to the receiving hardware to deal with it. I spent a lot of time “fixing” an analog sensor before I realized this was a problem.
Some serial USB cable have 3.3v l/O
I’m aware of that but the article is worded in such a way that it implies that USB has 3.3v natively. Not that there is a bit of circuitry somewhere doing the conversion. The parts list mentions said cable but he explicitly mentions USB cable within the body of the cable. A proper way to phrase it would be to say “adapter” because that’s what it really is.
I don’t usually use serial adapters, instead opting for slightly more flexible USB interfaces allowing me to pick almost any HID I desire.
not for the signals you don’t. the *power lines*, that’s a different matter, but things like the GL850G and the FE1.1 4-port hub ICs, those all run off of 3.3v power.
While a cloud-based ide is OK to get started for serious developments you need an actual toolchain with a compiler and make.
The other benefit to AVR development is its simplicity. The tiny13 datasheet is 176 pages, and tells you all you need to know to program the chip. I’ve been reading up on STM32F030 development and there’s a couple thousand pages across 3 documents to get the same info.
The chip prices cant be beat. A STM32F030 with 32K flash is 70c in small qty. Add a 15c qfp32-DIP board and you can be breadboarding for under a dollar. Like the LPC it has a serial bootloader in ROM so no SWD adapter is required for flashing.
Actually it’s two. The instruction table isn’t very detailed so you’ll usually get the instruction set documents for detailed explanations on the lower instructions. C programmers usually won’t worry about this but you deserve any punishments if you try using a tiny13 without the correct optimizations.
s/lower/lower level ASM/
On AVR, I like programming in asm.
Yes there is a 600 page minimum to ARM MCU’s but that doesn’t mean you have to know it all?
Use it as a dictionary and look up the perpherials you use.
It’s just as simple as any Arduino/ATmega.
My general experience is that those 700+ pages manual seems long enough until you start to use it. Then you wish it were 25% longer to cover the peripherals you want to use in more detail.
Someone ought to start work on The Universal Microcontroller Manual, a 2,000,000 page manual that not only details all the peripheral functions, but has documentation on every single glitch and bug in the hardware of every microcontroller in existence, and several not yet in existence, along with various ways to exploit them for various purposes (e.g. using internal clock frequency change as a temperature sensor)
It will require the clear-cutting of not only the entire Amazon rainforest, but the boreal forest as well, but that is but a small price to pay for ultimate knowledge.
You’ll find out that you’ll end up writing this
After all we are just cogs in a machine to calculate the Answer to the Ultimate Question of Life, the Universe, and Everything.
I drive 3.3v from 5v USB all the time with a simple voltage divider. Just another option.
Don’t forget the STMF32 Nucleo boards. $10 gets you the CPU, USB debugger, Arduino compatible headers and mbed compatibility (with drag and drop programming).
Trying install of IDE for it, i’m thinking that’s drug and drop
I had one for free. Was an introduction of this. Tons of problems with this chip. Now I can’t flash it anymore. No thanks I stay with arduino.
I’m almost ashamed to admit that I tried using an Arduino for the first time a couple of weeks ago. And I have to say.. it’s damn convenient. I’ve always used PICs before and since there’s usually a long down time for me between my projects it has always been a pain to start digging through the datasheets every time to see which peripherals I need to turn off/on, how to properly set up clock speeds, which pins I can use for what I want to do etc etc. With the Arduino my project was up and running within two days. Before it would’ve probably taken me 1-2 weeks to do the same thing.
It is bloaty though. Very little code (as in, code that isn’t linked in from some gigantic unknown library) fills the memory real quick like.
The thing with these ARMs from NXP, just as with the STMs is that they have a factory bootloader just as simple as Arduino. No JTAG or SWD required.
But once you get deeper you want to use those features.
I Always program my ATmegas with ICSP and dont use any bootloader.
In this case it wasn’t so much the bootloader (I’ve used that on PICs as well) but more the ease of setting stuff up and easy access to libraries that did what I needed. I used a small OLED, searched for it online and had a library for it and a display showing text within five minutes. I’ve looked for ready made code when working with PICs and almost always you have to tweak it in some way to get the damn thing to work.
I was just a bit surprised at how easy it was to use is all.
“Very little code (as in, code that isn’t linked in from some gigantic unknown library) fills the memory real quick like.”
yeah. total dross, isn’t it? i worked with the OSMC project back in… eek, 2001, i think it was? “apt-get install sdcc” and the compiler was there. quite a lot of source code involved in the OSMC (relatively speaking), and it *all fitted* into the PIC that was used.
then i found out about the arduinos, years later, and was shocked to find the vaast amount of utter dross that quotes has to be absolutely mandatory installed for use quotes. the clue is this: anything that requires a 160gbyte download (including the java runtime) to program a *1k* device, something is desperately, desperately wrong.
so, seriously: start investigating sdcc, and libopencm3, and some of the other recommendations here in this thread (someone else said they use the mips port of gcc with PICs), and you’ll find that you don’t start wondering if you’re going completely insane.
as an aside: i *DO NOT* compile the marlin firmware for my mendel90 with the utter shit that is the arduino “runtime environment”. i do “apt-get install libarduino-dev”, i get hold of the appropriate cross-compiler, i edit the Makefile to point to the library…. and i type “make”. i don’t like shit based on java (a) telling me what to do and (b) getting in the way and (c) interfering with the editing workflow that i’ve been using and refining for over 20 years.
that workflow is now “automatic” in my fingers and in my mindset. so if you have a good workflow that works for you, i strongly recommend that you tell people who think that “Thou Shalt Install Our GUI And Do It Our Way Because We Are Better Than You” to f*** right off, and stick with what works best for you, with a minimum amount of setup time / NREs to add the minimum necessary toolchain to *your* workflow.
of course, that applies to any advice i have given above: stick with what works for you… *including* ignoring anything i said above that doesn’t suit *you* :)
For micros these days, No local GCC compiler? No thanks. No GDB ICD? No thanks. No linux toolchain? No thanks. Dongle? No thanks. If these boxes are checked, you know you won’t be let down by someone else’s decision to drop support, to add a cost, to maximize profits this quarter etc, etc. To be stuck with an unsupported Windows operating system because the newer version does not have dongle drivers. To have your compiler company bought by the competition and shut down. And my favorite, a little close to home, to have your PCs stolen, with the compiler’s dongle still attached. A geographically diverse set of a couple of thousand hardware devices to support, so, expensive, but you just need to buy a new Dongle right. Until the supplier says sorry, it has been discontinued. So now you have to recompile, rewrite, confidence…?
Gray hairs anyone?
Not worth it. Answer? GCC GDB Linux. (I usually add openOCD and Eclipse too). Sure there is a learning curve, but that is only once.
Murray Horn.
Ah, a graybeard who’s dealt with proprietary developer environments before.
Yes, indeed. We would be very silly to go back to that kind of developer hell, only because someone else wanted control over us. I am younger, but I saw my dad go through that very situation you described. And then commence the pain and suffering.
And then he used his debugging skills and cracked the dev environment.
Well, in short I am not using ARM, even if i might want to, because the IDEs are a mess and I am comfortable with what I have and don’t need anything extra.
Reasons why I don’t use ARM:
-lack of free, complete IDE supported by the manufacturers
-i use 8/16 bit xmega and they are enough for my needs
-wanted to switch to atmel’s low range ARMs but they consume too much in standby and have worse peripherals than the XMEGA
-tried ST/NXP with free/puzzle IDEs … not satisfied
Reasons why I use ARM
-some work related stuff
-availability of nice, paid, complete IDEs.
-more powerful
Things that will not convince me to use them at hobby level
-web based ide
-3rd party, free sw
-DIP packages
Things moving in the right direction
-low cost programmers and dev boards
-more people interested
-the ARM core
Things that will convince me to use them
-manufacturer supported, complete, free IDE, even if gcc based.
-low cost programmers over 2 wires
-big enough community around them
FYI: Free/demo version of Keil MDK has a 32K limit on compile. It even install and set up the GCC toolchain for you. You can switch toolchain to GCC if you want. That path isn’t as integrated.
Very aware of that, however anything that sets a code limit is a bit out of purpose. 32K is too little for hobby use, i don’t go over it often, but frequent.
Tried TI’s Tiva-C line with Code Composer Studio (Eclipse based and free with GCC support and no code size limit)?
The LaunchPad variants have an on-board in-circuit-debug-interface / programmer that can be electrically isolated from the board and used to program off-board chips.
I might have missed this. I looked into TI arms quite a while ago, so I will give it another look.
Jesus! Why worie about limits?. Just learn to use that damn thing.
Doing GCC bare metal there are no limits, just upload the whole damn thing.
But you need to know how to use things.
When you know the limits are gone.
Check out Freescale’s KDS and their FRDM boards. Free Eclipse/GCC/GDB/OpenOCD toolchain and sub-$30 dev boards with onboard USB JTAG SWD debug adapters.
Check out the SiLabs Gecko ARM processors. They provide a free, unlimited Eclipse-based IDE with GCC/g++ under the hood. The chips also sip power, and some provide USB in tiny packages. They’re not quite Arduino-easy to get hello world going; you will invest some time figuring out all the clock trees to enable to each peripheral or else have some pretty infuriating failures. But the vendor libraries are pretty good, and every cheap dev/starter kit doubles as a SWD programmer/debugger for external boards.
To me, a lot of the comments would be like people saying: No car for me. I only drive trucks because it can tow a boat or a trailer. And I can put stuff in the back of it. No thank you to stupid cars!
Ok, that’s good for you. But there are a lot of people who want cars. My guess is that you guys aren’t using ‘duinos with the brain fucXXX dead IDE either. But a shiXXX boat load of people are. This seems to be a theme on this site’s comments: If it doesn’t meet MY needs then it is stupid.
Me? I like the freescale boards and I don’t care about the breadboard. I did start with mbed but quickly moved to a real IDE/debugger. But I clearly see the benefit to something like this. Just not for me at this time.
+1
Also FYI
Keil has free F0 and L0 for STM32 series. So no more 32K limit (for F0 and L0). More info :
Damn, another ARM compiler I’ll have to check out.
Its getting to be too many choices. With the AVR, its gcc and avr-libc and you’re off to the races…
A cross platform Free IDE supported by ST themselves can be downloaded from here (an accont is required)
I was successful in soldering 48QFN STM32F072 onto a 48QFN to DIP adapter from adafruit with a hot air rework station. I like the STM32F072 because it has an ADC, DAC, 4 UARTS!!, 128KB Flash and 16KB of RAM. The part also has USB device and a ROM bootloader that can be used over either USB (DFU) or USART…..An incredibly versatile part for $4 in unit quantity. I even built my own dip sized board (rev1…rev2 is in progress)!!!
I’ve also soldered the STM32F051 onto a 32-QFP(0.8 pitch) to DIP adapter from Adafruit. This package is the same as the SMD ATMEGA328p package and can be easily soldered by hand. The part comes with 64KB or Flash, 8KB of RAM ADC, 2 UARTS and a UART ROM bootloader (No USB)
You can also get the stm32F030 in a 20-ssop package which can be easily soldered onto a DIP adapter as well. The chip is ridiculously cheap . 16KB/32KB Flash 4KB of RAM, ADC, Timers, SPI, I2C, UART. Also UART based bootloader.
ST will be releasing some STM32F042 parts (with crystal less USB) in the 32-LQFP and 20-SSOP packages as well.
ST will also be releasing new Nucleo-32 boards based on parts that come in 32-QFP/QFN packages.
Also an STM32F303 part comes in a 32QFP package with USB and 2 5MSPS ADC’s 64KB Flash, 12KB of RAM and a Cortex-M4 running at 72MHz….a real powerhouse
The STM32F042F parts in TSSOP-20 have already shipped. I’ve been using one to make a cheap, tiny CMSIS-DAP SWD programmer with a BOM count of four (not counting passives).
@Devan, thanks for the heads up! I’m already completed my first STM32F042 board! I call it “The Little Critter”
I really wanted to like this…. gave it a try 1 year ago. Installation: smooth. Create empty project, select board….empty project with for loop: bam! linker error from the start. After this..try to find some led blink example. Where? Not place! no guide to get a led to blink.
when i said they lack free and complete IDEs….they still do. I should not need to look into 100 places to find how to blink an LED.
I like STs chips….. but sw side they are pretty bad.
Openstm has potential….but it is far from ok.
@Bogdan The STM32 microcontrollers have a lot going for them. There major weakness in my mind is easy to use software examples. But it’s not all doom and gloom. There’s ST’s IDE that I alluded too…nothing amazing but it’s pretty functional.
Have a look at this free tutorial based on the STM32VL-Discovery board. It’s based on the STM32 Standard peripheral libraries.
STM32 also recently introduced the STM32Cube libraries. I’m not a big fan of them because the api is all encompassing i.e. it tries to do all the ISR/DMA stuff in the background and gives the users simple callbacks to interface with it….it’s too high level but I can get used to it if I’m building a product but not the best for learning in my opinion. Luckily all the STM32F0 reference manuals have examples for getting things going at the register level without any libraries. There’s also the STM32F0Snippets
As far as building projects…its pretty straightforwards with the System Workbench tool. I also have no problems using GCC/make/VIM/GDB/OpenOCD as my workflow.
Under Linux there’s stm32flash a tool for programming STM32’s via the UART bootloader. There’s also df-util for programming USB capable STM32’s over USB (DFU). Finally there’s Texane’s stlink as well, which is an alternative to OpenOCD ..it’s basically and easier to use dedicated GDB server and SWD programmer tool
Thanks a lot. I ordered already the STM32F103 breakout board very cheap indeed
I agree, the STM chips are crazily cheap, and making up a few breakout boards gives the best of both worlds – breadboard prototyping, then use the same chip for smt production. And unlike AVR, there are a wide enough choice of chips at realistic prices to use for actual production.
Not sure about the best toolchain to use (there’s a project to have arduino IDE work), but with peripheral compatibility across the line etc, STM seem to me the obvious step up/successor to arduinos.
Also FYI.
Its mbed, not mBed… Just for sure.
How strange. I could swear I used to see mBed everywhere, but looking now, I don’t. Must be a bit flip in my firmware.
Kind of a nooby question…. I’m accustomed to the arduino serial viewer for debugging the actual code with printf function…. Question is, how am I able to see this on an ARM platform?
The mbed libs have a serial port object and you read it using the same serial port you bootload over. Very easy.
I am a hobbits and until now i have only programmed in assembler PIC 8 bit micro. I just tried the Arduino but the lack of debugger, the fact that is more expensive than a PIC and the Arduino can not be mounted on a PCB like a PIC does just push me back to the old PIC. I would like to try a new microcontroller that can be programmed in C and has more RAM, speed etc and i was pleased to read this article. Then i went on my favorite local electronic components supplier website to search for the LPC1114F… but they do not have it. A question: the free tool chain with the C compiler does include the debugger too? Any other suggestion of micros preferably bread board friendly that have free C compiler and debugger? I could do a a PCB adapter to mount a smd on the breadboard but i have to find also a guy that solder it for me, i would prefer to avoid that.
Try digikey:
I live in Thailand and I think if I buy from digikey will add delivery expenses and maybe customs tax.
If you want a DIP format, try Teensy 3.2 — sweet. or
$19 and great support!
I looked at your link . teensy seems to have much more resources than the 8 bit pic I am using but the price is much higher. A pic costs 2 $ and has a debugger. Sending variable values by serial port can also works as a debugger but… Are there better options? Cheaper and with debugger?
You are comparing apples to oranges. The Teensy is equivalent to an Arduino but much more memory and speed. Excellent price.
But check out TIs Tiva Launchpads, NXP LPXpresso, and STs Discovery and Nucleo boards. They all have free IDEs and debugging interfaces.
David
Thanks for your info. I have only used PIC until now and i have a question. Suppose i develop a program on the teensy board and I do not want to pay 19 $ for that board. Is it possible to buy the microcontroller only, program it and mounting on the definitive pcb? Do I need a programmer to do it or the microcontroller has a bootloader? Is it easy to do it? 19 $ is quite close to the cost of a raspberry and if you want to sell something the difference in price between 2$ pic and 19$ teensy means a lot. OK teensy is much more powerful too. But pic can do a lot too.
You can buy the chip, and the programming chip. However, that board includes: power supply, usb, etc. And has good engineering and great support… it would be very hard to duplicate at that cost.
Other interesting boards; Esp8266 based using Arduino IDE or the Particle Photon – both wifi/Arm.
David
The $19 teensy 3.2 includes everything i.e. voltage regulator, programmer, usb connector all on a very tiny form factor. To top it off, you also get the programming environment, compiler, and awesome libraries…No crippled compilers here. For hobbyists, the teensy 3,2 is one of the best deals out there hands down.
For those who need an even cheaper platform have a look at the Cortex-M0 based Teensy-LC…a little less powerful than the Cortex M4 based Teensy 3.2….but costs only $11-$12.
Teensy doesn’t have SWD debug or even a breakout for it. Serial ports can only get you so far for debugging when the ARM core goes into hardware fault. It is fine if you are causal programmer that copy/paste someone else’s code/library together or you are programming god that make absolute no mistakes.
That is a big disappointment over the development boards from chip vendors that comes with USB debuggers. Those can provide source level debugging if you are into writing your own driver or playing with DMA and other hardware bits in your bare metal code.
Therea rae tons of those as china clones all over ebay for about $2.99 to $4.99 each. Dont buy the official product unless you think you need official support
If you want to arm your breadboard with some pro hardware, check out the JIGMOD Kickstarter campaign. Just 4 days remaining.
Before it closed RadioShack had a super cool RISC PIC that I wanted to get even though it didn’t have the support.. Too late..
That’s sounds like the PIC32 (MIPS based). I use them with the Chipkit and Fubarino boards. I plan on designing my first modern PCB with a PIC32 as it’s main CPU. I’m using UECIDE (and MPIDE) as the Arduino env to keep things bit simple but I may need to get fancy and start write bare bones C/C++ code for future projects.
It looks like the vendor supplied dev tools are based around something called MPLAB.
It’d be way too expensive to dev with this chip apposed to ARM which has so many controllers on one chip. I wanted to do low-level dev on it. I probably would do a SBC with a VGA or ATSC chip.
The development systems is free – see PINGUINO or the MPLAB.
The 28 pin chips are around $4-5 in singles. PICKIt 3 programmer for $15.00. Investment is minimal.
Yes it would be expensive to develop on this chip if you had no money.
No code space for anything but a segment display, so you’d be buying other chips and adding discreet components. This is why ARM based chips actually hold so much market share because it’s already there and with libraries and plenty of code space.
The only reason I’m interested is for low level RISC dev.
I am very pretty sure ARM will be the best option for the future for at least the next 10 years. PIC sucks (very expensive)
I recomend to you the STM32F103 microcontroller (ARMv7 Cortex M3, 72 MHz, USB, CAN, etc)… and it costs only 1 dollar
+1 prettyamazing chip for the price!
David
The STM32F071 is pretty nice, and cheap.
I’ve really enjoyed using the LPC810 and then LPC812 to make UKHASnet wireless nodes, the switch matrix is particularly helpful – great place to start with ARM programming – its been nice to get away from arduino. Next step is LPC824 as its got an ADC…
I’ve extended the code base from microbuilder () to include some more functions ()
Also loads of great info from Jeelabs about using LPC81x and LPC824 ICs
Most common AVRs can run at at least 2.7V. Have done for years.
p.s. the ATMega328P will run at 1.8V as long as you’re happy to use a lower clock speed.
Have you ever considered Cypress PSoC ?
I used to use the old 8051 PSoCs and really liked them. I have two of the newer ones on my desk unopened because I’ll have to stand up a Windows environment to run the software. They are ARM core, if I’m not mistaken, and I do enjoy the architecture. But I hate having to boot a Windows VM just to do programming.
Please check this Hackaday old blog on the use of the LPC1114 ARM Cortex M0 Microcontrollers stuffed into a DIP28 package:
Coriudium still sells today a demo board complete with USB interface
A dev board for the LPC1114FN28 :
with forth…
I’m surprised Al didn’t mention this one.
I would recommend looking for the stm32f103c8t6 on ebay or aliexpress. It runs about $3 US in single quantities on a PCB with crystal and usb port. The pins are 600 mil spaced and fit nicely into a breadboard.
Thanks I will try one
New small factor Nucleo boards can now be bought from digi-key $10.99!!! And just after I’ve already submitted my STM32F042 board design for fabrication!!!! They look breadboard friendly (0.6″ DIP size)
These seem to be brand spanking new as I haven’t seen any announcements for them yet..though I did notice additions to the latest STM32F0Cube library (1.3) for them. Expect mbed support to be available in a decade or two (joke).
– NUCLEO-F042K6
– NUCLEO-F031K6
– NUCLEO-F303K8
Just noticed these boards are now up on the mbed site..though they’re not on the official mbed platform page:
I particularly like the F303K8 board. The stm32f303K8 part on the board comes with 2 DACs, opamps and 2 5MSPS ADCs. Not to mention 64KB Flash and 16KB Ram and a 72MHz Cortex-M4F core. The ADC’s alone are worth the price of admission. (In order to get the most out of the ADC’s though, you’ll probably have to use stm32Cube libs or register based code instead of mbed libs).
Another thing that I noticed is that the parts on the Nucleo-F042K6 and Nucleo-F303K8 both have USB device peripherals but are not advertised on the mbed site. I hope that these parts land USB support in mbed soon as it would make them even more attractive to use in the context of mbed.
One big reason for using thru-hole components is the ability to replace them easily.
I have beginning students working on Arduino projects that tend to accidentally burn out the I/O pins pretty often. If they do this, I replace the CPU chip, burn the bootloader and you’re done. ($3 vs $35) A surface mount dev board would kill us.
We have created our own breadboard CPU’s using SOIC or (sometimes) TSOP, SSOP to DIP adapter boards, but QFN, QFP or BGA pin cpu’s we can’t use.
We have most of our beginning students trained to use a ‘current limiting’ breadboard wire that has a 270 Ohm resistor spliced in to keep the current draw under 20mA at 5V from the I/O pins.
Savvy discussion ! Just to add my thoughts , if your company is searching for a GSA SF 93 , my colleagues encountered a sample version here.
Great Article. suggestions , I learned a lot from the specifics , Does someone know where my assistant might be able to get ahold of a blank IRS 1040-ES version to use ?
|
http://hackaday.com/2015/10/09/arming-a-breadboard-everyone-should-program-an-arm/
|
CC-MAIN-2017-30
|
refinedweb
| 10,389
| 72.46
|
:
Beginning Java
The art and science of java Chapter 9 programming exercise to draw a heart
Dennis Ouyang
Greenhorn
Posts: 11
posted 7 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
I have the correct code for the problem 7 in chapter 9 of "The art and science of java", which I found from a solutions manual online. Images of the page describing the problem are provided in attachment. however, I cannot tell how this programmer
found the correct values to pass to the GArc and GLine methods in order to draw the heart picture. I know it has something to do with trigonometry and fact that Math.sqrt(2) is the factor you multiply the side of a right triangle by to find the hypotenuse,
but I cannot see why the solution has those values for dx, height, and so forth. I realize this may be more of a math question than concerning
java
, but any help would be useful.
Javadoc on the ACM libraries I used if you need it:
.
/* * File: DrawHeart.java * -------------------- * This program draws a heart by assembling two arcs and two lines. */ import acm.graphics.*; import acm.program.*; public class DrawHeart extends GraphicsProgram { public void run() { double r = HEART_RADIUS; double root2 = Math.sqrt(2); double cx = getWidth() / 2; double cy = getHeight() / 2; double dx = r / root2; double height = 3 * dx + r; double top = cy - height / 2; double bottom = cy + height / 2; add(new GArc(cx - dx - r, top, 2 * r, 2 * r, 45, 180)); add(new GArc(cx + dx - r, top, 2 * r, 2 * r, -45, 180)); add(new GLine(cx, bottom, cx - 2 * dx, bottom - 2 * dx)); add(new GLine(cx, bottom, cx + 2 * dx, bottom - 2 * dx)); } /* Private constants */ private static final double HEART_RADIUS = 40; }
p361-Question-7-part-1.png
p-361-question-7-part-2.png
Campbell Ritchie
Marshal
Posts: 73243
332
posted 7 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Obviously the ACM drawing classes are an extension of Swing classes; I do not have them.
Does anything go wrong when you draw the heart? Did you work out the coordinates on paper before trying to program them? Here are some possible coordinates for the square:-
* 50, 10 * 10, 50 * 90, 50 * 50, 90
In which case the centres of the circles will be 30, 30 and 70, 30.
Dennis Ouyang
Greenhorn
Posts: 11
posted 7 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
here is my latest attempt. I tried setting the midpoint of the circle each arc is drawn from to exactly halfway between the points you display above. So the midpoint of the left arc would be (30, 35) for the left arc, and to define the upper left corner of the rectangle bounding the arc, I just subtract the radius, from the x and y coordinates, as seen below:
package Chapter9ProgrammingExercises; import acm.program.*; import acm.graphics.*; public class Heart extends GraphicsProgram { private final double HEART_RADIUS = 50; // length of ray is length of the GLine running from center of diamond to each vertex, and so is amt to add/subtract from the center point (cx, cy) to determine coordinates of each line. public void run () { double r = HEART_RADIUS; double lengthToRay = 100; double cx = getWidth() / 2; double cy = getHeight() / 2; add ( new GLine ( cx - lengthToRay, cy, cx, cy + lengthToRay) ); add ( new GLine ( cx, cy + lengthToRay, cx + lengthToRay, cy) ); add ( new GArc ( cx - lengthToRay / 2.0 - r, cy - lengthToRay / 2.0 - r, 2 * r, 2 * r, 45, 180 )); add ( new GArc ( cx + lengthToRay / 2.0 - r, cy - lengthToRay / 2.0 - r, 2 * r, 2 * r, -45, 180 )); } }
The arcs are still not connecting with the rays below. I have tried this with multiple sizes. I think the secret is to define just one number for either length To Ray (distance from center of the diamond to diamond vertex, or the radius of each circle that defines the left and right arcs, then just make all other coordinates functions of that, as seen in the official answer I originally posted. But I cannot tell how the official answer made the calculations. Nothing I remember on geometry tells me what, if any, relation there is between the radius of the circles making the left and right arcs and the rays that connect with them.
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
using 2 classes question
How do I flip/translate a GObject?
Bouncing balls
Drawing lines between JPanels/JInternalFrames
percentage based background scheme for a JPanel
More...
|
https://www.coderanch.com/t/635013/java/art-science-java-Chapter-programming
|
CC-MAIN-2021-31
|
refinedweb
| 793
| 63.73
|
This article describes how to build and test Web services that are based on Java API for XML Web Services (JAX-WS) 2.0 with the built-in capabilities of the NetBeans 5.0 IDE and the plug-in for Sun Java System Web Server 7.0 (henceforth, Web Server 7.0), now in Technology Preview 2. In this article, you also learn how to deploy and debug Web services.
This article assumes the following:
Note: Some of the URLs in this article contain
localhost and assume that the server instance is running on
localhost on port 80. Replace
localhost with hostname
: portnumber, as appropriate.
Before building a Web service, first create a Web application:
HelloWebServicein the Project Name text field, specify the directory in the Project Location text field, and choose Sun Java System Web Server 7.0 from the Server drop-down list.
Now create a Web service, starting from a service endpoint. Eventually, you will turn the Web application you just created into a Web service.
First, create and add a service class to the HelloWebService Web application:
ServiceImplin the Class Name text field and
my.sample.serverin the Package text field. Click Finish.
ServiceImpl.javaunder Source Packages to open the file for editing.
hello(java.lang.String)operation and specify the
portTypename, the service name, and the target namespace with JAX-WS 2.0 annotations, as follows.
Next, modify the
web.xml file to specify the JAX-WS servlet class and the servlet context listener:
web.xmlfile and choose Edit from the context menu to open the file for editing.
Next, create a
sun-jaxws.xml file, which is used by the JAX-WS runtime to specify the implementation class and relative URL for the service endpoint. Create that file under Web Pages/WEB-INF, as follows:
sun-jaxwsin the File Name text field. Click Next.
sun-jaxws.xmlfile for editing. Make its content read as follows:
As a final step, add the Ant target
-pre-dist to the project's
build.xml file:
build.xmlfor editing.
-pre-distAnt target to
build.xml, as follows.
After compiling your service class but before creating the WAR file, the NetBeans IDE calls the
-pre-dist target. That target calls the
wsgen Ant task, which creates the Java Architecture for XML Binding (JAXB) and JAX-WS files that are required for the Web service. For details on
wsgen, see the JAX-WS documentation.
Now build and deploy the project:
HelloWebService.warfile.
Next, run the Web project by choosing Run > Run Main Project from the main menu. The NetBeans IDE opens in the browser and shows the welcome page (
index.jsp in this case). To see the related information for HelloWebService, go to.
Note this optional but helpful procedure:
/helloin the Relative URL text field. this case, in a Web browser. That way, you can verify that the Web service has been deployed and browse the Web Services Description Language (WSDL) file. You can also edit the service class and verify the changes in the WSDL file by simply pressing F6 to rebuild and deploy the service.
Normally, the Hello service information is displayed in the browser as follows, which indicates that deployment was successful.
The simplest way to test the Web service is by using the Web Services Registry in the NetBeans IDE. Follow these steps: this case.
hello()operation.
To test the Web service with a JUnit test as a client, use the test capabilities in the NetBeans 5.0 IDE. Follow these steps:
ServiceTestin the Class Name text field and
my.sample.testin the Package text field. Click Finish.
ServiceTest.javafor editing and implement the
testService()method, as follows.
build.xmlfile.
localhostwith hostname
:portnumber, as appropriate, in the
-pre-compile-testAnt target below and add the target.
-pre-compile-test. When that target is run, the IDE ensures that the service is built and deployed and, if necessary, rebuilds the service. For details on
wsimport, see the JAX-WS documentation.
-init-macrodef-junitAnt target and append
${j2ee.platform.classpath}to the classpath, as follows.
-init-macrodef-junittarget of the project's
build-impl.xmlfile.
testService()to "World" and run the client again, you will see "Hello World."
To debug Web applications, right-click the project name in the NetBeans IDE and choose Debug Project from the context menu. The NetBeans IDE then starts the Web Server 7.0 instance in debug mode.
Alternatively, you can enable debugging as follows:, assuming that the installation is on
localhostwith the default settings.
Next, in the NetBeans IDE:
7896in the Port text field. Click OK. See Figure 4.
The debugger stops executing the program at the breakpoint you have set in the application.
To set a breakpoint, right-click a Java statement and choose Toggle Breakpoint (Ctrl+F8) from the context menu. You can set breakpoints in both service code and client code.
When debugging is complete, choose Run > Finish Debugger Session from the main menu to end the process.
This appendix describes how to create a Web service from WSDL. As an example, use the
AddNumbers.wsdl file in the
JAX-WS2.0/samples/fromwsdl directory.
Follow these steps:
AddNumbers.wsdlfile to the
HelloWebService/web/WEB-INF/wsdldirectory.
<servlet-mapping>entry to the
web.xmlfile.
<endpoint>entry to the
sun-jaxws.xmlfile.
-pre-compiletarget, to be executed before the
compiletarget, with the
wsimporttask, as follows.
-pre-compiletarget calls the
<wsimport>task, which generates all the necessary Java artifacts from the WSDL file and the referenced schema files. Those artifacts are generated in the
WEB-INF/classesdirectory with the
wsimport.generated.addnumberspackage.
ServiceImplclass, as follows.
wsimport.
The authors are grateful to Bobby Bissett and Milan Kuchtiak for their permission to use some code fragments and JAX-WS related text from their article, Building JAX-WS 2.0 Services With NetBeans 5.0 .
Thanks also to Mukesh Garg for his input during the technical review.
|
http://www.oracle.com/technetwork/java/websvcs-nb-138176.html
|
CC-MAIN-2014-42
|
refinedweb
| 983
| 59.9
|
,
since MonoTouch 5.4 I have a problem with a particular situation (I even tried the 6.3 beta).
The problem appears only on a real device: on the simulator, it works as expected.
Everything works correctly up to MonoTouch 5.2.13.
Unluckily I haven't been able to isolate the problem in a proper sample app, so at the moment I can just try to describe the situation.
I've created a base class to handle UIPickerView Models, UIPickerDataSource (you find it as attachment).
Basically, it's just an abstract generic class, containing a list of the elements that will be showed in the UIPickerView:
public abstract class UIPickerDataSource<TItem> : UIPickerViewModel
I have 3 implementations of this abstract class.
One is this, containing a list of DateTime? :
public class AvailabilityDatesDataSource : UIPickerDataSource<DateTime?>
{
public AvailabilityDatesDataSource(UIPickerView pickerView)
: base(pickerView)
{
}
public override string GetItemTitle(DateTime? item)
{
if (!item.HasValue)
return "---";
return item.Value.ToLongDateString();
}
}
The other implementations uses as generic argument a POCO class.
In a form I have only a UIPickerView that uses AvailabilityDatesDataSource as Model, in this way:
***
DatesSelectorDataSource = new AvailabilityDatesDataSource(DateSelector);
DatesSelectorDataSource.SetData(ViewModel.AvailabilityDates);
***
ViewModel.AvailabilityDates is just a IEnumerable<DateTime?>
When I run the app in the simulator, I can see in the UIPickerView all the dates with the proper values (in the tested situation, none of the elements in the ViewModel.AvailabilityDates is null).
When I run the app on the device, with the same data, I can see that the values exists in ViewModel.AvailabilityDates before calling DatesSelectorDataSource.SetData, but then the values become null when the method GetItemTitle of AvailabilityDatesDataSource is called (that is, the list contains always the same number of elements, e.g. 2 dates, but at some point they become null).
Just for testing purposes, if I change AvailabilityDatesDataSource from DateTime? to DateTime, the values are showed correctly.
As already stated, if I compile the same code with MonoTouch 5.2.13, also on the device I get the expected behavior.
I did also another test: I entirely copied the class UIPickerDataSource, calling the new one UIPickerDataSource2, and I changed AvailabilityDatesDataSource so that it inherits from UIPickerDataSource2 instead of UIPickerDataSource.
At this point, everything works!
I guess that some problems are caused by the fact that other classes inherits from UIPickerDataSource.
Have you got any idea about this problem?
Created attachment 2686 [details]
UIPickerDataSource.txt
You're creating a generic subclass of an exported class:
public abstract class UIPickerDataSource<TItem> : UIPickerViewModel
This is not supported, and may lead to all sorts of inexplicable behavior. I suggest you try making those classes non-generic (you can use Monotouch 6.0.3 to detect all cases where this happens - you'll get an error at build time).
See also bug #7390.
If it still fails without any generics, please reopen this bug report.
Thanks for the (very) quick response!
Ok, I will try without generics, hoping I don't have to change too much code.
I have also other controls in this way, and I've seen the error MT4112 in MonoTouch 6.0.2, signaled as a warning in 6.0.3: did you refer to this, when you say "error at build time" ?
PS: I cannot open bug #7390, it says "Access Denied"
Yes, it's the MT4112 message you can use to ensure you're not exporting any generic methods.
And I meant to point at bug #7547 (which is the but about the MT4112 error), not 7390.
We do understand that generic subclasses of NSObject is (unfortunately) quite common (we should never have allowed it in the first place, but it's a bit late for that now). The issue is that generics significantly increases the complexity of the interaction between ObjectiveC and managed code, and it will be a significant effort for us to support it properly - and for this reason I do not recommend that you wait for it. Even if we did start right away on it it would take several months before it would reach even a beta release.
However I have a few ideas which may or may not help you in the meantime if you're willing to try it out (remember that "it may fail/crash inexplicably at any time" still applies):
1) Don't instantiate generic types, create specialized non-generic subclasses of those types. Example:
var obj = new UIPickerDataSource<DateTime?> (); // BAD
var obj = new AvailabilityDatesDataSource (); // BETTER
Make all your generic classes (such as UIPickerDataSource) abstract, and the compiler will enforce this for you.
2) Specialize methods as much as possible - do not operate on type parameters in the generic classes, but instead do it in specialized methods in the derived non-generic subclasses.
// BAD:
class Bad<T> : NSObject
{
void BadMethod (T param)
{
// Do something with param
}
}
// BETTER
abstract class Base<T> : NSObject
{
virtual abstract void Method (T param);
}
class Derived : Base<object>
{
override void Method (object param)
{
// Do something with param
}
}
Again, if you make methods abstract the compiler will help you with this.
|
https://bugzilla.xamarin.com/76/7643/bug.html
|
CC-MAIN-2021-25
|
refinedweb
| 836
| 55.24
|
Textbook Notes (280,000)
Management (600)
Derek Chau (10)
Chapter 23
DepartmentManagement
Course CodeMGFC10H3
ProfessorDerek Chau
Chapter23
This preview shows half of the first page. to view the full 1 pages of the document.
Chapter 23 Options and Corporate Finance: Basic Concepts Notes
23.1 Options
•an option is a contact giving its owner the right to buy or sell an asset at a fixed price on or before a given date
•some important definitions related to options are:
1) Exercising the option. The act of buying or selling the underlying asset via the option contract.
2) Strike or exercise price. The fixed price in the option contract at which the holder can buy or sell the underlying asset.
3) Expiration date. The maturity date of the option. After this date, the option is dead.
4) American and European options. An American option may be exercised at any time up to and including the expiration
date. A European option differs in that it can be exercised only on the expiration date.
23.2 Call Options
•the most common type of option is called a call option
•a call option gives the owner the right to buy an asset at a fixed price during a particular time period
•there is no restriction on the kind of asset, but the most common options traded on exchanges are on stocks and bonds
23.3 Put Options
•a put option can be viewed as the opposite of a call option
•just as a call gives the holder the right to buy the stock at a fixed price, a put gives the holder the right to sell the stock for a fixed
exercise price during the life of the option
23.6 Combination of Options
•investor gets same payoff from (1) buying a put and buying underlying stock; (2) buying a call and buying a zero-coupon bond
•if investors have the same payoffs from the two strategies, the two strategies must have the same cost
•this leads to the result that: cost of first strategy = cost of second strategy
price of underlying stock + price of put = price of call + present value of exercise price
•this relationship is known as put-call parity and is one of the most fundamental relationships concerning options
23.8 An Option Pricing Formula
•the value of a call option is a function of 5 variables—(1) the current price of the underlying asset, which for stock options is the
price of the shares of common stock; (2) the exercise price; (3) the time to the expiration date; (4) the variance of the underlying
asset; and (5) the risk-free interest rate
The Black-Scholes Model
•C = SN (d1) – E e–rt N(d2)
where d1 = [ln (S/E) + (r + ½ σ2) t] / √σ2t and d2 = d1 - √σ2t
•this formula for the value of a call, C, involves 5 parameters and a statistical concept:
1) S = current stock price
2) E = exercise price of call
3) r = continuously compounded risk-free rate of return (annualized)
4) σ2 = variance (per year) of the continuous return on the stock
5) t = time (in years) to expiration date
6) N(d) = probability that a standardized, normally distributed, random variable will be less than or equal to d
23.13 Summary and Conclusions
1. The most familiar options are puts and calls. These options give the holder the right to sell or buy shares of common stock at a
given exercise price. American options can be exercised at any time up to and including the expiration date. European options
can be exercised only at the expiration date.
2. Options can be held either in isolation or in combination. We focused on the strategy of buying a put, buying the stock, selling a
call where the put and call have both the same exercise price and the same expiration date. This strategy yields a riskless return
because the gain or loss on the call precisely offsets the gain or loss on the stock-and-put combination. In equilibrium, the return
on this strategy must be exactly equal to the riskless rate. From this, the put-call parity relationship was established:
Value of stock + Value of put – Value of call = Present value of exercise price
3. The value of an option depends on 5 factors—(1) the price of the underlying asset; (2) the exercise price; (3) the expiration date;
(4) the variability of the underlying asset; and (5) the interest rate on risk-free bonds.
The Black-Scholes model can determine the intrinsic price of an option from these five factors.
4. Much of corporate financial theory can be presented in terms of options. It was pointed out that
a. Common stock can be represented as a call option on the firm.
b. Shareholders enhance the value of their call by increasing the risk of their firm.
c. Real projects have hidden options that enhance value.
You're Reading a Preview
Unlock to view full version
|
https://oneclass.com/textbook-notes/ca/utsc/mgt/mgfc10h3/16939-chapter-23-notes.en.html
|
CC-MAIN-2020-16
|
refinedweb
| 831
| 56.49
|
OverScrollEffectMode
Since: BlackBerry 10.0.0
#include <bb/cascades/OverScrollEffectMode>
Represents a set of states for overscroll effects in a ScrollView.
Overview
Public Types Index
Public Types
The overscroll effect mode type.
BlackBerry 10.0.0
- Default = 0x0
The default overscroll effect.
The system determines the overscroll effect for the ScrollView.Since:
BlackBerry 10.0.0
- None = 0x1
No effect is applied.Since:
BlackBerry 10.0.0
- OnScroll = 0x2
The effect is applied only when the user is scrolling.Since:
BlackBerry 10.0.0
- OnPinch = 0x3
The effect is applied only when the user pinch to zoom.Since:
BlackBerry 10.0.0
- OnPinchAndScroll = 0x4
The effect is applied for both pinch and scroll.Since:
BlackBerry 10.0.0
|
http://developer.blackberry.com/native/reference/cascades/bb__cascades__overscrolleffectmode.html
|
CC-MAIN-2014-15
|
refinedweb
| 118
| 56.01
|
Contents
Overview
Taskotron is a framework for automated task execution. It currently runs selected package
Our systems
Source code, getting involved and contributing
Taskotron consists of multiple separate components, mainly hosted in the taskotron namespace in Pagure. The general tasks that are developed along with Taskotron are named with the task- prefix.
Please see the contribution guide for instructions how to contribute.
The main mailing list for Taskotron discussion is qa-devel. The main IRC channel is #fedora-qa[?].
Documentation and further reading
Please see the Libtaskotron quick start and the Taskotron documentation. You may also find this further reading of interest:
|
https://fedoraproject.org/w/index.php?title=Taskotron&curid=52742&action=history
|
CC-MAIN-2018-30
|
refinedweb
| 102
| 50.33
|
Did you ever wanted to easily access data contained in the Steem blockchain and perform analysis or find valuable information. But not everybody has programming skills to gather those data and compute the wanted result.
Therefore, I created a publicly available SQL database with all the blockchain data in it.
Why use a SQL database?
The main advantage having such a database is the fact data are structured and easily accessible from any application able to connect to a SQL Server database. Having a SQL Server database makes it possible to produce quick answers to queries.
Simply put, a query is a question. You ask the server form something and it sends back an answer (called the query result set).
For example, when dealing with large amounts of data as Steem blockchain data, you might want quick answers to questions (queries) such as:
- What was the Steem power down volume during the past six weeks?
- Which are the top 10 most rewarded post ever?
- Did I get, me or my posts, mentioned in any post or comment?
- How many posts are talking about ants?
Browsing the blockchain over and over to retrieve and compute such information is time and resource consuming.
If you don’t have a local copy of the blockchain, instead of downloading the whole data from some external public node to process it, you will send your query to SteemSQL server and get only the requested information, saving tons of bandwidth.
Let’s have a look at some technical details
Database diagram
The Blocks table contains bare block information (timestamp, witness …)
Each block can contains Transactions
Depending on each transaction type, the associated transaction’s data is stored in the related table.
Full text search
The database has been full text search enabled. This allow fast search of information within post and replies.
Let say I want to know if anyone mentioned me in a post or comment, the following simple query will do the trick
SELECT author, title, body, url FROM TxComments WHERE CONTAINS(body, '@arcange')
Database Connection information:
Here the information to connect and query the database:
Server: sql.steemsql.com
User: steemit
Password: steemit
Database name: DBSteem
How to retrieve query the database
- Using Microsoft Excel
Check this tutorial to see how to create an analysis report with Excel
- If you’re a python programmer
import pypyodbc connection = pypyodbc.connect('Driver={SQL Server};' 'Server=sql.steemsql.com;' 'Database=DBSteem;' 'uid=steemit;pwd=steemit') cursor = connection.cursor() SQLCommand = ("YOUR SQL QUERY”) cursor.execute(SQLCommand) # do whatever you want with the retrieved data connection.close()
Support
If you need help, have any comment or request, join steemsql channel on steemit.chat
Availability and performance
The SQL server is hosted in a datacenter with 24/7/365 availability.
Available output bandwidth is up to 500Mb/s
New data from the latest blocks are injected in the database every 10 seconds.
The server is currently hosted in a shared infrastructure.
I will monitor server load and if it requires more resources, I will allocate any reward to this post to a dedicated infrastructure.
You like it, please upvote or follow me
the steemit account looks suspended, the service is no longer available?
it has moved to a monthly subscription model.
hi @arcange,
Is this database still working ?
If yes Then I am not able to connect to server using Sql server management studio.
I am able to connect just fine.
The database here is not responding!! I'm trying to connect to it from Java code and it says "Communication link failure". Also from comand line I run a ping and none of the packets come back!
Why MS SQL server, and not something more open like MySQL or PostgreSQL?
The fact the server behind is open or not does not matter to me.
The server itself is not open, only the data in it.
What's important is to have the required skills to manage it (including its security)and have it available to users's requests.
You're free to build your own if you really want an open source server.
How did you populate the database to begin with? If you're using the RPC mechanism, after 30 days some data is no longer returned. For example,
active_votesis empty for all posts after their second payout. You can even see this on steemit.com where old posts have zero upvotes.
All votes are in transactions and stored in the TxVotes table, even first votes ever :
@arcange
this is severely underrated. gave you my full blown 100%. we need this.
Thank you !
This is pretty good. I've been trying a few queries, sometimes taking a while. Would you consider adding some indexes on a few 'key' fields, or do you want to keep it like that ?
Post you queries in steemsql channel
I will analyze them and see how to improve DB design/performances
the differences between the graph database and the monolithinc, intransient relational database takes some compilation of data, and new blocks alter records, in ways that can be difficult to adapt, such as if a poster makes a really big edit, and suddenly the datatype has been overflowed.
But I think this is a cool idea. It might make a model for moving from a memory heavy graphene database to a storage heavy sql, maybe some sort of hybrid to cache data for faster retrieval or so.
SteemSQL database is a replica of the whole blockchain, not a compilation!
This mean if a user edit a post, you will find 2 or more transactions in TxComments with the same author/permlink but with different bodies/titles.
Compilation of data is made at query time.
Ah. So it's just another implementation of the graph database protocol, layered on top of a relational database.
This isn't a graph database at all, unless I am somehow mistaken.
No, it however has to implement one to allow the diff-updates that the platform allows, which essentially is a graph database (like CVS or Git). It just gives you the ability to search using SQL queries which are very concise and neat and easy to write, and with that pull all kinds of higher level data out of it. I think that was the purpose of building it - to allow more people to tinker with analytics.
Seriously, Doesn't this defeat the purpose of decentralization?
Why its defeat decentralization?
No. The essence of data analysis is collecting (aggregating ) data and making meaningful insights from it, which requires centralization by rule. The decentralized nature of the data isn't in jeopardy here because there are still unlimited copies of the Steemit blockchain out there ensuring that there is no vulnerable, mutable, single-source of the truth. This particular copy just happens to facilitate reporting.
Thankyou heaps for doing this!
I have a heap of ideas for queries but I've been trying to avoid the overhead of running my own full node - this is a far more efficient way to do it :)
I'll be following, great work
That's exactly the purpose of it: having an efficient alternative to local nodes.
Thanks!
As soon as I have some time I will use your steemit database because I am a data fanatic. Thank you for making this available. I am following you now.
Thanks!
I will closely monitor server as I made it a bit quick and dirty. I will now work on tweaking it for best performances
SQL Server is great - thank you very much for providing this!
You're welcome.
That's nice of you to make this available. hopefully you won't get flooded with requests that the resources requirements will require too much of an overhead :)
That could be, as for every service made public. But worth to experiment as it will be a good test for the infrastructure. This one is scaled for a normal usage.
The risk is indeed have bad response time if the load is to heavy. Then people writing poor queries might go away as they won't get correct response time.
Anyway, I will do my best to educate users on how to perform efficient queries.
Future will tell.
Argh!!!! I was just trying to build one of these!
I'm not sure whether to be upset I spent 2 days trying to make it work or ecstatic that whatever guided me, guided you there first.
Eitherway, I'm glad you did this, but super jealous you managed to pull it off faster than I could :)
Congratulations though, you earned my upvote. I'm following you now too!
I would have been super jealous too if you did it before me ;)
Everything was ready 2 weeks ago, but I wanted to fine tune and check every bit and byte of the infrastructure before releasing it. No worth to publish something if user experience is disappointing.
Many thanks for your support !
Cool!
Thanks!
This is a really great thing you have going here! Kudos for setting up a public node and service for the community. I sincerely believe this post should be upvoted like crazy and end with 3 or 4 figures. This does deserve more notice and appreciation. But from me, you've my upvote and follow. Thank you.
Thanks for your support!
The load is low at the moment but I already received lot of positive feedback of people wanting to use it.
I also wish I could get a few reward for this, not to become rich but to be able to put the server on a dedicated infrastructure with HA and DRS and ensure the best service to the community.
Hi, I can't connect using SSMS, do you use default port? (1433)
Ping to server is not responding, I'm not sure if i'm doing something wrong :(
Thanks for sharing!
SteemSQL has moved to a monthly subscription model and the default free account/password “steemit/steemit” has been disabled.
You will find more information about the subscription process here
Please visit steemsql.com for more information.! is not working?
Haven't noticed any problem.
Please use steemsql channel on steemit.chat for help or support
Just clicked on the link: , I got this:
The link in your first reply works.
The link in your last reply is broken (redirect to "," with a coma at the end)
It is useless to check "" website ATM as it redirect to this post
Still not working for me. No, it doesn't redirect to this post. Anyone else please check?
By the way the comma is a known old issue of steemit.com related to link parsing. It's off-topic though.
This is awesome! Thank you for your effort.
Doesn't this defeat the purpose of decentralization? If there is a central database with all the information on the blockchain, then wouldn't that create a vulnerability?
This would be better if the database itself was decentralized... I think I'll code one like this. Thank you for your information! :)
Thank you so much for hosting this! You are my hero! Successfully connected and doing some poking around in the data for fun tonight :)
I'm late to the party but I am excited about this as I am learning SQL at work and would love to use that knowledge to understand Steemit better and contribute to the community with that knowledge.
Do not hesitate to contact me on steemit.chat if you need any help to create amazing SQL queries.
Thank you, kindly.
hey, I'm playing with it right now. how I can I see the full architecture of the database?
All tables and their relation are shown in the database diagram in this post.
I thought there was another way as well
If you need help or have any request, please join steemsql channel on steemit.chat!
This is good. Although I like something like PhpMyAdmin more.
What hardware is your service running on? I'm curious about the scalability.
The server on a Intel Xeon E5-1650 v2 3.5Ghz 6 cores with 64GB memory, 8TB storage with MegaRAID 9271 Cache 1Go + CacheVault. It can be moved to a VMware HA cluster if required.
Sounds great.
Amazing. Glad to found this post. Thank you for providing the infrastructure. I have accessed it and it works well
Hi @arcange. Is this sever offline or no longer available?
This is way freaking cool. Man, I fall behind on #dev in steemit.chat by just a couple days and miss amazing gems like this. Well done!
Thanks ! Hopefully it will be useful to you.
I'm at RESTfest today, and I'm contemplating building a REST interface for the db as part of the hack day today... Hmmmm...
Best of luck! Waiting for any feedback.
Unfortunately, I wasn't able to get my local php connecting to mssql. :(
|
https://steemit.com/steemit/@arcange/steemsql-com-a-public-sql-server-database-with-all-steemit-blockchain-data
|
CC-MAIN-2019-18
|
refinedweb
| 2,155
| 74.29
|
Horn
Dependency:
compile "org.grails.plugins:horn-jquery:1.0.57"Custom repositories:
mavenRepo ""
Summary
Provides JS libraries and tags for embedding data in your HTML content using the HORN specification
Description
Provides JS libraries and tags for embedding data in your HTML content using the HORN specification.This enables you to render your data model as HTML for presentation to the user in the normal way, and have HORN pull this data out into a JS model for your client code to use. It You then alter the model from your JS and can reflect these changes back into the HTML.For details of the HORN specification see the docs. However understanding of HORN is not required for usage of this plugin.
Thus tags with
UsageInstall the plugin and then amend your GSPs to include the required resources and use Horn tags.The premise is simple:
- Horn tags with
pathattribute on specify a new relative or absolute model property path for their child nodes
- If the Horn tag has just text child nodes, these will be extracted and used as the
valuefor the model variable at the
pathspecified on the Horn tag.
pathare either defining a new value (text only child nodes) or defining a new path context for any values set in nested Horn tags.
This will result in the JS model containing:
<body> <h1>Welcome <horn:span${user}</horn:span></h1> <p>You have <horn:span${inbox.unreadCount}</horn:span> messages</p> <horn:div <g:each <horn:div${msg.text}</horn:div> </g:each> </horn:div> </body>
- { user: { name: 'a name here' } }
- { inbox: { undreadCount: 23, unreadMessages: {bodyText:'hello'}, {bodyText:'another msg'} (+) } }
Including the resource modulesHORN uses the Resources plugin. The Javascript resources required to parse out the HORN data into a model are defined in modules that you must
r:requirein your GSP or add to your own modules' @dependsOn@.The modules declared are:
- horn-html5 - HORN using HTML5 data attributes. This is the recommended module. Use this or horn-css, not both.
- horn-css - HORN using CSS classes. Only use if you cannot use HTML5 in your apps. Use this or horn-html5, not both.
- horn-converters - Extra optional code for converting values to and from text and native Javascript types. Include this if you want the default date conversions.
Accessing the model dataTo access the model data in your JS code, you just reference the
horn.model()function:
<r:script> window.alert( 'Unread messages count is "+horn.model().inbox.unreadCount); </r:script>
TagsAll the horn tags follow the same pattern, providing common HTML tag equivalents that take the attributes necessary for HORN data.The tags are in the "horn" namespace and support the following attributes:
Supported HTML tagsThere is built in support for most HTML5 tags. These are called using some attributes from the previous section, and their content is used as the value for the model variable denoted by the
pathattribute specified.
- horn:a
- horn:abbr
- horn:b
- horn:br
- horn:button
- horn:caption
- horn:col
- horn:colgroup
- horn:div
- horn:em
- horn:fieldset
- horn:form
- horn:head
- horn:html
- horn:i
- horn:h1 through to h6
- horn:input
- horn:label
- horn:legend
- horn:li
- horn:link
- horn:object
- horn:ol
- horn:optgroup
- horn:option
- horn:p
- horn:pre
- horn:script
- horn:select
- horn:span
- horn:string
- horn:style
- horn:sub
- horn:sup
- horn:table
- horn:tbody
- horn:textarea
- horn:tfoot
- horn:thead
- horn:td
- horn:th
- horn:tr
- horn:tt
- horn:ul
Calling Grails tagsSometimes you will want to use the text content of the output of a Grails tag as values in your model. To do this you use @horn:tag@.This example creates a link to a product Description that is extracted into the JS data model:
This simply delegates to
<horn:tag${product.description}</horn:tag>
g:linkpassing in all the arguments except from those used by HORN (path, tag, json, emptyBodyClass, template) and amends the attribute list to include the necessary values to hook up the HORN values.If you need to call a tag that uses any of these "reserved" attribute names, you can use the alternate form where you pass the attributes for the delegate tag in @attrs@:
<horn:tag${product.description}</horn:tag>
ConfigurationBy default the plugin defaults to using HTML5 HORN syntax, where data attributes are used for metadata. If you are not using HTML5 you can turn this off so that it falls back to using CSS classes for data.In Config.groovy:
You can also define the default CSS class used to hide empty or JSON data elements using In Config.groovy:
horn.no.html5 = true
horn.hiddenClass = true
|
http://www.grails.org/plugin/horn-jquery
|
CC-MAIN-2017-22
|
refinedweb
| 776
| 52.8
|
In this exercise, we will be focussing on the benefits of using
reduce() and
map() together.
Consider the example of having a dictionary representing a cost of an item sale called
costs which maps an item name to a tuple containing the total number of units sold and the price per unit. A dictionary entry would look like this:
"name": (total_number_of_item_sold, price_per_item)
We wish to find the total cost of all items sold. If this were a list or a tuple, we could simply apply
reduce() on it to find the sum. This, however, would present a problem if we attempt this with a dictionary.
The lambda provided to
reduce() requires that the two parameters and the returned value be of the same type. For example, in the lambda
lambda x, y: x*y, the
x,
y, and return type are all integers. As you can see, you cannot directly reduce a dictionary to a number because they are not of the same type; we must process the data in the dictionary first.
We can use
map() to iterate through the dictionary and compute the cost of every item sold. We can potentially store this in a tuple and then reduce that tuple to a single number, the total cost.
Note: when passing a dictionary as an iterable, the function will iterate through the list of the dictionaries keys.
Let’s look at an example with the following program:
from functools import reduce # Dictionary entry: {"name: (number_or_units_sold, price_per_unit_GBP)} costs = {"shirt": (4, 13.00), "shoes":(2, 80.00), "pants":(3, 100.00), "socks":(5, 5.00)} k = reduce(lambda x, y: x+y, map(lambda q: costs[q][0] * costs[q][1], costs)) print(k) # Output will be a total cost of: 537.0 GBP
This dictionary is passed into
map() along with the lambda
lambda q: costs[q][0] * costs[q][1]. The lambda function takes the price tuple and generates a total_cost_per_item by multiplying the
number_of_units_sold (
costs[q][0]) by the
price_per_unit_GBP (
costs[q][1]). The lambda in the
reduce() function is now working strictly with integers to sum them up and returns a total cost of £537.
We could have done this exercise using
namedtuple, but we excluded it for brevity. Using
map() to process a dictionary is key when working with the JSON format, as we will see in a later exercise.
Instructions
The dictionary provided represents the number of a given fruit sold over three days - a dictionary entry is:
fruit_name:(amount sold on day 1, amount sold on day 2, amount sold on day 3)
Using
map() and
reduce(), find the total number of fruits sold. Store this answer in a variable called
total_fruits. Make sure to print out your solution.
|
https://www.codecademy.com/courses/seds-software-engineering-in-python-i/lessons/functional-programming/exercises/reducing-a-mapped-collection
|
CC-MAIN-2022-40
|
refinedweb
| 456
| 70.23
|
PhpStorm 2017.1 EAP 171.2455
The new PhpStorm 2017.1 EAP build (171.2455) is now available! You can download it here or via JetBrains Toolbox. Or, if you have the previous PhpStorm 2017.1 EAP build (171.2272) installed, you should soon get a notification in the IDE about a patch update.
This build delivers new features, bug fixes and improvements for PHP and the Web, and takes on the latest improvements in IntelliJ Platform.
Improvements in support of PHP 7 Uniform Variable Syntax
This build brings improvements for PHP 7 Uniform Variable Syntax by RFC. Expressions such as isset/unset, foo()()().., and $some->foo()() style calls are now supported.
Auto-import of functions and constants
In this build, we’ve added auto-import of functions and constants. It will work for you automatically if Enable auto-import in file scope and/or Enable auto-import in namespace scope are enabled (Settings | Editor | General | Auto Import | PHP ).
Auto-import from the global namespace
We’ve added a new option to enable auto-import of classes, functions, and constants from the global space. The option can be found in Settings | Editor | General | Auto Import | PHP | Enable auto-import from the global space.
As an alternative to auto-importing functions and constants from the global namespace, you can ask the IDE to use global references. You can find this option in Settings | Editor | General | Auto Import | PHP | Prepend functions and constants from the global space with ‘\’.
This can help improve the performance of the PHP interpreter in some cases.
Fully-qualified class names in PHPDoc type description
Now when Use fully-qualified class names is enabled, it will be taken into account for completion, and the fully-qualified name will be used in the PHPDoc type description. The option can be found under Settings | Editor | Code Style | PHP | PHPDoc | Generated Doc Blocks.
Support for function/constant/namespace aliases in unused imports
Function/constant/namespace aliases are now supported in unused imports.
See the full list of bug-fixes and improvements in our issue tracker and the complete release notes.
Download PhpStorm 2017.1 EAP build 171.2455 for your platform from the project EAP page or click “Update” in your JetBrains Toolbox and please do report any bugs and feature request to our Issue Tracker.
Your JetBrains PhpStorm Team
The Drive to Develop
|
https://blog.jetbrains.com/phpstorm/2017/01/phpstorm-2017-1-eap-171-2455/
|
CC-MAIN-2022-05
|
refinedweb
| 393
| 57.77
|
Issues
generated app fails due to syntax error
Hello,
I have an app which is running ok when started from Python. I would like to use pyapp for packaging it on MAC OS 10.6.8.
The app is a small embedded webapp running with bottle microframework. It has been packages successfully on windows with py2exe.
I have the following py2app script
from setuptools import setup import sys, os, os.path wapp_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(wapp_path) DATA_FILES = [] setup( app = [ 'nsav_ws.py', ], options={ "py2app":{ 'argv_emulation': True, "includes":["shelve", "dbhash", "sqlite3", "waitress", "runpy_imports", "bottle_sqlalchemy"], "packages": ["sqlalchemy.dialects.sqlite", "sqlalchemy.util", "nsav_wapp"], } }, setup_requires=['py2app'] )
The setup.py py2app seems to be ok. I've a generated app file and I can see that it contains the right code.
Unfortunately, the app fails on startup. Here is the traceback:
25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] argvemulator warning: fetching events failed 25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] Traceback (most recent call last): 340, in <module> 25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] _run() 311, in _run 25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] exec(compile(source, path, 'exec'), globals(), globals()) 25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] File "/Users/luc/Dev/nelly_signe_avec_vous/nsav/nsav_mac/dist/nsav_ws.app/Contents/Resources/nsav_ws.py", line 2 25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] 25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] ^ 25/10/12 16:55:53 [0x0-0x118118].org.pythonmac.unspecified.nsav_ws[5126] SyntaxError: invalid syntax 25/10/12 16:55:53 nsav_ws[5126] nsav_ws Error
Is it a bug or a mistake in my use of py2app?
Thanks in advance Best luc
I'm not sure what's going on here. Is there anything special on at the start of the script?
Hello thanks for answering
just something basic : Please look at (i can't make python formatting in bitbucket comment)
I have no idea why it won't work. I'm assuming it works fine from the commandline given that your script works on Windows.
Something you could try to do is check if the problem is also present when you load your script the same way as py2app does:
If that doesn't give a clue: could you try to create a sample project that demonstrates the problem by removing as much of the contents of nsav_ws.py as possible (leaving just enough to cause the problem, without having to share all your code).
(formatting code should be possible with a block where the line before the block ends with a colon and the code block itself is indented 4 spaces)
Something else you could check:
py2app copies your script into the application bundle as myapp.app/Contents/Resources/nsav_ws.py. Does that script have the right contents?
check that are no strange characters on the second line:
Then check for unexpected text on the first few lines (all \x escapes would be suspect)
Thanks for your ideas:
The following code is causing a similar problem:
It seems that this is cause by windows type of line ending "\r\n". If i switch to unix type "\n", the code below works ok.
Is it something normal?
Executing the code with exec is ok. It runs the app without any problem.
However, it is still not working with py2app. The app fails with nsav_ws Error.
I've made a simple example with bottle and it runs ok.
In the traceback an error is raise in sqlalchemy:
I've opened the package and there is a util.pyc in sqlalchemy.sql. Any idea what can be wrong?
Thanks for your precious help
Windows line endings cause problems with compile() when using python 2.6. I've updated the py2app sources for this.
I don't understand the sqlalchemy problem, sqlalchemy should work just fine.
The SQLAlchemy problem could be caused by your setup.py file. Could you change the packages option to "packages = ['sqlalchemy']"? That will include all of SQLAlchemy.
Issue
#70: use 'rU' to open script files, otherwise launching won't work with python 2.6
Fixes issue
#70.
→ <<cset 26f3ad16737f>>
Thanks a lot :) using sqlalchemy rather than sqlalchemy.util in packages fixed the problem.
|
https://bitbucket.org/ronaldoussoren/py2app/issues/70/generated-app-fails-due-to-syntax-error
|
CC-MAIN-2017-26
|
refinedweb
| 743
| 68.06
|
Digital Thermometer with TI Lanchpad MSP430 and Sparkfun breakout board for Nokia 5110 LCD
The folks on the Energia project on github ( ) project have created a Arduino like development environment for the MSP 430. Their libraries hide the register manipulation details from the developer though knowing those details is important when tuning the power tuning and performance of the MSP 430 CPUs. The Energia project has a sample thermometer program that displays the current temperature on an the Nokia 5110 LCD display. Source is located on their github repository but don't appear in neither the 0101E0006 nor the 0101E0008 installation. The code creates a thermometer that looks like this, with the Nokia 5110 style LCD back-light turned off.
Hardware Configuration
Both the TI Launchpad and the 5110 style LCD run with 3.3v power and signal levels. No level converters are required when connecting them and when powering the LCD's back-light. The LCD has 8 pins including power, ground and the backlight control. This means there are 5 SPI style control pins to be managed by the Launchpad. I used only port 2 to control the LCD. pins_energia.h shows that P2.5 supports analog write so we could do PWM on the back light if we wanted to. Push button 2 is used to control the backlight.
I soldered male headers to the Sparkfun board and the TI Launchpad and then used female/female jumper cables to connect this together. It takes more space than direct solder but lets me rework without risking pads and traces.
I've modified the LCD 5110 demo pogram to report back the temperature to a host computer over the MSP430G2553's hardware UART running at 9600 baud. This is similar to the out-of-the-box TI demo program except that it converts the temp to decimal. The very simple code demonstrates how simple the Arduino environment makes common tasks. My Launchpad boards are version 1.4 which came with earlier CPUs. I upgraded to the later MSP430G2553 CPUs through the TI sample program and updated the board firmware. The only oddity there is the UART pins on the pre-1.5 boards are reversed because TI swapped the RX/TX pins when moving from software UARTs to hardware UARTs. You can see here how I swapped the pins on the header using an old cdrom cable. It just needs some shrink wrap. The code is super simple to support this.
Serial.begin(9600);
// the "display" variable
// contains temp string formatted for LCD
Serial.println(display);
Finding the Source
The firmware updates the LCD and reports over the UART/USB link every 1/2 second. The green LED's brightness indicates the magnitude of the temperature difference between startup and now.
// Red LED=P1.0 which is not on a timer
// see digital_pin_timer[] definition
// Green LED=P1.6 is on T0A1 where pwm is available
//
The demo uses software SPI because hardware SPI works on the UART pins which we want to communicate with the computer. The Energia header files say P1.2/P1.6, P2.1/P2.2 and P2.4/P2.5 can support analogWrite(), PWM. The Energia header file says there are only 3 independent analogWrite(), one out of each of the 3 pairs. P1.2 is RX and P1.6 is the on board LED which we will make use of in the program. This leaves the port 4 PWM capable pins for LEDs (2 independent) or servos.
Energia Example Program ModificationsThe original source also works for the LCD Shield, which I don't use. The no-argument constructor in LCD_5110.cpp is the code snippet below. This has the advantage of putting PWM on the backlight while leaving one open PWM on P2.5.
LCD_5110::LCD_5110() {
LCD_5110(P2_2, // Chip Select
P2_4, // Serial Clock
P2_0, // Serial Data
P2_3, // Data/Command
P1_0, // Reset
P2_1, // Backlight
PUSH2); // Push Button 2
}
The no-arg is called when this line is evaluated on start-up:
LCD_5110 myScreen;
Calling the parameter driven constructor lets us reorder the pins. I didn't really need PWM on the back-light. The following constructor call isolates all of the LCD to port 2 which is kind of slick. It makes for clean cabling but it also ties up 4 out of the 6 pins that support analogWrite() if you wanted to add servos or fancy LEDs.
LCD_5110 myScreen =
Reordering the pins can free up 2 independent port 2 analogWrite() pins, giving us 3 independent PWM to work with, including P1.6. The following puts sparkfun pins 3,4,5,6 on one side of the Launchpad and 7,8 on the other.
LCD_5110 myScreen =LCD_5110(PPWM/analogWrite() stays available on pins P2.2 and P2.5, and 1_6 if you give up the magnitude indicator on P1.6.
Arduino Style Main Program with UART
The Energia IDE includes the appropriate headers and definitions based on the board type. You Must select the correct "board" type in the Tools-->Board menu. Choose Launchpad w/MSP430g2553. This tells the system the amount of available ROM space, the fact that we have a Hardware UART and configures the IDE for the right registers and other features.
// // LCD_5110_main.ino // Sketch // ---------------------------------- // Developed with embedXcode // // Project LCD 5110 // Created by Rei VILO on 28/05/12 // Copyright (c) 2012 // Licence CC = BY SA NC // // Modified by FreemanSoft to send the current (text) temperature to the hardware serial port @ 9600 baud // // Core library #if defined(__MSP430G2452__) || defined(__MSP430G2553__) || defined(__MSP430G2231__) // LaunchPad specific #include "Energia.h" #else #error Board not supported #endif // Include application, user and local libraries #include "LCD_5110.h" #include "Thermometer_430.h" // Variables
//This version isolates to just port 2
/*
*/
LCD_5110 myScreen =
//This version saves P2_2 and P2_5 as independent PWMLCD_5110(PThermometer_430 myThermometer; boolean backlight = false; int ledPinGreen = P1_6; int ledPinRed = P1_0; // Add setup code void setup() { // try and find minimum PWM values myThermometer.begin(); myScreen.begin(); myScreen.setFont(1); myScreen.text(1, 1, "MSP430"); myScreen.setFont(0); myScreen.text(0, 5, "1234567890abcd"); delay(2000); myScreen.clear(); myScreen.text(2, 0, "Thermometer"); myScreen.text(0, 5, "off"); Serial.begin(9600); } // Display mask supports 3 digit + one decimal place char display[8] = {' ', ' ', ' ', '.', ' ', 0x7f, 'C', 0x00}; char displayCalibrationPoint[8] = {' ', ' ', ' ', '.', ' ', 0x7f, 'C', 0x00}; // Add loop code void loop() { if (myScreen.getButton()) { backlight = ~backlight; myScreen.setFont(0); myScreen.text(0, 5, backlight ? "on " : "off"); myScreen.setBacklight(backlight); } myThermometer.get(); // Temperature display int32_t number = myThermometer.temperatureX10(); calculateTemperatureDisplay(display, number); int32_t difference = number- myThermometer.calibrationX10(); // show calculated difference if (difference < 0){ calculateTemperatureDisplay(displayCalibrationPoint, -difference ); } else { calculateTemperatureDisplay(displayCalibrationPoint, difference ); } // show delta in corner myScreen.setFont(0); myScreen.text(7, 5, displayCalibrationPoint); // show the temp in large font myScreen.setFont(1); myScreen.text(0, 2, display); Serial.println(display); displayTemperatureChangeIndicator(difference); delay(500); } void calculateTemperatureDisplay(char *buffer, int32_t number){ boolean flag = (number<0); if (flag) number = -number; buffer[4] = 0x30 + (number%10); number /= 10; buffer[2] = 0x30 + (number%10); number /= 10; if (number>0) { buffer[1] = 0x30 + (number%10); } else if (flag) { buffer[1] = '-'; flag = false; } else { buffer[1] = ' '; } number /= 10; if (number>0) buffer[0] = 0x30 + (number%10); else if (flag) buffer[0] = '-'; else buffer[0] = ' '; } // can't really seem to get the pwm to work right for the RED light // this is because the // red LED is on P1.0 which is not on a timer see digital_pin_timer[] definition // green LED is on P1.6 which is on T0A1 where pwm is available // void displayTemperatureChangeIndicator(int32_t tempChangeX10){ int pinValue; if (tempChangeX10 > 0){ pinValue = tempChangeX10 ; } else { pinValue = -tempChangeX10; } pinValue = pinValue << 3 ; if (pinValue > 255) { pinValue = 255; } // green is the magnitude analogWrite(GREEN_LED,pinValue); }
This reminds me of the time I tried hyper hacking a Nokia 90 communicator to update its firmware. Had to connect it with cables and cat5e for the modem. Check it out simple answers to the question.
The best moment i think when somebody stealing a meat thermometer i really enjoy to read your article and also the digital thermometer make this topic more interesting. thermometers.co.uk
OXYPRO Cleaning System is one of the leading brands providing quality, and environmental-friendly Specialty cleaning solutions for laundry, kitchen, housekeeping, food manufacturing, and industrial industries.
|
https://joe.blog.freemansoft.com/2012/08/digital-thermometer-with-ti-lanchpad.html
|
CC-MAIN-2020-50
|
refinedweb
| 1,361
| 56.35
|
Episode 181 · April 10, 2017
Let's take a look at using the Webpacker gem in Rails to implement an additional pipeline for building modern frontend Javascript alongside our Rails application using VueJS.
What's up guys? This episode we're talking about the new rails webpacker gem. webpack, if you aren't familiar with it, is kind of like an asset pipeline that's build in a pure JavaScript, so the JavaScript community tends to use that a lot to be for their build pipelines, for building out vue or react or angular applications like that, it will let you write in ES6 syntax, and then you can take that, compile it down to the JavaScript that your browser can understand and then build out all your modules, install NPM packages and everything like that, and it will handle all of that stuff for you. Rails is adding support for webpack and you will effectively have two asset pipelines now. You'll have the asset pipeline where you'll still write your stylesheets, put your images, all that Jazz, and you'll also write your app like front ends in JavaScript in the webpack section if you want to go ahead and do that. Now you've always been able to do this in the asset pipeline, but it doesn't give you a good experience when you're building that stuff, so what webpack is actually going to allow you to do is module reloading and all kinds of other things, as well as a basic support for babel so you can write things like ES6.
Keep in mind, this gem is actually for rails 4.2, and up, but officially they're only supporting rails 5.1 and higher, so if you're using rails 4.2 or 5.0, you can definitely still use this, and it works great. But ther is a chance, a small chance that they might end up doing something that makes it incompatible with those versions. So keep that in mind as we go. I would wait into the first official release of this before you go and put it into production, but let's take a look at how you can set all this up in a rails 5.1 rc1 app right now, and just give you an idea of how it all works, and how you can put all of this stuff together using a front-end JavaScript framework like VueJs. So we're going to use vuejs, it's my personal favorite, out of all of them for many reason, and we're going to build a small example with tht and then I'm going to follow up with a second video showing you how we can make vuejs actually turbolinks compatible, which is pretty neat. So with webpacker, you're going to need of course webpack installed, which actually is easily done for you. You need to make sure that you have node js installed in your machine, as well as the JavaScript package manager called Yarn. So this is more recently come out as kind of a replacement for the npm command, so Yarn is what we'll use to add vuejs or any other node modules to your rails webpack set up. That is going to be all we really need, so it mentions that here in the prerequisites: Make sure that you install node and yarn, this also applies to production, you're going to need yarn in production as well, so that when you precompile your assets webpack can go ahead and install those packages with yarn and then compile those assets for production. One of the nice things that this gem does is it provides you link tags that are very similar to the asset pipeline tag, which means that when you pre compile you assets, when you deploy, all of that is going to work very very similar to the way that your JavaScript works in the asset pipeline. We don't have to learn a whole lot to use the webpacker set up, we just have to do acouple little set up things and we are good to go. Let's dive into an application and see how this works.
I've created this simple application, it's a really basic web app with one scaffold for a model called "Pages" and they have a title in that and that is simply it. All we're caring about is to have a few pages to navigate between so that we can make sure that our JavaScript is working, so that is a really basic application and if you are adding webpacker into your application, you can jump into the Gemfile, dropdown into the bottoma and add webpacker, and you're going to want to do this from the GitHub repository from the webpacker, for now, because that is going to install the latest version but because it hasn't oficially been really released yet, the latest code is always going to be up on GitHub and give you the most stable ad the best features until they release the first version, in which case you can switch to useing that published one. So we'll install this, and run
bundle intall to install that. Make sure that you have node and yarn installed around this time, so once that is done, you can run
rails webpacker:install. This is how you would install webpacker in any old rails app. There's also a --webpack option that you can use to have it installed by default in any new rails app as well, but we're just going to install it manually in this example. So
rails webpacker:install is going to create an app/javascript directory, so not app/assets/javascript this is app/javascript, and that you can see right here. This is effectively the location where all of your webpack javascript is going to live, so all of your front-end javascript is going to live now inside of this now for your react code, or your vue code or angular or whatever, and keep in mind that this is all now requiring us to run a separate process to monitor all of those files. So normally when you do a request in rails, you will have rails load, and then it will hit those assets, and then the asset pipeline precompiles them so that your browser can use them in development. Well, we now have to run webpack separately, so we have the webpack dev server, which is the one I would recommend, but you can also run the webpack watcher in development, and you have to run that side by side with your rails app. So what we can do is after this has installed all the packages, which it creates a bunch of config files and installs this bin stubs, and then it installs yarn add webpack and all of this stuff to your rails app, and installs all of those and you can go back and run your rails server and in another tab, you're going to need to run that
bin/webpack-dev-server, so that that can serve up the webpack JavaScript files, and it's going to come from localhost:8080, so you want to make sure nothing else is running on 8080, and your rails app can run on the standard 3000, so you'll still go back to your browser and load up localhost:3000, but in this case, we don't have any of that JavaScript loaded, so one thing when you get to set up is that you have to config the webpack folder. You don't really need to modify any of these configs, but if you want to look at that stuff, you can go ahead and do that, but the key here is that now we have this app/javascript/packs folder with application.js there which is different from the application.js in the asset pipeline. The comments up here show you there's a new JavaScript pack tag rather then the JavaScript include tag that we're used to. This is slightly different, and links to that port 8080 version that comes to webpack. In production it will actually just link to the file, so we need to put this in our layout, if we want to use any of our JavaScript from webpack, so we have to mention these files seprarately than the ones that we want to do with the asset pipeline. So you're going to keep both of those still, and you can load all of the JavaScript like the ujs stuff from rails if you want it. And you'll keep that with your JavaScript include tag, but your webpack stuff will be separate using the JavaScript pack tag. If we save this, this is going to load that application.js in our app, and if we refresh this page, we get "Hello World from Webpacker", so this works, and it's now including that, and it's coming from that localhost:8080 that separate server that we have right here, this is running and serving up that JavaScript file, and inside of here, we can do whatever we want. We can create and reference modules and anything that we would typically do with node modules, our JavaScript modules, we can create a app/javascript/gorails/index.js and here we can
export default { gorails: true } and we can import it in our other JavaScript file, so we can say:
app/javascript/packs/application.js
import GoRails from 'gorails'
This is going to reference that javascript/gorails directory, and it's automatically going to run or load up that index.js, so we're effectively assigning a local variable here called GoRails that imports that stuff that it exports, which is going to be this
gorails: true, so we could
console.log(Gorails), and if we save that, we can go back into the browser, and we see that
Object {gorails: true} so we have imported code from that other file and loaded that into our application.js, something to note here is that if you comment this out, and you say: "Hello from Gorails", and hit save, so you don't have to do anything and you can go back to your browser, and it's already caught that change, recompiled the JavaScript and it's actually reloaded it in your browser which is really nice because if you were going development of heavy JavaScript stuff, you need to be reloading that pretty regularly, you can get those new changes, I'm sure you're familiar with that process of hitting refresh constantly, this takes that away from you and does that automatically so that you don't have to worry about it, so it's pretty nice and convinient when you're building your front-end like that when you want to make sure that you make changes whenever you save those files. This is pretty cool, it allows you to then go build out your modules inside the app/javascript folder, organize it however you want, and then you can do your importing and everythign between those modules just like you would including modules and ruby or referencing other classes and things. This is all self-congtained inside of that app/javascript folder and you can add other dependencies that you want using yarn, and one thing I didn't point out, is that now you have this package.json. This is pretty much the same thing as your Gemfile, you reference the packages that you depend upon and their versions, and then when yarn is run, it will install all of these, so then you can add packages to this list once yarn is run you can update the yarn.lock which is of course pretty much the same thing as the gemfile.lock it locks down the versions that you have run and then it makes sure that when you update this for production you end up getting the exact same versions so you don't get anything unexpected when you deploy to production and maybe accidentally got two new versions, so this takes care of your JavaScript dependecies, pretty much the same way that the bundler library does that for your ruby dependency so that is really nice as well. Now I know I mentioned I was going to install ujs here, well one thing that we can do is we can use
rails webpacker:install:vue to install a vue application, so it's very very simple, but we can install that in our rails app by running this command, which is also an option for react and for angular that will give you a very basic example that gives you a place to start and think about how you want to organize your front-end. The view one also comes with this really cool, so if we go into the view stuff there's hello_vue.js and app.vue which is actually a single file component, so this single file contains the template as well as the JavaScript for that component, and then it also includes some scope styles for as well, which is really nifty, because this is going to be a single file that includes all of the things that are related to that component, so it's fully modular and you're not putting your template in one place and you're not putting your template inside of your JavaScript for the component, and you're also not putting your styles in a totally different place or anything like that, so it's all organized nicely inside of this, and separated into their different sections here, so this hello_vue.js is actually what requires vue, so one of the things that it did when it ran that command was that it actually did
yar add vue vue-loader vue-template-compiler, and that actually goes and tells yarn to add that to you local packages.json so now our packages.json has vue, vue-loader, vue-template-compiler and that is added to that, so you can either use yarn to add dependencies, or you can use this file directly and edit it, and then run yarn to install it. So it's usually easier to run yarn add, and we'll go ahead and do that for you, so we now have this hello_vue.js which is the actual location that we want to insert into the browser so if we were to go back to our layout/application.html.erb, rather than doing our application.js as the include, we could do
<%= javascript_pack_tag 'hello_vue' %> as the include, and this is going to include that, and then compile it and then run that in the browser, so if we hit refresh, we're going to get an error this time, because that hello_vue.js isn't in a manifest.json , so inside that manifest.json, it says which files are available. In this case, we needed to restart the webpack dev server because when you use those helpers, they actually configu those webpack loaders, so that needs to be restarted so that it picks up that config change, and then if we refresh this page, we get "Hello Vue" at the bottom, and we can see that we're running a view in development mode and everything is working, so we now have a vue app, but unfortunately, if we navigate to another page, it does not include vue, and you can see that it disappeared because turbolinks cached that version and it didn't re run it, so one of those things that we could do is change the event listener to
turbolinks:load the same thing as we do with all of our other JavaScripts, this simple inserts an element at the very end of the body, and then tells vue to initialize on that element. This is pretty straightforward how that works, but of course if we want to run that in every page, we need to run that when turbolinks loads, so if we hit Show, turbolinks runs the load event which triggers vue to render here, and if we hit back, that all works, except the browser back button actually does weird things, so it's going to do something kind of unexpected, and the reason for this is because that turbolinks is actually caching the final html on the page because we are dynamically rendering stuff with vuejs. That is not actually the html that rails would have given us, which we really want to cache, this is actually rails plus ujs's html, and we don't really want turbolinks to actually cache that, so we have built a vuejs mix-in which will make it turbolinks compatible which I will talk about in the next episode. So webpacker is a pretty straight forward implementation with rails, it gives you a lot of nice integrations that are familiar so that javascript pack tag in our layout is very familiar with what we're normally doing. We do have to run that additional process here in the terminal. So things like Foreman where you can set it up to say: Well we need a web process, we need a webpack process we need maybe a sidekick process, and it can manage and run all of those, and then shut them all down when you want to stop doing development, that can be very useful when you're using something like webpack now with your applications, because you have to manage rails, webpack, sidekiq maybe some other things like elasticsearch, I don't know, depends on your application, but if you add that, it now has an additional process which can be conveniently managed by Foreman, we'll talk about Foreman in the future, but if you want to learn anything more about webpacker their README is very good, it goes into a lot of the configuration stuff as well, if you wanted to include maybe some Sass styles inside of your JavaScript modules here, you can also use the style sheet pack tag, and it talks about how you can use require instead of the import like I did, and you just need to learn a lot more about how the modern JavaScript staff works if you want to dive into a lot more of this deeply. This README is still work in progress, but one thing I want to mention before we go is that the deployment process is no different that what you're normally used to, so that's really nice, so this gem is actually designed so that when it sees that the asset precompile command runs, it's actually going to insert webpacker compile right afterwards automatically, so the only change on your server is that you're going to need node and yarn installed. You probably already have node intalled, so that you could compile the asset pipeline, and so yarn is the only real dependency that you would need to install this time. So that is really nice, and gives you webpack with very little changes to the way that your normal workflow works, so that is great. You can also link the sprockets assets as well, so if you had any images in the asset pipeline that you want to link to inside of your webpack stuff you can go ahead and use erb is the extention in your JavaScript file inside of the webpack folder and you would just go. So there's the instructions here for react, angular with typescript, and vuejs as well. Feel free to add more as a pull request, this is still in active development, so things are bound to change, but for the most part, the way that you interact with this gem is probably going to stat exactly the same, they're just going to be building out little additional features and customizable things. That is a quick introduction to webpacker, we're going to be using it more in the future. I'm going to follow up this episode with an episode on that JavaScript mix-in for vuejs to make it turbolinks compatible. I'll explain more abou what the real problem with it is, and how we fix it, but for the most part it's a very simple solution, and it works really nicely and we've got a node module that you can use, and we'll show you how to use that in that episode as well. So until then, I will talk to you later. Peace
Transcript written by Miguel
Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.
|
https://gorails.com/episodes/using-webpack-in-rails-with-webpacker-gem?autoplay=1
|
CC-MAIN-2019-47
|
refinedweb
| 3,493
| 57.88
|
Chapter Objective
OOP's overview. Let's now
take a brief look at these concepts..
Simple "Hello World" C# Program
This simple one-class console "Hello world" program demonstrates many
fundamental concepts throughout this article and several future articles. C# code
So SimpleHelloWorld is the name of the class that contains the Main () method.
On line 1 , a using directive indicates to the compiler that this source file
refers to classes and constructs declared within the System namespace. Line 6
with the public keyword indicates the program accessibility scope for other
applications or components.
At line 7 there appears an opening curly brace ("{") which indicates the
beginning of the SimpleHelloWorld class body. Everything belongs to the class,
like fields, properties and methods appear an assembly or a module. If the program
has one class that contains a Main () method then it can be compiled directly
into an assembly. This file has an ".exe" extension. A program with no Main()
method can be compiled into a module as in the following:
csc /target:module "program name"
You can then compile this program by F9 or by simply running the C# command line
compiler (csc.exe) against the source file as the following:
csc oops.cs Classes and Objects
Classes are special kinds of templates from which you can create objects. Each
object contains data and methods to manipulate and access that data. The class
defines the data and the functionality that each object of that class can
contain.
A class declaration consists of a class header and body. The class header
includes attributes, modifiers, and the class keyword. The class body
encapsulates the members of the class, that are the data members and member
functions. The syntax of a class declaration is as follows:
Attributes accessibility modifiers class identifier: baselist { body }
Attributes provide additional context to a class, like adjectives; for example
the Serializable attribute. Accessibility is the visibility of the class. The
default accessibility of a class is internal. Private is the default
accessibility of class members. The following table lists the accessibility
keywords;
Modifiers refine the declaration of a class.
The list of all modifiers defined in the table are as follows;
The baselist is the inherited class. By
default, classes inherit from the System.Object type. A class can inherit and
implement multiple interfaces but doesn't support multiple inheritances. Step-by-step Tutorial for Creating a Class
C# code
Note: the C# console application project must
require a single entry point Main () function that is already generated in the
program class. For example if you add a new customer class and want to define
one or more Main () entry points here then .NET will throw an error of multiple
entry points. So it is advisable to delete or exclude the program.cs file from
the solution.
So here in this example the customer class defines fields such as CustID, Name
and Address to hold information about a particular customer. It might also
define some functionality that acts upon the data stored in these fields. C# code
You can then instantiate an object of this class to represent one specific
customer, set the field value for that instance and use its functionality, as
in: C# code
Here you use the keyword new to declare the customer class instance. This
keyword creates the object and initializes it. When you create an object of the
customer class, the .NET framework IDE provides a special feature called
Intellisense that provides access to all the class member fields and functions
automatically. This feature is invoke when the "." Operator is put right after
the object, as in the following;
Image 1.1 Intellisense feature
Normally, as the program grows in size and the code becomes more complex, the
Intellisense feature increases the convenience for the programmer by showing all
member fields, properties and functions.
Multiple Class Declaration
Sometimes circumstances require multiple classes to be declared in a single
namespace. So in that case it is not mandatory to add a separate class to the
solution, instead you can attach the new class into the existing program.cs or
another one as in the following; C# code
Here in this example, we are creating an extra class "demo" in the program.cs file
at line 12 and finally we are instantiating the demo class with the program
class inside the Main() entry in lines 6 to 11. So it doesn't matter how many
classes we are defining in a single assembly. Partial classes
Typically, a class will reside entirely in a single file. However, in situations
where multiple developers need access to the same class, then having the class
in multiple files can be beneficial. The partial keywords allow a class to span
multiple source files. When compiled, the elements of the partial types are
combined into a single assembly.
There are some rules for defining a partial class as in the following;
A partial type must have the same accessibility.
Each partial type is preceded with the "partial" keyword.
If the partial type is sealed or abstract then the entire class will be sealed and abstract.
In the following example we are adding two files,
partialPart1.cs and partialPart2.cs, and declare a partial class,
partialclassDemo, in both classes.
partialPart1.cs
partialPart2.cs
And finally we are creating an
instance of the partialclassDemo in the program.cs file as the following:
Program.cs
Static classes
A static class is declared using the "static" keyword. If the class is declared
as static then the compiler never creates an instance of the class. All the
member fields, properties and functions must be declared as static and they are
accessed by the class name directly not by a class instance object. C# code
Creating and accessing Class Component Library
.NET provides the capability of creating libraries (components) of a base
application rather than an executable (".exe"). Instead the library project's
final build version will be ".DLL" that can be referenced from other outside
applications to expose its entire functionality.
Step-by-step tutorial
1. First create a class library based application as:
2. Then we are implementing a math class library that is responsible of
calculating square root and the addition of two numbers as:
3. Build this code and you will notice that a DLL
file was created, not an executable, in the root directory of the application
(path = D:\temp\LibraryUtil\LibraryUtil\bin\Debug\ LibraryUtil.dll).
4. Now create another console based application where you utilize all the class
library's functionality.
5. Then you have to add the class library dll file reference to access the
declared class in the library dll. (Right-click on the Reference then "Add
reference" then select the path of the dll file.)
6. When you add the class library reference then you will notice in the Solution
Explorer that a new LibraryUtil is added as in the following;
7. Now add the namespace of the class library file in the console application
and create the instance of the class declared in the library as in the
following;
8. Finally run the application. Constructor and Destructor
A constructor is a specialized function that is used to initialize fields. A
constructor has the same name as the class. Instance constructors are invoked
with the new operator and can't be called in the same manner as other member
functions. There are some important rules pertaining to constructors as in the
following;
Classes with no constructor have an implicit constructor called the default constructor, that is parameterless. The default constructor assigns default values to fields.
A public constructor allows an object to be created in the current assembly or referencing assembly.
Only the extern modifier is permitted on the constructor.
A constructor returns void but does not have an explicitly declared return type.
A constructor can have zero or more parameters.
Classes can have multiple constructors in the form of default, parameter or both.
The following example shows one constructor for a
customer class. C# code
Note: The moment a new statement is executed, the default constructor is
called. Static Constructor
A constructor can be static. You create a static constructor to initialize
static fields. Static constructors are not called explicitly with the new
statement. They are called when the class is first referenced. There are some
limitations of the static constructor as in the following;
Static constructors are parameterless.
Static constructors can't be overloaded.
There is no accessibility specified for Static constructors.
In the following example the customer class has a
static constructor that initializes the static field and this constructor is
called when the class is referenced in the Main () at line 26 as in the
following: C# code
Destructors
The purpose of the destructor method is to remove unused objects and resources.
Destructors are not called directly in the source code but during garbage
collection. Garbage collection is nondeterministic. A destructor is invoked at
an undetermined moment. More precisely a programmer can't control its execution;
rather it is called by the Finalize () method. Like a constructor, the
destructor has the same name as the class except a destructor is prefixed with a
tilde (~). There are some limitations of destructors as in the following;
Destructors are parameterless.
A Destructor can't be overloaded.
Destructors are not inherited.
Destructors can cause performance and efficiency implications.
The following implements a destructor and dispose
method. First of all we are initializing the fields via constructor, doing some
calculations on that data and displaying it to the console. But at line 9 we are
implementing the destructor that is calling a Dispose() method to release all
the resources.
At line 12 when the instance is created, fields are initialized but it is not
necessary that at the same time the destructor is also called. Its calling
is dependent on garbage collection. If you want to see the destructor being
called into action then put a breakpoint (by F9) at line 10 and compile the
application. The CLR indicates its execution at the end of the program by
highlighting line 10 using the yellow color. Function Overloading
Function overloading allows multiple implementations of the same function in a
class. Overloaded methods share the same name but have a unique signature. The
number of parameters, types of parameters or both must be different. A function
can't be overloaded on the basis of a different return type alone.
At lines 3, 4 and 5 we are defining three methods with the same name but with
different parameters. In the Main (), the moment you create an instance of the
class and call the functions setName() via obj at lines 7, 8 and 9 then
intellisense will show three signatures automatically. Encapsulation
Encapsulation is the mechanism that binds together the code and the data it
manipulates, and keeps both safe from outside interference and misuse. In OOP,
code and data may be combined in such a way that a self-contained box is
created. When code and data are linked together in this way, an object is
created and encapsulation exists. portions of
your program may access it even though it is defined within an object. C# code
Inheritance
Inheritance is the process by which one object can acquire the properties of
another object. Inheritance is a "is a kind of" relationship and it supports the
concept of classification in which an object needs only define those qualities
that make it unique within the class. Inheritance involves a base class and a
derived class. The derived class inherits from the base class and also can
override inherited members as well as add new members to extend the base class.
A base type represents the generalization, whereas a derived type represents
a specification of an instance. Such as Employees that can have diverse types,.
The syntax of inheritance is as in the following;
Class derivedClass : baseClass, Iterface1, Interface2 { body }
For example we are defining two classes, Father and Child. You notice at line 7,
we are implementing inheritance by using a colon (:); at this moment all the
properties belonging to the Father Class is accessible to the Child class
automatically. C# code
At line 11 , the Intellisense only shows the Father class functions but at line
15 to 16 the Child class object is able to access both class methods as in the
following.
We can create a class in the VB.Net language or another .NET supported language
and can inherit them in a C# .Net class and vice versa. But a class developed in
C++ or other unmanaged environment can't be inherited in .NET.
Note: Cross-language and multiple inheritance is not supported by .NET. Accessibility
Accessibility sets the visibility of the member to outside assemblies or derived
types. The following table describes member accessibility;
Constructor in Inheritance
Constructors in a base class are not inherited in a derived class. A derived
class has a base portion and derived portion. The base portion initializes the
base portion, and the constructor of the derived class initializes the derived
portion.
The following is the syntax of a constructor in inheritance;
Accessibility modifier classname(parameterlist1) : base(parameterlist2) { body }
So the base keyword refers to the base class constructor, while parameterlist2
determines which overloaded base class constructor is called.
In the following example, the Child class's constructor calls the
single-argument constructor of the base Father class; C# code
At line 4, we are defining a base Father Class constructor and in the derived
class Child, at line 8 we are initializing it explicitly via base keyword. If we
pass any parameter in the base class constructor then we have to provide them in
the base block of the child class constructor. Virtual Methods
By declaring a base class function as virtual, you allow the function to be
overridden in any derived class. The idea behind a virtual function is to
redefine the implementation of the base class method in the derived class as
required. If a method is virtual in the base class then we have to provide the
override keyword in the derived class. Neither member fields nor static
functions can be declared as virtual. C# code
Hiding Methods
If a method with the same signature is declared in both base and derived
classes, but the methods are not declared as virtual and overriden the compiler will
generate a warning. The compiler will assume that you are hiding the base class
method. So to overcome that problem, if you prefix the new keyword in the
derived class method then the compiler will prefer the most derived version
method. You can still access the base class method in the derived class by using
the base keyword. C# code
Abstract Classes
C# allows both classes and functions to be declared abstract using the() that does not have an implementation. Then we are implementing the
displayData() body in the derived class. One point to be noted here is that we
have to prefixe the abstract method with the override keyword in the derived
class. C# code
Sealed Classes
Sealed classes are the reverse of abstract classes. While abstract classes are
inherited and are refined in the derived class, sealed classes cannot be
inherited. You can create an instance of a sealed class. A sealed class is used
to prevent further refinement through inheritance.
Suppose you are a developer of a class library and some of the classes in the
class library are extensible but other classes are not extensible so in that
case those classes are marked as sealed. C# code
Interface
An interface is a set of related functions that must be implemented in a derived
class. Members of an interface are implicitly public and abstract. Interfaces
are similar to abstract classes. First, both types must be inherited; second,
you cannot create an instance of either. Although there are several differences
as in the following;
So the question is, which of these to choose?
Select interfaces because with an interface, the derived type still can inherit
from another type and interfaces are more straightforward than abstract classes. C# code
An interface can be inherited from other
interfaces as in the following: C# code
Polymorphism
Polymorphism is the ability to treat the various objects in the same manner. It
is one of the significant benefits of inheritance. We can decide the correct
call at runtime based on the derived type of the base reference. This is called
late binding.
In the following example, instead of having a separate routine for the hrDepart,
itDepart and financeDepart classes, we can write a generic algorithm that uses
the base type functions. The method LeaderName() declared in the base abstract
class is redefined as per our needs in 2 different classes. C# code
View All
|
http://www.c-sharpcorner.com/UploadFile/84c85b/object-oriented-programming-using-C-Sharp-net/
|
CC-MAIN-2017-39
|
refinedweb
| 2,797
| 55.13
|
#include <CGAL/Kernel_traits.h>
The class
Kernel_traits provides access to the kernel model to which the argument type
T belongs.
(Provided
T belongs to some kernel model.) The default implementation assumes there is a local type
T::R referring to the kernel model of
T. If this type does not exist, a specialization of
Kernel_traits can be used to provide the desired information.
This class is, for example, useful in the following context. Assume you want to write a generic function that accepts two points
p and
q as argument and constructs the line segment between
p and
q. In order to specify the return type of this function, you need to know what is the segment type corresponding to the Point type representing
p and
q. Using
Kernel_traits, this can be done as follows.
|
https://doc.cgal.org/latest/Kernel_23/structCGAL_1_1Kernel__traits.html
|
CC-MAIN-2021-49
|
refinedweb
| 135
| 63.19
|
The Other Kind of Bypass Capacitor
There’s a type of bypass capacitor I’d like to talk about today.
It’s not the usual power supply bypass capacitor, aka decoupling capacitor, which is used to provide local charge storage to an integrated circuit, so that the high-frequency supply currents to the IC can bypass (hence the name) all the series resistance and inductance from the power supply. This reduces the noise on a DC voltage supply. I’ve written about this aspect of H-bridge design before, and Intersil has a good application note on selecting bypass capacitors. When in doubt, use ground and power planes, and some 0.1μF and 0.01μF surface mount capacitors nearby each IC that needs to connect to the planes, with vias between capacitors and the planes located as close as posssible to the capacitor pads; the 0.1μF is a good general value capacitor for charge storage, and the 0.01μF capacitor, in a small package like 0603 or 0402, will have better high-frequency characteristics for those ICs that really need to have a quiet power supply, or which have lots of switching spikes — use them on ADCs and microcontrollers, for example. (If you want more of the gory details, read Clemson University’s articles on EMI design and PCB layout.)
You probably know all that already.
But I’m going to talk about another type of bypass capacitor. Here are three practical examples where it is used:
C1 in a portion of a switching regulator circuit, from ON Semiconductor’s Application Note AND8327/D — authored in part by the eminent Christoph Basso
The 1000pF cap across the LF411 in the “Son of Godzilla Booster” from National Semiconductor’s AN-272, allegedly written by Jim Williams:
The 100pF cap across the LT1190 in a high-power wideband current source, from Linear Technology’s AN47, also by Jim Williams. (In fact there are several other circuits in this appnote that use the same technique.)
These are examples of circuits with feedback bypass capacitors. In all three cases, we have an error amplifier with gain \( K(s) \), feeding an ugly complex system with some input-to-output gain \( U(s) \) (U for “ugly”) through some equivalent resistance \( R \), along with a capacitor \( C_b \) that bypasses the feedback.
In the AND8327 appnote (“Figure 1” including the TL431), this capacitance is C1 (100nF) and the resistance R is the Thévenin equivalent \( R2 || R3 = 5\text{k}\Omega \); the “ugly” system includes the transconductance of the TL431, the current transfer ratio of the optoisolator, the pullup resistor, and the small-signal equivalent of whatever switching power supply stage relates the input FB to the output Vout.
In the Son of Godzilla Booster, the feedback capacitance is the 1000 pF capacitor across the LF411 and the resistance is the 1M capacitor at the top of the circuit (with 300pF parallel capacitance to provide some high-frequency feedback); the “ugly” system is the LM3524 switching converter, transformer, and rectifier.
In the wideband current source, the feedback capacitance is the 100 pF capacitor across the LT1190, and the resistance is the 2K resistor from the LT1194, which serves to correct any nonlinearities or offsets of the LT1190; the “ugly” system is the LT1194 and the transistor current mirror circuit.
The idea is that \( U(s) \) includes DC and low-frequency feedback that we care about, but for various reasons its high-frequency characteristics can’t be trusted. The capacitor gives us unity-gain feedback at high-frequencies, where feedback from the ugly complex system is attenuated.
Our overall loop gain is \( K(s)F(s) \) where $$F(s) = \dfrac{\frac{U(s)}{R} + C_bs}{\frac{1}{R} + C_bs} = \dfrac{U(s) + RC_bs}{1 + RC_bs}$$ is the net feedback transfer function, derived via Millman’s Theorem. At low frequencies (\( \omega \ll 1/RC_b \)), \( F(s) \approx U(s) \), and at high frequencies \( F(s) \approx 1 + \dfrac{U(s)}{RC_bs} \approx 1. \)
An example
Let’s look at a particular example in more detail. Here let’s say that \( U(s) \) is a unity-gain power amplifier (with some characteristic time constant \( \tau \)) followed by an LC circuit with some parasitic series resistance \( R_s \) in the inductance.
So we can model \( U(s) = \dfrac{1}{\tau s + 1}\cdot\dfrac{1/Cs}{Ls + R_s + 1/Cs} = \dfrac{1}{\tau s + 1}\cdot\dfrac{1}{LCs^2 + R_sCs + 1} \). The LC circuit we can treat as a 2nd-order system, so \( U(s) = \dfrac{1}{\tau s + 1}\cdot\dfrac{1}{s^2/\omega_n{}^2 + 2\zeta s/\omega_n + 1} \) where \( \omega_n = 1/\sqrt{LC} \) and \( \zeta = \frac{R_s}{2}\sqrt{\frac{C}{L}} \). For well-constructed inductors \( \zeta \) will be small: take for example \( L = 100\mu \text{H} \), \( R_s = 0.2 \Omega \), and \( C = 47\mu \text{F} \); this gives us \( \omega \approx 14587 \) rad/s and \( \zeta \approx 0.145 \).
What about the op-amp’s \( K(s) \)? Well, we can approximate \( K(s) = \dfrac{B}{s + B/K_{DC}} \) where \( B \) is the gain-bandwidth product in rad/s, and \( K_{DC} \) is the DC gain. Let’s assume we have a 1MHz GBW opamp with a DC gain of 200,000.
If we choose \( R = 100K\Omega \) and \( C_b = 1\mu F \), we can draw Bode plots of the overall loop gains \( KF \) (with the capacitor \( C_b \)) and \( KU \) (without). Jump past the Python code unless you’re really interested; it’s just there to draw pictures.
import numpy as np import matplotlib.pyplot as plt def opamp_tf(B, Kdc): def K(s): return B/(s+B/Kdc) return K def ugly_tf(L,C,Rs,tau): def U(s): return 1/(tau*s + 1)/(L*C*s*s + Rs*C*s + 1) return U class LimitFinder(): def __init__(self): self._min = None self._max = None def __iadd__(self, data): newmin = np.min(data) newmax = np.max(data) if self._min is None: self._min = newmin self._max = newmax else: self._min = min(newmin, self._min) self._max = max(newmin, self._max) return self @property def min(self): return self._min @property def max(self): return self._max def ticks(self, delta, clipmin=None, clipmax=None): tmin = self.min if clipmin is None else max(clipmin,self.min) tmax = self.max if clipmax is None else min(clipmax,self.max) return np.arange(tmin//delta*delta,tmax+delta,delta) def __repr__(self): return "[%s,%s]" % (self.min, self.max) def interpolate_steep(x, ylist, max_interp=100): n = len(x) ninterp = [] for y in ylist: ymin = np.min(y) ymax = np.max(y) dyref = np.abs(ymax-ymin)/n if dyref < 1e-10: alpha = x*0 else: alpha = np.abs(np.diff(y))/dyref ninterp.append(alpha) ninterp = np.floor(np.max(np.array(ninterp),0)) ninterp = np.minimum(max_interp, ninterp) xinterp = [] for k in np.argwhere(ninterp > 1): x1 = x[k] x2 = x[k+1] dx = (x2-x1)/ninterp[k] xinterp.append(x1+np.arange(1,ninterp[k])*dx) return np.hstack(xinterp) def bodeplot(Hfunclist, fig=None, npoints=100, maglimits=None, xlim=None): if xlim is None: xlim = [-2,6] else: xlim = np.log10(xlim) omega1 = np.logspace(xlim[0],xlim[1],npoints) lxlim = [omega1[0],omega1[-1]] db = lambda x: 20*np.log10(np.abs(x)) ang = lambda x: np.angle(x,deg=True) ticks = lambda xmin,xmax,delta: np.arange(xmin//delta*delta,xmax+delta,delta) if fig is None: fig = plt.figure(figsize=(8,6)) ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) omega_additional = interpolate_steep(omega1, [f(Hfunc(1j*omega1)) for f in [db, ang] for Hfunc in Hfunclist], max_interp=200) omega = np.union1d(omega1,omega_additional) maglim = LimitFinder() phaselim = LimitFinder() for Hfunc in Hfunclist: H = Hfunc(1j*omega) ax1.semilogx(omega,db(H)) maglim += db(H) ax2.semilogx(omega,ang(H)) phaselim += ang(H) ax1.set_ylabel(r'$20\, \log_{10} |H(\omega)|$', fontsize=16) ylim = [maglim.min, maglim.max] if maglimits is None: maglimits = (None, None) if maglimits[0] is not None: ylim[0] = max(maglimits[0], ylim[0]) if maglimits[1] is not None: ylim[1] = min(maglimits[1], ylim[1]) ax1.set_yticks(maglim.ticks(10, clipmin=maglimits[0], clipmax=maglimits[1])) ax1.set_ylim(1.05*ylim[0]-0.05*ylim[1],1.05*ylim[1]-0.05*ylim[0]) ax1.grid('on') ax2.set_yticks(phaselim.ticks(15)) if phaselim.min < -175 and phaselim.max > 175: ax2.set_ylim(-180,180) ax2.set_ylabel(r'$\measuredangle H(\omega)$',fontsize=16) ax2.set_xlabel(r'$\omega$ (rad/s)',fontsize=16) ax2.grid('on') return (fig,ax1,ax2) Kdc = 2e5 B = 2*np.pi*1e6 tau_opamp = Kdc/B K = opamp_tf(B=B, Kdc=Kdc) Utau = 500e-6 L = 100e-6 Rs = 0.2 C = 47e-6 U = ugly_tf(L=L, Rs=Rs, C=C, tau=Utau) R = 100e3 Cb = 1e-6 tau_fb = R*Cb F = lambda s: (U(s)+R*Cb*s)/(1+R*Cb*s) loop1 = lambda s: K(s)*U(s) loop2 = lambda s: K(s)*F(s) fig = plt.figure(figsize=(10,10)) _, ax1, ax2 = bodeplot([loop1, loop2], fig=fig, maglimits=[0,None]) for ax in [ax1,ax2]: ax.legend(['K*U','K*F'])
There’s a big difference between the loop gain with the feedback bypass capacitor (KF) and the loop gain without it (KU). Without the feedback bypass capacitor, we have a really ugly transfer function with more than 180 degree phase lag long before it gets to unity gain (and nearly 360 degree phase lag at unity gain). With the feedback bypass capacitor, we can achieve essentially a first-order transfer function for open-loop gain.
Just because the open-loop gain is well behaved, it doesn’t mean the closed-loop transfer function is very smooth, but it does ensure stability. Let’s draw a Bode plot of the closed-loop transfer function. We’ll also use the
scipy.signal.lti objects to show step responses (although there’s some algebra to get this).
# closed-loop transfer functions cloop1 = lambda s: K(s)*U(s)/(1+K(s)*F(s)) Uden = lambda s: 1/U(s) cloop2 = lambda s: Kdc*(1+tau_fb*s)/(Uden(s)*(tau_opamp*s+1)*(tau_fb*s+1) + Kdc*(1 + tau_fb*s*Uden(s))) cloopdiff = lambda s: cloop1(s)-cloop2(s) def maxdiff(f1,f2,x): return np.max(np.abs(f1(x) - f2(x))) # are these the same transfer function? (check my algebra) stest = 1j*np.logspace(-6,6,1000) print "cloop1-cloop2:", maxdiff(cloop1, cloop2, stest) import scipy.signal from numpy.polynomial.polynomial import Polynomial P1 = Polynomial(1) # 1/(tau*s + 1)/(L*C*s*s + Rs*C*s + 1) pUden = P1 * [1,Utau] * [1,Rs*C,L*C] # scipy.signal.lti expects *descending* order def make_closedTF(tau): tau_s = 0 if tau is None else Polynomial([0,tau]) return scipy.signal.lti(# Numerator (P1 * Kdc * (tau_s + 1)).coef[::-1], # Denominator ( (pUden * [1,tau_opamp] * (tau_s + 1)) + Kdc * (1 + pUden*tau_s) ).coef[::-1] ) closedTF = make_closedTF(tau_fb) closedTF_H = lambda s: closedTF.freqresp(s/1j)[1] print "cloop1-LTI", maxdiff(cloop1, closedTF_H, stest)
cloop1-cloop2: 6.66200242854e-16 cloop1-LTI 1.26858466865e-15
fig = plt.figure(figsize=(10,10)) bodeplot([cloop1, cloop2, closedTF_H], fig=fig, maglimits=[-60,None])
(<matplotlib.figure.Figure at 0x14f1d7050>, <matplotlib.axes._subplots.AxesSubplot at 0x14f1d7910>, <matplotlib.axes._subplots.AxesSubplot at 0x140dc0c50>)
This closed-loop transfer function is mostly well-behaved, although it does have a resonance due to the LC circuit. Here are step responses for various values of \( \tau = RC_b \):
fig=plt.figure(figsize=(10,8)) ax=fig.add_subplot(1,1,1) taulist = tau_fb * np.array([0.0005, 0.001, 0.01, 0.1, 1.0]) colors = 'gykbr' for k,tauval in enumerate(taulist): closedTF = make_closedTF(tauval) t,x=closedTF.step(T=np.arange(0,0.01,0.00001)) ax.plot(t,x, color=colors[k]) ax.legend(['%g us' % (tau*1e6) for tau in taulist]) ax.grid('on') ax.set_xlabel('t') ax.set_ylabel('y')
<matplotlib.text.Text at 0x146b3d6d0>
Essentially we have a tradeoff; by increasing the time constant (larger feedback bypass capacitance) we get slower response, but more stable. The circuit exhibits a step response with ringing with small feedback capacitance, and is unstable with no feedback capacitance.
Other examples
This technique is very powerful; I’ve used it several times in my career. One memorable occasion was a battery charger using a 95V Vicor FlatPAC switching power converter. (Designs I created using the Vicor converters both predated and followed the notorious William Tango Foxtrot design I wrote about a couple of years ago.) The FlatPAC converters have a trim circuit that allows trimming between 50% and 110% of nominal output voltage:
Unfortunately the trim circuit was originally intended to be a manual, potentiometer-based voltage adjustment. Vicor now has an application note on using it as a constant-current battery charger; at the time I created my design, they had some appnote about constant-current use, but I don’t think it went into as much detail, and I had to figure out the hard way that the trim pin had a nonlinear, bandwidth-limited response that was not well-documented, so I used an op-amp to control the trim pin, and in went the feedback bypass capacitor to save the day.
Op-amps have these feedback capacitors, too!
You won’t just find this used in application circuits. In fact, almost all op-amps have an internal feedback bypass capacitor for frequency compensation; here’s the design of the ubiquitous (and awful! please use a better one!) 741 op-amp:
The 30pF capacitor is an internal feedback capacitor that reduces the high-frequency gain of the op-amp, in order to allow the amplifier to have a predictable transfer function that is stable at unity-gain.
Isn’t it just an integrator?
Another way of thinking about the RC stabilizing technique is that it forms an integrator:
If you go through the circuit analysis, you can derive that the gain from \( V_{out} \) to the output of the op-amp is $$G(s) = \frac{-K}{1 + (1+K)RC_b s}$$
If the op-amp gain K is large, then \( G(s) \approx -1/RC_b s \) and we have an ideal integrator… but the op-amp’s low-frequency gain isn’t infinite. A Bode plot of the integrator’s transfer function (with the sign reversed) versus the op-amp’s open-loop gain shows that we’re basically just creating a “virtual” op-amp with much lower gain-bandwidth product:
fig = plt.figure(figsize=(10,10)) K = opamp_tf(B=B, Kdc=Kdc) integ = lambda s: K(s)/(1 + R*Cb*s + K(s)*R*Cb*s) _, ax1, ax2 = bodeplot([H1, integ], fig=fig, maglimits=[-60,None], xlim=[1e-6,1e6]) for ax in [ax1,ax2]: ax.legend(['K (opamp)','RC integrator'])
The analysis above isn’t completely correct, however; it shows the feedback loop transfer function, but neglects the transfer function from the \( + \) terminal of the op-amp to its output, which we can add:
$$ V_{opamp,out} = \frac{-KV_{out} + K(1 + RC_b s)V_{in}}{1 + (1+K)RC_b s} $$
This has an additional zero for the transfer function from \( V_{in} \) to op-amp output, which essentially creates a gain of 1 between the cutoff frequency \( \omega_c = 1/RC_b \) and the op-amp’s gain-bandwidth.
Wrap-up
Feedback bypass capacitors are really useful! They let you use an op-amp to take low-frequency feedback from some ugly, nonlinear, slow system, but stabilize the control loop by taking high-frequency feedback from the op-amp output itself, forming a unity gain at high frequencies. I recommend putting this in your bag of circuit-design tricks.
On a related subject: Jim Williams has a nice writeup called “The Oscillation Problem (Frequency Compensation without Tears)” in Linear Technology’s AN18 that gives some good practical advice without getting into any control theory.)
Happy New Year!
P.S. I need to point out another entry to the Hall of Shame. While doing some additional research for this article, I looked up National Semiconductor’s Application Note 4: Monolithic Op Amp — The Universal Linear Component, written by legendary chip designer Bob Widlar and published in April 1968. National was acquired by Texas Instruments in 2011, and you can still find AN4, but it’s been “revised” as TI’s SNOA650B. (I managed to find an earlier version of the National PDF on a webpage at Colorado State University.) The “revised” version omits any mention of Widlar as author of the appnote, and the documentation dwarves at TI have assiduously replaced “National Semiconductor” with “Texas Instruments”… but haven’t bothered to “revise” any other aspects of the appnote, including the fact that the abstract says
The cost of monolithic amplifiers is now less than \$2.00, in large quantities, which makes it attractive to design them into circuits where they would not otherwise be considered.
and later on
Although the designs presented use the LM101 operational amplifier and the LM102 voltage follower produced by Texas Instruments
Hello… it’s 2017, not 1968; I can buy an LM358 op-amp for less than 10 cents in 1K quantities, and there are no more LM102 voltage followers; they were long gone before TI ever got their hands on National. Someone bothered to change that sentence to say “Texas Instruments” rather than “National Semiconductor” but didn’t bother to check it for factual correctness.
I like many of TI’s chips, and am amazed at what kind of clever products come out of their factory, but I really wish they would have just published the old National appnotes in their original form, as historical — but still invaluable — documents. The
national.com website is gone, and sorely missed. It makes me wish I had kept some of those databooks-on-CD-ROM that the semiconductor manufacturers put out in the late 1990’s, in those few years between the era of paperweight databooks and the era of ephemeral publications on the Internet.
I hope TI will correct this injustice.
Previous post by Jason Sachs:
How to Read a Power MOSFET Datasheet
Next post by Jason Sachs:
Linear Feedback Shift Registers for the Uninitiated, Part I: Ex-Pralite Monks and Finite Fields
- Write a CommentSelect to add a comment
I've tried to download as many databooks as I can find in PDF format. I keep them on a micro-SD card that I can use in my tablet. I have found many at:
Jason
"It makes me wish I had kept some of those databooks..."
For what it's worth I preserved all my old data by scanning the data books. I am happy to send the archive to anyone. You can read about it in my blog "Preserving Data Books From Yesteryear". Incidentally although it's not clear in the blog, if you click on the National data book image, it will take you to a sequence of my impression of art on different data book covers.
I always called that process compensation, not bypass..
|
https://www.electronics-related.com/showarticle/1021/the-other-kind-of-bypass-capacitor
|
CC-MAIN-2019-51
|
refinedweb
| 3,188
| 55.34
|
Manpage of WCSNLEN
WCSNLENSection: Linux Programmer's Manual (3)
Updated: 2016-03-15
Index
NAMEwcsnlen - determine the length of a fixed-size wide-character string
SYNOPSIS
#include <wchar.h>size_t wcsnlen(const wchar_t *s, size_t maxlen);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
wcsnlen():
- Since glibc 2.10:
- _POSIX_C_SOURCE >= 200809L
- Before glibc 2.10:
- _GNU_SOURCE
DESCRIPTIONThe wcsnlen() function is the wide-character equivalent of the strnlen(3) function. It returns the number of wide-characters in the string pointed to by s, not including the terminating null wide character (Laq\0aq), but at most maxlenwide characters (note: this parameter is not a byte count). In doing this, wcsnlen() looks at only the first maxlenwide characters at sand never beyond s+maxlen.
RETURN VALUEThe wcsnlen() function returns wcslen(s), if that is less than maxlen, or maxlenif there is no null wide character among the first maxlenwide characters pointed to by s.
VERSIONSThe wcsnlen() function is provided in glibc since version 2.1.
ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7).
CONFORMING TOPOSIX.1-2008.
SEE ALSOstrnlen(3), wcslen(3)
Index
This document was created by man2html, using the manual pages.
Time: 19:53:54 GMT, October 26, 2017 Click Here!
|
https://www.linux.com/manpage/man3/wcsnlen.3.html
|
CC-MAIN-2018-22
|
refinedweb
| 207
| 54.73
|
18650 rechargeable 36v 48v 4.4ah 10s2p 158.4wh li-ion battery pack for 2 wheel smart hoverbaord self balance electric scooter
US $150-156 / Piece
1 Piece (Min. Order)
ISO9001 factory customized li-ion battery pack 36v 8ah with BMS and charger
US $75-95 / Piece
10 Pieces (Min. Order)
36V 10Ah 20Ah Scooter Li Ion Lipo Rechargeable Electric E Bike Li-Ion Lithium Battery Pack
US $100-200 / Pack
100 Packs (Min. Order)
Custom 18650 Li-Ion Ebike 36V 15Ah Electric Bicycle Lithium Ion Battery Pack
US $110-150 / Piece
1 Piece (Min. Order)
customized high quality lithium ion battery 12v 24v 36v 48v 10Ah 20ah 30ah li-ion ebike battery pack
US $65-495 / Piece
10 Pieces )
36V 20Ah Ebike Li-ion 36 Volt Deep Cycle Lithium Ion Battery Pack For Electric Bike with Charger
US $120-160 /)
36v electric scooter battery 36v 16ah 10s5p li-ion ebike battery pack with XT60 plug
US $100-200 / Unit
1 Unit (Min. Order)
high discharge rate 18650 li-ion battery pack 36v 5ah 6ah 7ah 8ah 9ah 12ah electric skateboard lithium battery
US $40-120 / Pack
1 Pack (Min. Order)
New!!36v 14Ah li-ion battery pack,cycle life 1000 times.
US $50-400 / Piece
1 Piece (Min. Order)
high rate 5C 36v 10Ah lithium li-ion battery pack for electric skateboard
US $130-150 / Piece
1 Piece (Min. Order)
High power rechargeable lithium ion battery pack 36v 12ah 20ah 30ah 50ah li-ion electric bike/scooter battery
US $100.0-130.0 / Pieces
10 Pieces (Min. Order)
Rechargeable 36v lithium li-ion battery pack electric bike battery for ebike Bicycle
US $86-255 / Piece
1 Piece (Min. Order)
36 Volt Lipo Ebike Li-Ion 36V 10000Mah 10Ah E-Bike Lithium Ion Polymer Battery Pack
US $80-100 / Piece
1 Piece (Min. Order)
li-ion battery pack 48v 100ah 36v 20ah lithium ion battery pack for ebike
US $30-168 / Pack
1 Pack (Min. Order)
Lithium 18650 Rechargeable 10S4P 8.8Ah 36V Li-ion Electric Skateboard Battery Pack
US $55-80 / Pack
100 Packs (Min. Order)
Low Factory Price Waterproof Golf Trolley Portable Battery Pack 36V 40ah Li-ion Battery for Storage Energy Battery
US $67.0-70.0 / Pieces
10 Pieces (Min. Order)
China Supplier e-bike battery li-ion 36v 9000mah 10S4P battery pack
US $93.0-98.0 / Pieces
5 Pieces (Min. Order)
36V 10Ah lithium li-ion battery pack for dual motor 1000W Electric skateboard with Charger
US $30.99-60.99 / Sets
100 Sets (Min. Order)
OEM li-ion li ion lithium Battery Pack 11.1V 18.5v 12V 24V 25.9V 36V 48V 60V 72V 10ah 17ah 20ah 30ah 40ah 50ah 60Ah 80ah
US $20-200 / Piece
1 Piece (Min. Order)
36v 40ah li-ion battery pack, lawn mower battery pack
US $400-450 / Piece
1 Piece (Min. Order)
36v 20ah li-ion lithium eclctric bike battery packs
US $50.0-50.0 / Pieces
1000 Pieces (Min. Order)
High performance customized li-ion accu 12v 24v 36v 48v 20ah lifepo4 battery pack
US $72.5-97.5 / Pack
10 Packs (Min. Order))
48V 20Ah li-ion battery pack 36V 48V 72V 30Ah electric bike battery 18650 lithium battery
US $0.56-2.7 / Piece
500 Pieces (Min. Order)
Lithium 18650 Rechargeable 10S4P 8.8Ah 36V Li-ion Electric Skateboard Battery Pack
US $50.0-90.0 / Pack
1 Pack (Min. Order)
Long cycle life 18650 li-ion battery pack ebike battery 36V 10Ah
US $50-110 / Piece
10 Pieces (Min. Order)
import cells 36v 13ah Ebike li-ion battery pack for 250W electric bike
US $155.0-159.0 / Piece
1 Piece (Min. Order)
36V 9Ah Frog Type Li-ion Battery Pack for Electric Scooter
US $120.0-125.0 / Pack
1 Pack (Min. Order)
UPP brand Silver fish e-bike battery pack 36v 10ah 18650 battery pack 36V li-ion battery with free charger
US $135.0-140.0 / Piece
1 Piece (Min. Order)
Custom 18650 E-Bike Li Ion 10S5P 36V 10Ah Li-Ion Electric Bike Lithium Battery Pack
US $75.5-95.5 / Set
10 Sets (Min. Order)
Electric bike battery rechargeable li-ion battery pack LiFePO4 36v 15ah / 36v 20ah
US $60-85 / Piece
1 Piece (Min. Order)
High capacity Customized 36V 18Ah Li-Ion battery pack for e-bike
US $1-2 / Pack
50 Packs (Min. Order)
Welcome to customized ! 10S2P 36V 7000mAh li-ion battery pack 36V ebike battery
US $102-110 / Piece
1 Piece (Min. Order)
Li-ion battery pack 12V 24V 36V 20Ah 48Ah for UAV
US $3.5-4 / Piece
100 Pieces (Min. Order)
- About product and suppliers:
Alibaba.com offers 22,423 li-ion battery pack 36v products. About 55% of these are rechargeable batteries, 25% are battery packs, and 2% are storage batteries. A wide variety of li-ion battery pack 36v options are available to you, such as li-ion, li-polymer. You can also choose from 1.2v, 12v, and 1.5v. As well as from aa, prismatic, and d. And whether li-ion battery pack 36v is paid samples, or free samples. There are 22,432 li-ion battery pack 36v suppliers, mainly located in Asia. The top supplying countries are China (Mainland), Hong Kong, and India, which supply 99%, 1%, and 1% of li-ion battery pack 36v respectively. Li-ion battery pack 36v products are most popular in North America, Western Europe, and Domestic Market. You can ensure product safety by selecting from certified suppliers, including 7,171 with ISO9001, 3,680 with Other, and 1,676 with ISO14001 certification.
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show li-ion battery pack 36v or other products of your own company? Display your Products FREE now!
|
http://www.alibaba.com/showroom/li--ion-battery-pack-36v.html
|
CC-MAIN-2018-30
|
refinedweb
| 974
| 75.71
|
Authentication Using Google in ASP.NET Core 2.0
Authentication Using Google in ASP.NET Core 2.0
We will learn how to successfully create and configured Google+ app and used it to authenticate our ASP.NET Core application.
Join the DZone community and get the full member experience.Join For Free
Sometimes, we want users to log in to our application using their existing credentials from third-party applications, such as Facebook, Twitter, Google, etc. In this article, we are going to look into the authentication of ASP.NET Core app using a Google account.
- GoogleAuth and press OK. Refer to this image.
After clicking OK, a new window, and a "Change Authentication" dialog box will open. Select "Individual User Account" and click OK. Now, click OK again to create will see a homepage, as shown below.
Note the URL from the browser address bar. In this case, the URL is. We need this URL to configure our Google app, which we will tackle in our next section.
Create a the API Manager Library page, similar to the one shown below.
Click on the Create button to move to the "New Project" page where you need to create a new project. The "Project name" field will be populated automatically with a default name provided by Google. If you want, you can then override that with your own custom name. For this tutorial, we will be using the default name. Accept the terms of service and then click on the Create button.
Your project will be created successfully and you will be redirected to the API Library page, similar to one shown below.
Search for the Google+ API in the search bar and select the the API home page. Click on the Create credentials button on the right side of the page to configure the secrets for your API.
You will see an "Add credentials to your project " form.
This form has three sections.
Fill in the details of the sections as described below.
Section 1 - Find out what kind of credentials you need
- Which API are you using? - Google+ API
- Where will you be calling the API from? - Web server (e.g. Node.js, Tomcat)
- What data will you be accessing? - User data
And click on.
After this, click on the Create client ID button. You will be redirected to section 3.
Section 3 - Set up the OAuth 2.0 Consent Screen
- Email address - Select your email address from the drop-down..
Your credentials have been created successfully. Click Download to download a JSON file to your local machine with all your application secrets, and then click Done to complete the process.
Open the just downloaded client_id.json file and make a note of the ClientId and ClientSecret field. We will need these values to configure Google authentication in our web app.
Configure Web App to Use Google Authentication
We need to store ClientId and ClientSecret field values in our application. We will use the Secret Manager tool for this purpose. The Secret Manager tool is a project tool that can be used to store secrets such as passwords, API Keys,:
A secrets.json file will open. Put the following code in it:
{ GoogleAuth.Data; using GoogleAuth.Models; using GoogleAuth.Services; namespace GoogleAuth {Authentication().AddGoogle(googleOptions => { googleOptions.ClientId = Configuration["Authentication:Google:ClientId"]; googleOptions.ClientSecret = Configuration["Authentication:Google:Client at the top right corner of the home page:
You will be redirected to page, where you can see the option to login using Google on the right side of the page.
Clicking on log in will already be populated in the Email id field. If you want to use another mail id you can change it here.
Click register, you will be redirected to the home page again but this time you can also see your registered email is at the top right corner.
See Also
Conclusion
We have successfully created and configured Google+ app and used it to authenticate our ASP.NET Core application.
You can get the source code from GitHub.
Please note that secrets.json file contains dummy values. Hence replace the values with the keys of your Google app before executing it.
You can check my other articles on ASP .NET Core here.
Published at DZone with permission of Ankit Sharma , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/authentication-using-google-in-aspnet-core-20?fromrel=true
|
CC-MAIN-2019-47
|
refinedweb
| 742
| 69.38
|
Jul 27, 2017 04:38 PM|Vivekisse|LINK
We have a url like :
We need the url to be in like : removing ‘Bank’ from the url.
How we can achieve this using asp.net mvc
Kindly help
Jul 28, 2017 03:14 AM|Velen|LINK
Hi Vivekisse,
VivekisseWe need the url to be in like : removing ‘Bank’ from the url.
Could you tell me that is “Bank” a controller’s name in your MVC application? If it is, I suggest you could hide the controller name along with the an action name using RouteConfig in ASP.NET MVC as following:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "NewRoute", url: "{Param}", //like "Home" defaults: new { controller = "Bank", action = "Sales", Param = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{Param}", defaults: new { controller = "Bank", action = "Sales", Param = UrlParameter.Optional } ); } }
So your url would be like:, as Bank and Sales are both set to default. If you just hide the controller, it may cause ambiguity when you access other controllers in your web application. Because ASP.NET Route Mapping could not distinguish the “AnotherController” is a controller name or the action in your Bank controller for a url like:. So that’s why I suggest you could hide your controller name along with an action name which you want to set default.
If you have any other questions, please feel free to contact me any time.
Best Regards
Velen
Jul 28, 2017 06:34 AM|Vivekisse|LINK
Actually we have two application as local and bank
the first application which has a controller and when we redirect from local application of '' from homecontroller to bank application.
the bank application which has Area 'sales' with 'Home' controller and the url changes from '' to '' we need to remove the 'Bank' from the url.
kindly help
Jul 28, 2017 10:11 AM|Velen|LINK
Hi Vivekisse,
If you remove the Area name from the Url with SalesAreaRegistration.cs file, ASP.NET MVC Routing will unable to distinguish whether you want to access the Sales controller or the root controller. So on my opinion, your current Url is OK.
Best Regards
Velen
Jul 28, 2017 10:57 AM|Vivekisse|LINK
We have two MVC Projects application as Application1 and Application2.
From Application1 we are redirecting to Application2 of Area ‘Sales’.
The Url becomes '' from this we need to remove the ‘Application1’ from the url.
Jul 28, 2017 11:28 AM|PatriceSc|LINK
And so you have to really keep Application1? Maybe with but I would try this really as a last resort
Contributor
2729 Points
Jul 28, 2017 11:36 AM|navneetmitawa|LINK
Vivekisse
We have a url like :
We need the url to be in like : removing ‘Bank’ from the url.
Do this:
[RouteArea("AreaName", AreaUrl = "")]
By default, areas are prefixed with the area name. The AreaUrl property lets you override that. I'll update the wiki here:
Or just remove your area name in your BankAreaRegistration.cs
Like i have are Test1 and my area registration is mentioned below
public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Test1_default", "Test1/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); }
I have just remove area name from " Test1/{controller}/{action}/{id}" to "" {controller}/{action}/{id}"" , now i can able to access all page without area.
so my updated area registration is
public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Test1_default", "{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); }
8 replies
Last post Jul 28, 2017 11:36 AM by navneetmitawa
|
https://forums.asp.net/t/2125959.aspx?Asp+Net+Mvc+hiding+some+part+for+Url
|
CC-MAIN-2017-43
|
refinedweb
| 595
| 63.49
|
This page describes how to schedule recurring queries in BigQuery.
Overview
You can schedule queries to run on a recurring basis. Scheduled queries must be written in standard SQL, which can include Data Definition Language (DDL) and Data Manipulation Language (DML) statements. The query string and destination table can be parameterized, allowing you to organize query results by date and time.
Before you begin
Before you create a scheduled query:
Scheduled queries use features of the BigQuery Data Transfer Service. Verify that you have completed all actions required in Enabling the BigQuery Data Transfer Service.
If you are creating the scheduled query by using the classic BigQuery web UI, allow pop-ups in your browser from
bigquery.cloud.google.com, so that you can view the permissions window. You must allow the BigQuery Data Transfer Service permission to manage your scheduled query.
Required permissions
Before scheduling a query:, see Predefined roles and permissions.
Configuration options
Query string
The query string must be valid and written in standard SQL. Each run of a scheduled query can receive the following query parameters.
To manually test a query string with
@run_time and
@run_date parameters
before scheduling a query, use the command line interface.
Available parameters
Example
The
@run_time parameter is part of the query string in this example, which
queries a public dataset named
hacker_news.stories.
SELECT @run_time AS time, title, author, text FROM `bigquery-public-data.hacker_news.stories` LIMIT 1000
Destination table
When you set up the scheduled query, if the destination table for your results doesn't exist, BigQuery attempts to create the table for you.
If you are using a DDL or DML query:
- In the GCP Console, choose the Processing location or region. Processing location is required for DDL or DML queries that create the destination table.
- In the classic BigQuery web UI, leave Destination table blank.
If the target table does exist, the destination table's
schema might be updated
based on the query results, if you add columns to the schema
(
ALLOW_FIELD_ADDITION) or relax a column's mode from
REQUIRED to
NULLABLE
(
ALLOW_FIELD_RELAXATION). In all other cases, table schema changes between
runs cause the scheduled query to fail.
Queries can reference tables from different projects and different datasets. When configuring your scheduled query, you don't need to include the destination dataset in the table name. You specify the destination dataset separately.
Write preference
The write preference you select determines how your query results are written to an existing destination table.
WRITE_TRUNCATE: If the table exists, BigQuery overwrites the table data.
WRITE_APPEND: If the table exists, BigQuery appends the data to the table.
If you are using a DDL or DML query:
- In the GCP Console, the write preference option will not appear.
- In the classic BigQuery web UI, leave the Write preference blank.
Creating, truncating, or appending a destination table only happens if BigQuery is able to successfully complete the query. Creation, truncation, or append actions occur as one atomic update upon job completion.
Clustering
Scheduled queries can create clustering on new tables only, when the table is
made with a DDL
CREATE TABLE AS SELECT statement. See
Creating a clustered table from a query result
on the Using Data Definition Language statements
page.
Partitioning options
Scheduled queries can create partitioned or non-partitioned destination tables. Partitioning is not available in the GCP Console, but is available in the classic BigQuery web UI, CLI and API setup methods. If you are using a DDL or DML query with partitioning, leave the Partitioning field blank.
There are two types of table partitioning in BigQuery:
- Tables partitioned by ingestion time: Tables partitioned based on the scheduled query's run time.
- Tables partitioned on a column: Tables that are partitioned based on a
TIMESTAMPor
DATEcolumn.
For tables partitioned on a column:
- In the classic BigQuery web UI, if the destination table will be partitioned on a column, you'll specify the column name in the Partitioning field when Setting up a scheduled query. For ingestion-time partitioned tables and non-partitioned tables, leave the Partitioning field blank.
For ingestion-time partitioned tables:
- Indicate the date partitioning in the destination table's name. See the table name templating syntax, explained below.
Partitioning examples
- Table with no partitioning
- Destination table -
mytable
- Partitioning field - leave blank
- Ingestion-time partitioned table
- Destination table -
mytable$YYYYMMDD
- Partitioning field - leave blank
- Column-partitioned table
- Destination table -
mytable
- Partitioning field - name of the
TIMESTAMPor
DATEcolumn used to partition the table
Available parameters
When setting up the scheduled query, you can specify how you want to partition the destination table with runtime parameters.
Templating system
Scheduled queries support runtime parameters in the destination table name with.
Setting up a scheduled query
Console
Open the BigQuery web UI in the GCP Console.
Run the query that you're interested in. When you are satisfied with your results, click Schedule query and Create new scheduled query.
The scheduled query options open in the New scheduled query pane.
On the New scheduled query pane:
- For Name for the scheduled query, enter a name such as
My scheduled query. The scheduled query name can be any value that allows you to easily identify the scheduled query if you need to modify it later.
(Optional) For Schedule options, you can leave the default value of Daily (every 24 hours, based on creation time), or click Schedule start time to change the time. You can also change the interval to Weekly, Monthly, or Custom. When selecting Custom, a Cron-like time specification is expected, for example
every 3 hours. The shortest allowed period is 15 minutes. See the
schedulefield under
TransferConfigfor more valid API values.
For DDL/DML queries, you'll choose the Processing location or region.
For a standard SQL
SELECTquery, provide information about the destination dataset.
- For Dataset name, choose the appropriate destination dataset.
- For Table name, enter the name of your destination table.
- For a DDL or DML query, this option is not shown.
- For Destination table write preference, choose either
WRITE_TRUNCATEto overwrite the destination table or
WRITE_APPENDto append data to the table.
- For a DDL or DML query, this option is not shown.
(Optional) For Advanced options, if you use customer-managed encryption keys, you can select Customer-managed key here. A list of your available CMEKs will appear for you to choose from.
For all queries:
- (Optional) Check Send email notifications to allow email notifications of transfer run failures.
Click Schedule.
To view the status of your scheduled queries, click Scheduled queries in the navigation pane. Refresh the page to see the updated status of your scheduled queries. Click one to get more details about that scheduled query.
Classic UI
Go to the classic BigQuery web UI.
Go to the classic BigQuery web UI
Run the query that you're interested in.
When you are satisfied with your results, click Schedule Query. The scheduled query options open underneath the query box.
On the New Scheduled Query page:
- For Destination dataset, choose the appropriate dataset.
- For Display name, enter a name for the scheduled query such as
My scheduled query. The scheduled query name can be any value that allows you to easily identify the scheduled query if you need to modify it later.
- For Destination table:
- For a standard SQL query, enter the name of your destination table.
- For a DDL or DML query, leave this field blank.
- For Write preference:
- For a standard SQL query, choose either
WRITE_TRUNCATEto overwrite the destination table or
WRITE_APPENDto append data to the table.
- For a DDL or DML query, choose Unspecified.
(Optional) For Partitioning field:
- For a standard SQL query, if the destination table is a column-partitioned table, enter the column name where the table should be partitioned. Leave this field blank for ingestion-time partitioned tables and non-partitioned tables.
- For a DDL or DML query, leave this field blank.
(Optional) For Destination table KMS key, if you use customer-managed encryption keys, you can enter a customer-managed encryption key here.
3 hours. The shortest allowed period is fifteen minutes. See the
schedulefield under
TransferConfigfor more valid API values.
(Optional) Expand the Advanced section and configure notifications.
- For Cloud Pub/Sub topic, enter your Cloud Pub/Sub topic name, for example,
projects/myproject/topics/mytopic.
Check Send email notifications to allow email notifications of transfer run failures.
Click Add.
To view the status of your scheduled queries, click Scheduled queries in the navigation pane. Refresh the page to see the updated status of your scheduled queries. Click one to get more details about that scheduled query.
CLI
Option 1:is an alternative way to name the target dataset for the query results, when used with DDL/DML queries.
- Use either
--destination_tableor
--target_dataset, but not both.
- interval, when used with
bq querymakes a query a recurring scheduled query. A schedule for how often the query should run is required. Examples:
--schedule='every 24 hours'
--schedule='every 3 hours'
Optional flags:
--project_idis your project ID. If
--project_idisn't specified, the default project is used.
--replacewill truncate the destination table and write new results with every run of the scheduled query.
--append_tablewill append results to the destination table.
For example, the following command creates a scheduled query named
My Scheduled Query using the simple query
SELECT 1 from mydataset.test.
The destination table is
mytable in the dataset
mydataset. The scheduled
query is created in the default project:
bq query \ --use_legacy_sql=false \ --destination_table=mydataset.mytable \ --display_name='My Scheduled Query' \ --replace=true \ 'SELECT 1 FROM mydataset.test'
Option 2: Use the
bq mk command.
Scheduled Queries are a kind of transfer. To schedule a query, you can use the BigQuery Data Transfer Service CLI to make a transfer configuration.
Queries must be in StandardSQL dialect to be scheduled.
Enter the
bq mk command and supply the transfer creation flag
--transfer_config. The following flags are also required:
--data_source
--target_dataset(Optional for DDL/DML queries.)
--display_name
--params
Optional flags:
--project_idis your project ID. If
--project_idisn't specified, the default project is used.
--scheduleis how often you want the query to run. If
--scheduleisn't specified, the default is 'every 24 hours' based on creation time.
For DDL/DML queries, you can also supply the
--locationflag to specify a particular region for processing. If
--locationisn't specified, the global Google Cloud Platform location is used.
bq mk \ --transfer_config \ --project_id=project_id \ --target_dataset=dataset \ --display_name=name \ --params='parameters' \ --data_source=data_source
Where:
- dataset is the target dataset for the transfer configuration.
- This parameter is optional for DDL/DML queries. It is required for all other queries.
- name is the display name for the transfer configuration. The display name can be any value that allows you to easily identify the scheduled query (transfer) if you need to modify it later.
- parameters contains the parameters for the created transfer configuration in JSON format. For example:
--params='{"param":"param_value"}'. For a scheduled query, you must supply the
queryparameter.
- The
destination_table_name_templateparameter is the name of your destination table.
- This parameter is optional for DDL/DML queries. It is required for all other queries.
- For the
write_dispositionparameter, you can choose
WRITE_TRUNCATEto truncate (overwrite) the destination table or
WRITE_APPENDto append the query results to the destination table.
- This parameter is optional for DDL/DML queries. It is required for all other queries.
- (Optional) The
destination_table_kms_keyparameter is for customer-managed encryption keys.
- data_source is the data source —
scheduled_query.
For example, the following command creates a scheduled query transfer
configuration named
My Scheduled Query using the simple query
SELECT 1
from mydataset.test. The destination table
mytable is truncated for every
write, and the target dataset is
mydataset. The scheduled query is created
in the default project:
bq mk \ --transfer_config \ --target_dataset=mydataset \ --display_name='My Scheduled Query' \ --params='{"query":"SELECT 1 from mydataset.test","destination_table_name_template":"mytable","write_disposition":"WRITE_TRUNCATE"}' \ --data_source=scheduled_query
The first time you run the command,.
Python
Before trying this sample, follow the Python setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Python API reference documentation .
from google.cloud import bigquery_datatransfer_v1 import google.protobuf.json_format client = bigquery_datatransfer_v1.DataTransferServiceClient() # TODO(developer): Set the project_id to the project that contains the # destination dataset. # project_id = "your-project-id" # TODO(developer): Set the destination dataset. The authorized user must # have owner permissions on the dataset. # dataset_id = "your_dataset_id" # TODO(developer): The first time you run this sample, set the # authorization code to a value from the URL: # # # authorization_code = "_4/ABCD-EFGHIJKLMNOP-QRSTUVWXYZ" # # You can use an empty string for authorization_code in subsequent runs of # this code sample with the same credentials. # # authorization_code = "" # Use standard SQL syntax for the query. query_string = """ SELECT CURRENT_TIMESTAMP() as current_time, @run_time as intended_run_time, @run_date as intended_run_date, 17 as some_integer """ parent = client.project_path(project_id) transfer_config = google.protobuf.json_format.ParseDict( { "destination_dataset_id": dataset_id, "display_name": "Your Scheduled Query Name", "data_source_id": "scheduled_query", "params": { "query": query_string, "destination_table_name_template": "your_table_{run_date}", "write_disposition": "WRITE_TRUNCATE", "partitioning_field": "", }, "schedule": "every 24 hours", }, bigquery_datatransfer_v1.types.TransferConfig(), ) response = client.create_transfer_config( parent, transfer_config, authorization_code=authorization_code ) print("Created scheduled query '{}'".format(response.name))
Setting up a manual run on historical dates
In addition to scheduling a query to run in the future, you can also trigger
immediate runs manually. Triggering an immediate run would be necessary if your
query uses the
run_date parameter, and there were issues during a prior run.
For example, every day at 09:00 you query a source table for rows that match
the current date. However, you find that data wasn't added to the source table
for the last three days. In this situation, you can set the query to run on
historical data within a date range that you specify. Your query is run using
combinations of
run_date and
run-time that correspond to the dates you
configured in your scheduled query.
After setting up a scheduled query, here's how you can run the query by using a historical date range:
Console
After clicking Schedule to save your scheduled query, you can click the Scheduled queries button to see the list of currently scheduled queries. Click any display name to see the query schedule's details. At the top right of the page, click Schedule backfill to specify a historical date range.
The run times chosen are all within your selected range, including the first date and excluding the last date.
Example 1
Your scheduled query is set to run
every day 09:00 Pacific Time. You're
missing data from Jan 1, Jan 2, and Jan 3. Choose the following historic
date range:
Start Time = 1/1/19
End Time = 1/4/19
Your query runs using
run_date and
run_time parameters that correspond
to the following times:
- 1/1/19 09:00 Pacific Time
- 1/2/19 09:00 Pacific Time
- 1/3/19 09:00 Pacific Time
Example 2
Your scheduled query is set to run
every day 23:00 Pacific Time. You're
missing data from Jan 1, Jan 2, and Jan 3. Choose the following historic
date ranges (later dates are chosen because UTC has a different date at
23:00 Pacific Time):
Start Time = 1/2/19
End Time = 1/5/19
Your query runs using
run_date and
run_time parameters that correspond
to the following times:
- 1/2/19 09:00 UTC, or 1/1/2019 23:00 Pacific Time
- 1/3/19 09:00 UTC, or 1/2/2019 23:00 Pacific Time
- 1/4/19 09:00 UTC, or 1/3/2019 23:00 Pacific Time
After setting up manual runs, refresh the page to see them in the list of runs.
Classic UI
After clicking Add to save your scheduled query, you'll see the details of your scheduled query displayed. Below the details, click the Start Manual Runs button to specify a historical date range.
You can further refine the date range to have a start and end time, or leave
the time fields as
00:00:00.
Example 1
If your scheduled query is set to run
every day 14:00, and you apply the
following historic date range:
Start Time = 2/21/2018 00:00:00 AM
End Time = 2/24/2018 00:00:00 AM
Your query runs at the following times:
- 2/21/2018 14:00:00
- 2/22/2018 14:00:00
- 2/23/2018 14:00:00
Example 2
If your scheduled query is set to run
every fri at 01:05 and you apply the
following historic date range:
Start Time = 2/1/2018 00:00:00(a Thursday)
End Time = 2/24/2018 00:00:00 AM (also a Thursday)
Your query runs at the following times:
- 2/2/2018 01:05:00
- 2/9/2018 01:05:00
CLI
To manually run the query on a historical date range:
Enter the
bq mk command and supply the transfer run flag
--transfer_run. The following flags are also required:
--start_time
--end_time
bq mk \ --transfer_run \ --start_time='start_time' \ --end_time='end_time' \ resource_name
Where:
- start_time and end_time are timestamps that end in Z or contain a valid time zone offset. Examples:
- 2017-08-19T12:11:35.00Z
- 2017-05-25T00:00:00+00:00
- resource_name is the scheduled query's (or transfer's) Resource Name. The Resource Name is also known as the transfer configuration.
For example, the following command schedules a backfill for scheduled query
resource (or transfer configuration):
projects/myproject/locations/us/transferConfigs/1234a123-1234-1a23-1be9-12ab3c456de7.
bq mk \ --transfer_run \ --start_time 2017-05-25T00:00:00Z \ --end_time 2017-05-25T00:00:00Z \ projects/myproject/locations/us/transferConfigs/1234a123-1234-1a23-1be9-12ab3c456de7
API
Use the projects.locations.transferConfigs.scheduleRun method and supply a path of the TransferConfig resource.
Quotas
A scheduled query is executed with the creator's credentials and project, as if you were executing the query yourself. A scheduled query is subject to the same BigQuery Quotas and limits as manual queries.
Scheduled queries are priced the same as manual BigQuery queries.
Known issues and limitations
Regions
Cross-region queries are not supported, and the destination table for your scheduled query must be in the same region as the data being queried. See Dataset locations for more information about regions and multi-regions.
Google Drive
You can query Google Drive data in a scheduled query. If you're scheduling an existing query, you might need to click "Update Credentials" in the scheduled query details screen. Allow 10—20 minutes for the change to take effect. You might need to clear your browser's cache. Credentials are automatically up to date for new scheduled queries.
|
https://cloud.google.com/bigquery/docs/scheduling-queries
|
CC-MAIN-2019-39
|
refinedweb
| 3,073
| 55.84
|
This technique makes use of the URLLoader's
close method. Therefore, the code is only available for AS3.
You know what would be nice? If we could serve every user the same 1024×768, 512 kilobits per second video. Unfortunately, some selfish people still refuse to pay us developers the simple courtesy of buying that T1 line (I'm looking at you, Mom). To make matters even worse, our bosses want these selfish losers to be able to watch our videos. Luckily, Flash's FLVPlayback component supports a subset of SMIL that allows us to serve different videos to users with different bandwidths.* For those who don't know, a SMIL file looks something like this:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" ""> <smil xmlns=""> <body> <switch> <video src="video2.flv" system- <video src="video1.flv" system- <video src="video0.flv" /> </switch> </body> </smil>
Given the above SMIL file, users with connections transferring at a rate of 512kbps or higher should see "video2.flv," users with transfer speeds between 256kbps and 512kbps should see "video1.flv," and everybody else should get "video0.flv." But they won't — unless you let the FLVPlayback component know what their transfer rate actually is. Generally, this means having to download a file of known size and estimate the user's bandwidth based on how long the download takes to complete. However, with the advent of AS3 (and a little clever actionscripting), we can automate this process entirely.
See the NCManagerAuto Example and then download the NCManagerAuto Source and Example Files to try it out for yourself. (Or grab it from my as3 subversion repository.)
Most of the work of the FLVPlayback component is actually done by the VideoPlayer object that it wraps. The VideoPlayer class, in turn, uses a helper class called NCManager to (of all things) manage NetConnections. Therefore, we could make some pretty significant changes to how our FLVPlayback components operate if we could only substitute our own versions of NCManager for the default. If you haven't already guessed, Adobe provides us with a simple method to do exactly that. By setting the static
iNCManagerClass property of the VideoPlayer class, we can change how VideoPlayers (and by extension FLVPlayback components) handle NetConnections. By setting the property to the xa NCManagerAuto class, we can enable automatic (and completely transparent) bandwidth detection for our FLVPlayback components. But enough babbling, here's how you do it:
import fl.video.FLVPlayback; import fl.video.VideoPlayer import com.exanimo.video.NCManagerAuto; VideoPlayer.iNCManagerClass = NCManagerAuto; var myFLVPlayback:FLVPlayback = new FLVPlayback(); myFLVPlayback.source = 'example.smil'; this.addChild(myFLVPlayback);
Except for the addition of one line (okay, one line and two import statements), everything here is business as usual. You can create your FLVPlayback component with ActionScript on a frame, in a document class, or even drag it onto the stage. Just add
VideoPlayer.iNCManagerClass = NCManagerAuto; and the FLVPlayback component will be able to parse your SMIL file and play the video appropriate for your user's internet connection.
So How Does it Work?
The NCManagerAuto class uses a variation of the same trick people have always used to estimate a user's bandwidth. Historically, this required a small file of known size on your server. This file would then be downloaded and, based on the time the download took, the bandwidth could then be estimated. However, NCManagerAuto doesn't require any extra files on your server. Instead, it creates an instance of the xa BandwidthChecker, which it uses to download the first 35K of one of the FLVs in your SMIL file — an uncached version of course. It then sets the bitrate of your component using the data returned by the BandwidthChecker.
Of course, this method of determining bandwidth isn't entirely foolproof. Its drawbacks have been documented by almost everybody who's written on the subject so I won't go into it. However, since the actual detection is encapsulated in the BandwidthChecker, it'll be a simple switch if a more accurate method arises. Both the NCManagerAuto and the BandwidthChecker are available under the MIT License. Enjoy the free code.
*There appears to be a bug in how Adobe's FLVPlayback component parses SMIL files: the SMILManager 's
parseVideo method throws away the system-bitrate attributes of your video nodes. Therefore, the component will think that the first node is your default video, and use it every time. The source code that Adobe includes with Flash 9 (located in the "Component Source" directory) does not exhibit this problem, so I can only guess that the FLVPlayback component was compiled with an earlier version of the SMILManager class.
This technique addresses the problem transparently by using a different SMILManager class. Even if you do not want to use automatic bandwidth checking (and instead want to detect bandwidth using your own method), you can still use the NCManagerAuto class to work around this bug. Simply set the
bitrate property of your FLVPlayback instance and the component will use that value instead of trying to determine the user's bandwidth itself.
2007.10.17
This looks cool. If I have my flv's hosted on an rtmp server should I be able to link to different versions of this content by changing the src path in the SMIL file? I have tried with the URL I usually use when linking from flash movies but to no avail.
rtmp://xx.xx.xx.xx/test_video/_definst_/movies/myfilename.flv
Is this possible and if so what do I need to do?
2007.11.13
Actually, when you use a SMIL file with an RTMP server, you need to set the application (rtmp://xx.xx.xx.xx/test_video) in the meta tag. Try this:
2007.11.18
Hey there,
This is almost what I was looking for, pretty transparent way to detect bandwidth. But what about simply turning videos on or off based on connection speed. For our dialup users, we want to disable videos entirely. Could I use something like ContentPath = null, and myFLVPlayback._visible=false?
Cheers,
Luke
2007.12.20
I understand the structure of the smil , my question is how do you actually embed this into your html/php code? We are looking to have 2, possibly 3 bitrate/size versions of each of our videos and I don't understand how to link to this in a page.
Thanks
2008.01.24
This is a bit odd. Probably a novice AS3 issue. When I try to compile the example with a supplied set of FLVs and SMIL I get this error in my ouput:()
2008.02.23
Yes I am also getting the same error message.()
And seems like it only happens in IE, which is weird coz flash is supposed to be crossbrowser?
In Firefox and in the IDE it works fine.
2008.02.23
Just confirmed that the example file given is also hosed in IE.
Making this change seems to fix it tho. Anyhow this is cool stuff.
Thx
var serverPath:String = "";
try {
serverPath = new LoaderInfo().url.split('/').slice(0, -1).join('/');
} catch (e:Error) {
serverPath = ExternalInterface.call( 'function(){ return window.location.toString(); }' );
serverPath = (serverPath)? serverPath : "";
}
//var myBandwidthChecker = new BandwidthChecker(URLUtil.getFullURL(new LoaderInfo().url.split('/').slice(0, -1).join('/'), URLUtil.getFullURL(_streamName, _streams0.src)));
var myBandwidthChecker = new BandwidthChecker(URLUtil.getFullURL(serverPath, URLUtil.getFullURL(_streamName, _streams0.src)));
2008.03.19
@Luke:
@PDL:
This is a Flash solution. Just embed a SWF like in the example. If you want to load different videos using the same SWF, just pass the SWF the URL of your SMIL file.
@jim, mteguh:
That was an error on my part. I've replaced
new LoaderInfo().urlwith
new Loader().contentLoaderInfo.loaderURL. Your solution is neat, mteguh, but I think it's off the mark for two reasons: 1) it requires JavaScript and 2) I believe we actually want the URL of the SWF (not the html container). The confusion is that (for some stupid reason) Flash expects FLV sources to be relative to the SWF, even though Loader and URLLoader treat URLs as being relative to the HTML container. Since we're using URLLoader to check the bandwidth (BandwidthChecker wraps URLLoader), we must account for the fact that the provided FLV source is relative to the location of the SWF. We do this by resolving the URL to the directory of the SWF. The ZIP file has been updated and the new code is checked into subversion.
2008.03.19
Oh man! That makes sense I don't know why I didn't even realize that was the problem. We had another guy in the office who had an install of flash 9 that had yet to be updated. It compiled for him. Pretty crazy that Adobe modified the language in Flash CS3 after it had been officially released for quite some time.
2008.06.02
I'm trying to use your detection once for two sets of videos – high bandwidth and low bandwidth. Each set is contained in two arrays, but from the info above, it looks like the src value must point to an FLV in order for the checking to occur – am I correct?
If so, is there a way that I can just pass a value based on the bitrate and then determine the FLV for playback? Currently I'm trying this:
// Function determining which Array to use
function setBandwidth():Array
{
var bandwidth:String = 'example.smil';
switch (bandwidth)
{
case "HI":
return(HiBandArray);
break;
case "LO":
return(LoBandArray);
break;
default:
trace ("defaulted!");
return(LoBandArray);
break;
}
}
2008.06.02
As a quick solution, I've used the FLV pathname to switch – but this would become cumbersome with larger directory paths and perhaps dynamic paths.
2009.01.15
[...] ex animo » Blog Archive » Automatic Bandwidth Detection for SMIL + FLVPlayback + Progressive Downl… [...]
2009.03.16
Does anyone know how you would go about getting a playback controller integrated into the movies using this method?
2009.04.16
I'm stumped. Things are working fine if I test the files locally, but once I upload the SMIL file, html and .swf file to my server, and point the FLVplayback component's source to the same SMIL on an http server, I don't get any video, just endless barber pole.
Any suggestions?
2009.04.17
Interesting. Your example code doesn't work for me either unless I open it locally on my Mac.
Your link above ("See the NCManagerAuto Example ") brings up nothing but a blank page.
If I download the sample source files and run them, voila! I see content.
But if I upload the exact same files to my server and try to run the html remotely, no content.
So, whatssupwiddat? ; ) Inquiring minds wanna know.
2009.04.17
Never mind. I figured it out.
For those following behind…
Apparently, in order for the smil file approach to work remotely, the smil file can NOT end with .smi or .smil as I had been informed elsewhere.
The file must end with .xml . (Or at least the way our http servers are configured, maybe this might work under different configurations, but it wouldn't work for me until I changed .smil to .xml )
I'm outtahere.
2009.04.22
@Mike Sorry I didn't respond sooner but thanks for reporting back with your findings!
2010.04.13
Hi man, nice code, work good but in Flex 3 and using SDK 4.0.x I' have problem on final compiling.
I use this additional compliler arguments: -locale en_US -static-link-runtime-shared-libraries=true
I solve the problem with next way…
edit next class: com.exanimo.video.NCManagerAuto.as
– error line: 175 -> var myBandwidthChecker = new BandwidthChecker(URLUtil.getFullURL(n…
– solution : you need declarate your variable, simply add ":*"
var myBandwidthChecker:* = new BandwidthChecker(URLUtil.getFullURL(new Loader().contentLoaderInfo.loaderURL.split('/').slice(0, -1).join('/'), URLUtil.getFullURL(_streamName, _streams[0].src)));
Good Luck
2010.04.13
Thanks for the comment Anthony, but I think you're using an old version. Try grabbing it from the SVN repository. I'll update the ZIP…someday.
2012.06.19
[...] you trying to do? ||| Originally, I was trying to detect the bandwidth using the method outlined here. Then, depending on either Lo or Hi bandwidth, define an array of associated FLVs to play. The [...]
2012.12.29
I am sure you will love ugg boots cheap cGfhwOOr [URL= – uggs cheap[/URL – and check coupon code available MHKmAOyN
2013.04.23
I love your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz respond as I'm looking to construct my own blog and would like to know where u got this from. thank you
2013.04.24
Thanks! I made it myself a long, long time ago.
|
http://exanimo.com/actionscript/automatic-bandwidth-detection-for-smil/
|
CC-MAIN-2019-09
|
refinedweb
| 2,138
| 66.03
|
View Complete Post
I am using MVC 2 with Entity Framework 4 models and MetadataType classes to create annotations that do not vanish everytime my model is generated... I followed Scott's article to create that.
I worked fine for simple classes, but when I got co a more complex one, with regular expression and range validations on doubles, it seemed to simply ignore the validation annotations altogether.
Any ideas?
Hi all,
I have a problem regarding validation of NHibernate models. For example I have these two models:
public class Person
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public Country Country { get; set; }
}
public class Country
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
When I implement a new Create-Person-View I use a dropdownlist to create a list of all countries (using for example View["countries"] = .. in the controller). When I save this new person in the controller action function the selected value (country Id in this case) of the country dropdownlist is stored in newPerson.Country.Id, this can be saved by using NHibernate so no problems here. However, my modelstate is invalid since the Name property of the country is not set and marked as Required in the country model, but I'm adding a person so only a country Id is fine. My question is how can I solve this problem, in other words: I only want the model validator to look at the current model and not deeper.
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
|
http://www.dotnetspark.com/links/21579-asp-net-mvc20-validation.aspx
|
CC-MAIN-2017-13
|
refinedweb
| 267
| 55.98
|
NOTE: If you are using the latest software for your Pi (which you should be) then you will need to edit the boot config text file:
Add the following line to /boot/config.txt
dtoverlay=w1-gpio
In previous tutorials we’ve outlined the integration of simple sensors and switches with the Raspberry Pi. These components have had a simple on/off or high/low output, which is sensed by the Raspberry Pi. Our PIR movement sensor tutorial for example, simply says “yes, I’ve detected movement”.
So, what happens when we connect a more advanced sensor and want to read data more complex data?. In addition to this, most 1-Wire sensors will come with a unique serial code (more on this later) which means you can connect multiple units up to one microcontroller without them interfering with each other.
The sensor we’re going to use in this tutorial is the Maxim DS18B20+ Programmable Resolution 1-Wire Digital Thermometer. The DS18B20+ has a similar layout to transistors called the TO-92 package, with three pins: GND, Data (DQ), and 3.3V power line (VDD). You’ll also need some jumper wires, a breadboard and a 4.7kΩ (or 10kΩ) resistor.
The resistor in this setup is used as a 'pull-up' for the data-line, and should be connected between the DQ and VDD line. It ensures that the 1-Wire data line is at a defined logic level, and limits interference from electrical noise if our pin was left floating. We’re also going to be using GPIO 4 [Pin 7] as the driver pin for sensing the thermometer output. This is the dedicated pin for 1-Wire GPIO sensing.
Hooking it up
1. Connect GPIO GND [Pin 6] on the Pi to the negative rail on the breadboard and connect GPIO 3.3V [Pin 1] on the Pi to the Positive rail on the breadboard.
2. Plug the DS18B20+ into your breadboard, ensuring that all three pins are in different rows. Familiarise yourself with the pin layout, as it’s quite easy to hook it up backwards!
3. Connect DS18B20+ GND [Pin 1] to the negative rail of the breadboard.
4. Connect DS18B20+ VDD [Pin 3] to the positive rail of the breadboard.
5. Place your 4.7kΩ resistor between DS18B20+ DQ [Pin 2] and a free row on your breadboard.
6. Connect that free end of the 4.7kΩ resistor to the positive rail of the breadboard.
7. Finally, connect DS18B20+ DQ [Pin 2] to GPIO 4 [Pin 7] with a jumper wire.
That’s it; we’re now ready for some programming!
Programming
With a little set up, the DS18B20+ can be read directly from the command line without the need for any Python programs. However, this requires us to input a command every time we want to know the temperature reading. In order to introduce some concepts for 1-Wire interfacing, we’ll access it via terminal first, and we’ll then write a Python programme which will read the temperature automatically at set time intervals.
The Raspberry Pi comes equipped with a range of drivers for interfacing. However, it’s not feasible to load every driver when the system boots, as it will increase the boot time significantly and use a considerable amount of system resources for redundant processes. These drivers are therefore stored as loadable modules and the command modprobe is employed to boot them into the Linux kernel when they’re required. The following two commands load the 1-Wire and thermometer drivers on GPIO 4.
sudo modprobe w1-gpio
sudo modprobe w1-therm
We then need to change directory cd to our 1-Wire device folder and list ls the devices in order to ensure that our thermometer has loaded correctly.
cd /sys/bus/w1/devices/
ls
In the device drivers, your sensor should be listed as a series of numbers and letters. In this case, the device is registered as 28-000005e2fdc3. You then need to access the sensor with the cd command, replacing our serial number with your own.
cd 28-000005e2fdc3
The sensor periodically writes to the w1_slave file, so we simply use the cat command to read it.
cat w1_slave
This yields the following two lines of text, with the output t= showing the temperature in degrees Celsius. A decimal point should be placed after the first two digits e.g. the temperature reading we’ve received is 23.125 degrees Celsius.
72 01 4b 46 7f ff 0e 10 57 : crc=57 YES
72 01 4b 46 7f ff 0e 10 57 t=23125
In terms of reading from the module, this is all that’s required from the terminal. Try holding onto the thermometer and taking another reading! With these commands in mind, we can write a Python program to output our temperature data automatically.
Python Program
Our first step is to import the required modules: os allows us to enable our 1-Wire drivers and interface with our sensor, and time allows our Raspberry Pi to define time, and enables the use of time periods in our code.
import os
import time
We then need to load our drivers:
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
The next step is to define our sensor’s output file (the w1_slave file) as defined above. Remember to utilise your own temperature sensor’s serial code!
temp_sensor = ‘sys/bus/w1/devices/28-000005e2fdc3/w1_slave’
We then need to define a variable for our raw temperature value (temp_raw); the two lines outputted by the sensor demonstrated with our terminal example. We could simply print this statement now. However, we’re going to process it into something more useable. So, we open, read, record and then close our temperature file. We use the return function here, in order to recall this data at a later stage in our code.
def temp_raw():
f = open(temp_sensor, 'r')
lines = f.readlines()
f.close()
return lines
First, we check our variable from the previous function for any errors. If you study our original output as defined in the terminal example, we get two lines of code (Line 0 = 72 01 4b 46 7f ff 0e 10 57 : crc=57 YES); we strip this line except for the last three digits, and check for the “YES” signal, indicating a successful temperature reading from the sensor. In Python, not-equal is defined as “!=”, so here we’re saying whilst the reading does not equal YES, sleep for 0.2s and repeat.
def read_temp():
lines = temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = temp_raw()
Once the program is happy that the YES signal has been received, we proceed to our second line of output code (Line 1 = 72 01 4b 46 7f ff 0e 10 57 t=23125). We find our temperature output “t=”, check it for errors, strip the output of the “t=” phrase to leave just the temperature numbers, and run two calculations to give us the figures in Celsius and Fahrenheit.
temp_output = lines[1].find('t=')
if temp_output != -1:
temp_string = lines[1].strip()[temp_output+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f
Finally, we loop our process and tell it to output our temperature data every 1 second.
while True:
print(read_temp())
time.sleep(1)
So that’s our code!
Save your program (I've saved as temp_2.py), and run it with Python to yield the temperature output:
sudo python temp_2.py
DS18B20+ sensors can be run in parallel, and accessed using their unique serial directories. The Python example above can be edited to access and read from multiple sensors!
42 Comments
|
https://www.modmypi.com/blog/ds18b20-one-wire-digital-temperature-sensor-and-the-raspberry-pi
|
CC-MAIN-2019-09
|
refinedweb
| 1,288
| 64.2
|
Hi, I have a python script where the user adds 10 shapefiles or geodatabse features that could be anywhere. Then each of the 10 shapefiles/gdb features are run through a few different tools (buffer, clip, intersect...) What is the best way to get all 10 shapes or geodatabase features into a list and then run the set of tools on the list. It seem like this would be much easier and quicker then copying all the tools 10 times. What is the recommended way to handle this task or get a list like using arcpy.ListFeatureClasses() but for a group of user supplied datasets.
Something that would look similar to this partial script
Something that would look similar to this partial script
import arcpy from arcpy import env import os env.workspace = "C:\Users\a\Desktop\DELME" output = "C:\Users\a\Desktop\FOLDER2\" data1 = "C:\Users\a\Desktop\FOLDER1\POLYGON1.shp" data2 = "C:\Users\a\Desktop\DELME\SpatialData\POLYGON2.shp" fcList = [] fcList.append([data1, data2]) for fc in fcList: arcpy.Buffer_analysis(fc, output, "100 FEET")
which is a nested list with two members.
This can be useful, but I don't think it is what you want.
Just making up the list is the simplest way:
the nested list thing is useful, as I said.
I use it for add field values:
|
https://community.esri.com/thread/94526-python-shapefile-list-for-geoprocessing
|
CC-MAIN-2019-13
|
refinedweb
| 223
| 75.3
|
17 May 2010 10:43 [Source: ICIS news]
SINGAPORE (ICIS news)--Here is Monday’s end of day ?xml:namespace>
CRUDE: June WTI $71.28/bbl down 33 cents/bbl BRENT June $77.85/bbl down 8 cents/bbl
Crude futures prices were trading just down on last Friday’s settlement levels late on Monday afternoon in Asia after recovering from losses of more than $1/bbl made earlier in the day. However, crude remained pressured by worries over demand from debt ridden European nations, and high
NAPHTHA: $719.00-720.00/tonne down $25.00/tonne
Naphtha was assessed lower in
BENZENE: $880-890/tonne; $25-30/tonne lower
Prices plummeted further in the afternoon as crude values continued its descent. No June prices were heard, but they were notionally pegged lower than July bids and offers which were hovering at $880-910/tonne FOB
TOLUENE: $785-800/tonne; $20/tonne lower
Prices fell further on Monday afternoon, pressured by the continuing fall in crude futures and weak market fundamentals in this region. Offers were heard for H2 June loading at $795-815
|
http://www.icis.com/Articles/2010/05/17/9359908/evening-snapshot-asia-markets-summary.html
|
CC-MAIN-2014-41
|
refinedweb
| 184
| 53.92
|
Try Microsoft.Dynamic.dll ;) Dave From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of mohammad mustaq Sent: Monday, August 16, 2010 5:49 AM To: Discussion of IronPython Subject: [IronPython] Microsoft.Scripting Assembly Version 1.0 does not contain Microsoft.Scripting.Hosting.Shell Namesapce Hi, I was using Microsoft.Scripting.dll (version 0.9) which was packaged with Iron Python 2.0.1. This assembly contains "Microsoft.Scripting.Hosting.Shell" Namesapce. I was using an Enum "Style" from this namespace. Now I upgraded to Iron Python 2.6.1. Here I observed that Microsoft.Scripting assembly does not contain "Microsoft.Scripting.Hosting.Shell" namespace. Could you please point me to where the Enum "Style" is located or its equivalent Enum in this version. thanks, Mustaq -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
|
https://mail.python.org/pipermail/ironpython-users/2010-August/013545.html
|
CC-MAIN-2017-30
|
refinedweb
| 141
| 63.86
|
See also: IRC log
waiting for people to come ...
basis for discussion is
dave: yves' points are
correct
... there is no way of writing a global pointer rule which is aware of values in the xliff
... even if we could figure out the xpath, you would need something in the rule to filter out things in the phase group that did not map to "revision"
... because you cannot differentiate phase groups in the way needed
... this topic, plus toolsRef issues
... plus if you want to do mapping between phase group and rules, you need more than pointer rules
... I'd say let's get rid of pointer rules
... appart of standoff pointers
"provenanceRecordsRefPointer"
everything else would be deleted. That is: "personPointer, personRefPointer, orgPointer, orgRefPointer, toolPointer, toolRefPointer, revPersonPointer, revPersonRefPointer, revOrgPointer, revOrgRefPointer, revToolPointer, revToolRefPointer and provRefPointer"
<scribe> ACTION: jirka to take for the ITS 2.0 schema into account [recorded in]
<trackbot> Created ACTION-325 - Take for the ITS 2.0 schema into account [on Jirka Kosek - due 2012-12-04].
<pnietoca> sorry i'm late
drop relax ng namespace, not used in the spec
added html namespace
dropping complete section
"The concept of a data category is independent of its implementation in an XML environment" > The concept of a data category is independent of its implementation in an XML and HTML environment"
"parts of an XML document " > "parts of an XML or HTML document"
"Selection relies on the information that is given in the XML Information Set [XML Infoset]. ITS applications MAY implement inclusion mechanisms such as XInclude or DITA's [DITA 1.0] conref."
drop the paragraph
<scribe> ACTION: felix to update list or IRI attributes at [recorded in]
<trackbot> Created ACTION-326 - Update list or IRI attributes at [on Felix Sasaki - due 2012-12-04].
action-326: not needed, handled during editing call
<trackbot> ACTION-326 Update list or IRI attributes at notes added
close action-326
<trackbot> ACTION-326 Update list or IRI attributes at closed
<scribe> dropped attribute list, reffering now only to RELAX NG schema and the anyURI data types
make sure that everything will say "HTML" or "HTML5"?
jirka: w3c working group said
they will use html versioning
... to avoid perception that ITS cannot be applied to HTML6
david: future proof is good
... but it is not valid HTML4
... you could say "HTML5 and higher"
karl: could say HTML and in an introduction we say "HTML is defined by HTML5 or its successor"
added a subsection in the terminology section, see
"[Ed. note: Below statement about schemas is wrong if the ITS schemas will be normative.]": deleting note
"[Ed. note: All traces of HTML has to be removed if we will proceed with CT 3 and HTML+ITS CC.]": note from Jirka
everyone is happy with separate html confirmance type, so can remove note
deleting all traces of HTML and HTML5 in this section, since there is now a separate conformacne type for html5
<Yves_>
discussed "processing expecations" vs "processing requirements", might change terminology (not normative def) during last call
<scribe> ACTION: Jirka to go through document and replace HTML5 > HTML [recorded in]
<trackbot> Created ACTION-327 - Go through document and replace HTML5 > HTML [on Jirka Kosek - due 2012-12-04].
discussion on "standoff markup", related to "location", but somehow different, not added here
delete ruby mentions throughout section 5.2
"The content model of span permits arbitrary nesting of ruby markup, since the rt element can contain span. An application of ruby, however, MUST not use such arbitrary nesting.": deleted, ruby not needed here
"The following attributes point to existing information:": deleted pointer attributes not needed anymore
scribe: after the "pointer in provenacne" discussion today
"5.3.3 CSS Selectors"
"5.3.4 Additional query languages"
"5.3.5 Variables in selectors"
<scribe> ACTION: felix to create example with rules element in sec. 5.4 - due 15 december [recorded in]
<trackbot> Created ACTION-328 - create example with rules element in sec. 5.4 [on Felix Sasaki - due 2012-12-15].
"Implicit Local selection in documents" > not inherited local selection is meant?
"Implicit Local selection in documents" > Selection via local ITS markup in documents
"Implicit Local selection in documents" > Selection via explicit (that is not inherited) local ITS markup in documents
keep as is, may clarify during LC phase
<pnietoca> the same happens in point 7.5
<pnietoca> so if you're going to change it you have to change both
tx, pnietoca, will take that into account during LC too
<pnietoca> sorry folks I have to leave, besides my microphone it's not working I don't know why!, I'm trying to speak but I can't
<pnietoca> I hope to have it fixed next time
sure, thanks for being here, pnietoca!
<pnietoca> anyway I 'll send a number of misprints and other things I noticed during the revision
<pnietoca> to the list
<pnietoca> cheers, bye!
discussing position of sec 7 "Using ITS Markup in HTML5"
<daveL> suggest text for last note in 5.5, change "and these are overridden via local markup." to "which are in turn overridden by local markup"
<scribe> done
sec 7 "Using ITS Markup in HTML5" is now sec 6, old sec 6 is sec 7
sec 8 about xhtml now also moved, is new sec 7, old sec 6 is sec 8
remove mentions of ontology
1 hour break
<Yves_> Sorry: i wasn't able to do diddly-squat on updating the provenance section
dave, felix - need a running list of all the MUST statements and make sure that we have a test
"The data category identifier MUST be one of the following identifiers" example of a statement that needs testing to
<scribe> ACTION: felix to come up with running list of MUST statements for testing - due december 15 [recorded in]
<trackbot> Created ACTION-329 - come up with running list of MUST statements for testing [on Felix Sasaki - due 2012-12-15].
<scribe> ACTION: felix to move data category identifiers to table in 8.1 Position, Defaults, Inheritance and Overriding of Data Categories [recorded in]
<trackbot> Created ACTION-330 - Move data category identifiers to table in 8.1 Position, Defaults, Inheritance and Overriding of Data Categories [on Felix Sasaki - due 2012-12-04].
replacing lq-issues with lq-issue in identifer list
"Inline global rules MUST be specified inside script which has type attribute with the value application/xml or application/its+xml. "
in 6.3 Inline Global Rules in HTML5
"with the value application/xml or application/its+xml." > "with the value application/its+xml."
"The script element itself MUST be child of head element." > "The script element itself SHOULD be child of head element."
6.4 Standoff Markup in HTML5
...
...xml: id attribute of the provenanceRecords element it contains."
same change for lq issue
"6.5 Precedence between Selections"
"Note: If identical selections are defined in different rules elements within one document, the selection defined by the last takes precedence.": removing the note in sec. 5.5 Precedence between Selections
same for 6.5 Precedence between Selections
added note from XML section 5.5 "ITS does not define precedence related to rules defined or linked based on non-ITS mechanisms (such as processing instructions for linking rules)." to HTML section 6.5
"7 Using ITS Markup in XHTML"
<scribe> ACTION: karl to create xhtml example for 7 Using ITS Markup in XHTML [recorded in]
<trackbot> Created ACTION-331 - Create xhtml example for 7 Using ITS Markup in XHTML [on Karl Fritsche - due 2012-12-04].
karl could do wed, felix not wed, but thur
dave from 1-3 p.m. utc
on thursday
and wed too
yves better on wed
felix on thur 2 p.m. utc - later
yves: will modify proveance ot remove pointers
This is scribe.perl Revision: 1.137 of Date: 2012/09/20 20:19:01 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) No ScribeNick specified. Guessing ScribeNick: fsasaki Inferring Scribes: fsasaki Present: karl yves felix Yves_ dave david jirka pnietoca Got date from IRC log name: 27 Nov 2012 Guessing minutes URL: People with action items: felix jirka karl[End of scribe.perl diagnostic output]
|
http://www.w3.org/2012/11/27-mlw-lt-minutes.html
|
CC-MAIN-2014-42
|
refinedweb
| 1,360
| 52.09
|
go to bug id or search bugs for
Description:
------------
When I try to define a particular class it fails with "cannot redeclare class ...". When I check with class_exists('...') it returns false, but I still cannot create it. I eventually found some previous code which uses the same name to define an interface.
Test script:
---------------
Interface Singleton{public static function instance();}
if (class_exists('Singleton')) {
$reason = 'class already exists';
} else {
class Singleton{
static function getInstance(){
return true;
}
}
}
Expected result:
----------------
If it is not possible to define a class and an interface with the same name, then the class_exists() function should also include interface names.
If it IS possible to have a class and an interface with the same name, then the compiler should NOT reject the second reference.
Add a Patch
Add a Pull Request
Thats how the OO is designed, internally is interfaces just a class with an additional flag.
So no bug here
If an interface is a class, then it should show up in class_exists() and get_declared_classes().
Yes, I agree.
I think the error message ("Cannot redeclare class") should be clearer about classes and interfaces sharing the same namespace, which is needed as type hints would be conflicting otherwise, but class_exists (by default) should only check classes in my opinion. Any change should consider that there's also interface_exists() and they should be consistent.
I disagree. class_exists() SHOULD check if that name has already been declared as an interface otherwise you get the following situation:
if (!class_exists('foobar') { // returns false
class foobar{} // fails because interface exists
}
On the one hand it is saying "a class with the name 'foobar' does not exist" which is immediately followed by "you cannot create a class with the name 'foobar' as it already exists". That is not logical to me.
In my opinion, in order to be valid the code snippet should read:
if (!class_exists('foobar') && !interface_exists('foobar') ) {
class foobar{}
}
The error message on attempting to declare a class with the same name as an
interface should respond:
Cannot declare class as an interface exists with that name
The reverse message should also be possible.
It does not make sense to allow an interface and a class to have the same name
(type hinting is a great example why not), and 'class_exists' should only refer
to classes (the clue's in the name).
The confusion is merely down to an inaccurate error message.
Note: There's a reason it's not uncommon for people to prefix interfaces with an
'i'
I think you the fact of class and interface sharing a same namespace should be clearly written into the manual!
And the better way, the two should not share a same namespace at all.
It waste me some much time to check my project.
The language-developers have two options. Either a clearer error message as a quick-fix, or allowing interfaces and classes with the same name, with the necessary underlying updates properly implemented in the language. That would be the elegant, and logical way.
xiaodujinjin@gmail.com
This was improved in PHP 7. For the code:
interface foo {}
class foo implements foo {}
new foo();
The error message is now:
Fatal error: Cannot declare class foo, because the name is already in use in /in/Nnh4T on line 6
Which I believe meets the criteria of "a clearer error message as a quick-fix,"
|
https://bugs.php.net/bug.php?id=51225
|
CC-MAIN-2021-21
|
refinedweb
| 562
| 58.62
|
Arduino IDE can't find message header
Hey, I'm new to ROS and trying to have a led blink at will with my Arduino from my computer using a message, the future goal being to control several ones from my terminal. I am using ROS lunar and the rosserial_arduino package.
I wrote my publisher, subscriber and message, ran the package from a terminal to another as a test and it worked perfectly. Then I put the subscriber code in a new Arduino sketch and adapted it. However, when I try to compile it, I get the following error:
/home/eric/Arduino/blink_one_ros/blink_one_ros.ino:2:30: fatal error: blink_one/Number.h: No such file or directory #include <blink_one/Number.h> ^
My include being as follows:
#include <ros.h> #include <blink_one/Number.h>
I already looked into this answer and several others, but I am afraid that it would be an error from my package so I want to be sure before re-installing ROS.
I did run the often advised:
rm -rf ros_lib/ rosrun rosserial_arduino make_libraries.py <my_path>
And indeed, I can find my message header in my ros_lib/blink_one . Yet it still does not seem to be recognized.
If anyone knows a solution or has some hints, I'd appreciate it!
Thanks!
is the blink_one msg is written by use? because by default there is no such msg
I don't quite understand the question, sorry. I made it so that the publisher node running in my PC publishes a message into a topic that will be read by the subscriber node, which will be loaded in the Arduino. The message data is an integer, that I want to input in my terminal.
what is the msg type of your topic? please check using
rostopic info /topic name. I just want to know what is
<blink_one/Number.h>. please let me know the msg type(std_msgs/Int64 or ?) of topic.
It should be an int16 but when I type this, I get
Type: blink_one/Number
Then why are you including
<blink_one/Number.h. It should be
#include std_msgs/Int16.h
Sorry, I slightly modified my previous answer after checking. About the use of the include, it's because I call this function
void chatterCallback(const blink_one::Number msg) { code... }.
How you have created
blink_one/Number.h. Make sure it is available in
Arduino/libraries/ros_lib/blink_one/Number.h. refre this link
I created the header by first creating the
.msgfile, then adding the required lines in the CMakeLists as shown in the msg and srv tutorials and finally
catkin_make. Yes, the header is in the
ros_lib/blink_onefolder.
|
https://answers.ros.org/question/292116/arduino-ide-cant-find-message-header/
|
CC-MAIN-2021-43
|
refinedweb
| 439
| 66.94
|
Tutorial
Intro to MDX.
Most of you have probably used Markdown files in your Gatsby.js sites, and you already know it’s an amazing way to write content. But plain Markdown is geared towards text-based content, and it can be limiting when you want to step outside of that use case. That all changes with MDX, a superset of Markdown that allows us to embed JSX directly into Markdown files. Sounds awesome, doesn’t it? In this article we’ll explore the basics of MDX with Gatsby, including some introductory techniques to help you start using it right away.
Before we dive in, you will need to have a Gatsby project that is set up and ready to edit. If you need help getting to that point, please follow the steps in Your First Steps with Gatsby v2 and then return here afterwards.
Installation
Thanks to Gatsby’s incredible plugins library, the installation process is easy! Using MDX with Gatsby only requires a single plugin, gatsby-plugin-mdx, along with the MDX peer dependencies.
Let’s install those now, like this:
$ yarn add gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react
Let’s also install
gatsby-source-filesystem so that we can make use of frontmatter, generate Gatsby nodes from local files, and use import/export functionality in our MDX files:
$ yarn add gatsby-source-filesystem
While not technically required, this step is highly recommended — as it really opens the full potential of MDX content with Gatsby!
Configuration
Like with all Gatsby plugins, we need to add configuration details to the
plugins section of
gatsby-config.js.
Let’s configure both
gatsby-plugin-mdx and
gatsby-source-filesystem like this:
module.exports = { //...siteMetadata, etc plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `pages`, path: `${__dirname}/src/pages/`, }, }, { resolve: `gatsby-plugin-mdx`, options: { defaultLayouts: { default: require.resolve(`./src/components/layout.js`), }, }, // ... other plugins ], }
Notice that we are setting a
default key in the
defaultLayouts option. This will automatically wrap all MDX files with our site’s default
layout.js component.
The gatsby-config.js file has been edited, so don’t forget to restart the development environment before proceeding!
Configuration options
There are several configuration options available for
gatsby-plugin-mdx:
- extensions: (Array of strings) Sets file extensions that will be processed as MDX. I typically set this to
['.mdx', '.md']to also process normal Markdown files as MDX.
- defaultLayouts: (Object) This is frequently used when you have multiple types of generated content, such as blog posts and product reviews. (And as seen above, you can also set a
defaultkey to auto-wrap all MDX files.)
- gatsbyRemarkPlugins: (Array of plugin objects) This allows us to use various Gatsby-specific remark plugins along with the MDX processing. The
gatsby-remark-imagesplugin is often used here.
- remarkPlugins: (Array of plugin objects) Similar to the above option, but for non-Gatsby dependent remark plugins.
- rehypePlugins: (Array of plugin objects) Similar to above, but for rehype plugins.
- mediaTypes: (Array of strings) Sets which media types are processed. (You probably won’t need to use this very often.)
Full details on the usage of these options can be found in the plugin’s documentation. These docs are excellent, and I highly recommend going over them after reading this article! 🔍
Basic Usage
The configuration we have so far can already process all
.mdx files in our site. And thanks to Gatsby’s built-in behavior, if we add them to the
src/pages/ directory they will also become pages automatically!
Let’s do that now by creating a simple MDX file at
src/pages/mdx-intro/index.mdx. We’ll start off with some frontmatter and basic Markdown text, like a typical Markdown blog page would have:
--- title: MDX is Magical! path: /mdx-intro date: 2019-08-25 --- # Hooray For MDX! This will be like turbo-charged Markdown!
You can view this new page by visiting in your browser.
You’ll probably recognize this page creation pattern if you went through the Your First Steps with Gatsby v2 article, the only difference being this is an MDX file instead of Markdown. This is nothing special or new so far. Let’s change that!
Using Components in MDX
One of the primary features of MDX is that we can import and use JSX components right inside of Markdown content.
To demonstrate this, let’s create a simple component at
/src/components/TitleBar.js that will let us display a customized title bar.
import React from 'react'; const TitleBar = ({ text, size, bkgdColor }) => ( <div style={{ margin: '2rem 0', padding: '2rem', backgroundColor: bkgdColor || '#fff', }} > <h2 style={{ fontSize: size || '18px', margin: 0, }} > {text} </h2> </div> ); export default TitleBar;
Next, let’s update our MDX file to look like this:
--- title: MDX is Magical! path: /mdx-intro date: 2019-08-25 --- import TitleBar from "../../components/TitleBar.js"; <TitleBar size={"32px"} bkgdColor={"#4aae9b"} text={props.pageContext.frontmatter.title} /> This will be like turbo-charged Markdown!
There are two things to note here:
- First, we just imported and used a React component directly inside Markdown! Let that sink in for a moment, because this is an incredibly powerful concept. (Imagine blog posts with animated charts and/or dynamically loaded data, complex interactivity, and more.)
- Second, you may have noticed that we are able to access the frontmatter values from
props.pageContext.frontmatter. This can be quite useful, too!
Important: If your MDX files contain frontmatter, always place any import statements after the frontmatter block!
Go ahead and view the updated page in your browser, and try editing the
size and
bkgdColor props to watch it update. It’s a really simple example, but again: we are using a React component inside Markdown! Pretty sweet, right?!
Assigning Layouts
As mentioned in the configuration section, MDX provides us with an easy way to set up custom layouts. These layouts are convenient for wrapping additional styling and/or content around our MDX files.
Configuring default layouts
We can set up default layouts for our MDX files in
gatsby-config.js, even for specific locations. Take a look at this example:
module.exports = { plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `pages`, path: `${__dirname}/src/pages/`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `posts`, path: `${__dirname}/src/blog/`, }, }, { resolve: `gatsby-plugin-mdx`, options: { defaultLayouts: { posts: require.resolve("./src/components/blog-layout.js"), default: require.resolve("./src/components/layout.js"), }, }, }, ], }
In this example, we have configured our site so that all MDX files sourced from the
/src/blog directory would use
blog-layout.js as a layout/wrapper. We also set up a
default config here, too.
Note: This behavior doesn’t currently seem to work as expected with MDX files sourced from the
pages directory. (But you can still wrap them with a
default layout setting, like we have currently done.)
Manually assigning or removing layouts
Sometimes you will need to wrap a specific MDX file with a unique layout, or with no layout at all. This can be easily done by using JavaScript’s
export default syntax inside our MDX files, which overrides any
defaultLayout settings. We’ll cover that in the next section!
Importing Other MDX Files
In addition to importing/using JSX components, we can also import and use other MDX files as if they were components. (Hint: they actually are!)
Let’s create a new MDX file in our components directory, at
/src/components/postSignature.mdx. We will use this at the bottom of our MDX page as an author’s signature.
##### Thanks for Reading! *🐊 Al E. Gator | alligator.io | al@example.com* export default ({ children }) => ( <> {children} </> )
Notice the
export default statement at the bottom of the file. As mentioned in the previous section, this is how we can override our
defaultLayout configuration settings. In this case, we’re exporting an empty
<> wrapper around our signature instead.
Moving along, let’s import this MDX signature into our main MDX file, over at
/src/pages/mdx-intro/index.mdx:
--- title: MDX is Magical! path: /mdx-intro date: 2019-08-25 --- import TitleBar from "../../components/TitleBar.js"; import PostSignature from "../../components/postSignature.mdx"; <TitleBar size={"32px"} bkgdColor={"#4aae9b"} text={props.pageContext.frontmatter.title} /> This is like turbo-charged Markdown! <PostSignature />
You should now see this signature at the bottom of the
mdx-intro page. Awesome!! 😎
GraphQL Queries
Thanks to the plugin combo of
gatsby-plugin-mdx and
gatsby-source-filesystem, our MDX pages are also readily available to us via GraphQL queries.
We won’t spend much time on this, as this functionality is nearly identical to querying plain Markdown files in the same manner. (The only difference is that the MDX nodes are in
allMdx and
mdx instead of
allMarkdownRemark and
markdownRemark.)
Here’s an example query that would fetch the frontmatter of all available MDX files:
query { allMdx { edges { node { frontmatter { title path date(formatString: "MMMM DD, YYYY") } } } } }
Providing Other Data
We can also provide additional data through our MDX files by using JavaScript’s
export syntax, (not to be confused with
export default as used above!) Any exported variables are added to the GraphQL schema automatically, so that we can use it when needed in GraphQL queries and/or during rendering.
Here’s some example “Food Truck Review” data that we could add to our MDX page:
export const myReviews = [ { name: "Tim's Tacos", overall: 9, variety: 7, price: 8, taste: 9 }, { name: "Noodleville", overall: 7, variety: 5, price: 6, taste: 8 }, { name: "Waffle Shack", overall: 6, variety: 5, price: 4, taste: 6 }, ];
After adding that anywhere in the file, we could query the data in GraphQL by accessing
allMdx.nodes.exports, like this:
query MdxExports { allMdx { nodes { exports { myReviews { name overall variety price taste } } } } }
This is just a really basic demo, but this functionality can be used in incredibly creative and dynamic ways.
A Practical Example
Let’s finish up by adding a fun & practical example to our page. We’re going to use the
myReviews data that we set up above to display an animated bar chart!
First, let’s add the Recharts library to our site. This is a powerful but lightweight charting library that I use frequently in my client projects.
$ yarn add recharts
Next, we will use Recharts to create a reusable bar chart component. Since this isn’t an article about Recharts, just go ahead and create a new file at
/src/components/BarChart.js and paste in the following code:
import React, { PureComponent } from 'react'; import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, } from 'recharts'; const colorsList = ['#008f68', '#6db65b', '#4aae9b', '#dfa612']; class ExampleChart extends PureComponent { render() { return ( <div style={{ width: '100%', height: 350 }}> <ResponsiveContainer> <BarChart data={this.props.data}> <CartesianGrid strokeDasharray="2 2" /> <XAxis dataKey="name" /> <YAxis type="number" domain={[0, 10]} /> <Tooltip /> <Legend /> {this.props.bars.map((bar, i) => ( <Bar dataKey={bar} fill={colorsList[i]} key={`bar_${i}`} /> ))} </BarChart> </ResponsiveContainer> </div> ); } } export default ExampleChart;
Now we have a nice bar chart component set up, so we just need to import and use it in the MDX page. Here’s our final version:
--- title: MDX is Magical! path: /mdx-intro date: 2019-08-25 --- import TitleBar from '../../components/TitleBar'; import PostSignature from '../../components/postSignature.mdx'; import BarChart from "../../components/BarChart"; export const myReviews = [ { name: "Tim's Tacos", overall: 9, variety: 7, price: 8, taste: 9 }, { name: "Noodleville", overall: 7, variety: 5, price: 6, taste: 8 }, { name: "Waffle Shack", overall: 6, variety: 5, price: 4, taste: 6 }, ]; <TitleBar text={props.pageContext.frontmatter.title} size={'32px'} bkgdColor={'#4aae9b'} /> This page is built with turbo-charged Markdown! #### My Food Reviews: <BarChart data={myReviews} bars={["overall", "variety", "price", "taste"]} /> <PostSignature />
You should now see a sweet-looking multi-colored bar chart that animates into view, and even has animated tooltips on rollover. 📊👈
And I’ll say it again:This is all inside a Markdown (MDX) page! Just think of all the interesting blog posts and pages you can create in no time flat…
Conclusion
We have really covered a lot in this intro to MDX with Gatsby! Hopefully it wasn’t too overwhelming, and you can see that this combo is a total game-changer for rapid website development.
However, we only scratched the surface of what is possible. From here, I recommend digging into the Gatsby docs section on MDX. It’s a rabbit-hole worth venturing down, I promise! 🕳🐇
|
https://www.digitalocean.com/community/tutorials/gatsbyjs-mdx-in-gatsby
|
CC-MAIN-2020-34
|
refinedweb
| 2,051
| 55.54
|
Qt Weekly is back from vacation with a post from a guest blogger (*applause*). In this post, Lorenz Haas tells us how to link Qt classes in custom documentation that is generated by using Doxygen.
By mid-2008, Sebastian Pipping introduced doxygen2qthelp for generating Qt Compressed Help files (*.qch) via Doxygen. Already by the end of the year, it was successfully merged into Doxygen. While 1.5.7.1 still had some mirror problems, version 1.5.8 provided stable and comprehensive support for creating QCH files out of the box. See Sebastian’s announcement as well as David Boddie’s article in Qt Quarterly.
Since then, this feature – I guess – has been used a thousand, a million times. Nowadays, I personally can’t imagine working without it. This is because it integrates perfectly into my favorite IDE – Qt Creator. There I can use my own documentation for context-sensitive help that can be triggered by the F1-shortcut:
However, one tiny, but very annoying detail spoils the party. Qt classes don’t get linked and so you can’t conveniently click on a piece of text, such as QString, to open the documentation of QString. In Qt’s own help files that come with Qt Creator, however, you can click every Qt class and you are thus used to doing so. So let’s see how we can rock the party with custom help files.
Before we do so, however, let’s briefly summarize how we generate the custom help file that is shown in the picture.
Generating Help Files
First, we have a small example file – main.cpp – posing as the full documented project:
class SomeClass { public: /** * \brief A simple description * * Here is the documentation body containing references * to Qt functions like QPixmap::copy(). */ QString getText(const QDomElement &e); };
Second, we create a basic configuration file for Doxygen by calling:
doxygen -g doxyfile.cfg
We edit the following options:
INPUT = main.cpp GENERATE_QHP = YES QCH_FILE = ../MyDoc.qch QHP_NAMESPACE = your.domain.project QHG_LOCATION = /path/to/qhelpgenerator
You’ll find detailed documentation for these options – as well as for all the other options – in the generated configuration file.
Third, we actually need to call Doxygen with this configuration file:
doxygen doxyfile.cfg
Finally, we have to open Qt Creator, select Tools > Options > Help > Documentation and add the generated Qt Compressed Help file there. That’s all.
Creating Links
So, how do we get the links? As a matter of fact, we need to tell Doxygen where it can find information about the Qt classes. This information is stored in so called tag files that Doxygen generates if you specify GENERATE_TAGFILE.
Although Qt Project uses QDoc to generate the documentation, it also generates tag files we can use with Doxygen. They are located in the directory Docs/Qt-5.3 where you have installed Qt. The tag file for each module is then located in the respective subfolder. E.g. the tag file for QtCore is located at Docs/Qt-5.3/qtcore/qtcore.tags. For convenience, we copy all the needed tag files for the modules we reference beside the Doxygen configuration file.
Now, we use TAGFILES to make the tag files usable for Doxygen. The syntax of TAGFILES entries is as follows:
<path to the tag file>=<path>
The path should be prepended to the (relative) link specified by the tag file.
If you like to use the documentation inside Qt Creator and use the local help files of Qt, the prepend path for QtCore looks like this:
qthelp://org.qt-project.qtcore/qtcore/
The URL schema qthelp:// will cause Qt Creator’s help engine to use the local available documentation, org.qt-project.qtcore corresponds to QHP_NAMESPACE, and qtcore to QHP_VIRTUAL_FOLDER. So, TAGFILES for our example looks like this:
TAGFILES = qtcore.tags=qthelp://org.qt-project.qtcore/qtcore/ \ qtgui.tags=qthelp://org.qt-project.qtgui/qtgui/ \ qtxml.tags=qthelp://org.qt-project.qtxml/qtxml/
If we now recreate the documentation and open it, we’ll see that QString, QDomDocument, and
QPixmap::copy() link to the Qt documentation. And even Qt links to the Qt
namespace documentation!
Last, two little hints:
- If you’d like to link to a specific version of Qt documentation, you can define that after the namespace. So qthelp://org.qt-project.qtcore.531/qtcore/ would generate links that point to the QtCore documentation for Qt 5.3.1.
- If you create online documentation, use e.g. qtcore.tags= to create links pointing to the official online documentation of Qt. As for the URL, you do not have to specify the module.
So go on, pimp your docs and happy documenting 🙂
By Lorenz Haas
Thanks for writing this guide. It’s good to know that the tagfiles are still being generated and that people are still using them!
Nicely shared the guide about Documentation Generated with Doxygen. The best part of this post is two little hints.
Appreciable post.
|
https://blog.qt.io/blog/2014/08/13/qt-weekly-17-linking-qt-classes-in-documentation-generated-with-doxygen/
|
CC-MAIN-2018-30
|
refinedweb
| 824
| 56.76
|
'writing your code twice', but at least it doesn't duplicate your code.
This is how it looks like:
static dynamic Sum1(dynamic a, dynamic b) { return a + b; }
The call to the '+'.
PingBack from
You don’t just pay a performance price, you pay a usability price. With the duplicated version, the compiler verifies that the types you are using are correct. With the dynamic version, the compiler can’t verify anything. What happens if two types are used which do not have an addition operator defined? A runtime exception occurs. What happens if this call exists in a code path which allows many different objects to be supplied to the dynamic function? The chances that any amount of testing will find all the potential runtime errors in such a circumstance are slim; whereas the compiler could have found the problem immediately.
The lack of a common interface for numeric types has been a top-rated issue on Connect for 5 years. It is clearly very important to the community, and yet there has still been no solution implemented. Frankly I am baffled by this.
I think that this is something that dynamic wasn’t meant for. In VS 10 we will also have F# and I’d rather use F# for this kind of things to have better performance and type safety. Actually I’d be more than happy to use F#, it’s programming model fits better with computational code.
This seems like playing at the edge of C#. C# was never designed for numeric programming an will probably stay that way for the foreseeable future. Which is a shame, because it’s seeing more use in games, 3d applications and computation intensive applications.
David: agreed with the comment on the need for INumeric. Agreed with the pitfall of run-time errors vs compile time errors. I thought I said it in the post, maybe I should have said it strongly.
Pop.Catalin: F# doesn’t help in this scenario. You still need to write duplicate code.
Of course there are issues with this implementation, but what you have done is take what you have and used a creative idea to get around a problem that has existed in C# for a long time. I say you have done an excellent job!
Very simple answer:
Generics are broken in C# and CLR in general.
That ought to have been fixed before any release.
Two, it just reflects different number systems, and decimal won’t cut it just the same (not to mention the perf penalty).
C# is unusable for numeric programming (without being dog slow and full of hacks), because its model (in general Java VM model) is broken not in usability, but in implementation of memory-abstracted-awayness, its idioms that are very weak, and generics (both in language and runtime). Quite obvious really.. just ask experts that do numeric libraries in C++ for your local government in the past 20 years..
Qwr: can you give me more details on the points you raise?
Apart from the lack of an INumeric interface, I’m not aware of any other big issue with C#/CLR for numeric computing.
Notice that PInvoke and unsafe features in C# helps you in these (hopefully limited) cases when you need direct memory access.
Sure, if you attempt to play with generics, you will see that substitution features are broken. Meta-programming is impossible, policy-based design is hard and bloated etc. Word ‘hack’ is all over IL 🙂
That’s the language designers fault and yet we are at 4.0 and still away from programming the compiler (but C# is looking more like modern C++ by the day, hmm).
The unsafe and managed mix, in terms of memory brings another dimension to the problem which is related to complex data flow and almost guaranteed memory leakage ie. it is impossible to get the deterministic behaviour that is essential for large datasets. Moreoever, everything in CLR 3.0+ is so heavily object-penalised that even before a large dataset appears overhead is already huge and subpar to anything in the industry (WPF or large apps for one).
Not to mention copy-construction hacks.. and so on. Numeric computing in Java and CLR is so far away from hardware reality of today it simply cannot be taken seriously in any HPC environment or other non-hobby work.
And if we are to believe the funny ‘managed’ speak, what on earth is the point of PInvoke or VM sandbox/security approaches anyway.. for numeric computing, games, video, audio, real-time apps, and much more, CLR just doesn’t have an appropriate solution without some sort of unmanaged solution or hack in sight.
This is all due to Java+Delphi influence if you ask me, but we told you so 10 years back when you completed the first beta, yet no one listened. It is surprising to see that even ‘using’ cannot be done twice over an indirection and the language designers keep talking of meta features, compiler extensibility ( CodeDOM Nulls? ) and so on..Seems to me C# is becoming a toy language really.
It just doesn’t tally.. A type system with single-inheritance, no mix in support, object approach, is like placing a void* everywhere in numeric and other disciplines.
Why doesn’t someone stand up and tell that serious computing is not for the guys that will keep pushing language integration and popularity and simplicity against proper engineering?
And of course, generics with value types are so limited it isn’t funny anymore.. how did that get pass any standard (ECMA or internal) is beyond me.
Numeric computing is happening elsewhere and your competition is making better tools in native and symbolic space.. I have to say it, although I would have liked for MS to take it on seriously (and it is a serious discipline and work, not ASP.NET or some such).
Hello Luca,
Very interesting article. I like the idea of an INumeric interface; if nothing else at least it would save me from writing tons of duplicated code.
Now, my two cents (a couple of thoughts I’d like to share with everyone):
In my view, the underlying problem that I think INumeric tries to solve, or at least alleviate (i.e. closing the gap between numbers and ‘numbers as computers understand them’), has much deeper roots. It seems to me that at the dawn of computing science, someone decided than a few millennia of Mathematics were really not that important and that, in the computer’s world they were creating, the following was going to hold true:
1/2 = 0
and yet
1./2 = 0.5
The above is just mathematically absurd and yet it ‘propagated’ everywhere; for 60+ years (and counting) computer scientists have lived happily with this. Now combine it with:
1./0. => "A division by zero error has been caught."
???
So, I can’t divide by zero in the field of real numbers – which makes perfect sense – and yet, magically, I can divide by two in the ring of integers. Simply put, this breaks some of the most basic principles of Mathematics. In this example, I can think of at least three possible options:
1/2 = {1,0} => one cake for two guys and you assume you can’t cut it: one guy gets the cake, the other one gets nothing (I don’t like this idea though).
1/2 = 0.5 => you promote the arguments to the (smallest) set where the operation is defined and return the relevant element from that set (I kind of like this one).
1/2 = "Error! Division by a non-invertible element." => in reality, the exact same stuff that is reported when dividing by zero (I like this one).
What seems totally unjustified to me is to return 0 just because it happens to be the integral part of 0.5.
I’m aware of the fact that the numeric representation of a number in a computer is finite, but I don’t think that’s reason enough for this state of affairs. In my opinion, a higher level of numerical abstraction is needed; one that would serve as a ‘bridge’ between numbers – in the Mathematical sense of the word – and ‘numbers as understood by computers’.
I find it intriguing that every single aspect of hardware and software has evolved at an incredible speed and yet, to a large extent, things like the way we define, store and manipulate numbers in computers seem to have frozen the very day those mechanisms were first defined.
Finally, I do think that this relates to INumeric: on top of more solid foundations one could build up to the point where INumeric is not needed anymore, simply because the concept is already there implemented at a much lower level (but this post is too long already).
Regards,
dfg
These are very good thoughts. Thanks for sharing.
Hi Luca,
Thanks; always glad to contribute in the little I can. Here’s another thought; luckily this one a bit more pragmatic.
What does INumeric look like in your mind at present? Would it allow me to write (in F#) something like this (for simplicity, I’m leaving out left-side operations with an INumeric):
type Complex =
{ Re: INumeric
Im: INumeric }
static member ( + ) (left: Complex, right: INumeric) =
{ Re = left.Re + right; Im = left.Im }
static member ( * ) (left: Complex, right: INumeric) =
{ Re = left.Re * right; Im = left.Im * right }
If this is the idea, then I suppose I’d have two options: either Complex implements INumeric or it doesn’t. If it doesn’t, then I’d need to add to the code above other methods like
static member ( * ) (left: Complex, right: Complex) =
{ Re = left.Re * right.Re – left.Im * right.Im ; Im = left.Re * right.Im + left.Im * right.Re }
On the other hand, if Complex implements INumeric, then I suppose I could write just one method:
static member ( * ) (left: INumeric, right: INumeric) =
with two branches: one for Complex and another one for all other INumeric types.
Having Complex implement INumeric would be a great advantage because then I could create a new type, say, Matrix, taking INumeric as the entries, and complex entries would be automatically considered. But in this case my question is: How would the (+) operation be resolved without some sort of hierarchical approach? For example, suppose that I create a new Matrix type implementing INumeric and I add to that type another
static member ( * ) (left: INumeric, right: INumeric) =
detailing matrix multiplication as well as (element-by-element) matrix-times-scalar multiplication.
Next, I type
let B = A * z;;
where A is a matrix and z is a complex. Which of the two methods would be invoked? Since I’m the one implementing INumeric, how would the framework make it possible for me to guarantee that the Matrix method will be invoked? The problem is that if the Complex method is invoked instead, then that forces me to duplicate code for Complex-Matrix multiplication (note that when I created the Complex type, Matrix did not exist yet).
I suppose it would be very useful to allow some kind of hierarchy (or some other approach to user control) over the call resolution, because then I would not have to duplicate code anywhere (neither for primitive types nor for my own types implementing INumeric).
Best regards,
dfg
PS.- I’m not sure if what I’m suggesting is already possible in similar contexts.
I forgot a couple of things:
– I’m aware that one can avoid problems by carefully using a unique non-static method:
let B = A.Times(z);;
I’m just curious to know how far flexibility and code uniqueness can be taken when using operator overloading instead.
– Is it correct that it is recommended to keep operator overloading in .NET to a minimum?
Thanks in advance,
dfg
Hi dfg,
I’m Melitta, a member of the Base Class Library team, which would own the INumeric feature. I have a couple of answers around what we’ve been thinking. We don’t have all the details and all of this is of course subject to change.
Currently our thinking has been along the lines of an INumeric<T> that simply guaranteed that a type had particular methods. So if you were to implement a generic Complex number as in your example, it would need to specify that both Re and Im were INumeric<T>. INumeric<T> would have methods like Add(left: T, right: T) that would return type T. Then you could perform the operations on the elements themselves, using the standard formulas for complex arithmetic. You would end up with a static member ( + ) (left: Complex, right: Complex) = {Re = left.Re + right.Re; Im = left.Im + right.Im} instead of static member ( + ) (left: Complex, right: INumeric). And then you could have your Complex structure itself implement INumeric<Complex>, and it could be used in larger structures like Matrices.
We haven’t been thinking of INumeric as a way to automatically interact with any possible numeric type. You still have to specify the T. This means that you still have to determine which other types your type will interact with and cast to implicitly or explicitly. In your Matrix example, if Matrix implemented INumeric, the multiplication function (it could only be an operator if interfaces allowed static methods, or if the compilers knew to compile the operator down to a particular instance method) would only multiply two matrices of the same type. So if you wanted to multiply a matrix by a complex scalar, you’d have to implement that specifically (and not call it through the interface, unless you found a way to treat complex scalars as matrices). However, INumeric may help simplify the task of multiplying a Matrix<T> by a scalar of type T.
As for your question about operator overloading recommendations, you may want to check out our Framework Design Guidelines on the topic:.
Thanks,
Melitta
Base Class Libraries
Hi Melitta,
Thanks a lot for taking the time to describe the INumeric<T> plan. With regards to static methods in interfaces, I found this:
Thought you might find it interesting.
Thanks and regards,
dfg
I’d like the ability to declare my own interface and then declare that other classes that I don’t control implement my interface, provided of course that those classes actually do have the appropriate methods/properties.
If I could do that, then in this situation I could possibly define my own INumeric<T> interface and declare that various primitive types do implement my interface.
I think extension methods introduced in 3.0 was kind of a step in this direction.
In general that would allow the consumers to identify similarities between distinct components and pull them together without having to wait for the owners of those components to enhance the library with common interfaces in a future version.
Think about the common interfaces in the System.Data namespace in .Net 2.0. We had to wait for it to become part of the standard framework in 2.0, even though we could already see the similarities in .Net 1.1 between the components in the OdbcClient namespace classes and the components in the SqlClient namespace.
Note that you can get a lot of this functionality *today* without using "dynamic". One approach is to use Expression as a micro-compiler to do the duck-typing, and cache the delegate away. This is precicely what the generic operator support in MiscUtil does.
See here for the overview:”>
or here for the actual code:
Just a comment on performance:
I implemented the BLAS function daxpy in different languages. And see what performance I got on my workstation (Intel Q9550 CPU, everything’s running single threaded in 32bit). n = 1000000 and performance is averaged over 1000 runs. Each addition and each multiplication is considered one FLOP. If you want to reproduce the results, make sure you start the programs without attaching a debugger.
————————————
Visual C++: 398.96 MFlops/s
void daxpy(int n, double a, double* xp, double* yp, double* rp)
{
for (int i = 0; i < n; i++)
{
rp[i] = a * xp[i] + yp[i];
}
}
————————————
Intel Fortran: 557.41 MFlops/s
subroutine daxpy(n,a,r,x,y)
integer (kind=4) :: n
real (kind=8) :: a
real (kind=8), dimension(n) :: r,x,y
integer (kind=4) :: i
do i=1,n
r(i) = a * x(i) + y(i)
end do
end subroutine daxpy
————————————
C# (Microsoft CLR): 399.43 MFlops/s
private static void Daxpy(int n, double a, double[] x, double[] y, double[] r)
{
for (int i = 0; i < x.Length; i++)
{
r[i] = a * x[i] + y[i];
}
}
————————————
The JIT compiler team did a great job. Only Intel Fortran outruns the CLR code. The nice thing about c# is that boundaries checks come for free. However, the major drawback is that CLR arrays can’t be larger
than 2GB.
Thomas,
>Only Intel Fortran outruns the CLR code
Did you use autovectorization with the Intel compiler?
This one place where the the CLR really lacks. MS should implement something like Mono.SIMD and Intel’s autovectorization for C#/F#.
In my view Adam’s comment above is in the right direction and very much what I’ve had in mind for a while now. I wouldn’t go as far as to always force the use of an interface for that though. I think the architecture would benefit from the equivalent to the mathematical concept of "category":
Or, in Adam’s words:
"allow the consumers to identify similarities between distinct components and pull them together"
Roughly speaking, the same underlying idea.
In some aspects, these "categories" could be seen as a light-weight version of the concept of interface.
But I suppose coming up with a concept is one thing and implementing it in the architecture is another thing. There I can’t help much, but I’ll elaborate a bit more on the idea in a later post.
What is really needed is something like a structural type constraint. See this feedback item for how this would work
But I must confess that after five years I have given up on C#. The language is just getting more and more bloated while still missing essential features.
I am trying to convince my boss to write the next big project in java with the more numerically complex parts written in scala.
@Rudiger
You’re giving up on C# and switching to JAVA? Talk about taking a step backwards…
Rüdiger:
"structural type constraint"?
Do you mean as in "using generics but combined with some stuff that makes generics not be so generic?"
I guess my question is: If generics have to come with some stuff to not make them so, say, "generic", then what’s the point in using generics in the first place?
I mean, what’s next, people using generics to
represent 2 + 2 = 4 using generics just for the sake of using generics?
Re: David Nelson
At least with java you know that they won’t add a dozen superficial language "features" for each release. C# has become much too complex and non-orthogonal.
But the language I am planning to use for the more complex algorithms is scala
The common base classes and interfaces will be written in java since that is the lowest common denominator for the java platform.
Re: dfg
A structural type constraint is not less generic than an interface constraint. It is just a different approach to generics.
@Rudiger
To each his own. Yes C# is continuing to evolve, and yes there is a lot to keep up with, but personally I am glad to be using a language and a platform that is still trying to keep up with the needs of modern developers, rather than one which has resigned itself to living in the past.
Rüdiger Klaehn, I will not say that Java has any advantages over .net than being multi-plataform, but I really liked your proposal for strutural constraints.
I, for example, always liked the C++ template because I could create a template for any class with a GetName() method.
I really liked your solution. I expect the .net team can use some structural solution like yours for generics.
But, for Luca, I liked Luca post also. Luca intended to show how dynamic could be used, and this has been done successfully.
I will really like to see numbers of performance comparison using dynamic and real primitive types.
Re: David Nelson
The language I am going to use is not java but scala. We are just using java for the common interfaces to ensure interoperability.
I have nothing against adding features to a language, but the features should be general purpose features and not just special syntax to address a special use case.
For example, instead of providing special syntax for nullable types, they should have made generics more flexible so that adding special operators for nullable types could be done in a library.
And don’t get me started about the new collection initializer syntax. It uses structural typing (a class that implements IEnumerable and has an add method is assumed to be a collection), but it does not provide a generic mechanism for those of us that would like to use structural typing for their own purposes.
Re: Paulo Zemek
I would love to do some benchmarks. But is there a version of the .net 4.0 framework available that is not obsolete and does not require virtual pc? I did not find one.
Hello everyone,
First of all I would like to thank Anders Hejlsberg for existing, on behalf of the people who think, who design solutions and project them into reality and also thank Eric, Luca, Charlie, and everyone in the Visual Studio, .NET, C#… teams.
I don’t actually understand the term "programmer" but, I have been programming since the 4th grade (started with BASIC on a Z80 computer, continued with Pascal, C++, moved to Visual Basic, Visual C++, Delphi, Assembler, (the order is just temporal, there is no actual logic in it), Delphi for .NET, Java, Prolog, C#, F#, Javascript, Python, Ruby ).
At first I lacked a stack (there was only a GOSUB routine which had a 1-length "stack"). Then I lacked memory, loading (of binary modules at runtime). Then I lacked a Garbage Collector. I’m not saying that the things I was looking for weren’t out there, somewhere, but they surely weren’t in the possibilities offered by that particular language. It is maybe the first time in my life when I am waiting for the next release of a framework, knowing what will be in it and everything I want to use as a language is not yet made.
I’m not trying to say what is good or bad, in general. There are many paradoxes in the human – computer communication that we call programming (it is good to have GC / it is better if I’m allowed to destroy things as I please).
The reason I dared to be so idiosyncratic when writing this comment is that others also dared. I don’t really want to read these blogs to know what people choose for a language, what projects they are working on. I’m not sure what the purpose of these blogs are but it is my believing that it has nothing to do with the peculiar tastes of the readers.
I’m only writing this because a disturbance was made (in the Force :)) and I believe all things reside in symmetry.
In my opinion, the power of C# stands not in the power to compute large sets of numbers (I would probably use PLINQ somehow to ask a number of processors to do a lot of work, or will make a different executable process and connect to it through I/O, or a different module and load it through "PInvoke Loading"), but rather in the elegance and simplicity of thread-flow and heap-state description. Please don’t be fooled by my passion and think that I cannot synchronize threads in C using POSIX, or don’t know how to throw an exception from a Java method that states it does not "throws" any.
I think it’s all about the maintenance of your ideeas while coding. I’m sorry to here that things like type inference cause a rash to some who appreciate multi inheritence in contrast. I don’t think there’s any doubt that reflection is a good thing (I mean in general, in humans, in poetry). Well Type is a great class (check it out if you haven’t, I mean really check it out, see when instances are created and what happens with all the threads).
And for Java lovers who think generics are better in Java because of straight-forwardness I have two small tests:
1. Try to infer on the generic type at runtime.
2. Try to declare a generic type particularization in process A, use I/O to serialize and send it to process B and deserialize it there (and of course, don’t mention the generic type particularization syntactically in program B). I wonder what will happen.
Please forgive me if I am wrong, but I suspect that those who said that C# is evolving too fast never got to understand it as a whole. The evolution of C# is normal and it is hard to accomplish. The reason Java is not evolving (from within the core) is because it cannot, not because they don’t want it to.
They have made a series of bad choices and are now stuck (they could either evolve and loose compatibility with tons of software already made and tons of knowledge that is within programmers’ heads).
You can only go as so far with the evolution as you can. And it is the "childhood sins" that keep you from going any further.
C# is wonderful for me. In my case it is the best compromise between speed, expressivity, maintainability. Please don’t be fooled and think that I appreciate the libraries that are pre-written so dearly. I do. But I appreciate the language and the framework the most.
It approaches the power of Javascript and Python from a strongly-type, highly aware of what IS, perspective.
I don’t think the problem of programming should be so highly bound to the engineering issues (the processor, memory, etc). I’m saying this and I am a computer engineer.
It should, in my opinion, be agnostic (in the sense that the compiler, the runtime and maybe part of the libraries, are taking care of those things). Isomorphisms don’t always add value.
Thank you for reading this chunk of personal beliefs. I am looking forward to the comming of C# 4.0 (already got the CTP machine :)).
Have a nice day everyone,
Eduard Dumitru
Please excuse my looon comment,
and my english spelling.
I found interesting that we have a similar situation Java <-> Scala, with (VB/C#) <-> F#.
RE: dfg
I am a little late to the party here, but to the point made by dfg about "violating the laws of mathematics", I think I can see a fourth option that could be useful.
For 80×86 CPUs, I believe the division instruction puts the result of the division in one register and the remainder in another. The problem with integer division in high-level languages is that we are only returned the result, and the remainder is lost. If I am not mistaken, the modulo operator is exactly the inverse case, we are given the remainder, not the result, even though at the hardware level, a division operation was still executed.
I think it would be possible to capture the remainder value and save it as a property of the integer variable (at least in a managed language). I am not sure how this is impacted by integers being value types in .Net.
|
https://blogs.msdn.microsoft.com/lucabol/2009/02/05/simulating-inumeric-with-dynamic-in-c-4-0/
|
CC-MAIN-2017-47
|
refinedweb
| 4,688
| 61.46
|
23 August 2010 15:45 [Source: ICIS news]
MOSCOW (ICIS)--Sibur plans to build new gas processing capacities and restructure its Sibur-Neftekhim subsidiary, the Russian petrochemical holding company said on Monday.
Sibur plans to build a new 2.8m tonne/year gas processing facility that will be operated by its Tobolsk-Neftekhim subsidiary at ?xml:namespace>
Sibur will also increase the capacity of Tobolsk-Neftekhim’s existing 3m tonne/year gas processing unit to 3.8m tonnes/year, it said.
Tobolsk-Neftekhim’s total gas processing capacity would be 6.6m tonnes/year, the statement said.
The new gas processing capacities would supply a new 500,000 tonne/year polypropylene (PP) facility to be built at the premises of Tobolsk-Neftekhim by 2012.
Sibur also said on Monday that it would restructure its Sibur-Neftekhim subsidiary.
Based in Dzerzhinsk, in the Nizhny-Novgorod region of central
But the Kstovo Petrochemical Plant, located at Kstovo, would be controlled by a new entity, Sibur-Kstovo, it said.
The restructure will give the businesses greater operational autonomy, Sibur said.
On 12 July, Sibur started construction of a new €750m ($949m) polyvinyl chloride (PVC) plant at Kstovo, which will have a capacity of 330,000 tonnes/year and is due to come on line by 2012.
($1 = €0.79)
|
http://www.icis.com/Articles/2010/08/23/9387510/sibur-to-raise-gas-processing-capacities-restructure-subsidiary.html
|
CC-MAIN-2014-41
|
refinedweb
| 216
| 55.34
|
Figure 1. The SimpleErrors sample application for this article.
In your previous project, you may have called Win32 or COM functions. This article won't discuss the particulars of calling such functions, but instead my purpose is to reveal a really simple way to handle errors from these functions. Mostly the functions themselves only return a hard-to-parse HRESULT (from COM) or an invalid HANDLE value (such as INVALID_HANDLE_VALUE or some other such value). But it's not easy to get the error that actually occurred, so that one can just display the message to the user.
HRESULT
HANDLE
INVALID_HANDLE_VALUE
Other articles on the Code Project, such as Ajit Jadhav's article, "Do Not Call GetLastError()!", and others, advocate a simple, object-oriented approach to handling this ugly situation. It turns out there's an even simpler approach, and one that will look up the error value, and parse it, and display the corresponding string (if found) in a message box, and all in one line. It has to do with compiler COM support, which - as it turns out - you can use even if you're not using COM anywhere in your application.
Several posters to this article (below) have made very insightful comments and I welcome any and all feedback on this approach. Some (not meant to be inclusive) to using this approach, and _com_error in particular, are listed in the message board posts below.
_com_error
This article is not advocating this approach to the exclusion of all others, nor is it saying there aren't other approaches which are better. But I am just putting this out here, especially for some of you who aren't in the mood to write big switch/case or if/else blocks every time you call a Win32 function, but instead want to do some more advanced handling.
switch
case
if
else
Basically, the message is: Here's another feature of VC++ that may be helpful to you; but in the end, the important thing is to do what makes the most sense for your particular application.
The details of compiler COM support and the classes it provides are beyond the scope of this article. Needless to say, there's a class, called _com_error, which you can use in lieu of some other ungodly approach, say, by using FormatMessage(). Jadhav tried to work around this by providing a CWin32Error class, which was even throwable as an exception object, which supposedly does what, in fact, the compiler's COM support already gives you!
FormatMessage()
CWin32Error
I will leave looking up _com_error in the docs to you, but needless to say this class has, among its constructors, a constructor that accepts either: a HRESULT or the output of the Win32 function, GetLastError(). Then, you can call the member function, _com_error::ErrorMessage() and get the corresponding system error message, quite naturally. Plus, the _com_error class is itself an exception class, and works with the compiler's built-in exception handling syntax. You can throw, catch etc. blocks using _com_error to your heart's content. Unfortunately, exception handling is not really my bag, so this article looks at only how to use the _com_error::ErrorMessage() member function.
GetLastError()
_com_error::ErrorMessage()
It's clear from the message board posts in Jadhav's article that people are aware of this, but it is in fact quite simple to use, and it works in a proven manner, as the included demo project and source code illustrate. Let me take you on a tour of the particulars of using the _com_error class with ease. Another upside of using _com_error natively is that the system error messages are automatically localized so that they appear in the language that the computer's locale is using.
The short answer: No. Not if the class doesn't depend on such, and thankfully, _com_error doesn't.
To illustrate how to use the _com_error class in your application, I used the MFC AppWizard to whip up a little, dialog-based sample program called SimpleErrors. As an example, Listing 1 shows the one single line of code to throw up a message box based on a Windows Win32 SDK system error, as returned by GetLastError():
AfxMessageBox(_com_error(GetLastError()).ErrorMessage(),MB_ICONSTOP);
Listing 1: Alerting the user to a Win32 error with a message box.
Listing 2: Shows the single line of code to use to get an error message from a FAILED HRESULT.
FAILED HRESULT
AfxMessageBox(_com_error(hResult).ErrorMessage(),MB_ICONSTOP);
Listing 2: Alerting the user to a COM error with a message box.
All of this comes "for free" just with Visual C++! Here are the steps.
To start, we need to make sure the proper include files are added to STDAFX.H. If you're not coding an MFC application, then add the line below to whatever file is #included in all your source files. Anyway, the line to add is shown, below, in Listing 3:
#include
#include <comdef.h> // Compiler COM support
Listing 3: Including the correct header file for compiler COM support and _com_error.
In the SimpleErrors sample application, I have added two buttons: one button that makes a bogus Win32 CreateFile() call; and another button to make a bogus CoCreateInstance() call on a non-existent interface (the self-deferential interface, IAmDumb). Let's go on a tour of the message handlers for each button. Listing 4 shows how I set up the bogus Win32 call:
CreateFile()
CoCreateInstance()
IAmDumb
void CSimpleErrorsDlg::OnBnClickedCallFunction()
{
// Do something bogus here, like try to open a file
// which doesn't exist.
if (CreateFile(_T("./testing.TXT"),
0L,FILE_SHARE_READ,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,NULL)==INVALID_HANDLE_VALUE) {
AfxMessageBox(
_com_error(GetLastError()).ErrorMessage(),MB_ICONSTOP);
}
}
Listing 4: Using _com_error::ErrorMessage() to handle a file-opening error.
My approach above was simply to call CreateFile() to open the non-existing file testing.TXT. Notice how the error handling is done all in one line. The line beginning with a call to AfxMessageBox() displays the following message box - shown below in Figure 2 - when the Call Win32 Function And Get Error button, in Figure 1, is clicked:
AfxMessageBox()
Figure 2: The call to _com_error::ErrorMessage(), in Listing 4, produced this message box.
When calling a COM function, things work out similarly. Now, with COM, we're calling CoCreateInstance(). For more info on what COM is and how to use COM in your programs, I'll simply refer you to Michael Dunn's excellent introduction on this subject.
Anyway - all the introductions aside - here's how to handle the failure of a COM function. Now, with Win32, we can simply pass the function a filename of a non-existent file, and there we are. But here, we are making up a bogus interface, and interfaces have tags, or GUIDS (Globally Unique IDs) which tell COM which interface you want. The ones we pass to CoCreateInstance() here are the so-called CLSIDs and IIDs. Never mind what these are; again, beyond the scope of this article. My first step, to prepare for calling CoCreateInstance(), is to use the Create GUID tool which comes with Visual C++ to create two GUIDs, one for the CLSID and one for the IID of my fake interface. Here are the ones I generated, shown in Listing 5:
// {9346460E-F860-450c-B8C6-80D705644FF0}
static const GUID CLSID_IAmDumb =
{ 0x9346460e, 0xf860, 0x450c, { 0xb8, 0xc6, 0x80,
0xd7, 0x5, 0x64, 0x4f, 0xf0 } };
// {5E0E7ED9-83FF-4c31-AD12-46021DE03884}
static const GUID IID_IAmDumb =
{ 0x5e0e7ed9, 0x83ff, 0x4c31, { 0xad, 0x12, 0x46,
0x2, 0x1d, 0xe0, 0x38, 0x84 } };
Listing 5: GUIDs I created for the fake, bogus, IAmDumb interface.
If you like, you can just copy the GUIDs from Listng 5 above to your project if you're following along. The best place to put these GUID declarations is in the same source file that I am going to call CoCreateInstance() in.
Note: This is not the way, ordinarily, to go about accessing COM interfaces! See Dunn's article (or the others) above for more details.
Just a reminder to our purpose. Remember, we want to see how to easily trap errors, especially from HRESULTs. So I made up a fake interface, the IAmDumb interface, and then I am going to call CoCreateInstance() on this fake, not-registered interface so that I will get an error to display. See Listing 6, below, for how I do this:
void CSimpleErrorsDlg::OnBnClickedCallCom()
{
// Call a random COM function,
// say, CoCreateInstance(), with
// bogus parameters so that it
// gives us a FAILURE HRESULT
IUnknown* pUnk=NULL;
// Always must be called before
// using COM functions
CoInitialize(NULL);
HRESULT hResult = CoCreateInstance(CLSID_IAmDumb,NULL,
CLSCTX_LOCAL_SERVER,IID_IAmDumb,(void**)&pUnk);
if (FAILED(hResult)) {
AfxMessageBox(_com_error(hResult).ErrorMessage(),MB_ICONSTOP);
}
CoUninitialize(); // Call so Windows can clean up
}
Listing 6. Calling CoCreateInstance() to try and get a fake interface, and handling the resultant error.
Again, I am not here to explain COM to you. Consult the Dunn, above, if you need help with what I am doing. Notice the use of the FAILED() macro. This can be used on any HRESULT value, and is - in general - a good way to determine if your COM call wasn't successful. Look up FAILED in the docs if you want more information. The AfxMessageBox() call above produces the box shown in Figure 3, below:
FAILED()
FAILED
Figure 3: The result of calling CoCreateInstance() on our fake interface, IAmDumb.
To follow along with me and see this for yourself in the sample application, click the Call COM Function And Get Error button. Again, since the error messages that _com_error::ErrorMessage() provides for you are automatically localized, whatever this message translates to in your locale's language will instead appear (I think).
It's worth discussing this particular approach to error-handling, and in particular cases in which it's not a good idea. Above all, you should use whatever approach you think is best for your particular application. A poster to the message board, Doug Scmidt, and to this article, cautions against the temptations to do things in one line. And it's true that there may be application types for which this approach is unsuitable. For more information, see Schmidt's post, below.
As yet another reader mentions that the system error messages provided by _com_error are terse, and rightly so. It's ironic that Microsoft, known for such books as The Windows User Interface Guidelines for Software Design - which sternly lectures readers to make error messages helpful and to not blame the user - would then put into its Windows system error message database these incredibly terse errors.
A possible way to overcome the terseness aspect is to add extra text to the error message; i.e. perhaps invent a GetErrorMessage() function that would format the message in a way that is a little more helpful to the user. I am not going to presume to know how the said function should be implemented, as the implementation for your application's purposes may vary. However, an error message containing the name of the file or interface (or whatever) was being operated on, plus the system error message and a way for the user to resolve the problem might be nice.
GetErrorMessage()
Something that is also worth discussing is that: in the Jadhav's article, some message board posters claimed that _com_error::_com_error() needs a HRESULT always, hence you have to pass the output of GetLastError() to it thusly:
_com_error::_com_error()
AfxMessageBox(
_com_error(HRESULT_FROM_WIN32(GetLastError())).ErrorMessage(),
MB_ICONSTOP);
Listing 7: Using the HRESULT_FROM_WIN32 macro on all outputs of GetLastError().
HRESULT_FROM_WIN32
For me personally, even as far back as VC5, this has never been my experience, and _com_error::ErrorMessage() appears to work regardless of whether you use the HRESULT_FROM_WIN32 macro or not.
I could go on and on discussing the shortfalls of this approach, but that is not what I am here to do. Instead, I would be delighted if readers could please use this article's message board, below, to share their thoughts - and tips - for navigating through the waters of Win32 and COM error reporting. Readers are also encouraged to address their posts not to me, but instead to the general readership of this article. Let the message board below be a 'forum' for discussion on this subject.
So there you have it. We looked at how to use a 'built-in' class, the _com_error class, which is provided along with the VC++ compiler, to generate human-readable errors from COM and Win32 calls.
Happy Error Handling (and Happy New Year 2006 - I am writing this on New Year's eve, 2005!)!
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Sam NG wrote:"Error initialize the program" seem good enough for general users but it won't help in finding the reason why the program won't start....
_com_error.ErrorMessage()
ARB70 wrote:So unlike some other posters I won't be changing all my code to use a one liner approach but will continue using support classes and other code to provide more meaningful error messages. Maybe this is not such a problem if all of your users are "propellor heads".
_bstr_t
if( !::SomeWin32API( ... ) )<br />
{<br />
// Get the cached error<br />
DWORD nError = ::GetLastError();<br />
<br />
// Now handle the error<br />
MySpecialErrorHandler( nError );<br />
}
if( !::SomeWin32API( ... ) )<br />
{<br />
MySpecialErrorHandler( ::GetLastError() );<br />
}
Doug Schmidt wrote:The above article is good, but readers should be cautioned not to embed a call to GetLastError() as an argument to another function. Resist the temptation to do everything in one line.
The only 100% reliable way of calling GetLastError() is on a line by itself, immediately after the WIN32 API call.
W. Kleinschmit wrote:Sorry, but this is wrong. By definition every negative HRESULT is an error. So the FAILED(...) macro only tests for bit 31 of the HRESULT set.
There are other possible return values (S_FALSE for example), that are sometimes used to indicate special situations but are not considered an error.
FAILED(S_FALSE) returns FALSE.
SUCCEEDED
Rob Manderson wrote:
Bloody brilliant!
And exactly what I needed for a COM object I'm writing. You got my 5.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
https://www.codeproject.com/Articles/12573/Lookup-and-Display-Win32-COM-Error-Strings-With-On?PageFlow=FixedWidth
|
CC-MAIN-2017-39
|
refinedweb
| 2,400
| 60.04
|
TypeNBTTypeNBT
TypeNBT is a idiomatic, type safe NBT library for Scala. TypeNBT allows you to focus on the data in the code, not the NBT as most other libraries requires.
Add TypeNBT to your project by including this line in build.sbt
libraryDependencies += "net.katsstuff" %% "typenbt" % "0.5.1" //Or this if you use Scala.js libraryDependencies += "net.katsstuff" %%% "typenbt" % "0.5.1"
Why TypeNBT?Why TypeNBT?
Why did I decide to write TypeNBT and not just use something that already existed.
- You can find TypeNBT on maven
- Everything in TypeNBT is immutable, this includes the collections
- TypeNBT is type safe. There are no surprises when running the code and getting an exception back because you expected the wrong data type. Even the list is type safe
- It includes the type information at runtime. How do serialize an empty list in other libraries, you can't really, but here you can do that
- Convert anything to NBT. TypeNBT defines typeclasses for encoding and decoding a value to NBT. This aspect of the library isn't hidden away either. Instead it's a core part of how it works
- Create a NBTCompound easily. TypeNBT easily allows you to create your entire NBTCompound in a single line using a HList like this
NBTCompound.fromHList("first" -> "hi" :: "second" -> 5 :: "third" -> false :: HNil). NOTE: Requires the use of the
typenbt-extramodule
- Easy conversion to and from common types not represented by raw NBT. Notice the boolean in the above line
- Full support for Mojangson parsing. NOTE: Requires the
typenbt-mojangsonmodule.
- TypeNBT works for Scala.js
Using TypeNBTUsing TypeNBT
Here is some information about how to use TypeNBT in practice. For all of these, make sure you import
net.katsstuff.typenbt._.
Creating NBTTag, and the typeclasses that TypeNBT usesCreating NBTTag, and the typeclasses that TypeNBT uses
Converting a value to nbt can be done like this:
import net.katsstuff.typenbt._ 5.nbt //Int, return NBTInt "hi".nbt //String, returns NBTString false.nbt //Boolean, returns NBTByte IndexedSeq(2, 5).nbt //IndexedSeq[Int], returns NBTIntArray NBTInt(1) //You can also create the NBTTag more explicitly
NBTSerializerNBTSerializer
This uses the typeclass
NBTSerializer[Repr, NBT] which takes to types, the type to convert from, and the type to convert to. This is analogous to the type
Repr => NBT.
NBTDeserializerNBTDeserializer
There is also
NBTDeserializer[Repr, NBT] which goes the other way around, except that it returns an
Option as the data might not be valid for a given type. This is analogous to the type
NBT => Option[Repr].
SafeNBTDeserializerSafeNBTDeserializer
For cases where a value can always be safely converted from an nbt value, there exists
SafeNBTDeserializer. This is analogous to the type
NBT => Repr.
NBTViewNBTView
Next there is
NBTView which combines
NBTSerializer and
NBTDeserializer.
SafeNBTViewSafeNBTView
There is also
SafeNBTView which uses
SafeNBTDeserializer instead of
NBTDeserializer.
CaseLikeCaseLike
Then there is
NBTViewCaseLike and
SafeNBTViewCaseLike. Which adds apply and unapply methods to the view to make certain types behave like they are normal nbt types. For example, you can do
NBTBoolean(false) which will then convert the boolean to an nbt byte.
NBTTypeNBTType
Lastly there is
NBTType which corresponds to the base nbt types. This also contains the byte id for the type.
On multiple type parameter listsOn multiple type parameter lists
For some methods like
NBTCompount#getValue, TypeNBT uses multiple parameter lists in the form of anonymous classes. Unless you really want to, you generally only have to fill in one of them.
typenbt-extratypenbt-extra
If you want more fanciness, then there is also the module
typenbt-extra, which contains some more operations which uses shapeless under the hood.
First add the dependency to your build.
libraryDependencies += "net.katsstuff" %% "typenbt-extra" % "0.5.1" //Or this if you use Scala.js libraryDependencies += "net.katsstuff" %%% "typenbt-extra" % "0.5.1"
Now you can convert a
HList into a
NBTCompound or add a
HList to an existing
NBTCompound. First make sure you have your HList. The HList must consist of tuples from string to values that an NBTSerializer exists for. Then import
net.katsstuff.typenbt.extra._ and call
NBTCompound.fromHList(hList) or do
compound ++ hList. TypeNBT takes care of the rest.
typenbt-mojangsontypenbt-mojangson
TypeNBT also has another module for both parsing and creating mojangson.
libraryDependencies += "net.katsstuff" %% "typenbt-mojangson" % "0.5.1" //Or this if you use Scala.js libraryDependencies += "net.katsstuff" %%% "typenbt-mojangson" % "0.5.1"
You can then use
Mojangson.toMojangson and
Mojangson.fromMojangson
ExamplesExamples
There exists more examples on how to use TypeNBT in the examples directory.
|
https://index.scala-lang.org/katrix/typenbt/typenbt/0.2?target=_sjs0.6_2.11
|
CC-MAIN-2020-34
|
refinedweb
| 751
| 60.82
|
Part).
This topic describes development for Windows 8.1. For an introductory tutorial for Windows 10 development in C++, seeCreate a "hello world" app in C++ (Windows 10). You can retarget apps written for Windows 8.1 and Windows Phone 8.1 to Windows 10.
For tutorials in other programming languages, see:
Create your first Windows Store app using JavaScript
Create your first Windows Store app using C# or Visual Basic
Before you start...
- To complete this tutorial, you must use Microsoft Visual Studio Express 2013 for Windows with Update 2 or later, or one of the non-Express versions of Visual Studio 2013 with Update 2 or later, on a computer that's running Windows 8.1 or Windows 10. To download, see Get the tools. In the Visual Studio edition you're using, make sure you select the Visual C++ development settings.
- You also must have a developer license. For instructions, see Get a developer license.
- We assume you have a basic understanding of standard C++, XAML, and the concepts in the XAML overview.
- We assume you're using the default window layout in Visual Studio. To reset to the default layout, on the menu bar, choose Window > Reset Window Layout.
- You can view the complete code for this tutorial in the Hello World (C++) sample on Code Gallery.
The Visual C++ compiler in Microsoft Visual Studio 2015 does not support developing Windows Runtime apps that target Windows 8 or Windows 8.1. To target these platforms, make sure that Visual Studio 2013 Update 2 or later is installed on the computer, and then, in your Visual Studio 2015 project, open your Windows 8 or Windows 8.1 project, choose Project > Properties from the main menu, and in the General section, set the Platform Toolset property to Visual Studio 2013 (v120).
Comparing C++ desktop apps to Windows apps
If you're coming from a background in Windows desktop programming in C++, you'll probably find that some aspects of Windows Store app and Windows Phone app programming are familiar, but other aspects require some learning.
What's the same?
You can use the STL, the CRT (with some exceptions), and any other C++ library as long as the code does not attempt to call Windows functions that are not accessible from the Windows Runtime environment.
If you're accustomed to visual designers, you can still use the designer built into Microsoft Visual Studio, or you can use the more full-featured Blend for Microsoft Visual Studio 2013. If you're accustomed. Windows Store apps in C++ don't execute in a managed runtime environment.
What's new?
The design principles for Windows Store apps are very different from those for desktop apps. Window borders, labels, dialog boxes, and so on, are de-emphasized. Content is foremost. Great Windows Store apps incorporate these principles from the very beginning of the planning stage.
You're using XAML to define the entire UI. The separation between UI and core program logic is much clearer in a Windows Store on Windows devices Win32 is still available for some functionality.
You use C++/CX to consume and create Windows Runtime objects. C++/CX enables C++ exception handling, delegates, events, and automatic reference counting of dynamically created objects. When you use C++/CX, the details of the underlying COM and Windows architecture are hidden from your app code. For more information, see C++/CX Language Reference.
Your app is compiled into a package that also contains metadata about the types that your app contains, the resources that it uses, and the capabilities that it requires (file access, internet access, camera access, and so forth).
In the Windows Store and Windows Phone Store your app is verified as safe by a certification process and made discoverable to millions of potential customers.
Hello World Store app in C++
Our first app is a "Hello World" that demonstrates some basic features of interactivity, layout, and styles. We'll create both a Windows Store 8.1 app and a Windows Phone 8.1 app from one universal app solution that contains a project for each version and a third project for the code they share.
We'll start with the basics:
How to create a universal app solution in Visual Studio Express 2013 for Windows with Update 2 or later.
How to understand the projects and files that are created.
How to understand the extensions in Visual C++ component extensions (C++/CX), and when to use them.
First, create a solution in Visual Studio
In Visual Studio, on the menu bar, choose File > New > Project.
In the New Project dialog box, in the left pane, expand Installed > Visual C++ > Store Apps > Universal Apps.
In the center pane, select Blank App (Universal Apps).
Enter a name for the project. We'll name it HelloWorld.
Choose the OK button. Your project files are created.
Before we go on, let’s look at what's in the solution. First, notice that there's a Windows 8.1 project, a Windows Phone 8.1 project, and a shared project. The shared project doesn't produce any binary output; it contains code that both of the other projects use. Each platform-specific project contains the code that's specific to its UI.
Now, expand those nodes, select the Windows 8.1 project node and click the Show All Files icon. Do the same for the Windows Phone 8.1 project. Something like this should appear, depending on what you named your project:
About the project files
Every .xaml file in a project folder has a corresponding .xaml.h file and .xaml.cpp file in the same folder and a .g file and a .g.hpp file in the Generated Files folder. You modify the XAML files to create UI elements and connect them to data sources (DataBinding). You modify the .h and .cpp files to add custom logic for event handlers. The auto-generated files represent the transformation of the XAML markup into C++. Don't modify these files, but study them to better understand how the code-behind works. Basically, the generated file contains a partial class definition for a XAML root element; this class is the same class that you modify in the *.xaml.h and .cpp files. The generated files declare the XAML UI child elements as class members so that you can reference them in the code you write. At build time, the generated code and your code are merged into a complete class definition and then compiled.
Let's look first at the project files.
- App.xaml, App.xaml.h, App.xaml.cpp: Represent the Application object, which is an app's entry point. App.xaml contains no page-specific UI markup, but you can add UI styles and other elements that you want to be accessible from any page. The code-behind files contain handlers for the OnLaunched and OnSuspending events. Typically, you add custom code here to initialize your app when it starts and perform cleanup when it's suspended or terminated.
- MainPage.xaml, MainPage.xaml.h, MainPage.xaml.cpp:Contain the XAML markup and code-behind for the default "start" page in an app. It has no navigation support or built-in controls.
- pch.h, pch.cpp: A precompiled header file and the file that includes it in your project. In pch.h, you can include any headers that do not change often and are included in other files in the solution.
- package.appxmanifest: An XML file that describes the device capabilities that your app requires, and the app version info and other metadata. To open this file in the Manifest Designer, just double-click it.
- HelloWorld.Windows_TemporaryKey.pfx:A key that enables deployment of the app on this machine, from Visual Studio.
A first look at the code
If you examine the code in App.xaml.h, App.xaml.cpp in the shared project, and MainPage.xaml.h and .cpp in each of the platform-specific projects, you'll notice that it's mostly ISO C++ code that looks familiar. However, some syntax elements might not be familiar. Here are the most common non-standard syntax elements you'll see in C++/CX:
Ref classes
Almost all Windows Runtime classes, which includes all the types in the Windows API--XAML controls, the pages in your app, the App class itself, all device and network objects, all container types--are declared as a ref class. (A few Windows types are value class or value struct). A ref class is consumable from any language. In C++, the lifetime of these types is governed by automatic reference counting (not garbage collection) so that you never explicitly delete these objects. You can create your own ref classes as well.
All Windows Runtime types must be declared within a namespace and unlike in ISO C++ the types themselves have an accessibility modifier. The public modifier makes the class visible to Windows Runtime components outside the namespace. The sealed keyword means the class cannot serve as a base class. Almost all ref classes are sealed; class inheritance is not broadly supported because Javascript does not understand it.
ref new and ^ (hats)
You declare a variable of a ref class by using the ^ (hat) operator, and you instantiate the object with the ref new keyword. Thereafter you access the object's instance methods with the -> operator just like a C++ pointer. Static methods are accessed with the :: operator just as in ISO C++.
In the following code, we use the fully qualified name to instantiate an object, and use the -> operator to call an instance method.
Typically, in a .cpp file we would add a
using namespace Windows::UI::Xaml::Media::Imagingdirective and the auto keyword, so that the same code would look like this:
Properties
A ref class can have properties, which, just as in managed languages, are special member functions that appear as fields to consuming code.
public ref class SaveStateEventArgs sealed { public: // Declare the property property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ PageState { Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(); } ... }; ... // consume the property like a public field void PhotoPage::SaveState(Object^ sender, Common::SaveStateEventArgs^ e) { if (mruToken != nullptr && !mruToken->IsEmpty()) { e->PageState->Insert("mruToken", mruToken); } }
Delegates
Just as in managed languages, a delegate is a reference type that encapsulates a function with a specific signature. They are most often used with events and event handlers
// Delegate declaration (within namespace scope) public delegate void LoadStateEventHandler(Platform::Object^ sender, LoadStateEventArgs^ e); // Event declaration (class scope) public ref class NavigationHelper sealed { public: event LoadStateEventHandler^ LoadState; }; // Create the event handler in consuming class MainPage::MainPage() { auto navigationHelper = ref new Common::NavigationHelper(this); navigationHelper->LoadState += ref new Common::LoadStateEventHandler(this, &MainPage::LoadState); }
WINAPI_FAMILY macro
In a Universal Windows app, some code files are shared between the phone and Windows projects. In those files you will sometimes see or need to use the conditional compilation directive to exclude code that is only available on one or the other platform. For example, in app.xaml.cpp, the RootFrame_FirstNavigated method is only relevant for phone projects:
In app.xaml.cpp:
Adding content to the app
Let's add some content to the app. We'll work in both the Windows 8.1 and the Windows Phone 8.1 projects as we go along and have two running apps at the end.
Step 1: Modify your start page
- In Solution Explorer, in the Windows 8.1 project, open MainPage.xaml.
- Create controls for the UI by adding the following XAML to the root Grid, immediately before its closing tag. It contains a StackPanel that has a TextBlock that asks the user's name, a TextBox element that accepts the user's name, a Button, and another TextBlock element.
<StackPanel Margin="120,30,0,0"> <TextBlock HorizontalAlignment="Left" Text="Hello World" FontSize="36"/> the Navigation, layout, and views article.
At this point, you have created a very basic Windows Store app. (We'll work on the Windows Phone app next. The concepts are very similar.) To see what the Windows Store app looks like, right-click the Windows 8.1 project and choose Set as StartUp Project., and then press F5 to build, deploy, and run the app in debugging mode.
The default splash screen appears first. It has an image—Assets\SplashScreen.scale-100.png—and a background color that are specified in the app's manifest file. To learn how to customize the splash screen, see Adding a splash screen.
When the splash screen disappears, your app appears. It displays a black screen and the title "My Application".
There's no button or command to close the app. Although you could use the close gesture or Alt+F4 to close it, you typically don't close Windows Store apps. (This is discussed in Part 2: Manage app lifecycle and state.) Press the Windows key to go to the Start screen and notice that deploying the app adds its tile to the Start screen. To run the app again, just tap or click its tile, or press F5 in Visual Studio to run it in debugging mode.
It doesn't do much—yet—but congratulations, you've built your first Windows Store app!
To stop debugging and close the app, return to Visual Studio and press Shift+F5.
For more information, see Running Windows Store apps from Visual Studio.
In the app, you can type in the TextBox, but clicking the Button doesn't do anything. In later steps, you create an event handler for the button's Click event, which displays a personalized greeting. You add the event handler code to your MainPage.xaml.h and MainPage.xaml.cpp files.
- Now, in the Windows Phone 8.1 project, open MainPage.xaml and add the same XAML that you added to the Windows Store app earlier.
Because the phone screen is smaller, let's make two changes to the XAML: first, reduce the outer StackPanel's left margin to "20". Then change the orientation of the inner StackPanel to vertical, so that the button displays below the text box. The entire XAML now looks like this:
<StackPanel Margin="20,30,0,0"> <TextBlock HorizontalAlignment="Left" Text="Hello World" FontSize="36"/> <TextBlock Text="What's your name?"/> <StackPanel Orientation="Vertical" Margin="0,20,0,20"> <TextBox x: <Button Content="Say "Hello""/> </StackPanel> <TextBlock x: </StackPanel>
Right-click the Windows Phone 8.1 project choose Set as StartUp Project, and then press F5 to run the app in the Windows Phone Emulator. You should see this:
Step 2: Create an event handler
- (Complete these steps in the Windows project and in the Windows Phone project.) In MainPage.xaml, in either XAML or design view, select the "Say Hello" Button in the StackPanel you added earlier.
- Open the Properties Window by pressing Alt+Enter, and then choose the Events button (
).
- Find the Click event. In its text box, type the name of the function that handles the Click event. For this example, type "Button_Click".
- Press Enter. The event handler method is created in MainPage.xaml.cpp and opened so that you can add the code that's executed when the event occurs.
At the same time, in MainPage.xaml, the XAML for the Button is updated to declare the Click event handler, like this:
- In MainPage.xaml.cpp, add the following code to the Button_Click event handler that you just created. This code retrieves the user's name from the
nameInputTextBox control and uses it to create a greeting. The
greetingOutputTextBlock displays the result.
- Set the project as the startup, and then press F5 to build and run the app. When you type a name in the text box and click the button, the app displays a personalized greeting.
Step 3: Style the start page
Choosing a theme
It's easy to customize the look and feel of your app. By default, your app uses resources that have a dark style. The system resources also include a light theme. Let's try it out and see what it looks like.
To switch to the light theme
- In the Shared project, open App.xaml.
- In the opening Application tag, add the RequestedTheme property and set its value to Light:
Here's the full Application tag with the light theme added:
- Make one of the platform projects the startup, and then press F5 to build and run it. Notice that it uses the light theme. Now set the other platform project as the startup, press F5, and notice that it, too, uses the light theme. That's because App.xaml is shared by both projects.
Which theme should you use? Whichever one you want. Here's our take: for apps that mostly display images or video, we recommend the dark theme; for apps that contain a lot of text, we recommend the light theme. If you're using a custom color scheme, use the theme that goes best with your app's look and feel.
Using system styles
Right now, in the Windows app the text is very small and difficult to read. Let's fix that by applying a system style.
To change the style of an element
- In the Windows project, open MainPage.xaml.
- In either XAML or design view, select the "What's your name?"TextBlock that you added earlier.
- In the Properties window (F4), choose the Properties button (
) in the upper right.
- Expand the Text group and set the font size to 18 px.
- Expand the Miscellaneous group and find the Style property.
- Click the property marker (the green box to the right of the Style property), and then, on the menu, choose System Resource > BaseTextBlockStyle.
BaseTextBlockStyle is a resource that's defined in the ResourceDictionary in <root>\Program Files\Windows Kits\8.1\Include\winrt\xaml\design\generic.xaml.
On the XAML design surface, the appearance of the text changes. In the XAML editor, the XAML for the TextBlock is updated:
- Repeat the process to set the font size and assign the BaseTextBlockStyle to the
greetingOutputTextBlock element.Tip Although there's no text in this TextBlock, when you move the pointer over the XAML design surface, a blue outline shows where it is so that you can select it.
Your XAML now looks like this:
<StackPanel Margin="120,30,0,0"> <TextBlock Style="{ThemeResource BaseTextBlockStyle}" FontSize="16" Text="What's your name?"/> <StackPanel Orientation="Horizontal" Margin="0,20,0,20"> <TextBox x: <Button Content="Say "Hello"" Click="Button_Click"/> </StackPanel> <TextBlock Style="{ThemeResource BaseTextBlockStyle}" FontSize="16" x: </StackPanel>
- Press F5 to build and run the app. It now looks like this:
- You can repeat these steps for the Windows Phone project.
Summary
Congratulations, you've completed the first tutorial! It taught how to add content to Universal Windows apps, how to add interactivity to them, and how to change their appearance.
See the code
Did you get stuck, or do you want to check your work? If so, see the Hello World (C++) sample on Code Gallery.
Next steps
In the next tutorial in this series, Manage app lifecycle and state, you can learn how the app life cycle works and how to save your app's state.
|
https://msdn.microsoft.com/en-us/library/dn263168.aspx
|
CC-MAIN-2016-50
|
refinedweb
| 3,204
| 65.12
|
It has different functions such as stepping out of a function, taking advantage of the autos window, using run to the cursor to set temporary breakpoints, modifying a variable's value to test potential fixes, and using Set Next Statement to turn back the clock and re-execute code.
which makes it time saving.
#include <vector> #include <iostream> class Data { public: Data () { _values.push_back( 1 ); _values.push_back( 2 ); } int getSum() { int total; for ( std::vector<int>::iterator itr = _values.begin(), end = _values.end(); itr != end; ++itr ) { total += *itr; } return total; } int getCount() { return _values.size(); } private: std::vector<int> _values; }; double compute_average( int sum, int count ) { return sum / count; } int main() { Data d; std::cout << compute_average( d.getSum(), d.getCount() ) << std::endl; }
1. Step Out of the Current FunctionSo you've written a function call, like so:
int main() { Data d; std::cout << compute_average( d.getSum(), d.getCount() ) << std::endl; }And the compute_average function is not returning the correct value. If you were to use a debugger, and you wanted to step into compute_average, you could, of course, put a breakpoint inside compute_average, but what if it were called from several places? Visual Studio has a very convenient feature of its debugger, that will allow you to step into compute_average very quickly.
Set a breakpoint on that line:
Once the debugger hits it, then step into the function. getSum and getCount will both be called before compute_average. Normally, you'd keep hitting next to get out of getSum and getCount, but with Visual Studio, you can quickly hit Shift-F11 to step out of the current function and return to the next call.
Once you step out of the current function, you're taken back to the original breakpoint. But now you can step in again, to go to the next function. Repeat until you've drilled down into the function you want.
When to Use This TrickObviously, there are times when it makes more sense to just set a breakpoint in your target function. But when doing so would require ignoring hundreds of calls to that function to find the one you want, it might not be worth it. Using step out provides a quick way of getting into a function without having to find the function and set a temporary break point (or use run to cursor).
2. Use the Auto Window to See Result of FunctionsOne of the most frustrating parts of debugging is when you have a function call whose result isn't stored anywhere, and you really want to know what it returned.
Sometimes, programmers write code like this, just to work around the issue:
int computed_avg; computed_avg = compute_average( d.getSum(), d.getCount() ); std::cout << computed_avg << std::endl;(Obviously, in this case, the program prints out the value, so all is not lost. This is rarely true in the general case.)
Fortunately, the autos window has good courtesy to display the result of a function evaluation:
Whenever you want to see a return value! Note that you the autos window will eventually erase the return value as you execute code, so be sure to check your return value immediately.
3. Run to CursorRun to cursor is a great way of avoiding the step-step-step-step-step-oh-no-I-stepped-over-it problem, where you know where you want to be, getting to it requires stepping multiple times, and you get impatient.
In effect, run-to-cursor is just a shortcut for setting a breakpoint that is immediately cleared once it's hit; nevertheless, it's a very convenient feature. It is most useful when you have a piece of code that is called frequently from different places, and you only care about one code path. Then you can place a breakpoint at the start of that path and use run-to-cursor to get to the point you really care about.
Going back to our sample program, we can use run-to-cursor rather than the step-out trick, to get into compute_average. (Of course, we could just put a breakpoint in compute_average; for the purpose of making this example sensible, please imagine 15-20 calls to compute_average that all work correctly, taking place before the broken call.)
Any time you want a throwaway breakpoint or want to avoid single-stepping through a lot of code. Be careful, though, that you run to a part of the code that will actually be executed. Watch out for early returns from a function within a loop, for instance.
4. Modify Any VariableNow that we're in the compute_average function, and we know that the value being returned is waayyy too big, we can check the arguments to the function. It turns out that sum is very large. We'll deal with that in a bit. First, let's test and make sure that the function works if we do get the right value.
Obviously, one way of doing this would be to pass in a new value. But Visual Studio conveniently makes it easy to change any value in memory. In fact, let's do that with the value of sum, and make sure that it returns the correct value.
All you need to do is click on in the Value column of the auto or watch window and change the value. (You can also do this when the variable's value pops up while hovering over a variable in the source code.)
and voila:
Continuing execution of the program demonstrates that, in fact, we still get the wrong answer--this time, it returns the value 1. This suggests that truncation is taking place due to integer division.
Before recompiling, we can add in a cast to solve this problem:
return (double) sum / count;
When to Use this TrickThis trick is powerful, and is particularly helpful when you have found one bug, but want to prove that the rest of your code will work. This is particularly handy when your debugging session requires a great deal of setup--for instance, you have to perform a lot of UI to get the right inputs or your code takes a long time to build. (An alternative would be to consider writing a unit test that demonstrates the bug and doesn't require so much setup.)
On the other hand, you can't rely on this trick when you are inside a loop or a function that is called frequently--it's just too much of a pain to have to manually set variables all the time.
5. Set Next StatementSet Next Statement is a real power tool. If you're debugging, and you've accidentally (or not so accidentally) stepped past the point where something interesting happens, you can sometimes "unwind" execution. What this really means is that, maintaining the current state of the world, you can tell Visual Studio to go back and start executing from a previous instruction.
You can also use set next statement to jump over code that you believe is buggy, or to jump past a conditional test on an if statement to execute a path of code that you want to debug without having to make the condition true.
Setting the next statement can be dangerous and lead to instability if the stack or registers aren't in a valid state for the line being executed. And because it won't restore the state of the world, if your code depends on that state, changing the next statement might not be useful. On the other hand, if you want to make a call that you're pretty confident won't behave differently, it can be a great way of avoiding recreating a specific failure just because you accidentally stepped too far.
For instance, take the following debugging state, where you're about to return the value total from getSum:
If you had accidentally run too far, it might be very convenient to be able to simply say, ok, let's start that again:
and then you can go back through executing the loop, perhaps setting the value of total to 0, since you notice that it wasn't initialized, and then checking to see if the program gives the correct sum (in which case, you can be pretty confident that the lack of initialization was the problem).
May 3rd, 2015
Refer a Friend
Dec 2nd, 2016
check_circle
Mark as Final Answer
check_circle
Unmark as Final Answer
check_circle
Final Answer
Secure Information
Content will be erased after question is completed.
check_circle
Final Answer
|
https://www.studypool.com/discuss/510469/quot-code-walk-through-quot-please-respond-to-the-following?free
|
CC-MAIN-2016-50
|
refinedweb
| 1,421
| 57.81
|
This is a second cut at commenting on how the buddy algorithm works forallocating and freeing blocks of pages. No code is changed but queriesabout the code are marked "QUERY".Thanks to the people who sent comments on the first cut effort. I've addeda number of new comments, removed some more obvious ones and all thecomments are less than 80 columns wide.Andrew, if the commententry is ok, are you still interested in pushingthem to the Higher Powers That Be? I'd greatly appreciate it. Mel--- linux-2.4.19pre7.orig/mm/page_alloc.c Tue Apr 16 20:36:49 2002+++ linux-2.4.19pre7.mel/mm/page_alloc.c Thu Apr 18 23:30:42 2002@@ -25,11 +25,23 @@ int nr_swap_pages; int nr_active_pages; int nr_inactive_pages;++/* The two LRU list. These of primary interest to the page replacement+ * algorithm. Pages that are referenced often will remain in the active_list.+ * Pages are moved to the inactive_list by refill_inactive called by kswapd.+ * Once in the inactive list, the page is a canditate to be swapped out+ */ struct list_head inactive_list; struct list_head active_list;+ pg_data_t *pgdat_list;-/* Used to look up the address of the struct zone encoded in page->zone */+/* zone_table is the replacement for page->zone . It's a simple way of+ * quickly looking up what zone a page belongs so. During init, the upper+ * most 8 bits of page->flags will be used to store what zone we are in.+ * See free_area_init_core . The macro page_zone returns the zone a page+ * belongs to. See linux/include/mm.h+ */ zone_t *zone_table[MAX_NR_ZONES*MAX_NR_NODES]; EXPORT_SYMBOL(zone_table);@@ -86,8 +98,22 @@ * storing an extra bit, utilizing entry point information. * * -- wli+ *+ * There is a brief explanation of how a buddy algorithm works at+ * . A better idea+ * is to read the explanation from a book like UNIX Internals by+ * Uresh Vahalia+ * */+/**+ * __free_pages_ok - Returns pages to the buddy allocator+ * @page: The first page of the block to be freed+ * @order: 2^order number of pages are freed+ *+ * This function returns the pages allocated by __alloc_pages and tries to+ * merge buddies if possible. Do not call directly, use free_pages()+ **/ static void FASTCALL(__free_pages_ok (struct page *page, unsigned int order)); static void __free_pages_ok (struct page *page, unsigned int order) {@@ -112,36 +138,70 @@ BUG(); if (PageLocked(page)) BUG();++ /* QUERY: The page was released from the cache a few pages above.+ * Presumably, it is a bug if a page is on the LRU while+ * is if been freed because it was up until 2.4.19preX .+ * If it's still a bug, should we call BUG() before calling+ * lru_cache_del?+ */ if (PageLRU(page)) BUG(); if (PageActive(page)) BUG(); page->flags &= ~((1<<PG_referenced) | (1<<PG_dirty));+ /* If it is balance_classzone that is doing the freeing, the pages+ * are to be kept for the process doing all the work freeing up pages+ */ if (current->flags & PF_FREE_PAGES) goto local_freelist;+ back_local_freelist: zone = page_zone(page);+ /* Multiple uses for mask which defies a common name+ * -mask == number of pages that will be freed+ * page_idx & ~mask == Is page aligned to an order size?+ * Also used later to calculate the address of a buddy+ */ mask = (~0UL) << order;++ /* zone_mem_map first page in the current zone */ base = zone->zone_mem_map;++ /* The number page insider the zone_mem_map relative to page size */ page_idx = page - base;+ if (page_idx & ~mask) BUG();- index = page_idx >> (1 + order);+ /* index is the number bit inside the free_area_t bitmap stored in+ * area->map+ */+ index = page_idx >> (1 + order); area = zone->free_area + order; spin_lock_irqsave(&zone->lock, flags); zone->free_pages -= mask;+ /* No matter what order the function started out as, this expression+ * will result in 0 when the mask would reach the max order+ */ while (mask + (1 << (MAX_ORDER-1))) { struct page *buddy1, *buddy2;+ /* QUERY: This could only be true if order was originally set+ * to be a value greater than MAX_ORDER, should the+ * sanity check not be made at the beginning of the+ * function and then removed from here?+ */ if (area >= zone->free_area + MAX_ORDER) BUG();++ /* QUERY: Can someone explain this to me? */ if (!__test_and_change_bit(index, area->map)) /* * the buddy page is still allocated.@@ -151,6 +211,9 @@ * Move the buddy up one level. * This code is taking advantage of the identity: * -mask = 1+~mask+ *+ * remember page_idx is the address index relative to the+ * beginning of the zone */ buddy1 = base + (page_idx ^ -mask); buddy2 = base + page_idx;@@ -159,7 +222,10 @@ if (BAD_RANGE(zone,buddy2)) BUG();+ /* buddy2 has already been freed */ memlist_del(&buddy1->list);++ /* Prepare to try and merge the higher order buddies */ mask <<= 1; area++; index >>= 1;@@ -171,11 +237,22 @@ return; local_freelist:+ /* If the process has already freed pages for itself, don't give it+ * more */ if (current->nr_local_pages) goto back_local_freelist;++ /* An interrupt doesn't have a current process to store pages on.+ *+ * QUERY: is this not a dead check, an interrupt could only get here if+ * alloc_pages took the slow path through balance_classzones. If an+ * interrupt got there, aren't we already dead?+ */ if (in_interrupt()) goto back_local_freelist;+ /* Add the page onto the local list, update the page information+ * and return */ list_add(&page->list, ¤t->local_pages); page->index = order; current->nr_local_pages++;@@ -184,19 +261,50 @@ #define MARK_USED(index, order, area) \ __change_bit((index) >> (1+(order)), (area)->map)+/* expand - Break up higher order pages until the right size block is available+ * @zone: The zone to free pages from+ * @page: The first page of the first order to split+ * @index: The page address index inside zone_mem_map+ * @low: The order block of pages required+ * @high: The order of the block of pages that are about to be split+ * @area: The array of free areas for this zone+ *+ * This function will break up higher orders of pages necessary and update the+ * bitmaps as it goes along. If it splits, the lower half will be put onto+ * the free list and the high half will be either allocated or split+ * further. This function is called from rmqueue() and not directly+ **/ static inline struct page * expand (zone_t *zone, struct page *page, unsigned long index, int low, int high, free_area_t * area) { unsigned long size = 1 << high;+ /*+ * If it turned out there was a free block at the right order to begin+ * with, no splitting will take place+ */ while (high > low) { if (BAD_RANGE(zone,page)) BUG();++ /* Mark that we are moving to the next area after we are+ * finished shuffling the free order lists+ */ area--; high--;++ /* Size is now half as big because the order dropped by 1 */ size >>= 1;++ /* Add the page to the free list for the "lower" area. The+ * high half will be split more if necessary+ */ memlist_add_head(&(page)->list, &(area)->free_list); MARK_USED(index, high, area);++ /* index is the page number inside this zone+ * page is the actual address+ */ index += size; page += size; }@@ -205,9 +313,26 @@ return page; }+/* rmqueue - Allocate page blocks of 2^order size via the buddy algorithm+ * @zone: The zone to allocate from+ * @order: The 2^order sized block to allocate+ *+ * This function is responsible for finding out what order of pages we+ * have to go to to satisify the request. For example if there is no+ * page blocks free to satisy order=0 (1 page), then see if there is+ * a free block of order=1 that can be spilt into two order=0 pages+ **/ static FASTCALL(struct page * rmqueue(zone_t *zone, unsigned int order)); static struct page * rmqueue(zone_t *zone, unsigned int order) {+ /* A free_area_t exists for each order of pages that can be allocated.+ * The struct stores a list of page blocks that can be allocated and+ * the bitmap the describes if the buddy is allocated or not.+ *+ * Here area is set to the free_area_t that represents this order of+ * pages. If necessary, the next higher order of free blocks will be+ * examined.+ */ free_area_t * area = zone->free_area + order; unsigned int curr_order = order; struct list_head *head, *curr;@@ -216,24 +341,48 @@ spin_lock_irqsave(&zone->lock, flags); do {+ /* Get the first block of pages free in this area */ head = &area->free_list; curr = memlist_next(head);+ /* If there is a free block available, split it up until+ * we get the order we want and allocate it+ */ if (curr != head) { unsigned int index;+ /* Get the page for this block */ page = memlist_entry(curr, struct page, list); if (BAD_RANGE(zone,page)) BUG();++ /* It is no longer free for this block so remove it from+ * the list+ */ memlist_del(curr);++ /* zone_mem_map is the first page in this zone block so+ * subtracting them will give us which index this page+ * in the zone is. MARK_USED will give what bit number+ * in the map it is+ */ index = page - zone->zone_mem_map; if (curr_order != MAX_ORDER-1) MARK_USED(index, curr_order, area);++ /* Remove from the count the number of pages that is+ * been split or assigned.+ */ zone->free_pages -= 1UL << order;+ /* expand is responsible for splitting blocks of higher+ * orders (if necessary) until we get a block of the+ * order we are interested in.+ */ page = expand(zone, page, index, order, curr_order, area); spin_unlock_irqrestore(&zone->lock, flags);+ /* Mark the page as used and do some checks */ set_page_count(page, 1); if (BAD_RANGE(zone,page)) BUG();@@ -241,10 +390,16 @@ BUG(); if (PageActive(page)) BUG();+ return page; }++ /* There isn't pages ready at this order so examine a block of+ * higher orders+ */ curr_order++; area++;+ } while (curr_order < MAX_ORDER); spin_unlock_irqrestore(&zone->lock, flags);@@ -252,13 +407,37 @@ } #ifndef CONFIG_DISCONTIGMEM+/* _alloc_pages - Find zone to allocate from and call __alloc_pages+ * @gfp_mask - Flags that determine the behaviour of the allocator+ * @order - 2^order number of pages will be allocated in a block+ *+ * This is called by alloc_pages. It's only task is to identify the+ * preferred set of zones to allocate from.+ **/ struct page *_alloc_pages(unsigned int gfp_mask, unsigned int order) {+ /* The zones currently are+ * ZONE_DMA, ZONE_NORMAL and ZONE_HIGHMEM. The index to allocate+ * from is stored in the lower bits of flag. GFP_ZONEMASK clears+ * the higher bits+ *+ */ return __alloc_pages(gfp_mask, order, contig_page_data.node_zonelists+(gfp_mask & GFP_ZONEMASK)); } #endif+/* balance_classzone - Free page frames from a zone in a synchronous fashion+ * @classzone: Zone to free from+ * @gfp_mask: Flags which determine the behaviour of the allocator+ * @order: It's a block of 2^order pages the caller is looking for+ * @freed: Returns the number of total number of pages freed+ *+ * In a nutshell, this function does some of the work of kswapd in a synchrous+ * fashion when there simply is too little memory to be waiting around. The+ * caller will use this when it needs the memory and is willing to block on+ * waiting for it.+ **/ static struct page * FASTCALL(balance_classzone(zone_t *, unsigned int, unsigned int, int *)); static struct page * balance_classzone(zone_t * classzone, unsigned int gfp_mask, unsigned int order, int * freed) {@@ -271,6 +450,10 @@ BUG(); current->allocation_order = order;++ /* These flags are set so that __free_pages_ok knows to return the+ * pages directly to the process+ */ current->flags |= PF_MEMALLOC | PF_FREE_PAGES; __freed = try_to_free_pages(classzone, gfp_mask, order);@@ -278,6 +461,7 @@ current->flags &= ~(PF_MEMALLOC | PF_FREE_PAGES); if (current->nr_local_pages) {+ /* If pages were freed */ struct list_head * entry, * local_pages; struct page * tmp; int nr_pages;@@ -290,7 +474,14 @@ do { tmp = list_entry(entry, struct page, list); if (tmp->index == order && memclass(page_zone(tmp), classzone)) {+ /* This is a block of pages that is of+ * the correct size so remember it+ */ list_del(entry);++ /* QUERY: if order > 0, wouldn't the+ * nr_local_pages drop by more than 1?+ */ current->nr_local_pages--; set_page_count(tmp, 1); page = tmp;@@ -318,7 +509,10 @@ } nr_pages = current->nr_local_pages;- /* free in reverse order so that the global order will be lifo */+ /* free in reverse order so that the global order will be lifo+ * The pages freed here are ones not of the order we are+ * interested in for the moment+ */ while ((entry = local_pages->prev) != local_pages) { list_del(entry); tmp = list_entry(entry, struct page, list);@@ -333,8 +527,21 @@ return page; }-/*+/**+ * __alloc_pages - Allocate pages in a block of size 2^order+ * @gfp_mask: Flags for this allocation that determine behaviour of allocator+ * @order: 2^order number of pages to allocate+ * @zonelist: The preferred zone to allocate from+ * * This is the 'heart' of the zoned buddy allocator:+ * There is a few paths the this will take to try and allocate the pages.+ * is takes depends on what pages are available and what flags on gfp_mask+ * are set. For instance, if the allocation is for an interrupt handler,+ * __alloc_pages won't do anything that would block. Each block or attempt+ * made gets progressively slower as the function executes.+ *+ * This function should not be called directly. Use either alloc_pages() or+ * __get_free_pages() */ struct page * __alloc_pages(unsigned int gfp_mask, unsigned int order, zonelist_t *zonelist) {@@ -343,15 +550,41 @@ struct page * page; int freed;+ /* zonelist is the set of zones for either ZONE_DMA, ZONE_NORMAL+ * or ZONE_HIGHMEM. zone is the subset of zones inside them three+ * groups+ */ zone = zonelist->zones;++ /* classzone is the first zone of the list. It's a "special"+ * zone which keeps track of whether the whole needs to be balanced or+ * something+ */ classzone = *zone;++ /* min is the number of pages that have to be allocated */ min = 1UL << order;++ /* Cycle through all the zones available */ for (;;) { zone_t *z = *(zone++); if (!z) break;+ /* Increase min by pages_low so that too many pages from a zone+ * are not allocated. If pages_low is reached, kswapd needs to+ * begin work+ *+ * QUERY: If there was more than one zone in ZONE_NORMAL and+ * each zone had a pages_low value of 10, wouldn't the+ * second zone have a min value of 20, the third of 30+ * and so on? Wouldn't this possibly wake kswapd before+ * it was really needed? Is this the expected behaviour?+ */ min += z->pages_low;++ /* There is enough pages, allocate it (rmqueue) and return the+ * page */ if (z->free_pages > min) { page = rmqueue(z, order); if (page)@@ -359,11 +592,19 @@ } }+ /* pages_low has been reached. Mark the zone set as needing balancing+ * and wake up kswapd which will start work freeing pages in this zone+ */ classzone->need_balance = 1; mb(); if (waitqueue_active(&kswapd_wait)) wake_up_interruptible(&kswapd_wait);+ /* Start again moving through the zones. This time it will allow the+ * zone to reach pages_min number of free pages. It is hoped that+ * kswapd will bring the number of pages above the watermarks again+ * later+ */ zone = zonelist->zones; min = 1UL << order; for (;;) {@@ -373,9 +614,20 @@ break; local_min = z->pages_min;++ /* If the process requesting this cannot discard other pages or+ * wait, allow the zone to be pushed into a tigher memory+ * position.+ */ if (!(gfp_mask & __GFP_WAIT)) local_min >>= 2;++ /* QUERY: same as above, does it not artifically inflate min+ * depending on the number of zones there is?+ */ min += local_min;++ /* If we are safe to allocate this, allocate the page */ if (z->free_pages > min) { page = rmqueue(z, order); if (page)@@ -387,7 +639,18 @@ rebalance: if (current->flags & (PF_MEMALLOC | PF_MEMDIE)) {+ /* PF_MEMALLOC if set if the calling process wants to be+ * treated as a memory allocator, kswapd for example. This+ * process is high priority and should be served if at+ * all possible. PF_MEMDIE is set by the OOM killer. The+ * calling process is going to die no matter what but+ * needs a bit of memory to die cleanly, hence give what+ * it needs because we'll get it back soon. */+ zone = zonelist->zones;++ /* Cycle through the zones and try to allocate if at all+ * possible */ for (;;) { zone_t *z = *(zone++); if (!z)@@ -404,10 +667,17 @@ if (!(gfp_mask & __GFP_WAIT)) return NULL;+ /* Basically do the work of kswapd in a synchronous fashion and return+ * a block of pages of the right order if one was found+ */ page = balance_classzone(classzone, gfp_mask, order, &freed); if (page) return page;+ /* if balance_classzone returned no pages, it might be because the+ * pages it freed up were of a higher or lower order than the one we+ * were interested in, so search though all the zones again+ */ zone = zonelist->zones; min = 1UL << order; for (;;) {@@ -434,8 +704,14 @@ goto rebalance; }-/*- * Common helper functions.+/**+ * __get_free_pages - Get a 2^order block of free pages+ * @gfp_mask: Flags which determine the allocator behaviour+ * @order: A block sized 2^order will be allocated+ *+ * This is the highest level function available for allocating a block of+ * pages to the caller. Ultimatly __alloc_pages() is called to use the+ * buddy algorithm to retrieve a block of pages */ unsigned long __get_free_pages(unsigned int gfp_mask, unsigned int order) {@@ -444,9 +720,17 @@ page = alloc_pages(gfp_mask, order); if (!page) return 0;++ /* Return the linear address of the page. Presumably the caller+ * is not interested in the struct page+ */ return (unsigned long) page_address(page); }+/**+ * get_zerod_page - Allocates one page from the buddy allocator and zeros it+ * @gfp_mask: Flags which determine the allocator behaviour+ */ unsigned long get_zeroed_page(unsigned int gfp_mask) { struct page * page;@@ -460,20 +744,39 @@ return 0; }+/* __free_pages - Sanity check before asking the buddy allocator to take pages+ * @page: The first page of the block to free+ * @order: Indicates the block size. size = 2^order+ */ void __free_pages(struct page *page, unsigned int order) {+ /* QUERY: __free_pages_ok() does a load of sanity checks at the+ * beginning of the function, would it not make more sense+ * to lump them all together and have one function call?+ */ if (!PageReserved(page) && put_page_testzero(page)) __free_pages_ok(page, order); }+/**+ * free_pages - Free pages allocated by the buddy allocator+ * addr: The address of the pages to free+ * order: The block size to free+ *+ * This is the highest level function available for freeing pages allocated+ * by the buddy allocator+ */ void free_pages(unsigned long addr, unsigned int order) { if (addr != 0) __free_pages(virt_to_page(addr), order); }-/*- * Total amount of free (allocatable) RAM:+/**+ * nr_free_pages - Returns number of free pages in all zones+ *+ * This function walks through all zones and sums the free page frames in each+ * of them. */ unsigned int nr_free_pages (void) {@@ -490,8 +793,11 @@ return sum; }-/*- * Amount of free RAM allocatable as buffer memory:+/**+ * nr_free_buffer_pages - Amount of free RAM allocatable as buffer memory+ *+ * This steps through all the zones that are suitable for normal use and+ * returns back the totals of "size-pages_high". */ unsigned int nr_free_buffer_pages (void) {@@ -517,6 +823,9 @@ } #if CONFIG_HIGHMEM+/**+ * nr_free_highpages - Returns the number of free page frames in high memory+ */ unsigned int nr_free_highpages (void) { pg_data_t *pgdat = pgdat_list;@@ -530,6 +839,9 @@ } #endif+/* This macro will yield the total amount of RAM in kB+ * addrssed by x number of pages.+ */ #define K(x) ((x) << (PAGE_SHIFT-10)) /*@@ -547,6 +859,8 @@ K(nr_free_pages()), K(nr_free_highpages()));+ /* Step through all zones in all pgdats and print out the pertinent+ * information about them */ while (tmpdat) { zone_t *zone; for (zone = tmpdat->node_zones;@@ -567,6 +881,10 @@ nr_inactive_pages, nr_free_pages());+ /* This steps through all the zones a second time and checks how+ * many blocks of each 2^order block of pages. This helps determine+ * how fragmented memory is+ */ for (type = 0; type < MAX_NR_ZONES; type++) { struct list_head *head, *curr; zone_t *zone = pgdat->node_zones + type;@@ -604,7 +922,10 @@ } /*- * Builds allocation fallback zone lists.+ * Builds allocation fallback zone lists. This determines what order zones+ * should be used to take pags from if an allocation fails. For example,+ * an allocation for HIGHMEM will fall to NORMAL if pages are not available+ * and in turn fall to DMA. */ static inline void build_zonelists(pg_data_t *pgdat) {-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
|
https://lkml.org/lkml/2002/4/18/204
|
CC-MAIN-2017-34
|
refinedweb
| 3,138
| 56.12
|
Using Django's Free Comments
Django includes some basic commenting functionality that can save you a ton of time if you want to allow users to add comments to objects such as blog entries or photos. Django's free comments are flexible enough that they can be used on pretty much anything.
Set Up
The first thing you'll need to do is to add Django's comment packages to your INSTALLED_APPS in "settings.py":
INSTALLED_APPS = ( [...] 'django.contrib.comments', )
If you're using custom views and not generic views, you'll need to add the following to the top of the relevant "urls.py" file. Generic views already include FreeComment, so you don't have to import it yourself.
from django.contrib.comments.models import FreeComment
Add the following URL pattern to your site-wide "urls.py" file:
urlpatterns = patterns('', [...] (r'^comments/', include('django.contrib.comments.urls')), }
You comments %}
Below that, you're free to access the comments.
Adding Comment Counts to List and Archive Pages
The only data you need to access an object's comments is that object's id. If you have that, you can get the comments themselves, comment count, and other info.
django.views.generic.list_detail.object_list
In an object_list template, you can do the following to add the comment count to each of the blog entry listings. The following example assumes you have an app named "blog" with a class called "entry", which has fields called "title", "summary", and has a method called "get_absolute_url" which returns an absolute path to that entry's detail page.
Note: The class name should be always be referred to in all lowercase. For example, if the class contained inside the app named blog were actually named Entry, it would still be referred to as blog.entry.
<ul> {% for object in object_list %} {% get_free_comment_count for blog.entry object.id as comment_count %} <li> <h2><a href="{{ object.url }}">{{ object.title }}</a></h2> <p class="description">{{ object.summary}}</p> <p class="details"><a href="{{ object.get_absolute_url }}">{{ comment_count }} Comments</a></p> </li> {% endfor %} </ul>
django.views.generic.date_based.archive_index
An archive_index generic view works almost exactly the same, except you're iterating through objects from the "latest" collection instead of the "object_list" collection:
<ul> {% for object in latest %} {% get_free_comment_count for blog.entry object.id as comment_count %} [...] {% endfor %} </ul>
In the date-based archives such as archive_year or archive_month, the collection you iterate through is called "object_list". archive_index is the only generic view with "latest".
Adding Comments to Detail Pages
Typically, you'll allow users to add comments through the detail page for an object. It's possible to allow them to do it elsewhere, but for simplicity's sake, this example only shows how to do it on detail pages. For any of the "detail" generic views such as django.views.generic.list_detail.object_detail or django.views.generic.date_based.object_detail, you'll have the object's id as "object.id", so getting the comment count is the same:
{% get_free_comment_count for blog.entry object.id as comment_count %}
To get the list of comments, you call the following, which puts the list of comments in "comment_list":
{% get_free_comment_list for blog.entry object.id as comment_list %}
Each comment object in comment_list has the following bits of data:
- comment.person_name - The comment poster's name.
- comment.submit_date - The date and time the poster submitted the comment. You can pipe this through the "date" filter to format the date. (Shown in the example below)
- comment.comment - The actual comment text. Don't forget to escape this to prevent code-injection attacks with the "escape" filter. (Shown in the example below)
- comment.is_public - Whether or not the comment is public. (TODO: How do we set a comment's public or non-public status?)
- comment.ip_address - The comment author's IP address.
- comment.approved - Whether or not this comment has been approved by a staff member. (TODO: Where is this set or modified?)
And the following built-in methods:
- comment.get_absolute_url - Returns an absolute URL to this comment by way of the content object's detail page. If a comment is attached to a blog entry located at "/blog/some-slug", this URL will look something like "/blog/some-slug/#c4", where "4" is the comments id number.
- comment.get_content_object - Returns the object that this comment is a comment on.
As of this writing, the free comments don't allow for you to specify other bits of data to be included, such as the comment poster's e-mail address or URL. This may be changed in the future.
Example
{% get_free_comment_count for blog.entry object.id as comment_count %} <h2><a href="{{ object.url }}">{{ object.title }}</a></h2> <em>{{ object.description }}</em> <div class="article_menu"> <b>Added on {{ object.add_date|date:"F j, Y" }}</b> <a href="{{ object.get_absolute_url }}#comments">{{ comment_count }} Comment{{ comment_count|pluralize }}</a> </div> {% get_free_comment_list for blog.entry object.id as comment_list %} <h2 id="comments">Comments</h2> {% for comment in comment_list %} <div class="comment_{% cycle odd,even %}" id="c{{ comment.id }}"> <span class="comnum"><a id="c{{ comment.id }}" href="#c{{ comment.id }}">#{{ forloop.counter }}</a></span> <p><b>{{ comment.person_name|escape }}</b> commented, on {{ comment.submit_date|date:"F j, Y" }} at {{ comment.submit_date|date:"P" }}:</p> {{ comment.comment|escape|urlizetrunc:40|linebreaks }} </div> {% endfor %} <h2>Post a comment</h2> {% free_comment_form for blog.entry object.id %}
Free Comment Templates
Django has internal default templates for the various bits of comments-related code. (NOTE: Actually, I lied. Once these patches are applied, it will. Until then, you'll have to specify your own templates for "free_preview.html" and "posted.html".)
You can override any of these built in templates by creating a "comments/" folder in your templates folder with any or all of the following files:
Post Comment Form (freeform.html)
This template holds the form code that is used by the user to post a comment. In the above example, this is included like so:
<h2>Post a comment</h2> {% free_comment_form for blog.entry object.id %}
Example
{% if display_form %} <form action="/comments/postfree/" method="post"> <p>Your name: <input type="text" id="id_person_name" name="person_name" /></p> <p>Comment:<br /><textarea name="comment" id="id_comment" rows="10" cols="60"></textarea></p> <input type="hidden" name="options" value="{{ options }}" /> <input type="hidden" name="target" value="{{ target }}" /> <input type="hidden" name="gonzo" value="{{ hash }}" /> <p><input type="submit" name="preview" value="Preview comment" /></p> </form> {% endif %}">Comment:</label> <br /> {{ comment_form.comment }} </p> <input type="hidden" name="options" value="{{ options }}" /> <input type="hidden" name="target" value="{{ target }}" /> <input type="hidden" name="gonzo" value="{{ hash }}" /> <p> <input type="submit" name="preview" value="Preview revised comment" /> </p> </form>
Posted Message (posted.html)
This template is shown after a user successfully posts a comment. You can access the.REQUEST.url }}" />
before
<p><input type="submit" name="preview" value="Preview revised comment" /></p>
This should be it. Enjoy
--NL
Other Examples
List Recent Comments
The following code lists all the recent comments on your site, regardless of app.
<h1>Recent comments</h1> <p> {% if has_previous %} <a href="?page={{ previous }}">Previous</a> | {% endif %} Page {{ page }} of {{ pages }} {% if has_next %} | <a href="?page={{ next }}">Next</a> {% endif %} </p> {% for comment in object_list %} <div class="comment" id="c{{ comment.id }}"> <h3> <a href="{{ comment.get_absolute_url }}"> {{ comment.person_name|escape }} <span class="small quiet"> {{ comment.submit_date|date:"F j, Y" }} at {{ comment.submit_date|date:"P" }} </span> </a> </h3> {{ comment.comment|escape|urlizetrunc:"40"|linebreaks }} </div> {% endfor %} <p> {% if has_previous %} <a href="?page={{ previous }}">Previous</a> | {% endif %} Page {{ page }} of {{ pages }} {% if has_next %} | <a href="?page={{ next }}">Next</a> {% endif %} </p>
|
https://code.djangoproject.com/wiki/UsingFreeComment?version=33
|
CC-MAIN-2014-10
|
refinedweb
| 1,257
| 50.94
|
Modern client-side application development demands modularity. Client-side modularity is required to achieve separation of logic from the UI. To implement this modularity, we usually use an MVC or MVVM framework to manage separate layers (in separate JavaScript files) for Models, Controllers, Modules, Services etc.
AngularJS is a great framework for implementing client-side modularity with MVC support.
However as the application grows, managing JavaScript dependencies on a page becomes a challenge, as you need to load your JavaScript by listing all <script> tags and their dependencies, in a particular order. Any JavaScript developer who has managed multiple <script> tags on a page knows how tedious and error prone the entire exercise is. In many cases, it also affects the performance of the app.
RequireJS is a JavaScript framework that enables asynchronous loading of files and modules and can come in very handy while managing dependencies across different AngularJS components and loading them asynchronously. An alternative to RequireJS is Almond.js, a stripped down version of RequireJS. RequireJS is more popular compared to it.
This article is published from the DNC Magazine for .NET Developers and Architects. Download this magazine from here [Zip PDF] or Subscribe to this magazine for FREE and download all previous and current editions
RequireJS is a JavaScript module and file loader. We start with each JavaScript file, listing the different files it depends on. RequireJS then recognizes these dependencies and loads them in the correct order. Since RequireJS manage dependencies on the client-side, we no longer need to manually refer to all script references on an html page. RequiresJS implements the AMD API (Asynchronous module definition API) and thus inherits all its advantages which includes asynchronous loading of dependencies and implicit resolution of dependencies, amongst other uses.
RequireJS can be used both in browsers as well as with server solutions like Node.js.
Since RequireJS loads files asynchronously, the browser starts its rendering process while waiting for RequireJS to do its work, without any blocking. This improves performance.
Note: If anybody is interested in looking at an implementation of KnockoutJS with RequireJS, please check here
In this article, we will be using Bower to install dependencies in this project; in our case - AngularJS and RequireJS. Bower is a package manager for the web. It manages frameworks, libraries etc. needed by the web application. Although I have implemented this application using Visual Studio 2015, you can also implement it using Visual Studio 2013. To learn more about Bower, check this article .
Pre-requisites for the implementation
Here are some pre-requisites before you get started:
Wherever you see Visual Studio, it either means Visual Studio 2013 or Visual Studio 2015. You can choose either, as per availability.
Step 1: Open Visual Studio and create an empty ASP.NET project with the name NG_RequireJS as shown in the following image
Step 2: To install necessary dependencies for the project, open Node.js command prompt (Run as Administrator) and follow these steps.
- From the command prompt navigate to the project folder.
- Install Bower for the project
- Initialize Bower. This will add bower.json file to the project. By default, the file is added in the project path which will not be displayed in the Solution explorer. So to view the file, click on Show all files on the toolbar of our Solution Explorer and you will find the bower.json file. Right-click on the file and select Include in project. This needs to be done for all dependencies which will be added in the next steps.
The above image shows bower init command which will ask for options to be added in the bower.json file. Please select options as per your application’s requirements. For this article, we have selected module options for amd, globals and node. Once these options are selected and added, the bower.json file will take the following shape:
The project will be added with bower.json.
- Install AngularJS with the following command: Bower install angularjs –save
- Now install RequireJS with the following command: Bower install requirejs –save
Step 3: Go back to the project in Visual Studio, select Show All Files from the Solution Explorer tool bar and you should now see bower_components include in the project. The project will be displayed as shown in the following image.
bower.js will show dependencies as shown below:
So far so good, we have added the necessary infrastructure for the project. Now we will add the necessary AngularJS components to the project.
Step 4: In the solution, add a new empty Web API project of the name ServiceProject. We will be using this API as a service provider project for making http calls using Angular’s $http service.
Step 5: In this project, in the Models folder, add a new class file with the following code:
using System.Collections.Generic;
namespace ServiceProject.Models
{
public class Product
{
public int ProdId { get; set; }
public string ProdName { get; set; }
}
public class ProductDatabase : List<Product>
{
public ProductDatabase()
{
Add(new Product() {ProdId=1,ProdName="Laptop" });
Add(new Product() { ProdId = 2, ProdName = "Desktop" });
}
}
}
Step 6: In the Controllers folder, add a new empty Web API Controller of the name ProductInfoAPIController. In this controller, add a Get() method with the following code:
using ServiceProject.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace ServiceProject.Controllers
{
public class ProductInfoAPIController : ApiController
{
public IEnumerable<Product> Get()
{
return new ProductDatabase();
}
}
}
Step 7: In the NG_RequireJS project, add a new folder of the name app. In this folder, add the following JavaScript files:
Main.js
require.config({
paths: {
angular: '../bower_components/angular/angular'
},
shim: {
'angular': {
exports:'angular'
}
}
});
require(['app'], function () {
require(['serv', 'ctrl'], function () {
angular.bootstrap(document, ['app']);
});
});
The above script bootstraps RequireJS by calling require.config() function, passing in a configuration object which contains path for the AngularJS framework. Since AngularJS is an external dependency here that is being managed using Bower, we are specifying a relative path to our bower_components directory. To make sure that AngularJS is embedded correctly, we are using RequireJS to assign AngularJS to the global variable angular. This is done using the attribute shim. We are using exports which defines global access to the angular object, so that all JavaScript modules/files can make use of this object.
The above file also defines require() used for loading the necessary modules asynchronously along with the loading of the document (DOM). require() loads the modules - app, serv and ctrl asynchronously.
The following line:
angular.bootstrap(document, ['app']);
..performs the same operation as the ng-app directive does. The reason we are using angular.bootstrap() instead of ng-app is because the files are loaded asynchronously. If we use ng-app, there could be a possibility that when AngularJS loads a module in the ng-app directive, RequireJS may have not yet loaded the module. Hence we use angular.bootstrap() to initialize our app only when RequireJS has finished loading its modules. The first parameter to angular.bootstrap() is the DOM element and the second parameter is the application module that is to be loaded. Here it simply means that the app module will be loaded at document level.
App.js
define(['angular'],function (angular) {
var app = angular.module('app', []);
return app;
});
The above file defines angular module of name ‘app’. The angular object declared through shim is passed to it.
serv.js
define(['app'], function (app) {
app.service('serv', ['$http',function ($http) {
this.getdata = function () {
var resp = $http.get('');
return resp;
}
}]);
})
The above code defines angular service of name serv, which makes call to the Web API service and receives a response.
ctrl.js
define(['app'], function (app) {
app.controller('ctrl', ['$scope','serv', function ($scope, serv) {
loaddata();
function loaddata() {
var promise = serv.getdata();
promise.then(function (resp) {
$scope.Products = resp.data;
$scope.Message = "Operation Completed Successfully...";
}, function (err) {
$scope.Message = "Error " + err.status;
})
};
}]);
});
The above file contains code for declaring angular controller. This file has dependency on the angular service. The above controller makes a call to getData() function of the angular service. Once the data is received from the service, it is stored in the Products $scope object.
Step 8: On the project root, add an index.html with the following markup and code:
<!DOCTYPE html>
<html>
<head>
<title>Using RequireJS with Angular.js</title>
<meta charset="utf-8" />
<style type="text/css">
table, td,th {
border:double;
}
</style>
</head>
<body ng-
<h1>Using RequireJS with Angular.js</h1>
<table>
<thead>
<tr>
<th>Product Id</th>
<th>Product Name</th>
</tr>
</thead>
<tbody>
<tr ng-
<td>{{p.ProdId}}</td>
<td>{{p.ProdName}}</td>
</tr>
</tbody>
</table>
<div>{{Message}}</div>
<script src="bower_components/requirejs/require.js" data-</script>
</body>
</html>
In the above file, the following line
<script src="bower_components/requirejs/require.js" data-</script>
..is used to initialize and load RequireJS. The data-main attribute is used to load Main.js, the starting point of our application. This attribute tells require.js to load app/Main.js after require.js has loaded. Main.js configures Angular and other module dependencies.
This is how we eliminate the need to refer to all JavaScript files in an HTML page using RequireJS.
Run the application by setting multiple startup projects in Visual Studio, as shown in the following image:
Run the application and the Index.html loads in the browser with the following result:
Right click on the page > View source and you will see all modules listed in order.
RequireJS is an awesome library for managing asynchronous module loading when the logic is segregated in separate JavaScript files. It loads modules and the relevant dependencies in their right order. Make sure you learn this library and use it in a project with multiple JavaScript files!
Download the entire source code of this article (Github)
|
http://www.dotnetcurry.com/angularjs/1207/using-angularjs-bower-requirejs-visual-studio
|
CC-MAIN-2017-26
|
refinedweb
| 1,624
| 50.23
|
Editor’s note: This Tailwind CSS and React tutorial was last updated on 19 February 2021 to reflect changes introduced with the latest Tailwind CSS release, Tailwind CSS v2.0. The instructions and configurations described herein have been updated accordingly.
Recently, I tried using Tailwind CSS in a React project bootstrapped by the Create React App (CRA) boilerplate and ran into difficulties setting up Tailwind CSS as CRA abstracts configuration.
To make custom configurations, you would have to
eject Create React App to have full access to tinker with the configurations, which also means a much more tedious setup — and should anything break, you’re on your own. I tinkered a bit, and after several Google searches, I found a better way to get it done.
In this tutorial, we’ll demonstrate how to to make Tailwind CSS work inside your React project without having to eject Create React App.
To follow along with this tutorial, you should have
- Node.js 12.13.0 or higher installed on their PC
- Yarn / npm 5.6 or higher installed on you PC
- Basic knowledge of how CSS works
- Basic understanding of React and Tailwind CSS
Using Tailwind CSS in your React boilerplate project
First, open your terminal and type the following commands to create a new project.
#using NPX npx create-react-app tailwindreact-app #using NPM npm init react-app tailwindreact-app #using yarn yarn create react-app tailwindreact-app
create-react-app is the official React build tool for scaffolding new React projects. It leverages webpack and babel and reduces the hassle of configuring and setting up the build processes for projects, allowing you to focus on writing the code that powers your app.
Add
cd to your app directory:
cd tailwindreact-app
Next, install Tailwind and its dependencies:
#using npm npm install -D [email protected]:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat [email protected]^7 [email protected]^9 #using Yarn yarn add [email protected]:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat [email protected]^7 [email protected]^9 -D
Create React App does not support PostCSS 8 yet, so we’ll install the version of PostCSS 7 that is compatible with Tailwind CSS v2.
As stated in the PostCSS documentation:
PostCSS is a tool for transforming styles with JS plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more.
Autoprefixer is a PostCSS plugin that parses your CSS and adds/removes unnecessary vendor prefixes in your compiled CSS rules. It can help you add prefixes for animations, transition, transform, grid, flex, flexbox, etc.
How to configure CRACO
Since Create React App doesn’t let you override the PostCSS configuration by default, we’ll need to install CRACO to configure Tailwind.
#using npm npm install @craco/craco #using Yarn yarn add @craco/craco
CRACO, short for Create React App configuration override, is an easy and comprehensible configuration layer for Create React App. It provides all the benefits of
create-react-app and customization and eliminates the need to “eject” your app by adding a
craco.config.js file at the root of your application to customize with your eslint, babel and PostCSS configurations.
First, create a CRACO configuration file in your base directory, either manually or using the following command:
touch craco.config.js
Next, add
tailwindcss and
autoprefixer as PostCSS plugins to your CRACO config file:
// craco.config.js module.exports = { style: { postcss: { plugins: [ require('tailwindcss'), require('autoprefixer'), ], }, }, }
Configure your app to use
craco to run development and build scripts.
Open your
package.json file and replace the content of
"scripts" with:
"start": "craco start", "build": "craco build", "test": "craco test", "eject": "react-scripts eject"
Your scripts file should look like this:
"scripts": { "start": "craco start", "build": "craco build", "test": "craco test", "eject": "react-scripts eject" }
Create the default configurations scaff tailwindcss init
This command creates a
tailwind.config.js in your project’s base directory. The file houses all of Tailwind’s default configuration. We can also add an optional
--full flag to generate a configuration file with all the defaults Tailwind comes with.
You’ll get a file that matches the default configuration file Tailwind uses internally.
Including Tailwind in your CSS
Inside your
src folder create a folder named
styles. This is where all your styles will be stored.
Inside that folder, create a
tailwind.css and an
index.css file.
The
index.css file is where we’ll import tailwind’s base styles and configurations.
tailwind.css will contain the compiled output of the
index.css.
Tailwind CSS components, utilities, and base styles
add the following to your
index.css file.
//index.css @tailwind base; @tailwind components; @tailwind utilities;
@tailwind is a tailwind directive that is used to inject default
base styles,
components,
utilities and custom configurations.
@tailwind base **injects Tailwind’s base styles, which is a combination of
Normalize.css and some additional base styles.
@tailwind components injects any component (small reusable styles such as buttons, form elements, etc.) classes registered by plugins defined in your tailwind config file.
Below the component import is where you would add any of your custom component classes — things that you’d want to be loaded before the default utilities so the utilities could still override them.
Here’s an example:
.btn { ... } .form-input { ... }
@tailwind utilities injects all of Tailwind’s utility classes (including the default and your utilities), which are generated based on your config file.
Below the utilities import is where you would add any custom utilities you need that don’t come out of the box with Tailwind.
Example:
.bg-pattern-graph-paper { ... } .skew-45 { ... }
Tailwind swaps all these directives out at build time and replaces them with the CSS generated.
Configure your app to build your CSS file
To configure your app to use CRACO to build your styles every time you run the
npm start or
yarn start command, open your
package.json file and replace the content of
"scripts" with:
"scripts": { "build:style": "tailwind build src/styles/index.css -o src/styles/tailwind.css", "start": "craco start", "build": "craco build", "test": "craco test", "eject": "react-scripts eject" },
To import your CSS to the app, open your
index.js file and import your Tailwind styles:
import './styles/tailwind.css';
Delete the
index.css and
app.css files in your projects root directory and remove their corresponding import statements in the
Index.js and
App.js files, respectively.
Your
index.js file should look similar to this:
// index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import reportWebVitals from './reportWebVitals';
After deletion, it should become:
//index.js import React from 'react'; import ReactDOM from 'react-dom'; import './styles/tailwind.css'; import App from './App'; import reportWebVitals from './reportWebVitals';
Your
App.js file should look like this before deletion:
//App.js import logo from './logo.svg'; import './App.css';
After deletion, it should become:
//App.js import logo from './logo.svg';
These changes would cause an output similar to this:
Testing your Tailwind CSS configurations
To test that our configurations work correctly, let’s create a simple sign-in form.
Open your
App.js file and replace the content between the return function with the following:
<section className="App h-screen w-full flex justify-center items-center bg-green-500"> ="[email protected]" /> <> </section>
We gave the paren
section width of
100% with
w-full. We also gave it a vertical height of
100vh with
h-screen. Then we gave the element a display property of
flex and aligned it to the center vertically and horizontally with
justify-center and
items-center.
We gave the child
div a width of
100% with
w-full and set the max-width with
max-w-md for medium screens and larger.
We gave the form a white background with
bg-white and a border radius to achieve the curved borders with
border.
px-8 and
py-8 add a padding of
8px to the
x-axis and
y-axis, respectively, while
pt-8 adds a padding of
8px to the top of the form.
We added a
font-size of
.875rem to the label element with
text-sm, gave the element reviewed how to configure Create React App to use Tailwind CSS. Tailwind has awesome documentation. Check it out for more information. You can also access the code used in this tutorial.
21 Replies to “How to use Tailwind CSS in React to configure…”
Hello there,
Thank you for your grate article.
After following your article, I wanted to try this:
But for some reason, it does not work properly.
I’ve also tried it in your codesanbox, but with no luck as well.
Do you know how to fix this?
Best,
Manu
Hey btw for this “`”scripts”: {
“build:style”:”tailwind build src/styles/index.css -o src/styles/tailwind.css”,
“start”: “npm run build:style && react-scripts start”,
“build”: “react-scripts build”,
“test”: “react-scripts test”,
“eject”: “react-scripts eject”
},“` You still have npm instead of using yarn.
Thanks a lot for the tutorial! Very helpful!
Hi!
Thanks for the tutorial.
One thing that might be nice to add is if you want to generate styles based on the taildwind config file, the build:style should be changed to:
“build:style”: “tailwind build src/styles/index.css -c tailwind.js -o src/styles/tailwind.css”,
Hi! Thanks a lot.. It was helpful to setup tailwind package vey easily by following those steps.
Hi Dennis,
I don’t find any difference in using “tailwind build src/styles/index.css -o src/styles/tailwind.css” instead of what you have above said. Is there any hidden difference could you explain?
Thanks for the tip! This helped a lot.
I was scratching my head because `tailwindcss(‘./tailwind.js’)` in `postcss.config.js` looked like it should work. But that doesn’t work. Maybe they updated the API?
The file should look like this:
“`
// postcss.config.js
module.exports = {
plugins: [require(“tailwindcss”), require(“autoprefixer”)]
};
“`
Also, making `@import` didn’t get me anywhere. I thought maybe I should go that route, but if you’re having trouble getting the tutorial to work I’d updated the build style and update `postcss.config.js` to what I have above first.
If you want to play with modifying the configuration in a sandbox environment, I made one based on this tutorial here:
I had to make it using a container environment based on the node template.
I hope this helps!
Really great article – thank you Anjolaoluwa
Really great article
Sorry if I’m wrong, isn’t the script “build:style” should be using “postcss” instead of “tailwind”?
This is a much easier way to do it
should we ignore tailwind.css file in gitignore?
You have to add it to your tailwind config. If you want to do the styling for a background add it like below. Not the extra key ‘group’ added to the variants.
module.exports = {
// …
variants: {
backgroundColor: [‘responsive’, ‘hover’, ‘focus’, ‘group’],
},
}
Followed all the steps, then yarn start.
and I am stuck with this in terminal:
$ yarn start
yarn run v1.19.2
$ npm run watch:css && react-scripts start
> postcss src/styles/tailwind.css -o src/styles/app.css -w
//My app.css has been populated but the app is not starting.
//Compiled succesfully message is not showing.
Will this work after eject? How do you load the new UI components? …
Just asking. I honestly got no idea – which is why I prefer things being implemented in a more controlled way.
I think you don’t have to eject the script instead use react-app-rewired more info available here
I have configured tailwind using react-app-rewired
this is my configuration :
const tailwindcss = require(‘tailwindcss’);
module.exports = config => {
require(‘react-app-rewire-postcss’)(config, {
plugins: loader => [
tailwindcss(‘./tailwind.js’),
require(‘autoprefixer’)
]
});
return config;
};
This way your css won’t update when you run it with npm start as it is compiled only once.
Use npm-run-all (npm install –save-dev npm-run-all) and change your scripts in package.json to run both css watcher and react project paralell (the “run-p” means run paralell).
“build:tailwind”: “postcss src/tailwind.css -o src/tailwind.generated.css”,
“watch:tailwind”: “postcss -w src/tailwind.css -o src/tailwind.generated.css”,
“start”: “run-p watch:tailwind start:react”,
“start:react”: “react-scripts start”,
Thanks OP! Wonderful article. The code snippet in the end, `sectiom` has a typo. Should be `section`.
Also, since @tailwind base; @tailwind components; @tailwind utilities; are being imported on the index.css file, index.js must import index.css instead of tailwind.css for the example to work. Thank you!
If ever I needed something to remind me how ludicrously complex React/frond-end development has become this has to be it. So many fragile pieces tied together with duct tape. I need to get back to being productive with Rails or Golang or something. Even Java is better than this.
worked for me fine, no issues, thanks man, elMozat from Ghana
|
https://blog.logrocket.com/tailwind-css-configure-create-react-app/
|
CC-MAIN-2022-40
|
refinedweb
| 2,176
| 58.38
|
This doc covers implementation details of the recipe engine and its processes. Read this if you want to understand/modify how the recipes as a system work. For general recipe development, please see user_guide.md.
All recipe engine subcommands live in the commands folder. The
__init__.py file here contains the entry point for all subcommand parsing
parse_and_run which is invoked from main.py.
The commands module contains (as submodules) all of the subcommands that the recipe engine supports. The protocol is pretty simple:
The subcommand lives in a submodule (either directory or .py file).
Each submodule has a
add_arguments(parser) function (for directories, this is expected to be in the
__init__.py file).
Each submodule may also define an optional
__cmd_priority__ field. This should be an integer which will be used to rank commands (e.g. so that ‘run’ and ‘test’ can precede all other subcommands). Commands will be ordered first by cmd_priority (lower values sort earlier) and then alphabetically. This is currently used to put
run and
test as the topmost arguments in the
recipes.py help output.
The
add_arguments function takes an argparse parser, and adds flags to it. The parser will be created:
__doc__to generate both the description and ‘help’ for the parser (help will be the first paragraph of
__doc__).
In addition to adding flags, the function must also call:
parser.set_defaults( postprocess_func=function(error, args), # optional func=function(args)) # required
Where the ‘args’ parameter is the parsed CLI arguments and ‘error’ is the function to call if the preconditions for the subcommand aren't met.
postprocess_func should do any post-CLI checks and call
error(msg) if the checks don‘t pass. Most subcommands don’t need this, but it's a nice way to verify preconditions for the command.
func executes the actual subcommand.
The reason for this structure is so that the actual
func can do lazy importing; this is necessary if the subcommand requires protobufs to operate correctly (which are only available after the CLI has successfully parsed).
All commands have
args.recipe_deps, which is the resolved RecipeDeps instance to use.
This section talks about how the recipe engine gets from the recipes.py command invocation to the point where it begins executing the recipe.
Recipes have a bit of an interesting multi-step loading process, though it has gotten simpler over the years.
Every recipe repo has at least two things:
recipes.pyscript (which is a literal copy of recipes.py).
recipes.cfgconfig file located at
//infra/config/recipes.cfg
The recipes.cfg contains a field
recipes_path (aka
$recipes_path for this doc) which is a path inside the repo of where the following can exist:
recipesfolder - contains entry point scripts (recipes) for the repo.
recipe_modulesfolder - contains modules which may be depended on (used by) both recipe scripts as well as other modules (in this repo and any other repos which depend on it).
Additionally,
recipes.cfg describes dependencies with a git URL, commit and fetch ref.
When a dev runs
recipes.py in their repo (their repo‘s copy of recipes.py), it will find and parse the repo’s
recipes.cfg file, and identify the version of the
recipe_engine repo that the repo currently depends on.
It will then bootstrap (with git) a clone of the recipe engine repo in the repo‘s
$recipes_path/.recipe_deps/recipe_engine folder, and will invoke main.py in that clone with the
--package argument pointing to the absolute path of the repo’s recipes.cfg file.
Once
main.py is running, it parses the
-O overrides and the
--package flags, and builds a RecipeDeps object which owns the whole
$recipes_path/.recipe_deps folder. Constructing this object includes syncing (with git) all dependencies described in
recipes.cfg. Every dependency will be checked out at
$recipes_path/.recipe_deps/$dep_name.
When dependencies are overridden on the command line with the
-O flag, the path specified for the dependency is used verbatim as the root of that dependency repo; no git operations are performed.
This is the mechanism that the
recipes.py bundle command employs to make a hermetic recipe bundle; it generates a
recipes script which passes
-O flags for ALL dependencies, causing the engine to run without doing any git operations.
The
RecipeDeps object also traverses (by scanning the checked-out state) all the dependent repos to find their recipes and recipe_modules. It does not yet read the code inside the files.
At this point, the chosen recipe subcommand's main function (e.g. [
run], [
test], etc.) executes with the loaded
RecipeDeps object, as well as any other command-line flags the subcommand has defined.
Some commands just work on the structure of the
RecipeDeps object, but most will need to actually parse the recipe code from disk (e.g. to run it in one form or another).
The recipe engine facilitates the use of protobufs with builtin
protoc capabilities. This is all implemented in proto_support.py.
recipes.py bundlegenerates so that builders don’t need to do any
protocactivity on their startup.
Due to the nature of .proto imports, the generated python code (specifically w.r.t. the generated
import lines), and the layout of recipes and modules (specifically, across multiple repos), is a bit more involved than just putting the .proto files in a directory, running ‘protoc’ and calling it a day.
After loading all the repos, the engine gathers and compiles any
.proto files they contain into a single global namespace. The recipe engine looks for proto files in 4 places in a repo:
recipe_modulesdirectory
recipe_modules/$repo_name/*.
recipesdirectory
recipes/$repo_name/*.
recipe_enginedirectory (only in the actual
recipe_enginerepo).
recipe_engine/*.
recipe_protodirectory (adjacent to the ‘recipes’ and/or ‘recipe_modules’ directories).
recipe_engine,
recipesor
recipe_modulessubdirectories.
While the engine gathers all the proto files, it sorts them and generates a checksum of their contents. This is a SHA2 of the following:
RECIPE_PB_VERSION|
NUL- The version of the recipe engine's compilation algorithm.
PROTOC_VERSION|
NUL- The version of the protobuf library/compiler we're using.
repo_name|
NUL- The name of the repo.
Then, for every .proto in the repo we hash:
relative_path_in_repo|
NUL
relative_path_of_global_destination|
NUL
githash_of_content|
NUL
The
githash_of_content is defined by git's “blob” hashing scheme (but is currently implemented in pure Python).
Once we‘ve gathered all proto files and have computed the checksum, we verify the checksum against
.recipe_deps/_pb/PB/csum. If it’s the same, we conclude that the currently cached protos are the same as what we're about to compile.
If not, we copy all protos to a temporary directory reflecting their expected structure (see remarks about “global namespace” above). This structure is important to allow
protoc to correctly resolve
import lines in proto files, as well as to make the correct python import lines in the generated code.
Once the proto files are in place, we compile them all with
protoc into another tempdir.
We then rewrite and rename all of the generated
_pb2 files to change their import lines from:
from path.to.package import blah_pb2 as <unique_id_in_file>
to:
from PB.path.to.package import blah as <unique_id_in_file>
And rename them from
*_pb2 to
*. We also generate empty
__init__.py files.
After this, we write
csum, and do a rename-swap of this tempdir to
.recipe_deps/_pb/PB. Finally, we put
.recipe_deps/_pb onto
sys.path.
Modules are loaded by calling the
RecipeModule.do_import() function. This is equivalent in all ways to doing:
from RECIPE_MODULES.repo_name import module_name
For example:
from RECIPE_MODULES.depot_tools import gclient
This import magic is accomplished by installing a PEP302 ‘import hook’ on
sys.meta_path. The hook is implemented in recipe_module_importer.py. Though this sounds scary, it‘s actually the least-scary way to implement the recipe module loading system, since it meshes with the way that python imports are actually meant to be extended. You can read PEP302 for details on how these hooks are meant to work, but the TL;DR is that they are an object with two methods,
find_module and
load_module. The first function is responsible for saying "Yes! I know how to import the module you’re requesting", or “No, I have no idea what that is”. The second function is responsible for actually loading the code for the module and returning the module object.
Our importer behaves specially:
RECIPE_MODULES- Returns an empty module marked as a ‘package’ (i.e., a module with submodules).
RECIPE_MODULES.repo_name- Verifies that the given project actually exists in
RecipeDeps, then returns an empty module marked as a ‘package’.
RECIPE_MODULES.repo_name.module_name- Verifies that the given module exists in this project, then uses
imp.find_moduleand
imp.load_moduleto actually do the loading. These are the bog-standard implementations for loading regular python modules. Additionally, we run a
patchupfunction on this module before returning it.
RECIPE_MODULES.repo_name.module_name....- All submodules are imported without any alteration using
imp.find_moduleand
imp.load_module.
The “patchup” we do to the recipe module adds a few extra attributes to the loaded module:
NAME- The short name of the module, e.g. “buildbucket”.
MODULE_DIRECTORY- A recipe
Pathobject used by the
api.resource()function present on RecipeApi subclasses indirectly (see next item). AFAIK, nothing actually uses this directly, but “it seems like a good idea”.
module.__file__instead.
RESOURCE_DIRECTORY- A recipe
Pathobject used by the
api.resource()function present on RecipeApi subclasses.
module.__file__instead.
REPO_ROOT- The Path to the root of the repo for this module, used by the
api.repo_resource()method.
CONFIG_CTX- The
ConfigContextinstance defined in the module's config.py file (if any).
DEPS- The DEPS list/dictionary defined in the module‘s
__init__.pyfile (if any). This is populated with
()if
__init__.pydoesn’t define it.
API- The
RecipeApiPlainsubclass found in the api.py file.
TEST_API- The
RecipeTestApisubclass found in the test_api.py file (if any).
PROPERTIES- This finds the
PROPERTIESdict in
__init__.pyand preprocesses it to ‘bind’ the property objects with the module name. These bound property objects will be used later when the recipe module is instantiated.
These patchup features are probably actually bugs/relics of the way that the module loading system used to work; it would be good to minimize/remove these over time.
Recipe loading is substantially simpler than loading modules. The recipe
.py file is exec‘d with
execfile, and then it’s PROPERTIES dict (if any) is bound the same way as it is for Recipe Modules.
Now that we know how to load the code for modules and recipes, we need to actually instantiate them. This process starts at the recipe‘s
DEPS description, and walks down the entire DEPS tree, instantiating recipe modules on the way back up (so, they’re instantiated in topological order from bottom to top of the dependency tree).
Instantiation can either be done in ‘API’ mode or ‘TEST_API’ mode. ‘API’ mode is to generate the
api object which is passed to
RunSteps. ‘TEST_API’ mode is to generate the
api object which is passed to
GenTests. Both modes traverse the dependency graph the same way, but ‘API’ mode does a superset of the work (since all
RecipeApi objects have a reference to their
test_api as
self.test_api).
Both
RecipeTestApi and
RecipeApiPlain classes have an
m member injected into them after construction, which contains all of the DEPS'd-in modules as members. So if a DEPS entry looks like:
DEPS = [ "some_repo_name/module", "other_module", ]
Then the
api and
test_api instances will have an ‘m’ member which contains
module and
other_module as members, each of which is an instance of their respective instantiated
api class.
As the loader walks up the tree, each recipe module's
RecipeTestApi (if any) subclass is instantiated by calling its
__init__ and then injecting its
m object.
If the loader is in ‘API’ mode, then the module‘s RecipeApiPlan subclass is also instantiated, using the declared PROPERTIES as arguments to init, along with
test_data, which may be provided if the
api is being used from the
recipes.py test subcommand to provide mock data for the execution of the test. The
m object is injected, and then any
_UnresolvedRequirement objects are injected as well. Finally, after
m has been injected and all
_UnresolvedRequirement objects are injected, the loader calls the instance’s
initialize() method to allow it to do post-dependency initialization.
_UnresolvedRequirementobjects are currently only used to provide limited ‘pinhole’ interfaces into the recipe engine, such as the ability to run a subprocess (step), or get access to the global properties that the recipe was started with, etc. Typically these are only used by a single module somewhere in the
recipe_enginerepo; user recipe modules are not expected to use these.
This section talks about the code that implements the test command of recipes.py.
As part of the definition of a simulation test, the user can add post-process hooks to filter and/or make assertions on the expectations recorded for the test run. Hooks can be added using either the
post_process or
post_check methods of RecipeTestApi. The code that runs these hooks as well as the implementation of the
check callable passed as the first argument to hooks is located in magic_check_fn.py.
The
check callable passed to post-process hooks is an instance of
Checker. The
Checker class is responsible for recording failed checks, including determining the relevant stack frames to be included in the failure output.
The
Checker is instantiated in
post_process and assigned to a local variable. The local variable is important because the
Checker object uses the presence of itself in the frame locals to define the boundary between engine code and post-process hook code. In the event of a failure, the
Checker iterates over the stack frames, starting from the outermost frame and proceeding towards the current execution point. The first frame where the
Checker appears in the frame locals is the last frame of engine code and the relevant frames begin starting at the next frame and excluding the 2 innermost frames (the
__call__ method calls
_call_impl which is where the frame walking takes place.
Failures may also be recorded in the case of a KeyError. KeyErrors are caught in
post_process and the frames to be included in the failure are extracted from the exception info.
Once relevant frames are determined by
Checker or
post_process,
Check.create is called to create a representation of the failure containing processed frames. The frames are converted to
CheckFrame, a representation that holds information about the point in code that the frame refers to without keeping all of the frame locals alive.
Processing a frame involves extracting the filename, line number and function name from the frame and where possible reconstructing the expression being evaluated in that frame. To reconstuct the expression,
CheckFrame maintains a cache that maps filename and line number to AST nodes corresponding to expressions whose definitions end at that line number. The end line is the line that will appear as the line number of a frame executing that expression. The cache is populated by parsing the source code into nodes and then examining the nodes. Nodes that define expressions or simple statements (statements that can‘t have additional nested statements) are added to the cache. Other statements result in nested statements or expressions being added to the queue. When a simple statement or expression is added to the cache, we also walk over all of its nested nodes to find any lambda definitions. Lambda definitions within a larger expression may result in line numbers in an execution frame that doesn’t correspond with the line number of the larger expression, so in order to display code for frames that occur in lambdas we add them to the cache separately.
In the case of the innermost frame, the
CheckFrame also includes information about the values of the variables and expressions relevant for determining the exact nature of the check failure.
CheckFrame has a varmap field that is a dict mapping a string representation for a variable or expression to the value of that variable or expression (e.g. ‘my_variable’ -> ‘foo’). The expression may not be an expression that actually appears in the code if the expression would actually be more useful than the actual expression in the code (e.g.
some_dict.keys() will appear if the call
check('x' in some_dict) fails because the values in
some_dict aren't relevant to whether
'x' is in it). This varmap is constructed by the
_checkTransformer class, which is a subclass of
ast.NodeTransformer.
ast.NodeTransformer is an instance of the visitor design pattern containing methods corresponding to each node subclass. These methods can be overridden to modify or replace the nodes in the AST.
_checkTransformer overrides some of these methods to replace nodes with resolved nodes where possible. Resolved nodes are represented by
_resolved, a custom node subclass that records a string representation and a value for a variable or expression. It also records whether the node is valid. The node would not be valid if the recorded value doesn't correspond to the actual value in the code, which is the case if we replace an expression with an expression more useful for the user (e.g. showing only the keys of a dict when a membership check fails). The node types handled by
_checkTransformer are:
Namenodes correspond to a variable or constant and have the following fields:
id- string that acts as a key into one of frame locals, frame globals or builtins If
idis one of the constants
True,
Falseand
Nonethe node is replaced with a resolved node with the name of the constant as the representation and the constant itself as the value. Otherwise, if the name is found in either the frame locals or the frame globals, the node is replaced with a resolved node with
idas the representation and the looked up value as the value.
Attributenodes correspond to an expression such as
x.yand have the following fields:
value- node corresponding to the expression an attribute is looked up on (
x)
attr- string containing the attribute to look up (
y) If
valuerefers to a resolved node, then we have been able to resolve the preceding expression and so we replace the node with a resolved node with the value of the lookup.
Comparenodes correspond to an expression performing a series of comparison operations and have the following fields:
left- node corresponding the left-most argument of the comparison
ops- sequence of nodes corresponding to the comparison operators
cmps- sequence of nodes corresponding to the remaining arguments of the comparison The only change we make to
Comparenodes is to prevent the full display of dictionaries when a membership check is performed; if the expression
x in yfails when y is a dict, we do not actually care about the values of
y, only its keys. If
opshas only a single element that is an instance of either
ast.Inor
ast.NotInand
cmpshas only a single element that is a resolved node referring to a dict, then we make a node that replaces the
cmpswith a single resolved node with the dict‘s keys as its value. The new resolved node is marked not valid because we wouldn’t expect operations that work against the dict to necessarily work against its keys.
Subscriptnodes correspond to an expression such as
x[y]and contains the following fields:
value- node corresponding to the expression being indexed (
x)
slice- node corresponding to the subscript expression (
y), which may be a simple index, a slice or an ellipsis If
valueis a valid resolved node and
sliceis a simple index (instance of
ast.Index), then we attempt to create a resolved node with the value of the lookup as its value. We don‘t attempt a lookup if the
valueis an invalid resolved node because we would expect the lookup to raise an exception or return a different value then the actual code would. In the case that we do perform the lookup, it still may fail (e.g.
check('x' in y and y['x'] == 'z')when ‘x’ is not in
y). If the lookup fails and
valueis a dict, then we return a new invalid resolved node with the dict’s keys as its value so that the user has some helpful information about what went wrong.
The nodes returned by the transformer are walked to find the resolved nodes and the varmap is populated mapping the resolved nodes' representations to their values that have been rendered in a user-friendly fashion.
Once the recipe is loaded, the running subcommand (i.e.
run,
test,
luciexe) selects a StreamEngine and a StepRunner. The StreamEngine is responsible for exporting the state of the running recipe to the outside world, and the StepRunner is responsible for running steps (or simulating them for tests).
Once the subcommand has selected the relevant engine and runner, it then hands control off to
RecipeEngine.run_steps, which orchestrates the actual execution of the recipe (namely; running steps, handling errors and updating presentation via the StreamEngine).
The StreamEngine's responsibility is to accept reports about the UI and data export (“output properties”) state of the recipe, and channel them to an appropriate backend service which can render them. The UI backend is the LUCI service called “Milo”, which runs on.
There are 2 primary implementations of the StreamEngine; one for the old
@@@annotation@@@ protocol, and another which directly emits build.proto via logdog.
The entire recipe engine was originally written to support the
@@@annotation@@@ protocol, and thus StreamEngine is very heavily informed by this. It assumes that all data is ‘append only’, and structures things as commands to a backend, rather than setting state on a persistent object and assuming that the StreamEngine will worry about state replication to the backend.
The ‘build.proto’ (LUCI) engine maps the command-oriented StreamEngine interface onto a persistent
buildbucket.v2.Build protobuf message, and then replicates the state of this message to the backend via ‘logdog’ (which is LUCI's log streaming service).
Going forward the plan is to completely remove the
@@@annotation@@@ engine in favor of the LUCI engine.
The StepRunner's responsibility is to translate between the recipe and the operating system (and by extension, anything outside of the memory of the process executing the recipe). This includes things like mediating access to the filesystem and actually executing subprocesses for steps. This interface is currently an ad-hoc collection of functions pertaining to the particulars of how recipes work today (i.e. the
placeholder methods returning test data).
There are two implementations of the StepRunner; A “real” implementation and a “simulation” implementation.
The real implementation actually talks to the real filesystem and executes subprocesses when asked for the execution result of steps.
The simulation implementation supplies responses to the RecipeEngine for placeholder test data and step results.
One feature of the StepRunner implementations is that they don‘t raise exceptions; In particular the ‘run’ function should return an ExecutionResult even if the step crashes, doesn’t exist or whatever other terrible condition it may have.
Within a chunk of recipe user code, steps are executed sequentially. When a step runs (i.e. the recipe user code invokes
api.step(...)), a number of things happens:
step_streamwith the StreamEngine so the UI knows about the step.
ok_retand
infra_step.
If an exception is raised during this process it's logged (to
$debug) and then saved while the engine does the final processing.
Currently, when a step has finished execution, its
step_stream is kept open and the step is pushed onto a stack of
ActiveSteps. Depending on the configuration of the step (
ok_ret,
infra_step, etc.) the engine will raise an exception back into user code. If something broke while running the step (like a bad placeholder, or the user asked to run a non-executable file... you know, the usual stuff), this exception will be re-raised after the engine finalizes the StepData, and sets up the presentation status (likely, “EXCEPTION”).
However, the step remains open until the next step runs!
The step's presentation can be accessed, and modified in a couple ways:
api.step()
api.step.active_resultproperty.
The first one isn't too bad, but the last two are pretty awful. This means that a user of your module function can get access to your step result and:
|
https://chromium.googlesource.com/infra/luci/recipes-py.git/+/9fb81f7e911877991cc908a63d59ab515707fe54/doc/implementation_details.md
|
CC-MAIN-2021-49
|
refinedweb
| 4,034
| 54.22
|
When I first started running my system I kept the execution process extremely simple:
- Check that the best bid (if selling) or best offer (if buying) was large enough to absorb my order
- Submit a market order
Yes, what a loser. Since I am trading futures, and my broker only has fancy orders for equities, this seemed the easiest option.
I then compounded my misery by creating a nice daily report to tell me how much each trade had cost me. Sure enough most of the time I was paying half the inside spread (the difference between the mid price, and the bid or offer).
After a couple of months of this, and getting fed up with seeing this report add up my losses from trading every day, I decided to bite the bullet and do it properly.
Creating cool execution algorithms (algos) isn't my area of deep expertise, so I had to work from first principles. I also don't have much experience of writing very complicated fast event driven code, and I write in a slowish high level language (python). Finally my orders aren't very large, so there is no need to break them up into smaller slices and track each slice. All this points towards a simple algo being sufficient.
Only one more thing to consider; I get charged for modifying orders. It isn't a big cost, and its worth much less than the saving from smarter execution, but it still means that creating an algo that modifies orders an excessive number of times where this is not necessary probably isn't worth the extra work or cost.
Finally I can't modify a limit order and turn it into a market order. I would have to cancel the order and submit a new one.
What does it do?A good human trader, wanting to execute a smallish buy order and not worrying about game playing or spoofing etc, will probably do something like this:
- Submit a limit order, on the same side of the spread they want to trade, joining the current level. So if we are buying we'd submit a buy at the current best bid level. In the jargon this is passive behaviour, waiting for the market to come to us.
- In an ideal world this initial order would get executed.We'll have gained half the spread in negative execution cost (comparing the mid versus the best bid).
- If:
- the order isn't being executed after several minutes,
- or there are signs the market is about to move against them, and rally
- or the market has already moved up against them
- ... then the smart trader would cut their losses and modify their order to pay up and cross the spread. This is aggressive behaviour.
- The new modified aggressive order would be a buy at the current best offer. In theory this would then be executed, costing half the spread (which if the market has already moved against us, would be more than if we'd just submitted a market order initially).
- If we're too slow and the market continues to move against us, keep modifying the order to stay on the new best offer, until we're all done
Although that's it in a nutshell there are still a few bells and whistles in getting an algo like this to work, and in such a way that it can deal robustly with anything that gets thrown at it. Below is the detail of the algo. Although this is shown as python code, its not executable since I haven't included many of the relevant subroutines. However it should give you enough of an idea to code something similar up yourself.
Pre tradeIt's somewhat dangerous dropping an algo trade into the mix if the market isn't liquid enough; this routine checks that.
pretrademultiplier=4.0
def EasyAlgo_pretrade(ctrade, contract, dbtype, tws):
"""
Function easy algo runs before getting a new order
ctrade: The proposed trade, an signed integer
contract: object indicating what we are trading
dbtype, tws: handles for which database and tws API server we are dealing with here.
Returns integer indicating size I am happy with
Zero means market can't support order
"""
## Get market data (a list containing inside spread and size)
bookdata=get_market_data(dbtype, tws, contract, snapshot=False, maxstaleseconds=5, maxwaitseconds=5)
## None means the API is not running or the market is closed :-(
if bookdata is None:
return (0, bookdata)
## Check the market is liquid; the spread and the size have to be within certain limits. We use a multiplier because we are less discerning with limit orders - a wide spread could work in our favour!
market_liquid=check_is_market_liquid(bookdata, contract.code, multiplier=pretrademultiplier)
if not market_liquid:
return (0, bookdata)
## If the market is liquid, but maybe the order is large compared to the size on the inside spread, we can cut it down to fit the order book.
cutctrade=cut_down_trade_to_order_book(bookdata, ctrade, multiplier=pretrademultiplier)
return (cutctrade, bookdata)
New orderNot just one of the best bands in the eighties, also the routine you call when a new order request is issued by the upstream code.
MAX_DELAY=0.03
def EasyAlgo_new_order(order, tws, dbtype, use_orderid, bookdata):
"""
Function easy algo runs on getting a new order
Args:
order - object of my order type containing the required trade
tws - connection object to tws API for interactive brokers
dbtype - database we are accessing
use_orderid- orderid
bookdata- list containing best bid and offer, and relevant sizes
"""
## The s, state, variable is used to ensure that log messages and diagnostics get saved right. Don't worry too much about this
log=logger()
diag=diagnostic(dbtype, system="algo", system3=str(order.orderid))
s=state_from_sdict(order.orderid, diag, log)
## From the order book, and the trade, get the price we would pay if aggressive (sideprice) and the price we pay if we get passive (offsideprice)
(sideprice, offsideprice)=get_price_sides(bookdata, order.submit_trade)
if np.isnan(offsideprice) or offsideprice==0:
log.warning("No offside / limit price in market data so can't issue the order")
return None
if np.isnan(sideprice) or sideprice==0:
log.warning("No sideprice in market data so dangerous to issue the order")
return None
## The order object contains the price recorded at the time the order was generated; check to see if a large move since then (should be less than a second, so unlikely unless market data corrupt)
if not np.isnan(order.submit_price):
delay=abs((offsideprice/order.submit_price) - 1.0)
if delay>MAX_DELAY:
log.warning("Large move since submission - not trading a limit order on that")
return None
## We're happy with the order book, so set the limit price to the 'offside' - best offer if selling, best bid if buying
limitprice=offsideprice
## We change the order so its now a limit order with the right price
order.modify(lmtPrice = limitprice)
order.modify(orderType="LMT")
## Need to translate from my object space to the API's native objects
iborder=from_myorder_to_IBorder(order)
contract=Contract(code=order.code, contractid=order.contractid)
ibcontract=make_IB_contract(contract)
## diagnostic stuff
## its important to save this so we can track what happened if orders go squiffy (a technical term)
s.update(dict(limit_price=limitprice, offside_price=offsideprice, side_price=sideprice,
message="StartingPassive", Mode="Passive"))
timenow=datetime.datetime.now()
## The algo memory table is used to store state information for the algo. Key thing here is the Mode which is PASSIVE initially!
am=algo_memory_table(dbtype)
am.update_value(order.orderid, "Limit", limitprice)
am.update_value(order.orderid, "ValidSidePrice", sideprice)
am.update_value(order.orderid, "ValidOffSidePrice", offsideprice)
am.update_value(order.orderid, "Trade", order.submit_trade)
am.update_value(order.orderid, "Started", date_as_float(timenow))
am.update_value(order.orderid, "Mode", "Passive")
am.update_value(order.orderid, "LastNotice", date_as_float(timenow))
am.close()
## Place the order
tws.placeOrder(
use_orderid, # orderId,
ibcontract, # contract,
iborder # order
)
## Return the order upstream, so it can be saved in databases etc. Note if this routine terminates early it returns a None; so the upstream routine knows no order was placed.
return order
Action on tickA tick comes from the API when any part of the inside order book is updated (best bid or offer, or relevant size).
Within the tws server code I have a routine that keeps marketdata (a list with best bid and offer, and relevant sizes) up to date as ticks arrive, and then calls the relevant routine.
What does this set of functions do?
- If we are in a passive state (the initial state, remember!)
- ... and more than five minutes has elapsed, change to aggressive
- if buying and the current best bid has moved up from where it started (an adverse price movement), change to aggressive
- if selling, and the current best offer has moved down from where it started (also adverse)
- If there is an unfavourable order imbalance (eg five times as many people selling than buying on the inside spread if we're also selling), change to aggressive.
- If we are in an aggressive state
- ... and more than ten minutes has elapsed, cancel the order.
- if buying and the current best offer has moved up from where it was last (a further adverse price movement), then update our limit to the new best offer (chase the market up).
- if selling and the current best bid has moved down from where it was last (a further adverse price movement), then update our limit to the new best offer
passivetimelimit=5*60 ## max five minutes
totaltimelimit=10*60 ## max another five minute aggressive
maximbalance=5.0 ## amount of imbalance we can copy with
def EasyAlgo_on_tick(dbtype, orderid, marketdata, tws, contract):
"""
Function easy algo runs on getting a tick
Args:
dbtype, tws: handles for database and tws API
orderid: the orderid that is associated with a tick
marketdata: summary of the state of current inside spread
contract: what we are actually trading
"""
## diagnostic code
log=logger()
diag=diagnostic(dbtype, system="algo", system3=str(int(orderid)))
s=state_from_sdict(orderid, diag, log)
## Pull out everything we currently know about this order
am=algo_memory_table(dbtype)
trade=am.read_value(orderid, "Trade")
current_limit=am.read_value(orderid, "Limit")
Started=am.read_value(orderid, "Started")
Mode=am.read_value(orderid, "Mode")
lastsideprice=am.read_value(orderid, "ValidSidePrice")
lastoffsideprice=am.read_value(orderid, "ValidOffSidePrice")
LastNotice=am.read_value(orderid, "LastNotice")
## Can't find this order in our state database!
if Mode is None or Started is None or current_limit is None or trade is None or LastNotice is None:
log.critical("Can't get algo memory values for orderid %d CANCELLING" % orderid)
FinishOrder(dbtype, orderid, marketdata, tws, contract)
Started=float_as_date(Started)
LastNotice=float_as_date(LastNotice)
timenow=datetime.datetime.now()
## If a buy, get the best offer (sideprice) and best bid (offsideprice)
## If a sell, get the best bid (sideprice) and best offer (offsideprice)
(sideprice, offsideprice)=get_price_sides(marketdata, trade)
s.update(dict(limit_price=current_limit, offside_price=offsideprice, side_price=sideprice,
Mode=Mode))
## Work out how long we've been trading, and the time since we last 'noticed' the time
time_trading=(timenow - Started).total_seconds()
time_since_last=(timenow - LastNotice).seconds
## A minute has elapsed since we
if time_since_last>60:
s.update(dict(message="One minute since last noticed now %s, total time %d seconds - waiting %d %s %s" % (str(timenow), time_trading, orderid, contract.code, contract.contractid)))
am.update_value(orderid, "LastNotice", date_as_float(timenow))
## We've run out of time - cancel any remaining order
if time_trading>totaltimelimit:
s.update(dict(message="Out of time cancelling for %d %s %s" % (orderid, contract.code, contract.contractid)))
FinishOrder(dbtype, orderid, marketdata, tws, contract)
return -1
if not np.isnan(sideprice) and sideprice<>lastsideprice:
am.update_value(orderid, "ValidSidePrice", sideprice)
if not np.isnan(offsideprice) and offsideprice<>lastoffsideprice:
am.update_value(orderid, "ValidOffSidePrice", offsideprice)
am.close()
if Mode=="Passive":
## Out of time (5 minutes) for passive behaviour: panic
if time_trading>passivetimelimit:
s.update(dict(message="Out of time moving to aggressive for %d %s %s" % (orderid, contract.code, contract.contractid)))
SwitchToAggresive(dbtype, orderid, marketdata, tws, contract, trade)
return -1
if np.isnan(offsideprice):
s.update(dict(message="NAN offside price in passive mode - waiting %d %s %s" % (orderid, contract.code, contract.contractid)))
return -5
if trade>0:
## Buying
if offsideprice>current_limit:
## Since we have put in our limit the price has moved up. We are no longer competitive
s.update(dict(message="Adverse price move moving to aggressive for %d %s %s" % (orderid, contract.code, contract.contractid)))
SwitchToAggresive(dbtype, orderid, marketdata, tws, contract, trade)
return -1
elif trade<0:
## Selling
if offsideprice<current_limit:
## Since we have put in our limit the price has moved down. We are no longer competitive
s.update(dict(message="Adverse price move moving to aggressive for %d %s %s" % (orderid, contract.code, contract.contractid)))
SwitchToAggresive(dbtype, orderid, marketdata, tws, contract, trade)
return -1
## Detect Imbalance (bid size/ask size if we are buying; ask size/bid size if we are selling)
balancestat=order_imbalance(marketdata, trade)
if balancestat>maximbalance:
s.update(dict(message="Order book imbalance of %f developed compared to %f, switching to aggressive for %d %s %s" %(balancestat , maximbalance, orderid, contract.code, contract.contractid)))
SwitchToAggresive(dbtype, orderid, marketdata, tws, contract, trade)
return -1
elif Mode=="Aggressive":
if np.isnan(sideprice):
s.update(dict(message="NAN side price in aggressive mode - waiting %d %s %s" % (orderid, contract.code, contract.contractid)))
return -5
if trade>0:
## Buying
if sideprice>current_limit:
## Since we have put in our limit the price has moved up further. Keep up!
s.update(dict(message="Adverse price move in aggressive mode for %d %s %s" % (orderid, contract.code, contract.contractid)))
SwitchToAggresive(dbtype, orderid, marketdata, tws, contract, trade)
return -1
elif trade<0:
## Selling
if sideprice<current_limit:
## Since we have put in our limit the price has moved down. Keep up!
s.update(dict(message="Adverse price move in aggressive mode for %d %s %s" % (orderid, contract.code, contract.contractid)))
SwitchToAggresive(dbtype, orderid, marketdata, tws, contract, trade)
return -1
elif Mode=="Finished":
## do nothing, still have tick for some reason
pass
else:
msg="Mode %s not known for order %d" % (Mode, orderid)
s.update(dict(message=msg))
log=logger()
log.critical(msg)
raise Exception(msg)
s.update(dict(message="tick no action %d %s %s" % (orderid, contract.code, contract.contractid)))
diag.close()
return 0
def SwitchToAggresive(dbtype, orderid, marketdata, tws, contract, trade):
"""
What to do... if we want to eithier change our current order to an aggressive limit order, or move an order is already aggressive limit price
"""
## diagnostics...
log=logger()
diag=diagnostic(dbtype, system="algo", system3=str(int(orderid)))
s=state_from_sdict(orderid, diag, log)
if tws is None:
log.info("Switch to aggressive didn't get a tws... can't do anything in orderid %d" % orderid)
return -1
## Get the last valid side price (relevant price if crossing the spread) as this will be our new limit order
am=algo_memory_table(dbtype)
sideprice=am.read_value(orderid, "ValidSidePrice")
ordertable=order_table(dbtype)
order=ordertable.read_order_for_orderid(orderid)
ordertable.close()
if np.isnan(sideprice):
s.update(dict(message="To Aggressive: Can't change limit for %d as got nan - will try again" % orderid))
return -1
## updating the order
newlimit=sideprice
order.modify(lmtPrice = newlimit)
order.modify(orderType="LMT")
iborder=from_myorder_to_IBorder(order)
ibcontract=make_IB_contract(contract)
am.update_value(order.orderid, "Limit", newlimit)
am.update_value(order.orderid, "Mode", "Aggressive")
am.close()
# Update the order
tws.placeOrder(
orderid, # orderId,
ibcontract, # contract,
iborder # order
)
s.update(dict(limit_price=newlimit, side_price=sideprice,
message="NowAggressive", Mode="Aggresive"))
return 0
def FinishOrder(dbtype, orderid, marketdata, tws, contract):
"""
Algo hasn't worked, lets cancel this order
""" diag=diagnostic(dbtype, system="algo", system3=str(int(orderid)))
s=state_from_sdict(orderid, diag, log) log=logger()
if tws is None:
log.info("Finish order didn't get a tws... can't do anything in orderid %d" % orderid)
return -1
log=logger()
ordertable=order_table(dbtype)
order=ordertable.read_order_for_orderid(orderid)
log.info("Trying to cancel %d because easy algo failure" % orderid)
tws.cancelOrder(int(order.brokerorderid))
order.modify(cancelled=True)
ordertable.update_order(order)
do_order_completed(dbtype, order)
EasyAlgo_on_complete(dbtype, order, tws)
s.update(dict(message="NowCancelling", Mode="Finished"))
am=algo_memory_table(dbtype)
am.update_value(order.orderid, "Mode", "Finished")
am.close()
return -1
Partial or complete fillBlimey this has actually worked, we've actually got a fill...
def EasyAlgo_on_partial(dbtype, order, tws):
diag=diagnostic(dbtype, system="algo", system3=str(int(order.orderid)))
diag.w(order.filledtrade, system2="filled")
diag.w(order.filledprice, system2="fillprice")
return 0
def EasyAlgo_on_complete(dbtype, order_filled, tws):
"""
Function Easy algo runs on completion of trade
"""
diag=diagnostic(dbtype, system="algo", system3=str(int(order_filled.orderid)))
diag.w("Finished", system2="Mode")
diag.w(order_filled.filledtrade, system2="filled")
diag.w(order_filled.filledprice, system2="fillprice")
am=algo_memory_table(dbtype)
am.update_value(order_filled.orderid, "Mode", "Finished")
am.close()
return 0
Hi Rob
I got your book yesterday, I started reading it, it looks very promising, very rarely you see books that mention portfolio optimization for trade systems ( I think only Perry Kaufman has a couple of pages on that)..anyway
I would like to setup an automated platform for trading live and back-testing with python...
for backtesting have you developed your own code? I guess so.I browsed a bit zipline..but I think in the long term it will limit the kind of systems that can be developed...
how would you recommend that a back-test program should be done in python?
Many thanks
Hi
I wrote my own stuff
zipline is interesting as is, and. But I haven't used them. Here is a list
Of course if you dig around my blog you will find advice on the automated trading side.
Unfortunately it would take another book to describe how to develop a back test system yourself.
Mike's book might help you () (tell him I sent you). I haven't read it but it seems to be the only book that tries to attack this.
At some point I'd like to publish a system that people can use, but that project is some way off.
Updated reply: See
You mention that execution costs have come down by 80% versus your earlier market-order strategy. Do you measure these savings relative to the initial mid, or do you update the mid after adverse price movements?
Eg, suppose the market is 99 - 101 and you want to buy. Your new algo would rest at 99 with original mid at 100. The market now moves to 101 - 103. You update to aggressive and get filled at 103. Do you measure your performance relative to a mid of 100 or 102?
80% reduction seems extremely good if measured versus the original mid in futures markets that typically trade at min tick size. Any intuition? Thanks!
It's versus the initial mid of 100; on the assumption that I'd get filled at 101 if I'd just submitted a market order at that point. So I'd pay 103 versus 100; 3 ticks slippage, a market order would have cost me 1 tick slippage.
Hi Robert, I loved your book. Am in its detailed second read now. But n3ed your help: Sharpe or Sortino! Am confused...as Sortino seems obvious given the leeway it has for upside volatility. Yet, everyone seems to prefer, at least publicly, Sharpe; even you. Its easier to calculate can be one--albeit--minor advantage I can see. Kindly show me the light on this one. Thanks!
Yes it's easier to calculate Sharpe. All performance measures have disadvantages; ideally you should use several.
This comment has been removed by the author.
Thanks Rob! 'Use the average' is my new ideology!
I've found your blog unfortunately today, cause you really do a great job sharing intelligent and fundamental principals in this challenge area. Keep your work up
Hi Rob,
It's been a while since you wrote this blog post, but it is as relevant as it ever was. Thank you!
There is something I don't understand, and hope you could explain:
When you only used market orders, you always paid half the inside spread. With the new algo, you start passive, hoping that the market will go in your direction. if it did, you gained half the spread. I figure it is safe to assume that the market is as likely to go in your direction as it is in the opposite direction. Now if it goes against you, then you change to aggressive, and will most likely pay 1.5 of the original spread. Doesn't this leave you with an average execution cost of half the spread, as you paid with market orders?
That would be true if (a) there is a 50% chance of being filled before you change to aggressive and (b) you always get filled immediately with just a one tick move. In practice the average loss is higher than 1.5 times the spread; since sometimes the market keeps moving away and the algo chases it. And fortunately you tend to get passively filled more often than not - I haven't analysed it but perhaps 2/3 of the time.
Hi Rob,
Hope you are well, I am still enjoying very much (re)reading your many posts. I love your execution algo which I think I finally got my head around. A couple of things I don't quite get though:
1. Once you change from passive to aggressive and you are forced to chase the market, wouldn't a marketorder achieve more or less the same outcome?
2. Why is the algo averse to trading when there is no size at your side. If there are bids, no asks and you come in to sell, wouldn't you be ok to place a limit order at the ask?
Sorry for the delay in responding.
1. Yes, but it's not possible to update an order type only the price, so I'd need to cancel the existing order and submit a new market order. This would cost something since I get charged for cancelling orders. But to be fair this might work out cheaper than chasing the market. Definitely something to consider for algo version 2.
2. Yes I guess if the market is 109.00 bid - nothing; then it would make sense to offer 109.01 (or even a cheeky 109.02... or higher). I do store the typical bid-ask spread in my database so in theory this is something I could do.
Thanks v much for getting back to me Rob.
Rob, As a follow up to to my previous questions, I think I now see one of the potential risks of placing an bid when, say there is only an offer in the market. Someone could dangle a minimum sized offer as bait, cross the spread to take your trade and then massively move away from that original offer on the assumption that you or your algo will be forced to chase the market up (which is what your algo might well do if it gets an initial fill). I have almost zero knowledge of execution best practices so apologies for the noob question.
It's always possible for people to game you if they know how your algo works. The more complex and weird your algo is, the more likely this would happen. So I'm not interested in getting into a war with HFT traders as I don't have the weaponry; just doing sensible things and trying not to get picked off.
Hi Rob - Thanks for sharing the passive-aggressive idea.
I am wondering how this 80% performance compares to what we'd get using other loosely similar fancy IB orders, e.g. a trail with amount being half the spread?
No idea as I have never used that order type, not even sure if you can use it in the API. If you can, then I can experiment to check
Seems in theory you can:
But I haven't tried to be honest, that's a bit tricky to backtest.
Hi Rob, Is there any books you suggest for execution algorithm from engineering perspective? what kind of tips and trick you do as you mix the periodically pull and event driven programming model.
Any suggestion?
No I don't know of any, maybe ask on elitetrader.com or nuclearphynance
|
https://qoppac.blogspot.com/2014/10/the-worlds-simplest-execution-algorithim.html
|
CC-MAIN-2021-31
|
refinedweb
| 4,010
| 55.44
|
SysTest quick start
Overview
I am a big fan of TestDrivenDevelopment and I am trying to follow this approach for all my development. Unfortunately DynamicsAX didn't have any UnitTest framework and thus it was difficult to use TestDrivenDevelopment. It was clear that we needed something in DynamicsAX and that's why we now have SysTest.
SysTest
SysTest is a UnitTest framework. If you are familiar with any other UnitTest framework then you will feel comfortable with SysTest.
Main features/goals:
- it is very fast
- it offers rich set of "assert" methods
- it supports tests throwing exceptions (expected exceptions)
- it supports transactions (tests can be placed inside a database transaction that is aborted at the end)
- it supports company accounts (tests can be placed inside a separate company account that is deleted at the end of the test)
- it supports fixture setup and tear down that are called automatically by the framework
- it supports suites of tests
- it supports setup and tear down method for suite that is run before the first method and after the last test method
- it supports suites of suites
- it supports code coverage
- it has a wide variety of listeners for DynamicsAX environment
- toolbar for quick test suite execution
Examples
Let's demonstrate the framework on examples. Let's create a unit test to test int2str conversion method. First we have to create our test class:
public class MySimpleTest extends SysTestCase { }
Now if you use toolbar (Tools > Development Tools > Unit Test > Show toolbar), then enter name of your test MySimpleTest and click Run. You immediately see "0 run, 0 failed". It's that simple. Ok, it maybe simple because it doesn't do much. Let's add a test validating that the function can successfully convert positive and negative numbers. To do so just add new method named with test prefix that is public, returns void and doesn't take any parameter. In the method check all your asserts.
public class MySimpleTest extends SysTestCase { public void testConversion() { this.assertEquals('123', int2str(123)); this.assertEquals('-2', int2str(-2)); } }
When you run the test in a toolbar runner for example you will immediately see "1 run, 0 failed". Great! Let's add more tests to our test class. Let's see how the framework handles tests that throw exceptions but those exceptions are expected. Because of that we don't want to fail the test method. There are two ways to do that. First one is that you will code the exception handling yourself:
public void testExpectedException() { try { throw Exception::Error; } catch(Exception::Error) { return; } this.fail('An expected exception wasn\'t thrown!'); }
As you can see when we expect an exception and it is not thrown then it is considered a failure. SysTest offers a better way to do the same.
public void testExpectedException() { this.parmExceptionExpected(true); throw Exception::Error; }
Exceptions are more complex in DynamicsAX. Usually we don't just throw an error exception but we throw an error message. How do we handle that in SysTest?
public void testExpectedError() { ; this.parmExceptionExpected(true, 'Oops -- error message'); throw error('Oops -- error message'); } }
When you run the test you will get "3 run, 0 failed". Let's now see what happens when a failure occurs. We will begin by adding a failing test.
public void testFailure() { this.assertEquals('0', int2str(123)); }
This is clearly a failing test. When we run the test class now we get "3 run, 1 failed". Toolbar displays all failures in Infolog window. For our test class we would see the following window:
On the other hand we don't have to rely on toolbar. Let's say that we want to see all messages (not just failures) and let's say that we want to write them into DynamicsAX Print window. First let's write our own runner. For a runner we have to specify the whole suite we want to run. That's easy and all you have to do is to create instance of SysTestSuite class and pass your test class name to SysTestSuite constructor. To run the suite call run method. Here is one little problem. Suite itself is not interested in results at all. The problem is that we are and if we want to know the result at the end we have to create special SysTestResult object and pass it to the suite when it runs our test.
public static void main(Args _params) { SysTestSuite suite = new SysTestSuite(classstr(MySimpleTest)); SysTestResult result = new SysTestResult(); ; suite.run(result); print result.getSummary(); }
The code above creates the suite for our test class and executes all the tests. At the end it prints the summary report to the Print window. If we want to print all messages (failures, information, but also when a test is started or completed) then we have to register the corresponding listener.(); }
In total our whole class looks like this:
public class MySimpleTest extends SysTestCase { public void testConversion() { ; this.assertEquals('123', int2str(123)); this.assertEquals('-2', int2str(-2)); } public void testExpectedException() { ; this.parmExceptionExpected(true); throw Exception::Error; } public void testExpectedError() { ; this.parmExceptionExpected(true, 'Oops -- error message'); throw error('Oops -- error message'); } public void testFailure() { ; this.assertEquals('0', int2str(123)); }(); } }
That's all. If you want more information then stay tuned. In the next post I will try to describe individual features of SysTest in more details.
|
https://docs.microsoft.com/en-us/archive/blogs/dpokluda/systest-quick-start
|
CC-MAIN-2020-24
|
refinedweb
| 890
| 65.73
|
I'm filing this bug report from a newsgroup post in mozilla.dev.apps.firefox:
Object.defineProperty(String.prototype, "com_example_bool", {
get : function() {
return (/^(true|1)$/i).test(this);
}
});
alert("true".com_example_bool);
That returns true in Opera, IE9, Chrome Canary and Safari, but returns
false in Firefox (at least latest trunk).
Anyone know why?
A quick investigation shows that in the get() function, uneval(this) gives me:
(new String("")) instead of the "true" string I would expect. I don't think this has anything to do with the regex part of the testcase.
Created attachment 591181 [details]
PASS/FAIL TC
Created attachment 591182 [details]
Pass/Fail TC
System doesn't want to set text/html mime type for the attachment, even if I try explicitly.
Yeah, getters and setters on the boxed-type prototypes get a boxed |this| when invoked through property accesses on primitive values. Known, certainly needs fixing. I'll take this and see what I can do for it.
It returns true now in firefox too.
|
https://bugzilla.mozilla.org/show_bug.cgi?id=720760
|
CC-MAIN-2016-50
|
refinedweb
| 168
| 57.87
|
Domain-Driven Design Demystified
Let's demystify DDD, a software design concept that has long been around and continues to gain traction.
Join the DZone community and get the full member experience.Join For Free
Domain-driven design, or DDD, is a software design methodology aimed at producing better software. Engineers achieve this by working closely with domain experts during the continuous design process.
Eric Evans created domain-driven design and wrote a book about the practice called Domain-Driven Design: Tackling Complexity in the Heart of Software. His main points are to use models, use the language of the business, and follow specific technical patterns during development. Together, these steps will help you deal with complex software without painting yourself into a corner.
In this post, I'll go further into demystifying domain-driven design. First, I'll share a story about how I came to know the practice myself. Then I'll get into some details about the modeling part of the process. Finally, I'll do an overview of the technical bits of the craft.
How I Came to Know Domain-Driven Design
Let me be honest. When I first started hearing the term "DDD," I would smile and nod politely. It was very mysterious to me, and I didn't give it much thought until I got a somewhat polite comment on a TDD post I wrote. The commenter was insisting that domain-driven design was the way to go.
In that TDD post, I took the angle that test-driven development should really be "test-driven design." Sure, there's value in emergent design. But there's value in other methodologies, too. So, being an open-minded, curious person, I just had to know more about domain-driven design. Soon after, I read Evans' book and immediately saw the value in how it solves design problems.
The Design Problem
In software, there are many design problems. And, there are many tools to solve them. For one thing, we have patterns. For another, we have models. Domain-driven design uses these tools and introduces some concepts of its own for dealing with complexity.
But not so fast. What are the problems with complexity?
The Trouble With Complexity
We know intuitively what complexity is. However, it can be relative to each person and environment. A problem may be simple to one person but complex to another.
To quantify complexity, let's think of something with more than three interconnected components and at least five business rules requiring formal definition beyond "required field." Perhaps the problem involves some computations, data transfer, multiple screens, and an external data source. And, speaking of externalities, software is often part of a complex web of interconnected systems. How's that for complexity? Right...it depends. To one developer, this system is complex. But another developer may eat systems like this for lunch!
Domain-driven design is all about how to deal with complexity in software development. Really, this is its value proposition. In contrast, emergent design is useful when the problem is simple. But, when you have complexity, some forethought is needed. See, when there is complexity, it will exist no matter what. You can move the complexity around but you can't eliminate it. And the real trouble comes when you add more complexity.
On the other hand, you can contain the complexity. Domain-driven design contains complexity within "bounded contexts."
Bounded Contexts Contain Two Things
Bounded contexts contain two things: complexity and terminology.
First, bounded contexts are meant to contain complexity. In other words, we can create a bounded context for some specific complex business logic. The bounded context connects to other contexts through adapters. And, those adapters protect against change. When those complexities contained within the context change, the rest of our system doesn't also have to change. That's why we should use adapters to "impedance-match" between contexts.
For another thing, bounded contexts are about defining terminology within the context. For example, the risk management department may think of employees as, well, "employees." But the HR department may call them "personnel." And, of course, the finance department has their own term for them: "labor resources." Whether you love these terms or not, you've got to respect that the same entity has different names in different contexts.
Being a service industry, we IT folks should take the time to learn the language of our customers. When talking to the HR department, we should use the term "personnel." But, when working with finance, we should use "labor resources," even if that makes us cringe slightly. After all, they're just words to us, but in the specific context, those words have meaning. Imagine how you'd feel if a non-developer used the term "unit testing" to mean "functional testing." Could you take that person seriously if they insisted on abusing ubiquitous terminology in such a way? This is why we need to work directly with domain experts-someone working in or with intimate knowledge of the business area.
Model With the Domain Expert
Domain-driven design stresses the importance of working with the business. This is especially so when working on the model. A model is a tool for communication and planning. It can be a simple box-and-line model or a more complex format like UML. In the end, it has to be understood by both the domain expert in the business domain and the engineer(s). Modeling is an important step in communicating the business problem and iterating over solutions.
Note that this type of modeling isn't data modeling. It's also not database design. Data modeling and database design are exercises in defining low-level details. Those generally aren't done in conjunction with the business. Also, this type of modeling isn't object modeling, either. See, object models are implementation details in the same way as database design is.
The modeling in domain-driven design is about creating a model for understanding the business. It can be somewhat abstract, but it must be a shared vision. The goal is to create a joint understanding and facilitate two-way communication between the business and engineering about the business problem. Only then are we truly prepared to get into the technical details.
The Technical Parts
Once the domain is understood well enough, it's time to build the pieces of the puzzle. Evans stresses the importance of change. As implementation happens, new understandings unfold. There may be better ways to solve certain problems. Often, you'll need to make trips back to the modeling board. This is a good thing since those iterations over the model will further improve the design!
Design improvements aside, there are some technical recommendations in domain-driven design. Evans presents many patterns that make the software more resilient to change. A couple of patterns-the adapter pattern and bounded contexts-we've already discussed. Others include the factory pattern and the repository pattern. There are others, but these are the two I'll focus on since they're the most common. Let's check out the factory pattern first.
Factory Pattern
When we need to create some new object, we should use the factory pattern. We don't want every consumer to be concerned with the details of constructing an object of a specific type or sub-type. So, what do we do? We delegate the responsibility to a factory. Sure, we can call the constructor directly, but it's best not to perform too many operations in a constructor. The solution to complex object creation is the factory! (And, by the way, a factory is really useful for containing decisions about which specific type to return.)
A factory can be a static method on the base class, or it can be its own object. The consumer must use the factory to build the object. We can specify this behavior by making the constructor for the class inaccessible to the consumer. The only way to get a new Foo is to call Foo.Build(...params). Then you'd work with the Foo object to do some Foo things:
Foo aFoo = Foo.build(fooData); aFoo.reportHours(7); aFoo.setManager(managerData); Integer aFooId = aFoo.save();
This code calls the factory method to build a Foo. Then, it uses the object to report hours and set the manager. Finally, it saves and gets the id generated from the save. Later, we can use the id to rehydrate a Foo from the saved data.
Rehydrate Using a Repository
A repository is an abstraction of a persistence mechanism. A few common persistence mechanisms are a database, a file, and memory. Basically, the repository represents anything that can save and retrieve the data for the object. All of this happens inside the object or the factory. In this way, a domain class is dependent on the repository.
A domain class is something that represents a real-world concept. It can also be called a domain object. These domain classes are what your application works with. So, how do we rehydrate a domain object using a repository?
Luckily, all that can happen in the factory so it's all nicely contained. Here's a quick look at how you might accomplish this:
Foo aFoo = Foo.Get(aFooId); //---// public class Foo { private Foo(FooData data) { ... } public static Foo Build(FooData data) { return new Foo(data); } public static Foo Get(int id) { var data = ServiceLocator.GetRepository<Foo>().Get(id); if(!data) throw new NoFooFoundException(id); return new Foo(data); } }
You can see that Foo.Get uses a ServiceLocator to get the repository, but that's an implementation detail. You can accomplish the same goal using dependency injection.
You've got to remember that domain-driven design came around more than a decade ago. Since then, our tools have evolved. Even so, there are many important concepts here. One really good takeaway is containing all the code that's primarily responsible for making a Foo. These are important object-oriented programming principles that get cast aside too frequently. When these patterns are missing, a codebase becomes much more difficult to maintain!
In the End, Domain-Driven Design Is About Organization
All the terminology and technical practices add up to one thing in the end — organization. Evans' book carries the subtitle "Tackling Complexity in the Heart of Software" for good reason. Complex software requires special care to advance on the good road ahead. Without it, the project can get bogged down in the mud. The concepts and practices of DDD are a well-thought-out way to manage the complexity. There are others, to be sure, but this one has enough merit that you should pay attention to it! If you haven't read the book yet, I highly recommend grabbing a copy and checking it out.
Published at DZone with permission of Phil Vuollet, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
|
https://dzone.com/articles/domain-driven-design-demystified
|
CC-MAIN-2021-04
|
refinedweb
| 1,832
| 58.99
|
Apache OpenOffice (AOO) Bugzilla – Full Text Issue Listing
I have a java program which uses openoffice to convert files between different
formats.
When I run it OO takes more and more memory for each conversion and doesn't free it.
I have started openoffice with (on linux):
/opt/openoffice.org1.9.74/program/soffice -invisible "-accept=socket,port=8100;urp;"
The java program is as follows:
import net.sf.joott.uno.*;
import java.io.*;
public class Test {
public static void main(String[] a) throws Exception {
UnoConnection conn = DocumentConverterFactory.getConnection();
DocumentConverter conv = new DocumentConverter(conn);
File source = new File("test.ppt");
File dest = new File("test.pdf");
for (int i=0; i<1000; i++) {
conv.convert(source, dest, DocumentFormat.PDF_IMPRESS);
}
}
}
The leak happens with conversions between other formats as well.
I just converted 100 documents from ppt to pdf always ind the sequecence
1. open document
2. export document
3. close document
and I had an increase of memory usage of 10k per document. Don't think this can
be called a memory leak ... what am I missing ? How much memory is kept during
your conversion ? Can you provide a java-program that does all the steps you do,
so rebuilding the behaviour is possible ?
You can find joovonverter at (you need just the jar in the root of the archive):
(jar too big to attach)
1) Compile the program found in the issue with
javac -classpath jooconverter.jar Test.java
2) Run openoffice as in the issue:
/opt/openoffice.org1.9.74/program/soffice -invisible "-accept=socket,port=8100;urp;"
3) Run the java test program with
java -cp jooconverter.jar:.:/opt/openoffice.org1.9.74/program/classes/juh.jar:
/opt/openoffice.org1.9.74/program/classes/jurt.jar:
/opt/openoffice.org1.9.74/program/classes/ridl.jar:
/opt/openoffice.org1.9.74/program/classes/sandbox.jar:
/opt/openoffice.org1.9.74/program/classes/unoil.jar Test
You need to have a file test.ppt in the current directory.
Notice that you need to exit the program with CTRL-C after the conversions are done.
After converting 1000 times memory usage shows for me over 400Mb.
I'll attach the ppt I have used.
Thanks for your quick response.
Created attachment 22049 [details]
File used when testing
I have the same problem (memory leak) with OOo 1.1.2, 1.1.3, and 1.1.4 on
Windows XP Home, Windows XP Professional and Debian Linux.
I wrote a Java application which uses OOo through the Java-UNO-API. The Java
application loads a OOo writer template, replaces several bookmarks, exports the
result as a PDF and closes the document. With every loaded document the used
memory increased and never decreased although I'm very certain that I freed all
used resources.
My luck was that I repeatedly loaded the same documents. So I made a
modification to my program: I load all documents once, and start then the
bookmark replacement and the PDF export. With this modification my Java
application is using a constant amount of memory for over 30000 exported PDF
documents.
I'd like to clarify that I wasn't talking about a leak in my java program, but
in openoffice.
Created attachment 22087 [details]
complex testcase which meassures memory usage on *nix
The attached complex testcase loads a ppt document, exports it to pdf and then
closes the document again. This is done 5 times. Afterwards it measures the
memory usage with the help of "pmap".
To execute it unzip the file memoryTest.zip and change to the appearing folder
memoryTest/complex/memCheck. Now
1. call setsolar in your shell
2. call dmake
3. start the office with the parameters
-invisible "-accept=socket,port=8100;urp;"
4. call dmake run
The testcase allows 20K of additional memory usage, but the src680_m74 consumes
500K per conversion ... so doing 1000 conversions will lead to 500MB.
Remark:
run the test at least twice, since during the first run the memory usage will
increase dramatically due to the fact that the impress libraries are loaded into
memory for the first time.
Sven, is that the memory leak armin just discovered with the autoshapes not
freeing theire SdrObjects?
sj->aw: I think you already fixed this issue in your cws, can you please check
if it is double.
AW->SW: Should be fixed with #i40944# which is in m76, please review there again.
sw->aw: just checked on Solaris with an src680_m76 ... sadly the memory
consumption persists :-( ... so I'd say the mentioned fix doesn't solve the problem
AW->SJ: Unforzunately not double to the fixed one, there is more leaks involved.
Maybe IHA or BM have time for a boundscheck round? Ask KA for that.
sj->bm: Very nice from you to agree to analyse the problem.
I did a valgrind on Linux (m76) and didn't find anything that I think could
cause this leak yet.
Thanks for you confirmation
but I think the bug does exist...
or There is something wrong with my java source?
the problems occurs when I try to modify the xsl file or compress it to PDF file
with the UNO developement package
I find ver1.9.7.4 may be better than 1.1.X on this issue and it will be
fantastic if the 2.0 solved such problem throughly...
Created attachment 22577 [details]
Output of a valgrind session using memCheck (conversion is done 3 times)
Created attachment 22578 [details]
Output of the memCheck session
I didn't find a culprit for the leaks. I attached the 12MB valgrind output
(gzipped) and the output of the memory test program running on a StarOffice
SRC680.m78 (on Linux). The only places that caught my eye were spellchecker
calls. I don't know if these appear only because we loose control over the
memory management at some place?
The output of memCheck is a bit strange insofar as the memory consuption doesn't
seem to increase, but that's probably due to the fact that valgrind is running.
->SJ: Maybe you (or someone else) find(s) a stack that may be related to the
conversion process in the log file.
What I forgot to add: Maybe the leaks come from Java. In Java, as you know,
memory is not freed at a specific time, it depends on the garbage collector. If
the Java program keeps references to the XModel of the first document loaded,
and then loads a second document, the first XModel may still exist in memory.
Have you (anybody) checked if the memory that is not freed is probably freed
after the Java program terminated?
retargeted to OOo 2.0.1 after QA approval by MSC
.
Have you tried to run my sample program or SW:s while you did the valgrind run?
Unfortunately I haven't used valgrind or know much C(++), so I can't help here.
It is definitely a leak in OOo, and the memory remains used even after I exit my
java program.
Does OOo use java internally for this, and if, how can I set the java -Xmx flags
for heap size?
Maybe they are set high, and as you probably know java will try to eat all
memory given to it. In that case it wouldn't be a leak, just a configuration matter.
Just to be sure. The output of the memcheck run seems odd, and it reads:
/home/bm/bin/memcheck soffice.bin -invisible -accept=socket,port=8100;urp;
Shouldn't the parameters be in ""? Like:
/home/bm/bin/memcheck soffice.bin -invisible "-accept=socket,port=8100;urp;"
Because of a too huge workload I can't fix this issue for OOo 2.01 -> changed
target to OO Later.
I have the similar problem in OOo Calc using OOo Basic macros
(OOo2.0.2/Linux:Slackware 10.2). It happens at about 50 file open & 50 file
close. In addition, could this cause a "Signal 11 / SIGSEGV" report from KDE, on
OOo exit? Perhaps OOo is trying to release the leaked memory when quitting,
somehow? Thanks.
I can't believe, a year and a half on and a couple of releases later that this
is still "OOo later"
Being the author of the mentioned JOOConverter
() open source project I've done some
testing myself to make sure the problem was not with my Java code. I'm using OOo
2.0.3 on Linux.
The memory usage increase seems to greatly vary based on the type of document
used. For example, ODT to PDF only increases by 2.5kb per conversion, which may
not be a memory leak at all.
However a PPT to PDF conversion using the document attached to this issue does
produce a significant increase, approx 1mb for each conversion!
Just loading and disposing the document without exporting to PDF results in
almost the same increase. While loading and disposing the same document but in
ODP format shows not much increase at all.
So my guess is that most of the leak is caused by the PPT import filter.
However, converting from ODP to PDF also increases memory usage by some 200kb
per conversion so there may be a problem with the impress PDF export filter as well.
The problem also occurs when you try to convert a ppt to an swf.
I can confirm the issue in OO version 3.0. Opening doc-files leaves about 20kb
and ppt about 700kb in memory (depending the size of the files).
A fix would be very, very nice :)
I too have a very difficult time understanding what after four years this
defect doesn't seem to be important.
I am working on a software application where we use the OpenOffice software in
server mode. We are running OpenOffice 3.0. We use OpenOffice to extract text
from Microsoft formatted documents (word, PowerPoint and Excel). After running
for about an hour (I know, not much of a metric), the OpenOffice server hangs.
By hang I mean: all processing stops (the CPU usage is approximately zero), but
the OpenOffice process is still live (or at least shown in the Windoz process
monitor). Our guess is that this problem is due to a memory error.
For anyone using OpenOffice in server mode, this is a pretty critical problem.
I guess the problem with this sort of bug reports - and why they end up getting
stuck in "OOo Later" forever - is that they are a bit too generic.
We (as users) should follow the rule of "one problem, one issue". How can we
expect the OOo team to fix all possible memory leaks for all possible
import/export formats as part of a single issue?
I tried to focus this issue on a specific case, i.e. PPT import which seemed to
be the biggest culprit, in my comment (some 3 years ago now). But people keep
adding generic complaints relating to various formats, with the only result that
this issue will never be solved, because it's impossible to solve an ill-defined
problem.
(Incidentally, JODConverter 3.0 for its part now does provide a workaround: it
automatically restarts OOo - see if interested.)
good job mnasato, haha though i am using the java OODaemon instead for
production.
is it possible to write unit test case for each of the input and output pair so
that it will be easier for the developer to test?
Amazing. I've been subscribed to this bug for nearly 4 years now, and I'm still
getting emails about it :)
Is there any way to monitor soffice.bin for active/unreleased objects? I just
processed about 600 documents and used memory jumped from 80M to 190M, and it's
not being released.
We're experiencing a similar problem. An application converts many .doc archives
to odt format, and, at a particular moment, the soffice process had 5.2G of
resident memory, in a 8GB machine.
We'll start monitoring closer this problem, but seems really strange to me the
age of this bug, almost 5 years. Is this Category of milestone (OOo Later)
hidden to the Open Office team?
My code opens a simple Calc document with four cells filled and a Chart based on
them.
It exports the chart (via XFilter) and closes the document (the right way as
described at).
After 1000 of such operations (less than 10 minutes) soffice.bin grows from 84Mb
to 330Mb.
The workaround that I'm going to use is to kill OO process periodically, so it's
ok to mark this issue as FIXED.
And concerning the comment from mnasato about issue being too generic.
Lets make it clear: this issue is not related to any sort of import/export.
OO leaks even if you just open and close a document - just like that.
The next piece of code will make OO grow 100Mb per 2 minutes (demo.ods is a
spreadsheet with four cells and one chart):
public static void main(String[] args) throws Exception {
XComponentContext xCompContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
XMultiComponentFactory xMCF = xCompContext.getServiceManager();
Object xDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop",
xCompContext);
XComponentLoader aLoader = UnoRuntime.queryInterface(XComponentLoader.class,
xDesktop);
PropertyValue[] loadProps = new PropertyValue[]{new PropertyValue("Hidden",
0, true, null)};
while (true) {
XComponent xComponent = aLoader.loadComponentFromURL("",
"_blank", 0, loadProps);
close(xComponent);
}
}
private static void close(XComponent xComponent) {
XCloseable xCloseable = UnoRuntime.queryInterface(XCloseable.class, xComponent);
if (xCloseable != null) {
try {
xCloseable.close(true);
} catch (CloseVetoException e) {}
} else xComponent.dispose();
}
I just hit this bug while using a small Python based script found at:
When converting Excel files to CSV, memory usage slowly increases. Server
crashes after a few hundreds conversion.
cc myself
Same problem for me.
The difference is my conversion method can convert more than 43 000 documents before OOo crashes.
Hope that bug will be fixed soon....
Moulay
Is there any way you can show us the bulk of the Java code (if it is Java) and what it is you are disposing so successfully that you can convert 4300. I have % OO instances and I can only convert about 2300 total before all the instances lockup or crash. The once that do lockup use over 2G of memory.
(In reply to comment #41)
> Same problem for me.
> The difference is my conversion method can convert more than 43 000 documents
> before OOo crashes.
> Hope that bug will be fixed soon....
>
> Moulay
In response to the comments by Bjoern Milcke on 2005-02-14:
Some leak also occurs if each relevant Open Office call in Java is followed by
System.gc();
System.runFinalization();
I verified this by using uno_dumpEnvironment(logFile, binaryUno_.get(), 0); in bridge.cxx, the object count in the bridge is constant between opening documents.
Also, I can confirm that a leak occurs just by creating and closing text documents in a Java loop (with gc and runFinalization) using the URP UNO bridge.
In order to find this bug, I'd suggest running valgrind not for 3 conversions (as was done in the attached valgrind logs), but for example for 100 or even more conversions. This should make it a lot easier to find the leak, as the relevant loss records would probably be repeated.
Could someone possibly do this? I have compiled AOO on Windows and do not have a corresponding tool available for Windows.
Created attachment 83796 [details]
Simple program to make it easier to find the leak.
I'm attaching a very simple Java program to help hunting down this issue.
All it does is creating and closing Open Office text documents in a loop, and calling the garbage collector/finalizer to ensure that things are properly cleaned up on the Java side.
The program takes one argument, which is the number of loops (i.e. the number of times a text document is created and closed). If you run it with argument "1000" or "10000" you will note the increase in memory usage just by creating and closing documents.
In order to run this program, you need the "Nice Office Access" jars (license LGPL)
and add them to the classpath.
Additionally, add
java_uno.jar;juh.jar;jurt.jar;officebean.jar;ridl.jar;unoil.jar;unoloader.jar
to the classpath.
You may need to adjust the Open Office path
final String officeInstallDir = "C:\\Program Files (x86)\\OpenOffice 4";
I'm sorry I could not attach a complete jar file containing all libs, because of the size restrictions. Feel free to request it via email.
|
https://bz.apache.org/ooo/show_bug.cgi?format=multiple&id=41675
|
CC-MAIN-2021-43
|
refinedweb
| 2,745
| 66.03
|
Hide Forgot
Description of problem:
The strace delivered in the RHEL 6.4, 6.3 (and possibly earlier) releases does not report the return value for the shmat. It incorrectly returns a "?" (question mark) instead of the address that the segment was attached to.
Version-Release number of selected component (if applicable):
# strace -V
strace -- version 4.5.19
# uname -a
Linux perf82.lab.bos.redhat.com 2.6.32-330.el6.x86_64 #1 SMP Thu Oct 11 15:37:45 EDT 2012 x86_64 x86_64 x86_64 GNU/Linux
How reproducible:
The simple reproducer .c file and command is listed below
Steps to Reproduce:
Compile the following .c file and run it with strace. The steps are listed below:
# cat shm_example.c
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main ()
{
int seg_id;
char* shm_ptr;
int segment_size;
const int seg_siz = 1024*1024;
seg_id = shmget (IPC_PRIVATE, seg_siz , IPC_CREAT | S_IRUSR | S_IWUSR );
shm_ptr = (char*) shmat (seg_id, 0, 0);
shmdt (shm_ptr);
shmctl (seg_id, IPC_RMID, 0);
return 0;
}
# gcc shm_example.c -o ./a.out
# strace -etrace=shmat ./a.out
shmat(294912, 0, 0) = ?
Actual results:
# strace -etrace=shmat ./a.out
shmat(294912, 0, 0) = ?
Expected results:
# strace -etrace=shmat ./a.out
shmat(294912, 0, 0) = <the_attached_address>
Additional info:
I've confirmed that this is fixed in the upstream strace 4.7 version. It would be really useful to make this fix available in the RHEL 6.x release stream.
Realistically too late for RHEL 6.4; retargetting for consideration in RHEL 6.5.
Created attachment 646650 [details]
Patch which seems to fix the problem..
Product Management, Engineering, and have determined that this bug should be described in the RHEL 6.7 Release Notes. Please update the Doc Text field with a summary feature description by April.
|
https://bugzilla.redhat.com/show_bug.cgi?id=877193
|
CC-MAIN-2019-43
|
refinedweb
| 294
| 70.8
|
I am using linux. How do you normally go about finding machines on the local network?
Is it possible to find a list of machines and/or IP addresses connected to the local area network?
- 2Before you do any sort of scanning, ensure you have proper authorization first. In most organizations this is a fireable offense.– K. Brian KelleyOct 8, 2009 at 2:26
- 6Fireably? Really? Do you work for the NSA? Reprimandable, definately. Disciplinable, maybe. But fireable? Must be the BOFH...– Mark HendersonOct 8, 2009 at 2:32
- 4Can we please try to remember that what is and is not possible in the sense of fireable is location dependent. Just because it can't happen where I am doesn't mean it can't happen elsewhere. I would also assume we are talking about someone who hasn't been authorised to perform a scan.– John GardeniersOct 8, 2009 at 10:59
- 2en.wikipedia.org/wiki/Randal_L._Schwartz– Joe CasadonteOct 8, 2009 at 12:37
- 1superuser.com/questions/261818/…– Ciro Santilli Путлер Капут 六四事Nov 30, 2015 at 11:32
8 Answers
Sure, install nmap and then run:
nmap -sP 192.168.0.1-254
Of course you'll need to replace the IP range with the appropriate values for your network.
- nmap should actually use arp if it believe you're on the same network and nmap is run as root. It can be forced with the -PR option as well. Oct 8, 2009 at 14:06
- 5
I think the right approach would be to inspect the LAN at a level lower that IP, then ARP scanning is a better choice.
See my answer to this duplicate question, I suggested nast -m.
As an alternative to scanning your network, if you have access to the switch or router you can check the router directly for it's arp table which should list all connected machines and their MAC addresses. If you're just looking to map your network and see what's online, this may be a better/easier solution.
If you have a decent router/switch, you may also be able to grab this info over SNMP rather than logging into the equipment directly, which has it's own set of advantages when it comes to regularly mapping your network.
A nice graphical tool is Auto Scan network (). It shows open ports too. For Windows, I'd suggest Look@lan, which does the same thing.
I agree nmap, and arpwatch are good tools,you can use also fping.
Here I complete an existant python script from bortzmeyer that do the job for you, the script is very fast. but first you have to install ipcalc module and psyco
import os, sys, re from threading import Thread import psyco, ipcalc
class ping(Thread): def init(self, ip, version): Thread.init(self) self.ip =ip self.version=version self.tab=("No response", "Partial Response", "Alive")
def run(self): try: if self.version==4: req=os.popen("ping -c2 -q "+self.ip, "r") elif self.version==6: req=os.popen("ping6 -c2 -q "+self.ip, "r") while 1: reponse=req.readline() if not reponse: break stat = re.findall(re.compile("(\d) received"), reponse) if stat: print "Status ", self.ip, " ",self.tab[int(stat[0])] except: raise sys.stderr.write("Error in ping.\n") sys.exit(-1)
if __name__=='__main__': psyco.full() try: address=sys.argv1 if address.find('/') > 0: net=ipcalc.Network(address) else: net=[address] for ip in net: p=ping(str(ip), 4) p.start() except: pass
I use (will be available for download when it's ready) a tool that I wrote which handles both DNS/DHCP administration and SNMP walks of the switches. If something isn't in DHCP, I at least get a MAC address from the switch, but we've made a policy decision to put everything in DHCP, even if the machines themselves are statically IPed, just to aid in tracking address space.
If you're talking about finding something that perhaps you didn't put there, I'd agree with nmap. Or, if you're worried about legal/political issues, just a script that wraps ping...
|
https://serverfault.com/questions/72380/is-it-possible-to-find-a-list-of-machines-and-or-ip-addresses-connected-to-the-l
|
CC-MAIN-2022-27
|
refinedweb
| 693
| 67.04
|
I have been using bash for most of my system administration tasks. I also know a bit of perl.
bash
Should I learn Python or Perl is better for system automation. So far from my experience learning perl has been easy.
Python
Perl
Short answer: learn both.
You are going to encounter both as a sysadmin, so you'll want to know how to read/troubleshoot/debug both.
As for writing scripts, I have used mostly Perl over the last 10 years for most of my sysadmin utility and "glue" scripts. Its regex syntax is really simple, and it lends itself quite well to extremely fast script development. This is quite important when you have to get something working on-the-spot.
Lately I have been making an effort to use more Python for the following reasons:
It takes a lot of discipline to write good Perl. All too often a "quick n' dirty" script has more features crept in over time, yet still implemented in a hasty manner. Before too long, you have a sprawling file of line noise which is a PITA to maintain.
Writing OO (or even reusable) code in Perl is not easy compared to Python. Believe me, in the long run you want lots of reusable code (and not cut-and-paste!)
Python's principles (import this) are much better suited to collaborating with others when compared to Perl's TMTOWTDI principle. If you've ever read someone else's Perl, you may know that it can be about the most frustrating thing to unravel. Python suffers from this unreadability problem far less due to its design. Worse even is when you encounter your own Perl after many years. You'll wonder at which point you must have blacked out.
import this
Documenting is important if your code is going to be around a while. Writing docstrings in Python is much easier than writing pod markup in Perl. Easy enough that you might actually use it.
I still use Perl quite a lot, but it's now more for one-liners and "throwaway" scripts which will only run once. If I think I'm ever going to edit the script again, I consider Python instead.
It depends on what you're trying to do, and where you're trying to do it. All things being equal, and where you have no restrictions on your environment, can install whatever you want, and don't have to worry about interoperating with legacy code, feel free to pick the language that suits your personal preferences best.
That said, for sysadmin work, I do think Perl has an edge: it's installed on everything out of the box, and has been since roughly the dawn of time. If you're writing a system automation or management script and using only core Perl modules, you can be almost positive that it will run without modification everywhere in your heterogeneous UNIX environment, and can be extended fairly painlessly to Windows with an installation of ActiveState or Strawberry Perl.
Hope that helps!
I would recommend python. I know perl enough but am not an expert and my experience with python has been vastly superior. I think it depends on your needs but if its simply for system automation I would go the python route and forget about perl (for the time being).
Here is a great way to sink your teeth in:
With things like Fabric in development it can really make things easier:
Example from the page:
from fabric.api import run
def host_type():
run('uname -s')
Output
$ fab -H localhost,linuxbox host_type
[localhost] run: uname -s
[localhost] out: Darwin
[linuxbox] run: uname -s
[linuxbox] out: Linux
Done.
Disconnecting from localhost... done.
Disconnecting from linuxbox... done.
They're equivalent; for a home machine, which you use depends on which one you feel more comfortable in, but when working with others you should adhere to any established standards (if everyone else uses Python you shouldn't use Perl without good
|
http://serverfault.com/questions/245086/perl-or-python-better-suited-for-unix-system-automation
|
crawl-003
|
refinedweb
| 668
| 70.73
|
Python’s objects and classes — a visual guide
Python m =:
>>> type(m) __main__.MyClass:
- Because MyClass is an instance of type, type.__init__ determines what happens to our class when it is created.
- Because MyClass inherits from object, invoking a method on m will result in first looking for that method on MyClass. If the method doesn’t exist on MyClass, then Python will look on object.:
>>> object.__bases__ () let me know if there are additional aspects that you find confusing, and I’ll try to clarify them in future blog posts.
If you liked this explanation, then you’ll likely also enjoy my ebook, “Practice Makes Python,” with 50 exercises meant to improve your Python fluency.
thank you. this is very useful to learn as a beginer
If I do:
>> dir(MyClass)
I can’t find the attribute __bases__ in the list.
Why ? Doesn’t dir provide all attributes and methods from an object ?
But:
>> MyClass.__bases__
provides (,) this is correct
One thing you don’t mention: where does the attribute __bases__ come from.
dir(MyClass) and dir(object) do not reveal this attribute
It wasn’t until Abhisek asked about “type” and you explained that “type creates classes, and type is a class” that I thought to check type’s attributes for __bases__ wherein I was rewarded with my answer.
The attributes for instances of class A are set by A.__init__. Or, if the attribute isn’t set on the instance, A might have the attribute.
So the attributes for an instance of class “type” are set by type.__init__, or are on type itself. Because MyClass is a class, and thus an instance of type, __bases__ is set by type.__init__ for new classes; if it isn’t set, then type.__bases__ is the default, which is (). Or so I’m assuming!
What advantage does Python gets by making classes an instantce of type over other languages where classes aren’t instances?
First of all, the fact that classes are regular objects that can be passed to functions and stored in dictionaries makes the language simpler to understand, simpler to implement, and more flexible.
When you invoke int(‘5’), you’re not casting 5 to be an integer. Rather, you’re creating a new instance of int, based on the string ‘5’. Invoking a class in the way you do a function is very standard in Python, and exists because classes (like functions) are “callable.” Thus, invoking int(‘5’) works in the same as calling len(‘abc’) — we’re invoking the callable protocol on an object. The fact that one object is a class, and another is a function, is irrelevant.
The moment you say that classes are special, you’re ensuring that the implementation of the language will be more complex, and that it’ll be harder for people to understand. At least, I think so!
One thing that doesn’t make sense to me is your favorite part of python “type of type is type”.
As far as I know class and instance are two different things.
so the type class and the type instance in python should be two different things, indeed the name with which we refer to the type class and type instance are same!
yet (type(type) is type) == True
and (type.__class__ is type) == True
Don’t get it!
How the class and instance are happen to be same?
Great Blog though…
When we say that everything in Python is an object, what we’re really saying is that everything in Python is an instance of a class. So “abc” is an instance of str, and 123 is an instance of int.
In many other languages, that’s where it ends: You have instances and classes, and that’s that.
But in Python, our classes are also objects, which means they’re also instances. But instances of what? It turns out that str and int are both instances of type.
As an analogy, imagine that you have a bunch of cars. Each car is made at a factory. But the factory was also made by someone or something, right?
So if type() creates classes, then what creates type? That’s the magic, and the weirdness: type creates classes, and type is a class, thus type creates itself ! In other words, the type of type is type. Weird, but true.
[…] Visual Guide to Objects and Classes. […]
> MySubClass inherits from MyClass, but is still an instance of type
Why ?
All Python classes are instances of type. That’s just by definition. So type(str) is type, and type(int) is type. Every class is an instance of the type class. Indeed, just as you can create a new int by invoking int() and a new str by invoking str(), you can create a new class by invoking type(). Weird and wild, but true!
So every class is an instance of type. But classes have a separate attribute (__bases__) indicating from whom they inherit. You might have 100 different classes in your system. They’ll all inherit from different classes, depending on how you’ve defined them. But unless you use metaclasses, 100% of your defined classes will be instances of type.
Does this make sense?
Everything is an object. Except variables.
Yeah, except that variables (i.e., identifiers) are really keys in a namespace. So you could even possibly argue that those are objects, too.
There aren’t really variables in Python. There are names. And they are strings, which, of course, are objects. And as Rueven says, are keys in a namespace dict
I really like your graphic explanation. Although I knew the terms, this presentation makes it very easy to see. I think this style of diagrams will be even more valuable when you start to think about metaclasses.
Ooh, interesting idea — maybe I’ll explore metaclasses in the future, and extend the diagram accordingly!
A post on metaclasses would be great!
|
https://lerner.co.il/2015/10/18/pythons-objects-and-classes-a-visual-guide/
|
CC-MAIN-2019-35
|
refinedweb
| 993
| 75.3
|
Scala: the flying sandwich parts
JavaScript existed since 1995 long before 'JavaScript: The Good Parts' (2008), jQuery (2006), and V8 (2008) happened. The interesting thing about Douglas Crockford's 'The).
values
What talk you of the posy or the value?
— William Shakespeare, Merchant of Venice
The Scala Language Specification describes a value as follows:
A value definition
val x: T = edefines
xas a name of the value that results from the evaluation of
e.
In TFSP, do not omit the type annotation
T inside the body of traits and classes. Local values within a function can be defined using type inference. This makes sure that the types checked at the function level.
lazy vals
The order in which the values are defined is critical when using plain vals. Referencing the values prior to initialization will cause
NullPointerException at the runtime. By annotating the values as
lazy, initialization can be delayed until the name is first referenced.
implicit val m: MachineModule = new MachineModule { val left: State => State = buildTrans(pm.moveBy((-1, 0))) lazy val buildTrans: (Piece => Piece) => State => State = f => s0 => { // .... } }
In the above,
buildTrans is marked as
lazy, since it's referenced by
left that is defined earlier.
pattern definition
When pattern matching appears in the left hand side of a value definition, it deconstructs date types using extractors.
val x :: xs = list
avoid vars
In TFSP, the use of variables is discouraged.
expressions
In Scala, most syntacic constructs return a value, which is nice.
literals
In Scala, there are literals for integer numbers, floating point numbers, characters, booleans, symbols, and strings.
no nulls
In TFSP, nulls are not allowed. Use
Option[A] instead.
infix operations
In Scala, a method call can be written as an infix operation.
no postfix
In TFSP, postfix operations are not allowed.
if expressions
In Scala,
if-else syntax returns a value. Always provide an
else clause.
scala> val x = 1 x: Int = 1 scala> :paste // Entering paste mode (ctrl-D to finish) if (x > 1) x else 0 res1: Int = 0
for comprehensions
In Scala,
for can be used as for comprehensions with
yield and for loops without
yield. Always provide an
yield. There's a minor syntactic difference based on parentheses or curly braces. In TFSP, always use curly braces.
scala> for { x <- 1 to 10 } yield x + 1 res2: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
prefer
Either[A, B] over expceptions
TFSP prefers
Either[A, B] or similar data types that encodes failure over throwing exceptions.
case class
Thy case, dear friend, Shall be my precedent
— William Shakespeare, The Tempest
Case classes in Scala is a good way of emulating algebraic data types. Each case class would correspond to a constructor of an ADT, and the ADT itself would be represented by a sealed trait.
scala> :paste // Entering paste mode (ctrl-D to finish) sealed trait Tree case class Empty() extends Tree case class Leaf(x: Int) extends Tree case class Node(left: Tree, right: Tree) extends Tree // Exiting paste mode, now interpreting.
Under the hood, case classes are classes with automatically implemented
equals,
toString,
hashcode, and
copy. In addition, their companion objects automatically implement
apply and
unapply.
pattern matching
We can use pattern matching to decontruct the case classes:
scala> val badDepth: Tree => Int = { case Leaf(_) => 1 case Node(l, r) => 1 + math.max(depth(l), depth(r)) } <console>:13: warning: match may not be exhaustive. It would fail on the following input: Empty() val badDepth: Tree => Int = { ^ badDepth: Tree => Int = <function1>
Because the trait is sealed, the compiler can help us in exhastiveness.
scala> val depth: Tree => Int = { case Empty() => 0 case Leaf(_) => 1 case Node(l, r) => 1 + math.max(depth(l), depth(r)) } depth: Tree => Int = <function1> scala> depth(Node(Empty(), Leaf(1))) res5: Int = 2
no methods in case classes
In TFSP, case classes will not have methods. More on this in the next section.
modular programming
Both modern object-oriented and functional programming are trying to claim the concept of modularity, but neither objects nor functions are intrinsitcally modular. The key aspect of the object is associating verbs together with nouns, and mapping them as metaphors to the human world. The key aspect of the function is mapping values to another, and treating the mapping also as a value.
Modularity is about defining cohesive modules that are loosely-coupled, and it's rooted in more engineering than mathematics. In modular programming, modules communicate via interfaces indirectly. This enables encapsulation of the modules, and ultimately the substitutability of the modules.
traits
In Scala, defining typeclasses with trait would be the most flexible way of implementing the modules. First, the typeclass contract would be defined with a trait that only declares function signatures.
scala> trait TreeModule { val depth: Tree => Int } defined trait TreeModule
Next, we can define another trait to implement the typeclass as follows:
scala> trait TreeInstance { val resolveTreeModule: Unit => TreeModule = { case () => implicitly[TreeModule] } implicit val treeModule: TreeModule = new TreeModule { val depth: Tree => Int = { case Empty() => 0 case Leaf(_) => 1 case Node(l, r) => 1 + math.max(depth(l), depth(r)) } } } defined trait TreeInstance
refined types (object literal)
The way the default instance of
TreeModule was defined is an example of an anonymous type with refinement, or a refined type for short. Since the type doesn't have a name, any fields that are defined in the type should be hidden from the outside except for
depth.
scala> val treeModule2: TreeModule = new TreeModule { val depth: Tree => Int = { case _ => 0 } val foo = 2 } treeModule2: TreeModule = $anon$1@79c4cc17 scala> treeModule2.foo <console>:11: error: value foo is not a member of TreeModule treeModule2.foo ^
prefer imports over implicit scopes
In Scala there are several ways of enabling
TreeModule. One way is to create an object of
TreeInstance, and importing all the fields under it to load them into the scope. TFSP prefers explicitly importing the implicit values over implicit scopes. This reduces the need of companion object.
Here's how we can use
TreeModule:
scala> { val allInstances = new TreeInstance {} import allInstances._ val m = resolveTreeModule() m.depth(Empty()) } res1: Int = 0
The implementation of the
depth function is completely substitutable, because the data that deals with it is separated from the module and because
TreeModule is abstract.
prefer traits over classes
TFSP prefers traits over classes. Except for working with external libraries, there shouldn't be a need for plain classes.
functions
Faith, I must leave thee, love, and shortly too.
My operant powers their functions leave to do.
— William Shakespeare, Hamlet
Scala has first-class functions, which are functions that can be treated like values. Having first-class functions enables higher-order functions, which is useful. What's interesting is the number of ways you can end up with a function in Scala.
case functions (partial function literal)
In Scala, a sequence of cases defines an anonymous partial function. I'm going to call this a case function since "pattern matching anonymous function" is too long.
scala> type =>?[A, R] = PartialFunction[A, R] defined type alias $eq$greater$qmark scala> val f: Tree =>? Int = { case Empty() => 0 } f: =>?[Tree,Int] = <function1>
Since
PartialFunction extends
Function1, a case function can appear in any place where a function is expected.
function literal
In Scala, a function may take multiple parameters, or it could be curried as a function that takes only one parameter and returns another function. In TFSP, curried functions will be the default style unless it makes sense to pass tuples.
scala> val add: Int => Int => Int = x => y => x + y add: Int => (Int => Int) = <function1>
This makes partial application the default behavior.
scala> val add3 = add(3) add3: Int => Int = <function1> scala> add3(1) res5: Int = 4
no placeholder syntax
In TFSP, the anonymous functions using placeholder syntax such as
(_: Int) + 1, will not be allowed. As fun as it is, removing it would reduce the numbers of way a function can be created.
prefer functions over defs
In Scala, def methods can exist side-by-side with the first-class functions. TFSP prefers the first-class functions over defs. This is because functions should be able to fulfil the def method's tasks in many cases. An exception is defining functions with type parameters or implicit parameters.
no overloading
In TFSP, method overloads are not allowed.
polymorphism
In Scala, polymorphism can be achieved via both subtyping and typeclasses.
prefer typeclasses over subtyping
TFSP prefers ad-hoc polymorphism using typeclasses over subtyping. Typeclasses offer greater flexibility since the behavior can be added to existing data types without recompilation.
For example, we can generalize the
TreeModule as
Depth[A] that supports both
List[Int] and
Tree.
trait Depth[A] { val depth: A => Int } trait DepthInstances { def resolveDepth[A: Depth](): Depth[A] = implicitly[Depth[A]] implicit val treeDepth: Depth[Tree] = new Depth[Tree] { val depth: Tree => Int = { case Empty() => 0 case Leaf(_) => 1 case Node(l, r) => 1 + math.max(depth(l), depth(r)) } } implicit val listDepth: Depth[List[Int]] = new Depth[List[Int]] { val depth: List[Int] => Int = { case xs => xs.size } } }
context-bound type parameters
To take advantage of the
Depth typeclass, define a def method with a context-bound type parameter.
scala> { val allInstances = new DepthInstances {} import allInstances._ def halfDepth[A: Depth](a: A): Int = resolveDepth[A].depth(a) / 2 halfDepth(List(1, 2, 3, 4)) } res2: Int = 2
modular dependencies
I've mentioned that in modular programming, modules must communicate indirectly through interfaces. So far we have only seen one module. How can we desribe a module that depends on another one? Cake pattern is a popular technique of doing this, but we can do something similar using implicit functions.
Suppose we have two modules
MainModule and
ColorModule.
import swing._ import java.awt.{Color => AWTColor} trait MainModule { val mainFrame: Unit => Frame } trait ColorModule { val background: AWTColor }
I would like to define a
MainModule instance that depends on a
ColorModule.
trait MainInstance { def resolveMainModule(x: Unit)(implicit cm: ColorModule, f: ColorModule => MainModule): MainModule = f(cm) implicit val toMainModule: ColorModule => MainModule = cm => new MainModule { // use cm to define MainModule } }
A
MainModule can be instantiated normally.
scala> { val allInstances = new MainInstance with ColorInstance {} import allInstances._ val m = resolveMainModule() m.mainFrame() } res1: scala.swing.Frame = ...
avoid variance
In Scala, a type parameter can be annotated as covariant or contravariant to indicate how the type constructor behaves with respect to subtyping. Since TFSP avoids subtyping altogether, variance annotation should also be avoided.
method injection (enriched class)
In Scala, an existing type may be wrapped implicitly to inject method that did not exist in the original type. If it is desirable to have methods on data types, using method injection allows us to emulate methods without compromising modularity.
The technique of injecting methods using typeclass was inspired by Scalaz 7's implementation.
scala> :paste // Entering paste mode (ctrl-D to finish) trait DepthOps[A] { val self: A val m: Depth[A] def depth: Int = m.depth(self) } trait ToDepthOps { implicit def toDepthOps[A: Depth](a: A): DepthOps[A] = new DepthOps[A] { val self: A = a val m: Depth[A] = implicitly[Depth[A]] } } // Exiting paste mode, now interpreting.
Here's how we can inject
depth method to all data types that supports
Depth typeclass.
scala> { val allInstances = new DepthInstances {} import allInstances._ val ops = new ToDepthOps {} import ops._ List(1, 2, 3, 4).depth } res4: Int = 4
case study: Tetrix
I've been listing the language constructs from Scala, but it's hard to see just how different or useful this subset is without writing some code. Naturally, Tetrix came to my mind as the test program.
MainModule
First,
MainModule was defined to wrap the Swing UI.
import swing._ trait MainModule { val mainFrame: Unit => Frame }
MainModule depends on two other modules called
ColorModule and
MachineModule. Here's how the dependencies are set up:
trait MainInstance { def resolveMainModule(x: Unit)(implicit cm: ColorModule, mm: MachineModule, f: ColorModule => MachineModule => MainModule): MainModule = f(cm)(mm) implicit val toMainModule: ColorModule => MachineModule => MainModule = cm => mm => new MainModule { // ... } }
This is used by application trait that I had to extend from
SimpleSwingApplication:
object Main extends TetrixApp {} trait TetrixApp extends SimpleSwingApplication { val allInstances = new MainInstance with ColorInstance with MachineInstance with PieceInstance {} import allInstances._ implicit val machine: MachineModule = MachineModule() val main: MainModule = MainModule() lazy val top: Frame = main.mainFrame() }
ColorModule
ColorModule determines the color setting used in the application.
trait ColorModule { val background: AWTColor val foreground: AWTColor } trait ColorInstance { val resolveColorModule: Unit => ColorModule = { case () => implicitly[ColorModule] } implicit val colorModule: ColorModule = new ColorModule { val background = new AWTColor(210, 255, 255) // bluishSilver val foreground = new AWTColor(79, 130, 130) // bluishLigherGray } }
This is the module in its entirety. It is a bit of overhead to express just two fields, but the point is to demonstrate that these settings can be configured to something else after the fact.
For example, we can define a new instance of
ColorModule by extending the default instance:
trait CustomColorInstance extends ColorInstance { implicit val customColorModule: ColorModule = new ColorModule { val background = new AWTColor(255, 255, 255) // white val foreground = new AWTColor(0, 0, 0) // black } }
This can be loaded into the implicit search space as follows:
trait TetrixApp extends SimpleSwingApplication { val allInstances = new MainInstance with ColorInstance with MachineInstance with PieceInstance with CustomColorInstance {} import allInstances._ implicit val machine: MachineModule = resolveMachineModule() val main: MainModule = resolveMainModule() lazy val top: Frame = main.mainFrame() }
Now the blocks are rendered in another color configuration. This alternative setup can be defined in another jar without recompiling the first jar.
MachineModule
MachineModule represents the state machine of the game. First, I defined a case classes as follows:
import scala.collection.concurrent.TrieMap // this is mutable case class Machine(stateMap: TrieMap[Unit, State]) case class State(current: Piece, gridSize: (Int, Int), blocks: Seq[Block]) case class Block(pos: (Int, Int))
Machine keeps current
State in a concurrent
Map. Currently
MachineModule defines the following functions:
trait MachineModule { val init: Unit => Machine val state: Machine => State val transition: Machine => (State => State) => Machine val left: State => State val right: State => State val rotate: State => State } trait MachineInstance { def resolveMachineModule(x: Unit)(implicit pm: PieceModule, f: PieceModule => MachineModule): MachineModule = f(pm) implicit val toMachineModule: PieceModule => MachineModule = pm => new MachineModule { // ... } }
This module depends on another module called
PieceModule, so module instance is defined as the implicit function
toMachineModule. Since implicit parameters are resolved at the call-site,
PieceModule can be substituted to an alternative instance at the top-level application.
The state machine is implemented as follows:
val state: Machine => State = { case m => m.stateMap(()) } val transition: Machine => (State => State) => Machine = m => f => { val s0 = state(m) val s1 = f(s0) m.stateMap replace((), s0, s1) m }
As you can see, all functions are implemented as curried function values. Here is an example that takes advantage of the currying.
val left: State => State = buildTrans(pm.moveBy((-1, 0))) val right: State => State = buildTrans(pm.moveBy((1, 0))) val rotate: State => State = buildTrans(pm.rotateBy(-Math.PI / 2.0)) lazy val buildTrans: (Piece => Piece) => State => State = f => s0 => { val p0 = s0.current val p = f(p0) val u = unload(p0)(s0) load(p)(u) getOrElse s0 }
buildTrans is a function that takes
Piece transformation function, and the initial
State and returns another
State. By applying only the first parameter, it can be also seen as a function that returns
State => State function.
PieceModule
PieceModule describes the movements of the pieces. For example,
moveBy used in
left and
right is implemented as follows:
val moveBy: Tuple2[Int, Int] => Piece => Piece = { case (deltaX, deltaY) => p0 => val (x0, y0) = p0.pos p0.copy(pos = (x0 + deltaX, y0 + deltaY)) }
observations
Actually writing code using TFSP, even for a toy project, gave me a better understanding of the subset. The implementation of the modular dependency, for instance, went through several iterations of try-and-error to be able to substitute arbitrary modules correctly.
Overall, I am pleasantly surprised that this subset seems usable thus far. I did not complete Tetrix, but since I got to the point where I could move the block around with collision detection, I figure it's just matter of spending more time.
Except for a few
def applys, all functions were defined using
val. This did not cause troubles for the most part. The only thing I had to watch out for was the initialization order, which I wouldn't need to worry if I were using
def methods. The initialization issue can go away if we always used
lazy vals.
Some of the functions that return a mutable object was implemented as
Unit => X, like
val init: Unit => Machine. This results in
init and
init() having different semantics, which is not common in idiomatic Scala.
Giving up placeholder sytanx for anonymous functions resulted in parameter named having throw-away names. This is a tradeoff for reducing the syntactic constructs for functions.
The differentiating aspect of TFSP is the modularity. Without relying on heavy subtyping, TFSP can define modules that are loosely coupled. It's also interesting that TFSP achieves encapsulation without marking any functions
private. Other dependency injection solutions like Cake pattern and SubCut probably could achieve these things too.
summary
Since Scala allows wide spectrum of style, it's useful to ponder your own subset to see where you fit in. One use of the subset is to write majority of the code in it, and treat the rest of Scala as FFI to talk to other libraries and Java.
Here's the summary of TFSP:
- separate data into case classes
- define behaviors as typeclasses using traits
- use imports to load implicits
- define functions using case functions and curried function values
The first two points can be found in some of the functional- or modular- oriented code bases. TFSP just applies them strictly to everything possible.
The last two points would be considered diversion from normal Scala. But, in a way it's the parts that feels awkward if one reviewed the language with fresh eyes. For example, it's a bit odd to have two notions of functions: first-class functions that can appear anywhere, and methods that has implicit passing of
this. If possible, it's natural to unify them towards
val. The implicit scope via companion object is another oddity that's great if you understand it, but the idea of tying things together based on names feels a bit like magic.
We will be landing shortly to Newark Liberty International Airport. The weather forecast is sunny, at 72°F or 22°C. Please make sure your seat backs and tray tables are in their idiomatic positions. On behalf of the crew, I’d like to thank you for joining us on the flying sandwich.
|
http://eed3si9n.com/node/139
|
CC-MAIN-2017-51
|
refinedweb
| 3,118
| 54.52
|
I, enum or handle to refer to them, etc.
Meh.
So of course this is a terrific opportunity to write some code to write my code for me.
I've blogged on Ragel and its usefulness for parsing things like shaders before. I don't know what happened to that post, though. It seems to have disappeared in the transition from Tumblr to my new site. Oh well. It was a bad post anyway.
I won't bore you with all the details, but I wrote a little tool called
shaderize which takes a folder full of vertex and fragment shaders (hereafter referred to as the shader directory) along with an output folder containing templates (hereafter referred to as the output directory), parses the shaders and applies the data to the templates producing… code I did not have to write! Hooray!
Installation
I used Ruby to write
shaderize, so I packaged it up as a gem. All you need to do is:
gem install shaderize
You'll probably need to prefix that with
sudo unless you're using Ruby Version Manager. Note: OS X comes with Ruby installed out-of-the-box.
Templates
The templates are written in mustache, a wonderfully simple little templating language. Seriously, it will take you about 2 minutes to learn. Your code templates can have anything in them, but mine look something like:
// Shaders.h.tpl #pragma once #ifndef _Shaders_H_ #define _Shaders_H_ #include "ShaderProgram.h" #include "ShaderUniform.h" #include "ShaderAttribute.h" namespace Shader { {{#shaders}} class {{name}}_Shader : public ShaderProgram { public: {{#attributes}} ShaderAttribute {{name}}; {{/attributes}} {{#uniforms}} ShaderUniform {{name}}; {{/uniforms}} public: void Load( void ) { ShaderProgram::Load( "{{name}}" ); {{#attributes}} {{name}} = GetAttribute( "{{name}}" ); {{/attributes}} {{#uniforms}} {{name}} = GetUniform( "{{name}}" ); {{/uniforms}} } }; extern {{name}}_Shader {{name}}; {{/shaders}} void LoadShaders( void ); }; // namespace #endif // _Shaders_H_
And:
// Shaders.cpp.tpl #include "Shaders.h" namespace Shader { {{#shaders}} {{name}}_Shader {{name}}; {{/shaders}} void LoadAll( void ) { {{#shaders}} {{name}}.Load(); {{/shaders}} } }; // namespace
You can see the files have a double extension. Shaderize expects the templates to end in
.tpl and will produce files in the same directory with the same name sans the
.tpl extension.
Invoking
You can run
shaderize from the command line like so:
shaderize Resources/Shaders Source/Application
I have a shell build phase that does this for me. Shaderize is smart enough to only update the scaffolded files if something has changed that requires it to do so.
shaderize $PROJECT_DIR/Resources/Shaders $PROJECT_DIR/Source/Application
And that's it. Now when I hit build,
shaderize will take all my shaders and produce wrapper classes for me, including members for the attributes and uniforms, along with a method that loads them all. This means I can write a shader, and use it without writing a single line of boilerplate code to manage it.
Nifty.
Of course there is a lot more code hiding behind
ShaderProgram,
ShaderAttribute and
ShaderUniform, but that's just vanilla C++ code and left as an exercise to the reader.
Tangent
I do actually have a C version of my shader parser that I use to extract the uniforms and attributes at load time so I can set those up with the appropriate OpenGL handles and so on. As a result I have no enums, constants or
#define statements littering my code. That's really a more complicated subject and could be done with
shaderize too — I just haven't got around to it yet.
I'm really happy with my shader workflow now. Code for using them is very clean. There's a lot more that could be done, including smart shader generation, but I've done enough yak shaving for now.
Meta
You can get the Ruby source for
shaderize on my GitHub page.
The code is released under the MIT license.
This post is part of iDevBlogADay,, a collaboration of blogs by indie iOS developers. You can subscribe to iDevBlogADay through RSS or follow the #iDevBlogADay hash tag or @idevblogaday on Twitter.
|
http://www.gallantgames.com/posts/21/scaffolding-code-from-shaders
|
CC-MAIN-2019-35
|
refinedweb
| 652
| 71.85
|
2017 is shaping up to be an exciting year in Python data development. In this post I'll give you a flavor of what to expect from my end. In follow up blog posts, I plan to go into more depth about how all the pieces fit together. I have been a bit delinquent in blogging in 2016, since my hands have been quite full doing development and working on the 2nd edition of Python for Data Analysis. I am going to do my best to write more in 2017.
New position
After a productive 2 years with Cloudera, a few months ago I transitioned to a software architect role at Two Sigma Investments. Since leaving the quant finance world in 2010, I have observed the profound impact that open source tools have had on the financial industry. I was refreshed to find that forward thinking institutions like Two Sigma have increased their engagement with the open source ecosystem, releasing internally-developed tools and contributing work back to established OSS projects.
In my new role, I am working to solve data analysis problems that are well-aligned with the open source software I've been developing over the last decade:
- User-friendly API design
- High performance IO and data access
- Fast and expressive computational engines
With regards to open source and business, there's a couple of interesting trends happening right now, in my view:
- Companies not participating in open source (as users and/or developers) are getting left behind
- Many of the best software engineers won't work for a company that forbids them from working on open source projects (I certainly would not).
pandas 2.0
Over the last year, we have been publicly discussing a plan to improve the internals of pandas to better suit the needs of today's data problems. I spoke a bit about this in a recent talk.
General speaking, the goals of pandas 2.0 are:
- Fixing design warts and accumulated technical debt from the last 9 years.
- Faster single-threaded performance
- More efficient memory management, less memory usage
- Improved performance and scalability through true multithreaded execution
My goal is to deliver the same quality pandas user experience on 10x as much data. pandas works well on 1GB of data, but less well on 10GB. This has to change for pandas to remain a relevant tool in the future.
In the meantime, the pandas team is toiling away with a major 0.20 release in the works, followed by pandas 1.0, which will mark a period of API stability while we work on refactoring the pandas core.
Apache Arrow
Last February, we announced Apache Arrow, a collaboration amongst open source data projects to establish a standard for high-performance in-memory columnar data structures and IO.
Arrow development has been proceeding well since then. We recently reached a major development milestone by achieving full binary compatibility between the initial Java and C++ library implementations. This is a critical step in delivering high performance IO between the JVM (and systems like Spark) and C/C++ or Python-based systems.
One of my goals in building Arrow's C++ libraries is to facilitate low-overhead columnar memory management and high performance, multithreaded IO in pandas 2.0. When I can, I will write some posts about these tools and how they help.
While pandas 2.0 is in development, we'll continue to do work to make Arrow a high speed "data conduit" for data en route to or from the current production version of pandas.
Apache Parquet for Python
In 2016, we've worked to create a production-grade C++ library for reading and writing the Apache Parquet file format. En route, I became a committer and then a PMC member of Apache Parquet. Uwe Korn, from Blue Yonder, has also become a Parquet committer.
As Parquet is columnar file format designed for small size and IO efficiency, Arrow is an in-memory columnar container ideal as a transport layer to and from Parquet.
To read and write Parquet files from Python using Arrow and parquet-cpp, you
can install
pyarrow from conda-forge:
conda install pyarrow -c conda-forge
Then, the code to read looks like:
import pyarrow.parquet as pq arrow_table = pq.read_table('path-to-data/0.parquet') df = arrow_table.to_pandas()
We'll be writing more documentation and blog posts about Parquet in the coming months.
Continuum Analytics recently started developing a separate Parquet implementation for Python that uses Numba for accelerating encoding and decoding routines. I'm glad to see more Python developers working on these problems.
Feather file format
Earlier this year, I worked with Hadley Wickham to design and deliver the Feather file format for R and Python. Feather uses Apache Arrow's columnar representation and sports a simple metadata specification that can handle the main R and Python data types.
As time has passed, as one might expect, quite a bit of code overlap has developed between Feather's C++ and Python components and Apache Arrow's respective C++ and Python libraries. To address this, I'm planning to merge the Feather implementation into the Arrow codebase, which will enable me to provide better performance and new features to Feather users.
Improving PySpark
PySpark, the Python API for Apache Spark, has well known performance
issues (compared with Scala equivalents) around data serialization (Spark's
DataFrame.toPandas and
sqlContext.createDataFrame) and relatedly UDF
evaluation (
rdd.map,
rdd.mapPartition, or
sqlContext.registerFunction).
In line with the above work on fast columnar IO for Python and the JVM using Arrow, some of my Two Sigma colleagues and I are collaborating with IBM and the Spark community to accelerate PySpark using these new technologies. If you would like to get involved with this, please let me know.
The PySpark-Arrow work is progressing well, and we should have some interesting updates to share in February at the Spark Summit East conference.
Update on Ibis
Last, but not least, I am still maintaining Ibis and helping its users how I can. I'm proud of the level of deep SQL semantic support that Ibis provides its users. You can write very complex queries with pandas-like Python code that is composable and reusable.
As pandas 2.0 progresses, I am interested in building an in-memory backend for Ibis. I had thought about doing this in the past, but decided it would be better to wait.
|
https://wesmckinney.com/blog/outlook-for-2017/
|
CC-MAIN-2021-31
|
refinedweb
| 1,075
| 60.75
|
Hide Forgot
abrt version: 1.1.13
architecture: i686
cmdline: /usr/bin/python /usr/bin/scout
component: scout
executable: /usr/bin/scout
kernel: 2.6.35.6-48.fc14.i686
package: scout-0.4-6.fc14
reason: scout:5:<module>:ImportError: No module named pkg_resources
release: Fedora release 14 (Laughlin)
time: 1289715735
uid: 500
backtrace
-----
scout:5:<module>:ImportError: No module named pkg_resources
Traceback (most recent call last):
File "/usr/bin/scout", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named pkg_resources
Local variables in innermost frame:
__builtins__: <module '__builtin__' (built-in)>
__file__: '/usr/bin/scout'
__package__: None
sys: <module 'sys' (built-in)>
__requires__: 'scout==0.4'
__name__: '__main__'
__doc__: None
Created attachment 460330 [details]
File: backtrace
scout-0.4-8.fc15 has been submitted as an update for Fedora 15.
scout-0.4-7.fc14 has been submitted as an update for Fedora 14.
Package scout-0.4-7.fc14:
* should fix your issue,
* was pushed to the Fedora 14 testing repository,
* should be available at your local mirror within two days.
Update it with:
# su -c 'yum update --enablerepo=updates-testing scout-0.4-7.fc14'
as soon as you are able to.
Please go to the following url:
then log in and leave karma (feedback).
scout-0.4-7.fc14 has been pushed to the Fedora 14 stable repository. If problems still persist, please make note of it in this bug report.
scout-0.4-8.fc15 has been pushed to the Fedora 15 stable repository. If problems still persist, please make note of it in this bug report.
|
https://bugzilla.redhat.com/show_bug.cgi?id=653027
|
CC-MAIN-2020-24
|
refinedweb
| 265
| 57.47
|
Hide Forgot
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7
Description of problem:
If you try and install using the FC4 x86_64 ISO boot disc, it crashes as it is booting just after:
md: ...autorun DONE.
with the message:
VFS: Cannot open root device "<NULL>" or unknown-block(3,2)
Please append a correct "root=" boot option
Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(3,2)
Call Trace: <ffffffff8013a4a5>{panic+133} <ffffffff801cba74>{sys_mount+196}
<ffffffff801f6ef9>{__bdevname+41} <ffffffff80582c00>{mount_block_root+496}
<ffffffff80582d85>{prepare_namespace+213} <ffffffff801c186>{init+326}
<ffffffff8010fc33>{chip_rip+8} <ffffffff8010c040>{init+0}
<ffffffff8010fc2b>{chip_rip+0}
<3>BUG: soft lockup detected on CPU#0!
NOTES:
I even tried removing one CPU to see if that helped. FC3 boot iso for x86_64 does not exhibit this behavior and I will have to reinstall my system again using FC3.
Version-Release number of selected component (if applicable):
How reproducible:
Always
Steps to Reproduce:
1. insert boot iso turn on machine
2. watch it boot
3. watch it crash
Actual Results: same as above
Expected Results: boots and anaconda starts.
Additional info:
The bug I'm duplicating this against has a pointer to an unofficial FC4.2, which
is FC4 + updates. The newer kernel might be just enough to get you up and running.
*** This bug has been marked as a duplicate of 169613 ***
|
https://bugzilla.redhat.com/show_bug.cgi?id=174770
|
CC-MAIN-2018-51
|
refinedweb
| 244
| 58.58
|
What is Tree Shaking?
Tree shaking is a term used as a means to eliminate code that isn't in use, or dead-code, as we call it. You can also think of it like choosing 3-4 relevant quotes from a book to write an excellent paper. If you only need 3-4 relevant quotes, why use the entire book?
Whenever a code bundler, like webpack, builds our web application for production. It does tree shaking. Code bundlers like webpack do their best to remove dead code, or unused code, to reduce the bundle size of your application when you prepare your code to be able to be used for production. Unfortunately, it can't catch everything, and that because we sometimes write code that isn't tree shaking friendly.
A way for us to help code bundlers with tree shaking, or eliminating dead code, in our web development projects is to only import necessary methods and components into our application. We do this by using JavaScript destructuring syntax in our
import statements and properly
export code as well. In Vuetify, this is done by default when you import and use it throughout your project.
Let's dive into an example to find out more about tree shaking!
Starting off, in JavaScript we sometimes unintentionally import an entire framework and/or library into our application. Example below:
import Vuex from 'vuex'
The problem with this import statement is that we import the entire library,
vuex, when we don't need everything from it when programming.Because of that, we end up bringing a significant amount of unnecessary code, into our web application.
What are the problems with this?
- It increases bundle size when we build and deploy our app.
- In return, it will take longer to load. Longer load times make for a bad end user experience.
- It helps us follow DRY ("don't repeat yourself" - write code only once if at all possible) coding principles when using the library of choice and the functions/methods within it.
The question you should always ask when you import a module is "What exactly do I need from here?" This allows you to better approach what to import. Example:
import { mapState } from 'vuex'
In this example we are solely importing the mapState helper from the vuex library, which is used to help manage the data and how it flows for a vue.js application. To many people not comfortable with es6 this is a different syntax from what you usually see starting out. We are using ES6 object destructuring to grab the
mapState helper from vuex. Instead of importing all of vuex and only using one small part of the library, we use this syntax to grab only what we need from the vuex library. This "take what you only need" mindset helps keep dead code out of your application.
Making Your Code Tree Shaking Friendly
BOOM we magically now have a small calculator app. This is what it currently looks like:
calculator.js
//creating an object that holds functions to caclulate the numbers we input const myCalculator= { add(a, b) { return a + b; }, subtract(a, b) { return a - b; }, divide(a, b) { return a / b; }, multiply(a, b) { return a * b; } }; //Making it possible for other files to import and use the calculator object export default myCalculator;
index.js
import myCalculatorfrom "./calculator.js"; console.log(myCalculator.add(1, 2)); // Expected output: 3 console.log(myCalculator.subtract(15, 9)); // Expeted output: 6
This looks great, right? Well unfortunately there are a couple problems:
- First, even if we use just one method on the
myCalculatorobject we will still import everything else inside
myCalculator.
- Second, due to that when we use a code bundler, like webpack, to bundle it for production, our bundle size will remain the same.
How do we refactor this to make it tree shaking friendly for our code bundlers?
We're going to split each of our methods inside
myCalculator into their own modules!
calculator.js
export function add(a,b){ return a + b; } export function subtract(a, b){ return a - b; } export function divide(a, b) { return a / b; } export function multiply(a, b) { return a * b; }
What we did here was:
- Break down all the methods inside the exported
myCalculatorobject into their own separate and exportable files
- Made it possible to specify what method we would like to use in our index.js
Below we will declare the function we want without worrying about dead code:
import { add } from "./calculator"; console.log(add(1, 2)); // Expected output: 3
How would we import other methods that were exported as modules from the same file?
For example, after you add two numbers you'd like to use the
subtract method for two other numbers.
We can do that within our destructuring object next to
add.
index.js
import { add, subtract} from "./calculator"; console.log(add(1, 2)); // Expected output: 3 console.log(subtract(15, 9)); // Expeted output: 6
There you have it! We've now learned how to make our code tree shake ready. Not only are we happy but your code bundler is as well!
More Info on Tree Shaking, Destructuring, ES6 Modules:
- Reduce JavaScript Payloads with Tree Shaking (Article)
- Destructuring assignment (MDN Documentation)
- Destructuring in ES6 - Beau teaches JavaScript (Video)
- Understanding ES6 Modules (Article)
P.S. Huge thanks for Johanna being the editor of this article!
This blog post is a part of Vuetify Beginner's Guide Series. 🐣 Each blog has been collaboratively worked on by the Vuetify Core Team. Interested in contributing a topic? ➡ Reach out to Johanna on Dev.to or in the Vuetify Community Discord.
Discussion (2)
You use vue as a reference here, but vue-cli doesn't support tree-shaking out of the box. Do you have any suggestions on how to achieve tree-shaking in a vue app or lib?
Webpack would be your best bet in my opinion! If you're using vueity, vueitfy-loader has automatic tree-shaking if I'm not mistaken :)
|
https://dev.to/bboyakers/what-is-tree-shaking-1ojb
|
CC-MAIN-2022-21
|
refinedweb
| 1,004
| 63.39
|
- Basic Syntax
For Java programmer, it is very important to keep in mind about the following points.
- Case Sensitivity - Java is a case sensitive language, which means that the identifier Hello, hello, HeLLo, hEllO, helLo, HELLO. All are different in Java.
- Method Names - All the method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each first letter of inner word should be in Upper Case
Example: public void employeeRecords(), public void myMethodName(), public void employeeNumber() etc.
- Class Names - For all class names, the first letter should be in Uppercase
If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Examples: class MyJavaProgram, class MyThirdJavaProgram, class StudentRecords etc.
- public static void main(String args[]): Java program processing starts from the method main() which is a mandatory part of every Java program.
- Program File Name - Name of a program file should exactly match the class name.
When saving the file, you should save it using the class name and add/append '.java' to end of the name.
If file name and the class name do not match, your program will not compile.
Example: Think 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
Java Basic Syntax Example
Following is Java's simplest program, prints Hello World on the screen.
/* Java Program Example - Java Basic Syntax */ public class JavaProgram { public static void main(String args[]) { /* print Hello World */ System.out.println("Hello World"); } }
When the above Java program is compile and executed, it will produce the following output:
Identifiers in Java
In Java, an identifiers are used to name things, such as classes, variables, and methods.
An identifier may be any sequence of uppercase and lowercase letters, number or the underscore and dollar-sign characters. As you know, Java is case-sensitive, therefore, VALUE is a different identifier than Value.
Following are the rules to declare Identifiers in Java:
- All identifiers can begin with a letter (A to Z or a to z) or dollar currency character ($) or an underscore (_).
- After the first character identifiers can have any combination of characters.
- Most importantly identifiers are case-sensitive.
- A keyword cannot be used as an identifier since it has reserved words and have some special meaning.
- Examples of illegal identifiers: 123abc, -salary etc.
- Examples of legal identifiers: AvgTemp, count, a4, this_is_ok, age, $salary, _value, __1_value, customers etc.
Whitespaces in Java
A line containing only whitespace, possibly with comment, is known as blank line, and Java compiler totally ignores it.
There are the three types of comments defined by Java. You have already seen two: single-line and multiline comments. The third type is a documentation comment. This type of comment is used to produce an HTML file that documents your program. The documentation comment begins with /** and ends with */.
All characters available inside any comment are ignored by Java compiler. Her is an example.
/* Java Program Example - Java Basic Syntax */ public class JavaProgram { /* This is a simple Java program. It will print 'Hello World' on the output screen It is an example of multi-line comments or block comments. */ public static void main(String args[]) { // It is an example of single line comment /* It is also an example of single line comment. */ System.out.println("Hello World"); } }
When the above Java program is compile and run, it will produce the following output:
« Previous Tutorial Next Tutorial »
|
https://codescracker.com/java/java-basic-syntax.htm
|
CC-MAIN-2022-21
|
refinedweb
| 584
| 55.95
|
It is a compile-time constant. A field or local variable which is declared as constant can be initialized with a constant expression which must be fully evaluated at compile time.
- const int x = 10;
- const int y = 20;
- const int z = x + y;
- Console.WriteLine("The value of x :" + x);
- Console.WriteLine("The value of y :" + y);
- Console.WriteLine("The value of z :" + z);
-
- int a = 15;
- const int b = x + a;
- Console.WriteLine("The value of b :" + b);
- //The variable 'a' is assigned but its value is never used
You can mark Constants as public, private, protected, internal, or protected internal access modifiers.
When to use
If you think that the value of field or local variable is never changed.
When to use
If you think that the value of field or local variable is never changed.
ReadOnly:-
It is same as Constant but it is run time constant. I mean to say that a ReadOnly field or local variable can be initialized either at the time of declaration or inside the constructor of same class. That is why we called it run time constant.
- public class MyClassProgram
- {
- readonly int x = 10;
- public MyClassProgram()
- {
- //changed the value in constructor
- x = 20;
- }
- }
- As you know that we cannot declare Constant as static but we can do it for readonly explicitly. By default it is not static. It can be applied to value type and reference type [which initialized by using the new keyword)] both and also with delegate and event
When to use
If you think, you need to change the value of variable or field at run time inside the calling constructor, then you need to use the readonly modifier.
Total Post:135Points:949
C# C# .NET
Ratings:
255 View(s)
Rate this:
|
https://www.mindstick.com/forum/33923/difference-between-constant-and-read-only-in-c-sharp
|
CC-MAIN-2016-44
|
refinedweb
| 295
| 71.55
|
These days most people represent angles using degrees or radians, but many old-skool game programmers preferred a binary integer format where a full circle is 65536. To convert:
short ToBinary(float degrees) { return (short)(degrees * 65536 / 360); }
If you store such a value in a 16 bit integer type, it will automatically overflow any time you increment it past a full circle, so you no longer need special case wrapping code to handle the circular (modulo) nature of angle arithmetic.
When manipulating degrees using floats, you might have to write:
angle += turnAmount; if (angle >= 360) angle -= 360; else if (angle < 0) angle += 360;
But with a binary angle represented as a short, you can get the same result with just:
angle += turnAmount;
This simplifies many common angle computations. For instance the TurnToFace method from the Aiming sample would no longer need to bother calling WrapAngle if it used this binary format.
Back in the day most games used integer or fixed point math, so this was a major win. But today most people use floating point, and converting between integer and float formats is awkward and slow. So it is debatable whether this format is still useful.
Great post Shawn. I can think of a *very* popular engine that even today, still uses this method of angle representation for many of its rotations.
The other major win with this method of angle representation is the inherent compression, which is a huge win when it comes to sending rotational data over the network.
The rotation a quaternion or 3×3 matrix represents can instead be represented this way and only use 6 bytes (yaw, pitch, roll) instead of 16 bytes for a quat (4 floats) or 36 bytes for a 3×3 matrix (9 floats).
Given a choice between a really smart one-liner code, and an explicit overflow check, I think it’s best to code a few more lines.
It’s more readable. Readable = easier to optimize, less room for bugs.
I actually think that in this case, the really smart one-liner may be more readable and less error-prone. The bounds checking due to wrapping around at 360 degrees is really a corner-case for most types of functions that accept an angle as an input, and this approach eliminates it.
Aw, you just gave me some Allegro nostalgia 🙂
It goes back to your optimization article. I tend to optimize for readability and maintainability rather than speed (especially since I’m writing a turn-based game where most of the time I’m waiting for user input).
Have been following your blog for a while. Thought I’d say hello and give my appreciation!
It was only the day before yesterday that was I reading through Doom’s source code and came across the curious BAMS (Binary Angle Measurement System), so it’s a great coincidence (or scary?) that you mention it 🙂
I had been using a similar method up until now for breaking a circle up into a custom number of "arcs" for some old school ray casting.
Thanks again! Great posts as always.
Best regards,
Terry
> Given a choice between a really smart one-liner code, and an explicit overflow check, I think it’s best to code a few more lines.
Such decisions can be a subtle judgment call.
On the one hand, it’s certainly not a good idea to rely on cryptic one liners that depend on non obvious side effects.
But on the other hand, it’s also not a good idea to write more code than is strictly necessary to solve the problem at hand! The more code you have to write, the more risk you will make a mistake or forget to include something important.
If someone was doing computations with floating point numbers, and every time they stored a result, they were adding a floor() call, I would say that was silly: if they wanted the result to always be an integer, they could simplify their code and reduce the chance of error by just doing the computations directly with an integer data type.
So I guess the question here is whether the modulo nature of integer overflow is an obscure implementation detail that is liable to confuse the reader, or a fundamental characteristic of the data type which the reader can be expected to intuitively understand?
I suspect this mostly comes down to how familiar you (and of course anyone else expected to work on the code in question) are with binary number representations, bit twiddling, etc.
This may come down to a performance issue as well. If the angle remained within the normalised range most of the time, the cost of two false if statements might have some effect if this code was called a lot every frame. Using the implicit wrapping of an unsigned short would eliminate that cost.
Now if only there was a "short BinaryMath.Sin(short Angle)" that didn’t involve converting it to a double then back again… But then, doesn’t the FPU have a sin instruction that would be faster than trying to compute it on the CPU for an integer?
Looking back, I think dealing with angles and having to re-learn trigonometry was one of the areas that took most of my time when making relspace. The more examples/explanations the better! 🙂
@Erzengel: If you’re that concerned about speed, precompute!
> If you’re that concerned about speed, precompute!
Beware: in these days of fast CPUs with relatively slow memory, lookup tables are no longer necessarily a speeed boost over just recomputing values whenever you need them.
Hmm, interesting point Shawn. I do development mostly for mobile devices, so that’s not a tradeoff I’ve considered before!
My original statement is probably best replaced with something along these lines:
"If you’re that concerned about speed, try writing a test app to compare the different approaches."
:¬)
Shawn,
I agree with your analysis of Cardin's comments. I have done more than a little simulation software that dealt calculations involving changing angles. Using the scaled binary angle approach (BAMs/BRADs) greatly simplified my code and eliminated boundary conditions that were always a plague.
Additionally, they forgave a multitude of sins.
Not only did I no longer have to worry about normalizing my angles with every computation, I no longer had to worry about HOW to normalize them. The two most common normalization ranges are [0,360) and [-180,+180). Either can be realized without any computation at all. The first is realized by interpreting the stored integer as an unsigned integer with no sign bit. The second is realized by interpreting the stored integer as a twos-complement signed integer with the traditional sign bit being the high order bit. Conversion to degrees/radians/grads is a simple matter of scaling the integer appropriately (as signed or unsigned depending on the normalization range). This was done in the user-interface subsystem.
The biggest gain though was with trigonometric functions. Transcendental functions can eat your lunch in high-fidelity, real-time simulation systems. The trig functions of BAMS can be computed by dividing the integer into three zones. The high order 2 or 3 bits tell you what quadrant or octant the angle is in (permitting the trig computation to make use of that function's symmetry; the middle set of bits can be used for a table lookup; while the low-order bits can be used for interpolation. I suppose these days a specialized ASIC or FGPA could be assembled that did the computation is silicon. The bottom line is that the trig functions were blazeingly fast, the models built using them had no discontinuities in them, and the user-interface was simple and effective.
The modulo arithmetic of binary integers is also rather easily grapsed.
All in all I find this to be a useful technique for the roaming programmer (or indeed ANY programmer) to have in his bag of techniques.
|
https://blogs.msdn.microsoft.com/shawnhar/2010/01/04/angles-integers-and-modulo-arithmetic/?replytocom=11413
|
CC-MAIN-2018-34
|
refinedweb
| 1,336
| 59.13
|
Problem Statement
“K’th Largest element in BST using constant extra space” states that you are given a binary search tree and you need to find the kth largest element in it. So if we arrange the elements of the binary search tree in descending order then we need to return the kth number from the sequence.
Example
k=4
3
Explanation: If the elements are arranged in the descending order, the sequence is [6, 5, 4, 3, 2, 1]. Now the fourth largest element is the element at the fourth index that is 3.
Approach to find K’th Largest element in BST using constant extra space
Naive approach
We can solve this problem by first storing the inorder traversal and then finding the n-k+1 element in the sequence will result in the answer to the problem. But this approach will have O(N) space complexity. We also discussed a more efficient solution where we did a reverse inorder traversal and kept a count for the number of nodes. While counting the nodes we were also checking if we node count is equal to k. If the node count is equal to k, we return the node. Else, in the end, we return a message that the kth largest node is not found.
Efficient Approach
In the previous approach, we used reverse inorder traversal which required O(H) space for recursion. We can do the same thing as we did with the inorder traversal. As we reversed the inorder traversal. We will use Morris traversal for doing the inorder traversal in O(1) space. but instead of simply doing this we will do the reverse in-order traversal using Morris Traversal.
Morris Traversal is used on the binary threaded tree, the binary threaded tree is nothing but a binary tree having an extra thread. This makes it easier to perform traversal on the tree. Reverse Morris Traversal is just Morris Traversal but in a reverse manner. In normal morris traversal, we would have first moved to left subtree and then to right subtree. But here first we move to right subtree and then to left subtree. This way can perform the traversal in descending order. And then we return the kth element from the start. That is we keep a count and when the count is equal to k we return that element.
Code
C++ code to find K’th Largest element in BST using constant extra space
#include <bits/stdc++.h> using namespace std; struct node{ int data; node *left; node *right; } ; node* create(int data){ node * tmp = new node(); tmp->data = data; tmp->left = tmp->right = NULL; return tmp; } // normally insert the node in BST node* insert(node* root, int x) { if (root == NULL) return create(x); if(x<root->data) root->left = insert(root->left, x); else if(x>root->data) root->right = insert(root->right, x); return root; }; } int main() { node *root = NULL; int n;cin>>n; for(int i=0;i<n;i++){ int element;cin>>element; root = insert(root, element); } int k;cin>>k; node* res = findKthLargest(root, k); if(res == NULL) cout<<"No kth largest found"; else cout<<"Kth largest element is "<<res->data; }
6 3 2 1 5 4 6 4
Kth largest element is 3
Java code to find K’th Largest element in BST using constant extra space
import java.util.*; import java.lang.*; import java.io.*; class node{ int data; node left; node right; } class Tree{ static node root; static int count; static node create(int data){ node tmp = new node(); tmp.data = data; tmp.left = null; tmp.right = null; return tmp; } static node insert(node root, int x) { if (root == null) return create(x); if(x<root.data) root.left = insert(root.left, x); else if(x>root.data) root.right = insert(root.right, x); return root; } static; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i=0;i<n;i++){ int element = sc.nextInt(); root = insert(root, element); } int k = sc.nextInt(); count = 0; node res = findKthLargest(root, k); if(res == null) System.out.println("No kth largest found"); else System.out.println("Kth largest element is "+res.data); } }
6 3 2 1 5 4 6 4
Kth largest element is 3
Complexity Analysis
Time Complexity
O(N), because we have once traversed over all the elements of the tree. The time complexity is linear i.e. O(N).
Space Complexity
O(1), because we have used morris traversal instead of doing the traversal recursively.
|
https://www.tutorialcup.com/interview/tree/kth-largest-element-in-bst-using-constant-extra-space.htm
|
CC-MAIN-2021-49
|
refinedweb
| 761
| 62.98
|
Over the last few months, I have heard more about state machines used for front-end development. The idea of a state machine is that it has only a finite number of states and can only be in one state at any given time. Conceptually this makes perfect sense for app development - there are only a certain number of states available.
The concept of state machines and statecharts is not new, and it isn't rooted in front-end development, either. It's a mathematical model, and one used in many things around us. As an example, a light can be
OFF or
ON. You can describe anything with a state machine, even though this is a simple example.
Introduction to XState
Using a state machine in front-end development has become much less complicated with the creation of the package XState. XState helps us define state machines, create events and effects, and control the entire application flow. XState uses JavaScript methods and objects to describe the state machine.
The light bulb example from above would be written out like the following:
const lightBulb = Machine({ id: 'lightBulb', initial: 'off', states: { off: { on: { TURN_ON: 'on' } }, on: { on: { TURN_OFF: 'off', } } } });
The state machine defined here shows the two states for the light bulb,
OFF and
ON, and the transitions from the events
TURN_ON and
TURN_OFF.
The object itself isn't very complex to read, but as the state machine grows in complexity, it can be harder to understand. XState has create a tool to help out with this - the XState visualizer.
Using the XState visualizer helps to see how the state machines work and are interactive, so playing with them is fun. If you want to check out the code for the machine, you can also click the code button to take a peek.
Building a Vonage Video State Chart
When I set out to learn state machines, and XState, my overall goal was to build an application similar to Google Meet using Vonage Video. The app would allow a user to create a meeting room, share the URL, and have a meeting with multiple streams. To get to that point, I had to learn some of the various concepts for state charts and how to represent those in XState.
Thinking through the possible application states is not an easy task, I found. There are many possibilities to explore, and ultimately finding the right solution takes some trial and error.
The rest of this article will cover some basic concepts and build a state chart visualization that will mimic the eventual state machine. I will also provide some additional links and resources throughout so you can explore on your own.
States and State Nodes
A state is a representation of a machine at any given time. This moment can be defined and then made into a state node in XState, captured as a configuration.
In my Vonage Video app, there are a couple of different possible solutions to this, but I've found that describing the states in as simple of terms as possible is the best way to get to a useful result.
Creating a machine uses the following pattern:
const machine = Machine(state_nodes, options)
With a video state machine in mind, there are two compound states -
connected and
disconnected.
Two state nodes may seem overly simplified, but there are only two states after some trial and error. Each of these states, however, are more complex than an atomic (no children) node. Instead of creating every possible state at the top level, XState helps us organize with hierarchical and parallel state nodes.
Hierarchical State Nodes
XState provides the option to create nested states called
hierarchical state nodes. When we first start the machine, we can set it to
idle first, as the machine will be ready but doing nothing. Why not just make another top-level atomic state node?
Adding states to the top level is called "state explosion" and is a typical side-effect of finite state machines. Since Vonage Video is still technically
disconnected, nesting
idle makes sense as the video is both disconnected and idle. Another
disconnected substate should be
ready. The
disconnected.ready state would happen just before moving to the
connected state. The state machine also has a state node in-between
idle and
ready to get everything set up. This middle state can be called the
init phase.
The state machine now would look like this:
You should notice that we don't currently have a way to move in between the two nodes. We will cover events and actions in a moment.
Parallel State Nodes
A
parallel state node allows the application to be in all of its substates at the same time. The Vonage Video state machine is highly event-driven, so we need to manage multiple states at once.
To specify that a state node is parallel, we use
type:parallel in the configuration. After the transition to
connected, three parallel states will occur -
session,
publisher, and
subscribers. Each of these states will set up events and event listeners to control the Vonage Video service's responses.
The resulting visualization looks like this:
With these primary states, we can control what our application shows at particular times. Currently, however, we are unable to move between states. Let's have a look at events and transitions.
Events and Transitions
Since a state node is just the configuration of an individual state, their inherently is not a way to move from state to state without declaring that in the state node.
Each node listens for a sent event to transition to the next state. In the light bulb example, the
TURN_ON event sent tells the machine to transition to
on.
Transitions only occur between top-level nodes and within hierarchical nodes. Parallel nodes are not allowed to transition between each other. For our Vonage Video app, this means the following:
- When the page is ready, we can send a
STARTevent. This event will transition the state to
disconnected.init.
- The
disconnected.initstate will transition out once the
VIDEO_ELEMENT_CREATEDevent has fired.
- Once we reach
disconnected.ready, we can allow the user to connect, sending the
CONNECTevent, and transition to
connected.
- If the application passed the
DISCONNECTevent, the state machine would disconnect.
Declaring an event and transition in XState uses the following pattern:
on: { EVENT_DESCRIPTOR: 'nextState' }
You can add specific actions to the transition as well. I would recommend you read the sections on internal and external transitions in the documentation. They cover in great detail the various types of transitions possible.
Guarded Transitions
You may have noticed that one of the transitions has a
cond node in the transition. This conditional is what's called a
guarded transition. Guarded transitions help protect the machine from moving to a state that is not allowed based on certain conditions. In this case, I don't want to transition to
ready until the token and video element are both created.
on: { 'VIDEO_ELEMENT_CREATED': { target: 'ready', cond: 'checkToken' } }
The guard condition
checkToken is a named reference to the guards object in the options paramater sent to machine:
const video = Machine( state_nodes,{ guards: { checkToken: () => true } });
Context
In order to be more useful to an application, our state machine will need a longer living state, called an
extended state, or
context. The context object updates using various effects with the
assign() method.
Speaking of actions, let's get to these now and finish out the rest of the skeleton.
Actions and Services
There are what's known as "side-effects" in state machines that XState puts into one of two categories:
- "Fire-and-forget" - where the effect doesn't send events
- Invoked - where sending events are required
Actions
Actions are single effects and tend to be one of the more common effects in the video state machine. You can use actions when you enter or exit a node, or during a transition. Understanding the order of actions is incredibly important.
An excellent resource for learning the action order (and all of the topics on XState) is a video published by @kyleshvlin over at Egghead.io. It helped me understand how actions fired.
The bulk of the actions for this machine revolve around updating the context as a transition. When events are called, we can use the action to run the
assign() method:
on: { 'SOME_EVENT': { actions: assign({'someContext': (ctx, e) => e.someValue}) } }
Services
Invoked Services are the other main effect in the video state machine. To use promises and event listeners, you need to invoke a service. This concept was, by far, the hardest for me to grasp. The main difficulty I had to work through was understanding that an invoked service stops when the state exits. If you transition too quickly, your promise or callback will disappear.
There are two primary services that I'm using in the video state machine, promises, and callbacks. The
invoke promises service allows the state machine to use a promise to either resolve or reject and then act accordingly. I used this to interact with the server asynchronously and then update the context when complete.
The function signature of invoked promises looks like this:
src: (context, event) => new Promise((resolve, reject) => { if (event.error) reject('Rejected') resolve('Resolved') }), onDone: {/*success transition*/} onError: {/*error transition*/}
The second, and probably the most important part of this machine, is the
invoked callbacks. The Vonage Video architecture relies heavily on events and event listeners. In a state machine, those are set up through a callback. Let me show you an example:
invoke: { id: 'initPublisher', src: (ctx) => (cb) => { let publisher = initPublisher(pubOptions); publisher.on('videoElementCreated', (e) => { cb({ type: 'VIDEO_ELEMENT_CREATED', publisher: publisher }) }) return () => publisher.off('videoElementCreated'); } }
The function signature of an invoked callback looks like this:
src: (context, event) => (callback, onReceive) => { callback('EVENT'); onReceive(event) => { callback('OTHER_EVENT') }; return () => cleanup() };
Using actions and services, our Vonage Video state machine now looks like the following:
Don't forget to click around, and click the
code tab to see what the state machine looks like as a configuration.
Resources and Wrap-up
Ok - so you've made it this far.
If this is your first time looking at XState, it's a lot to take in all at once. I'm still exploring and learning new ways to do things. This post is just a small portion of what's out there. As you are learning - here are a few great resources you will want to check out
- Kyle Shevlin's Intro to State Machines Using XState videos
- XState Docs
- Introduction to XState at flaviocopes.com
- The Rist of State Machines - Smashing Magazine
Feel free to reach out if you have questions about XState, and we can learn something new together!
|
https://developer.vonage.com/blog/2020/07/01/learn-and-apply-xstate-with-vonage-video
|
CC-MAIN-2022-27
|
refinedweb
| 1,786
| 61.77
|
Opened 5 years ago
Closed 5 years ago
Last modified 5 years ago
#17548 closed New feature (wontfix)
updated simplejson version
Description
It would be nice to have a bundled simplejson version that supports the use_decimal feature which has been added in version 2.1.0.
import simplejson as json
from decimal import Decimal
json.loads('1.1', use_decimal=True) == Decimal('1.1')
True
json.dumps(Decimal('1.1'), use_decimal=True) == '1.1'
True
Change History (3)
comment:1 Changed 5 years ago by
comment:2 Changed 5 years ago by
The copy of simplejson we bundle is for internal use in the (de)serializer code. We are well server by the version we currently include and we force use of
decimal=False
because it can introduce problems (see #16850, r17228 and r17229)
I'm going to wontfix this ticket because:
- I don't think users should be relying on specific versions of libraries we bundle, and
- Django shouldn't be the vehicle for users getting versions of these libraries newer than the ones available in the platform especially if its for uses outside of the ORM model serialziation/deserialziation functionality like calling
.loads()
and
dumps()
directly. It is out of scope and that's what tools like virtualenv and such are for.
comment:3 Changed 5 years ago by
Also, note that we will remove the bundled copy after the 1.4 release, since Python >= 2.6 includes the "json" module.
example code:
|
https://code.djangoproject.com/ticket/17548
|
CC-MAIN-2017-04
|
refinedweb
| 244
| 53
|
Signals and Slots - Closed
Hi there,
For my university assignment, I have created three classes. Film class, FilmGUI class (it is a form that accepts info about the Film) and FilmWriter class (this class writes to a file on the disk).
When I click on Save button in the FilmGUI class, I want the FilmWriter class to write to the text file on the disk.
I have declared a signal in the FilmGUI class that emits when the button is clicked. But I am not able to declare a slot in the Main class that would then pass the Film object to the FilmWriter class so that it can write to the file.
I want to declare a slot in the Main class and connect it with the signal in the FilmGUI class.
Please assist.
Thanks
- raven-worx Moderators
what do you have so far? What exactly do you mean "you're not able to declare a slot"?
Hi and welcome to devnet,
Have a look at Qt's documentation examples to see how in works.
As for the Main class, do you mean the main function ? If so, you can't declare a slot in there.
Just curious, how many are you in that class ?
Ok. Let me take it one step at a time.
Below is the Form that I have made
#include <QDialog>
#include "filmwriter.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
QString title;
QString director;
int duration;
QDate releaseDate;
singals:
write();
private slots:
void on_pushButton_clicked();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
When I try to compile it I get C3861 error. Identifier not found.
Below is the CPP file:
#include "dialog.h"
#include "ui_dialog.h"
#include "film.h"
#include "filmwriter.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_clicked()
{
title = ui->lineEdit->text();
director = ui->lineEdit_2->text();
duration = ui->lineEdit_3->text().toInt();
releaseDate = ui->dateEdit->date();
emit write();
}
- Jeroentjehome
Hi, welcome to devnet!
A quick comment about your post, for code examples/post always use the code insert option, that is"@code@" so it becomes readable to other programmers.
Second when stating an error, the compiler usually gives a line number where the error is detected. That shortens searching for us.
Did you read the tutorial of signal/slots? "here!":
- raven-worx Moderators
oh no ... post messages got lost again ... :/
To your question where you should define a slot:
Do this in every QObject subclass. In your case probably in the FilmWriter class.
Ok. Lets say I do define the slot in FilmWriter.
- I click the button in the GUI class.
- In the button clicked event, I make a Film class with the data entered in the form.
- When the button is clicked in the GUI class then it should emit a signal to write the info to the file.
- First I need to create the FilmWriter class to use its slot. The FilmWriter class takes a Film as parameter in the constructor.
My question then is where should I do this part?
Thanks
As I was saying in my lost message:
Why not do the writing in on_pushButton_clicked ? Would be a lot simpler
- Jeroentjehome
Hi,
You can't emit a signal to a slot that's not there yet. If you still need to create the FilmWriter class the slot will not exist when the signal is emitted. Like SGalst says is probably the easiest way to do so. In the on_pushbutton create a FilmWriter class (function scope), handle the write to file there, and exit the function (FilmWriter class) get's deleted.
Greetz
Thanks guys done that. Now a new problem.
The header for FilmWriter:
@#include <QtCore>
#include <QTextStream>
#include <QFile>
#include <QString>
#include "film.h"
class FilmWriter
{
public:
FilmWriter();
FilmWriter(Film myFilm);
private:
};
@
CPP for filmWriter
Film.getDirector(); out<< myFilm.getDuration(); out<< myFilm.getTitle(); mFile.flush(); mFile.close();
}@
I am getting two errors:
c:\qt\qt5.0.2\tools\qtcreator\bin\assignment1ques1\filmwriter.h:17: error: C2061: syntax error : identifier 'Film'
c:\qt\qt5.0.2\tools\qtcreator\bin\assignment1ques1\filmwriter.h:17: error: C2535: 'FilmWriter::FilmWriter(void)' : member function already defined or declared
Please help.
Sorted. Circular dependency. I had declared a FilmWriter class in Film class and Film class in FilmWriter Class.
Thanks all for the help. Much appreciated.
If it's all good now, don't forget to update the thread's title to closed so other forum users may know a solution has been found
I am trying to update the title to closed but not happening. Will keep trying.
Sorry, I meant "solved" not "closed"
|
https://forum.qt.io/topic/30712/signals-and-slots-closed
|
CC-MAIN-2018-09
|
refinedweb
| 779
| 67.04
|
What a great new addition to Tulum hotels, and believe me, I did my homework! It was already mid-January when I decided to spend a milestone birthday in late March with a bunch of friends in Tulum, and I searched furiously for accommodations that would suit all of us. Boutique-like rooms and atmosphere? Check. Air conditioning? Check. Modern-style bathrooms? Check. Central beach location? Check. Availability for a group of 8? Check! And that was only because My Way only opened in November, so word had not spread yet. Lucky me, as I took a chance and booked 4 suites for a week and we ALL loved it!
They were very prompt and accommodating when making reservations, and trust me, that is not something I encountered with many other properties. The new "hip" Papaya Playa Project? NO emails or phone calls back!? Be Tulum? A response took days. I love Casa Violeta, but it also took days to hear back from them. Knowing that I've been to Tulum numerous times and was bringing many seasoned NY'ers with me (!), they were kind enough to give me a terrific birthday discount, which helped a lot. And then we arrived, and oh man, was it paradise.
The rooms or "suites" are the perfect combination of rustic and modern, just as the pictures convey -- thatched roof casitas with charming decor, comfy king beds, A/C and ceiling fans, and the nicest bathrooms I've encountered in a Tulum hotel! That might sound like a lot of the hotels there, but there was a newer, more modern feel to My Way: It was new and hip enough for us to feel comfortable, yet laid-back enough for us to go barefoot all the time. It was not a scene, thank god (see: Coqui Coqui, Be Tulum) so we made our own "scene" - lounging on the beautiful blue chaise lounges, drinking made-to-order cocktails, and eating simple lunches (quesadillas, guacamole & chips, fish tacos), all on a beautiful - and rather secluded - stretch of beach. They don't have a restaurant, but it doesn't matter as the rate includes a fantastic breakfast brought right to your deck, and as stated, they do light lunches. More importantly, My Way is just two doors down from the fantastic Posada Margarita (really great Italian food and great vibe) and numerous other great restaurants.
Because of moving around a bit, we stayed in 6 of their 7 rooms, and they are all similarly lovely with the same decor. Koko is closest to reception and the road, whereas the identical Horizon, while small, is right on the beach, where my friend had to close her sliding glass doors at night so as to not be awoken by the roar of the sea (silly girl!). On top of Horizon is a veranda (their "spa") where I had one of the best massages in recent memory, with a view and breezes of the sea all around me - pretty magical. The Queen and Imperial suites were really large, with the latter able to easily accommodate 3 or 4 people. The Imperial had a small kitchen, which we used for cocktail-making (!) and 3, count 'em 3 decks! The upper deck/rooftop had a large, shaded lounger and an outside rain shower and was just spectacular. The Corazon/Caribbean house had that too.
If I were to return (and I will!) I would stay in Horizon - for the beach - or the Imperial - for the room and the decks. But you really can't go wrong with any of the rooms.
Lastly, and though it is written all the time, I can't not write about the warm and welcoming feeling we experienced by all who worked there, from check-in to check-out. Vincente at reception helped us with EVERYTHING, Leo took care of all our drink and lunch orders with a constant smile, and the young Italian owners Elena and Massimo were just great. Without hesitation, Elena helped the girls of my party with a certain item we had forgotten, ahem, and on my birthday, they arranged a great lunch next to the bar and surprised me with a beautifully decorated birthday cake!
What more could one want in Tulum? New and modern decor, all the amenities of modern travel, charm and comfort galore, a central beach location yet secluded enough to feel private, and a great staff. If I had the money to stay at uber-chic and pricey Be Tulum, where the celebs stay, or even a fancy private vila, I'd still choose My Way. It was EVERYTHING!
- Reservation Options:
- TripAdvisor is proud to partner with Expedia, Orbitz, Booking.com, Hotels.com, Travelocity, Hotwire, Priceline, Cheap Tickets, Agoda and Hotel.de so you can book your My Way Boutique Hotel reservations with confidence. We help millions of travelers each month to find the perfect hotel for both vacation and business trips, always with the best discounts and special offers.
|
https://www.tripadvisor.com/ShowUserReviews-g150813-d5564484-r203658296-My_Way_Boutique_Hotel-Tulum_Yucatan_Peninsula.html
|
CC-MAIN-2017-22
|
refinedweb
| 832
| 68.91
|
While technology continues to advance, machine learning programs still speak human only as a second language. Effectively communicating with our AI counterparts is key to effective data analysis.
Text cleaning is the process of preparing raw text for NLP (Natural Language Processing) so that machines can understand human language. This guide will underline text cleaning’s importance and go through some basic Python programming tips.
Feel free to jump to the section most useful to you, depending on where you are on your text cleaning journey:
Gathering, sorting, and preparing data is the most important step in the data analysis process – bad data can have cumulative negative effects downstream if it is not corrected.
Data preparation, aka data wrangling, meaning the manipulation of data so that it is most suitable for machine interpretation is therefore critical to accurate analysis.
The goal of data prep is to produce ‘clean text’ that machines can analyze error free.
Clean text is human language rearranged into a format that machine models can understand. Text cleaning can be performed using simple Python code that eliminates stopwords, removes unicode words, and simplifies complex words to their root form.
Here’s a quick and easy no-code example of what this might look like (Python coding guide further below):
Say you receive a customer service query with a hashtag and a url:
INPUT:
“Hey Amazon - my package never arrived PLEASE FIX ASAP! @AmazonHelp”
You’d need to perform the two most basic text cleaning techniques on this query:
Here we remove capitalization that would confuse a computer model:
INPUT:
“Hey Amazon - my package never arrived PLEASE FIX ASAP! @amazonhelp”
OUTPUT:
“hey amazon - my package never arrived please fix asap! @amazonhelp”
You’ll notice we still have a fair bit of noise – since NLP will convert @’s, URLs and emojis into unicode, making them unhelpful for analysis, we further normalize by eliminating unicode characters. The same concept applies to punctuation.
INPUT:
“hey amazon - my package never arrived please fix asap! @amazonhelp”
OUTPUT:
“hey amazon my package never arrived please fix asap”
We are well on our way but still have some words that don’t directly apply to interpretation. Luckily, a number of stopword lists for english and other languages exist and can be easily applied. Observe the results.
INPUT:
“hey amazon my package never arrived please fix asap”
OUTPUT:
“amazon package never arrived fix asap”
And just like that we have turned a complex, multi-element text into a series of keywords primed for text analysis.
This is just the tip of the iceberg – let’s explore some further text cleaning techniques and how they can be programmed in Python.
While text cleaning, like data preprocessing as a whole, has greatly benefited from a number of new self-service tools that can standardize and clean your data for you, it is still important to understand the underlying code.
Enter the Natural Language Toolkit (NLTK), a python toolkit specifically designed for raw text to NLP transformation.
With an understanding of a few basic NLTK processes you can easily grasp the foundation of most text cleaning programs, and from there modify and customize them to best serve your purposes!
To get us started we are going to approach how we would achieve our previous examples using python, then graduate to a few more basic techniques.
We will go over the basic python code to:
Let’s jump right into it by approaching our previous example with python code.
Before doing so, let’s go over why we ‘normalize’ text in a little more depth.
Normalizing text is the process of standardizing text so that, through NLP, computer models can better understand human input, with the end goal being to more effectively perform sentiment analysis and other types of analysis on your customer feedback.
Specifically, normalizing text with Python and the NLTK library means standardizing capitalization so that machine models don’t group capitalized words (Hey) as different from their lowercase counterparts (hey).
This is called case normalization – let’s look at what the code is and the changes it has on our base text.
INPUT:
“Hey Amazon - my package never arrived PLEASE FIX ASAP! @AmazonHelp”
PYTHON CODE:
Here’s our first swing at Python code – we are simply telling our program to turn every capitalization to lowercase:
text = "Hey Amazon - my package never arrived FIX THIS ASAP! @AmazonHelp" text = text.lower() print(text)
OUTPUT:
“hey amazon - my package never arrived please fix asap! @amazonhelp”
Success! Now our analytics models can group all uses of Amazon and amazon together, etc. Let’s further normalize our text by eliminating punctuation, URL, and @ noise.
Punctuation, Emoji’s, URL’s and @’s confuse AI models because they are uniques signatures that either end up being translated unhelpfully into unicode (Smiley face becomes \u200c or similar), or are unique (in the case of @’s and hyperlinks).
Punctuation also creates noise and impedes NLP understanding because it relates to the tone of the specific sentence, not necessarily the word it is attached to.
Let’s get into what coding the removal of these examples might look like and see how the output might be better for machine analysis.
INPUT:
We have our case-normalized text:
“hey amazon - my package never arrived please fix asap! @amazonhelp”
PYTHON CODE:
We tell our program to eliminate the punctuation, URL, and @:
import re text = "hey amazon - my package never arrived please fix asap! @amazonhelp" text = re.sub(r"(@\[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^rt|http.+?", "", text) print(text)
OUTPUT:
And voilà, we have distilled our example to uniform lowercase words:
“hey amazon my package never arrived please fix asap”
We’ve made great progress, but still have room to parse and simplify the text further.
Here, we finally get to make good use of the NLTK library by importing the pre-programmed english stop words library.
With english, among many popular languages, stop words are common words within sentences that do not add value and thus can be eliminated when cleaning for NLP prior to analysis.
Here’s what this looks like when coding our example.
INPUT:
“hey amazon my package never arrived please fix asap”
PYTHON CODE:
import nltk.corpus nltk.download('stopwords') from nltk.corpus import stopwords stop = stopwords.words('english') text = "my package from amazon never arrived fix this asap" text = " ".join(\[word for word in text.split() if word not in (stop)]) print(text)
OUTPUT:
“package amazon never arrived fix asap”
The progress we’ve made from the initial example is massive (at least for our analytical purposes). We’ve simplified the language down to standardized words that directly relate to the problem.
We have: amazon[service] package[product] never[time] arrived[problem] fix[request] asap[urgency].
Breaking our example down in this manner not only helps us log and archive the customer request more accurately but also helps us get it in front of the right support team (shipping) at the right level of urgency (as the customer said, asap).
Let’s move on to one final basic step.
Stemming and lemmatization via Python is a bit more obtuse than the three previous techniques. It involves breaking down words to their roots and root meanings respectively. By doing so we can better measure intent.
While both techniques are similar, they produce different results so it is important to determine the proper one for the analysis you hope to perform.
Stemming, the simpler of the two, groups words by their root stem. This allows us to recognize that ‘jumping’ ‘jumps’ and ‘jumped’ are all rooted to the same verb (jump) and thus are referring to similar problems.
Lemmatization, on the other hand, groups words based on root definition, and allows us to differentiate between present, past, and indefinite.
So, ‘jumps’ and ‘jump’ are grouped into the present ‘jump’, as different from all uses of ‘jumped’ which are grouped together as past tense, and all instances of ‘jumping’ which are grouped together as the indefinite (meaning continuing/continuous).
So, if we are looking to find all instances of a product (say an engine) having any sort of ‘jump’ related response to analyze all responses, good or bad, we would use stemming.
But, if we want to break this even further down to the type of jump i.e. whether it was in the past, present, or a continuous problem, and want to approach all three different instances with distinct types of analysis, then we will use lemmatizing.
Let’s take a gander at the base code for each:
INPUT:
“jump” “jumps” “jumped” “jumping”
PYTHON CODE:
import nltk from nltk.stem.porter import PorterStemmer from nltk.stem import WordNetLemmatizer words = \["jump", "jumped", "jumps", "jumping"] stemmer = PorterStemmer() for word in words: print(word + " = " + stemmer.stem(word))
OUTPUT:
jump = jump jumped = jump jumps = jump jumping = jump
INPUT:
“jump” “jumps” “jumped” “jumping”
PYTHON CODE:
import nltk from nltk.stem.porter import PorterStemmer from nltk.stem import WordNetLemmatizer words = \["jump", "jumped", "jumps", "jumping"] lemmatizer = WordNetLemmatizer() for word in words: print(word + " = " + lemmatizer.lemmatize(word))
OUTPUT:
jump = jump jumped = jumped jumps = jump jumping = jumping
With these basic techniques, your journey to clean, NLP input-ready data is underway. This guide will now get into some more specific tips, but if you think you’re already primed and ready to analyze your data, check out Monkeylearn’s full suite of no-code analysis tools.
With markets more accessible and competitive than ever before, it’s the small things that will make the biggest difference. For this reason, companies need unique, tailor-made approaches to their customer experiences, customer service strategies, and yes – even their text cleaning.
Here are some methods to further hone your text cleaning approach to your needs.
There are eight main parts of speech, and using NLTK to tag each within our data allows us to glean further useful insight from our text.
For instance, by tagging and grouping our adjectives, we can calculate the most and least used descriptors, which points us towards our products’ strengths and weaknesses.
Each part of speech has their own unique POS tag. Here you can see some examples:
Thankfully, NLTK has a built-in program to tag your text for you.
We can input the following Python code and it will sort any given data set into POS tags (see the full list of POS tags here):
The first step is to tokenize our sentence (split it into words):
INPUT:
amazon package never arrived fix asap
PYTHON CODE:
import nltk nltk.download('punkt') tokens = nltk.word_tokenize("amazon package never arrived fix asap") print(tokens)
OUTPUT:
['amazon', 'package', 'never', 'arrived', 'fix', 'asap']
Once we have these tokens we can tag each word with its corresponding Part of Speech (see above table):
INPUT:
['amazon', 'package', 'never', 'arrived', 'fix', 'asap']
PYTHON CODE:
import nltk nltk.download('averaged_perceptron_tagger') tokens = ['amazon', 'package', 'never', 'arrived', 'fix', 'asap'] pos = nltk.pos_tag(tokens) print(pos)
OUTPUT:
[('amazon', 'JJ'), ('package', 'NN'), ('never', 'RB'), ('arrived', 'VBD'), ('fix', 'JJ'), ('asap', 'NN')]
Using this kind of code, we can now tabulate the POS totals for large bodies of text!
Text cleaning has three further sorting functions that may be of use:
Translation, despite being the most obvious topic for standardization, is also a subset of text cleaning. You will want to have all your text in the same language so that it can be properly analyzed using the same machine parameters.
In the pursuit of this, it is of utmost importance to keep account of linguistic differences when translating other languages to your base language of choice. Not all languages have the same descriptors, and verbs that translate the same often diverge in meaning to a native speaker.
Typo Correction, while obvious, has to be one of the first steps before taking on any of the previously mentioned major text cleaning steps. Often, social media posts and reviews are riddled with deliberately misspelled words (like, ‘biz’ instead of ‘business’, ‘wiv’ instead of ‘with’, ‘woz’ instead of ‘was’, and ‘da’ instead of ‘the’), as well as accidental spelling errors.
While it might seem as simple as losing the misspelled words, those words could convey important meaning, so keeping a catalogue of common misspellings and correcting as much as possible is crucial.
Finally, Number Unification is absolutely essential – if your numbers aren’t standardized you have bad data. As a subset of data preparation, standardizing address and phone numbers so that they are in the same format ensures your data analysis will be accurate and not ruined by a couple entries where users put their street and city in the same field.
Any text cleaning approach is about attention to detail and boiling your data down to only it’s most crucial bits, without losing it’s context – and that’s a hard balance to strike.
That’s what makes text cleaning fascinating and, now that we have the help of AI tools to sort through millions of lines for us, innovative and effective approaches to text cleaning are right at our fingertips.
Once our data is clean and prepared, it’s time to remember why we went through all of that trouble in the first place.
Monkeylearn provides a suite of self-service no-code tools ready to analyze any data set.
Sign up for a free demo, or explore our full suite of tools via our built-in Python API today.
|
https://monkeylearn.com/blog/text-cleaning/
|
CC-MAIN-2022-27
|
refinedweb
| 2,232
| 58.32
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.