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 |
|---|---|---|---|---|---|
pyfiglet 0.7.1
Pure-python FIGlet implementation
Christopher Jones (cjones@insub.org).
Packaged by Peter Waller <peter.waller@gmail.com>,
various enhancements by Stefano Rivera <stefano@rivera.za.net>.
_|_| _| _| _|
_|_|_| _| _| _| _|_|_| _| _|_| _|_|_|_|
_| _| _| _| _|_|_|_| _| _| _| _| _|_|_|_| _|
_| _| _| _| _| _| _| _| _| _| _|
_|_|_| _|_|_| _| _| _|_|_| _| _|_|_| _|_|
_| _| _|
_| _|_| _|_|
SYNOPSIS
pyfiglet is a full port of FIGlet () into pure
python. It takes ASCII text and renders it in ASCII art fonts (like
the title above, which is the 'block' font).
Q. Why? WHY?!
A. I was bored. Really bored.
Q. What the hell does this do that FIGlet doesn't?
A. Not much, except allow your font collection to live
in one big zipfile. The point of this code is to embed
dynamic figlet rendering in Python without having to
execute an external program, although it operates on the
commandline as well. See below for USAGE details. You can
think of this as a python FIGlet driver.
Q. Does this support kerning/smushing like FIGlet?
A. Yes, yes it does. Output should be identical to FIGlet. If
not, this is a bug, which you should report to me!
Q. Can I use/modify/redstribute this code?
A. Yes, under the terms of the GPL (see LICENSE below).
Q. I improved this code, what should I do with it?
A. You can mail patches to <cjones@insub.org>. Particularly bugfixes.
If you make changes to the kerning/mushing/rendering portion, PLEASE
test it throroughly. The code is fragile and complex.
USAGE
You can use pyfiglet in one of two ways. First, it operates on the
commandline as C figlet does and supports most of the same options.
Run with --help to see a full list of tweaks. Mostly you will only
use -f to change the font. It defaults to standard.flf.
tools/pyfiglet 'text to render'
Pyfiglet is also a library that can be used in python code:
from pyfiglet import Figlet
f = Figlet(font='slant')
print f.renderText('text to render')
pyfiglet also supports reading fonts from a zip archive. pyfiglet
comes with a file called fonts.zip which includes all of the default
fonts FIGlet comes with as well as the standard collection of user-
contributed fonts. By default, pyfiglet uses this for fonts. Specifying
a directory (on the commandline or in the Figlet() object) will override
this behavior. You may also specify a zipfile to use with -z or zipfile=PATH
in the Figlet() constructor.
If you wish to add/remove fonts or create your own font package, be aware
that there *must* be a folder in the root of the zipfile called "fonts". You
can examine the bunlded fonts.zip to see how it should be packaged.
AUTHOR
pyfiglet is a *port* of FIGlet, and much of the code is directly translated
from the C source. I optimized some bits where I could, but because the smushing
and kerning code is so incredibly complex, it was safer and easier to port the logic
almost exactly. Therefore, I can't really take much credit for authorship, just
translation. The original authors of FIGlet are listed on their website at
The Python port was done by Christopher Jones <cjones@insub LICENSE for full details)
- Downloads (All Versions):
- 0 downloads in the last day
- 70 downloads in the last week
- 3026 downloads in the last month
- Author: Peter Waller (Thanks to Christopher Jones and Stefano Rivera)
- License: GPLv2+
- Categories
- Development Status :: 5 - Production/Stable
- Environment :: Console
- Intended Audience :: Developers
- License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)
- Natural Language :: Bosnian
- Natural Language :: Bulgarian
- Natural Language :: English
- Natural Language :: Japanese
- Natural Language :: Macedonian
- Natural Language :: Russian
- Natural Language :: Serbian
- Natural Language :: Ukranian
- Operating System :: Unix
- Programming Language :: Python
- Programming Language :: Python :: 2.6
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3
- Programming Language :: Python :: 3.1
- Programming Language :: Python :: 3.2
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: 3.4
- Topic :: Text Processing
- Topic :: Text Processing :: Fonts
- Package Index Owner: pwaller
- DOAP record: pyfiglet-0.7.1.xml | https://pypi.python.org/pypi/pyfiglet/0.7.1 | CC-MAIN-2016-18 | refinedweb | 728 | 65.42 |
import to social engine.
Budget $30-250 USD
I have my database backed up in a sql file. I have 10,000 users and want the users and their details to be imported into my social engine site. I need the users imported, their images and their profile fields. I think there's about 9 fields. Need this doing asap, MAX 2 days. Preferably 1 day would be great.
Good english speaker is essential.
Prompt replys
Must have skype.
**If you cant do this, dont reply to this, thanks
P.S - Don't bid silly, wont reply.
i forgot to say that its a wordpress sql
6 freelancers are bidding on average $77 for this job
We can help in your project, please check PMB and our ratings/reviews to get idea of our experience. | https://www.freelancer.com/projects/sql-mysql/import-social-engine/ | CC-MAIN-2018-13 | refinedweb | 135 | 85.89 |
Darren Wilkinson has a nice post up comparing different programming languages (C, Java, scala, Python, and R) for writing Gibbs samplers. Unsurprisingly, C is fastest, although it is certainly not the easiest language to program in. In particular, I/O is a bitch.
Others have suggested an interesting solution: write the core of the Gibbs sampler in C and embed it in a high-level language. This saves you from writing the I/O in C. Rcpp and Cython can do this in R and Python. Here I will show how to do the same in Matlab, by automagically writing a mex file based on a numeric C snippet using mexme.
The C Gibbs sampler
Here is the original Gibbs sampler written in C:
); } }
This is a straightforward application of the GSL library. To create a mex file out of this, I extracted the numeric component of the code and saved it as djwsampler.csnip:
int i,j; gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); double x=0; double y=0; for (i=0;i<N;i++) { for (j=0;j<thin;j++) { x=gsl_ran_gamma(r,3.0,1.0/(y*y+4)); y=1.0/(x+1)+gsl_ran_gaussian(r,1.0/sqrt(2*x+2)); } samples[i] = x; samples[i+N] = y; }
Next, I created a djwsampler.includes file which contains the required #include calls for working with the GSL:
#include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h>
The Matlab interface
This is all we need to write in terms of C code. As you can see from the code above, I’ve removed the hard-coded definitions of N and thin, and instead of writing out the samples with printf, I am storing them in a samples vector of size Nx2. Thus, in Matlab, I define the two input arguments and the output argument, and then call mexme to automagically write the mex wrapper, then compile this wrapper. Thus:
inputargs = [InputNum('N',true,true,'int32'); InputNum('thin',true,true,'int32')]; outputargs = [OutputNum('samples','N,2')]; opts.extraincludes = readfile('djwsampler.includes'); cfile = mexme('djwsampler.csnip',inputargs,outputargs,opts); writefile('djwsamplermex.c',cfile) mex -lgsl -lgslcblas djwsamplermex.c
Matlab has now compiled a mex function called djwsamplermex, which can be called like any other Matlab function:
tic; results = djwsamplermex(int32(50000),int32(1000)); toc;
Then you can manipulate the results like you would any other Matlab variable. To plot, for example,
plot(results(:,1),results(:,2),'.'):
Speed
How fast is this? On a core i7 920, this takes 9.6 seconds. The original pure C version called from the command line took 9.7 seconds. That means that there is essentially no overhead in calling the mex function, and that it is slightly faster to return the raw values to Matlab than write them to a file using printf. Pretty cool, right?
Generated code
You might be wondering what mexme actually does here. It simply takes the definition of the mex file’s interface and generates the corresponding wrapper. This includes some basic checks to verify that the supplied arguments to the function make sense. Here’s what it looks like:
/* C file autogenerated by mexme.m */ #include <mex.h> #include <math.h> #include <matrix.h> #include <stdlib.h> #include <float.h> #include <string.h> /* Translate matlab types to C */ #define uint64 unsigned long int #define int64 long int #define uint32 unsigned int #define int32 int #define uint16 unsigned short #define int16 short #define uint8 unsigned char #define int8 char #define single float #include "mexmetypecheck.c" /* Your extra includes and function definitions here */ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist *N_ptr = prhs[0]; mexmetypecheck(N_ptr,mxINT32_CLASS,"Argument N (#1) is expected to be of type int32"); if(mxGetNumberOfElements(N_ptr) != 1) mexErrMsgTxt("Argument N (#1) must be scalar"); const int32 N = (int32) mxGetScalar(N_ptr); const mxArray *thin_ptr = prhs[1]; mexmetypecheck(thin_ptr,mxINT32_CLASS,"Argument thin (#2) is expected to be of type int32"); if(mxGetNumberOfElements(thin_ptr) != 1) mexErrMsgTxt("Argument thin (#2) must be scalar"); const int32 thin = (int32) mxGetScalar(thin_ptr); mwSize samples_dims[] = {N,2}; plhs[0] = mxCreateNumericArray(2,samples_dims,mxDOUBLE_CLASS,mxREAL); mxArray **samples_ptr = &plhs[0]; double *samples = (double *) mxGetData(*samples_ptr); /*Actual function*/ #include "djwsampler.csnip" }
Of course, it’s not that hard to write the C code by hand, but if you are more comfortable with Matlab than with C, mexme could be helpful. | https://xcorr.net/2011/07/16/gibbs-sampler-in-matlab-using-mexme/?shared=email&msg=fail | CC-MAIN-2019-26 | refinedweb | 719 | 56.96 |
Changelog History
Changelog History
v0.3.1 ChangesMay 28, 2020
- ⚡️ Transfer the code to the "change" namespace (only an update to
mix.exs).
v0.3.0 ChangesApril 29, 2020
- ⬆️ Upgrade
ex_cldrto version 2. From the PR description (by @barrieloydall): > This PR updates ex_cldr to the latest 2.x
version which requires a few changes beyond a number version update. > > Some initial reading: > > We are now required to a have a backend module, which i've placed in cldr_backend.ex, this essentially acts as the public interface to the CLDR functionality and is used for some of the configuration now. > > Onlyjson_library
anddefault_locale
can be defined in config, anything else will generate warnings for future deprecation. > > As we use Linguist within a couple of other apps, we need to specify anotp_app
name. This allows for related config to be passed in by our other apps. This keeps linguist just using the 3 locales it previously defined:config :linguist, Linguist.Cldr, locales: ["fr", "en", "es"]
. > > Now also defining thedata_dir`, and also ignoring it from git. Without this, I would run into an issue which I should go back and validate...
- ➕ Add sobelow to the project. Address the issues it flagged.
- ➕ Add ex_doc and tidy up the generated documentation output
v0.2.1 ChangesJanuary 25, 2018
- Add helper function for normalizing locales argument in MemorizedVocubalary.t/3. Locales will be made into the format "es-ES" or "es"
v0.2.0 ChangesOctober 22, 2018
- ♻️ LARGE SCALE REFACTOR described in this pull request
v0.1.5March 03, 2015
v0.1.4 ChangesNovember 24, 2014
- 🐛 Bug Fixes
- Fix bug causing interpolations at beginning of string to be missed
v0.1.3November 21, 2014
v0.1.0 ChangesJuly 06, 2014
✨ Enhancements
- Add
localemacro for locale definitions
- Support String filepath locale source for automated evaluation
- Suppport arbitrary locale source to fetch keyword list of translations, ie function call, Code.eval_file, etc.
- Add
t!lookups where
NoTranslationErroris raised if translation not found
Backwards incompatible changes
- Rename
Linguist.Compilerto
Linguist.Vocabulary
- Locale definitions now required to use
locale/2macro instead of
useoptions
- Update
tlookups to return
{:ok, translation}or
{:error, :no_translation}
v0.0.1 ChangesJune 28, 2014
🎉 Initial release | https://elixir.libhunt.com/linguist-changelog | CC-MAIN-2021-43 | refinedweb | 359 | 50.73 |
In this post, we will learn how to use Python Scrapy.
We will use Rust notification website This Week In Rust as an example. If you are a Rust developer, you will find you can easily extract only the parts you want from its pages.
Otherwise, use another website you want.
Prerequistes
I will suppose you already have experience with Python.
It will be helpful for you to spend a few hours to read Scrapy documentations.
Table of Contents
- Setup Python development environment
- Inspect the website
- Write Python Scrapy code
- Conclusion
You can skip 1. if you already have Scrapy development environment ready.
1. Setup Python development environment
We will start by setting Scrapy development environment with pip. Use this command.
$python3 -m venv scrapy
It will make a structure similar to this in your machine with directory name scrapy.
bin include lib lib64 pyvenv.cfg share
We don't have to care for others and our interest will be only bin/activate file to use virutalenv. We should activate Python development environment to with it.
You will have more Scrapy projects later and making alias for it will save your time. Use this command.
$vim ~/.bashrc
Then, include the code similar to this.
alias usescrapy="source /home/<youraccount>/Desktop/code/scrapy/bin/activate"
You should find the equivalent part of /home/youraccount/Desktop/code/ with $pwd command if you want to use this. Then, $source ~/.bashrc and you can use this Python development environment with $usescrapy only whenever you want.
Type $usescrapy and $pip install ipython scrapy. It will install the minimal dependencies to use Python Scrapy.
If you want to reuse the exactly same packages later, use these commands.
- $pip freeze > requirements.txt to extract the list of them.
- $pip install -r requirements.txt to install them later.
2. Inspect the website
I hope you already visited the Rust notification website or other websites you want to crawl.
Refer to the processes used here with Scrapy Tutorial and apply it later to a website you want to scrap.
I will assume you already know how to use browser inspector and familiar with CSS and HTML.
The purpose of This Week In Rust is to give you useful links relevant to Rust for each week.
It has the recent issue links in the homepage.
When you visit each of them, you will see the list of links for blog posts, crates(packages in Rust), call for participation, events, jobs etc.
Back to its homepage and use your browser inspector with CRTL+SHIFT+I and find how its html is structured. You can see that it is just simple static website with a CSS framework.
Inspect This week in Rust of publication part. Then, you will find many html tags similar to this.
<a href="">This Week in Rust</a>
Collecting those links to follow will be our main job for this page. They will be the entry points to the pages with target informations that we will scrap.
Visit one of them. When you inspect jobs parts and others you want to scrap, you will see that they structure similar to this.
Our main target will be href to help you find job titles and job links for them. It is the part of a tag that are wrapped with li and its parent element ul.
You can see that ul is also followed by h1 or h2 tags with ids. Knowing how html tags are organized for the data we want to scrap will help you test the Scrapy code we will write in the next part.
3. Write Python Scrapy code
We set up development environment and have the information ready to use with the previous parts. What left is to write the Python code for Scrapy.
Before that, use shell command from Scrapy CLI to test how the Scrapy programm will see the webpage.
$scrapy shell
Use another website you want to scrap if you have any. Then, the console will become the Ipython mode with information similar to this.
[s] Available Scrapy objects: [s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc) [s] crawler <scrapy.crawler.Crawler object at> [s] item {} [s] request <GET> [s] response <200> [s] settings <scrapy.settings.Settings> [s] spider <DefaultSpider 'default'> [s] Useful shortcuts: [s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed) [s] fetch(req) Fetch a scrapy.Request and update local objects [s] shelp() Shell help (print this help) [s] view(response) View response in a browser
Use $view(response) first to verify your target websites can be read by Scrapy. For example, if the website is rendered with JavaScript, it may not work well and you should find more documentation for that.
With This Week In Rust, there will be no problem because it is just a normal static website.
You can play with Scrapy shell mode with request, response etc. For example, use response.body, response.title. Then, exit it with
quit()and start your Scrapy project.
Use $scrapy startproject notification rust.
It will automatically generate Scrapy project folder with rust and project name notification and will show message similar to this in your console.
cd rust scrapy genspider example example.com
You can use $scrapy startproject -h for more information.
Follow the instruction.
Then, use command similar to $scrapy genspider this_week_in_rust this-week-in-rust.org/.
It should have created spiders/this_week_in_rust.py in your machine. Then, We will write code for the spider(this_week_in_rust.py).
Edit it similar to this.
import scrapy class ThisWeekInRustSpider(scrapy.Spider): name = 'this_week_in_rust' start_urls = [''] # 1. def parse(self, response): # Or test it with $scrapy shell for href in response.css("div.custom-xs-text-left > a::attr(href)").getall(): # 1. # print("page") # print(href) yield response.follow(href, self.parse_jobs) # 2. def parse_jobs(self, response): date = ".".join(response.url.split("/")[4:7]).replace(".","-") # Or test it with $scrapy shell<date>/<text> job_titles = response.css("#rust-jobs ~ p ~ ul > li > a::text").getall() job_urls = response.css("#rust-jobs ~ p ~ ul > li > a::attr(href)").getall() jobs = { **dict(zip(job_titles, job_urls)) } # 2. # print("\n") # print(date) # print(jobs) # jobs = { "job": len(job_titles), **dict(zip(job_titles, job_urls)) } # 3. jobs = { "total_jobs": len(job_titles), **dict(zip(job_titles, job_urls)) } # sorted(list, key = lambda i: i["Posts"], reverse = True) yield { "date": date, **jobs, } # yield { # "date": date, # "jobs": jobs, # }
We just converted the information we get from the previous part into Python code with Scrapy.
1. we extract the publication page links to follow with CSS Selectors. div.custom-xs-text-left is to help it to select href part in a tags.
We extract all links to follow through so we use getall().
Then, we define what to do with them with parse_post_and_jobs callback function.
2. This is payload of all these processes. We extract date of the publication, the total number of them, titles and other important datas of Rust jobs to make the information useful.
Then, we turn it into JSON format with Python API.
You can see the pattern that only id part such as #news-blog-posts, #rust-jobs are different and others are repeated.
You can easily include events, call for participation etc from the website if you want to scrap other parts.
3. We return the data we want to use here.
Your code will be different from this if you used other websites but the main processes to find what you want will be similar.
- Get the links to follow to visit the payload webpages.
- Extract the information you want at each page.
Test it work with $scrapy crawl this_week_in_rust -o rust_jobs.json.
Then, you can verify the result similar to this structure.
[ {"date": "", "total_jobs": "", "job_name": "job_link"} ]
It may not be ordered well by date. Therefore, make Python file similar to this if you want.
# sort_json.py import os import sys import json target = sys.argv[1] with open(target, 'r') as reader: json_str = reader.read() json_lists = json.loads(json_str) # dict, read with open(target, 'w+') as writer: sorted_list = sorted(json_lists, key = lambda i: i["date"], reverse = True) # only work for list of dicts json_sorted_str = json.dumps(sorted_list, indent=4) # write writer.write(json_sorted_str) print(f"Sort {target} by dates.")
Use it with $python sort_json.py rust_jobs.json and it will organize the JSON file by dates.
You should comment or remove sort_json.py from your Scrapy project if you want to use this project later.
4. Conclusion
In this post, we learnt how to use Python Scrapy. If you followed this post well, what you need later will be just use $scrapy genspider and edit the Python file(spider) made from it.
I hope this post be helpful for other Rust developers who wait for This Week In Rust every week and also for people who want to learn Python Scrapy.
If you need to hire a developer, you can contact me.
Thanks.
Top comments (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/steadylearner/how-to-use-python-scrapy-to-scrap-a-website-with-examples-298i | CC-MAIN-2022-40 | refinedweb | 1,486 | 67.65 |
Asked by:
Working on 2 projects under single solution
Question
Hello, I am working on 2 project under single solution in C# desktop application. Here I want to update a Label on form1 of project1 which is dependent on project2 string variable (a calculation is happened on project2). Note that this is all required on runtime.
I have tried so many techniques; I have made a static variable on project1 and send it to project2 i.e., Process.Start("Project2.exe", textbox1.Text) for calculation and on button click from project2 a static method is called which is made on project1 for what I want to update a label on form, but because of static method label is not accessible there.
All replies
Hello,
See the following on anonymous pipes. have tried so many techniques
Simply add reference to the project 2 in project 1.
> a static method is called
In this situation you need to organize access to the form and to the label on the form. Simplest way - have a static reference to the form.
But, by my opinion, you doing something wrong...
Sincerely, Highly skilled coding monkey.
> both are the projects which contains forms.
Stefan ask about what project have as result - *.EXE or *.DLL? Difference is - first is self-executable file and second need some another executable to make it work.
Is there form or not - does not matter.
Sincerely, Highly skilled coding monkey.
This was not the question..
But in this case:
You need three projects. Your two application (UI) projects and one class library. Place the common (calculation code) in the class library. Then reference the class library in both UI projects and use the common code.
Thanks for the reply Stefan, but the communication between the projects is easily done using static variables, but the question is how could I update a label or textbox on runtime where both project1 and project2 is on running condition. Actually, I want to change the text of label or textbox of project1 using the value of project2.
I had made a static variable in project1 and on the run of project2 it calls there and calculation happened there after that I want to update to update text of label or textbox.
Is there any option to assign static variable to non-static label or textbox? I know this is creepy
Greetings Naveed.
So the two projects are executables, running at the same time, correct?
There's probably a proper robust way of doing this using remoting or a service or something, but there is also a quick and dirty fix that a lazy programmer like myself would use.
In the project sending the information, write the text to a file. In the project receiving the information, use a timer to look for the file every few seconds (say five seconds, or whatever) and read it if it exists then delete the file.
Hi M Naveed Qamar,
I would suggest that project2 could save the string variable into a text file after it changed. set a timer control in project form, which read the text file and modify the label's text..
> how could I update a label or textbox on runtime where both project1 and project2 is on running condition.
There was mentioned PIPES between process.
But I would say again - if it required there are a problem with task definition or code organisation,
Sincerely, Highly skilled coding monkey.
namespace Poject1 { public partial class Form1: Telerik.WinControls.UI.RadForm { public static string Points=""; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Process.Start("Project2.exe"); } public static void CallProject1() { Label1.Text=Points; // this line alert error "Object reference not set to the instance of an object" when I had made Label1 public static } } } using Project1; namespace Poject2 { public partial class Form2: Telerik.WinControls.UI.RadForm { string AddPoints="2"; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form1.Points=this.AddPoints; Form1.CallProject1(); } } }
Above was just a demonstration of what I really want.
- Edited by M Naveed Qamar Thursday, September 27, 2018 10:55 AM
Instead of
private void button1_Click(object sender, EventArgs e) { Process.Start("Project2.exe"); }
use
private void button1_Click(object sender, EventArgs e) { Project2.Form2 form2 = new Project2.Form2; form2.Form1 = this; form2.Show(); } public void UpdateLabel(string text) { mylabel.Text = text; }
in form 2:
Form1 Form1 {get; set; } private void button1_Click(object sender, EventArgs e) { Form1.UpdateLabel("My texte for label"); }
Sincerely, Highly skilled coding monkey.
No, two form projects do not work in the manner you are trying to use them. You can have two or more Windows form projects in a .NET solution, but they are independent of each other as individual exe(s) that would be generated.
You can have more than one form in a .NET Windows forms based solution and the forms within the same Windows form project can communicate with each other.
But no, what you are thinking will not work.
Why starting the second project as process?
private void button1_Click(object sender, EventArgs e) { Process.Start("Project2.exe"); }
When it must be a separate process, then you need inter-process communication (IPC). This can be (named) pipes, shared memory or TCP/IP. Even Windows messaging.
When it must not be a separate process, then you can do what Andrey already wrote.
It's time that you explain in detail, why you want to exchange what data on what purpose. | https://social.msdn.microsoft.com/Forums/en-US/c34682b3-8291-4932-b1e8-7cd29b49a875/working-on-2-projects-under-single-solution?forum=csharpgeneral | CC-MAIN-2020-50 | refinedweb | 907 | 65.73 |
XvGrabPort(3X) UNIX Programmer's Manual XvGrabPort(3X)
XvGrabPort - lock port for exclusive use by client
#include <X11/extensions/Xvlib.h> XvGrab vari- able. The display option has the format hostname:number. Using two colons (::) instead of one (:) indicates that DECnet is to be used for transport. port Defines the port to be grabbed. time Specifies the request timestamp.
XvGrabPort(3X) grabs a port. Once a client grabs a port, only that client can make video requests to that port. pro- cessed:.
[Success] Returned if XvGrabPort(3X) completed successfully. [XvInvalidTime] Returned if requested time is older than the current port time. [XvAlreadyGrabbed] Returned if the port is already grabbed by another XFree86 Version 4.5.0 1 XvGrabPort(3X) UNIX Programmer's Manual XvGrabPort(3X) client. [XvBadExtension] Returned if the Xv extension is unavailable. [XvBadAlloc] Returned if XvGrabPort(3X) failed to allocate memory to process the request.
[XvBadPort] Generated if the requested port does not exist.
XvUngrabPort. | http://mirbsd.mirsolutions.de/htman/sparc/man3/XvGrabPort.htm | crawl-003 | refinedweb | 157 | 53.37 |
apollo13 0 Posted July 25, 2012 I have wrote this script in order to move mouse on systray icon of my programs and entry in their menus. It's all right! QUESTION: If i don't have programs loaded in systray and i want Move Mouse on systray Clock how can I do ?? I can manually insert coordinates "x", "y" of the position of "DATE CLOCK" but if i change screen resolution change also coordinates. How can test Systray Clock Position and move mouse there ??? I can't insert into variable $st_process because there is no process running and now how can do ?? #NoTrayIcon #include <SysTray_UDF.au3> $st_process = "MyProgram.exe" If not processexists($st_process) then Run("C:\Program Files\Prog\" & $st_process) endif ; -------- wait until TootlTip NOT EXIST (program is loading not ready yet) --------- while not _SysTrayIconTooltip(_SysTrayIconIndex($st_process))="ProgramToolTip" sleep (100) wend ; -------------------------------------------------------------------------------------- $pos = _SysTrayIconPos(_SysTrayIconIndex($st_process)) mouseMove($pos[0], $pos[1], 0) Thank you Share this post Link to post Share on other sites | https://www.autoitscript.com/forum/topic/142745-systray-clock-coordinate/ | CC-MAIN-2018-34 | refinedweb | 164 | 63.39 |
.
To give you all a brief outline of what we will be tackling in this post, here’s a quick list of steps:
1) Define our symbol pair, download the relevant price data from yahoo Finance and make sure the data downloaded for each symbol is of the same length.
2) Plot the two ETF price series against each other to get a visual representation, then run a Seaborn “jointplot” to analyse the strength of correlation between the two series.
3) Run an Ordinary Least Squares regression on the closing prices to calculate a hedge ratio. Use the hedge ratio to generate the spread between the two prices, and then plot this to see if it looks in any way mean reverting.
4) Run an Augmented Dickey Fuller test on the spread to confirm statistically whether the series is mean reverting or not. We will also calculate the Hurst exponent of the spread series.
5) Run an Ordinary Least Squares regression on the spread series and a lagged version of the spread series in order to then use the coefficient to calculate the half-life of mean reversion.
Right now let’s get to some code…time to import the relevant modules we will need, set our ETF ticker symbols and download the price data from Yahoo Finance.
#import needed modules from datetime import datetime from pandas_datareader import data import pandas as pd import numpy as np from numpy import log, polyfit, sqrt, std, subtract import statsmodels.tsa.stattools as ts import statsmodels.api as sm import matplotlib.pyplot as plt import seaborn as sns import pprint #choose ticker pairs for our testing symbList = ['EWA','EWC'] start_date = '2012/01/01' end_date = datetime.now() #download data from Yahoo Finance y=data.DataReader(symbList[0], "yahoo", start=start_date, end=end_date) x=data.DataReader(symbList[1], "yahoo", start=start_date, end=end_date) #rename column to make it easier to work with later y.rename(columns={'Adj Close':'price'}, inplace=True) x.rename(columns={'Adj Close':'price'}, inplace=True) #make sure DataFrames are the same length min_date = max(df.dropna().index[0] for df in [y, x]) max_date = min(df.dropna().index[-1] for df in [y, x]) y = y[(y.index>= min_date) & (y.index <= max_date)] x = x[(x.index >= min_date) & (x.index <= max_date)]
Now that we have our price data stored in DataFrames, let’s just bring up a quick plot of the two series to see what information we can gather
plt.plot(y.price,label=symbList[0]) plt.plot(x.price,label=symbList[1]) plt.ylabel('Price') plt.xlabel('Time') plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show()
It looks like the prices are definitely correlated to a degree, and generally move in the same direction. But just how strong is this correlation? Well there’s an easy way to get a clearer visual representation of this…we can just use a Seaborn “jointplot” as follows:
sns.jointplot(y.price, x.price ,color='b') plt.show()
We can see from the information provided in the jointplot that the Pearson Correlation coefficient is 0.87 – so we can see that there is definitely a pretty strong correlation here between the price series. This sets the pair up as a potentially good fit for a mean reversion strategy.
What we need to do now is create the spread series between the two prices by first running a linear regression analysis between the two price series.
#run Odinary Least Squares regression to find hedge ratio #and then create spread series df1 = pd.DataFrame({'y':y['price'],'x':x['price']}) est = sm.OLS(df1.y,df1.x) est = est.fit() df1['hr'] = -est.params[0] df1['spread'] = df1.y + (df1.x * df1.hr)
Right so we have now managed to run the regression between the ETF price series; the beta coefficient from this regression was then used as the hedge ratio to create the spread series of the two prices.
If we plot the spread series we get the following:
plt.plot(df1.spread) plt.show()
So it looks relatively mean reverting. But sometimes looks can be deceiving, so really it would be great if we could run some statistical tests on the spread series to get a better idea. The test we will be using is the Augmented Dickey Fuller test. You can have a quick read up about it here if you need to refresh your memory:
cadf = ts.adfuller(df1.spread) print 'Augmented Dickey Fuller test statistic =',cadf[0] print 'Augmented Dickey Fuller p-value =',cadf[1] print 'Augmented Dickey Fuller 1%, 5% and 10% test statistics =',cadf[4]
This gets us the following:
Augmented Dickey Fuller test statistic = -3.21520854685 Augmented Dickey Fuller p-value = 0.0191210549486 Augmented Dickey Fuller 1%, 5% and 10% test statistics= {'5%': -2.86419037625175, '1%': -3.436352507699052, '10%': -2.5681811468354598}
From this we can see that the test statistic of -3.215 is larger in absolute terms than the 10% test statistic of -2.568 and the 5% test statistic of -2.864, but not the 1% test statistic of -3.436, meaning we can reject the null hypothesis that there is a unit root in the spread time series, and is therefore not mean reverting, at both the 10% and 5% level of significance, but not at the 1% level.
The p-value of 0.0191 means that we can reject the null hypothesis up to the 1.91% significance level. That’s pretty good in terms of statistical significance, and from this we can be pretty certain that the spread series does in fact posses mean reverting qualities.
The last thing we will do is run a quick function to calculate the Hurst exponent of the spread series.
For info on the Hurst Exponent please refer to: this article
To simplify things, the important info to remember here is that a time series can be characterised in the following manner with regard to the Hurst exponent (H):
H < 0.5 – The time series is mean reverting H = 0.5 – The time series is a Geometric Brownian Motion H > 0.5 – The time series is trending
I have “borrowed” a code snippet of a Hurst Exponent function found on the blog (great site by the way – definitely worth checking out).
The post containing the “borrowed” code can be found here:
and here is the code:
Now we run the function on the spread series:
print "Hurst Exponent =",round(hurst(df1.spread),2)
and get:
Hurst Exponent = 0.42
The Hurst Exponent is under the 0.5 value of a random walk and we can therefore conclude that the series is mean reverting, which backs up our conclusion based on the Augmented Dickey Fuller test previously. Good! This means that the spread series looks like a definite candidate for a mean reversion strategy, what with the spread series being mean reverting and all.
However just because a time series displays mean reverting properties, it doesn’t necessarily mean that we can trade it profitably – there’s a difference between a series that deviates and mean reverts every week and one that takes 10 years to mean revert. I’m not sure too many traders would be willing to sit and wait around for 10 years to close out a trade profitably.
To get an idea of how long each mean reversion is going to take, we can look into the “half-life” of the time series. Please click here for more info on half-life.
We can calculate this by running a linear regression between the spread series and a lagged version of itself. The Beta coefficient produced by this regression can then be incorporated into the Ornstein-Uhlenbeck process to calculate the half-life.
Please see here for some more info.
The code to calculate this is as follows:
#Run OLS regression on spread series and lagged version of itself spread_lag = df1.spread.shift(1) spread_lag.ix[0] = spread_lag.ix[1] spread_ret = df1.spread - spread_lag spread_ret.ix[0] = spread_ret.ix[1] spread_lag2 = sm.add_constant(spread_lag) model = sm.OLS(spread_ret,spread_lag2) res = model.fit() halflife = round(-np.log(2) / res.params[1],0) print 'Halflife = ',halflife
Which gets us:
Halflife = 40.0
So according to this result, the halflife of mean reversion is 40 days. That’s not too bad, and not so long as to automatically exclude it from consideration for a mean reversion strategy. Ideally the half-life would be as short as possible so as to provide us with more profitable trading opportunities but there you have it, 40 days is what we have.
OK so I think I’ll cut it here as this is getting a little long. Next post we will work on producing a normalised “Z Score” series that allows us to see the deviation away from the local mean in terms of standard deviations. We will then begin the actual backtest itself using Pandas and see if we can produce something that is any way profitable.
If anyone has any comments, please leave them below – always eager to hear the thoughts of others.
Until next time!
Hello, you are doing a great job here quoting excellent examples, but here i wanted to understand what has changed as I am unable to find update on difference function :
def hurst(ts):
lags=range(2,100)
tau=[np.sqrt(np.std(difference(ts[lag:],ts[:-lag]))) for lag in lags]
poly=polyfir(log(lags),log(tau),1)
return poly[0]*2
when I am running above code, this is throwing below error:
“NameError: name ‘difference’ is not defined”
could you please check and let me understand the change.
thanks
Use This one –
[…] I will also define a function for “Halflife” which just recycles some tof the code from my mean reversion pairs trading blog post from a couple of years ago, which can be found here. […]
It would be a nice touch to show how from the OLS regression of the spread and the lag one could use the OU dynamics to simulate the data
Great blog!! I just try to run the Hurst test, following error message:
Hurst Exponent = nan
main:10: RuntimeWarning: divide by zero encountered in log
Using this code:
Hurst Test
print (“Hurst Exponent =”,round(hurst(df1.spread),2))
Please help
It seems like one of the values you are passing to numpy.log is zero. Saying as “lags” is just a range with no zero value- it must be one of your “tau” values I would imagine.
That’s the error message you get when this occurs: | https://www.pythonforfinance.net/2016/05/09/python-backtesting-mean-reversion-part-2/ | CC-MAIN-2020-10 | refinedweb | 1,764 | 63.9 |
Wireless systems come with a lot of flexibility but on the other hand, it leads to serious security issues too. And, how does this become a serious security issue — because attackers, in case of wireless connectivity, just need to have the availability of signal to attack rather than have the physical access as in case of wired network. Penetration testing of the wireless systems is an easier task than doing that on the wired network. We cannot really apply good physical security measures against a wireless medium, if we are located close enough, we would be able to "hear" (or at least your wireless adapter is able to hear) everything, that is flowing over the air.
Before we get down with learning more about pentesting of wireless network, let us consider discussing terminologies and the process of communication between the client and the wireless system.
Let us now learn the important terminologies related to pentesting of wireless network.
An access point (AP) is the central node in 802.11 wireless implementations. This point is used to connect users to other users within the network and also can serve as the point of interconnection between wireless LAN (WLAN) and a fixed wire network. In a WLAN, an AP is a station that transmits and receives the data.
It is 0-32 byte long human readable text string which is basically the name assigned to a wireless network. All devices in the network must use this case-sensitive name to communicate over wireless network (Wi-Fi).
It is the MAC address of the Wi-Fi chipset running on a wireless access point (AP). It is generated randomly.
It represents the range of radio frequency used by Access Point (AP) for transmission.
Another important thing that we need to understand is the process of communication between client and the wireless system. With the help of the following diagram, we can understand the same −
In the communication process between client and the access point, the AP periodically sends a beacon frame to show its presence. This frame comes with information related to SSID, BSSID and channel number.
Now, the client device will send a probe request to check for the APs in range. After sending the probe request, it will wait for the probe response from AP. The Probe request contains the information like SSID of AP, vender-specific info, etc.
Now, after getting the probe request, AP will send a probe response, which contains the information like supported data rate, capability, etc.
Now, the client device will send an authentication request frame containing its identity.
Now in response, the AP will send an authentication response frame indicating acceptance or rejection.
When the authentication is successful, the client device has sent an association request frame containing supported data rate and SSID of AP.
Now in response, the AP will send an association response frame indicating acceptance or rejection. An association ID of the client device will be created in case of acceptance.
We can gather the information about SSID with the help of raw socket method as well as by using Scapy library.
We have already learnt that mon0 captures the wireless packets; so, we need to set the monitor mode to mon0. In Kali Linux, it can be done with the help of airmon-ng script. After running this script, it will give wireless card a name say wlan1. Now with the help of the following command, we need to enable monitor mode on mon0 −
airmon-ng start wlan1
Following is the raw socket method, Python script, which will give us the SSID of the AP −
First of all we need to import the socket modules as follows −
import socket
Now, we will create a socket that will have three parameters. The first parameter tells us about the packet interface (PF_PACKET for Linux specific and AF_INET for windows), the second parameter tells us if it is a raw socket and the third parameter tells us that we are interested in all packets.
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0003))
Now, the next line will bind the mon0 mode and 0x0003.
s.bind(("mon0", 0x0003))
Now, we need to declare an empty list, which will store the SSID of APs.
ap_list = []
Now, we need to call the recvfrom() method to receive the packet. For the sniffing to continue, we will use the infinite while loop.
while True: packet = s.recvfrom(2048)
The next line of code shows if the frame is of 8 bits indicating the beacon frame.
if packet[26] == "\x80" : if packetkt[36:42] not in ap_list and ord(packetkt[63]) > 0: ap_list.add(packetkt[36:42]) print("SSID:",(pkt[64:64+ord(pkt[63])],pkt[36:42].encode('hex')))
Scapy is one of the best libraries that can allow us to easily sniff Wi-Fi packets. You can learn Scapy in detail at. To begin with, run Sacpy in interactive mode and use the command conf to get the value of iface. The default interface is eth0. Now as we have the dome above, we need to change this mode to mon0. It can be done as follows −
>>> conf.>> packets = sniff(count = 3) >>> packets <Sniffed: TCP:0 UDP:0 ICMP:0 Other:5> >>> len(packets) 3
Let us now import Scapy as a library. Further, the execution of the following Python script will give us the SSID −
from scapy.all import *
Now, we need to declare an empty list which will store the SSID of APs.
ap_list = []
Now we are going to define a function named Packet_info(), which will have the complete packet parsing logic. It will have the argument pkt.
def Packet_info(pkt) :
In the next statement, we will apply a filter which will pass only Dot11 traffic which means 802.11 traffic. The line that follows is also a filter, which passes the traffic having frame type 0 (represents management frame) and frame subtype is 8 (represents beacon frame).
if pkt.haslayer(Dot11) : if ((pkt.type == 0) & (pkt.subtype == 8)) : if pkt.addr2 not in ap_list : ap_list.append(pkt.addr2) print("SSID:", (pkt.addr2, pkt.info))
Now, the sniff function will sniff the data with iface value mon0 (for wireless packets) and invoke the Packet_info function.
sniff(iface = "mon0", prn = Packet_info)
For implementing the above Python scripts, we need Wi-Fi card that is capable of sniffing the air using the monitor mode.
For detecting the clients of access points, we need to capture the probe request frame. We can do it just as we have done in the Python script for SSID sniffer using Scapy. We need to give Dot11ProbeReq for capturing probe request frame. Following is the Python script to detect clients of access points −
from scapy.all import * probe_list = [] ap_name= input(“Enter the name of access point”) def Probe_info(pkt) : if pkt.haslayer(Dot11ProbeReq) : client_name = pkt.info if client_name == ap_name : if pkt.addr2 not in Probe_info: Print(“New Probe request--”, client_name) Print(“MAC is --”, pkt.addr2) Probe_list.append(pkt.addr2) sniff(iface = "mon0", prn = Probe_info)
From the perspective of a pentester, it is very important to understand how a wireless attack takes place. In this section, we will discuss two kinds of wireless attacks −
The de-authentication (deauth) attacks
The MAC flooding attack
In the communication process between a client device and an access point whenever a client wants to disconnect, it needs to send the de-authentication frame. In response to that frame from the client, AP will also send a de-authentication frame. An attacker can get the advantage from this normal process by spoofing the MAC address of the victim and sending the de-authentication frame to AP. Due to this the connection between client and AP is dropped. Following is the Python script to carry out the de-authentication attack −
Let us first import Scapy as a library −
from scapy.all import * import sys
Following two statements will input the MAC address of AP and victim respectively.
BSSID = input("Enter MAC address of the Access Point:- ") vctm_mac = input("Enter MAC address of the Victim:- ")
Now, we need to create the de-authentication frame. It can be created by executing the following statement.
frame = RadioTap()/ Dot11(addr1 = vctm_mac, addr2 = BSSID, addr3 = BSSID)/ Dot11Deauth()
The next line of code represents the total number of packets sent; here it is 500 and the interval between two packets.
sendp(frame, iface = "mon0", count = 500, inter = .1)
Upon execution, the above command generates the following output −
Enter MAC address of the Access Point:- (Here, we need to provide the MAC address of AP) Enter MAC address of the Victim:- (Here, we need to provide the MAC address of the victim)
This is followed by the creation of the deauth frame , which is thereby sent to access point on behalf of the client. This will make the connection between them cancelled.
The question here is how do we detect the deauth attack with Python script. Execution of the following Python script will help in detecting such attacks −
from scapy.all import * i = 1 def deauth_frame(pkt): if pkt.haslayer(Dot11): if ((pkt.type == 0) & (pkt.subtype == 12)): global i print ("Deauth frame detected: ", i) i = i + 1 sniff(iface = "mon0", prn = deauth_frame)
In the above script, the statement pkt.subtype == 12 indicates the deauth frame and the variable I which is globally defined tells about the number of packets.
The execution of the above script generates the following output −
Deauth frame detected: 1 Deauth frame detected: 2 Deauth frame detected: 3 Deauth frame detected: 4 Deauth frame detected: 5 Deauth frame detected: 6
The MAC address flooding attack (CAM table flooding attack) is a type of network attack where an attacker connected to a switch port floods the switch interface with very large number of Ethernet frames with different fake source MAC addresses. The CAM Table Overflows occur when an influx of MAC addresses is flooded into the table and the CAM table threshold is reached. This causes the switch to act like a hub, flooding the network with traffic at all ports. Such attacks are very easy to launch. The following Python script helps in launching such CAM flooding attack −
from scapy.all import * def generate_packets(): packet_list = [] for i in xrange(1,1000): packet = Ether(src = RandMAC(), dst = RandMAC())/IP(src = RandIP(), dst = RandIP()) packet_list.append(packet) return packet_list def cam_overflow(packet_list): sendp(packet_list, iface='wlan') if __name__ == '__main__': packet_list = generate_packets() cam_overflow(packet_list)
The main aim of this kind of attack is to check the security of the switch. We need to use port security if want to make the effect of the MAC flooding attack lessen. | https://www.tutorialspoint.com/python_penetration_testing/python_penetration_testing_pentesting_of_wireless_network.htm | CC-MAIN-2019-39 | refinedweb | 1,773 | 62.27 |
log10 - base 10 logarithm function
#include <math.h> double log10(double x);
The log10() function computes the base 10 logarithm of x, log10(x). The value of x must be positive.
An application wishing to check for error situations should set errno to 0 before calling log10(). If errno is non-zero on return, or the return value is NaN, an error has occurred.
Upon successful completion, log10() returns the base 1010() function will fail if:
- [EDOM]
- The value of x is negative.
The log10() function may fail if:
- [EDOM]
- The value of x is NaN.
- [ERANGE]
- The value of x is 0.
No other errors will occur.
None.
None.
None.
isnan(), log(), pow(), <math.h>.
Derived from Issue 1 of the SVID. | http://pubs.opengroup.org/onlinepubs/007908775/xsh/log10.html | CC-MAIN-2015-35 | refinedweb | 123 | 77.53 |
module to create a scientific calculator in Python. We’ll be building off of the original calculator program, so if you have that, feel free to load it up. There are four steps to building a scientific calculator in Python, they are:
- Creating Function Definitions
- The Operation Map
- Getting the Desired Operation from the User
- Mapping and Performing Operations
Creating Function Definitions
The first thing we need to do is create the functions for each operation we want our calculator to have. Last time we created four functions: add, subtract, divide, and multiply. This time, we’ll add four more functions.
We’ll add square, square root (
sqrt), log, and exponentiate. The square, square root, and log functions each take one parameter. Meanwhile, the exponentiate function takes two parameters like the other four functions we originally created.
import math # create function declarations def add(a, b): return a + b def subtract(a, b): return a - b def divide(a, b): return a/b def multiply(a, b): return a*b def square(a): return a**2 def sqrt(a): return math.sqrt(a) def log(a): return math.log(a) def exponentiate(a, b): return a**b
The Operation Map
Next, we’ll create an operation map. This is simply a dictionary that maps a string onto a function. This is one of the nice things about Python, we can set the function as the value in a dictionary automatically. The only string we’ll change from the actual function name is
sqrt to “square root”.
# create map function_map = { "add": add, "subtract": subtract, "divide": divide, "multiply": multiply, "square": square, "square root": sqrt, "log": log, "exponentiate": exponentiate }
Getting the Desired Operation from the User
Now we have all our functions written and the dictionary map that maps strings to functions. Next, we’ll write the code to ask the user for the input string. This string has to be one of the strings that is a key in the dictionary. We’ll give the user a list of possible operations, so they know which ones are available.
# ask user for desired operation op = input("Which operation would you like to do? Add, subtract, divide, multiply, square, square root, log, or exponentiate? ")
Mapping and Performing Operations
At this point, everything is set up except for the actual execution of the operations. Unlike the four-function calculator, we have two kinds of operations, ones that take one argument and ones that take two. That’s why we asked for the operation first this time.
We’ll have to check if the operation is one of the three operations that only takes one input. If it does, then we’ll ask for one number. We’ll use the map to get the function and then pass the user input number to it and print our result.
If we are using one of the operations that require two parameters, we’ll ask the user for two numbers. Once we have the two numbers, we’ll call the function map to get the function and then pass the two input parameters to it. Then, we’ll print out the value returned from the function.
if op in ["square", "square root", "log"]: a = float(input("What number would you like to perform your operation on? ")) x = function_map[op](a) print(x) else: a = float(input("What is the first number? ")) b = float(input("What is the second number? ")) x = function_map[op](a, b) print(x)
Summary of Creating a Scientific Calculator in Python
In this post we extended the basic, four-function calculator into a scientific calculator. We added four functions, two of which use the
math library, and three of which take only one parameter. We also extended the function dictionary. Then we changed up our input pattern to get the function first before asking for the numbers because the functions don’t take the same number of parameters anymore. | https://pythonalgos.com/level-1-python-scientific-calculator/?amp=1 | CC-MAIN-2022-27 | refinedweb | 654 | 62.78 |
Modify the flags associated with a connection
#include <sys/neutrino.h> int ConnectFlags( pid_t pid, int coid, unsigned mask, unsigned bits ); int ConnectFlags_r( pid_t pid, int coid, unsigned mask, unsigned bits );
In QNX Neutrino 7.0 and later, the server or client can set this flag if it doesn't trust the program at the other end of the connection, but only the kernel can clear it.
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.:
For more information, see procmgr_ability().
The previous value of the flags associated with the connection. If an error occurs: | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/c/connectflags.html | CC-MAIN-2018-43 | refinedweb | 105 | 58.69 |
Intro: Esp32 Temperature and Humidity Web Server Using PYTHON & Zerynth IDE
Esp32 is a magnificent micro-controller, It is powerful just like an Arduino but even better!
It has Wifi connectivity, Enabling you to develop IOT projects cheaply and easily.
But Working with Esp devices is frustrating, First it is not stable, Second it is extremely difficult to develop your projects with the official SDK. Third it is a huge headache to find a suitable working library.
What if you could use all of the functionalities of the mico-controller while also code it in PYTHON.
Would it make a difference? of course, Python is powerful, easy to read and extremely easy to write.
Plus you don't have to worry about all of the low level stuff (pointers, registers and configuration files)
Also, You are using Zerynth stable system.
If you are not familiar with Zerynth yet, it is the next BIG THING!
It gives you all of the functionalities of the micro-controller with the easiness of Python and it is Free
Let me introduce to you the Esp32 Temperature and humidity web server written in Python.
Step 1: Step 1 : Hardware Connection
The hts221 Temp and humidty sensor uses I2C connection, You have to connect the sensor to the appropriate pins in the ESp32
Node-MCU Esp32s Hts221 Sensor
3v3 pin --> 3.3v pin
GND pin --> GND pin
IO26 --> SCL pin
IO25 --> SDA pin
Step 2: Step 2 : ESP32 Code
- Connect your Esp32 development board to your computer.
- Download the Latest Zerynth Studio IDE for free :
Use this installation Guide to help you:...
- Inside the application; Create a new account and vertualize your device.
Use this guide to help you...
- Now Create a new project from main toolbar ; Project --> New -->Write a name for the project and save it.
- Find the code Attached
- Copy the code and Uplink ( upload to the uC)
- Open serial monitor
- Copy the Ip-address to your browser and open the web page !
If you need help with the IDE :
Step 3: Step3 : Code Sample !
You can find the whole project attached!
This wanted to show you how easy it is:
from stm.hts221 import hts221
temp_hum = hts221.HTS221( I2C0,D16) #initiate i2C protocol with the sensor
temp, hum = temp_hum.get_temp_humidity() # get the current temp and humidty using the library !
--------------------------------------------------------------------------------------------------------------------
from espressif.esp32net import esp32wifi as wifi_driver #importing Esp32 Wifi driver
WifiAP_name = "WIFI AP Name"
Wifi_Pass = "Wifi Pass!"
wifi_driver.auto_init()
wifi.link(WifiAP_name,wifi.WIFI_WPA2,Wifi_Pass)
---------------------------------------------------------------------------------------------------------------------
It is that easy to use Zerynth IDE with python.
Discussions
4 weeks ago
Welcome to Instructables. Thanks for sharing with the community. | https://www.instructables.com/id/Esp32-Temperature-and-Humidity-Web-Server-Using-PY/ | CC-MAIN-2018-43 | refinedweb | 436 | 64.2 |
CodePlexProject Hosting for Open Source Software
Hi All,
Firstly I'd just like to thank the Farseer team for providing us all with such an amazing physics engine, especially as it's completely free! It's very generous of them and I'm very grateful.
I've read quite a few threads on the forum and it looks like there's a very helpful and friendly user/dev community here, so I hope someone can help me out. I'm trying to learn how to use Farseer for my 2d game with the XNA framework but I'm
struggling to get to grips with how it works. I've read the manual and I've looked at the simple examples, but I'm still finding it somewhat difficult. The examples with the menu system are great, but I'm finding find the ScreenSystem set
of classes and the way the PhysicsSimulatorView is implemented is making it more complex for me to learn.
Personally I'd find it very helpful to see a simple example Solution containing an XNA Windows game project and Farseer Physics. The example game project could have a couple of Texture2Ds with bodies and geoms attached (e.g.
one controlled by player and one not) showing how to manage movement, collision detection and collision response/reaction. I'd like to see the PhysicsSimulatorView implemented but no ScreenSystem.
Does anybody have a simple project like this they could show me? It would really help me a lot.
Many thanks!
Matt
Hi Matt.
Thanks for the very kind words about our engine and our team. The community means a lot to us and we really appreciate people taking their time to help out and contribute to the project.
I have some plans to make Farseer Physics Engine even easier. To accomplish this I'm including the simplest samples you can imagine (much like you describe). I remember the first time I stepped into the world of game physics, I was as much lost by the clutter
as you are now. Sometimes we just need a place to start - get the fundamentas right and begin from there.
When the features for Farseer Physics 2.1 are done and we are close to a release, I'm going to make some improvements to the manual. I have a lot of requests from our users and even examples on what the changes might look like. I aim to create a fully documented
physics engine that is easy to use and learn. It's not an easy task, but it can be done. If you have any suggestions other than what you already have, you are welcome to tell us and we will take it up to consideration.
As for the sample itself, I do hope someone here can brew a quick sample for you, I don't have the time right now as I have exams tomorrow and need to study. However, I can tell you the very basic setup of a sample:
1. Create new XNA game
2. Create a PhysicsSimulator object. - This object is in charge of updating bodies and geometries.
3. Create 2 objects:
3.a A Body object for dynamics (force and impulse) - Use BodyFactory class to create a body. Also, remember to position the body.
3.b A Geom object for collision detection (it consists of vertices that makes up an shape) - Use GeomFactory class to create a Geom.
4. If you used the factories that use a PhysicsSimulator argument, you can skip this step. But else you need to add both the Body and Geom object to the PhysicsSimulator object (Example: PhysicsSimulator.Add(Body) )
5. Make sure to have PhysicsSimulator.Update() called inside your update loop.
That is it. If you have done it right, you now have a geometry (geom) that supports collisions with other geometries. To see them, you will need to draw them on the screen. In the samples, the DrawingSystem folder has some classes that can create textures
(rectangles, polygons, circles).
Hi genbox,
Thanks for your quick reply. Good luck with your exams tomorrow, hope it all goes well!
I'll have a go at creating a simple project as you've suggested in your post. I need to get the PhysicsSimulatorView working as well so that I can actually see what's happening with the (invisible) bodies/geoms that I'm creating...
If anybody can help me out I'd really appreciate it!
Anyway you'd better go and study so I'll leave you in peace for now!
Thanks again.
Matt
Is anybody able to help me out with this please?
To use the PhysicsSimulatorView, you need to move the PhysicsSimulatorView.cs file and dependencies (everything in DrawingSystem folder) into your own project.
Then you need to instanciate the PhysicsSimulatorView and remember to give it the reference to your physics simulator object. (PhysicsSimulatorView view = new PhysicsSimulatorView(physicsSimulator); )
Then you call view.LoadContent(graphicsDevice, contentManager); to make it initialize all the graphics and stuff. And finally, you just call view.Draw(spriteBatch); to make it draw to screen.
That should be it. You can not see geometries, bodies, joints and the internals of the engine. Remember that you can turn off and on the different features.
Here is a bare bones sample like the one described. It just has circle body and a static rectangle that it falls onto. I went a little crazy with the using statements lol. The one thing I had problems with was that the default template in visual studio adds
a Content.RootDirectory = "Content", which won't work if you pass this content manager to the PhysicsSimulatorView. Just comment that line out and let it use the default root directory.;
using FarseerGames.AdvancedSamples;
using FarseerGames.AdvancedSamples.DrawingSystem;
namespace SimpleTest
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
PhysicsSimulator physicsSimulator;
Body player;
Geom playerGeom;
Body platform;
Geom platformGeom;
PhysicsSimulatorView simView;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content = new ContentManager(Services);
//Content.RootDirectory = "Content"; // commented out so PhysicsSimulatorView can find its stuff in the default directory
// setup the physics sim
physicsSimulator = new PhysicsSimulator(new Vector2(0.0f, 300f));
// setup the player body and geom
float playerRadius = 10.0f;
player = BodyFactory.Instance.CreateCircleBody(physicsSimulator, playerRadius, 1.0f);
playerGeom = GeomFactory.Instance.CreateCircleGeom(physicsSimulator, player, playerRadius,
10, // number of edges
new Vector2(0.0f, 0.0f), // position
0.0f); // rotational offset
player.Position = new Vector2(300.0f, 300.0f);
//// setup the platform
platform = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, 40f, 100f, 100f);
platformGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, platform, 100, 100f);
platform.Position = new Vector2(300.0f, 310.0f);
platform.IsStatic = true;
create the simView, but don't load resources yet
simView = new PhysicsSimulatorView(physicsSimulator);
}
/// );
// now load the simView's content
simView.LoadContent(GraphicsDevice, Content);
//();
// ----- apply any game logic forces first -----
// in a real game this will be some force you calculate from user input, or more than one force
Vector2 someForceFromInput = new Vector2(100.0f, 0.0f);
// apply force for user input
player.ApplyForce(new Vector2(someForceFromInput);
// ----- now update the physics simulator -----
physicsSimulator.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// ----- draw your game textures first -----
spriteBatch.Begin();
// draw everything in your game
spriteBatch.End();
// ----- now draw the simView in a separate Begin/End section, so the PhysicsSimulatorView draws on top of everything you drew earlier
spriteBatch.Begin();
// this draws the simview
simView.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://farseerphysics.codeplex.com/discussions/56573 | CC-MAIN-2017-22 | refinedweb | 1,307 | 58.89 |
Truth be told, the initial XML serialization that shipped with .NET Framework 1.0 and 1.1 wasn't that bad. Or that might just be my foggy memory forgetting some of the various hurdles and headaches that stemmed from working with these earlier versions of the .NET Framework. Either way, I'm probably remembering whatever hoops I had to jump through to get .NET serialization to work were it was a lot easier and more reliable to use than what I was able to cobble together on my own with classic ASP and Visual Basic (back in the day).
But if memory serves me correctly, then around the release of.NET Framework 2.0, not only did XML serialization become more tedious and error prone, but I also seem to remember that around this time frame that Microsoft sadly became obscenely pedantic in regard to XML Schema Definitions (XSDs), namespaces, and a couple of non-trivial XML requirements that made doing anything with XML overly painful and prone to excessive amounts of troubleshooting and tweaking. In other words, the .NET Framework 2.0 serialization framework just became obscenely brittle and painful to use -- even for tasks that should be been simple such as serialization.
Fast forward to a few years later along with a couple additional .NET version releases, and I still don't think that the serialization story that ships with .NET has gotten much better. Thanks to Windows Communication Foundation (WCF), I'd argue that serialization has in many cases become much more tedious, brittle, and prone to troubleshooting. That's to say nothing of how much I despise having to couple my objects with endless [DataMember] and [DataContract] attributes just to get them to serialize using System.Runtime.Serialization infrastructure..
JSON.NET: Simple, Easy, High-Performance Serialization
In fairness, however, the last time I really dealt with .NET serialization other than JSON outputs for client interactions was roughly two years ago. Although I haven't had time to look into some of the JSON serialization mechanisms that ship with the ASP.NET Web API framework, I knew that I'd need to look into seeing if there was some sort of sea change in the .NET serialization landscape. Consequently, I took a brief tour through Google looking for any kind of lightweight and easy-to-use serialization options that I might be able take for a spin.
What I found immediately were a few links to JSON.NET. It only took me a few minutes to be sold on the advertised features to pull down the binaries and try a few quick serialization tests. Sure enough and with just a few lines of code, I was able to seamlessly and easily serialize and then rehydrate a couple of my .NET objects. Best of all, the entire process not only was flawless in terms of working as advertised, but it also didn't require any modification to my objects. Instead, what I got was a full-blown POCO serialization without any fuss or headaches.
JSON.NET is More than just Simple Serialization
A part of what makes JSON.NET so awesome -- above and beyond its core operating principles to enable fast and easy serialization -- is the documentation. Within just a few minutes of perusing the documents and corresponding examples, I was not only able get spun up on all the core features of JSON.NET, but I was also able to spot some other very cool options and features that were also insanely easy to grok as well. For example, I initially assumed the LINQ to JSON capability was a sort of spiffy feature of JSON.NET that I probably wouldn't use. But within about 20 minutes of plugging away within my application I found a perfect place to end up using this functionality to pass around dynamic message objects and rehydrate them via receiver or router on the flip side. As with everything else in this framework, the functionality was insanely easy to use and worked just as advertised.
Some other very cool aspects of this open-source framework are that it also provides painfully simple options for debugging along with easy-to-configure settings options that have magically managed to do just about everything I need them to do in default config-mode. This means that I have yet to really even bother making any config changes. There are also a host of awesome features that you can use to address error handling, customize serialization output, and perform pretty much anything else you'd want or need a serialization framework to do. Although I still more or less despise WCF object serialization through [DataContract] attributes, one very cool thing about JSON.NET is that it fully supports opt-in member serialization either through .NET or WCF serialization attributes. In essence, JSON.NET is lightweight, easy, speedy, and fun to use. It also supports more enterprise-related scenarios in which [DataContract] serialization also makes good sense as well. Long story short: JSON.NET is totally worth a review and test drive if you have any .NET serialization needs in any of your upcoming projects. | https://www.itprotoday.com/net/jsonnet-serialization-done-right | CC-MAIN-2020-40 | refinedweb | 859 | 54.42 |
AJAX (Asynchronous JavaScript and XML) is arguably one of the most hyped technology acronyms around. The primary advantage of using AJAX is that page refreshes can be minimized, allowing users to get the information they need quickly and easily through a more rich and functional interface. Ajax accomplishes this by using JavaScript and an XmlHttp object to send data asynchronously from the browser to the Web server and back. So, although AJAX has a lot of marketing-hype surrounding it, the benefits it offers can’t be denied.
Microsoft’s ASP.NET AJAX Extensions provide developers with a quick and simple way to add AJAX functionality into any ASP.NET Website, without requiring in-depth knowledge of JavaScript or other AJAX technologies. This article will demonstrate how you can add AJAX capabilities into a new or existing Website by using a new ASP.NET AJAX server-side control called the UpdatePanel. You’ll see how the UpdatePanel control can be used to allow portions of a page to be updated without requiring the entire page to be posted back to the server and reloaded in the browser. Additional topics covered include:
- The role of the ScriptManager control
- Nesting UpdatePanel controls
- Triggering asynchronous requests
- Providing progress indicators to end users
- Interacting with the UpdatePanel on the client-side, using the PageRequestManager class.
Let’s get started by discussing how to get the ASP.NET AJAX Extensions installed and configured.
Installing the ASP.NET AJAX extensions
Before you can use the ASP.NET AJAX UpdatePanel control you need to install the ASP.NET AJAX Extensions, available from, on your development machine. Once installed, a new Website template titled “ASP.NET AJAX-Enabled Website” will appear when you first create a new Website using Visual Studio .NET 2005 or Web Developer Express. Select this template when you want to add ASP.NET AJAX functionality into Web pages.
The ASP.NET AJAX Extensions rely upon special HTTP handlers and modules to handle and respond to asynchronous requests sent from a browser. By creating a new ASP.NET AJAX Website in Visual Studio .NET, a web.config file will automatically be created that contains references to a ScriptResource.axd handler as well as a ScriptModule module. The ScriptResource handler dynamically loads JavaScript files into pages that leverage AJAX features while ScriptModule manages HTTP module functionality that is related to request and response messages.
If you’d like to upgrade an existing Website and add ASP.NET AJAX functionality into it you’ll need to ensure that you manually update your site’s web.config file with the proper entries. The easiest way to do this is to create a new ASP.NET AJAX-Enabled Website (as mentioned earlier) and then copy the AJAX-specific portions of web.config to your original web.config file. You’ll of course need to ensure that the ASP.NET AJAX Extensions are also installed on your production server before deploying the updated site.
Adding AJAX functionality into ASP.NET Web Forms
Before the ASP.NET AJAX Extensions were released, developers had to rely on custom AJAX libraries to AJAX-enable a Web site. While these libraries were quite powerful and worked in cross-browser scenarios, they often required a familiarity with JavaScript, and even XML or Web Service technologies. Some of the frameworks were/are susceptible to CSRF (Cross Site Request Forgery) attacks, whereby a hacker could hi-jack AJAX messages and potentially steal information. Fortunately, the ASP.NET AJAX Extensions offer a secure AJAX framework that includes a new server control called the UpdatePanel that hides JavaScript complexities.
The UpdatePanel control allows you to focus on the functionality of your application rather than on programming and understanding AJAX-specific technologies. It performs asynchronous postback operations that update a portion of a page rather than the entire page itself. This technique is often referred to as “partial-page updates“. The UpdatePanel control works by intercepting postback requests triggered by the page and converting them into asynchronous postback calls, which are then sent to the server using the browser’s XmlHttp object. It relies on client-side scripts managed by the ASP.NET AJAX framework to perform this asynchronous functionality.
Before using the UpdatePanel control you must first add into your page an important ASP.NET AJAX control, called the ScriptManager. The ScriptManager handles loading all of the necessary client-side scripts that are required by the UpdatePanel and other AJAX controls in order to make asynchronous AJAX calls. You can drag a ScriptManager control onto a page from the VS.NET toolbox or add it directly into the source code as shown next:
Once a ScriptManager control is added, an UpdatePanel control can then be defined in the page. The UpdatePanel acts as a container in much the same way as the standard ASP.NET Panel control. However, content embedded within the UpdatePanel is wrapped within a template named ContentTemplate. Any content placed within the ContentTemplate is automatically AJAX-enabled. This means that button click or other postback events triggered by controls in the template will be intercepted and converted into asynchronous AJAX calls to the server.
Listing 1 demonstrates how to use an UpdatePanel control in a page in order to AJAX enable a GridView, which allows paging through customer data:
Listing 1. Using the UpdatePanel control and ContentTemplate.
As users page through customer records in the GridView control, or sort different columns, the UpdatePanel control automatically handles AJAX-enabling the call resulting in a partial-page update rather than a complete page refresh.
Displaying progress
Although the UpdatePanel is simple to use, you must take the end user into account when using it, especially if you don’t know how long an asynchronous postback may take to complete. Long requests may cause an end user to think that their request has failed or hung and they may start the request again, navigate to a different page or even close the browser. The solution is to provide them with a visual progress indicator so that they know that their request is being processed.
The ASP.NET AJAX Framework includes the UpdateProgress control that can be used to provide users with a visual indication of whether or not their request is still being processed. Listing 2 shows an example of using the UpdateProgress control to display an animated image to an end user, while a Web Service is called that retrieves album information.
Listing 2. Using the UpdateProgress control.
You’ll see that the UpdateProgress control has a ProgressTemplate that contains the content to show to the end user, while the UpdatePanel asynchronous postback is processed. Any content type of content (images, flash movies, videos, etc.) can be placed inside of the template. In cases where you’d like the content to take up a fixed amount of space on the page as opposed to dynamically being added, you can set the DynamicLayout property to false.
The UpdateProgress control shown in Listing 2 is embedded directly within the target UpdatePanel. However, it can be embedded elsewhere in the page and linked to the appropriate UpdatePanel by setting its AssociatedUpdatePanelID property to the ID of the UpdatePanel. In cases where quick partial-page updates may occur, and you don’t want the UpdateProgress control to show its content, you can set the DisplayAfter property to the number of milliseconds that you’d like it to wait before displaying progress content. DisplayAfter defaults to a value of 500 milliseconds.
Figure 1 demonstrates the end-user effect of using the UpdateProgress control. As the UpdatePanel is being refreshed with album information from a call to the Amazon.com Web Service, a progress indicator is displayed directly below the Artist textbox.
Figure 1. Using the UpdateProgress control to give visual feedback to end users as a call is made to the Amazon.com Web Service.
Nesting UpdatePanel controls
Multiple UpdatePanel controls can be added into a page in cases where different sections need to make AJAX calls to the server to avoid reloading the entire page. In addition to having multiple UpdatePanels in a page, you can also nest UpdatePanels to provide more granular AJAX functionality. For example, you may want to show a GridView control that displays information and allows a user to drill-down into additional details to achieve a master-details style view. Figure 2 shows an example of doing this using two GridView Controls.
Figure 2. Creating a master-details view of customer and order data.
To accomplish this type of master-details view, an UpdatePanel is nested inside of a GridView‘s ItemTemplate, as shown in Listing 3. As a user clicks the “View Orders” LinkButton, within each row shown in Figure 2, the GridView within the nested UpdatePanel is made visible. Any paging or sorting requests made within the nested UpdatePanel control will cause it to reload new data by making asynchronous AJAX requests, while data in the parent GridView control is left untouched.
Listing 3. Creating a master-details view of data using nested UpdatePanel control.
The UpdatePanel control exposes an UpdateMode property that defaults to a value of “Always”. This means that any asynchronous request triggered anywhere within the page will cause the UpdatePanel to refresh itself. In cases where this behavior isn’t desired, the UpdateMode property can be assigned a value of “Conditional” so that only triggers associated with the control or child controls embedded within the control’s ContentTemplate can cause it to be refreshed through an asynchronous postback. Other controls outside of the UpdatePanel will not cause it to be refreshed. Additional information about UpdatePanel triggers is covered in the next section.
The parent UpdatePanel control in Listing 3 has its UpdateMode set to Conditional so that any asynchronous postback operations caused by the nested UpdatePanel or by other controls in the page do not cause the parent GridView control to be refreshed. This minimizes the number of asynchronous postback requests made to the server.
Using triggers
While controls inside of an UpdatePanel control can cause it to perform asynchronous postbacks, other controls defined outside of the UpdatePanel can also act as “triggers” that cause the UpdatePanel to refresh itself with new data. Two types of triggers exist for UpdatePanels including the AsynchronousPostBackTrigger control and PostBackTrigger control.
An AsynchronousPostBackTrigger causes an UpdatePanel‘s content to be updated asynchronously when a specific control’s event is fired such as a Button’s click event or a DropDownList‘s SelectedIndexChanged event. A PostBackTrigger causes a regular postback operation to occur that reloads the entire page. When AJAX-enabling your Websites you’ll normally want to use the AsynchronousPostBackTrigger to stop postback operations from occurring.
Listing 4 shows how to define a DropDownList control as a trigger that can perform a refresh of the UpdatePanel‘s contents. This is done by using the AsynchronousPostBackTrigger control. Notice that the ID of the DropDownList control is defined using the ControlID property, and the event that causes the partial-page update of the UpdatePanel is defined using the EventName property. When the SelectedIndexChanged event fires, an asynchronous postback is made to the server and the UpdatePanel‘s content is reloaded.
Listing 4. Defining triggers to perform partial-page updates on the contents of an UpdatePanel.
In cases where you’d like to prevent controls defined within an UpdatePanel‘s ContentTemplate from triggering an asynchronous postback operation, you can set the UpdatePanel‘s ChildrenAsTriggers property to false and the UpdateMode to “Conditional”. Any events raised by child controls in the ContentTemplate of the control will be ignored, while events raised by triggers such as the one shown in Listing 4 will cause a partial-page update to occur, if needed.
Listing 5 shows an example of setting the ChildrenAsTriggers property to false to prevent LinkButtons clicked within a DataList control from updating the contents of an UpdatePanel. While the LinkButtons don’t cause the UpdatePanel to refresh itself, they do cause another UpdatePanel defined in the page to be refreshed so that additional details about employees can be shown to the end user (see Figure 3).
Listing 5. Using the ChildrenAsTriggers property to stop child control’s of an UpdatePanel from triggering an asynchronous postback operation.
The results of this are displayed in Figure 3. When a territory is clicked, employees in that territory will be shown.
Figure 3. LinkButtons defined in an UpdatePanel trigger a separate UpdatePanel to display additional details about employees.
The UpdatePanel where the controls are defined is not updated since the ChildrenAsTriggers property is set to false.
Handling UpdatePanel events on the client
The UpdatePanel control handles all asynchronous requests to the server, so you don’t have to worry about writing JavaScript code. This is great from a productivity and maintenance standpoint but there will be times when you want to know when an UpdatePanel request is going to start, or when data has returned and is about to be updated in the page. For example, you may want to access data returned by an UpdatePanel and use it to make another asynchronous postback request. Or, you may want to animate the UpdatePanel as a request is started so that the end user sees what is happening and knows when content in a particular area of a page has been refreshed. All of this can be done by using a JavaScript class provided by the ASP.NET AJAX script library, called the PageRequestManager.
The PageRequestManager lives in the Sys.WebForms namespace in the ASP.NET AJAX script library and allows you to tie into requests and responses processed by one or more UpdatePanels in a page. It’s responsible for managing partial-page updates that occur within a page as well as managing the client page life-cycle. By using it you can tie into several different events and act upon them. PageRequestManager also exposes properties and methods that can be used to check if asynchronous requests are in process. It can also be used to abort existing requests and even cancel pending requests.
Events exposed by the PageRequestManager class include initializeRequest, beginRequest, pageLoading, pageLoaded and endRequest. The following table provides more details about these events and when they are fired.
To access the PageRequestManager you can call its getInstance() method on the client-side as shown next:
Once the PageRequestManager object is available, you can define event handlers for the different events that it exposes and attach to them. Listing 6 shows how to attach an event handler to the endRequest event and access data returned from the asynchronous postback request.
Listing 6. This code shows how to attach an event handler to the endRequest event of the PageRequestManager.
Once a request is completed, errors are checked and if none are found, data returned by the request is accessed and passed to another method for processing.
Notice that the parameter signature for the EndRequest() event handler mirrors the one found in the .NET framework where the sender of the event as well as any event arguments are passed as parameters. The eventArgs parameter can be used to check if any errors occurred during the request by calling the error property which can be used to access the HTTP status code of the request. If a 500 error is found then the code accesses the error message by calling the message property, marks that the error has been handled and shows the error message to the end user. If no error occurs, a hidden field, named hidField, which is returned from the asynchronous postback, is accessed to get a value needed by a GetMap() method, which is used to display a Virtual Earth map.
The PageRequestManager can also be used to abort or cancel asynchronous postback requests by handling the initRequest event. Listing 7 shows an example of canceling a request in cases where an UpdatePanel is in the process of making a request and the end user is impatiently clicking a Refresh button.
Listing 7. This code shows how the PageRequestManager‘s initRequest event can be used to cancel a pending asynchronous postback request.
The code in Listing 7 starts by accessing an instance of the PageRequestManager in the Application’s init phase and ensuring that an asynchronous postback isn’t already in progress on the page. If no asynchronous postback is occurring, the InitRequest event handler is attached to the initializeRequest event. Once the InitRequest handle is called, a call is made to the PageRequestManager‘s isInAsyncPostBack property and the event argument’s postBackElement property (the event argument is of type InitializeRequestEventArgs). The isInAsyncPostBack property returns a Boolean value indicating if an asynchronous postback is currently in progress and postBackElement property provides access to the control that triggered the request.
If an asynchronous postback is already in progress and a new request is triggered by a button with an ID of btnRefresh, the pending request is cancelled by assigning a value of true to set_cancel. A message is then displayed to the end user letting them know that a request is already being processed and that they need to wait. The PageRequestManager class can be used to perform several other actions such as animating an UpdatePanel before a request is made and after the response is processed.
Conclusion
The ASP.NET AJAX Framework provides a simple and productive way to add AJAX functionality into new or existing Websites. With a minimal amount of effort you can make your applications perform more efficiently and provide end users with a richer experience than traditional Web applications by using partial-page updates.
In this article you’ve seen how the ScriptManager and UpdatePanel controls can be used to make asynchronous postbacks from the browser to the server and how different types of triggers can initiate the requests. You’ve also seen how UpdatePanel controls can be nested to provide a master-details style view of data and how the UpdateMode and ChildrenAsTriggers properties can control how and when an UpdatePanel‘s content is updated. Finally, you’ve seen how the PageRequestManager client-side class can be used to notify you of partial-page update requests and responses. | https://www.simple-talk.com/dotnet/asp.net/enhance-your-website-with-asp.net-ajax-extensions/ | CC-MAIN-2017-04 | refinedweb | 3,024 | 52.49 |
C++ representation of the MarkLogic token. More...
#include <MarkLogic.h>
C++ representation of the MarkLogic token.
The offsets point to the position in the codepoint array of the first codepoint in the token and the codepoint following the last codepoint in the token.
The part of speech of the token being returned. Part of speech is only relevant for word tokens.
LexerUDF implementations may return tokens with the followings parts of speech. Returning UNSPECIFIED_POS for every token reduces the storage overhead and processing time. Implementations are free to return other unsigned char values in the range 0x01 to 0x7F as well as any of the values listed here, but the high bit is reserved.
UNSPECIFIED_POS: part of speech is not reported NOUN_POS: a noun, such as "laptop" VERB_POS: a verb, such as "ate" ADJECTIVE_POS: an adjective, such as "green" ADVERB_POS: an adverb, such as "rapidly" PRONOUN_POS: a pronoun, such as "her" CONJUNCTION_POS: a conjunction, such as "and" DETERMINER_POS: a determiner, such as "the" MISC_POS: some other miscellaneous part of speech
The kind of token being returned.
LexerUDF implementations will return tokens of the following types.
SPACE: a whitespace token, will not be indexed PUNCT: a punctuation token, will not be indexed WORD: a separate word in the current language, will be indexed SPECIAL: some other kind of token, will be indexed | http://docs.marklogic.com/cpp/udf/classmarklogic_1_1Token.html | CC-MAIN-2018-09 | refinedweb | 221 | 51.18 |
I'd like to host php projects and perhaps asp.net prjs on my server. Theres two main issues i have.
1) The php files scanning my filesystem. I dont want it to visit /var/www/majorapp/config.xml and read the db or admin password. Along with source of other host projects (which are also in php)
2) track or kill processes that eat up CPU or ram. If a php file or project is doing something cpu intensive i'd like to kill it. It would be great if it works on spawn process as well.
bonus: if i can prevent it from using the network such as visiting or
I am considering allowing the user run asp.net prjs as well since my site is using asp.net. My server is apache2 on a linode virtual host. Debian lenny
One solution would be to use something like Linux Containers (LXC) to provide isolated environments to each project. This solution lets you assign hard limits to things like memory and CPU utilization, and it lets you set network firewalls and so forth for each project. This also means each project gets its own filesystem namespace. More information here:
Similar projects | http://serverfault.com/questions/203502/host-projects-safely-on-linux-server | crawl-003 | refinedweb | 202 | 76.11 |
2012-04-23 09:01:59 8 Comments
Is the metasyntactic static library for iOS . . .
. . . compatible with regular old C++ compiled protofiles? I do not want to use the bundled compiler that generates Obj-C.
Is there any way to compile the library supplied by Google for iOS?
Related Questions
Sponsored Content
14 Answered Questions
[SOLVED] Biggest differences of Thrift vs Protocol Buffers?
- 2008-09-16 04:07:42
- Bob
- 119049 View
- 286 Score
- 14 Answer
- Tags: serialization protocol-buffers thrift
1 Answered Questions
[SOLVED] How to install protocol buffers with Objective C/iOS 5 SDK?
- 2012-02-22 20:21:45
- Groppe
- 1697 View
- 2 Score
- 1 Answer
- Tags: objective-c ios xcode ios5 protocol-buffers
1 Answered Questions
[SOLVED] Protocol Buffer for Objective-C
- 2011-09-12 03:18:42
- Jay Zhao
- 740 View
- 1 Score
- 1 Answer
- Tags: objective-c protocol-buffers
1 Answered Questions
[SOLVED] cocoaasyncsocket sending data >128bytes (google protocol buffers)
- 2011-07-14 10:41:45
- robert
- 824 View
- 2 Score
- 1 Answer
- Tags: objective-c protocol-buffers metasyntactic-variable cocoaasyncsocket
1 Answered Questions
[SOLVED] Difference in .NET Protocol Buffer libraries
- 2011-01-18 11:37:35
- Ray Booysen
- 782 View
- 7 Score
- 1 Answer
- Tags: .net protocol-buffers
@learnvst 2012-04-23 11:29:15
Ok. It appears that the metasyntactic library (or any other 3rd party library) is unnecessary in this case. You can just add the Google source directly to your project. I found the following answer from Nicola Ferruzzi in a google discussion group . . .
The original answer is here . . .
The content of this answer is included below with images to make a permanent record ...
EDIT
Since trying this again tonight for the first time in a while, I needed a couple more steps in addition to those outlined below (this works with protobuf 2.5.0).
find . -name "*unittest*" -exec rm -rf {} \;
testing
#include <google/protobuf/testing/googletest.h>in
stringprintf.cc
@Tavis Bones 2012-07-23 20:39:43
When you say "add the directory of google headers to your additional include directories" what does that mean? Add it to the Header Search Paths?
@learnvst 2012-07-25 11:42:07
In XCode, it means add it to the header search paths, yes. Different compiler IDEs will have different labels. All the best.
@Tony 2012-10-11 13:19:05
If someone follow this and get issue that <tr1/unordered_map> cannot be found, remove 'tr1' in
config.h. And also, if you failed to compile
message.cc, add
include <iostream>in
message.ccfile.
@Bennett Smith 2013-10-19 19:11:03
Following the general instructions provided here I have build a Cocoapod that does an install of Google Protobuf v2.5.0 directly from the Google tar.gz file. It works for Xcode 5 and targets iOS 7. It also includes a build of the protoc compiler for Mac OS so it becomes possible to add Protobuf support to a project with no additional messing about. The podspec is in the main Cocoapods Specs repo. Just "pod search protobuf" to find it.
@Teddy 2014-08-25 21:01:37
After following your description and using Xcode 6 beta6 I receive the following error: 'unordered_map' file not found. What do I miss here?
@Teddy 2014-08-25 21:11:53
OK I found it. C++ language dialect must be set to C++11 and standard library to libc++.
@Oscar 2019-04-22 06:32:51
This procedure suffers from quite a few problems, at least with protobuf 3.7.1. Several (non-test-related) required header files wind up being deleted.
@Bennett Smith 2013-10-19 19:19:18
You can add support for Google Protocol Buffers to an Xcode 5 project using Cocoapods by adding the following line to your Podfile.
This will place the C++ version of the protobuf code into a Pod for your project. It will also add the
protoccompiler in the folder
Pods/GoogleProtobuf/bin/protocwithin your project.
You can create a custom build rule in your project that automatically converts the
.protofiles into
.ph.{h,cc}files. Here is how I did that:
Setup a build rule to "Process Source files with names matching: *.proto Using Custom Script". The script should include the following:
Set the output files to include the following:
Any
.protofiles you include in your project will now automatically be converted to C++ and then compiled as part of your build.
@Bennett Smith 2013-10-25 06:35:08
Refer to stackoverflow.com/questions/19444376/… for another possible solution that performs a local build.
@Ted Tomlinson 2013-08-07 18:45:45
I guess based on the actual question my comment is worth posting as an answer:
I'm using a slightly modified version of the native Obj code generation provided by Booyah
It supports repeated fields out of the box but in order to use ObjC fast enumeration you need to convert the PBArray type (basically a typed c buffer) to an array of NSObjects that it represents - either the NSNumber or protobuf message of the objects. You can see an example of the updated fast enumeration code in this change: . You could also add a category for that on PBArray called toObjects.
I just mark the generated code with
-fno-objc-arc, but you can get arc and 2.5 support from the booyah pull requests.
The directions are pretty good for setup, but if people want more explicit instructions on the category I use, how I built the protobuf-objc plugin, how to get support for Class prefixes (e.g. IXMyProtoMessage instead of MyProtoMessage) or how I generate the code let me know and I'll try to set aside time to write up a post. I'm using it with > 50 proto files with a lot of cross project dependencies.
A weakness of the library is that it doesn't include the typical Protobuf reflection api on the generated code so doing something like converting a message to a NSDictionary would have to do some hacky stuff with the objC runtime (the code doesn't follow typical KV compliance) or write a custom code generator from protos that do have the reflection api (I did this with python + jinja2). Or - better yet and of similar difficulty, add reflection apis to the code generator ;).
@Richard Topchii 2019-03-04 14:17:49
Could you please share your extension on how to convert
PBArrayto
NSArray?
@Tushar Koul 2013-03-06 11:41:57
EDIT : I had answered this earlier but was deleted by moderator. So I have included some code from the tutorial.
A tutorial which is almost same as the answer posted above - Using Google Protocol Buffers in Objective-C on iOS and the Mac
Follow the steps given in learnvst's answer, and refer the comments for pitfalls. I followed the exact same steps except for
Also, when i did
#import xyz.pb.hthe project wasn't building. When I renamed my .m file to .mm i was able to build. This point is mentioned in the tutorial very subtly :P.
Here's some content from the tutorial -
PROTO FILE
ZombieSightingMessage.h
ZombieSightingMessage.mm
EDIT : I am using Xcode 4.5. Even after I followed all the steps I was getting a linker error.
Due to this I couldnt run the code on simulator. But it worked on actual device
@Ted Tomlinson 2013-08-06 20:31:09
This is a great post, but I'm curious why people wouldn't want to use the booyah port (based on metasyntactic)? It gives you Objc objects so your view code doesn't have to worry about having c++ objects with different notation and manually free memory (if using arc)? Is is a protobuf version thing? do you need the reflection api that c++ provides? I'm using the booyah port in multiple projects and it's worked great so far...
@Tushar Koul 2013-08-07 04:54:30
I was facing problem compiling protos with "repeated" variables.
@Tushar Koul 2013-08-07 04:57:27
@Ted pls post the link of the library you are using.
@AlBeebe 2014-01-30 19:47:58
I also ran into the "repeated" variables bug like @TusharKoul which means i have to utilize this c++ code.
@Tushar Koul 2014-01-31 05:56:15
@AlBeebe did you try compiling the code from booyah repo that Ted posted? | https://tutel.me/c/programming/questions/10277576/google+protocol+buffers+on+ios | CC-MAIN-2020-29 | refinedweb | 1,405 | 64 |
>>>>> "Tom" == Tom Tromey <address@hidden> writes: Tom> gcc3 very nearly does exactly what automake wants in terms of Tom> dependency tracking. Tom> I think that ideally automake should recognize this and avoid Tom> using depcomp when it discovers that the user is using gcc3. In Tom> this situation instead of invoking depcomp we would just invoke Tom> gcc like depcomp does (with a small change): Tom> gcc <args> <dependency args> && mv "$tmpdepfile" "$depfile" Tom> I don't think we need the explicit `rm $tmpdepfile' because the Tom> whole problem is that gcc deletes it on failure. Tom> Akim, any comments on the best approach to implementing this? Tom> One problem I see is that detecting gcc3 in a Tom> language-independent way is not going to be easy, at least not Tom> without autoconf assistance. Well, at first sight we might be doing good with the current scheme. I might very well be underestimating some issues, but let me just imagine :) Say for .o: ?GENERIC?.%EXT%.o: ?!GENERIC?%OBJ%: %SOURCE% if %AMDEP% source='%SOURCE%' object='%OBJ%' libtool=no @AMDEPBACKSLASH@ depfile='$(DEPDIR)/%BASE%.Po' tmpdepfile='$(DEPDIR)/%BASE%.TPo' @AMDEPBACKSLASH@ $(%FPFX%DEPMODE) $(depcomp) @AMDEPBACKSLASH@ endif %AMDEP% ?-o? %COMPILE% %-c% %-o% %OBJ% `test -f %SOURCE% || echo '$(srcdir)/'`%SOURCE% ?!-o? %COMPILE% %-c% `test -f %SOURCE% || echo '$(srcdir)/'`%SOURCE% we can map %AMDEP% to something else than FALSE or AMDEP, but, say, CCAMDEP, and let the if CCAMDEP endif CCAMDEP magic happen. And conditioning the mv should be quite easy too. Am I missing something? | http://lists.gnu.org/archive/html/automake/2001-05/msg00219.html | CC-MAIN-2014-52 | refinedweb | 250 | 61.87 |
For some reason it never occurred to me that you could use property() as a decorator. Of course, if you want to use getters and setters you can't, but for the (fairly common) case when you have a function that you want to turn into a read-only attribute, it works great:
class Foo(object): @property def bar(self): return <calculated value>
Huh. Seems obvious now.
Update: these days this is built in, and fancier. Try:
class Velocity(object): def __init__(self, x, y): self.x = x self.y = y @property def speed(self): return math.sqrt(self.x**2 + self.y**2) @speed.setter def speed(self, value): angle = math.atan2(self.x, self.y) self.x = math.sin(angle) * value self.y = math.cos(angle) * value @speed.deleter def speed(self): self.x = self.y = 0
That is,
@property is both a decorator, and creates
a decorator, that can be used to add a setter and deleter to the getter.
Note the name of the second two functions is insignificant.
For getters and setters, I like this: class Foo(object): @apply def bar(): def fget(self): return self.whatever def fset(self, value): self.whatever = value return property(**locals()) fdel and doc can be added if needed. And, if the "**locals()" seems too magical "fget, fset" can be substituted.
I)
A clean namespace is good, but a namespace can be _too_ clean.
Having '_get_something' '_set_something' available is usually nice.
I'd prefer camel cased versions, and preferably, set the decorator myself. (Like the python 2.3 notation) | http://www.ianbicking.org/property-decorator.html | CC-MAIN-2014-42 | refinedweb | 260 | 69.28 |
//: MMRDecoder.h,v 1.9 2003/11/07 22:08:22 leonb Exp $ // $Name: release_3_5_17 $ #ifndef _MMRDECODER_H_ #define _MMRDECODER_H_ #ifdef HAVE_CONFIG_H #include "config.h" #endif #if NEED_GNUG_PRAGMAS # pragma interface #endif #include "GSmartPointer.h" #ifdef HAVE_NAMESPACES namespace DJVU { # ifdef NOT_DEFINED // Just to fool emacs c++ mode } #endif #endif class ByteStream; class JB2Image; /** @name MMRDecoder.h Files #"MMRDecoder.h"# and #"MMRDecoder.cpp"# implement a CCITT-G4/MMR decoder suitable for use in DjVu. The main entry point is function \Ref{MMRDecoder::decode}. The foreground mask layer of a DjVu file is usually encoded with a #"Sjbz"# chunk containing JB2 encoded data (cf. \Ref{JB2Image.h}). Alternatively, the qmask layer may be encoded with a #"Smmr"# chunk containing a small header followed by MMR encoded data. This encoding scheme produces significantly larger files. On the other hand, many scanners a printers talk MMR using very efficient hardware components. This is the reason behind the introduction of #"Smmr"# chunks. The #Smmr# chunk starts by a header containing the following data: \begin{verbatim} BYTE*3 : 'M' 'M' 'R' BYTE : 0xb000000<s><i> INT16 : <width> (MSB first) INT16 : <height> (MSB first) \end{verbatim} The header is followed by the encoded data. Bit 0 of the fourth header byte (#<i>#) is similar to TIFF's ``min-is-black'' tag. This bit is set for a reverse video image. The encoded data can be in either ``regular'' MMR form or ``striped'' MMR form. This is indicated by bit 1 of the fourth header byte (#<s>#). This bit is set to indicate ``striped'' data. The ``regular'' data format consists of ordinary MMR encoded data. The ``striped'' data format consists of one sixteen bit integer (msb first) containing the number of rows per stripe, followed by data for each stripe as follows. \begin{verbatim} INT16 : <rowsperstripe> (MSB first) INT32 : <nbytes1> BYTE*<nbytes1> : <mmrdata1> INT32 : <nbytes2> BYTE*<nbytes2> : <mmrdata2> ... \end{verbatim} Static function \Ref{MMRDecoder::decode_header} decodes the header. You can then create a \Ref{MMRDecoder} object with the flags #inverted# and #striped# as obtained when decoding the header. One can also decode raw MMR data by simply initialising a \Ref{MMRDecoder} object with flag #striped# unset. Each call to \Ref{MMRDecoder::scanruns}, \Ref{MMRDecoder::scanrle} or \Ref{MMRDecoder::scanline} will then decode a row of the MMR encoded image. Function \Ref{MMRDecoder::decode} is a convenience function for decoding the contents of a #"Smmr"# chunk. It returns a \Ref{JB2Image} divided into manageable blocks in order to provide the zooming and panning features implemented by class \Ref{JB2Image}. @memo CCITT-G4/MMR decoder. @version #$Id: MMRDecoder.h,v 1.9 2003/11/07 22:08:22 leonb Exp $# @author Parag Deshmukh <parag@sanskrit.lz.att.com> \\ Leon Bottou <leonb@research.att.com> */ //@{ #define MMRDECODER_HAS_SCANRUNS 1 #define MMRDECODER_HAS_SCANRLE 1 /** Class for G4/MMR decoding. The simplest way to use this class is the static member function \Ref{MMRDecoder::decode}. This function internally creates an instance of #MMRDecoder# which processes the MMR data scanline by scanline. */ 00151 class MMRDecoder : public GPEnabled { protected: MMRDecoder(const int width, const int height); void init(GP<ByteStream> gbs, const bool striped=false); public: /** Main decoding routine that (a) decodes the header using #decode_header#, (b) decodes the MMR data using an instance of #MMRDecoder#, and returns a new \Ref{JB2Image} composed of tiles whose maximal width and height is derived from the size of the image. */ static GP<JB2Image> decode(GP<ByteStream> gbs); /// Only decode the header. static bool decode_header(ByteStream &inp, int &width, int &height, int &invert); public: /// Non-virtual destructor. ~MMRDecoder(); /** Create a MMRDecoder object for decoding an image of size #width# by #height#. Flag $striped# must be set if the image is composed of multiple stripes. */ static GP<MMRDecoder> create(GP<ByteStream> gbs, const int width, const int height, const bool striped=false ); /** Decodes a scanline and returns a pointer to an array of run lengths. The returned buffer contains the length of alternative white and black runs. These run lengths sum to the image width. They are followed by two zeroes. The position of these two zeroes is stored in the pointer specified by the optional argument #endptr#. The buffer data should be processed before calling this function again. */ const unsigned short *scanruns(const unsigned short **endptr=0); /** Decodes a scanline and returns a pointer to RLE encoded data. The buffer contains the length of the runs for the current line encoded as described in \Ref{PNM and RLE file formats}.) The flag #invert# can be used to indicate that the MMR data is encoded in reverse video. The RLE data is followed by two zero bytes. The position of these two zeroes is stored in the pointer specified by the optional argument #endptr#. The buffer data should be processed before calling this function again. This is implemented by calling \Ref{MMRDecoder::scanruns}. */ const unsigned char *scanrle(const bool invert, const unsigned char **endptr=0); #if 0 /** Decodes a scanline and returns a pointer to an array of #0# or #1# bytes. Returns a pointer to the scanline buffer containing one byte per pixel. The buffer data should be processed before calling this function again. This is implemented by calling \Ref{MMRDecoder::scanruns}. */ const unsigned char *scanline(); #endif private: int width; int height; int lineno; int striplineno; int rowsperstrip; unsigned char *line; GPBuffer<unsigned char> gline; unsigned short *lineruns; GPBuffer<unsigned short> glineruns; unsigned short *prevruns; GPBuffer<unsigned short> gprevruns; public: class VLSource; class VLTable; private: GP<VLSource> src; GP<VLTable> mrtable; GP<VLTable> wtable; GP<VLTable> btable; friend class VLSource; friend class VLTable; }; //@} // ----------- #ifdef HAVE_NAMESPACES } # ifndef NOT_USING_DJVU_NAMESPACE using namespace DJVU; # endif #endif #endif | http://djvulibre.sourcearchive.com/documentation/3.5.17/MMRDecoder_8h-source.html | CC-MAIN-2017-26 | refinedweb | 931 | 56.55 |
Stein's Algorithm used for discovering GCD of numbers as it calculates the best regular divisor of two non-negative whole numbers. It replaces division with math movements, examinations, and subtraction. In the event that both an and b are 0, gcd is zero gcd(0, 0) = 0. The algorithm for GCD(a,b) as follows;
START Step-1: check If both a and b are 0, gcd is zero gcd(0, 0) = 0. Step-2: then gcd(a, 0) = a and gcd(0, b) = b because everything divides 0. Step-3: check If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor. Multiplication with 2 can be done with a bitwise shift operator. Step-4: If a is even and b is odd, gcd(a, b) = gcd(a/2, b). Similarly, if a is odd and b is even, then gcd(a, b) = gcd(a, b/2). It is because 2 is not a common divisor. Step-5: If both a and b are odd, then gcd(a, b) = gcd(|a-b|/2, b). Note that difference of two odd numbers is even Step-6: Repeat steps 3–5 until a = b, or until a = 0. END
In the view of above algorithm to calculates the GCD of 2 numbers, the following C++ code is write down as;
#include <bits/stdc++.h> using namespace std; int funGCD(int x, int y){ if (x == 0) return y; if (y == 0) return x; int k; for (k = 0; ((x | y) && 1) == 0; ++k){ x >>= 1; y >>= 1; } while ((x > 1) == 0) x >>= 1; do { while ((y > 1) == 0) y >>= 1; if (x > y) swap(x, y); // Swap u and v. y = (y - x); } while (y != 0); return x << k; } int main(){ int a = 24, b = 18; printf("Calculated GCD of numbers (24,18) is= %d\n", funGCD(a, b)); return 0; }
Finally, the GCD of two supplied number 24 and 18 is calculated in 6 by applying Stein's Algorithm as follows;
Calculated GCD of numbers (24,18) is= 6 | https://www.tutorialspoint.com/stein-s-algorithm-for-finding-gcd-in-cplusplus | CC-MAIN-2021-17 | refinedweb | 351 | 77.16 |
1 import java.io.IOException ;2 import java.io.InputStream ;3 4 import ch.ethz.ssh2.ChannelCondition;5 import ch.ethz.ssh2.Connection;6 import ch.ethz.ssh2.Session;7 8 public class SingleThreadStdoutStderr9 {10 public static void main(String [] args)11 {12 String&2");38 39 /*40 * Advanced:41 * The following is a demo on how one can read from stdout and42 * stderr without having to use two parallel worker threads (i.e.,43 * we don't use the Streamgobblers here) and at the same time not44 * risking a deadlock (due to a filled SSH2 channel window, caused45 * by the stream which you are currently NOT reading from =).46 */47 48 /* Don't wrap these streams and don't let other threads work on49 * these streams while you work with Session.waitForCondition()!!!50 */51 52 InputStream stdout = sess.getStdout();53 InputStream stderr = sess.getStderr();54 55 byte[] buffer = new byte[8192];56 57 while (true)58 {59 if ((stdout.available() == 0) && (stderr.available() == 0))60 {61 /* Even though currently there is no data available, it may be that new data arrives62 * and the session's underlying channel is closed before we call waitForCondition().63 * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may64 * be set together.65 */66 67 int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA68 | ChannelCondition.EOF, 2000);69 70 /* Wait no longer than 2 seconds (= 2000 milliseconds) */71 72 if ((conditions & ChannelCondition.TIMEOUT) != 0)73 {74 /* A timeout occured. */75 throw new IOException ("Timeout while waiting for data from peer.");76 }77 78 /* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */79 80 if ((conditions & ChannelCondition.EOF) != 0)81 {82 /* The remote side won't send us further data... */83 84 if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)85 {86 /* ... and we have consumed all data in the local arrival window. */87 break;88 }89 }90 91 /* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */92 93 // You can be paranoid and check that the library is not going nuts:94 // if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)95 // throw new IllegalStateException("Unexpected condition result (" + conditions + ")");96 }97 98 /* If you below replace "while" with "if", then the way the output appears on the local99 * stdout and stder streams is more "balanced". Addtionally reducing the buffer size100 * will also improve the interleaving, but performance will slightly suffer.101 * OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)102 */103 104 while (stdout.available() > 0)105 {106 int len = stdout.read(buffer);107 if (len > 0) // this check is somewhat paranoid108 System.out.write(buffer, 0, len);109 }110 111 while (stderr.available() > 0)112 {113 int len = stderr.read(buffer);114 if (len > 0) // this check is somewhat paranoid115 System.err.write(buffer, 0, len);116 }117 }118 119 /* Close this session */120 121 sess.close();122 123 /* Close the connection */124 125 conn.close();126 127 }128 catch (IOException e)129 {130 e.printStackTrace(System.err);131 System.exit(2);132 }133 }134 }135
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/SingleThreadStdoutStderr.java.htm | CC-MAIN-2017-04 | refinedweb | 529 | 51.34 |
Hide classes
Hi!
Using pythonista i find many good classes: Button, TextLayer etc.
Where I can read documentation of this classes (without console)?
scene.Button and scene.TextLayer are "undocumented" classes so:
- you will not find them in the normal Pythonista docs, and
- use them at your own risk as they should be considered incomplete, unsupported, and possibly buggy.
See OMZ's comments in:
You can however read the source code for them...
import inspect, scene print(inspect.getsource(scene.Button)) print(inspect.getsource(scene.TextLayer))
Thanks!
Fantastical app ))
And more: I don't find in docs about run() function for run scene subclasses.
KeyboardHack.py rebuilt to leverage scene.Button: | https://forum.omz-software.com/topic/494/hide-classes/3 | CC-MAIN-2018-09 | refinedweb | 111 | 52.05 |
Michal Privoznik
2017-03-14 12:41:50 UTC
I'm a libvirt developer and we rely on gnulib in our project. However, I
was reviewing a patch for bhyve driver (bhyve is a *BSD hypervisor), so
I've booted up my FreeBSD virtual machine and started the review. While
doing 'make distcheck' gnulib tests ran and I've noticed couple of them
failing. So I've tried to update our submodule checkout to the latest
master (1c2185b80a7). However, I still see the following failure:
libtool: compile: gcc -std=gnu99 -DHAVE_CONFIG_H -I.
-I../../../../gnulib/lib -I../.. -I../../../.. -O0 -ggdb3 -MT fflush.lo
-MD -MP -MF .deps/fflush.Tpo -c ../../../../gnulib/lib/fflush.c -fPIC
-DPIC -o .libs/fflush.o
../../../../gnulib/lib/fflush.c:31:30: fatal error: unused-parameter.h:
No such file or directory
#include "unused-parameter.h"
Please let me know if you need more info.
Regards,
Michal | http://bug-gnulib.gnu.narkive.com/a6jPkgvV/unused-parameter-h-not | CC-MAIN-2018-13 | refinedweb | 150 | 60.21 |
Avoid getters and setters whenever possible
scottshipp
Dec 8 '17
Noooo!!! Don't click that generate getters and setters option!!!
I like the rule: "Don't use accessors and mutators." Like any good rule, this one is meant to be broken. But when?
First, let me be clear about what I am saying: adding getters and setters to OO classes should be the last resort after considering a series of better alternatives. I believe that a careful analysis yields the conclusion that getters and setters are harmful in the clear majority of cases.
What is the harm?
First let me point out that the "harm" I am talking about might not be any harm at all. The following is, in some cases, a perfectly reasonable class:
// Car1.java public class Car1 { public Engine engine; }
Notice, though, that feeling of tightening in your stomach, the bristle of your hair, the tensing of the muscles that you may experience looking at something like that.
Now, I want to point out that there's no meaningful functional difference between that class, a public class with a public class member, and the following class below, a public class with a private member that is exposed by getters and setters. In both classes, Car1.java and Car2.java, we get essentially the same result.
// Car2.java public class Car2 { private Engine engine; public Engine getEngine() { return engine; } public void setEngine(Engine engine) { this.engine = engine; } }
To show this, I read and write the engine in either Car1.java or Car2.java:
// Car1 member read and write Car1 car1 = new Car1(); logger.debug("Car1's engine is {}.", car1.engine); car1.engine = new HemiEngine(); // Car2 member read and write Car2 car2 = new Car2(); logger.debug("Car2's engine is {}.", car2.getEngine()); car2.setEngine(new HemiEngine();
The point here is that anything I can do with Car2.java, I can do with Car1.java, and vice-versa.
This is important because we've been taught to get squeamish when we see Car1.java. We see that public member sitting there and we say, not safe! Engine is not protected by anything! Anyone can do anything! Aaaaaaaaagggghhhhh!
Yet for some reason we breathe a sigh of relief when we see Car2.java. Which--I'm sorry--I personally think is funny since there's literally the same (non-existent) protections around both of these things.
What could go wrong?
The following are some of the disadvantages of public getters and setters that directly expose a single private member, have the same name, and provide no other functionality.
Getters and setters are a fake insurance policy of isolated change
One supposed advantage of getters and setters is that on the off-chance that the type of a class member needs to change, the change can be limited to inside the class by making the existing getter simply translate from the internal type to the previously-exposed type.
// Car2.java, engine changed to motor public class Car2 { private Motor motor; public Engine getEngine() { return convertToEngine(motor); } public void setEngine(Engine engine) { this.motor = convertToMotor(engine); } }
My question is how often has the working programmer ever had to do that? I don't remember ever doing this in all my years of software. Not once have I been able to take advantage of the fake insurance policy that getters and setters provide.
Also, this argument becomes an entirely moot point if the
engine had never been exposed to begin with (let's say it was kept private or package-private). Just expose behavior, rather than state, and you never need to worry about flexibility in changing implementation.
This realization that the private member should not have been exposed triggers another realization that this argument is tautological. Getters and setters expose the private member, and rest the case for their existence on the fact that the private member is exposed.
Getters and setters expose implementation details
Let's say I give you only the following API to my Car object:
_________________________________ | Car | |---------------------------------| | + getGasAmount(): Liters | | + setGasAmount(liters: Liters) | |_________________________________|
If you assume that this is a gas-powered car that internally tracks gasoline in liters, then you are going to be right 99.999% of the time. That's really bad and this is why getters and setters expose implementation / violate encapsulation. Now this code is brittle and hard to change. What if we want a hydrogen-fuelled car? We have to throw out this whole Car class now. It would have been better just to have behavior methods like
fillUp(Fuel fuel).
Things like this are the reason why famous libraries have terrible legacy classes. Have you ever noticed how most languages have a
Dictionary data structure but it's called
Map in Java?
Dictionary actually was an interface that was introduced in JDK 1.0, but it had problems and ultimately had to be replaced by
Map.
Getters and setters can actually be dangerous
Let me tell you a story about a friend. OK? A friend I said!!!
One day this friend came into work, and found that dozens of well-known web sites in countries around the world all had the header and navigation of the parent corporation's main web site (not their own), and were using British English. The operations team was frantically restarting hundreds of servers around the globe because for the first half-hour or so that these servers ran, things functioned normally. Then (bam!) all of a sudden something would happen that made the whole thing go sideways.
The culprit was a setter method deep in the guts of a shared platform that all these different sites were using. A little piece of code that ran on a schedule happened to be updated recent to this fiasco that changed the underlying value that determined site headers and languages by calling this setter.
If you only have a getter, things can be just as bad. In Java at least, returning a reference type from a getter provides that reference to the caller and now it can be manipulated by the caller in unexpected ways. Let me demonstrate.
public class Debts { private List<Debt> debts; public List<Debt> getDebts() { return debts; } }
OK, that seems reasonable. I need to be able to see a person's debts to give them a statement. Huh? What's that you say? You can add debts now? Shit! How did that happen!
Debts scottsDebts = DebtTracker.lookupDebts(scott); List<Debt> debts = scottsDebts.getDebts(); // add the debt outside scotts debts, outside the debt tracker even debts.add(new Debt(new BigDecimal(1000000))); // prints a new entry with one million dollars DebtTracker.lookupDebts(scott).printReport();
Eek!
One way to guard against this is to return a copy instead. Another way is to have an immutable member. The best way, though, is to not expose the member in any way at all and instead bring the behavior that manipulates the member inside the class. This achieves full isolation of the implementation and creates only one place to change.
When getters make sense
Wait a second! If there are so many disadvantages to accessors and mutators, why ever use them?
I'm convinced that getters and setters which just return a class member almost never make sense. But you might write something close to getter/setter functionality as long as you are actually doing something in that method.
Two examples:
In a setter, before updating the state in this object according to some input, we validate the input. The input validation is additional functionality.
The return type of a getter is an interface. We have therefore decoupled the implementation from the exposed interface.
See, what I'm really advocating for here is a different stance and philosophy towards getters and setters. Rather than say never use accessors and mutators, I want to give you the list of options that I try to exhaust before using one:.
If it's absolutely necessary for some reason, then I relax to package-private (in Java) and expose the member only to other classes in the same package, but no further.
OK, what about the data use case? Literally I might need to have an object to pass data across some kind of interface boundary (let's say to a file system, database, web service, or something). I still don't futz around with getters and setters. I create the class with all package-private members, and I think of and use it as just a bag of properties. I try to limit these into their own packages and layers at the boundaries of the application.
I would consider creating both a getter and a setter for the data use case in a public API, like let's say I am writing a library meant to be used as a dependency in a lot of other applications. But I would only consider it after exhausting all of these list items.
Wisdom of the Masters
A short postscript. Obviously, there's debate about getters and setters out there in the world. It's important to know there's clearly a camp of "masters" like Robert C. ("Uncle Bob") Martin who are proponents of avoiding getters and setters. In the book Clean Code, Martin wrote about this in chapter 6:
Beans have private variables manipulated by getters and setters. The quasi-encapsulation of beans seems to make some OO purists feel better but usually provides no other benefit.
Josh Bloch has a nuanced stance in Effective Java, Item 14 that is slightly in favor of getters and setters for public classes, and slightly against for others. He ends up basically saying that what he is really concerned about is mutability, a point I touched on above:
In summary, public classes should never expose mutable fields. It is less harmful, though still questionable, for public classes to expose immutable fields. It is, however, sometimes desirable for package-private or private nested classes to expose fields, whether mutable or immutable.
Further Reading
Here's some helpful thoughts from smarter people than me.
Why getter and setter methods are evil
Let's talk net neutrality
What do you think the results of the latest push to abolish net neutrality in the US will be?
Also consider kotlin
Yeah, one of my friend does this thing constantly in Scala, where basically all the fields he creates are immutable val-s. So there exists an immutable field, as well as a getter for it, which doesn't make sense at all, especially because the functional approach implies, that an immutable variable is basically the same as a constant function.
Oh sweet mother of mercy, no. I am currently forced to work with code where someone once decided that getters and setters were evil and did everything with public variables. It's... not good. Yes, 95% of the variables work that way (because we have lot of them), but the remaining 5% make more work than it's worth.
Also your example "gasAmount" is completely nonsenical, because the problem exists no matter if you use getters/setters or just a public variable. How does a public variable with the same name change that problem?
Also your debt example is a perfect example why getters are BETTER than exposing the variables. With a getter you can protect your list by returning a copy. With direct member access? Not really.
So, your arguments against getters and setters are not really good. That's unfortunately, because the basic idea is not a bad one:
While getters/setters ARE better than directly exposing the member, we should of course try to prevent BOTH.
Immutable objects, for example, have far less problems than mutable ones - and if all members are final and imutable themselves, they can be exposed as public members directly, because it's read-only. But the problem this solves is not that getters and setters are but, but that mutability is more dangerous than the other way.
I think you're missing a bit of the point there.
Scott wasn't comparing which of the two (getters vs. public variable) is better. What he said is that getters and setters by default (e.g. when automatically generated by IDE, or shown in beginner examples) expose the variable just the same as making it public; however, people seem to appreciate getters more than public vars, even when they're essentially the same.
The point is reinforced in your last sentence that, above all, the problem is mutability.
Returning copies are not getters (or at least not what most think as getters); they're essentially behaviors. You have to do the extra work to make them only as exposed/encapsulated as necessary.
The point I took from this article is to always strive to make your variables private, and that means not even getters and setters, and only expose behaviors around that data. Which I think makes sense, with some caveats that also have been stated in this article. Not necessarily agreeing, but a good food for thought nonetheless.
That's what I said... "the basic idea is not a bad one" - it was just surrounded by bad arguments for the wrong problems. By starting with the public member thing, the whole text got the wrong spin from the start and the following bad argument didn't help.
Directly addressing mutability, exposing behavior, adding methods that directly work on the members instead of just holding them in a dumb object, etc. is a great idea. But by surrounding it with discussions about public members vs. getters/setters, etc. just dilutes those great points.
I see, and that I can agree with. Hopefully the readers can see beyond it too. Thank you for elaborating!
In the debt example he didn't argue for public variables though, I think you misread that?
He said it wasn't good to expose it at all, but if you do with a getter that returns a copy.
But the better alternative is doing what you want to do with it in the class itself
Yeah, it's too bad many inexperienced developers will not understand that this is just clickbait. Thank you for the great comment. I couldn't do it better.
btw the example of famous person being against setters/getters seem to be about very specific use case.
Well, I used to think that getters and setters are usually useless. Until one day I had to do some computations once a value was set and there I had to re-factor my whole code around the fact that the member was no longer directly accessible but had a getter and a setter.
So I'd say, putting getters and setters is more future proof whilst not being very expensive.
Yet I'd also say that this problem almost only exists in Java because other languages have ways around this (Python <3)
the computations should happen inside your object (in a OO world) you shouldn't be asking other objects for their internals (unless they are simple value objects).
Yup but sometimes you start without needing the computation and then later realize that you need it for a new feature. In that case, it's hard to come back on your decision.
That's why you should program with an OO style and encapsulate. All requires computation.
I was about to mention the same thing. I had the same experience many love C# 😬
Edit: C# Property Design Guidelines
Actually when I just started reading this article. C# is what came to my mind instantly.
I think C# is even worse in this regard.
The argument is that getters/setters and properties VIOLATE ENCAPSULATION by exposing internals as properties rather than mutating through behavior as classic OO would prescribe.
I've seen excessive use of getters/setters/properties in Java, C#, Ruby, and Javascript. Changing the syntax does not help. If anything it aggravates the problem by telling people that its ok to set attributes willy nilly and separate the logic that dictates the behavior from the object.
You made me think!
Great post!
You have just shown bad design. Reason not in getter/setter, but in approach.
If you open properties to public you must have reason why. But not like exception with
debtexample.
If replace getter/setter theme with singleton or composite – and write in the same manner, the result that all is bad, will be the same.
Main point: use features properly. We have instruments in our belts, and to hammer nails with a saw is not the best choice.
Hi Pilipenko, my goal with this article was to show bad design. All of the code examples here are things I would not do, including the debt example. I tried to give guidelines for what I would do in the section at the end, but I probably could follow up with code examples of what I think people should do.
But your topic name is "Avoid getters and setters whenever possible", not "Bad design in getter/setter". This article just discredits specific area of programming, but not educational.
We have a lot of useless articles like "Don't use OOP", "Don't use functional programming", "Why declarative worse that imperative" and so on. But whole idea in right usage, and neither getter/setter neither functional or AOP are not bad.
I must say you have a point: we lack a vast body of "how to do X without violating design flaw Q".
This year I learned about Domain Driven Design, and the Onion Architecture, where they design apis around use cases instead of data. Maybe there is some source of positive guidelines we can tap.
Get/Setter.
Why? Because it's easier to say in a set:
If(Value not null){
set value
}
else{
w/e
}
Than to go EVERYWHERE and check if that value is null then use something.
Sure a basic example looks stupid... but you were not taught not touching the flames by being explained what thermodynamics are...
Get/Setter's are better for a good approach and have assurance that the class will work no matter what the values will be given.
PHP is a loosely typed language getter/setter are perfect for this.
You're concerned about code duplication and that's a good concern. But what if there's a bigger issue here? The fact that this setter can be called "EVERYWHERE", as you say, is a bigger problem to me. Everyone has access to set this value. If just one of them makes a mistake, everyone else using it suffers the downstream effects.
So the real problem here isn't duplicated code, to my mind. It's the fact that there's a variable available everywhere. That sounds like a global variable with some procedural code manipulating its state.
Consider what happens if the field is kept private, and no get/set methods are made public either. Where is everywhere now? Only inside the class itself. It's not a global variable anymore. There aren't a bunch of random classes out there that can go set that value. Another developer can't come in with some new code that calls set on that value incorrectly, and stops several user scenarios from working correctly.
I think we've all worked in scary code like this and we can do better. In my experience, I've found that looking at everywhere the set method is called yields the result that I come out with at most a few different uses, and I can write a method for each use and call the new method from these call sites instead. They'd be behavior methods which keep that variable inside a class or at worst inside a package, and not available everywhere. That way I not only de-duplicate code, but I prevent other bugs that could occur as well. Bugs like the site header one that I mentioned. When no one can call setWhatever(newValue)--indeed they don't even know that the Whatever variable exists--then those kinds of things aren't possible.
In PHP we also use reflection for hydrating objects. If all your objects properties have getters and setters you can hydrate by reflection, otherwise you have to write lots of exchange_array code.
However we can also hydrate on properties directly, but you don't get to do any validation of the data. As you say PHP is loosely typed, so that opens you up to hacking/injection.
What is harder to do is hydrate on both get/set and properties. So you wind up all ways using setters, even if you don't need them all the time.
I think we are confusing bad practice with the role of getter/setter.
Bad practice is everywhere. But when you are using a getter/setter you expect to give a certain value and get a certain value.
You know you are setting a string. You will get a string. Thats the role of the getter/setter.
You are certain and sure that there will be in no circumstation a null there. Or a number. Always a string.
Using getter/setter for everything is bad as well. Leaving a variable there that is used and can be moddified to contain anything is even worse.
If you use get/set just to "return","$this->alfa = value" that's bad practice.
But a beginner doesn't know when should use it or not. So the one that's easiest to "implement after" it's the cheapest.
Scope of projects change. Agile is here and not always you have time to get all the information/specs or maybe some new information get there with constraints.
Always take the safest/easiest way rather than "smart way but it might blow up later".
Hi,
I don't agree with expressing that package private attributes are a better approach than getters and setters.
Suppose you have the case of a bag of properties as you stated in the data use case. A bag of properties may be abstracted as a case of class with state but not behaviour.
Now, let's suppose that, in any time in the future, you have to add behaviour to one of the attributes.
If you implemented the getters and setters, then you put that behaviour in the corresponding methods and you are done.
If you didn't implement those getters and setters, you have several choices to make:
1) Put the new code without being coherent with the rest of the class
2) Refactor all the class to make it coherent and then include the new behaviour
3) Put the behaviour in the calling classes
Maybe I'm missing some point, but I don't see the advantages of the second option.
I didn't understand your option 1, but I would definitely not do option 3. If I understand right, option 3 would mean you go and duplicate the new behavior at every reference to the member. Option 2, then, is way better than 3 in my mind.
For option 2, since it is package private, I would expect the number of references to that field to be fairly limited. How large is a package usually? I'm sure it varies depending on context, but generally its manageable. I personally wouldn't expect more than a few places inside a package where there's a direct reference to a given field. Maybe I make smaller packages than others? With today's refactoring tools, my experience is that its quite painless to switch to a method call rather than a direct member access if that were necessary.
The other thing I would point out is that usually, in the case you mention, you would have to change the method name if you wanted to adhere to the principle of least surprise.
Let's say for a user object, you did start with a getter to reference the user's name, and there were now quite a few references to "user.getFirstName()". Now let's say you got a new requirement to return the user's nickname, if available, rather than their legal first name. Well, if you update the getFirstName() method to do that, yes, you don't have to change code everywhere, but it would kind of suck since it is unexpected for getFirstName to sometimes return the nickname and sometimes return the legal first name.
If we were following good coding practices, what we actually need now is to change all those references from "getFirstName()" to some new method (like "getPreferredName()") instead, which, once again, is no different than if we had used a direct reference to begin with.
Hi Scott, thanks for your answer.
I intended to leave the option 2 as the "more adequate" because the other two are very, very smelly.
Option 2 is more addequate but I wasn't thinking in a case like the one you describe. That case is not a change of behaviour in the getter, but a change in the behaviour of the class. I was thinking in some other cases:
1) Let's say you start with a setter that only does this:
public void setLastName(String ln) {
this.lastName = ln;
}
But in the future, you want to keep track of the modified fields after last read of the database, so in the next update you can only set those fields.
So you add an array of "touched" fields and say, "ok, so when every field is touched by a setter I will add it to the array". Like this:
public void setLastName(String ln) {
this.setTouchedField("lastName");
this.lastName = ln;
}
If you didn't had the setter in the first place, then it would be a pain in the ass adding this behaviour.
2) Let's say you have an object composed of some other objects. Your constructor creates an instance of every each object. But at some point you realize that you want to initialize some of the objects not on parent constructor, but when it's needed. So you could do something like this:
public CustomObject getInstanceOfCustomObject() {
if (this.instanceOfCustomObject == null) {
this.instanceOfCustomObject = new CustomObject();
}
return(this.instanceOfCustomObject);
}
These are some examples I had in mind when I said that it is at some point good to have those getters and setters already coded, even if they are initially totally dumb implementations.
Saludos,
Thanks for the thoughtful questions Daniel! In both cases, I think its still worth asking if there's not some behavior that can be exposed publicly instead of just exposing data. It is easy (because there's so many programmers doing it) to think in terms of data classes being passed around to behavior classes. This is not object-oriented, though. It's a near-cousin to global variables and procedural code operating on those variables. The paper Jason C. McDonald posted in the comments here is a pretty good discussion of these issues.
Unfortunately, both of the examples you gave are going to be prone to concurrency issues that are more serious than the discussion of whether they use "get" style methods. For the second example, try switching to the Initialization-on-demand holder instead. As far as the fact that the method is named "getInstance()" I would not put this in the same category as the getters/setters described in this article. This is a static factory method.
For your example 1, I feel that using the decorator pattern to track the changes in a separate class might be a better approach since it would be a cleaner separation of responsibilities, and you could dynamically add the change-tracking capability only where its needed. OTOH, you don't want to make a whole separate class if its not needed. If you really need to be able to track changes everywhere, then keep it as you showed (but think about concurrency!).
In that case, it would still have a "getXXXX" method then, and I would not be opposed to that. That's why I wrote:
Hi Scott,
Thanks for your answer. Now I understand a little more about the concept you are communicating.
Saludos,
Fantastic stuff! Ultimately, it is the lack of encapsulation and presence of mutability that are the real problems. It is not a style or language issue, rather, it is the lack of awareness from developers to push for better solutions that do not rely on 'cheap and nasty' to do the job.
Very good write up. I had an undefinable suspicion about getters and setters, but you've helped cement it for me. Thanks for the much-needed kick in the teeth for us OOP purists! :)
I'd like to add to this, if you are only using a class/object for storing data, you've got bigger design issues than just getters and setters. Read Pseudo-Classes and Quasi-Classes Confuse Object-Oriented Programming by Conrad Weisert.
Thanks for this paper Jason! It is great!
Someone has never changed his code. Sorry, but afet this "In both classes, Car1.java and Car2.java, we get essentially the same result" i stopped reading. Public properties are not the same as getters and setters. With getters and setters we have an entry point to our business logic, with public properties we don't have any. After changing hundreds of calls to any property through the whole project you'll understand why. This is the first point.
The second point was mentioned in comments. Calls by reference. When you use public properties you usually don't bother with copying stuff. Why should I? Doing that hundred times. That leads to a couple of painfull bugs. The most common one are date objects being modified by reference. Hours thrown away trying to debug that one. Especially by middle/juniors.
Third, getters and setters can be covered with unit tests. If someone changes something you will see that.
The last and not least. It's a lot harder to control workflow with this approach. Instead of reviewing code design, you are forced to check every property call through the whole project. Not very effective.
It's not bad to try to find something new, but getters and setters are used not by chance. If you want to remove a tool, propose something to cover that gap. Good luck.
It shows that you stopped reading at that point. His point was not that public attributes are just as good or better than getters and setters, his point was that the internals of a class should be as restricted as possible and having getters and setters violates that.
If you actually read the article, you would see this:
``.```
My points wasn't on good/bad. He said that both ways give you the same result. And this is wrong. That was what I wrote about.
Second, but not least. Getters and setters can also be restricted, if you need that.
Third, there could be dozens of parameteres. Constructor will become huge and I personally don't like that. For that I'd better use a factory, that will garantee to create a valid object. For any other call there's code review to deny them.
Fourth, there's metaprograming in many languages. That lets you use even private members. So I don't see a reason to be so paranoic about that. But private members could give you headache when writing unit tests or changing class with tens of references to that private member.
To conclude, my main point was that these two methods don't give you the same result. Hope that makes my thougts clearer.
I agree. I think that you should decide the method of your class on the basis of what you expect that class to do (in an abstract sense), rather than on the basis of its internal structure. My personal experience (but YMMV) is that most of the cases (note: not all) where you are tempted to use a setter can be solved with suitable constructor to set the attribute once for all when the object comes to life.
Usually my approach (I use Ada, not Java, so the jargon will be slightly different) is to initially define the internal structure of the object as a "null record," with no field at all. In the spec file then I write the methods I think I need, possibly trying to compile the rest of the code against that spec. Of course, I am not going to obtain an executable, but I can check if the API of my object is complete. Successively, I begin working on the implementation (and this includes the fields of the class).
Usually with this approach any getters/setters you end up with make sense since they do not start from the implementation, but from an abstract view of the object and they are getters/setters "by accident," just because their implementation boils down to reading/writing a field. The resulting code will naturally pass the "acid test" named in one of the linked article why getters and setters method are evil
I see you had two different problems here: The important one, you found a getter returning a pointer, what means you have the control over the content. Aditionally, you put the blame on the getters and setters.
The feature I hate most about Java are equals, getters and setters. They are harder to read (car.setEngine(engine) against car.engine=engine) and harder to write, even with IDEs help, because I need to be generating them and maintaining them if I decide to change the variable name.
They require more code, so when I open the class I have to read those methods just to be sure they are not doing anything more than an assignment. This is time.
And all of this, as you said, to override one in a million.
I found a library, lombok (projectlombok.org/features/GetterS...), that helps you to avoid the implementations with annotations. It is true that it still require to use .getFoo and .setFoo, but I avoid generating them from the IDE and maintain them.
Anyways, I miss a feature in Java like Python's properties, that allow you to override just that method in a million:
So, you can change any public variable to a property just when you require to override that method.
At the begining I was ..."I hope he doesn't suggest to expose the variables", then
I agree that in most of the cases no variables should be exposes, in any matter, it is a statement of: "please side effects and bug, come and get me". In some env it makes sense because 99% of the time is about public vars (for example in Unity3d you have components, and you need to expose parameters of all sort so the game devs can visually instatiante and configure the instances, and ofc this leads to other big issues, beside the ones mentioned here).
I'm happy to see that more people are avoiding getters and setters. But this is such a long wall of text and all of it can be sumarized into one simple idea: "model objects" (get/set JavaBeans) are not real objects!
They are lifeless toys, which we have to move ourselves, instead of relying on them to move and do the job for us. Model objects should not exist in an object oriented world at all. Here is a metaphor about it:
amihaiemil.com/2018/04/17/dolls-an...
Awesome approach and good arguments.
I don't know if you knows the "jsf" ( web programming in java ) , that some specific classes that requires the getters and setters ( convention over configuration ) to their internal implementations uses all structure of the application that use some implementation.
Do you know some advice about it? Or isn't related to the post and there aren't to do?
I think I should have tackled this in the article. You are going to be on the hook to use getters and setters for libraries (like JSF) that reflect on them. Can't really avoid that.
But you can avoid a dangerous anti-pattern (in my opinion), which is then passing such objects around inside the application.
Usually, Java libraries that use reflection on getters and setters are doing it to bind data to/from these objects. There is usually a specific intent behind this, such as to create a POJO from incoming data, such as from the JSON body of an http request.
I believe that this type of automatic object creation should be limited to a single place at the edge of the application. If the usual pattern is followed of turning around and passing the resulting object around inside the app, it creates a situation where changes in the JSON body (or whatever it is), makes you have to change all the code paths that the object travels across.
So its best if you can isolate and decouple these auto-generated objects from your application. Build walls around them and keep them at the edges.
What we have to use if we want validation for the current field only in the class?
... Yes we use setters!
These examples are not correct and don't give a logical answer to the question why we shouldn't use getters and setters.
Hi Dobromir! I mentioned the case of validation in a setter as a valid usage, in the section "When getters make sense"
Nevertheless, a key point that shouldn't be overlooked is to prefer to make validation part of a behavior rather than part of a setter. For example, let's say a web site has a place where potential customers can enter their name and email address to request more information. When someone enters their information in the form and submits it, we want to perform a number of actions including but not limited to:
A common approach is that once the web server receives the request, an object called
Customeror
Useris created with name and email fields. The object is passed around the application and the name, email, and other fields are constantly gotten and set. For example the first thing that may happen is a database lookup which indicates we already have other information for this person, and those fields are all set on the existing object.
Well, whether or not the validation of the email happens in this object, and whether or not it happens in the constructor or setter, I think this data-centered approach is fundamentally flawed. Consider the case where we change what data we collect. Instead of name and email, now we're going to do it with name and cell phone and we're going to use SMS messaging to interact with the customer, because SMS has eight times the response rate of email (retaildive.com/ex/mobilecommerceda...).
In this scenario, we switched from email to phone, and now we go refactor every place in the application that calls
getEmail()or
setEmail().
Instead, what if we took behavior as the first-class citizen of this scenario. What behavior do we want to happen when the customer submits their data? We want to give them more information. OK. We make an interface
PotentialCustomerwith a
giveMoreInformation()method. (Sidebar: the naming here could use some work probably). We implement this interface for our name and email scenario.
When the web server receives this data, it creates the instance of our implementation of
PotentialCustomer. The name and email data is passed to
PotentialCustomervia the implementation's constructor, and this data is private and immutable so the rest of our application doesn't even know (or care) that we're using name and email.
The
PotentialCustomeris composed of other members, who are themselves behavioral objects, and each have a task. One persists the data. Another sends the initial email. Another schedules the follow-up. All of this is called when
giveMoreInformation()is invoked.
Now we have a much better situation for the update to use SMS instead of email. The worst case here is that we create a new implementation of the
PotentialCustomerinterface for this scenario. We don't need to refactor code across many paths.
Does that makes better sense?
This post was amazing. It changed my perspective towards getters and setters.
Having getters and setters makes no sense only if it exposes the private members of the class for being manipulated by other classes.
Functional programming is better!
Totally agree! Accessors is totally anti-OOP feature. I believe it was Martin Fowler who popularized a reprobation of this concept in his post Anemic Domain Model. But little changed from 2003. A lot of people still are not aware that the whole point of OOP is combining data and behavior. Thus accessors still don't make any sense there.
Generally, the $64k question is how to come up with such an objects that expose only behavior, not data. Well, my take on it that it all starts with the problem space -- your concrete domain at hand. Talk to your business-experts, consider the use of CRC-cards, draw use-case diagrams and find your smart and knowledgeable objects.
It so naive for you to misunderstanding how getters and setters work;
The reality is that getters/setters have at least exactly the same security as of any over accessor modifiers.
Moreover, getters/setter have more security other the items thy control when geclared properly.
Getter/Setter is an abstracton of control, allowing you to make some additional operations before you get into trouble with references you incapsulated class data outside of a class.
For examle, SIMPLY buuld and return a COPY of data when getter called, when needed, or clone data when setter called. It is that simple
I think the title is a bit problematic because you trying not to use getters and setters at every single moment just because we were taught to use them. At the end the message is to create real isolation between different parts of the code you do instead of doing setters and getters as check mark for OOP "requirements".
And interface and inheritance and proxy for AOP you newer see? Yes I see a lot of project where was same stupid developers and the harm which they do was prity expensive. Mainly see in a lot of copy paste or repetitive work, because inheritance and interface coldn't be reasonable use.
The article should be named: avoid auto-generation of getters and setters, (because it can cause free mutability issues on a plain field).
And has nothing to do with getters and setters in general.
Just fix the title and article will start to make way more sense, we all know - naming is the most difficult problem.
"In a setter, before updating the state in this object according to some input, we validate the input. The input validation is additional functionality."
Well... that's what a setter should be. You are calling this an alternative, "something close to a setter" but that's just the intended way to use them. The code generated by an IDE should be always a building block to cut repetition while coding, but nothing else. The IDE knows nothing about your implementation so it's your responsibility to make sense of the getter and setter.
But, even if you don't have any sanitisation to make or any other task before the set/get, you still should be using a setter/getter, so you can add them later without meaningless rewrites.
Don't get me wrong, I get what you are trying to say, but I think that framing it like "this is wrong" instead of "you may be using it wrong" just makes it worst. People get defensive with this things (they have a valid point, since the statement is somewhat misleading), end up learning nothing, and nobody wins. | https://dev.to/scottshipp/avoid-getters-and-setters-whenever-possible-c8m | CC-MAIN-2018-30 | refinedweb | 7,336 | 63.7 |
python-keystoneclient SSL CA certificate validation
Bug Description
Following the commit by Adam Young, we discover that python-
(https:/
So in case that the CA certificate is not bundled with the distribution, it refuses to do any operation due to the invalid certificate chain.
This could be solved by specifying an extra parameter with the CA chain in python-
This also affects horizon when using keystone api to check the user during login.
Not validating SSL certificates is definitely not a solution. Then you can as well remove the whole SSL code, if it doesn't check anything. Furthermore, it is actually correct to rely on the certificate store provided by the distribution as it is reviewed by dedicatated security teams (speaking for openSUSE / SLES here but I'm sure thats no different for Ubuntu and RHEL / Fedora) that review and maintain the cert store.
Consider your customer, if you would ship a cert store and a cert gets revoked, you would have to submit a patch to github (to fix the issue for everyone) and then provide that somehow to the customer. OpenStack should only ship example certs so that you can test. But this is nothing you would want to use in production.
I understand your point of view, but this was described as a temporary solution to disable the validation of the CA certificate on the client side to enable SSL while a better solution is proposed.
My request was a parameter on the client side to summit our certificate chain, this parameter is only used in case that you have your own certification authority and it does nothing to the community.
That sounds reasonable, maybe I forgot to clarify that I disregarded the current solution by Liem. I think it still makes sense to add the parameters you proposed. On the other hand, I prefer https:/
Reviewed: https:/
Committed: http://
Submitter: Jenkins
Branch: master
commit dec8f77c9233f19
Author: Sascha Peilicke <email address hidden>
Date: Mon Jul 9 17:07:41 2012 +0200
Add '--insecure' commandline argument
Allows to ignore validation errors that typically occur with self-signed
SSL certificates. Making this explicit is important as one would
typically only use this in development or in-house deployments.
This should also fix bug 1012591.
Change-Id: I1210fafc925764
you can also disable CA validation by
--- keystoneclient/
client. py 2012-07-17 18:02:33.910494211 +0200 client. py.orig 2012-07-17 18:02:22.525503421 +0200
+++ keystoneclient/
@@ -55,6 +55,7 @@
# httplib2 overrides
self. force_exception _to_status_ code = True ssl_certificate _validation = True
+ self.disable_
def authenticate(self):
""" Authenticate against the keystone API. | https://bugs.launchpad.net/python-keystoneclient/+bug/1012591 | CC-MAIN-2017-47 | refinedweb | 433 | 52.6 |
Web services in IntelliJIDEA using the Web Services plugin
By arungupta on Feb 01, 2007:
-).:
- Create a new Web module (wonder why 12 clicks are required for a default project).
- Add a new POJO as:
package hello;It is required to have a non-default package ("hello" in this case).
public class Hello {
public String sayHello(String name) {
return "Hello " + name;
}
}
- Select "Tools", "WebServices", "Enable Web Service Support" as shown here.
- Add
@javax.jws.WebServiceannotation.'s Blog on February 10, 2007 at 02:36 AM PST #
Posted by Arun Gupta's Blog on July 09, 2008 at 11:06 PM PDT # | https://blogs.oracle.com/arungupta/entry/web_services_in_intellijidea_using | CC-MAIN-2015-27 | refinedweb | 101 | 61.26 |
GPS, Location API and Calling Web Services - Day 3 - Part 10
- Posted: Nov 11, 2010 at 6:08 PM
- 34,545 Views
- 49 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
Each Windows Phone 7 includes a Global Positioning System (GPS) that allows the phone to determine the latitude and longitude of the device. In this video, we first look at a special part of the Windows Phone 7 API to access the Geo Location information. Then, once we have the coordinates, we call a Web Service—a "method hosted on a web server," which when given the coordinates will return the city, state, and country names—and we use this to display the location of the device on screen.
Thanks for the feedback! I too had trouble -- even when recording this video -- in getting the web service to work reliably. I think I may have alluded to this during the recordings. If it didn't work the first time, I would try with a fresh project and that would usually fix it.
Thanks for some great videoes, but I'm kinda stuck on this one!
When I press the "Go" button when adding the Web Service, it goes:
"Please wait for service information to be downloaded or click Stop",and nothing happens.
What am I doing wrong here?
Thanks,
H.
Woops; after 5 minutes this errormessage came:
There was an error downloading ''.The operation has timed outMetadata contains a reference that cannot be resolved: ''.The HTTP request to '' has exceeded the allotted timeout of 00:00:00. The time allotted to this operation may have been a portion of a longer timeout.If the service is defined in the current solution, try building the solution and adding the service reference again.
@spier: Thanks a lot for these tipps. I couldn't get the Service Reference to build, even in a clean fresh project. Yout tipps did the trick.
I also tried and tried to get the service to work with no luck, none of the posted suggestions worked for me. So I decided to see if I could do this another way. I ran across Yahoo's PlaceFinder, it is implemented a little different in that it is a REST web service. More info can be found here:
Yahoo! PlaceFinder Guide
I should point out I am an Absolute Beginner, thus why I am watching this series, so if there is a better way todo this I would love the insight. Here is the code I came up with:
You will need to add a reference to your project for System.Xml.Linq so that you can parse the XML data that is returned from Yahoo. And if you plan on using this as a solution you will need to get a developer ID from Yahoo to use it, refer to the link above about this.
I do like the flexibility of the XML returned and that I can grab just the city or state. Hopefully this will help someone else out struggling with the Microsoft Service.
****NOTE**** the code block seems to be messing up my Uri address. It should be:
Uri uri = new Uri("" + latitude + "+" + longitude);
-Shelby
Thanks for the vids but I'm stuck with this one. I cannot find any way to use the TerraService webservice. I get these ugly errors. The trick of spier did't work for me! I tried with a fresh project and it still does't work. Anyone can share a new trick? or explain why it 's so complicated to reference the webservice?
thanks
Vince
you shoud escape the second quote in the Uri's cunstructor
I just want to first say thanks for the videos Bob! They are very helpful. But I too am stuck with this one. I have tried all of the "tricks" but none are working. There is one error that says there are no endpoints of Silverlight 3, could there be an issue since I am working with Silverlight 4?
@spier: Don't know how I missed yours, but that worked.
But now my latitude and longitude are not changing :S help?
<code>
private void button1_Click(object sender, RoutedEventArgs e) { GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher(); var myPosition = myWatcher.Position; double latitude = 0.0; double longitude = 0.0; if (!myPosition.Location.IsUnknown) { latitude = myPosition.Location.Latitude; longitude = myPosition.Location.Longitude; } textBlock2.Text = latitude + ":" + { Lat = latitude, Lon = longitude }); } void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e) { textBlock1.Text = e.Result; // throw new NotImplementedException(); }
</code>
@spier: Don't know how I missed yours, but that worked. But now my latitude and longitude are not changing
On the phone device, I was unable to get the GeoCoordinateWatcher class to work as shown in the video. Rather, I had to use:
watcher =new GeoCoordinateWatcher();
watcher.PositionChanged +=new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
watcher.Start(); // TryStart works too.
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
var myPosition = watcher.Position;
watcher.Stop();
...
}
[quote]
Nov 17, 2010 at 12:24 PM, spier wrote
[/quote]
Thanks Bob!
The spier's solution worked for me!
Is this for the whole world or only for the US?
I got mine working after closing VS and instead of using the .asmx address I ued the
And it worked fine. Pretty cool feature, although just looking at the code is a bit confusing.
I had issues with wavy lines under the 'myTerraService' and 'TerraServiceSoapClient' not changing.
I got it to work by simply by deleting all my service references, restarting visual studio, opening my current project and adding it.
Job done
Bob,
Thanks for the video.
I've been developing in VS for some years and these processes come and go in the fog but I really appreciate your simple clear discussions. Your analogy of throwing a web service request across the fence and receiving the response back across the fence at some unknown future time paints a clear mental picture of what's really happening in a asynchronous web service call.
Thanks again for your efforts in making these somewhat complicated concepts easy to understand and remember.
This has been a really useful video series thus far, but I'm stuck on this one.
Is anyone else having problems actually accessing the terraservice right now? I can't actually navigate my browser to msrmaps.com, let alone access the webservice in VS. Is the service still live?
Thanks again for the videos,
Paul
Hi all,
The concept of adding service reference in order to consume web service is the same if I try to access System.Speech API right? But how should I do it?? Which url is the one to speech recognition? I have been looking for it for a few days but can't find any..I am not sure whether its because I misunderstand or there's other way of doing it as I saw some web pages talking about WCF services..
Thanks in advance for any ideas or point me to right direction.
Hi , Im new with this ,
Im Stuck on this one ,
After adding the teraservice from the url as new service reference , I got few errors and warnnings :
Error 6 Custom tool error: Failed to generate code for the service reference 'myTera'. Please check other error and warning messages for details. References\myTera\Reference.svcmap 1 1 GeoLocationD3_L10
Warning 2='TerraServiceSoap']
XPath to Error Source: //wsdl:definitions[@targetNamespace='']/wsdl:binding[@name='TerraServiceSoap'] GeoLocationD3_L10
it works fine at the Visual Express for windows phone , Wirdly it has the error problem I published at the privious comment at the Visual Studio Ultimat IDE .
any sugestions ?
Hi Bob,
how do we make sure that our app does not crash when the TerraService is down?
I'm getting EndPointNotFoundException whenever the Web service is down. The exception is thrown in publicMyApp.myTerraService.ConvertLonLatPtToNearestPlaceResponseEndConvertLonLatPtToNearestPlace(System.IAsyncResult result) which is in Reference.cs file. That means the exception is thrown before we even get to void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e).
How do we handle such an exception? Thank you in advance.
@spier: That did the trick...thanks...!
Actually, the issue of this WebService is with Microsoft.Phone namespace. If @spier trick doesn't work for you then try this guys;
While you're adding the service, go to the Advance tab below the namespace field and Uncheck the "Reuse types in referenced assemblies" and select OK.
It should work. =)
spier's solution didn't work for me, but this did (don't know if restarting had any role in it).
I restarted Visual Studio. After that, I right-clicked "myTerraService" in the Solution Expolorer and selected "Update Service Reference".
That got rid of the warnings and the error.
[quote
While you're adding the service, go to the Advance tab below the namespace field and Uncheck the "Reuse types in referenced assemblies" and select OK.
[/quote]
This one worked for me with this url:
Thx for your help as I was doubting on myself
@Mintydog:Thanks a lot! Though spier had mentioned the WDSL portion of it earlier, it wasn't until I restarted VS that it worked out. Much obliged for the post!
Just tried to add the Service Reference (with ?WSDL)...and restarted VS and get:
There was an error downloading ''.
The request failed with HTTP status 403: Forbidden.
Metadata contains a reference that cannot be resolved: ''.
Metadata contains a reference that cannot be resolved: ''.
If the service is defined in the current solution, try building the solution and adding the service reference again.
Anyone else still successful at adding the reference?
...I know Bing Maps has an option, but you need an API key for that...which I have...may just try that route.
May help others too...has Bing geo location services:
Hi Bob, thanks for the excelente videos...
The code seems to work fine... but I am getting a wrong location... I am in UK and I am getting the following location 742 km SE of Abidjan,, Cote dlvoire... Any idea? thank you.
I really enjoy this video series. FInally a video series that actually works (with minor modifications).
I ran into several problems getting the GPS to work; finally, I re-installed the Windows Phone 7.1 SDK into my Visual Studio 2010 Professional x64 and this GPS things works.
I obtained the Windows 7.1 SDK from which provided a link to the download. If you are having problems, re-install your Windows 7.1 SKD as the RTM version does not work... This process resolved my issues, I hope it works for you too.
Mejamz
NOTE: I also installed 2 other reference packs; Microsoft.Phone.Controls and Microsoft.Phone.Controls.Maps
This comment has been redacted
@G Cupertino: I get the same location returned and I live in the USA. I believe it is a default location to simulate a working program; when I set the corrdinates to Microsoft in Redmond Washington, the app resolves correctly as mentioned in my postings.
Another possible resolve for the GPS is after creating the service reference, save, close and reopen the solution. Then right click on the new service reference and select update service reference... this has worked in VS 2010 Pro x64 once so far.
Hi Bob
A great set of videos :-)
I was able to to get the myTerraService to resolve the errors by right clicking on myTerrService and selecting "Update Service Reference"
Wayne
Bob can you please send me the web service which will be helpful for me in order to know the complete address of the user's current location?
The web service you told us to use over here is through longitude and lattitude is retrieving the name of the city and state only.
Only mooreshelby's solution worked for me! Thanks man...
Great videos Bob! I had issues too with this one but I followed this one and it runs like a charm now:
@Mejamz
<Another possible resolve for the GPS is after creating the service reference, save, close and reopen the solution. Then right click on the new service reference and select update service reference... this has worked in VS 2010 Pro x64 once so far.>
Thanks, worked for me.
I changed the file name to the WDSL one spiers said ''then ran it - it complained about a '{A4CACFEE-4F0A-4996-975D-8B5B30F9BABD}.dess' file that was corrupt and said to remove it.
Once I had renamed it '_{A4CACFEE-4F0A-4996-975D-8B5B30F9BABD}.dess' (which I do in case i delete the wrong file and need it back!) it stopped showing errors!
It is sitting in the 'ProgramData\Microsoft\XDE' folder. Maybe some of you can try that.
Having said that. I could not get the longitude and latitude in the following as it didn't accept it so i left it blank and it told me i was 742km se of Abidjan Cote D'voire Africa! I am in London Uk! So something not quite right here. Any help why i got this wrong?
pls see below.
client.ConvertLonLatPtToNearestPlaceAsync(new myTerraService.LonLatPt()); // will not accept parameters long or lat.
//------------------------------------
GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher();
//add object variable.
var myPosition = myWatcher.Position;
double Longitude = 47.674;
double Latitude = -122.12;
if (!myPosition.Location.IsUnknown)
{
Latitude = myPosition.Location.Latitude;
Longitude = myPosition.Location()); // this is wrong! gave up!
}
void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e)
{
//throw new NotImplementedException();
textBlock1.Text = e.Result;
}
}
//------------------------------------
This stuck me too. And I tried . At first, it did not work. Then I restarted my vs2010, I just made it. Amazing and puzzling.
Firstly I have the common error which has been solved by restarting Visual Studio and updating the service.
Secondly, I run the app on a Nokia Lumia 710, but no GPS coordinates are retrieved. It keeps showing me "Redmond, Washington, United States". Do I have just to wait more? Re-click on the Find Me button? How do I know if the GPS is ON and if the app is trying to retrieve the coordinates?
Many thanks indeed to anyone who can answer me.
Yeah this totaly stuck me!! Sad and very frustrating! Tryed to get it by doing it four different times and using all the different fixes! sigh :/
I've to say that this comment helped me a lot for adding the Service Reference.
This second post solve the other problem. Hence, for sake of clarity, I am posting here my full code in order to give to everybody the possibility of having a working program.
<Button Content="Find Me" Height="72" HorizontalAlignment="Left" Margin="290,135,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="6,6,0,0" Name="myPositionTextBlock" Text="" VerticalAlignment="Top" Width="444" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="6,42,0,0" Name="myLatitudeTextBlock" Text="" VerticalAlignment="Top" Width="444" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="6,78,0,0" Name="myLongitudeTextBlock" Text="" VerticalAlignment="Top" Width="444" />
You need to add myWatcher.Start() to start the watcher. otherwise, you'll always get the default location. Remember to stop it afterwards.
Hello Bob.Thanks for the wonderful series of videos. I have problem loading the LonLatPt from myTeraService
client.ConvertLonLatPtToNearestPlaceAsync(new myTerraService.LonLatPt { Lat = geo.Latitude, Lon = geo.Longitude });
The code I have written works perfectly fine but it just give me one error :
Error 3 The type or namespace name 'LonLatPt' does not exist in the namespace 'Splendor.myTerraService' (are you missing an assembly reference?) C:\Users\Kocev\Desktop\Mobile Splendor1\Splendor\Splendor\MainPage.xaml.cs 78 80 Splendor
Works perfectly. Had some problem previously running the code but then i tried restarting VS and then updating myTerraService by Right Clicking on it. Though it seems that MSR Maps have been shut down since 1st of May as it is written on the website. Also i am not from US so it gives me weird Location.
Thanx Bob and great Video Series.
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Series/Windows-Phone-7-Development-for-Absolute-Beginners/GPS-Location-API-and-Calling-Web-Services?format=progressive | CC-MAIN-2014-10 | refinedweb | 2,673 | 67.15 |
Opened 6 years ago
Last modified 3 years ago
#11716 assigned Bug
Various methods in django.db.models.fields don't wrap ValueErrors and allow them to escape
Description
Passing in a '---' as the value for a ModelChoiceField causes an exception down in query.py that filters up through the form.
Here is specifically what I'm doing:
class Bar(Model): name = TextField() class Foo(Model): bar = ForeignKey(Bar, blank=True, null=True) class FooForm(ModelForm): def __init__(self, *args, **kwargs): super(FooForm, self).__init__(*args, **kwargs) bars = list(Bar.objects.order_by('name')) self.fields['bar'].choices = [('---','---')] + [(b.id, b.name) for b in bars]
If someone submits the form without selecting a Bar in the dropdown, the view does the standard is_valid() call and blows up.
But even if setting the field up this way that isn't a good idea (which it may not be), a client can submit whatever they want to the view that processes the form so this is a situation where submitting an invalid value creates a 500 rather than being caught in the field and reported as a form error.
Here is the full traceback
File "C:\ws\fuzzy\EvoworxSite\src\testapp\views.py", line 13, in do_test if form.is_valid(): File "C:\Python25\lib\site-packages\django\forms\forms.py", line 120, in is_valid return self.is_bound and not bool(self.errors) File "C:\Python25\lib\site-packages\django\forms\forms.py", line 111, in _get_errors self.full_clean() File "C:\Python25\lib\site-packages\django\forms\forms.py", line 240, in full_clean value = field.clean(value) File "C:\Python25\lib\site-packages\django\forms\models.py", line 993, in clean value = self.queryset.get(**{key: value}) File "C:\Python25\lib\site-packages\django\db\models\query.py", line 299, in get clone = self.filter(*args, **kwargs) File "C:\Python25\lib\site-packages\django\db\models\query.py", line 498, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Python25\lib\site-packages\django\db\models\query.py", line 516, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Python25\lib\site-packages\django\db\models\sql\query.py", line 1675, in add_q can_reuse=used_aliases) File "C:\Python25\lib\site-packages\django\db\models\sql\query.py", line 1614, in add_filter connector) File "C:\Python25\lib\site-packages\django\db\models\sql\where.py", line 56, in add obj, params = obj.process(lookup_type, value) File "C:\Python25\lib\site-packages\django\db\models\sql\where.py", line 269, in process params = self.field.get_db_prep_lookup(lookup_type, value) File "C:\Python25\lib\site-packages\django\db\models\fields\__init__.py", line 210, in get_db_prep_lookup return [self.get_db_prep_value(value)] File "C:\Python25\lib\site-packages\django\db\models\fields\__init__.py", line 361, in get_db_prep_value return int(value) ValueError: invalid literal for int() with base 10: '---'
Digging into the code it looks like django.db.models.fields.AutoField.get_db_prep_value should look something like this:
def get_db_prep_value(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( _("This value must be an integer."))
Which is just like the to_python() method above it.
Further, it looks like IntegerField and several others in that file have the same problem and let the ValueErrors escape.
Attachments (4)
Change History (40)
comment:1 Changed 6 years ago by Leo
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Summary changed from ModelChoiceField blows up on non-integer input to Various methods in django.db.models.fields don't wrap ValueErrors and allow them to escape
comment:2 Changed 6 years ago by Leo
- Has patch set
- Needs tests set
Changed 5 years ago by Leo
comment:3 Changed 5 years ago by Leo
- Needs tests unset
- Owner changed from nobody to Leo
- Status changed from new to assigned
Thanks to mattmcc for pointing me in the right direction, I've attached a patch with the tests.
comment:4 Changed 5 years ago by adamnelson
Would this also more gracefully handle an invalid value like 'f' when an int is expected?
Model.objects.get(id='f')
comment:5 Changed 5 years ago by Leo
int('f') and int('--') result in the same exception being thrown, which this patch would then convert into a ValidationError which gets turned into a normal form error.
comment:6 Changed 5 years ago by Leo
Ah, I see what you're asking now. Doing get() takes you through the same code path. This patch changes the behavior to be consistent with how it would be if you tried to do get(some_boolean_field='foo') and the documentation is silent on what the proper response should be if the argument is incorrect.
ValidationError comes from django.core.exceptions so it seems like its fair game to be used here (and is used for the other fields). If one of the committers feels its needed, I can try to add the behavior to the docs in the appropriate places.
comment:7 Changed 5 years ago by Leo
- Version changed from 1.1 to SVN
comment:8 Changed 5 years ago by russellm
- milestone set to 1.2
- Patch needs improvement set
- Triage Stage changed from Unreviewed to Accepted
I suspect the patch needs to be updated in the light of the changes for multidb.
comment:9 Changed 5 years ago by Leo
Thanks for accepting it Russell. I suspect you're right, I'll take a look.
It would have been fabulous to have had the patch merged in to trunk a little bit earlier in the cycle to prevent that though.
Changed 5 years ago by Leo
comment:10 Changed 5 years ago by Leo
- Patch needs improvement unset
Ok, I've updated the patch. There were a few more details involved here:
- several functions in BooleanField would accept a value of None silently, that's no longer the case - this is backed up by the thinking in #5563
- IntegerField's default error message had a typo in it - 'invalid': _("This value must be a float.") - it's been changed to read correctly - This value must be an integer.
Please let me know if there are any more issues that need to be resolved. I'd really love to get this into 1.2.
comment:11 Changed 5 years ago by kmtracey
A newly-added test fails with the current patch:
====================================================================== ERROR: testCommentDoneReSubmitWithInvalidParams (regressiontests.comment_tests.tests.comment_view_tests.CommentViewTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/kmt/tmp/django/trunk/tests/regressiontests/comment_tests/tests/comment_view_tests.py", line 235, in testCommentDoneReSubmitWithInvalidParams response = self.client.get(broken_location) File "/home/kmt/tmp/django/trunk/django/test/client.py", line 286, in get response = self.request(**r) File "/home/kmt/tmp/django/trunk/django/core/handlers/base.py", line 101, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/kmt/tmp/django/trunk/django/contrib/comments/views/utils.py", line 41, in confirmed comment = comments.get_model().objects.get(pk=request.GET['c']) File "/home/kmt/tmp/django/trunk/django/db/models/manager.py", line 132, in get return self.get_query_set().get(*args, **kwargs) File "/home/kmt/tmp/django/trunk/django/db/models/query.py", line 331, in get clone = self.filter(*args, **kwargs) File "/home/kmt/tmp/django/trunk/django/db/models/query.py", line 545, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/kmt/tmp/django/trunk/django/db/models/query.py", line 563, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/kmt/tmp/django/trunk/django/db/models/sql/query.py", line 1100, in add_q can_reuse=used_aliases) File "/home/kmt/tmp/django/trunk/django/db/models/sql/query.py", line 1040, in add_filter connector) File "/home/kmt/tmp/django/trunk/django/db/models/sql/where.py", line 66, in add value = obj.prepare(lookup_type, value) File "/home/kmt/tmp/django/trunk/django/db/models/sql/where.py", line 275, in prepare return self.field.get_prep_lookup(lookup_type, value) File "/home/kmt/tmp/django/trunk/django/db/models/fields/__init__.py", line 318, in get_prep_lookup return self.get_prep_value(value) File "/home/kmt/tmp/django/trunk/django/db/models/fields/__init__.py", line 498, in get_prep_value return self.to_python(value) File "/home/kmt/tmp/django/trunk/django/db/models/fields/__init__.py", line 492, in to_python raise exceptions.ValidationError(self.error_messages['invalid']) ValidationError: [u'This value must be an integer.'] ---------------------------------------------------------------------- Ran 82 tests in 13.539s FAILED (errors=1)
I kind of thought it was going to and nearly didn't add it, pending some resolution between that ticket (#12151) and this one, but on further reflection I think the problem is here. If there is existing code that handles errors in submitted data by catching ValueError raised on a get, that's going to break if the same error condition now raises ValidationError instead.
I agree that it's ugly that bad data can cause a plethora of different exceptions to be raised -- but switching to one and only one, if that is not one that was previously being raised, seems bckwards-incompatible. Am I missing something here?
comment:12 Changed 5 years ago by Leo
I agree that this is a behavior change (and in principle backwards incompatible) but virtually any bugfix is going to be.
This is my reasoning as to why this bugfix is worth the behavior change.
IMO, the issue here isn't that bad data can cause a plethora of different exceptions. IMO the issue is that the API for a Field's behavior is to throw ValidationErrors and not allow other errors to percolate up through the call stack. Most of the other fields already do this properly and these few do not.
The actual behavior in the current codebase is inconsistent with the expected API and therefore broken which forced users (and django itself - see the fix to django/forms/models.py in the patch) to have to code defensively. Yes, the behavior does change, however the rest of the stack is already written with the expectation of getting a ValidationError from fields when they're cleaned or when invalid input is given to them.
In the test that was added in r12681, the catch statement should be catching a ValidationError rather than a ValueError. In that specific test if for some reason request.GET['c'] returned something of a type that AutoField couldn't handle, you'd have to check for TypeError as well. Those exceptions are implementation details of AutoField and should be encapsulated by AutoField. For that specific example, if pk could ever refer to something other than an IntegerField (its not entirely crazy that a primary key might not be an integer) then you would have to catch any exceptions that field threw as well.
comment:13 Changed 5 years ago by kmtracey
But we can't introduce a change where previous application code that worked will now raise an exception. If yesterday code had to catch ValueError (and TypeError, and whatever else if it was to be 100% robust) in order to properly recover from being handed bad data, we cannot now start raising a different exception and make previously robust code start throwing exceptions.
comment:14 Changed 5 years ago by Leo
I'm not sure if you're stating that as a policy or as an argument for why this fix shouldn't be taken. I don't have sufficient knowledge to argue against it as a Django policy (although if that's the case, I will try and figure out the best way to do so). I can, however, make a strong argument for making this change on its own merits.
I agree with the principle of keeping the API consistent for a given release but this is a case where the implementation of the API was broken. If the point that you're making is that any code that relied on this broken behavior will be broken once this bug is fixed, well, yes. Any bugfix changes behavior and IMO a bugfix that causes an explicit loud exception to get thrown is much better than one that may have not immediately obvious side effects. As a random example of a bug that I've worked on, take #5605 - someone relying on the 'incorrect' lowercasing behavior and using a case sensitive DB backend may now have a very subtle bug in their code when they upgrade to 1.2. One could easily find such cases for pretty much any bug.
The consequences of not fixing this bug are fairly significant as described in the example above and require client code to look significantly uglier as well as become tied to the actual implementation of any specific field. I just double checked the docs and primary_key is just a method on Field so it can be applied to ANY field. Which in turn means that if you abandon the API of requiring the Field to encapsulate its internal working in a ValidationError, the catch statement in the comments code has to catch pretty much any exception that could possibly come out of the field. That should clearly not be the responsibility of that client code.
comment:15 follow-up: ↓ 16 Changed 5 years ago by kmtracey
I'm saying it's policy not to introduce backwards-incompatible changes in a micro or minor release update, and therefore I have concerns about this patch, because it seems to me it may likely cause previously robust application code to start raising exceptions.
You say the consequences of not fixing this bug are significant. What I'm saying is we cannot now break code in the wild that has already been written to accommodate those consequences. Code that likely looks similar to the comments code:
def confirmed(request): comment = None if 'c' in request.GET: try: comment = comments.get_model().objects.get(pk=request.GET['c']) except (ObjectDoesNotExist, ValueError): pass return render_to_response(template, {'comment': comment}, context_instance=RequestContext(request) )
This code catches ValueError there because that is the exception that has in fact been raised in observed cases where bad data is present in request.GET['c']. It doesn't catch ValidationError because that has not been an exception observed to be raised..
comment:16 in reply to: ↑ 15 Changed 5 years ago by Leo
I'm saying it's policy not to introduce backwards-incompatible changes in a micro or minor release update, and therefore I have concerns about this patch, because it seems to me it may likely cause previously robust application code to start raising exceptions.
I agree that it will cause some applications to start raising exceptions. I think your concerns are vary valid and critical to consider for a project like Django. I believe that its a better choice for Django to make this change in this release and take the impact of introducing this behavior change especially since non-trivial parts of the DB architecture have been worked on for this release (including the very functions this patch changes).
You say the consequences of not fixing this bug are significant. What I'm saying is we cannot now break code in the wild that has already been written to accommodate those consequences.
Sure, but that's true for virtually any bugfix so this isn't an absolute. This is a discussion with a range of impacts of either making the change or not making it.
This code catches ValueError there because that is the exception that has in fact been raised in observed cases where bad data is present in request.GET['c'].
It doesn't catch ValidationError because that has not been an exception observed to be raised.
In my experience the approach of seeing what exceptions I can observe has not been a great way figure out what exceptions to catch in the code that I write. I've found that fairly often I either overlook a potential failure case or do not fully understand (or sometimes don't even have access to) how the code I'm working with behaves. This has resulted in me preferring to think about interfaces and how the code should behave and defining those interfaces in one form or another..)
It doesn't need to be a very non-standard field. A DecimalField will cause the problem. It's a slightly larger test case to create a custom Comments model but I've attached a very simple one that breaks another part of the comments application that also doesn't catch ValidationError properly..
I think you're right. Very few developers are happy when their code doesn't work as they expect. In my experience the best way to prevent that is to have interfaces on commonly used components. If this change is properly messaged in the release notes I believe that it will make Django users happy when they can replace rather ugly and patched code with much cleaner code that represents a contract and gives them more assurance that their app won't break.
I respect your concerns about this patch and I think we're both striving to make Django better but I suspect we may not come to agreement on this issue so I'm wondering what the right next step is given Django's process. Should this be brought up for discussion on django-dev? is there a vote by the core committees? does the release manager decide this?
Changed 5 years ago by Leo
Example failure case from not catching ValidationError
comment:17 Changed 5 years ago by adamnelson
@kmtracey While it may in theory be true that milestone:1.2 is 'minor', that's not true in practice. Python 2.3 support is being dropped as well as all sorts of major backwards incompatible changes. Anybody who wrote a workaround for this behavior can stick with milestone:1.1 for an extended period of time while updating their codebase. Well maintained apps can move to this format in short order without losing milestone:1.0 compatibility. I would understand not making a backwards incompatible change in milestone:1.1.1 , but for something as big as milestone:1.2 with so many other major incompatibilities, we're wasting time.
In addition, russelm accepted the ticket and assigned it to milestone:1.2 . That should be sufficient to get the ticket merged.
comment:18 Changed 5 years ago by adamnelson
Maybe the compromise is to revert the ValidationError to ValueError change and leave everything else as is? ValidationError isn't in the standard library, so it's not the craziest thing to just stick with ValueError for milestone:1.2 and make a new ticket to rationalize exceptions in Django.
comment:19 Changed 5 years ago by kmtracey
In my view it is not a waste of time to ensure we don't blindside users with backwards-incompatible changes. Note we do attempt to document all backwards incompatible changes, so that people who might run into them may have a clue, if they read the release notes, that they could run into them when updating. There are no such notes included with this patch, nor was there even mention of the possibility of this introducing a backwards-incompatibility, until I brought it up. If this is to be done for 1.2, it needs documentation of the backwards incompatibility introduced.
(Note claiming it's perfectly OK to add more backwards-incompatible changes into 1.2 because it already has so many is fallacious: each one is considered on its own merits. If anything I'd argue that the reasons needs to be even stronger as the list gets longer, not the other way around.)
Alternatively, if there is a way to accomplish the bulk of what this ticket was aiming for without introducing a backwards-incompatibility, that would be even better, in my opinion. Hopefully I've clarified above what I mean by backwards-incompatible. (It is not true that every behavior change introduced by a bugfix introduces a backwards-incompatibility.)
As for process, what's needed is consensus among the core devs. What we've got now is one (me) who has expressed concerns and none who have come forward to say my concerns are unfounded or overblown. While Russ accepted the ticket, I do not know if he was aware of the backwards-incompatibility introduced and did not think it enough of a problem to worry about, or if he did not notice it.
I won't stand in the way if others on the core think this is a change worth making, even in light of the problems it may cause for existing code. I'll just strongly urge that it at least needs documentation of the backwards incompatibility.
comment:20 Changed 5 years ago by adamnelson
Is all that's being asked is whether to change ValidationError back to ValueError ? If so that seems like the way to go.
comment:21 Changed 5 years ago by Leo
@adamnelson Thanks for weighing in, however making the code not throw a ValueError is the heart of the patch. All that does is wrap the TypeErrors but doesn't fix the implementation from an API perspective.
@kmtracey, I strongly agree that this behavior change needs documentation. I left it out of the original patch since I strongly suspect that what I write will need to be re-written by a core dev anyways to fit style and consistency guidelines. If that's not the case, I'm happy to take a crack at it.
comment:22 Changed 5 years ago by kmtracey
Replying to adamnelson:
Is all that's being asked is whether to change ValidationError back to ValueError ? If so that seems like the way to go.
I don't know what you are proposing there exactly.
I'd object to changing fields (such as DecimalField) that currently raise ValidationError for bad data to instead raise ValueError, for the same reason as I've raised concerns about the reverse change: it would break previously working code.
If you're not proposing that but rather proposing that these particular fields that currently unfortunately raise ValueError instead of the ValidationError that would be more proper, continue to raise ValueError while other fields continue to raise ValidationError, then I'm not sure what the change buys us, exactly. I thought one of the aims was to bring consistency to the API across the field types?
Having ValidationError inherit from ValueError might be a possibility, but I haven't had time to think through whether that introduces any of its own problems.
comment:23 Changed 5 years ago by russellm
- milestone changed from 1.2 to 1.3
Not critical for 1.3
comment:24 Changed 5 years ago by Leo
I understand that this ticket isn't crucial to the 1.2 release (even though it fixes functionality that was changed in 1.2) but it would be really fantastic if it got addressed/landed early in the 1.3 cycle. It would be incredibly frustrating to do a third version of this patch if there were significant DB layer changes as part of 1.3.
comment:25 Changed 4 years ago by sirex
Same here. Instead of getting normal form validation error, I getting unhandled exception, what leads to 500 error.
Why this error is not already fixed?
Changed 4 years ago by timo
updated patch to trunk + tests passing
comment:26 Changed 4 years ago by timo
This has always bugged me too. When submitting non-integer data to a ModelChoiceField having a server error instead of a validation error isn't nice. I updated the existing patch to apply cleanly and get the test suite passing with the hopes that this might get some consideration for 1.3.
comment:27 Changed 4 years ago by Leo
timo, thanks for cleaning up the patch! The path in your diff, however, seems incorrect, all of the diffs start with 'a/django/' instead of 'django/'
I'm continually trying to get a core dev's attention to this ticket/bug/issue.
comment:28 Changed 4 years ago by lukeplant
- Needs documentation set
The patch is fine regarding the format ('a/django' is just an artifact of using git/hg to create the diff, and can be handled easily using 'patch -p1').
The patch lacks documentation of the backwards incompatibilities, as already noted by Karen. Every circumstance where previously working code might fail needs to be documented in the 1.3 release notes - and there seem to be quite a few, given the number that cropped up just in the test suite. Even if this documentation is re-written, it is always useful to have a starting point.
comment:29 Changed 4 years ago by kmtracey
Is there no way to do this is a backwards-compatible way, such that code which currently does not raise exceptions when handed bad values continues to not raise exceptions when handed the same bad values? Even with documentation this is the kind of change that is hard to easily "upgrade to" and be sure that you have actually covered all the places where you (or some piece of code you have inherited) may have used "except ValueError" or whatever where now some other exception is more properly going to be raised. There was mention of possibly having ValidationError inherit from ValueError above -- I would like to see some investigation of the feasibility of an approach like that or at least some explanation of why it can't possibly work before going ahead and adding a backwards-incompatible alternative.
comment:30 Changed 4 years ago by timo
Actually, r13751 fixed the particular use case I had (posting a non-integer value to a ForeignKey field would raise an exception rather than a form field error). I'm not sure if there is anything else that Leo is looking for.
comment:31 Changed 4 years ago by Leo
timo, thanks for pointing that out. r13751 fixes the initial problem that I posted, however it changes the behavior of the to_python function in the same way as my proposed patch - which means that according to the discussion in this ticket it requires the same backwards incompatible documentation. Code that caught ValueError on that field before will now not catch it.
The patch for this ticket makes the same fix across several other models and makes the API here consistent. @kmtracey, I don't think that there's a backward compatible solution here, precisely because it's trying to fix behavior that's broken. Having ValidationError extend from ValueError is a bad idea that's going to affect a LOT more of the codebase and client code.
@lukeplant all of the test changes were necessary because the tests were testing the broken API, just like they were in r13751. The expected exception is a ValidationError not a ValueError.
I will spend time this week to add a note to the backwards compatibility for this patch. Hopefully it's not too late for 1.3.
comment:32 Changed 4 years ago by danfairs
- Cc danfairs added
comment:33 Changed 4 years ago by julien
- Severity set to Normal
- Type set to Bug
comment:34 Changed.
I've attached a patch, and I'm happy to add some tests but I can't figure out where they would go. The similar behavior for DecimalField has no test that I could find. | https://code.djangoproject.com/ticket/11716 | CC-MAIN-2015-11 | refinedweb | 4,572 | 54.12 |
ui/ Group
Provides a component that renders a group of components given a set of data.
import Group from '@enact/ui/Group';
GroupComponent
A component that supports selection of its child items via configurable properties and events.
Selected item is managed by ui/Changeable.Changeable.
import Group from '@enact/ui/Group';
Properties
Component type to repeat. This can be a React component or a string describing a DOM node (e.g.
'div')
An array of data to be mapped onto the
childComponent.
This supports two data types. If an array of strings is provided, the strings will be used in the generated
childComponentas the content (i.e. passed as
children). If an array of objects is provided, each object will be spread onto the generated
childComponentwith no interpretation. You'll be responsible for setting properties like
disabled,
className, and setting the content using
children.
NOTE: When providing an array of objects be sure a unique
keyis assigned to each item. Read about keys for more information.
The property on each
childComponentthat receives the data in
childrenDefault: 'children'
The name of the event that triggers activation.Default: 'onClick'
The property on each
childComponentthat receives the index of the itemDefault: 'data-index'
An object containing properties to be passed to each child.
Callback method to be invoked when an item is activated.
Selection mode for the group
Default: 'single'
single- Allows for 0 or 1 item to be selected. The selected item may be deselected.
radio- Allows for 0 or 1 item to be selected. The selected item may only be deselected by selecting another item.
multiple- Allows 0 to n items to be selected. Each item may be selected or deselected.
The index(es) of the currently activated item.
The name of the DOM property that represents the selected state.Default: 'data-selected'
GroupBaseComponent
A stateless component that supports selection of its child items via configurable properties and events.
import {GroupBase} from '@enact/ui/Group'; | https://enactjs.com/docs/modules/ui/Group/ | CC-MAIN-2021-04 | refinedweb | 324 | 51.04 |
Great, here we go!
I read the warning about RMI aswell but i need definitely to access the
repository from Java in a programatic way, therefore i need to obtain the
running repository object somehow and JNDI (at least for me) did tricky
things (such as effectively registering the repository object in the JNDI
namespace but returning null as i try to access to it). In my case,
performance is still not the point, but if it comes to performance i think
that the most convinient will be to use the WebDav access, for which there
is no warning, isn't it?. By now i need to have a basic repository running,
that is why RMI is enough for me (with some limitations: for example i did
not achieve to instantiate a UserManagerImpl object to deal with user
accounts (and queries are not supported neither i heard).
Let's go then. About the distribution of the system you mentioned: RMI
objects are available JVM-wide (as far as i know, you should confirm), here
you are some code snippets to get your running instance of the Repository
object:
*STANDALONE VERSION*
Fireup the repository:
java -jar jackrabbit-standalone-2.2.7.jar --conf /path/to/repository.xml
--repo /path/to/repositoryrootfolder
Obtain the repository object instance in your Java program:
...
Repository repository = JcrUtils.getRepository("");
Session session = repository.login(new SimpleCredentials("user",
"".toCharArray()));
*// if no exception && no null => running-repository object was retrieved
successfully***
System.out.println("Ready to operate the repository: " + repository);
...
*WAR VERSION*
bootstrap.properties file:
repository.name=XXXXX
# RMI Settings
rmi.enabled=true
# I guess that 0 means default port (that is 1099)
rmi.port=0
rmi.host=localhost
Obtain the repository object instance in yoir Java program:
Repository repository =
JcrUtils.getRepository("rmi://localhost:1099/XXXXX");
Session session = repository.login(new SimpleCredentials("user",
"".toCharArray()));
*// if no exception && no null => running-repository object was retrieved
successfully***
System.out.println("Ready to operate the repository: " + repository);
...
That is all, you should be able now to access the repository from a simple
Java program, but remember that not all the operations are supported by RMI
(nor WebDav).
Since you mentioned some design issues aswell i paste here some response i
got about similar issues (from Edouard Hue, in this list, don't know why it
was not published there by the way), just in case:
*The standalone version has the same capabilities as the WAR : both expose
HTTP (DAV) and RMI interfaces. It's a mode 3 deployment model, see. *
*You won't need a Servlet context to use these. Please also have a look at
this page :*
*
*
*RMI and DAV remote interfaces don't implement 100% of the JCR API. Some
operations (such as querying) can only be achieved locally. The only
solution I know for this case is to use deployment model 2 and expose the
Repository through JNDI ().*
Hope that helps, greetings!
2011/8/3 Matthieu Legras <matthieu.legras@spotuse.com>
> Hi Francisco,
>
> That's exactly what I want to do, indeed!
>
> I'd also like to know if your solution implies some limitations, for
> example in case I want to have the java application and the JR Repo on
> different servers (in the future)? I found a notice saying "Warning: The
> current JCR-RMI library is designed for simplicity, not performance. You
> will probably experience major performance issues if you try running any
> non-trivial applications on top of JCR-RMI." on this page:
> , which seems
> pretty scary to me (since splitting my java app and the JR repo to different
> servers would occur in case my application gets a considerable amount of
> users). Is the solution you develop concerned by this notice?
>
> Thanks for your help!
>
> Matthieu
>
> On Wed, Aug 3, 2011 at 3:57 PM, Francisco Carriedo Scher <
> fcarriedos@gmail.com> wrote:
>
>> Hi there Matthieu,
>>
>> during last week i have been developing a similiar solution, but i started
>> with the Java side of the system (use a repository through Java classes i
>> mean), so i think that perhaps i can result useful. For the sake of
>> simplicity, what you want to develope is the left part of this "graph",
>> isn't it?:
>>
>> Java applications HTTP
>> clients
>> accessing concurrently ====> JR Repo <==== GETTING [and
>> to the repository
>> PUTTING] resources
>>
>> If the answer is no i did not understand you, sorry... Otherwise, just
>> answer this email and i will try to tell you useful things from the last
>> week.
>>
>> Greetings!
>>
>>
>>
>>
>> 2011/8/3 Matthieu Legras <matthieu.legras@spotuse.com>
>>
>>> Hi,
>>>
>>> I'm currently implementing a calendar system using the CalDAV part of
>>> jackrabbit. I have to link it with an application, running on the same
>>> server, which will massively interact with the CalDAV data.
>>>
>>> Therefore, i'm looking for a way to add, suppress and synchronize data,
>>> without using an http connexion between jackrabbit and the application.
>>>
>>> Any help on this would be highly appreciated!
>>>
>>> Cheers,
>>>
>>> Matthieu
>>>
>>
>>
> | http://mail-archives.apache.org/mod_mbox/jackrabbit-users/201108.mbox/%3CCAFWtOcMnZ5pdcLTbp-kYgJ_jn5LSfkyhORGzP2UitdUOix4nkg@mail.gmail.com%3E | CC-MAIN-2018-47 | refinedweb | 818 | 54.93 |
*
It has recently become apparent that bacterial DNA has potent
immunostimulatory properties. Vertebrate DNA has low levels of CpG
dinucleotides and most of the cytokine residues are methylated. In
contrast, the genomes of bacteria, viruses, and retroviruses are not
methylated and may or may not show CpG suppression (3, 4).
It is now well established that humans and other vertebrates may detect
unmethylated CpG dinucleotides in particular base contexts ("CpG
motifs") as a sign of danger or infection. Such CpG DNA, or synthetic
oligodeoxynucleotides
(ODN)3 containing
these CpG motifs, activate dendritic cells, monocytes, and macrophages
to secrete Th1-like cytokines and to induce Th1 T cell responses,
including the generation of cytotoxic T lymphocytes
(5, 6, 7, 8, 9, 10, 11). In conjunction with adherent cell-derived
cytokines, CpG DNA strongly stimulates NK cells to secrete IFN-
and
to have increased lytic activity (12, 13, 14). CpG DNA also
directly activates B cells to proliferate, secrete IL-6, and Ig and to
have increased cell surface expression of costimulatory molecules
(3, 9, 15). In contrast to LPS and other immune
stimulatory agents that have been evaluated, CpG DNA shows an extremely
strong pattern of Th1-like cytokine induction and can even be used for
immunotherapy of Th2-mediated allergic disease in experimental models
(16, 17, 18). Teleologically, it seems likely that immune
recognition of CpG DNA has evolved as a defense against intracellular
pathogens, thus providing a rationale for the observed skewing of its
effects toward Th1 activation (19).
Since Th1-like immune activation and NK cells are thought to be desirable for cancer immunotherapy (20, 21), we tested a variety of CpG ODN to identify which type of CpG motif is optimal for activating these responses. There was little correlation between the ability of a CpG motif to induce cytokine secretion and its ability to induce NK activity. Moreover, although several CpG ODN were active as sole immunotherapeutic agents in two tumor models, different motifs were optimal in each model. CpG ODN 1585 was optimal against B16 melanoma and its effects were dependent on NK cells. CpG ODN 1826 was optimal in a lymphoma model and its effects appeared to require NK (early) and T cells (late). These results illustrate the potent therapeutic potential of various CpG motifs and suggest that distinct CpG motifs can be custom-tailored for each desired immune effect.
Virus-free 4- to 6-wk-old C57BL/6 (B6), SCID, and beige mice, as
well as IL-2, IL-4, IFN-
, IL-12, TAP, perforin, and
2-microglobulin knockouts (all on a C57BL/6
background) were purchased from The Jackson Laboratory (Bar Harbor,
ME); type I IFNR (IFN-IR) knockout mice (on a 129J background) were
generously supplied by Dr. T. Waldschmidt (Department of Pathology,
University of Iowa, Iowa City, IA). All mice were housed in the
specific pathogen-free facility at the University of Iowa Animal
Care Unit.
Oligodeoxynucleotides
Phosphorothioate-modified ODN and chimeric ODN were provided by
Coley Pharmaceutical Group (Wellesley, MA). Chimeric ODN have
phosphorothioate linkages between the first two bases on the 5' end and
the last five bases on the 3' end with the remaining, central, bases
connected by phosphodiester linkages; we have previously shown this
arrangement to be optimal (3, 22). The sequences used are
provided in Table I
. ODN were found to have undetectable endotoxin
levels using the limulus amebocyte lysis assay (BioWhittaker,
Walkersville, MD; lower detection limit, 0.1 endotoxin
units/ml). For in vitro assays, ODN were diluted in TE buffer
(10 mM Tris (pH 7.0) and 1 mM EDTA) and stored at -20°C. For in vivo
use, ODN were further diluted in PBS (0.1 M PBS, pH 7.3) and stored at
4°C. All dilutions were conducted using pyrogen-free reagents.
Spleens were removed from 6- to 12-wk-old female C57BL/6 mice
and cultured at 5 x 106/ml with the
indicated ODN for 4 h (TNF-
) or 24 h (IL-6, IFN-
,
IL-12), the supernatants were harvested, and cytokines were detected by
ELISA as previously described (14, 23). To
evaluate CpG-induced B cell proliferation, spleen cells were depleted
of T cells with anti-Thy-1.2 and complement treatment; viable cells
were obtained by centrifugation over Lympholyte M (CEDARLANE
Laboratories, Hornby, Ontario, Canada) and cultured with the indicated
ODN. At 44 h, the cultures were pulsed for 4 h with 1 µCi
of [3H]thymidine as described previously
(3).
Tumor models
The B16.F1 melanoma and EL4 T cell lymphoma cell lines, which are syngeneic to B6 mice, were maintained in vitro (24, 25). Tumor cells were harvested and injected, i.p. (B16.F1) or s.c. (EL4), into B6 mice at the doses indicated in the figure legends. Various ODN were administered at the indicated time points i.p. at doses of 100 µg/mouse, unless otherwise indicated. Mice were checked daily for tumor growth and for survival. There were 510 mice in each group, unless otherwise indicated. NK cell depletion was done as previously described (26).
Statistical analysis
Survival curves were estimated using the Kaplan-Meier method (27). Hypotheses were tested using the log rank test (28). All statistical tests were performed using the SAS system (SAS System for Windows, version 8.0; SAS Institute, Cary, NC).
Previous studies have demonstrated that ODN containing CpG motifs
trigger the activation of B cells, NK cells, and dendritic cells, favor
a Th1-like cytokine production, and function as very effective vaccine
adjuvants (3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 29, 30, 31). To date, these effects have
been thought to be a general property of CpG ODN, and there has been no
evidence for the existence of CpG motifs with fundamentally different
types of immune effects (32, 33, 34). To determine whether
there may be different subsets of CpG motifs with distinct profiles of
immune activity, we tested >300 ODN, with different types of CpG
motifs, for their ability to induce cytokine secretion (IL-6, IL-12,
IFN-
, and TNF-
), for their ability to stimulate B cell
proliferation, and for their ability to induce NK cell killing
activity. We found that many CpG ODN with a completely
phosphorothioate-modified backbone (S-ODN) were potent inducers of
cytokine secretion and B cell proliferation with significant effects at
nanomolar concentrations (representative ODN are depicted in Table I
). Chimeric CpG ODN (in which the flanks
were phosphorothioate-modified but the center was native
phosphodiester; SOS-ODN) were also effective at inducing cytokine
secretion and B cell proliferation albeit at higher concentrations. For
these ODN, there was little apparent correlation between the ability of
an ODN to induce cytokine secretion or B cell proliferation and its
ability to augment NK cell activity (Table I
). Of the ODN initially
tested, the optimal CpG ODN for activating NK cells had a chimeric
backbone with a single copy of the palindromic motif TCAACGTTGA in the
middle phosphodiester portion of the ODN and poly(G) sequences on both
the 5' and 3' phosphorothioate ends (Table I
).
CpG ODN increase survival of B6 mice with B16 melanoma
We have previously shown that CpG ODN, while not effective on
their own, synergized with mAb in inducing the regression of tumor in a
B cell lymphoma model (35). We wondered whether a CpG ODN
could be effective on its own in a murine melanoma tumor model. The B16
melanoma was chosen because it is known to be susceptible to
MHC-nonrestricted cytotoxicity (36, 37, 38, 39, 40, 41). The B16 cell line
grown in our laboratory is NK resistant but is susceptible to lysis by
lymphokine-activated killer cells (data not shown). Because of the B16
susceptibility to activated NK cells, we first tested the effect of the
NK-optimized CpG ODN 1585 in C57BL/6 (B6) mice, which are syngeneic to
the B16 melanoma. In our hands, 100% of the mice die from progressive
tumor when challenged with as few as 1000 tumor cells. B6 mice received
various amounts of the B16 tumor i.p. on day 0. The CpG or control ODN
was administered on days 0, 3, and 7 and weekly thereafter. As shown in
Fig. 1
, we found that the CpG ODN 1585
significantly prolonged (with a p < 0.001 for all of
Fig. 1
panels comparing 1585 vs PBS or non-CpG ODN) survival of mice
that received the very high challenge dose of 1.5 x
106 tumor cells (Fig. 1
A). When
smaller numbers of tumor cells were used, the mice survival improved
progressively with a resultant 80% long-term survival of the mice that
received 1 x 104 tumor cells and the CpG
ODN 1585 (Fig. 1
D). It is worth noting that the duration of
survival of mice receiving PBS only was almost identical regardless of
the tumor dose tested in Fig. 1
, demonstrating the high tumorigenic
potential of the B16 tumor. Using a 5 x 103
tumor challenge dose and pooling identical experiments, we found that,
using a pool of 25 mice with PBS challenge, the mean survival time was
25.16 ± 0.84 (mean ± SEM) days, the mean survival of the
control CpG group was 35.53 ± 2.12, and all 25 mice in the 1585
group were long-term survivors (i.e., 0% mortality). We next attempted
to determine the optimal dose and frequency of CpG ODN. B6 mice were
given 5 x 103 tumor cells on day 0 and then
were given only one injection, on day 0 as well, of various doses of
CpG ODN 1585 or control ODN (2118). As shown in Fig. 2
, 100 µg of 1585 was optimal and
resulted, in this experiment, in a 100% survival. Interestingly,
higher doses (300 µg) were less effective and resulted in a survival
rate similar to that of lower doses (30 µg).
CpG ODN have been shown to stimulate a variety of immune cell
types. For example, some CpG ODN are very potent mitogens for B cells
and can induce the activation of APC (3, 7, 8, 42, 43). It
has also been suggested that CpG ODN can activate T lymphocytes
(10, 11). The ability of CpG ODN to activate APC could
potentially promote the induction of CTL against the tumor. To
determine whether T or B cells were required for this protection,
C57BL/6 SCID mice were treated with CpG ODN 1585 and challenged with
the B16 melanoma using the same regimen as in Fig. 1
. Similar survival
rates were seen in CpG-treated SCID mice compared with wild-type mice
at each tumor dose (Fig. 3
). These data
demonstrate that neither T nor B cells are necessary for the observed
survival induced by CpG ODN in this model. Interestingly, not all CpG
ODN were equally effective. When the CpG ODN 1826 (optimal B and
dendritic cell-inducing motif; Table I
and data not shown) and the CpG
ODN 2006 (also optimal for B and dendritic cell activation) were
tested, using SCID (Fig. 4
) or B6 (data
not shown) mice, we found CpG 1585 to be optimal whereas CpG 1826 was
intermediate and CpG 2006 was similar to the non-CpG control ODN. Also
shown in Fig. 4
is that, when 5 x 103 tumor
cells were used, CpG ODN 1585 induced a 100% survival of the SCID
mice, similar to the immunocompetent B6 mice. In data not shown,
TAP-1 and
2-microglobulin knockout mice
were protected by CpG 1585 to a similar degree as normal B6 mice, again
suggesting that CD8 and NKT lymphocytes are not needed for the
protective effect.
The data shown above demonstrated that B and T cells are not
necessary for the observed therapeutic effect. It remained possible,
however, that T cells might play a role in tumor protection in
immunocompetent mice. We reasoned that if this were the case, we should
be able to demonstrate immunological memory; i.e., mice that survived
the tumor challenge should be able to reject a second tumor challenge
in an accelerated fashion. Therefore, mice that had been treated with
CpG ODN 1585 and failed to establish tumor (tumor free for >100 days
after the initial tumor challenge) were rechallenged later with 1
x 104 tumor cells each. The tumor challenge dose
was given 23 mo after the last dose of CpG ODN to allow for the
protective CpG ODN effect to "wear off." Age-matched control B6
mice were also given the same dose. As shown in Fig. 5
, mice previously "cured" by CpG ODN
had a slightly prolonged survival (with a mean survival time of 38.9
days compared with 26.0 days for the control mice) but there were no
long-term survivors and no "cures." Thus, CpG ODN-mediated
resistance to the B16 melanoma does not lead to the generation of
significant Ag-specific memory responses. Indeed, in data not shown,
adoptive transfer of splenocytes from cured mice failed to protect
naive mice against B16 tumor challenge.
The data presented so far strongly suggested that T cells and B
cells are not necessary for the observed therapeutic effect, the
implication being that NK cells are the cells of import. However, SCID
mice, in addition to having normal NK cells, have normal APC including
dendritic cells. We, therefore, examined whether NK cells were
necessary for the CpG ODN effect. SCID mice were given 100 µg of
anti-NK1.1 Ab, or control Ig, on days -4 and -1. On day 0, the
mice were give 2 x 104 B16 cells i.p.; some
mice also received CpG ODN 1585 as above. Anti-NK1.1 Ab was given i.p.
twice weekly until the end of the experiment (we have previously shown
that this regimen results in near total depletion of NK cells
(26)). As seen in Fig. 6
, the control mice whose NK cells were depleted died more rapidly than
the control mice that received the control Ig. Similarly, the mice that
received CpG ODN 1585 and anti-NK1.1 had 100% mortality in a time
frame identical to the control mice. The mice that received CpG ODN
1585 and control Ig had a 100% survival. These data demonstrate that
it is indeed the NK cells that are responsible for the observed
therapeutic effect in this model. To confirm these results further,
normal B6 mice were depleted of NK cells and the effect of CpG ODN was
examined. In data not shown, we found that NK cell depletion in the
wild-type mice also resulted in abolishing the CpG protective
effect.
It is clear from the above data that the effects of CpG in the B16
melanoma model are dependent on NK cells. It remained to be seen,
however, as to whether CpG acted by inducing cytokine secretion by NK
cells and/or dendritic cells or whether the protective effect was
actually mediated by the lytic capacity of NK cells. We first examined
the ability of CpG to induce NK cell killing activity in vivo in
various knockout mice. CpG was injected in the footpad and the draining
lymph nodes were obtained 2 days later and used as effectors against
YAC-1 tumor target cells (we have previously shown (13)
that this approach was optimal for the in vivo induction of NK cell
killing activity by CpG). As shown in Fig. 7
, CpG was able to induce NK cell
activity in normal B6 mice as well as in IL-2, IL-4, IFN-
, IL-12,
and
2-microglobulin knockout mice.
Interestingly, mice whose receptor for type I IFN has been inactivated
(IFNI-R) did not augment their NK cell activity. These data suggested
that the induction of type I IFNs may be the pivotal step in the
protection conferred by CpG. It has been known for some time that type
I IFN can augment the lytic potential of NK cells without necessarily
inducing their proliferation (44). We sought to determine
whether NK lytic activity is necessary for rejection of the B16
melanoma. We tested beige mice whose fresh NK killing activity is
barely detectable but this activity can be readily augmented with the
proper stimulation (45, 46). As shown in Fig. 8
A, CpG induced significant
protection in beige mice with 80% long-term survival
(p < 0.0001). Perforin knockout mice (whose NK
cells cannot kill except through the relatively less efficient Fas
pathway; 47), on the other hand, had only 20% long-term
survivors. These findings strongly suggest that it is the ability of
CpG ODN to augment the killing activity of NK cells, perhaps by the
induction of type I IFN, that is responsible for the rejection of B16
melanoma in this model.
The toughest challenge for any type of tumor therapy is to cure
established tumors, rather than simply preventing the generation of a
new tumor. To test whether CpG ODN treatment could accomplish this,
mice were challenged with 1 x 104 B16
melanoma cells on day 0; 100 µg of CpG ODN 1585 or control ODN 2118
was given starting 3 days afterward. The ODN were also given on days 7,
10, and 14 and weekly thereafter for 2 mo. As shown in Fig. 9
, treatment with the CpG ODN 1585 led to
a 60% survival rate, while the mice given a control ODN or PBS all
died between days 20 and 41 (1585 vs PBS had a p <
0.01, 2118 vs PBS had a p of 0.8 and 2118 vs 1585 had a
p of 0.006). The surviving mice lived with no evidence of
recurrent tumor for >100 days, when the experiment was terminated.
To assess whether the above results can be generalized to other
tumors, we examined the effect of CpG ODN in a lymphoma model using the
EL4 tumor cells, which are also syngeneic to B6 mice. Similar to B16,
EL4 cells are resistant to killing by fresh NK cells but are
susceptible to killing by activated NK cells. B6 mice were inoculated
s.c. with 107 EL4 cells on day 0 and treatment
with 100 µg of several different CpG ODN given i.p. weekly beginning
on day 2 (i.e., days 2, 9, 16, etc.). All mice developed tumor by day
12. However, tumor growth was slower in those mice treated with CpG ODN
1826 (data not shown) and overall survival was significantly prolonged
(Fig. 10
A). In repeat
studies, between 30 and 50% of mice treated with CpG ODN in this
manner rejected the tumor and remained tumor free thereafter (Fig. 10
B). A number of interesting differences were found when
comparing results from the B16 model to those from the EL4 model. The
CpG ODN 1585, which was more effective than the CpG ODN 1826 in the B16
model, was not effective in the EL4 model. Unlike the B16 tumor, it
appeared that the EL4-challenge surviving mice were able to develop
memory since they failed to develop tumor upon rechallenge (arrow in
Fig. 10
B), suggesting a memory response.
To assess the relative contribution of NK and T cells for the
rejection of EL4 induced by the CpG ODN 1826, SCID mice were examined.
In contrast to the B16 model, no antitumor activity against EL4 was
seen (Fig. 11
), suggesting that T cells
are necessary and that NK cells, if needed, are not sufficient for the
therapeutic effect. Surprisingly, however, NK cell depletion, using
anti-NK1.1 as above, in normal B6 mice abrogated the protective
effect of CpG (Fig. 11
). Thus, in contrast to the B16 model, both NK
and T cells are required for the antitumor effect in the EL4 model.
Previous studies performed using phosphodiester or phosphorothioate
backbone ODN suggested that a single type of optimal CpG motif mediates
these protean effects (3, 32, 33, 34). Our present results
show that the effects of CpG DNA are actually more complicated. There
are at least two classes of CpG ODN, with distinct profiles of immune
activity depending on the ODN backbone and on the presence of another
kind of DNA sequence motif, the G quartet or poly(G) sequence. The
nuclease-resistant phosphorothioate backbone greatly improves the
stability of an optimal CpG ODN and its ability to activate B cells and
dendritic cells, and its ability to induce cytokine production
(3, 8, 22, 62) (Table I
). On the other hand, the
phosphorothioate backbone reduces the ability to activate NK cells and
thus may be less useful for tumor immunotherapy applications that
depend on these effector cells (Table I
) (13). Since the
beneficial stabilizing effects of the phosphorothioate backbone can be
obtained by modification of just the 5' and 3' ends of the ODN
(22), we have tested this type of chimeric ODN backbone.
Poly(G) sequences consist of four or more consecutive guanines in a
row, or two or more regions of three consecutive guanines, and are
known to bind to the macrophage scavenger receptor and to improve ODN
uptake and IFN-
production (63), but to interfere with
cell proliferation (64, 65).
The experiments reported in this manuscript indicate that the
combination of a CpG motif with a chimeric backbone along with poly(G)
sequences on the 5' and 3' flanks yields an ODN which has relatively
little B cell-, TNF-
-, or IL-12-stimulating effects, but which is
extremely active at inducing NK cell lytic activity (Table I
). NK cells
have long been thought to be important in tumor surveillance. By virtue
of their ability to secrete IFN-
, among other cytokines, NK cells
are also thought to influence adaptive immunity (66, 67).
Melanoma is a tumor model that has lent itself to the examination of
various models of immunotherapy. For human melanoma, several
tumor-specific Ags have been described and are known to induce T cell
responses (68, 69). On the other hand, the B16 murine
melanoma is thought to be amenable to treatment both by activated T or
NK cells (37, 39).
Since we have shown that CpG ODN activate NK cells both in vivo and in
vitro (13), we examined their effect on the survival of
mice with melanoma. The data presented in this report clearly
demonstrate that, by virtue of their ability to activate NK cells, some
CpG ODN are quite effective, as the sole therapeutic agent, at
preventing the development of B16 melanoma and, more interestingly, at
rejecting an established B16 tumor. As little as one dose of CpG ODN
1585 is as protective against tumor challenge as repeated doses (Fig. 2
). Moreover, there appeared to be nonlinear dose response since a
300-µg dose of CpG was less effective than doses of 100 or 30 µg.
This is similar to our previous findings with CpG in a
Listeria model and probably relates to the observation that
high doses of CpG prime mice for the sepsis syndrome
(70, 71, 72).
Interestingly, it appears that the protection afforded by CpG ODN against the B16 melanoma is mediated by innate rather than adaptive immunity since SCID mice rejected the tumor just as efficiently as normal mice. Moreover, no "memory" appears to have developed in the cured immunocompetent mice. In data not shown, we were not able to transfer protection by adoptive immune transfer using spleen cells from the cured immunocompetent mice. All of these results point to innate immunity as being the system of import in this model.
The two major cellular components of innate immunity are NK cells and
dendritic cells. In theory, dendritic cells could be the cells of
import in this model. However, our data with the in vivo depletion of
NK cells, clearly demonstrate that NK cells are the essential cells.
These results do not exclude the possibility that DC may help to
activate NK cells as shown in other antitumor models where NK cells can
slow tumor growth, but do not cause tumor regression (73).
Interestingly, it has been suggested that it is the NKT, rather than
the classical NK cells, that are the cells of import in rejecting the
B16 melanoma in an IL-12-induced tumor rejection model (37, 41). Our data suggest that NKT (equivalent data obtained in
TAP-1 and
2-microglobulin knockout mice; data
not shown) cells are not necessary for the therapeutic effect of CpG
ODN in this model.
It appears that IL-12 is also not necessary for the therapeutic effect
in this model. Using SCID mice, we found IL-12 (which is dependent on
NKT cells for its therapeutic effect (37, 41)) to be less
efficient than CpG ODN at rejecting the B16 tumor and we had no
long-term survivors (data not shown). Moreover, the ability of a CpG
ODN to induce IL-12 did not correlate with its ability to stimulate NK
cell activity or to improve long-term survival. These data suggest that
the antitumor effect of CpG ODN in this model is not mediated through
the IL-12 pathway and that the IL-12 pathway is not essential for the
CpG ODN beneficial effect. Indeed, IL-12 knockout mice gave a response
similar to the normal B6 mice (data not shown), suggesting that IL-12
is not necessary for the protective effect. Surprisingly, the induction
of IFN-
secretion also did not correlate with CpG-induced
protection, suggesting that the therapeutic effects in this model may
be mediated through distinct NK activation pathways. Our studies with
the various knockout mice indicate that type I IFN may be the cytokine
of import since IFNI-R knockout mice were the only cytokine/cytokine
receptor knockout mice that failed to augment their NK cell activity in
response to CpG either in vivo (Fig. 7
) or in vitro (data not shown).
Moreover, it appears that it is the lytic potential of NK cells (rather
than their ability to secrete various cytokines) which is protective in
this model, since perforin knockout mice yielded significantly less
long-term survivors (20 vs 80%). NK cells can kill through the
perforin pathway or through the Fas/Fas ligand pathway with the
perforin pathway being dominant in cytokine-activated NK cells
(47). It is possible that the 20% survival seen in the
perforin knockout mice is due to killing through the Fas pathway,
although we were unable to demonstrate significant staining of B16 with
anti-CD95 Ab nor were we able to demonstrate augmentation of CD95
on B16 melanoma cultured with CpG in vitro (data not shown). Moreover,
we examined the effect of CpG on the expression of other surface
markers on B16 cells after culture with CpG ODN for 13 days; we found
no change in the expression of class I or class II MHC, CD40, CD40
ligand, CD28, CD80, or CD86 (data not shown).
The results in the B16 model are in marked contrast to results in the
EL4 T cell lymphoma model. Whereas CpG ODN 1585 was optimal in the B16
melanoma model, CpG ODN 1826 was more effective in the EL4 model.
Although CpG 1826 is optimal for B cell induction, it does induce some
NK cell activity (Table I
) and, perhaps by virtue of cytokine
induction, it appears to induce some T cell activity (data not shown).
Therefore, it was not too surprising to find that 1826 requires NK
cells for its anti-EL4 activity although NK cells were not, by
themselves, sufficient for the therapeutic effect. Although we have not
directly demonstrated that T cells are needed for this effect, one can
infer that T cells play a major role in the EL4 model since no
therapeutic effect was seen in SCID mice (which have NK and dendritic
cells but lack T or B cells). Furthermore, we found that cured mice
reject a subsequent tumor challenge, suggesting a memory response. The
effectors of this memory response remain to be established. Ones
initial suspicion would be a T cell response. However, it is possible
that Abs might play a role in this response as well. Since the CpG
motifs that work best in EL4 are also those that are optimal for B cell
stimulation, it is possible that these ODN induce a significant
anti-EL4 Ab. Depending on the Ab induced, one can envision at least
two mechanisms. Complement-fixing Abs could kill the tumor via that
pathway; noncomplement-fixing Abs could kill EL4 by Ab-dependent
cellular cytotoxicity. Ongoing studies are exploring these
possibilities more extensively. It is likely that the mechanism through
which NK cells contribute to the antitumor response in the EL4 model is
different from that in the melanoma model, where it is clear that the
lytic activity of NK cells is pivotal. It is likely that the role of NK
cells in the EL4 model does not rely on their lytic potential but
relies on their ability to secrete certain cytokines (such as IFN-
,
for example) which may facilitate the activation of T cells that lead
to rejection of EL4. These possibilities are currently under
investigation.
Interestingly, the results in these two models also differ from our previous findings in a murine B cell lymphoma model (35). In the B cell lymphoma model, CpG ODN alone were not effective at inhibiting tumor growth, although some CpG ODN were synergistic with antitumor mAb and gave an impressive survival rate of 80%. The 38C13 lymphoma used in that model is not susceptible to NK or activated NK cell lysis. Interestingly, Carpentier et al. (74) reported that a phosphorothioate CpG ODN was effective in slowing the growth of a murine neuroblastoma model and that this effect seemed to be dependent on NK cells.
For more than a century, it has been clear that bacterial extracts such as Coleys toxins contain potent compounds with the potential to induce regression of established tumors in humans (1, 2). Although it remains to be established whether the CpG motifs in bacterial DNA are the "missing link" to Coleys toxins, the data presented in this report clearly demonstrate that CpG ODN can be effective as antitumor agents. Importantly, our findings suggest that different immunotherapeutic strategies will be required for different tumors and that one may need to design different CpG ODN for inducing different types of desired responses. A more complete understanding of the antitumor immune responses needed for cancer therapy, and further dissection of the immunologic response to CpG ODN, should allow for the development of more rational and effective therapeutic strategies based on these promising new classes of potent immunologic agents.
2 Address correspondence and reprint requests to Dr. Zuhair K. Ballas, Department of Internal Medicine, C42-E13, GH, University of Iowa, Iowa City, IA 52242. E-mail address: ballasz{at}uiowa.edu
3 Abbreviation used in this paper: ODN, oligodeoxynucelotide.
Received for publication June 4, 2001. Accepted for publication August 23, 2001.
This article has been cited by other articles: | http://www.jimmunol.org/cgi/content/full/167/9/4878 | crawl-002 | refinedweb | 5,135 | 58.52 |
The following code fails to create a valid icon recognized by Windows Explorer or VS2005; though, it can be opened in Paint.
using (Bitmap bmp = new Bitmap(@"C:\ABitmap.bmp"))
{
bmp.Save(@"C:\IconFromBitmap.ico", ImageFormat.Icon);
}
After googling, a post in MSDN forum was found with similar problem
The code seems rather straight-forward but it does not appear to do the job.
Does anyone have a solution?
The following code fails to create a valid icon recognized by Windows Explorer or VS2005; though, it can be opened in Paint.
It's a known bug. The .NET GDI doesn't even have an icon encoder so it saves it as a png file. I was trying to find a solution for that for a long time and the only thing I've found is that you can use a free image conversion library called FreeImage ( ) which can save images to many different icons. It's free and released under the GNU license if I'm not mistaken, but there's one limit - it can save icons only in this size range: 16x16 - 128x128 . So keep in mind that smaller or bigger images won't be saved.
If you find a better solution please share it with us. I'd really like to know how to solve it without using an external source.
Since *.ico files are simply binary files containing an embedded resource list containing bitmap icons.
So couldn't you create an *.ico file using .NET's resource manipulation namespaces?
What are the .NET's resource manipulation namespaces?
- yyy wrote:What are the .NET's resource manipulation namespaces?
System.Resources
Thanks but I don't think I know how to use it in order to create the icon. An icon file's layout is quite complicated, as explained in this article: . I think that if you need to convert a bitmap to an icon you'll first have to get a lot of information from that bitmap and that's the hard part. But maybe there's something I don't know about.
If you are willing to put one per file, you can just save it as a bitmap with the ICO extension.
Just make sure it is 16x16, 32x32, or 64x64 if you want to work in most places.
Jorgie
J..
the .NET framework's class libraries have only been extended in .NET 3.0 and 3.5, all the core assemblies remain the same. So no.googlexp said:yyy said:*snip*
i tried the freeimage lib, the sample for .NET didn't even compile.
Re: Jorgie: that wouldn't work because an ICO is application/x-icon, Explorer is just more tolerant and loads up the Win32 bitmap reader despite the file extension, a proper icon reader would choke on it.
System.IO.Stream outputStream;
Icon tIco;
Bitmap tBmp = new Bitmap(pictureBox1.Image);
outputStream = System.IO.File.Create(@textBox2.Text);
tIco = Icon.FromHandle(tBmp.GetHicon());
tIco.Save(outputStream);
outputStream.Close();
----
The only problem I have with the code it the apparent loss of colors. Though the end result does show up in properties as 32bit.
This will allow you to use the icon as an icon on your forms.
-Chazm
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know. | https://channel9.msdn.com/Forums/TechOff/130238-C-20-convert-Bitmap-to-Icon-problem | CC-MAIN-2016-07 | refinedweb | 570 | 75 |
There is a ton of different tensorflow posts on the web already, and many of them are actually good. This is not that. This is me, writing a crappy little classifier for what's essentially an elaborate shitpost.
In this post, I will walk you through how I built DRIL OR NO DRIL.
Overview
If you don't know who or what dril is, have a look. If you already do, great. If you're just coming back - isn't that one of the weirdest twitter accounts you've seen in a while? Anyway - the style is quite distinctive, so I thought I might have a stab at creating a classifier that tries to pick up on what makes dril dril.
To do that, I first need tweets. Lots of tweets, both from dril and other accounts. I ended up using myself, a few of my friends who agreed to be included in the model, and the Prime Minister (at the time of writing this paragraph, lol) Theresa May.
I also need a model. I ended up using a modified version of the IMDB review classifier from tensorfow docs.
Finally, to put it online without having to pay for anything, I needed a way to ship my model to the browser with glitch. This also has a bonus of keeping all the text you enter in that box on your machine. I achieved that through tensorflow.js, a browser-based subset of tensorflow which runs on WebGL producing loads of warnings because, really, WebGL wasn't designed to be used this way.
Getting some tweets
The first thing to do is get some tweets. This requires a Twitter API account so you can authenticate. It's that or doing some screen-scraping hacks but for convenience I stuck with the API - perhaps to my detriment. I wrote a Python script to download all these tweets which was pretty easy thanks to tweepy. It downloads tweets and saves them into a sqlite3 database. It even supports resuming from the earliest downloaded tweet (important in case it crashes). Tweepy's cursor API is also really neat - you can iterate over tweets and it'll handle pagination for you:
cursor = tweepy.Cursor(api.user_timeline, id=args.account, max_id=max_id, include_rts=False) for status in cursor.items(): tweet = status_to_tuple(status) save_tweet(db, tweet)
It's also great that you can tell tweepy to automatically wait in case of a rate-limit response - though I don't think I ran into that issue yet:
def get_twitter_api(): auth = tweepy.OAuthHandler(secrets.TW_API_KEY, secrets.TW_API_SECRET) auth.set_access_token(secrets.TW_TOKEN, secrets.TW_SECRET) return tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
I then ran the script on some Twitter timelines. I used dril, obviously, as well as some examples of non-dril content. Then I looked at the amount of tweets I downloaded and saw a discrepancy:
Turns out that as per Twitter API docs, the endpoint used only returns up to 3200 most recent tweets. So I guess if you really needed that archival content, you'd have to implement those screen-scraping hacks after all. I chose to not bother.
Installing TensorFlow
Because this is the real hard problem in computer science (citation needed), I'm now going to spend 5 paragraphs talking about how to install TensorFlow.
j/k, get anaconda and go here: - works even on exotic platforms such as Windows.
The classifier
To create the classifier you will first need to load the data into a format that tensorflow accepts, and there is only one such format - numpy arrays. This is also the first step you will need to make a decision as to how you want to represent the text you put in because you can't simply throw strings at a neural network.
There are a number of ways you could represent a piece of text in a compact way, for instance by using the bag-of-words approach which only preserves word frequencies, or by encoding each word as a number as is the case of the TF/Keras IMDB example dataset. You can also try to do fancy things like discarding the most popular words like "a", "the", and "hyperloop is a good idea". In my example I'm not doing any of that and instead I take the raw bytes of each character and shove them into a 240-element numpy array, padding out the remaining space with zeros. The idea is that any other preprocessing could remove nuance about the style of these tweets. Also I'm lazy.
def to_padded_bytes(tweet): bts = np.array([ord(c) for c in tweet]) return np.pad(bts, (0, 240 - bts.shape[0]), mode='constant')
This still meant that I needed to have an embedding layer in my network that extracted features from the byte values, but it was a little bit different than in the example.
Finally, the labels are represented as 2-dimensional vectors. A dril tweet is labelled as
[1, 0], whereas a non-dril tweet is
[0, 1]. This is so that at the end of the process I can get the confidence value from the network - it will usually reply with a vector like
[0.98, 0.02] which means "I am 90% confident that this is a dril tweet and only 2% confident that it's not". Or the inverse. Or somewhere in between.
The model itself is as follows:
model = keras.Sequential([ keras.layers.Embedding(255, 16, input_length=240), keras.layers.Conv1D(140, 3, padding='valid', activation='relu', strides=1), keras.layers.GlobalAveragePooling1D(), keras.layers.Dense(512, activation='relu'), keras.layers.Dense(2, activation='softmax') ])
I threw in the convolutional stage because I'm hoping it's able to pick up on the stylistic differences between types of tweeter, but so far it's mostly learned that shorter tweets are more likely to be dril, and that he doesn't use emoji very often. Nonetheless, at ~89% validation accuracy, I decided that it's good enough for a joke.
If I were doing this properly I might look at existing text classification architectures and try to actually learn something from them. Then maybe I'd achieve that 99% accuracy.
Onwards to JavaScript
tensorflow.js is a little limited. From the docs:.
That's fine though, as my model is only using standard constructs. The first step is to save it to a h5 file, then you can run the tensorflowjs converter on it. To get the converter, you can run
pip install tensorflowjs in your conda environment. Note, though, that some of the installed packages might get downgraded as the dependencies are a little out of sync - this shouldn't be too worrying as they are all within requirements of each other. The converter will generate a directory with two or more files: a
model.json file which describes the structure of the model, and some
groupK-shardNofM files which contain the learned attributes of your model (the weights, in the ML lingo). You can then serve these files from a web server and load them on the client side like so:
// This assumes that model.json is in the same directory as the current document const model = await tf.loadModel('model.json');
If you don't know what the
await does, read this:. If you do and are positive you can't use it, it's still a promise so you can work with that instead. If you need to support Internet Explorer, ask your doctor if tensorflow.js is right for you. In my case I decided that being compatible with popular browsers is for losers and just use async/await as they are.
The glitch project itself is also very simple - the main issue is getting the text from a
<textarea> into the same format as I used in training, namely a 1x240 tensor. The code is pretty similar to the python version:
function tweetToTensor(tweet) { const array = new Uint8Array(240); for (let i = 0; i < tweet.length && i < array.length; i++) { array[i] = tweet.charCodeAt(i); } return tf.tensor1d(array); } // later... const batch = tweetToTensor(text).reshape([1, 240]); const prediction = model.predict(batch); const result = prediction.reshape([2]);
It's nice that I don't have to explicitly pad out my arrays here because allocating a
Uint8Array automatically gives me a zero'd-out array so I only need to copy in the relevant byte values.
There is one issue with hosting everything on glitch though - since the
group-shard-piece-whatever files are binary, glitch uploads them to a cdn and gives you a long link to the file in its bucket. This is fine for images, but tensorflow.js expects that it'll be able to get the weights files from the same base URL as the model.json file (eg. if the model file is at, it'll look for files like etc). However, since the library uses
fetch(), it also follows redirects, and it's easy to set up your server script to catch requests for the weights files and point it to the right place.
Well, easy if you've got one or two files; if you need more than that, again ask your doctor if tensorflow.js and glitch are right for you.
Where's the code?
The classifier etc: - the same repo also contains the tweet download scripts, but you'll need to provide your own
secrets.py file.
The glitch site:
Learnings
From what's essentially an elaborate joke, I learned a thing or two about conducting machine learning experiments on data that wasn't delivered to you in a neatly wrapped package with instructions. It's a harsh world out there and most data will be messy and in the wrong format. About 2/3 (or more, haven't checked) of the code I wrote deals with acquiring the data and preparing it for the model. If I was to do this again properly, I might also look into ways of getting past that Twitter API tweet limit, and gathered up much more non-dril material. As it stands, the classifier is biased towards saying the input is dril-like. I would definitely look at different text processing models, both in terms of how the neural network is actually designed, and how to encode the data going into it. The vector-of-bytes idea is not terribly efficient and would not scale well to longer documents. I might even be tempted to try and serve this model from an actual server instead of dumping it into the user's browser in hopes that it'll work (those weights files can get awfully large sometimes...). I hear that Google has an offering for production machine learning apps. Or something.
Discussion
I'd like to hear from you if you have an idea of what you'd do for an application like that, especially if what you'd do is different and actually works. I'd also like to know what's the silliest machine learning thing you've made, and whether you went through the trouble of putting it online.
Right, until next time!
Discussion (0) | https://dev.to/minkovsky/dril-or-no-dril-building-a-text-classifier-in-tensorflow-208k | CC-MAIN-2022-05 | refinedweb | 1,863 | 63.59 |
I have a dictionary like so:
d = {}
d['key1'] = [('tuple1a', 'tuple1b', ['af1', 'af2', 'af3']),
('tuple2a', 'tuple2b', ['af4', 'af5', 'af6']),
('tuple3a', 'tuple3b', ['af7', 'af8', 'af9'])]
['af1','af2','af3']
def update_dict(dictionary, key, tuple_a, tuple_b, new_list=None):
for k,v in dictionary.items():
if key in k:
for i in v:
if tuple_a in i:
if tuple_b in i:
#di.update(i[2], new_lst) #this is what I'd like to do but can't get the right syntax
return dictionary
di.update(i[2], new_lst)
Since tuple is an immutable type, you cannot change a single entry in the tuple. A workaround is to create a list with the elements you would like to have in the tuple, and then create a tuple from the list. You will also have to assign the new tuple to the given element in the parent-list, like this:
for k,v in dictionary.items(): if key in k: for n,tpl in enumerate(v): if tuple_a in tpl and tuple_b in tpl: v[n] = tuple( list(tpl)[:-1] + [new_list] )
(I was a little confused by your example, in which the variables called tuple_a and tuple_b were actually strings. It might have been better to call them name_a and name_b or similar.) | https://codedump.io/share/AWXRXqPY8sr0/1/replace-a-value-in-a-dictionary-of-liststuples-python | CC-MAIN-2017-43 | refinedweb | 207 | 65.05 |
Renaming Serialized Fields
One of the problems we faced was how could we rename fields without having our users lose data. During our beta period, we wanted to refactor our code without breaking our beta users projects, so they could continue testing each new version without having to worry about data loss and project breakage. To solve that we introduced the [FormerlySerializedAs] attribute.
What can you do with it? Let’s look at some use cases for it!
Variable renaming
Let’s say you have the following class:
But you would like to rename m_MyVariable to something else like m_ABetterName, but you don’t want your users to have to re-populate the data for this MonoBehaviour in all of their scenes and/or prefabs. You can now accomplish that like this:
Encapsulating public API
In this case, you have a public field that is part of your API, but would like to encapsulate it in an accessor. So let’s assume we have a class MyClass like this:
To encapsulate this value in an accessor without losing any existing data in your assets you can do something like this:
Multiple Renames
Renaming fields multiple times is supported, just add the attribute multiple times, one for each name of the previous names of the field:
When can I remove the attribute?
You can remove the attributes after you have re-saved all of your scenes and assets, after the rename. Of course this implies you have ‘control’ of your users. For some, like the Asset Store publishers for instance, this ‘control’ is impossible. So in this case you will have to keep it as long as you want to make sure people with any version of your code can upgrade to your new code without losing data.
Hope you find this new little feature helpful!
Entradas relacionadas
30 ComentariosSubscribirse a los comentarios
Ya no se aceptan más comentarios.
Steffano (Stiffix)marzo 19, 2015 a las 11:33 pm
I can’t say enough how many times I needed it. Thank you
focusmarzo 6, 2015 a las 6:09 pm
Thanks, this is awesome addition! Every Asset Store developer should keep it in mind.
Mike Mandelfebrero 13, 2015 a las 7:25 am
This new renaming attribute is sounding like a great direction! One related thing that often happens is wanting to change the units of a particular serialized property – like a float representing milliseconds suddenly wanting to represent seconds at an artists request. It would be awesome if these rename attributes (or maybe a new attribute) let you supply an optional «upgrade» function that can actually convert the old data to the new data, so you could supply conversions in code where necessary. Is this something other people have wanted?
Marllon Brandofebrero 5, 2015 a las 9:38 pm
Excellent new feature. Ohh, how can I do not keep loving the Unity? :D
thienhaflashfebrero 5, 2015 a las 5:30 am
Cool !
thienhaflashfebrero 5, 2015 a las 5:29 am
Very useful small feature indeed !
Kaleb Gracefebrero 4, 2015 a las 7:20 pm
[FormerlySerializedAs(«Prince»)]
[SerializeField]
private string TheArtist;
Seriously useful feature!
Rayfebrero 4, 2015 a las 7:22 pm
Upvote!
Shawnfebrero 4, 2015 a las 5:29 pm
Awesome feature guys! Especially the fact this work on Serializable classes!
Any chance we’re eventually going to get full ‘dynamic’ keyword support for classes? Then we can safely remove fields from our SaveFiles with worrying about them blowing up on Deserialize.
Jashan Chitteshfebrero 4, 2015 a las 10:46 am
These «small changes» or «small additions» are really what I like most about Unity. Not being able to do that kind of refactoring was a rather significant limitation and I think adding this new attribute fixes that limitation quite nicely. Right on!
Imifebrero 3, 2015 a las 10:27 pm
Simple renaming is nice and fun but basically it is far not enough in bigger projects that spans over longer development time. We need re-typing, changing of default values, changing of whole data structures, mergability, human readability, external-tool-readability, easier to parse in random access order etc.
(Of course, some of these points are conflicting. We want different aspects in different types of assets)
We start to abandon unity save format here, for its lack of extendability in any of these points and switch to our own format :(. Unfortunately, that’s also a pain in the neck, as Unity does not provide any kind of helping hands in this direction either..
Here is my 2c idea that I posted in a somewhat related issue report (665302):
—-
I would recommend to have a post-save in the editor. This step gets the save data as structured input (like key/value pairs. The SerializedObject data format seems perfect – if its not bound to concrete object Types?) and can start to optimize the structure of the data for several things like «mergability».
Mirrored to that, there is a pre-load step that first «restores» the data before it is passed to the current deserialization data mapping.
This approach makes it far more easier to optimize the save file format for various different things independend of the internal data representation. There are many conflicting goals that an export format should look like. Speed, size, human readability, mergability, random-access-reading, easiness to analyse with other tools…
(What would be even better: Add some hooks to give editor plugins the chance to alter the save format. That would make it possible to upgrade scene files and prefabs during the lifetime of a project so much easier)
Galen Rfebrero 4, 2015 a las 12:54 am
I think you could implement this yourself if you use OnAfterDeserialize and OnBeforeDeserialize. You would need to keep your old serialized fields around until all the data was converted but I think you could do it.
Either that or live dangerously by forcing all your assets to text serialization and then process the text assets to your new format.
Imifebrero 26, 2015 a las 1:12 am
Yes. This is what we are doing. We encode everything into a single list of strings, which gets encoded into separate lines by YAML most of the time. The only other thing we need is a «list of objects» to hold references so Unity’s reference-system still works. Its a pain, e.g. since you cannot access even the name of any asset during OnAfterDeserialize, but relying on Unity mergability is even more pain, so…
Inokfebrero 3, 2015 a las 9:21 pm
Can we expect in the future better solution for rename the fields without losing data? (automatically without user intervention). Another solution not use connections between fields and assets via inspector, instead use Resourses.Load, but this uncomfortably if you rename folders or assets in project often.
Leonardo Carneirofebrero 4, 2015 a las 2:19 pm
I don’t really understand what you mean. Can you explain a bit more in detail what you would like to see?
Michaelfebrero 3, 2015 a las 6:39 pm
I think a «variable name» attribute could work too. So if I had a variable and I wanted to have a specific «weird» name on the inspector but not the one from the variable…
e.g.
public int myVar; (and the name I wanted would be «1. My Var»)
I would go like…
[VariableName(«1. My Var»)]
public int myVar;
or even on a private variable
[VariableName(«1. My Var»)]
[SerializeField]
private int myVar;
So changing the name wouldn’t lose its value reference on the inspector. It would change just the «label».
Of course the attribute (FormerlySerializedAs) you have created works too!
Dylan Bennettfebrero 3, 2015 a las 5:55 pm
I’m speaking out of some ignorance here, so apologies if this is a silly suggestion. It seems like this would be better if it somehow threw a warning on compile when developers are using a «formally serialized field». This is similar to when a method is deprecated, is it not?
Leonardo Carneirofebrero 3, 2015 a las 6:07 pm
Not really, this attribute enables developers to change field names in their code, without losing data, giving our users more flexibility to refactor their code.
Issam Khalilfebrero 3, 2015 a las 5:23 pm
This is great. As a suggestion, I would say that next time it might also be worth offering a way for user to write code to modify the behavior that is affecting them. In this case maybe being able to write callback script code during the serializing/deserializing would be more useful for people, especially since it would allow people to write Asset Store utilities to solve other problems you might not have noticed.
Leonardo Carneirofebrero 3, 2015 a las 6:01 pm
I think we have something very similar already. I’m not sure if it’s exactly what you want but you can get really far with: ISerializationCallbackReceiver.OnBeforeSerialize.html
I would also recommend reading this blog post
Issam Khalilfebrero 3, 2015 a las 8:34 pm
Thanks for the links!
Sampsa Lehtonenfebrero 3, 2015 a las 4:52 pm
Also, which Unity version is this going to be in? I hope in 4.6…
Richard Finefebrero 4, 2015 a las 9:52 am
It’s already in there :)
Sampsa Lehtonenfebrero 3, 2015 a las 4:51 pm
This is a really welcome feature. Nice job!
In the past I’ve done something like use OnValidate to check if data has been migrated to new version, but that required keeping tabs of things – and duplicate variables. Quite awkward.
BTW, how far can we stretch this? Would this work:
Before:
[System.Serializable] public class ItemA { public int value; }
public ItemA a;
After:
[System.Serializable] public class ItemB { public int value; }
[FormerlySerializedAs(«a»)]
public ItemB b;
that is, change the type as well where the new type is compatible with the old one. Because changing the type already works as long as the type is compatible.
Leonardo Carneirofebrero 3, 2015 a las 5:58 pm
Yes, that would work just fine :)
I guess the post is not clear on this but yeah, this is in 4.6 already!
Lior Talfebrero 3, 2015 a las 4:24 pm
Nice.
Just went back to my own blog post on Unity attribute () this seems to have been there already when I wrote it (in 4.6 RC2).
Although the name is pretty bad to my taste :)
Dmitriy Pyalovfebrero 3, 2015 a las 4:16 pm
Will something similar be done for MonoBehaviours inside assemblies?
Right now the fileID of MonoBehaviour inside assemblies is based somewhat on MD4 of the class name, so it is not possible to refactor them.
An attribute to set fileID explicitly would be very helpful.
Emil "AngryAnt" Johansenfebrero 3, 2015 a las 4:56 pm
Generally, I’d say that serialising based on assembly classes doesn’t inspire a lot of confidence.
To the point where I would indeed not mind having to be completely explicit about it. Unfortunately that has not been an option so far.
Joachim Antefebrero 3, 2015 a las 7:08 pm
I agree that the ability to specify the a deprecated ID of a class in a dll or old name would be very useful.
Walt Dfebrero 3, 2015 a las 10:27 pm
Agreed that this would be really useful. Not being able to rename classes inside custom-built DLLs (without losing script references in my scenes & prefabs) is currently the only big reason why I don’t use DLLs. | https://blogs.unity3d.com/es/2015/02/03/renaming-serialized-fields/ | CC-MAIN-2019-35 | refinedweb | 1,932 | 60.95 |
The libLDAP.rts library and supporting library files (written by Mark Boddington) allow you to interrogate and modify LDAP traffic from a TrafficScript rule, and to respond directly to an LDAP request when desired.
You can use the library to meet a range of use cases, as described in the document Managing LDAP traffic with libLDAP.rts.
Note: This library allows you to inspect and modify LDAP traffic as it is balanced by Stingray. If you want to issue LDAP requests from Stingray, check out the auth.query() TrafficScript function for this purpose, or the equivalent Authenticating users with Active Directory and Stingray Java Extensions Java Extension.
A long, long time ago on a Traffic Manager far, far away, I (Mark Boddington) wrote some libraries for processing LDAP traffic in TrafficScript:
That library (version 1.0) mostly focused on inspecting LDAP requests. It was not particularly well suited to processing LDAP responses. Now, thanks to a Stingray PoC being run in partnership with the guys over at Clever Consulting, I've had cause to revist this library and improve upon the original. I'm pleased to announce libLDAP.rts version 1.1 has arrived.
Now that the decoding is lazier it means you can almost entirely bypass decoding for packets which you have no interest in. So if you only want to check BindRequests and/or BindResponses then those are the only packets you need to fully decode. The rest are sent through un-inspected (well except for the envelope).
We now have several functions to allow you to process responses which are made up of multiple LDAP messages, such as those for Search Requests. You can use a loop with the "getNextPacket($packet["lastByte"])" function to process each LDAP message as it is returned from the LDAP server. The LDAP packet hash now has a "lastByte" entry to help you keep track of the messages in the stream. There is also a new skipPacket() function to allow you to skip the encoder for packets which ou aren't modifying.
With the ability to process response streams I have added a number of functions specifically for processing SearchResults. The getSearchDetails() function will return a SearchResult hash which contains the ObjectName decoded. If you are then interested in the object you can call getSearchResultAttributes() to decode the Attributes which have been returned. If you make any changes to the Search Result you can then call updateSearchResultDetails() to update the packet, and then encodePacket() to re-encode it. Of course if at any point you determine that no changes are needed then you can call skipPacket() instead.
import libDLAP.rts as ldap; $packet = ldap.getNextPacket(0); while ( $packet ) { # Get the Operation $op = ldap.getOp($packet); # Are we a Search Request Entry? if ( $op == "SearchRequestEntry" ) { $searchResult = ldap.getSearchResultDetails($packet); # Is the LDAPDN within example.com? if ( string.endsWith($searchResult["objectName"], "dc=example,dc=com") ) { # We have a search result in the tree we're interested in. Get the Attributes ldap.getSearchResultAttributes($searchResult); # Process all User Objects if ( array.contains($searchResult["attributes"]["objectClass"], "inetOrgPerson") ) { # Log the DN and all of the attributes log.info("DN: " . $searchResult["objectName"] ); foreach ( $att in hash.keys($searchResult["attributes"]) ) { log.info($att . " = " . lang.dump($searchResult["attributes"][$att]) ); } # Add the users favourite colour $searchResult["attributes"]["Favourite_Colour"] = [ "Riverbed Orange" ]; # If the password attribute is included.... remove it hash.delete($searchResult["attributes"], "userPassword"); # Update the search result ldap.updateSearchResultDetails($packet, $searchResult); # Commit the changes $stream .= ldap.encodePacket( $packet ); $packet = ldap.getNextPacket($packet["lastByte"]); continue; } } } # Not an interesting packet. Skip and move on. $stream .= ldap.skipPacket( $packet ); $packet = ldap.getNextPacket($packet["lastByte"]); } response.set($stream); response.flush();
This example reads each packet in turn by calling getNextPacket() and passing the lastByte attribute from the previously processed packet as the argument. We're looking for SearchResultEntry operations, If we find one we pass the packet to getSearchResultDetails() to decode the object which the search was for in order to determine the DN. If it's in example.com then we decide to process further and decode the attributes with getSearchResultAttributes(). If the object has an objectClass of inetOrgPerson we then print the attributes to the event log, remove the userPassword if it exists and set a favourite colour for the user. Finally we encode the packet and move on to the next one. Packets which we aren't interested in modifying are skipped.
Of course, rather than do all this checking in the response, we could have checked the SearchRequest in a request rule and then used connection.data.set() to flag the message ID for further processing.
We should also have a request rule which ensures that the objectClass is in the list of attributes requested by the end-user. But I'll leave that as an exercise for the reader ;-)
If you want more examples of how this library can be used, then please check out the additional use cases here: Managing LDAP traffic with libLDAP.rts | https://community.pulsesecure.net/t5/Pulse-Secure-vADC/libLDAP-rts-a-TrafficScript-LDAP-Library/ta-p/28244 | CC-MAIN-2020-16 | refinedweb | 825 | 57.06 |
12cm Qqqy China Brass Shoes Bronze Ancient Pair Of Dragon Animal Shoes Sculpture
This item has been shown 2 times.
12cm Qqqy China Brass Shoes Bronze Ancient Pair Of Dragon Animal Shoes Sculpture:
$120
Welcome to my ! Qitiandasheng882013 has been committed to creating the most advanced buyers shopping experience! Qitiandasheng882013 has grown from a small seller, summed up the experience and lessons that have grown into a rich product category, the number of products big sellers! We will continue to borrow platform to continue to develop our network sales, we have always attached great importance to qitiandasheng882013 in development!
There are many categories, we have long been engaged in the research and production of Chinese cultural works of art, our projects are handmade, guided by experts ... ...
Whether you are collecting, or engaged in sales, you can contact me! Can provide wholesale price for the dealer (according to the number of purchases)
Project details:
high : 12cm
width: kgPayment plan:
We accept and mainly recommend payment by paypal, because paypal is more secure and is more endorsed by ! But we also accept other payment methods, if you want to pay by other means, please contact us!
Return plan:
We not only accept returns, but we accept returns without any reason! You can make a variety of reasons to return (such as: girlfriend not to buy, their mother does not like, or because the weather is not good ... ...) we accept unconditional in 60 days, no reason to return! But if for your subjective reasons, you may need to pay the shipping costs incurred when returning the item ....
Shipping program:
Under normal circumstances, we will Send item to buyer within 24 hours after receiving the buyer's payment, but if there are special reasons, we will send the item within 48 hours; and we will use the near-metamorphosis of the strong packaging! If the project is damaged, it must be that the parcel has been tortured by the transport personnel ... all ravaged .....; but do not worry, we will be responsible for this situation! We will not let the buyer losses in any case! Because of our goal: to create the best buyers shopping experience!
We only use the shipping process with all the process tracking information, such as: EMS UPS DHL FedEx! Or USPS .....; we resolutely refused to “small package” ... long transport time delivery ..... very painful!!!
Leave response:
We have been so hard, if you are still not satisfied; please contact us first! We 24 hours * 365 days online ! we can solve any problems! Our goal is to build the best buyers shopping experience! The We are not casually talk about .... This is not a slogan .......
Sincerely!
12cm Qqqy China Brass Shoes Bronze Ancient Pair Of Dragon Animal Shoes Sculpture:
$120
Antique Framed Chinese Character Baby Shoes And Bib Picture Art Zhangs Textiles
Chinese Carved Jade Monkey Figurine / Pendant
Chinese Gold-plated Brass Arrowhead
Old Shoushan Stone Animal Figure Carved Statue
Vintage 1968 Chairman Mao Lin Biao Chinese Ashtray China Cultural Revolution
| http://www.holidays.net/store/12CM-QQQY-China-brass-shoes-Bronze-Ancient-pair-of-dragon-animal-shoes-Sculpture_273667899841.html | CC-MAIN-2019-09 | refinedweb | 499 | 61.26 |
In this example program, we will not so much be concerned with describing new ways how to use deal.II and its facilities, but rather with presenting methods of writing modular and extensible finite element programs. The main reason for this is the size and complexity of modern research software: applications implementing modern error estimation concepts and adaptive solution methods tend to become rather large. For example, when this program was written in 2002, the three largest applications by the main authors of deal.II, are at the time of writing of this example program:
(The library proper - without example programs and test suite - has slightly more than 150,000 lines of code as of spring 2002. It is of course several times larger now.) The sizes of these applications are at the edge of what one person, even an experienced programmer, can manage.
The numbers above make one thing rather clear: monolithic programs that are not broken up into smaller, mostly independent pieces have no way of surviving, since even the author will quickly lose the overview of the various dependencies between different parts of a program. Only data encapsulation, for example using object oriented programming methods, and modularization by defining small but fixed interfaces can help structure data flow and mutual interdependencies. It is also an absolute prerequisite if more than one person is developing a program, since otherwise confusion will quickly prevail as one developer would need to know if another changed something about the internals of a different module if they were not cleanly separated.
In previous examples, you have seen how the library itself is broken up into several complexes each building atop the underlying ones, but relatively independent of the other ones:
Besides these, and a large number of smaller classes, there are of course the following "tool" modules:
These complexes can also be found as a flow chart on the front page of the deal.II manual website.
The goal of this program is now to give an example of how a relatively simple finite element program could be structured such that we end up with a set of modules that are as independent of each other as possible. This allows to change the program at one end, without having to worry that it might break at the other, as long as we do not touch the interface through which the two ends communicate. The interface in C++, of course, is the declaration of abstract base classes.
Here, we will implement (again) a Laplace solver, although with a number of differences compared to previous example programs:
The things the program does are not new. In fact, this is more like a melange of previous programs, cannibalizing various parts and functions from earlier examples. It is the way they are arranged in this program that should be the focus of the reader, i.e. the software design techniques used in the program to achieve the goal of implementing the desired mathematical method. However, we must stress that software design is in part also a subjective matter: different persons have different programming backgrounds and have different opinions about the "right" style of programming; this program therefore expresses only what the author considers useful practice, and is not necessarily a style that you have to adopt in order to write successful numerical software if you feel uncomfortable with the chosen ways. It should serve as a case study, however, inspiring the reader with ideas to the desired end.
Once you have worked through the program, you will remark that it is already somewhat complex in its structure. Nevertheless, it only has about 850 lines of code, without comments. In real applications, there would of course be comments and class documentation, which would bring that to maybe 1200 lines. Yet, compared to the applications listed above, this is still small, as they are 20 to 25 times as large. For programs as large, a proper design right from the start is thus indispensable. Otherwise, it will have to be redesigned at one point in its life, once it becomes too large to be manageable.
Despite of this, all three programs listed above have undergone major revisions, or even rewrites. The wave program, for example, was once entirely teared to parts when it was still significantly smaller, just to assemble it again in a more modular form. By that time, it had become impossible to add functionality without affecting older parts of the code (the main problem with the code was the data flow: in time dependent application, the major concern is when to store data to disk and when to reload it again; if this is not done in an organized fashion, then you end up with data released too early, loaded too late, or not released at all). Although the present example program thus draws from several years of experience, it is certainly not without flaws in its design, and in particular might not be suited for an application where the objective is different. It should serve as an inspiration for writing your own application in a modular way, to avoid the pitfalls of too closely coupled codes.
What the program actually does is not even the main point of this program, the structure of the program is more important. However, in a few words, a description would be: solve the Laplace equation for a given right hand side such that the solution is the function \(u(x,t)=\exp(x+\sin(10y+5x^2))\). The goal of the computation is to get the value of the solution at the point \(x_0=(0.5,0.5)\), and to compare the accuracy with which we resolve this value for two refinement criteria, namely global refinement and refinement by the error indicator by Kelly et al. which we have already used in previous examples.
The results will, as usual, be discussed in the respective section of this document. In doing so, we will find a slightly irritating observation about the relative performance of the two refinement criteria. In a later example program, building atop this one, we will devise a different method that should hopefully perform better than the techniques discussed here.
So much now for all the theoretical and anecdotal background. The best way of learning about a program is to look at it, so here it is:
As in all programs, we start with a list of include files from the library, and as usual they are in the standard order which is
base –
lac –
grid –
dofs –
fe –
numerics (as each of these categories roughly builds upon previous ones), then C++ standard headers:
Now for the C++ standard headers:
The last step is as in all previous programs:
As for the program itself, we first define classes that evaluate the solutions of a Laplace equation. In fact, they can evaluate every kind of solution, as long as it is described by a
DoFHandler object, and a solution vector. We define them here first, even before the classes that actually generate the solution to be evaluated, since we need to declare an abstract base class that the solver classes can refer to.
From an abstract point of view, we declare a pure base class that provides an evaluation operator() which will do the evaluation of the solution (whatever derived classes might consider an
evaluation). Since this is the only real function of this base class (except for some bookkeeping machinery), one usually terms such a class that only has an
operator() a
functor in C++ terminology, since it is used just like a function object.
Objects of this functor type will then later be passed to the solver object, which applies it to the solution just computed. The evaluation objects may then extract any quantity they like from the solution. The advantage of putting these evaluation functions into a separate hierarchy of classes is that by design they cannot use the internals of the solver object and are therefore independent of changes to the way the solver works. Furthermore, it is trivial to write another evaluation class without modifying the solver class, which speeds up programming (not being able to use internals of another class also means that you do not have to worry about them – programming evaluators is usually a rather quickly done task), as well as compilation (if solver and evaluation classes are put into different files: the solver only needs to see the declaration of the abstract base class, and therefore does not need to be recompiled upon addition of a new evaluation class, or modification of an old one). On a related note, you can reuse the evaluation classes for other projects, solving different equations.
In order to improve separation of code into different modules, we put the evaluation classes into a namespace of their own. This makes it easier to actually solve different equations in the same program, by assembling it from existing building blocks. The reason for this is that classes for similar purposes tend to have the same name, although they were developed in different contexts. In order to be able to use them together in one program, it is necessary that they are placed in different namespaces. This we do here:
Now for the abstract base class of evaluation classes: its main purpose is to declare a pure virtual function
operator() taking a
DoFHandler object, and the solution vector. In order to be able to use pointers to this base class only, it also has to declare a virtual destructor, which however does nothing. Besides this, it only provides for a little bit of bookkeeping: since we usually want to evaluate solutions on subsequent refinement levels, we store the number of the present refinement cycle, and provide a function to change this number.
After the declaration has been discussed above, the implementation is rather straightforward:
The next thing is to implement actual evaluation classes. As noted in the introduction, we'd like to extract a point value from the solution, so the first class does this in its
operator(). The actual point is given to this class through the constructor, as well as a table object into which it will put its findings.
Finding out the value of a finite element field at an arbitrary point is rather difficult, if we cannot rely on knowing the actual finite element used, since then we cannot, for example, interpolate between nodes. For simplicity, we therefore assume here that the point at which we want to evaluate the field is actually a node. If, in the process of evaluating the solution, we find that we did not encounter this point upon looping over all vertices, we then have to throw an exception in order to signal to the calling functions that something has gone wrong, rather than silently ignore this error.
In the step-9 example program, we have already seen how such an exception class can be declared, using the
DeclExceptionN macros. We use this mechanism here again.
From this, the actual declaration of this class should be evident. Note that of course even if we do not list a destructor explicitly, an implicit destructor is generated from the compiler, and it is virtual just as the one of the base class.
As for the definition, the constructor is trivial, just taking data and storing it in object-local ones:
Now for the function that is mainly of interest in this class, the computation of the point value:
First allocate a variable that will hold the point value. Initialize it with a value that is clearly bogus, so that if we fail to set it to a reasonable value, we will note at once. This may not be necessary in a function as small as this one, since we can easily see all possible paths of execution here, but it proved to be helpful for more complex cases, and so we employ this strategy here as well.
Then loop over all cells and all their vertices, and check whether a vertex matches the evaluation point. If this is the case, then extract the point value, set a flag that we have found the point of interest, and exit the loop.
In order to extract the point value from the global solution vector, pick that component that belongs to the vertex of interest, and, in case the solution is vector-valued, take the first component of it:
Note that by this we have made an assumption that is not valid always and should be documented in the class declaration if this were code for a real application rather than a tutorial program: we assume that the finite element used for the solution we try to evaluate actually has degrees of freedom associated with vertices. This, for example, does not hold for discontinuous elements, were the support points for the shape functions happen to be located at the vertices, but are not associated with the vertices but rather with the cell interior, since association with vertices would imply continuity there. It would also not hold for edge oriented elements, and the like.
Ideally, we would check this at the beginning of the function, for example by a statement like
Assert (dof_handler.get_fe().dofs_per_vertex > 0, ExcNotImplemented()), which should make it quite clear what is going wrong when the exception is triggered. In this case, we omit it (which is indeed bad style), but knowing that that does not hurt here, since the statement
cell->vertex_dof_index(vertex,0) would fail if we asked it to give us the DoF index of a vertex if there were none.
We stress again that this restriction on the allowed finite elements should be stated in the class documentation.
Since we found the right point, we now set the respective flag and exit the innermost loop. The outer loop will the also be terminated due to the set flag.
Finally, we'd like to make sure that we have indeed found the evaluation point, since if that were not so we could not give a reasonable value of the solution there and the rest of the computations were useless anyway. So make sure through the
AssertThrow macro already used in the step-9 program that we have indeed found this point. If this is not so, the macro throws an exception of the type that is given to it as second argument, but compared to a straightforward
throw statement, it fills the exception object with a set of additional information, for example the source file and line number where the exception was generated, and the condition that failed. If you have a
catch clause in your main function (as this program has), you will catch all exceptions that are not caught somewhere in between and thus already handled, and this additional information will help you find out what happened and where it went wrong.
Note that we have used the
Assert macro in other example programs as well. It differed from the
AssertThrow macro used here in that it simply aborts the program, rather than throwing an exception, and that it did so only in debug mode. It was the right macro to use to check about the size of vectors passed as arguments to functions, and the like.
However, here the situation is different: whether we find the evaluation point or not may change from refinement to refinement (for example, if the four cells around point are coarsened away, then the point may vanish after refinement and coarsening). This is something that cannot be predicted from a few number of runs of the program in debug mode, but should be checked always, also in production runs. Thus the use of the
AssertThrow macro here.
Now, if we are sure that we have found the evaluation point, we can add the results into the table of results:
A different, maybe slightly odd kind of
evaluation of a solution is to output it to a file in a graphical format. Since in the evaluation functions we are given a
DoFHandler object and the solution vector, we have all we need to do this, so we can do it in an evaluation class. The reason for actually doing so instead of putting it into the class that computed the solution is that this way we have more flexibility: if we choose to only output certain aspects of it, or not output it at all. In any case, we do not need to modify the solver class, we just have to modify one of the modules out of which we build this program. This form of encapsulation, as above, helps us to keep each part of the program rather simple as the interfaces are kept simple, and no access to hidden data is possible.
Since this class which generates the output is derived from the common
EvaluationBase base class, its main interface is the
operator() function. Furthermore, it has a constructor taking a string that will be used as the base part of the file name to which output will be sent (we will augment it by a number indicating the number of the refinement cycle – the base class has this information at hand –, and a suffix), and the constructor also takes a value that indicates which format is requested, i.e. for which graphics program we shall generate output (from this we will then also generate the suffix of the filename to which we write).
Regarding the output format, the DataOutBase namespace provides an enumeration field DataOutBase::OutputFormat which lists names for all supported output formats. At the time of writing of this program, the supported graphics formats are represented by the enum values
ucd,
gnuplot,
povray,
eps,
gmv,
tecplot,
tecplot_binary,
dx,
vtk, etc, but this list will certainly grow over time. Now, within various functions of that base class, you can use values of this type to get information about these graphics formats (for example the default suffix used for files of each format), and you can call a generic
write function, which then branches to the
write_gnuplot,
write_ucd, etc functions which we have used in previous examples already, based on the value of a second argument given to it denoting the required output format. This mechanism makes it simple to write an extensible program that can decide which output format to use at runtime, and it also makes it rather simple to write the program in a way such that it takes advantage of newly implemented output formats, without the need to change the application program.
Of these two fields, the base name and the output format descriptor, the constructor takes values and stores them for later use by the actual evaluation function.
After the description above, the function generating the actual output is now relatively straightforward. The only particularly interesting feature over previous example programs is the use of the DataOutBase::default_suffix function, returning the usual suffix for files of a given format (e.g. ".eps" for encapsulated postscript files, ".gnuplot" for Gnuplot files), and of the generic
DataOut::write function with a second argument, which branches to the actual output functions for the different graphics formats, based on the value of the format descriptor passed as second argument.
Also note that we have to prefix
this-> to access a member variable of the template dependent base class. The reason here, and further down in the program is the same as the one described in the step-7 example program (look for
two-stage name lookup there).
In practical applications, one would add here a list of other possible evaluation classes, representing quantities that one may be interested in. For this example, that much shall be sufficient, so we close the namespace.
After defining what we want to know of the solution, we should now care how to get at it. We will pack everything we need into a namespace of its own, for much the same reasons as for the evaluations above.
Since we have discussed Laplace solvers already in considerable detail in previous examples, there is not much new stuff following. Rather, we have to a great extent cannibalized previous examples and put them, in slightly different form, into this example program. We will therefore mostly be concerned with discussing the differences to previous examples.
Basically, as already said in the introduction, the lack of new stuff in this example is deliberate, as it is more to demonstrate software design practices, rather than mathematics. The emphasis in explanations below will therefore be more on the actual implementation.
In defining a Laplace solver, we start out by declaring an abstract base class, that has no functionality itself except for taking and storing a pointer to the triangulation to be used later.
This base class is very general, and could as well be used for any other stationary problem. It provides declarations of functions that shall, in derived classes, solve a problem, postprocess the solution with a list of evaluation objects, and refine the grid, respectively. None of these functions actually does something itself in the base class.
Due to the lack of actual functionality, the programming style of declaring very abstract base classes is similar to the style used in Smalltalk or Java programs, where all classes are derived from entirely abstract classes
Object, even number representations. The author admits that he does not particularly like the use of such a style in C++, as it puts style over reason. Furthermore, it promotes the use of virtual functions for everything (for example, in Java, all functions are virtual per se), which, however, has proven to be rather inefficient in many applications where functions are often only accessing data, not doing computations, and therefore quickly return; the overhead of virtual functions can then be significant. The opinion of the author is to have abstract base classes wherever at least some part of the code of actual implementations can be shared and thus separated into the base class.
Besides all these theoretical questions, we here have a good reason, which will become clearer to the reader below. Basically, we want to be able to have a family of different Laplace solvers that differ so much that no larger common subset of functionality could be found. We therefore just declare such an abstract base class, taking a pointer to a triangulation in the constructor and storing it henceforth. Since this triangulation will be used throughout all computations, we have to make sure that the triangulation exists until the destructor exits. We do this by keeping a
SmartPointer to this triangulation, which uses a counter in the triangulation class to denote the fact that there is still an object out there using this triangulation, thus leading to an abort in case the triangulation is attempted to be destructed while this object still uses it.
Note that while the pointer itself is declared constant (i.e. throughout the lifetime of this object, the pointer points to the same object), it is not declared as a pointer to a constant triangulation. In fact, by this we allow that derived classes refine or coarsen the triangulation within the
refine_grid function.
Finally, we have a function
n_dofs is only a tool for the driver functions to decide whether we want to go on with mesh refinement or not. It returns the number of degrees of freedom the present simulation has.
The implementation of the only two non-abstract functions is then rather boring:
Following now the main class that implements assembling the matrix of the linear system, solving it, and calling the postprocessor objects on the solution. It implements the
solve_problem and
postprocess functions declared in the base class. It does not, however, implement the
refine_grid method, as mesh refinement will be implemented in a number of derived classes.
It also declares a new abstract virtual function,
assemble_rhs, that needs to be overloaded in subclasses. The reason is that we will implement two different classes that will implement different methods to assemble the right hand side vector. This function might also be interesting in cases where the right hand side depends not simply on a continuous function, but on something else as well, for example the solution of another discretized problem, etc. The latter happens frequently in non-linear problems.
As we mentioned previously, the actual content of this class is not new, but a mixture of various techniques already used in previous examples. We will therefore not discuss them in detail, but refer the reader to these programs.
Basically, in a few words, the constructor of this class takes pointers to a triangulation, a finite element, and a function object representing the boundary values. These are either passed down to the base class's constructor, or are stored and used to generate a
DoFHandler object later. Since finite elements and quadrature formula should match, it is also passed a quadrature object.
The
solve_problem sets up the data structures for the actual solution, calls the functions to assemble the linear system, and solves it.
The
postprocess function finally takes an evaluation object and applies it to the computed solution.
The
n_dofs function finally implements the pure virtual function of the base class.
In the protected section of this class, we first have a number of member variables, of which the use should be clear from the previous examples:
Then we declare an abstract function that will be used to assemble the right hand side. As explained above, there are various cases for which this action differs strongly in what is necessary, so we defer this to derived classes:
Next, in the private section, we have a small class which represents an entire linear system, i.e. a matrix, a right hand side, and a solution vector, as well as the constraints that are applied to it, such as those due to hanging nodes. Its constructor initializes the various subobjects, and there is a function that implements a conjugate gradient method as solver.
Finally, there is a set of functions which will be used to assemble the actual system matrix. The main function of this group,
assemble_linear_system() computes the matrix in parallel on multicore systems, using the following two helper functions. The mechanism for doing so is the same as in the step-9 example program and follows the WorkStream concept outlined in Parallel computing with multiple processors accessing shared memory . The main function also calls the virtual function assembling the right hand side.
Now here comes the constructor of the class. It does not do much except store pointers to the objects given, and generate
DoFHandler object initialized with the given pointer to a triangulation. This causes the DoF handler to store that pointer, but does not already generate a finite element numbering (we only ask for that in the
solve_problem function).
The destructor is simple, it only clears the information stored in the DoF handler object to release the memory.
The next function is the one which delegates the main work in solving the problem: it sets up the DoF handler object with the finite element given to the constructor of this object, the creates an object that denotes the linear system (i.e. the matrix, the right hand side vector, and the solution vector), calls the function to assemble it, and finally solves it:
As stated above, the
postprocess function takes an evaluation object, and applies it to the computed solution. This function may be called multiply, once for each evaluation of the solution which the user required.
The
n_dofs function should be self-explanatory:
The following function assembles matrix and right hand side of the linear system to be solved in each step. We will do things in parallel at a couple of levels. First, note that we need to assemble both the matrix and the right hand side. These are independent operations, and we should do this in parallel. To this end, we use the concept of "tasks" that is discussed in the Parallel computing with multiple processors accessing shared memory documentation module. In essence, what we want to say "here is something that needs to be worked on, go do it whenever a CPU core is available", then do something else, and when we need the result of the first operation wait for its completion. At the second level, we want to assemble the matrix using the exact same strategy we have already used in step-9, namely the WorkStream concept.
While we could consider either assembling the right hand side or assembling the matrix as the thing to do in the background while doing the other, we will opt for the former approach simply because the call to
Solver::assemble_rhs is so much simpler to write than the call to WorkStream::run with its many arguments. In any case, the code then looks like this to assemble the entire linear system:
The syntax above using
std_cxx11::bind requires some explanation. There are multiple version of WorkStream::run that expect different arguments. In step-9, we used one version that took a pair of iterators, a pair of pointers to member functions with very specific argument lists, a pointer or reference to the object on which these member functions have to work, and a scratch and copy data object. This is a bit restrictive since the member functions called this way have to have an argument list that exactly matches what WorkStream::run expects: the local assembly function needs to take an iterator, a scratch object and a copy object; and the copy-local-to-global function needs to take exactly a copy object. But, what if we want something that's slightly more general? For example, in the current program, the copy-local-to-global function needs to know which linear system object to write the local contributions into, i.e., it also has to take a
LinearSystem argument. That won't work with the approach using member function pointers.
Fortunately, C++ offers a way out. These are called function objects. In essence, what WorkStream::run wants to do is not call a member function. It wants to call some function that takes an iterator, a scratch object and a copy object in the first case, and a copy object in the second case. Whether these are member functions, global functions, or something else, is really not of much concern to WorkStream. Consequently, there is a second version of the function that just takes function objects – objects that have an
operator() and that consequently can be called like functions, whatever they really represent. The typical way to generate such function objects is using
std::bind (or, if the compiler is too old, a replacement for it, which we generically call
std_cxx11::bind) which takes a pointer to a (member) function and then binds individual arguments to fixed values. For example, you can create a function that takes an iterator, a scratch object and a copy object by taking the address of a member function and binding the (implicit) argument to the object on which it is to work to
*this. This is what we do in the first call above. In the second call, we need to create a function object that takes a copy object, and we do so by taking the address of a member function that takes an implicit pointer to
*this, a reference to a copy object, and a reference to a linear system, and binding the first and third of these, leaving something that has only one open argument that can then be filled by WorkStream::run().
There remains the question of what the
std_cxx11::_1,
std_cxx11::_2, etc., mean. (These arguments are called placeholders.) The idea of using
std_cxx11::bind in the first of the two cases above is that it produces an object that can be called with three arguments. But how are the three arguments the function object is being called with going to be distributed to the four arguments
local_assemble_matrix() (including the implicit
this pointer)? As specified, the first argument given to the function object will become the first argument given to
local_assemble_matrix(), the second the second, etc. This is trivial here, but allows for interesting games in other circumstances. Consider, for example, having a function
void f(double x, double y). Then, creating a variable
p of type
std_cxx11::function<void f(double,double)> and initializing
p=std_cxx11::bind(&f, std_cxx11::_2, std_cxx11::_1) then calling
p(1,2) will result in calling
f(2,1).
Solver::local_assemble_matrixand
Solver::copy_local_to_globalwith the required number of arguments, utilizing what the lambda function has gotten as arguments itself. We won't show the syntax this would require since it is no less confusing than the one used above.
At this point, we have assembled the matrix and condensed it. The right hand side may or may not have been completely assembled, but we would like to condense the right hand side vector next. We can only do this if the assembly of this vector has finished, so we have to wait for the task to finish; in computer science, waiting for a task is typically called "joining" the task, explaining the name of the function we call below.
Since that task may or may not have finished, and since we may have to wait for it to finish, we may as well try to pack other things that need to be done anyway into this gap. Consequently, we first interpolate boundary values before we wait for the right hand side. Of course, another possibility would have been to also interpolate the boundary values on a separate task since doing so is independent of the other things we have done in this function so far. Feel free to find the correct syntax to also create a task for this interpolation and start it at the top of this function, along with the assembly of the right hand side. (You will find that this is slightly more complicated since there are multiple versions of VectorTools::interpolate_boundary_values(), and so simply taking the address
&VectorTools::interpolate_boundary_values produces a set of overloaded functions that can't be passed to Threads::new_task() right away – you have to select which element of this overload set you want by casting the address expression to a function pointer type that is specific to the version of the function that you want to call on the task.)
Now that we have the complete linear system, we can also treat boundary values, which need to be eliminated from both the matrix and the right hand side:
The second half of this set of functions deals with the local assembly on each cell and copying local contributions into the global matrix object. This works in exactly the same way as described in step-9:.
Note that taking up the address of the
DoFTools::make_hanging_node_constraints function is a little tricky, since there are actually three of them, one for each supported space dimension. Taking addresses of overloaded functions is somewhat complicated in C++, since the address-of operator
& in that case returns more like
Finally initialize the matrix and right hand side vector
The second function of this class simply solves the linear system by a preconditioned conjugate gradient method. This has been extensively discussed before, so we don't dwell into it any more.
In the previous section, a base class for Laplace solvers was implemented, that lacked the functionality to assemble the right hand side vector, however, for reasons that were explained there. Now we implement a corresponding class that can do this for the case that the right hand side of a problem is given as a function object.
The actions of the class are rather what you have seen already in previous examples already, so a brief explanation should suffice: the constructor takes the same data as does that of the underlying class (to which it passes all information) except for one function object that denotes the right hand side of the problem. A pointer to this object is stored (again as a
SmartPointer, in order to make sure that the function object is not deleted as long as it is still used by this class).
The only functional part of this class is the
assemble_rhs method that does what its name suggests.
The constructor of this class basically does what it is announced to do above...
... as does the
assemble_rhs function. Since this is explained in several of the previous example programs, we leave it at that.
By now, all functions of the abstract base class except for the
refine_grid function have been implemented. We will now have two classes that implement this function for the
PrimalSolver class, one doing global refinement, one a form of local refinement.
The first, doing global refinement, is rather simple: its main function just calls
triangulation->refine_global (1);, which does all the work.
Note that since the
Base base class of the
Solver class is virtual, we have to declare a constructor that initializes the immediate base class as well as the abstract virtual one.
Apart from this technical complication, the class is probably simple enough to be left without further comments.
The second class implementing refinement strategies uses the Kelly refinement indicator used in various example programs before. Since this indicator is already implemented in a class of its own inside the deal.II library, there is not much t do here except cal the function computing the indicator, then using it to select a number of cells for refinement and coarsening, and refinement the mesh accordingly.
Again, this should now be sufficiently standard to allow the omission of further comments.
As this is one more academic example, we'd like to compare exact and computed solution against each other. For this, we need to declare function classes representing the exact solution (for comparison and for the Dirichlet boundary values), as well as a class that denotes the right hand side of the equation (this is simply the Laplace operator applied to the exact solution we'd like to recover).
For this example, let us choose as exact solution the function \(u(x,y)=exp(x+sin(10y+5x^2))\). In more than two dimensions, simply repeat the sine-factor with
y replaced by
z and so on. Given this, the following two classes are probably straightforward from the previous examples.
As in previous examples, the C++ language forces us to declare and define a constructor to the following classes even though they are empty. This is due to the fact that the base class has no default constructor (i.e. one without arguments), even though it has a constructor which has default values for all arguments.
What is now missing are only the functions that actually select the various options, and run the simulation on successively finer grids to monitor the progress as the mesh is refined.
This we do in the following function: it takes a solver object, and a list of postprocessing (evaluation) objects, and runs them with intermittent mesh refinement:
We will give an indicator of the step we are presently computing, in order to keep the user informed that something is still happening, and that the program is not in an endless loop. This is the head of this status line:
Then start a loop which only terminates once the number of degrees of freedom is larger than 20,000 (you may of course change this limit, if you need more – or less – accuracy from your program).
Then give the
alive indication for this iteration. Note that the
std::flush is needed to have the text actually appear on the screen, rather than only in some buffer that is only flushed the next time we issue an end-line.
Now solve the problem on the present grid, and run the evaluators on it. The long type name of iterators into the list is a little annoying, but could be shortened by a typedef, if so desired.
Now check whether more iterations are required, or whether the loop shall be ended:
Finally end the line in which we displayed status reports:
The final function is one which takes the name of a solver (presently "kelly" and "global" are allowed), creates a solver object out of it using a coarse grid (in this case the ubiquitous unit square) and a finite element object (here the likewise ubiquitous bilinear one), and uses that solver to ask for the solution of the problem on a sequence of successively refined grids.
The function also sets up two of evaluation functions, one evaluating the solution at the point (0.5,0.5), the other writing out the solution to a file.
First minor task: tell the user what is going to happen. Thus write a header line, and a line with all '-' characters of the same length as the first one right below.
Then set up triangulation, finite element, etc.
Create a solver object of the kind indicated by the argument to this function. If the name is not recognized, throw an exception!
Next create a table object in which the values of the numerical solution at the point (0.5,0.5) will be stored, and create a respective evaluation object:
Also generate an evaluator which writes out the solution:
Take these two evaluation objects and put them in a list...
... which we can then pass on to the function that actually runs the simulation on successively refined grids:
When this all is done, write out the results of the point evaluations, and finally delete the solver object:
And one blank line after all results:
There is not much to say about the main function. It follows the same pattern as in all previous examples, with attempts to catch thrown exceptions, and displaying as much information as possible if we should get some. The rest is self-explanatory.
The results of this program are not that interesting - after all its purpose was not to demonstrate some new mathematical idea, and also not how to program with deal.II, but rather to use the material which we have developed in the previous examples to form something which demonstrates a way to build modern finite element software in a modular and extensible way.
Nevertheless, we of course show the results of the program. Of foremost interest is the point value computation, for which we had implemented the corresponding evaluation class. The results (i.e. the output) of the program looks as follows:
What surprises here is that the exact value is 1.59491554..., and that it is apparently surprisingly complicated to compute the solution even to only one per cent accuracy, although the solution is smooth (in fact infinitely often differentiable). This smoothness is shown in the graphical output generated by the program, here coarse grid and the first 9 refinement steps of the Kelly refinement indicator:
While we're already at watching pictures, this is the eighth grid, as viewed from top:
However, we are not yet finished with evaluation the point value computation. In fact, plotting the error \(e=|u(x_0)-u_h(x_0)|\) for the two refinement criteria yields the following picture:
What is disturbing about this picture is that not only is the adaptive mesh refinement not better than global refinement as one would usually expect, it is even significantly worse since its convergence is irregular, preventing all extrapolation techniques when using the values of subsequent meshes! On the other hand, global refinement provides a perfect \(1/N\) or \(h^{-2}\) convergence history and provides every opportunity to even improve on the point values by extrapolation. Global mesh refinement must therefore be considered superior in this example! This is even more surprising as the evaluation point is not somewhere in the left part where the mesh is coarse, but rather to the right and the adaptive refinement should refine the mesh around the evaluation point as well.
We thus close the discussion of this example program with a question:
What is wrong with adaptivity if it is not better than global refinement?
Exercise at the end of this example: There is a simple reason for the bad and irregular behavior of the adapted mesh solutions. It is simple to find out by looking at the mesh around the evaluation point in each of the steps - the data for this is in the output files of the program. An exercise would therefore be to modify the mesh refinement routine such that the problem (once you remark it) is avoided. The second exercise is to check whether the results are then better than global refinement, and if so if even a better order of convergence (in terms of the number of degrees of freedom) is achieved, or only by a better constant.
(Very brief answers for the impatient: at steps with larger errors, the mesh is not regular at the point of evaluation, i.e. some of the adjacent cells have hanging nodes; this destroys some superapproximation effects of which the globally refined mesh can profit. Answer 2: this quick hack
in the refinement function of the Kelly refinement class right before executing refinement would improve the results (exercise: what does the code do?), making them consistently better than global refinement. Behavior is still irregular, though, so no results about an order of convergence are possible.) | https://www.dealii.org/8.4.1/doxygen/deal.II/step_13.html | CC-MAIN-2019-39 | refinedweb | 7,572 | 53.34 |
A template engine to render Markdown with external template imports and variable replacements.
Project description
markdown-subtemplate
A template engine to render Markdown with external template imports and basic variable replacements.
Motivation
We often make a choice between data-driven server apps (typical Flask app), CMSes that let us edit content on the web such as WordPress, and even flat file systems like Pelican.
These are presented as an either-or. You either get a full database driven app or you get a CMS, but not both. This project is meant to help add CMS like features to your data-driven web apps and even author them as static markdown files.
Here's how it works:
- You write standard markdown content.
- Markdown content can be shared and imported into your top-level markdown.
- Fragments of HTML can be used when css classes and other specializations are needed, but generally HTML is avoided.
- A dictionary of variables and their values to replace in the merged markdown is processed.
- Markdown content is converted to HTML and embedded in your larger site layout (e.g. within a Jinja2 template).
- Markdown transforms are cached to achieve very high performance regardless of the complexity of the content.
Standard workflow
Write markdown content, merge it with other markdown files, deliver it as HTML as part of your larger site.
Usage
To use the library, simply install it.
pip3 install markdown-subtemplate
Next, write a markdown template,
page.md:
## This is a sub-title * Here's an entry * And another
Register the template engine in your web app startup:
from markdown_subtemplate import engine # Set the template folder so that when you ask for page.md # the system knows where to look. engine.set_template_folder(full_path_to_template_folder)
Then generate the HTML content via:
data = {'variable1': 'Value 1', 'variable2': 'Value 2'} contents = engine.get_page('page.md', data)
Finally, pass the HTML fragment to be rendered in the larger page context:
# A Pyramid view method: @view_config(route_name='landing', renderer='landing.pt') def landing(request): data = {'variable1': 'Value 1', 'variable2': 'Value 2'} contents = engine.get_page('page.md', data) return { 'name': 'Project name', 'contents': contents }
And the larger website template grabs the content and renders it,
landing.pt:
... <div> ${structure:contents} </div> ...
Beware the danger!
This library is meant for INTERNAL usage only. It's to help you add CMS features to your app. It is not for taking user input and making a forum or something like that.
To allow for the greatest control, you can embed small fragments of HTML in the markdown (e.g. to add a CSS class or other actions). This means the markdown is processed in UNSAFE mode. It would allow for script injection attacks if opened to the public.
Extensibility
markdown-subtemplate has three axis of extensibility:
- Storage - Load markdown content from disk, db, or elsewhere.
- Caching - Cache generated markdown and HTML in memory, DB, or you pick!
- Logging - If you are using a logging framework, plug in logging messages from the library.
See the extensibility doc for details and examples.
Nested markdown
One of the reason's this project exists, rather than just passing markdown text to a markdown library is allowing nesting / importing of markdown files.
If you have page fragments that need to appear more than once, create a dedicated markdown import file that can be managed and versioned in one place. Here's how:
Created an imported file in TEMPLATES/_shared
All imported markdown files are located in subpaths of
TEMPLATES/_shared where
TEMPLATES is the path you set during startup.
TEMPLATES |- _shared |- contact.md |- footer.md |-pages | - page.md | - about.md
Write the imported / shared markdown,
contact.md:
Then in your page, e.g.
page.md you can add an import statement:
# Our amazing page Here is some info **about the page**. It's standard markdown. Want to contact us? Here are some options: [IMPORT CONTACT] And a footer: [IMPORT FOOTER]
The resulting markdown is just replacing the
IMPORT statements with the contents of those files, then passing the whole thing through a markdown to HTML processor.
Variables
markdown_subtemplate has some limited support for variable replacements. Given this markdown page:
# Example: $TITLE$ Welcome to the $PROJECT$ project. Here are some details ...
You can populate the variable values with:
data = {'title': 'Markdown Transformers', 'project': 'sub templates'} contents = engine.get_page('page.md', data)
Note that the variable names must be all-caps in the template. Missing variable statements in markdown that appear in the data dictionary are ignored.
Requirements
This library requires Python 3.6 or higher. Because, f-yes! (f-strings).
Licence
markdown-subtemplate is distributed under the MIT license.
Authors
markdown_subtemplate was written by Michael Kennedy.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/markdown-subtemplate/ | CC-MAIN-2021-21 | refinedweb | 797 | 58.38 |
I'm trying to make my own short version of the windows header stuff I use, like this for an MessageBox app:
Why does it not work? I'm getting an unresolved external for the MessageBoxA.Why does it not work? I'm getting an unresolved external for the MessageBoxA.Code:#ifdef strict struct handtp { int unused; }; typedef struct handtp* hand; #else #define hand void* #endif #define wusr __declspec(dllimport) #define wapi __stdcall #define pch const char * #define uint unsigned int wusr int wapi MessageBoxA (hand, pch, pch, uint); int __stdcall WinMain (hand hInstance, hand hPrev, pch cmdline, uint showhow) { uint unsg = 0; hand hnul = 0; pch myadr; char mystr[] = "mycapt"; myadr = &mystr[0]; MessageBoxA(hnul, myadr, myadr, unsg); return 0; } | https://cboard.cprogramming.com/windows-programming/64409-types.html | CC-MAIN-2017-09 | refinedweb | 121 | 57.2 |
37319/how-to-list-files-directories-in-python
You can use the os module to list the files and directories, and then use a for loop to use each files/directory. Refer to the following code:
import os
for filename in listdir(path/to/dir):
#whatever code you want
Firstly we will import pandas to read ...READ MORE
print(*names, sep = ', ')
This is what ...READ MORE
ou are using Python 2.x syntax with ...READ MORE
You can use the reversed function in ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
You can simply the built-in function in ...READ MORE
Well, you are using a complex way. ...READ MORE
Before printing, you can use a check ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/37319/how-to-list-files-directories-in-python | CC-MAIN-2021-21 | refinedweb | 149 | 78.75 |
I am trying to a simple thing, just like that, in a header file;
#include <filesystem> #include <iostream> namespace fs = std::filesystem;
And IntelliSense goes:
namespace std has no member filesystem.
Okay no worries, it’s an easy fix. Just set the C++ language standard in the propery pages…
Well, it turns out it isn’t, it’s not an option in Unreal VS project. Tried typing in search bar, View -> Property pages, but no luck.
Okay let’s try doing the whole thing in a console project first.
Same message from IntelliSense as before.
Ok, no worries, I found this.
I found my settings under: Project > projectname Properties
And voila, the console app works.
Let’s try it in the Unreal project.
Well, well… My options are limited here.
I had a look around in the project settings as well:
How do I get this filesystem header work with my project?
| https://proxieslive.com/how-to-set-c-language-standard-for-vs2019-in-an-unreal-project/ | CC-MAIN-2020-40 | refinedweb | 152 | 83.36 |
Has anybody managed to use this sensor board with arduino??
Views: 3365
<![if !IE]>▶<![endif]> Reply to This...
<![if !IE]>▶<![endif]> Reply
Thanks! I will give it a try with Arduino Nano V3.0.
The board seems to have 2v5 requlator and 2k2 iic pull-ups to it. Schema: (page 4).
So do I need a level converter or can I easilly disable the internal pull-ups in arduino code? And how about other pins (RXD, TXD, SS). Sorry about silly question (actually I am physicist and working as HW designer, but Iv been playing mainly with rf / power electronics / analogue signals and got the iic specs from SW guys)... I dont know what happens in startup of arduino. In some cases the internal pull-ups are high at start/boot. Prolly that is not a problem because iic is open collector and the output impedance is pretty high from digital pins.
<![if !IE]>▶<![endif]> Reply
I took another look on atavrsbin2. The wiring is pretty simple. There is i2c and power test points (holes) on the board. Power test points are regulated 2v5 and gnd. So the wiring goes like this:
Arduino 5 V -> Logic level converter HV
Arduino ground -> Logic level converter GND
Arduino I2C to both TX0 (high level tx)
Converters both TX1's to atavrsbin I2C
Converters LV to atavrsbin2 power test pin (regulated 2,5 V) and gnd to gnd
Arduino 3V3 to atavrsbin2 power in pin (socket)
So only one pin is needed in the socket and the sockets can be then used for mounting like in sensors xplained.
I will take some pics when the logic level converter arrives and I have tested it. I bought also a I/O shield for nano V3.0, so the connection should be plug and pray.
<![if !IE]>▶<![endif]> Reply
Thanks again! It was pretty simple to solder that level converter directly to Inertial Two board. I will take a pic later. Here is the code for reading the sensors (gyro, acc, mag). The orientation should be corrected for FreeImu, but it seems to print some values out...
/* IMU Fusion Board ATAVRSBIN2 - Atmel Inertial Two
Original code by (Gyro & ACC) and SparkFun Electronics (Magnetometer)
I2C address changed for Kionix KXTF9
Only for demonstartion! Orientation as in original code and not correct for this board!
*/
#define GYRO 0x68 // gyro I2C address
#define REG_GYRO_X 0x1D // IMU-3000 Register address for GYRO_XOUT_H
#define ACCEL 0x0F // Accel I2c Address
#define KXTF9_POWER_CTL 0x1B
#define magnetometer 0x1E //0011110b, I2C 7bit address of HMC5883
byte buffer[12]; // Array to store ADC values
int gyro_x;
int gyro_y;
int gyro_z;
int accel_x;
int accel_y;
int accel_z;
int mag_x;
int mag_y;
int mag_z;
int i;
#include <Wire.h>
void setup()
{
Serial.begin(9600);
Wire.begin();
// Set Gyro settings
// Sample Rate 1kHz, Filter Bandwidth 42Hz, Gyro Range 500 d/s
writeTo(GYRO, 0x16, 0x0B);
//set accel register data address
writeTo(GYRO, 0x18, 0x06);
// set accel i2c slave address
writeTo(GYRO, 0x14, ACCEL);
// Set passthrough mode to Accel so we can turn it on
writeTo(GYRO, 0x3D, 0x08);
// set accel power control to 'measure'
writeTo(ACCEL, KXTF9_POWER_CTL, 0x80);
//cancel pass through to accel, gyro will now read accel for us
writeTo(GYRO, 0x3D, 0x28);
Wire.beginTransmission(magnetometer); //open communication with HMC5883
Wire.send(0x02); //select mode register
Wire.send(0x00); //continuous measurement mode - is this ok for this app?
Wire.endTransmission();
}
//
// First set the register start address for X on Gyro
Wire.beginTransmission(GYRO);
Wire.send(REG_GYRO_X); //Register Address GYRO_XOUT_H
Wire.endTransmission();
// New read the 12 data bytes
Wire.beginTransmission(GYRO);
Wire.requestFrom(GYRO,12); // Read 12 bytes
i = 0;
while(Wire.available())
{
buffer[i] = Wire.receive();
i++;
}
Wire.endTransmission();
Wire.beginTransmission(magnetometer);
Wire.send(0x03); //select register 3, X MSB register
Wire.endTransmission();
Wire.requestFrom(magnetometer, 6);
if(6<=Wire.available()){
mag_x = Wire.receive()8; //X msb
mag_x |= Wire.receive(); //X lsb
mag_z = Wire.receive()8; //Z msb
mag_z |= Wire.receive(); //Z lsb
mag_y = Wire.receive()8; //Y msb
mag_y |= Wire.receive(); //Y lsb
}
//Combine bytes into integers
// Gyro format is MSB first
gyro_x = buffer[0] 8 | buffer[1];
gyro_y = buffer[2] 8 | buffer[3];
gyro_z = buffer[4] 8 | buffer[5];
// Accel is LSB first. Also because of orientation of chips
// accel y output is in same orientation as gyro x
// and accel x is gyro -y
accel_y = buffer[7] 8 | buffer[6];
accel_x = buffer[9] 8 | buffer[8];
accel_z = buffer[11] 8 | buffer[10];
// Print out what we have
Serial.print("GY X: ");
Serial.print(gyro_x); // echo the number received to screen
Serial.print("\t GY Y: ");
Serial.print(gyro_y); // echo the number received to screen
Serial.print("\t GY Z: ");
Serial.print(gyro_z); // echo the number received to screen
Serial.print("\t ACC X: ");
Serial.print(accel_x); // echo the number received to screen
Serial.print("\t ACC Y: ");
Serial.print(accel_y); // echo the number received to screen
Serial.print("\t ACC Z: ");
Serial.print(accel_z); // echo the number received to screen
Serial.print("\t MAG X: ");
Serial.print(mag_x); // echo the number received to screen
Serial.print("\t MAG Y: ");
Serial.print(mag_y); // echo the number received to screen
Serial.print("\t MAG Z: ");
Serial.print(mag_z); // echo the number received to screen
Serial.println(""); // prints carriage return
}
<![if !IE]>▶<![endif]> Reply
Nice, keep us posted!
<![if !IE]>▶<![endif]> Reply
This is how I connected the converter board to Inertial Two.
Only 3V3 is connected to socket. GND and I2C goes through the converter board. I used the other RX hole for jumper wire so I took off the voltage divider resistor. I guess it is not needed to be ripped off (removed resistor was 10 k to gnd and pull-ups something like 2-3 k to 2V5).
Ps. Arduino Nano 3.0 does not have the same pinmap as that DFRduino shield. I2C goes in that board like this: SLC to pin labeled "2" in the shield and SDA to "3". More about the problem:...
<![if !IE]>▶<![endif]> Reply
Thanks for the posting Markus. I got mine today but haven't gotten the level converter (hmmm, shipped faster from Malaysia than Colorado...). The only place where it seems you can get 2.5V is at the test point labeled PWR. I was hoping to steal one of the pins on J2 but they all seem to be connected somewhere even if the schematic doesn't show any connections. I guess I can use J1 for that or at worst case put another 2.5V regulator on the shield. The idea is to create a shield that will hold the IMU more securely and do the level conversions as well as a few other functions.
<![if !IE]>▶<![endif]> Reply
How to import the values to FreeIMU? I quess I am doing it wrong :)
Is there any basic info about the orientation of the sensors? And how about the values?
For example I have the IMU3000 at 500 deg/s and it is 16 bits.. I guess the output should be divided by approx 3755 (500 deg/s so with 16 bit signed the sensor value is from -32767 to +32767 and 500 deg/s = 8,72638 rad/s so 1 LSB = 2,6631611 * 10^-4 rad/s -> 1/LSB = 3 754,93)
When trying to convert the quaternion to angles the result just rotates around. I tried to use lpf with acc sensor without success. So how is the orientation defined? Could that be the problem or is it just me?
<![if !IE]>▶<![endif]> Reply
Hi, I am playing with your code. Thanks for posting. it looks like the forum SW dropped a bunch of left shift operators (I can't even post them, they just go away). Pretty obvious what to do though.
Also, I'm using arduino 1.0 and the wire lib forced a number of changes:
<![if !IE]>▶<![endif]> Reply
There might be also a better way to read the sensors. That was just a quick test for proper registers.I think at least the accel axises should be changed.
Somehow I managed to get the DCM to work, but not properly. Heavy drifting and one axis does not work on full scale when converting to euler. I will try some filtering and clean the code before sharing it. I took only the DCM part of FreeIMU for it.
Ps. What is the easiest way to visualize sensor values or quaternion output?
<![if !IE]>▶<![endif]> Reply
Thanks for the quick reply. It seems like pretty straightforward code. I just got my level shifter from SFE today so haven't had much time with it so far.
Yeah, I noticed your comment about the acc being wrong on the atavrsbin2.
By the way, I seem to not get any values from the HPF registers of the KXTF9 - all zeros. I tried changing the filter bits (reg 0x21) but nothing seems to work. I couldn't find any errata on the kionix site. Filtering isn't that hard but I'd still like to play with it. I found some one else that posted about the same problem about a month ago but no response.
For visualization I've been using Processing with another accelerometer - derived from a 3d cube example I found on the web. Use the acc to control the position of the cube. It's easy enough to plug the this program's data stream into it. I was thinking of doing something similar for the gyro output. Mag output would control a sphere - not very compelling. Not sure when I'll get to that, though. I'll give you what I've got once I get it together.
<![if !IE]>▶<![endif]> Reply !IE]>▶<![endif]> Reply | http://diydrones.com/forum/topics/atmel-inertial-two-atavrsbin2-arduino | CC-MAIN-2014-10 | refinedweb | 1,617 | 67.96 |
what is package and how its creates,and advantage also.....?
Java what is Package
A package is a namespace that organizes a set of related classes and interfaces.
Advantages:
Advantages of Packages
1)Anyone can easily determine which files are related.
2)Name space collision is minimized.
3)One can allow types in one package to have unrestricted access to one another, still restricting the access for the types outside the package.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://www.roseindia.net/answers/viewqa/Java-Interview-Questions/16515-java.html | CC-MAIN-2013-20 | refinedweb | 108 | 56.35 |
I have started learning C++ recently and am currently working my way through various tutorials and books.
Most recently the object of interest was a very basic calculating program, running from the win prompt.
I understand the code and the program runs perfectly fine. However, I had the idea to try and add a little gimmick to the program. As you might already guess, that didn't work the way I expected. Actually, it didn't work at all.
The basic idea of the original program is, asking the user to input two numbers and then asking again to choose between adding, subtracting, multiplying and dividing the numbers, then displaying the result.
With the intent to increase my understanding of C++ and explore the code system a bit on my own I was wondering if it was possible to get the program to react to the result it puts out in the end.
My idea was to add a literature reference at the end if the output result equals 42, i.e. Don't Panic! or The answer to the great question or something like that. Would that be possible? And if so, what would I need to do?
The original code for the program is as follows:
#include <iostream>
int main()
{
using namespace std;
float num1;
float num2;
char op;
float ans;
cout << "Please enter a number: ";
cin >> num1;
cout << "Please enter another number: ";
cin >> num2;
cout << "Press A to add the two numbers." << endl;
cout << "Press S to subtract the two numbers." << endl;
cout << "Press M to multiply the two numbers." << endl;
cout << "Press D to divide the two numbers." << endl;
cin >> op;
if (op == 65)
ans = num1 + num2;
if (op == 83)
ans = num1 - num2;
if (op == 77)
ans = num1 * num2;
if (op == 68)
ans = num1 / num2;
cout << "The answer is " << ans << endl;
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
Like I said, this runs just like it should.
I tried to add my "Easter egg" by inserting an integer 'x' and declaring it being '42'. I then followed to insert the code that if 'ans' equals 'x' 'cout' should display my extra statement 'Don't Panic!'.
Like already mentioned, this didn't work. The compiler seems to have processed everything accordingly, no errors were reported, but the extra simply got left out.
Can somebody help me understand why that happens and help me fix it?
I'm hoping that I will be able to understand the code and programming in C++ a little better when venturing off the path given by the books and trying some new/other things that are not set in the curriculum.
Appreciate your help and would like to thank you in advance. | http://cboard.cprogramming.com/cplusplus-programming/124817-adding-extra-lines-code-doesn%27t-work.html | CC-MAIN-2016-07 | refinedweb | 453 | 71.14 |
The size, age, and complexity of software is growing. Programmers now spend more time reading, maintaining, and enhancing code than they do writing original code. Therefore, it is critical that a professional programmer not only be able to write efficient and correct code, but it must also be written in a style that others can understand.
Coding standards are used by an organization to help everyone work more reliably together, improve quality, reduce development time, and allow quicker maintenance. Your guiding principle when writing code should be whether the reader will easily understand what you mean and what the code does. Well-designed, well-written code is a joy to debug, maintain, and enhance.
We will use a subset of Sun Microsystem’s Java Coding Conventions. You are expected to follow these conventions for all source code you develop for this course. Refer to How To Write Javadoc Comments for tips on the appropriate use of Javadoc tags.
Code Layout
Consistent layout of the source code not only improves readability but provides a professional appearance.
- Use four spaces for indentation. Set your editor to automatically expand the TAB character to 4 spaces
- Avoid lines longer than 72 characters.
- Split statements longer than 72 characters into multiple lines by placing carriage returns after commas and operators.
- Printed source code should not have lines that wrap.
- Indent compound statements such as loops and branching statements. See example below.
- Indent nested if statements as you would a switch statement. See example below.
- Put the opening brace ‘{‘ on the same line as the class header, method header, conditional statement (if, switch), and loops.
- Indent the closing brace ‘}’ at the same level as the corresponding class header, method header, conditional statement, and loops.
- Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. Avoid duplicating information that is clearly evident in the code.
- Javadoc comment must begin with
/**and end with
*/
Class Headers
All source files should begin with a class header that lists the class name, version information, and author. Use Javadoc
@author and
@version tags where appropriate. See sample code below.
Method Headers
Provide headers for every method that includes horizontal lines to make the header visually distinctive. Use two blanks lines before each method header. Use Javadoc
@param,
@return, and
@throws tags where appropriate. See sample code below.
Block Comments
Single line comments appear before ‘interesting events’ such as loops and branching statements. Provide a blank line before the comment and indent it with the code it describes. See sample code below.
If used, trailing comments at the end of lines should fit neatly within the 72 character line.
Declarations
- Provide one variable declaration per line and provide javadoc comments before each declaration. See sample below.
- Place declarations only at the beginning of blocks. One exception to the rule is indexes in for loops.
- Declare instance variables at the top of the class definition (do not instantiate the object).
- Instantiate instance variables in the class constructor (do not declare it).
- Declare and initialize local variables at the start of a method.
Statements
- Each line should contain only one statement.
White Space
Blank lines improve readability by setting off sections of code that are logically related.
- Use a blank line before each method header.
- Use a blank line before each comment.
- Use a blank line between local variables declared in a method and its first statement.
- Use a blank space around operators.
Naming Conventions
Naming conventions make programs more understandable by making them easier to read.
- Class names should be a noun and begin with a capital letter. Keep the name simple and descriptive.
- Method names should be verbs and begin with a lower case letter.
- Variable names should be short yet meaningful. Avoid single character names, except for loop variables.
- Variables defined as final or intended to serve as a constant should be in ALL CAPS.
Programming Principles
The following recommendations help prevent common errors and reinforce strong software design principles.
- Avoid making instance or class variables public without a good reason.
- Use instance variables for data that is part of the object state.
- Use local variables within methods if the data is not part of the object state.
- Strive to have a single return statement at the end of a method. However, there can be legitimate exceptions to improve readability or efficiency.
- Avoid using break statements within loops and if statements. However, there can be legitimate exceptions to improve readability or efficiency.
- Strive to keep methods short and perform a single task (less than 20 lines). This is a software engineering principle called high cohesion.
- Avoid numeric constants. Instead, define a named constant at the top of the block. For example,
final int MONTHS = 12;
- Error messages and output should be clear and consistent.
- The graphical user interface (GUI) should have a professional appearance.
Sample Source Code (with JavaDoc comments)
JavaDoc comments are only provided immediately before class definitions, methods, and instance variable declarations. Traditional Java comments should be used within the body of a method as necessary.
/***************************************************************** Graphical representation of a six sided die with various controls over the appearance. Current value is constrained between 1 and 6. @author Joanne Programmer @version Winter 2007 *****************************************************************/ public class Dice extends Panel { /** current value of the die */ private int myValue; /** current size in pixels */ private int mySize; /** number of miliseconds between rolls */ private int myDelay; /** color of the dots */ private Color myColor; /** background color */ private Color myBackground; /***************************************************************** Constructor creates a die of specified size X size pixels @param size the length of each side in pixels *****************************************************************/ public Dice(int size) { // initialize the die and determine display characteristics mySize = size; dotSize = mySize / 5; setBackground(Color.white); myColor = new Color(0,0,0); myColor = Color.black; setLayout(null); myValue = (int) (Math.random()*6)+1; } /***************************************************************** Default constructor creates a die of size 100 X 100 pixels *****************************************************************/ public Dice( ) { this(100); } /***************************************************************** Set the delay in milliseconds between frames of the animation. Default value is 250. @param msec milliseconds to delay *****************************************************************/ public void setDelay (int msec) { myDelay = 0; if (msec > 0) myDelay = msec; } /***************************************************************** Display the current value of the die. Called automatically after rolling. There is no need to call this method directly. @param g the graphics context for the panel @return none *****************************************************************/ public void paintComponent(Graphics g) { //ask my parent to paint needed components super.paintComponent(g); // paint dots based on current value switch (myValue) { case 1: g.fillOval (middle, middle, dotSize, dot); break; case 2: g.fillOval (left, left, dotSize, dotSize); g.fillOval (right, right, dotSize, dotSize); break; case 3: g.fillOval (middle, left, dotSize, dotSize); g.fillOval (middle, middle, dotSize, dotSize); g.fillOval (middle, right, dotSize, dotSize); break; case 5: g.fillOval (middle, middle, dotSize, dotSize); // the "break" statement is intentionally omitted here // fall through and paint four more dots case 4: g.fillOval (left, left, dotSize, dotSize); g.fillOval (left, right, dotSize, dotSize); g.fillOval (right, left, dotSize, dotSize); g.fillOval (right, right, dotSize, dotSize); break; case 6: g.fillOval (left, left, dotSize, dotSize); g.fillOval (left, middle, dotSize, dotSize); g.fillOval (left, right, dotSize, dotSize); g.fillOval (right, left, dotSize, dotSize); g.fillOval (right, middle, dotSize, dotSize); g.fillOval (right, right, dotSize, dotSize); break; } } }
Additional References
- Sun Microsystem’s Java Coding Conventions
- How To Write Javadoc Comments
- J. Langr, Essential Java Style, Prentice Hall, 2000
- A. Vermeulen et al., The Elements of Java Style, Cambridge University Press, 2000. | http://www.cis.gvsu.edu/java-coding-style-guide/ | CC-MAIN-2018-26 | refinedweb | 1,251 | 59.4 |
is there any way to convert string to byte in c++ just like the getbytes() in java??
Printable View
is there any way to convert string to byte in c++ just like the getbytes() in java??
Like using the [ ] operator perhaps?
Code:
#include <iostream>
#include <string>
#include <iomanip>
int main ( ) {
std::string foo = "hello";
std::cout << "Letter=" << foo[0] << std::endl;
};
Don't forget to delete that!
A better approach:
Code:
std::string str = "Hello World";
std::vector<char> bytes(str.begin(), str.end());
thanks..not the answer i am looking for but it helps in another way..
Then what do you want? You have your array of bytes (examples above)..
Perhaps the best question is, what are you trying to do? | http://cboard.cprogramming.com/cplusplus-programming/138795-converting-string-byte-cplusplus-printable-thread.html | CC-MAIN-2015-22 | refinedweb | 122 | 76.01 |
Making my own sprite class
#1 Members - Reputation: 122
Posted 30 September 2007 - 07:58 AM
#2 Members - Reputation: 2008
Posted 30 September 2007 - 08:13 AM
Also, Draw[Indexed]Primitive() calls are particularly expensive, you don't want to be making more than 500 or so calls per frame. Using transforms for each sprite means you have to call Draw[Indexed]Primitive() once per sprite, which will give you horrible performance.
My sprite manager uses a std::vector of structs, one for each sprite and it fills an internal VB and renders from it once per frame.
#3 Members - Reputation: 122
Posted 30 September 2007 - 08:53 AM
#4 Members - Reputation: 359
Posted 30 September 2007 - 11:12 AM
#5 Members - Reputation: 122
Posted 30 September 2007 - 01:08 PM
I could be completly misunderstanding you though, if so, I have no idea what you mean by Draw once vs multiple times.
#6 Members - Reputation: 960
Posted 30 September 2007 - 01:54 PM
1. Each image is loaded into one giant volume texture, this eliminates the need to to switch textures.
2. Each image stores an array of 4 vertices and 6 indices. The vertices looked something like this:
Vertex V1 = new Vertex( 0, Height, -Width / 2, U1, V1, W );
Vertex V2 = new Vertex( 0, Height, Width / 2, U2, V1, W );
Vertex V3 = new Vertex( 0, 0, -Width / 2, U1, V2, W );
Vertex V4 = new Vertex( 0, 0, Width / 2, U2, V2, W );
This was for 3D billboarding, but something similar will also for 2D.
Edit: Width and Height are the dimensions of the image. That's because in Doom, 1 unit in object space is the size of one pixel. You'll of course need to adjust these to match your game.
3. At the start of each frame a list(vector for C++) of vertices and a list of indices are cleared.
4. When an image is "drawn" its vertices and indices are added to the list. The copies of the vertices in the vertex list then have the necessary transformations done to them through software calculations.
5. When everything is added, every sprite is then rendered with a single DrawIndexedUserPrimitives call.
I'm no GPU guru, but this was the best method I could think of at the time. I never tested it with a dynamic VB/IB, so I don't know if it would be any faster.
#7 Members - Reputation: 496
Posted 30 September 2007 - 02:56 PM
If you can group your sprites by texture and render state you will get even greater speed as you will be able to tell the GPU to render hundreds of sprites at once.
#8 Members - Reputation: 122
Posted 30 September 2007 - 02:57 PM
Anyway this whole sprite thing is really frustrating me, it has been 2 weeks and every time I get close to doing one way, something comes up and hoses it all up. Let me go over the history here.
I start off with making my own quads and then notice the Sprite class.
I spend a few days messing with Sprite.Draw2d.
Then I get told I shouldn't use that, and just use my own transforms in lew of Draw2d.
Ok fine...
I then go on and start using Sprite.Draw() and spend a full week on this. I end up doing a bunch of matrix math so I can get a virtual cordinate system, handle aspect ratio and viewport changes. Everything seems great and then...
I try and draw two sprites. They overlap. I can use the Draw() to move them in screen space, which breaks my virtual coordinate system, but I absolutly can not rotate or scale them. The last matrix used affects all sprites. I ask around and am told that I just can't do that without a bunch of Begin / Ends, which is a bad thing.
Now I am hosed, again... I go back to doing my own quads and sprite class just so I can be done with this whole Sprite class mess.
So I had some other issues, like textures dissapearing when my viewport changed size and I couldn't make my textures transparent. I figured that all out, but in the course of all that I get several people telling me (not all from this thread):
I really should use the sprite class. Try Draw2d... like I was doing before? Don't do a bunch of DrawPrimitives either, its slow. Don't edit vertex buffers, its slow. WTF?!
I just want to cry now. 2 weeks and not even a basic sprite system and I am running in circles. I keep getting conflicting information.
Is there anyone, who can difinitavly give me a 'best practices' on how I should be rendering 2D sprites? Id like to move on to other programming issues and stop with the sprite business.
#9 Members - Reputation: 466
Posted 30 September 2007 - 04:10 PM
Quote:
I would consider frustration and lack of information to be the "normal" state of an average programmer. Which is why you keep searching, keep learning and keep trying until you are good enough. And then your next problem is a lot more difficult than the last so the cycle repeats.
Now, about your sprite problem. I might be mistaken, but ID3DXSprite::SetTransform should affect individual sprites. Meaning, you can call SetTransform once, render 3 sprites all with that transform, then call SetTransform again, render 5 more sprites with that transform, etc.
Because you are allowed to specify screen coordinates in the call, you should probably use SetTransform only for rotation (which may include translation if center is off-center), or scaling. You can also animate through changing texture coordinates of the RECT that you pass to ID3DXSprite::Draw.
Perhaps you can give more info on how you set up your rendering (why you are having problems with SetTransform?) It looks like you should be able to make ID3DXSprite work for you, but instead you are trying to roll your own, which is by far not a simple task. For "general" case scenarios, you probably can't create something that is better than ID3DXSprite.
#10 Members - Reputation: 122
Posted 30 September 2007 - 04:17 PM
Quote:
I just re-read what you wrote and read some manuals on this. I have a few questions on implementation.
So I have a giant VB, maybe one that has 250 'quads', worth of sprites, 1000 verts. I have a list of 600 sprites to draw. I then follow these steps:
1. The very first run (per frame) I use Lock.None.
2. I loop through my sprite list, and edit the verts in the VB until I have done all 1000, or 250 quads worth.
3. Unlock the buffer, issue the draw command.
4. Lock with Lock.discard and go to step 2 until I am done with my 600 sprites.
Is that essentially it?
There is another thing you said, I am confused about. You said I can't afford a matrix transform per sprite. The only way I know how to rotate a point (or 4 of them) is to multiply them against a matrix. In fact, I would think that for each quad, you would have to do for each vert, Vector3() * RotationMatrix * ScaleMatrix * TranslationMatrix.
If not, how am I suppose to set up each sprite? Also since I will be doing this stuff manually, should I switch from PositionTextured to TransformedTexturered verts?
#11 Members - Reputation: 122
Posted 30 September 2007 - 04:31 PM
Quote:
I am trying to make an actio 2D rts game that takes place in Space. So I am going to have a lot of sprites I need for this. Imagine two armies of fighters, cruisers, and capitol ships clashing. There might be 100 of each, and they are shooting bullets and missiels at each other, maybe even lasers if I decided to try and figure out how to make my own procedural textures to use.
After I am done with the basic game logic, which is where each unit goes, what direction it is facing, and what other effects are going, like explosions, Ill have a big list of game objects that Ill need to render.
Ill end up with a bunch of sprites of a few size classes 16x as bullets, 32x as fighters, 64x as bigger ships, and maybe even a few 128x capitol ships. Some of these might not need rotation because a bullet might be round. Most of them will.
All of them will need scaling because I do not know of another way to keep the aspect ratio and position on the screen independent of the resolution. I can't just say Unit 112 has an X location of 600, because it would appear in different relative spots on a system running 800x600 vs 1920x1200. I also have the issue of knowing the screen is in 1920x1200 but the viewport is only 400x400 because the window is shrunk.
Then of course, there is the final location of the sprite. I am not sure if I should try and figure out of each sprite is on screen or just pump them all out and let the render system figure out if it wants to cull it or not.
With all that in mind, I now need to render all the sprites. I was using the sprite class to draw them all using the Draw function. Only when I tried to rotate and scale them, it applied to ALL sprites, not the last one I did the Sprite.draw() with. I was stuck. So this is why I went with my own sprite class.
#12 Members - Reputation: 359
Posted 30 September 2007 - 07:44 PM
Quote:
Yep, that's it. There's not much to say about it. One tipp: Make your system dynamic: If the buffer is too small to hold all sprites, that need to be rendered, just adjust it's size: there's no need to call Draw(Indexed)Primitve twice for all the sprites.
That means: You have a function that will eventually call Draw(Indexed)Primitive. But before it can do that, it will check wether the std::vector contains more sprites than the VB can hold. If it does, release the VB and create a VB with the needed size.
After that, just call Draw(Indexed)Primitive
Quote:
I assume that your camera never rotates if it's a 2D game?
This will make things easier concerning the matrix multiplications.
It's something I read from jollyjeffers:
If you set the ViewProjectionmatrix to be an identity matrix, you can scale and reposition your sprites really easy. Just try it out. If you render a quad with a matrix that sets the scale to 1 for all axes, the quad will fill out the entire screen, no matter under wich resolution your app is running. If you render it with 0.5 scale, your quad will just fill 1/4th of the screen.
Positioning becomes as easy as scaling: (-1|1) is the top left point of the screen (I hope I'm not mistaken *g), (1|-1) the bottom right.
#13 Members - Reputation: 2008
Posted 30 September 2007 - 09:25 PM
static const size_t s_nBatchSize = 8192;
static bool SpriteSorter(const ESprite* a, const ESprite* b)
{
// First, sort by depth
if(a->GetDepth() == b->GetDepth())
{
// Then by texture
if(a->GetTexture().Get() == b->GetTexture().Get())
{
// Sort by pointer
return a < b;
}
return a->GetTexture().Get() < b->GetTexture().Get();
}
return (a->GetDepth() >= b->GetDepth());
}
struct SpriteVertex
{
D3DXVECTOR3 vPos;
u32 nColour;
float u1;
float v1;
};
bool PSpriteMgr::Init(PGraphics& gfx)
{
// Create vertex buffer
m_pVB = new PDynamicVertexBuffer(gfx);
HRESULT hResult = m_pVB->Create(s_nBatchSize*4*2, sizeof(SpriteVertex));
if(FAILED(hResult))
{
m_pVB = 0;
std::wstringstream str;
str << L"Failed to create vertex buffer for sprite manager. Error: ";
str << DXGetErrorString(hResult);
PApp::Get().SetError(str.str());
ELog::Get().ErrorFormat(L"SPRT MGR: %s\n", PApp::Get().GetError().c_str());
return false;
}
// Create index buffer
m_pIB = new PIndexBuffer(gfx);
hResult = m_pIB->Create(s_nBatchSize*6);
if(FAILED(hResult))
{
m_pIB = 0;
m_pVB = 0;
std::wstringstream str;
str << L"Failed to create index buffer for sprite manager. Error: ";
str << DXGetErrorString(hResult);
PApp::Get().SetError(str.str());
ELog::Get().ErrorFormat(L"SPRT MGR: %s\n", PApp::Get().GetError().c_str());
return false;
}
// Lock the IB
WORD* pIndex = m_pIB->Lock(0, s_nBatchSize*6);
if(!pIndex)
{
m_pIB = 0;
m_pVB = 0;
std::wstringstream str;
str << L"Failed to lock index buffer for sprite manager. Error: ";
str << DXGetErrorString(hResult);
PApp::Get().SetError(str.str());
ELog::Get().ErrorFormat(L"SPRT MGR: %s\n", PApp::Get().GetError().c_str());
return false;
}
// Fill it with data
for(size_t i=0; i<s_nBatchSize; ++i)
{
*pIndex++ = (WORD)(i*4 + 0);
*pIndex++ = (WORD)(i*4 + 1);
*pIndex++ = (WORD)(i*4 + 2);
*pIndex++ = (WORD)(i*4 + 1);
*pIndex++ = (WORD)(i*4 + 3);
*pIndex++ = (WORD)(i*4 + 2);
}
// Unlock it
m_pIB->Unlock();
// Create vertex declaration
m_pVertexDecl = new PVertexDecl;
m_pVertexDecl->AppendPosition().AppendDiffuse().AppendTextureCoords();
if(!m_pVertexDecl->GetDecl()) // Ensure decl is created
{
m_pVertexDecl = 0;
m_pIB = 0;
m_pVB = 0;
return false;
}
// Init shader
m_pShader = gfx.GetShader(L"Sprite.vsh", PVertexShader::VS_2_0);
if(!m_pShader)
{
m_pVertexDecl = 0;
m_pIB = 0;
m_pVB = 0;
return false;
}
// Done
return true;
}
//============================================================================
bool PSpriteMgr::Render(PGraphics& gfx)
{
// Merge pending sprites into main list
for(SpriteVecIter it=m_pendingSprites.begin(); it!=m_pendingSprites.end(); ++it)
m_sprites.push_back(*it);
m_pendingSprites.clear();
// Sort sprite list
std::sort(m_sprites.begin(), m_sprites.end(), SpriteSorter);
// No sprites means early out
if(m_sprites.empty())
return true;
// Apply device state
m_pShader->SetMatrix("mWorldViewProj", EMatrix().SetToOrthogonal(0.0f, 0.0f,
(float)gfx.GetWidth(), (float)gfx.GetHeight(), 0.0f, 1000.0f));
gfx.SetIndices(m_pIB);
gfx.SetVertexDecl(m_pVertexDecl);
gfx.SetVertexShader(m_pShader);
gfx.SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
gfx.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
gfx.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
gfx.SetRenderState(D3DRS_LIGHTING, FALSE);
// Render sprites
u32 nRemain = (u32)m_sprites.size();
SpriteListIter itSprite = m_sprites.begin();
ESprite* pLast = *itSprite;
PTexture* pLastTexture = (PTexture*)pLast->GetTexture().Get();
LPDIRECT3DTEXTURE9 pLastD3DTexture = NULL;
while(nRemain > 0)
{
// Lock as much of the VB as possible
Assert(m_pVB, "VB not created");
u32 nSpritesToLock = min(nRemain, (u32)s_nBatchSize);
u32 nRenderOffset=0;
SpriteVertex* pVertex = (SpriteVertex*)m_pVB->Lock(nSpritesToLock*4, nRenderOffset);
if(!pVertex)
return false;
// Fill the VB and unlock it
SpriteListIter itCurr = itSprite;
for(u32 i=0; i<nSpritesToLock; ++i)
{
PTexture* pTexture = (PTexture*)(*itCurr)->GetTexture().Get();
EVector2 vPos = (*itCurr)->GetPos() + (*itCurr)->GetOrigin();
float fDepth = (float)(*itCurr)->GetDepth() / 65535.0f;
EVector2 vSize = EVector2((float)pTexture->GetWidth(), (float)pTexture->GetHeight()) * (*itCurr)->GetScale();
u32 nColourTL = (*itCurr)->GetColourTL().ToARGB();
u32 nColourTR = (*itCurr)->GetColourTR().ToARGB();
u32 nColourBL = (*itCurr)->GetColourBL().ToARGB();
u32 nColourBR = (*itCurr)->GetColourBR().ToARGB();
++itCurr;
pVertex->vPos = D3DXVECTOR3(vPos.x - 0.5f, vPos.y - 0.5f, fDepth);
pVertex->nColour = nColourTL;
pVertex->u1 = pTexture->GetTUMin();
pVertex->v1 = pTexture->GetTVMin();
pVertex++;
pVertex->vPos = D3DXVECTOR3(vPos.x+vSize.x - 0.5f, vPos.y - 0.5f, fDepth);
pVertex->nColour = nColourTR;
pVertex->u1 = pTexture->GetTUMax();
pVertex->v1 = pTexture->GetTVMin();
pVertex++;
pVertex->vPos = D3DXVECTOR3(vPos.x - 0.5f, vPos.y+vSize.y - 0.5f, fDepth);
pVertex->nColour = nColourBL;
pVertex->u1 = pTexture->GetTUMin();
pVertex->v1 = pTexture->GetTVMax();
pVertex++;
pVertex->vPos = D3DXVECTOR3(vPos.x+vSize.x - 0.5f, vPos.y+vSize.y - 0.5f, fDepth);
pVertex->nColour = nColourBR;
pVertex->u1 = pTexture->GetTUMax();
pVertex->v1 = pTexture->GetTVMax();
pVertex++;
}
m_pVB->Unlock();
// Submit batches
size_t nStart = 0;
size_t nCount = 0;
gfx.SetStreamSource(m_pVB, nRenderOffset);
while(nSpritesToLock > 0)
{
ESprite* pCurr = *itSprite++;
--nSpritesToLock;
// Need to flush?
if(pLastD3DTexture != ((PTexture*)pCurr->GetTexture().Get())->GetTexture())
{
if(nCount > 0)
{
gfx.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, (UINT)(nStart*4),
(UINT)(nCount*4), (UINT)(nStart*6), (UINT)(nCount*2));
nStart += nCount;
}
nCount = 1;
pLast = pCurr;
pLastTexture = (PTexture*)pLast->GetTexture().Get();
pLastD3DTexture = pLastTexture->GetTexture();
gfx.SetTexture(0, pLastTexture);
}
else
++nCount;
}
// Render last batch
gfx.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, (UINT)(nStart*4),
(UINT)(nCount*4), (UINT)(nStart*6), (UINT)(nCount*2));
nRemain -= min(nRemain, (u32)s_nBatchSize);
}
return true;
}
Even if that doesn't make much sense, the comments should give you a rough idea of what's going on. Most of the types there are my own custom classes, but all you need to care about is that it uses a static index buffer (Filled once at init time) and a dynamic vertex buffer, which is filled every frame.
Hope this helps.
#14 Members - Reputation: 496
Posted 01 October 2007 - 12:31 AM
Quote:
Others have already given you some good feedback on this, but my advice would be make the 'giant VB' more giant. You want to be using it over multiple frames; by reusing the same vertices within a frame you could easily cause a pipeline stall. You can use the NOOVERWRITE flag to clue the driver in that you are doing this, allowing it to continue working on the old data while you supply the new (upcoming sprites) data. I would recommend having something like 32000 vertices and you only have to 'start from the beginning' of it every 10th frame or whatever.
Quote:
This is of course fine; I am referring to using the device's world matrix which can be used to transform a group of points (such as a 3D mesh). By all means determine your final sprite positions using matrices on the CPU, but doing the transformation math on the GPU is difficult for a sprite system as you describe.
I recently completed a Direct3D space-shooter type game which sounds very similar to your project so I hope I am not way off base here, but the idea is that you can't afford to set a transformation, draw 2 triangles, set the next transformation, draw 2 more triangles, etc. Drawing each sprite by itself like this is SLOW. The overhead for draw calls is such that if you're going to draw 2 triangles, you might as well draw 100 triangles for 5% extra cost (hypothetical numbers but you get the idea).
On a related subject, this is the same reason that it's very important to use texture atlases; you can use (per-vertex) UV coordinates to identify what the sprite 'looks like' instead of needing a device.SetTexture (which is slow itself AND breaks the batch). You don't need to go overboard (i.e. combining completely irrelevant sprites) but I would recommend you try to fill up 512x512 or 1024x1024 sized textures instead of using many smaller ones. Also note that if you're careful with your floating point math you can use these texture atlases to your advantage, creating 'internal' sprites that don't necessarily conform to the power-of-2 texture size guideline.
#15 Members - Reputation: 122
Posted 01 October 2007 - 03:57 AM
However, you say chaning texture pages is expensive? ie: Calling SetTexture more then once? Right now I only have one texture page, and making the changes suggested here for just one page is a minor change from what I have. If I need to use more then one page, Ill need a big architectural change (before I was just using SetTexture for every quad, but if I shouldn't do that ...) Ill suppose Ill need to create sprite lists per texture page and render them in seperate batches.
Is there a matrix transform method to apply against a list of verts opposed to one vert at a time? I figure that will be more efficent then doing 4 individual matrix multiplies for each quad.
As far as camera transformations, those are bad? My main camera was going to move around over the playfield, but should I just transpose my sprites based upon the camera location instead?
On Vertexbuffer size, I heard there was some problems if it was too big or that you should never call DrawPrimitive() with more then a certain number of them at once. Is this true, how much is too much?
You said you just made a 2d space game. Are the sprites you used in the public domain? I haven't been able to find any space game sprites. So far I am using the 1942 sprites from the standard sprite lib. Id even be willing to buy a 'starter pack' of game artwork, but I can't find any for sale.
#16 Members - Reputation: 2008
Posted 01 October 2007 - 04:20 AM
Quote:It's not hugely expensive, but the main problem is that it breaks your batching - You'll need to submit two Draw calls to use two textures.
Quote:Is there a reason you don't use an orthogonal projection matrix, and let D3D do the vertex transform? That way you can take advantage of hardware vertex processing.
m_pRightAs far as camera transformations, those are bad? My main camera was going to move around over the playfield, but should I just transpose my sprites based upon the camera location instead?[/quote]I'd recommend using an orthogonal projection matrix. All transforms are effectively free, since they should be happening on the graphics card anyway.
Quote:I wouldn't make a dynamic vertex buffer over 4 or 8MB or so. I use 8192 verts just because that's what ID3DXSprite (The C++ version of the D3DX sprite) uses.
EDIT: Fixed by broken copy & paste :P
[Edited by - Evil Steve on October 1, 2007 12:20:10 PM]
#17 Members - Reputation: 122
Posted 01 October 2007 - 06:37 AM
Quote:
Errr what? I am drwaing 500 sprites that each have thier own rotation, scale and location. How do you define a matrix for 'these 4 verts' without a seperate draw command for each quad? You just have confused me.
#18 Members - Reputation: 2008
Posted 01 October 2007 - 06:44 AM
Quote:You're right, I'm an idiot [smile] Sorry, I totally forgot about rotation and scale...
You might be best off using a vertex shader for the rotation, although I'm not sure how easy that would be. Failing that, doing transforms on a per-vector basis is likely to be less efficient than transforming a lot at once, but only really because of the function call overhead. I wouldn't worry about it too much - don't go out of your way to get all the vectors to transform in one array, unless your data comes in that way anyway.
#19 Members - Reputation: 122
Posted 01 October 2007 - 09:30 AM
In the case I need to do it manually, I was thinking of this method, which may be way overboard.
Each sprite would have a reference to a matrix from a list of matrixes(whats the plural?) when each object updates its position before rendering starts (ie: the game object the sprite is attached to) it just updates the reference in this array.
Once I get down to the busniess of drawing, Ill just have a for-loop match the matrix in the index to the set of verts for the quad I am setting up. This way all the matrixes and verts will be in a solid block of memory and the caches should be able to predict the next memory Ill need and run much faster.
I do not know if this level of optimization is wasted on C# or not or if the yeild will be so small it will not be worth the extra code complexity. | http://www.gamedev.net/topic/466493-making-my-own-sprite-class/ | CC-MAIN-2015-48 | refinedweb | 3,852 | 62.48 |
Locks and unlocks sections of open files.
lockfx, lockf: Standard C Library (libc.a)
#include <fcntl.h>
int lockfx (FileDescriptor, Command, Argument) int FileDescriptor; int Command; struct flock *Argument;
#include <sys/lockf.h> #include <unistd.h>
int lockf (FileDescriptor, Request, Size) int FileDescriptor; int Request; off_t Size;
Note: The lockf64 subroutine applies to Version 4.2 and later releases.
int lockf64 (FileDescriptor, Request, Size) int FileDescriptor; int Request; off64_t Size;
#include <sys/file.h>
int flock (FileDescriptor, Operation) int FileDescriptor; int Operation;
Note: The lockf64 subroutine applies to Version 4.2 and later releases.
Attention: Buffered I/O does not work properly when used with file locking. Do not use the standard I/O package routines on files that are going to be locked.
The lockfx subroutine locks and unlocks sections of an open file. The lockfx subroutine provides a subset of the locking function provided by the fcntl subroutine.
The lockf subroutine also locks and unlocks sections of an open file. However, its interface is limited to setting only write (exclusive) locks.
Although the lockfx, lockf, flock, and fcntl interfaces are all different, their implementations are fully integrated. Therefore, locks obtained from one subroutine are honored and enforced by any of the lock subroutines.
The Operation parameter to the lockfx subroutine, which creates the lock, determines whether it is a read lock or a write lock.
The file descriptor on which a write lock is being placed must have been opened with write access.
lockf64 is equivalent to lockf except that a 64-bit lock request size can be given. For lockf, the largest value which can be used is OFF_MAX, for lockf64, the largest value is LONGLONG_MAX.
In the large file enabled programming environment, lockf is redefined to be lock64.
Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned and the errno global variable is set to indicate the error.
The lockfx, lockf, and flock subroutines fail if one of the following is true:
The lockfx and lockf subroutines fail if one of the following is true:
The flock subroutine fails if the following is true:
These subroutines are part of Base Operating System (BOS) Runtime.
The flock subroutine locks and unlocks entire files. This is a limited interface maintained for BSD compatibility, although its behavior differs from BSD in a few subtle ways. To apply a shared lock, the file must be opened for reading. To apply an exclusive lock, the file must be opened for writing.
Locks are not inherited. Therefore, a child process cannot unlock a file locked by the parent process.
The close subroutine, exec: execl, execv, execle, execlp, execvp, or exect subroutine, fcntl subroutine, fork subroutine, open, openx, or creat subroutine.
Files, Directories, and File Systems for Programmers in AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs. | https://sites.ualberta.ca/dept/chemeng/AIX-43/share/man/info/C/a_doc_lib/libs/basetrf1/lockfx.htm | CC-MAIN-2022-40 | refinedweb | 474 | 58.08 |
In recent months I played with QEMU emulation of an ARM Versatile Platform Board, making it run bare metal programs, the U-Boot boot-loader and a Linux kernel complete with a Busybox-based file system. I tried to put everything together to emulate a complete boot procedure, but it was not so simple. What follows is a description of what I’ve done to emulate a complete boot for an emulated ARM system, and the applied principles can be easily transferred to other different platforms.
Prerequisites
qemu-system-arm: can be installed on Ubuntu with “
sudo apt-get install qemu-kvm-extras“, on Debian with “
aptitude install qemu” as root.
mkImage: can be installed with the package
uboot-mkimage. Alternatively, it is compiled from U-Boot source.
arm-none-eabitoolchain: can be downloaded from the the CodeSourcery ARM EABI toolchain page
zImage: the Linux kernel created in my previous post here
rootfs.img.gz: the Busybox-based file system created in my previous post here
The boot process
On real, physical boards the boot process usually involves a non-volatile memory (e.g. a Flash) containing a boot-loader and the operating system. On power on, the core loads and runs the boot-loader, that in turn loads and runs the operating system. QEMU has the possibility to emulate Flash memory on many platforms, but not on the VersatilePB. There are patches ad procedures available that can add flash support, but for now I wanted to leave QEMU as it is.
QEMU can load a Linux kernel using the
-kernel and
-initrd options; at a low level, these options have the effect of loading two binary files into the emulated memory: the kernel binary at address
0x10000 (64KiB) and the ramdisk binary at address
0x800000 (8MiB). Then QEMU prepares the kernel arguments and jumps at
0x10000 (64KiB) to execute Linux. I wanted to recreate this same situation using U-Boot, and to keep the situation similar to a real one I wanted to create a single binary image containing the whole system, just like having a Flash on board. The
-kernel option in QEMU will be used to load the Flash binary into the emulated memory, and this means the starting address of the binary image will be
0x10000 (64KiB).
Understanding memory usage during the boot process is important because there is the risk of overwriting something during memory copy and relocation. One feature of U-Boot is self-relocation, which means that on execution the code copies itself into another address, which by default is
0x1000000 (16MiB). This feature comes handy in our scenario because it frees lower memory space in order to copy the Linux kernel. The compressed kernel image size is about 1.5MiB, so the first 1.5MiB from the start address must be free and usable when U-Boot copies the kernel. The following figure shows the solution I came up with:
At the beginning we have three binary images together: U-Boot (about 80KiB), Linux kernel (about 1.5MiB) and the root file system ramdisk (about 1.1MiB). The images are placed at a distance of 2MiB, starting from address
0x10000. At run-time U-boot relocates itself to address
0x1000000, thus freeing 2MiB of memory from the start address. The U-Boot command
bootm then copies the kernel image into
0x10000 and the root filesystem into
0x800000; after that then jumps at the beginning of the kernel, thus creating the same situation as when QEMU starts with the
-kernel and
-initrd options.
Building U-Boot
The problem with this solution is that U-Boot, when configured to be built for VersatilePB, does not support ramdisk usage, which means that it does not copy the ramdisk during the
bootm command, and it does not give any information about the ramdisk to the kernel. In order to give it the functionality I need, I patched the original source code of U-Boot before compilation. The following code is the patch to apply to
u-boot-2010.03 source tree:
diff -rupN u-boot-2010.03.orig/common/image.c u-boot-2010.03/common/image.c --- u-boot-2010.03.orig/common/image.c 2010-03-31 23:54:39.000000000 +0200 +++ u-boot-2010.03/common/image.c 2010-04-12 15:42:15.911858000 +0200 @@ -941,7 +941,7 @@ int boot_get_ramdisk (int argc, char *ar return 1; } -#if defined(CONFIG_B2) || defined(CONFIG_EVB4510) || defined(CONFIG_ARMADILLO) +#if defined(CONFIG_B2) || defined(CONFIG_EVB4510) || defined(CONFIG_ARMADILLO) || defined(CONFIG_VERSATILE) /* * We need to copy the ramdisk to SRAM to let Linux boot */ diff -rupN u-boot-2010.03.orig/include/configs/versatile.h u-boot-2010.03/include/configs/versatile.h --- u-boot-2010.03.orig/include/configs/versatile.h 2010-03-31 23:54:39.000000000 +0200 +++ u-boot-2010.03/include/configs/versatile.h 2010-04-12 15:43:01.514733000 +0200 @@ -124,8 +124,11 @@ #define CONFIG_BOOTP_SUBNETMASK #define CONFIG_BOOTDELAY 2 -#define CONFIG_BOOTARGS "root=/dev/nfs mem=128M ip=dhcp "\ - "netdev=25,0,0xf1010000,0xf1010010,eth0" +/*#define CONFIG_BOOTARGS "root=/dev/nfs mem=128M ip=dhcp "\ + "netdev=25,0,0xf1010000,0xf1010010,eth0"*/ +#define CONFIG_BOOTARGS "root=/dev/ram mem=128M rdinit=/sbin/init" +#define CONFIG_BOOTCOMMAND "bootm 0x210000 0x410000" +#define CONFIG_INITRD_TAG 1 /* * Static configuration when assigning fixed address
I also changed the boot arguments (
CONFIG_BOOTARGS)so that they are the same as those given from QEMU command line, and then added a command (
CONFIG_BOOTCOMMAND) to start the Linux boot automatically. To apply the patch:
- save the patch to a file, for example
~/u-boot-2010.03.patch
- download u-boot-2010.03 source tree and extract it, for example in
~/u-boot-2010.03
cdinto the source tree directory
- apply the patch, for example with “
patch -p1 < ~/u-boot-2010.03.patch“
After applying the patch, U-Boot can be built as seen in my previous post:
make CROSS_COMPILE=arm-none-eabi- versatilepb_config make CROSS_COMPILE=arm-none-eabi- all
The building process will create a
u-boot.bin image that supports ramdisks for the VersatilePB. Incidentally, it will also build the
mkimage executable in the
tools directory; it can be used instead of the one installed with Debian/Ubuntu packages.
Creating the Flash image
As I said earlier, I need to create a flash image in which the three binary images are placed at a distance of 2MiB. U-Boot needs to work with binary images wrapped with a custom header, created using the
mkimage tool. After creating the Linux and root file system images, we can write them inside a big binary at a given address with the
dd command. Assuming that we have in the same directory:
u-boot.bin,
zImage and
rootfs.img.gz, the list of commands to run are:
mkimage -A arm -C none -O linux -T kernel -d zImage -a 0x00010000 -e 0x00010000 zImage.uimg mkimage -A arm -C none -O linux -T ramdisk -d rootfs.img.gz -a 0x00800000 -e 0x00800000 rootfs.uimg dd if=/dev/zero of=flash.bin bs=1 count=6M dd if=u-boot.bin of=flash.bin conv=notrunc bs=1 dd if=zImage.uimg of=flash.bin conv=notrunc bs=1 seek=2M dd if=rootfs.uimg of=flash.bin conv=notrunc bs=1 seek=4M
These commands do the following:
- create the two U-Boot images,
zImage.uimgand
rootfs.uimg, that contain also information on where to relocate them
- create a 6MiB empty file called
flash.bin
- copy the content of
u-boot.binat the beginning of
flash.bin
- copy the content of
zImage.uimgat 2MiB from the beginning of
flash.bin
- copy the content of
rootfs.uimgat 4MiB from the beginning of
flash.bin
At the end we have a binary image,
flash.bin, containing the memory layout that I had in mind.
Booting Linux
To boot Linux we can finally call:
qemu-system-arm -M versatilepb -m 128M -kernel flash.bin -serial stdio
The U-Boot-related messages will appear on the console:
U-Boot 2010.03 (Apr 12 2010 - 15:45:31) DRAM: 0 kB ## Unknown FLASH on Bank 1 - Size = 0x00000000 = 0 MB Flash: 0 kB *** Warning - bad CRC, using default environment In: serial Out: serial Err: serial Net: SMC91111-0 Hit any key to stop autoboot: 0 ## Booting kernel from Legacy Image at 00210000 ... Image Name: Image Type: ARM Linux Kernel Image (uncompressed) Data Size: 1492328 Bytes = 1.4 MB Load Address: 00010000 Entry Point: 00010000 ## Loading init Ramdisk from Legacy Image at 00410000 ... Image Name: Image Type: ARM Linux RAMDisk Image (uncompressed) Data Size: 1082127 Bytes = 1 MB Load Address: 00800000 Entry Point: 00800000 Loading Kernel Image ... OK OK Starting kernel ... Uncompressing Linux... done, booting the kernel.
Then the Linux kernel will execute inside the emulated screen and the message “
Please press Enter to activate this console” will appear, indicating that the root file system is working and so the boot process completed successfully. If something doesn’t work, one can always check that the system works without U-Boot, with the following command:
qemu-system-arm -M versatilepb -m 128M -kernel zImage -initrd rootfs.img.gz -append "root=/dev/ram mem=128M rdinit=/sbin/init" -serial stdio
The kernel should uncompress and execute up to the activation of the console.
This procedure has room for improvements and optimizations, for example there’s too much memory copying here and there, where mostly everything can be executed in place. It is anyway a nice exercise and a good starting point that reveals interesting details about the boot process in embedded systems. As usual, this is possible mainly due to the fact that all the tools are free and open source.
Howimboe
2010/04/19
Thx for the tuto, works perfectly with custom rootfs, host running last Ubuntu.
Jon Rios
2010/09/29
First of all, thank you very much for all the tutorials you have written in the blog, they have been very useful for me.
I’m trying to configure an ARM emulation enviroment consisting in QEMU+U-Boot+Busybox.
I followed all the steps to create the linux kernel image (linux kernel version 2.6.34.7) and the busybox file system (busybox version 1.17.2) with the other tutorials you have in the blog.
Also I created the flash.bin image as described in this post.
The problem is that when I try to execute qemu with the flash as kernel, I get nothing but a black screen.
No errors
No u-boot messages
No kernel messages
Do you know what can I do or where the problem can be?
Thank you for your attention
Balau
2010/09/29
The screen should be black at first, but the terminal should show the autoboot countdown and some other messages. If you see nothing on the terminal, then surely the problem is not in Linux or Busybox. Are you using u-boot version 2010.03? Try to make just u-boot work, once you have created
u-boot.bin, with the following command:
$ qemu-system-arm -M versatilepb -m 128M -kernel u-boot.bin -serial stdio
The autoboot should fail and it should display a prompt on the terminal.
Check also if the following command works (it skips u-boot):
$ qemu-system-arm -M versatilepb -m 128M -kernel zImage -initrd rootfs.img.gz -append "root=/dev/ram mem=128M rdinit=/sbin/init" -serial stdio
Jon Rios
2010/09/29
Hi, thanks for the fast response.
I am using U-boot 2010-03 and also I tried with 2010-09.
Each component separately works fine. I mean, executing only u-boot fails on loading the image but it shows the prompt.
Also running busybox with the linux kernel works fine.
With this info, the only thing I think it could be wrong may be the flash.bin file, but I’m sure I made it right as explained in this post.
Balau
2010/09/29
Try to run:
$ hexdump -C u-boot.bin |head >u-boot.hex
$ hexdump -C flash.bin |head >flash.hex
$ diff u-boot.hex flash.hex && echo OK
The two dumps should be equal.
Is any of the binaries composing the flash bigger than 2MB? Because I assumed they were smaller and spaced them accordingly on the flash.
Jon Rios
2010/09/29
Ok, I found the problem. It was I was using the dd command wrong. When the pc is creating the 6M file, the console doesn’t write anything. I interpreted this as I must enter then the rest of dd commands. And when I end entering this, I was terminating the first proccess.
The result was a blank file.
Thank you for helping me realize this and congratulations for the great info you have in the blog. All is workin fine now-
Balau
2010/09/30
Glad to help!
Robert Smith
2010/10/01
Hello,
Thank you for your tutorial.
It seems to me that something is missing in the text of your u-boot patch.
My browser shows 29 lines and last two of them are open comment:
28 /*
29 * Static configuration when assigning fixed address
May be something wrong with my browser, I use Firefox 3.6.10 under Ubuntu 9.10?
Can you clarify.
Thanks
Balau
2010/10/01
It’s just context that helps the “patch” program to verify that it is indeed modifying the right piece of code. The lines that are actually changed in the patch are those with “+” or “-” as the first character of the line. See
satya prakash
2010/12/29
hi everyone,
Currently i’m working on arm-linux(embedded system).
The process of my booting up is that initially i have got a bootloader(u-boot) which initializes kernel and then kernel takes care of rest. But can anyone please tell me a more regarding the basics:
1) What happens when initially the board is powered on or reset(beginning from cpu)?
2)bootloader initializes kernel, but who initializes bootloader? I mean something should be there which is activated by default on being powered up or reset, which in turn must be starting bootloader? (this is what i think)
I have tried to search in google regarding this, but everywhere i get the results directly beginning from uboot, but who starts uboot, that i haven’t found upto now.
Can anyone please help me regarding these basics?
If possible, please provide me with the links where i can get these details both from hardware and software point of view.
thanking in advance,
With regards,
sattu
Balau
2010/12/29
The answer depends on the hardware system you are using. For example if you are using a BeagleBoard it’s different than using a RealView versatile board. QEMU has its own implementation of the boot, that prepares the minimum for a Linux kernel and then jumps to address
0x10000, and is very different than what real hardware does.
Usually you have a ROM at a particular address (can be
0x00000000or
0xFFFF0000, …) that executes when the hardware is reset. It should turn on the clocks and it should configure the memory interfaces, then it can jump to a fixed address or load some code from Flash and execute it. This procedure and its code is very specific to the architecture so you should find the information on the manual of the hardware platform.
Here are a couple of links for the Beagleboard:
The Android boot process from power on
satya prakash
2010/12/30
Oh sorry balau, thanks for your reply but i forgot to mention the details regarding the board. It’s using a soc called S3C2440 having arm9 architecture. Can you please send me a mail i.d of yours(yahoo, gmail or rediff) so that i can mail you the introductory pdf regarding the board i’m working upon.
with regards,
sattu
satya prakash
2010/12/30
By the way balu, you have sent me the link regarding android boot process. As far as i know, Android is nothing but a different flavour of linux. So, can you send me any links where it will be mentioned regarding the boot process of embedded linux(2.6.30.4) specifically. The link that you have sent regarding the android is really conceptual and to the core. As far as i feel, almost the same principle would be working for linux. Still, if you can explain me regarding the exact booting process of embedded linux or atleast send me some links, dat would really be great. Looking forward for your help. :)
Balau
2010/12/30
Dear Sattu,
my mail is in my About Me page.
I never looked in details the internal process of Linux booting, but I’m expecting that it’s very similar (if not the same) for Android and for any Linux distribution for ARM.
The Linux kernel itself contain some information that can be useful:
ARM Booting
Samsung-S3C24XX documents
nguyễn văn đạt
2011/01/18
i thank you, but why when i do follow your instruction then it error message:
“Failed to execute /init
Kernel panic – not syncing: No init found. Try passing init= option to kernel.”
you can see picture
Balau
2011/01/18
First things that come to mind:
– have you set the execution bit of “sbin/init” with “cmod +x” ?
– have you tried this simpler exercise, and does it work?
Adithya
2011/01/25
Hello,
Can u plz suggest me a way, by which we can pass a Device Tree from U-Boot to the linux kernel on ARM platform. I want to pass only a subset of the available hardware to the linux kernel.
Thank you in advance.
nguyễn văn đạt
2011/01/25
– have you set the execution bit of “sbin/init” with “cmod +x” ?
by how set execution when Qemu cant input keyboard ?
Balau
2011/01/25
I don’t know how to do it currently but I know they are actively working on it, especially Grant Likely of Secretlab.
The last update I have read for Device Tree support on ARM is the following presentation: ARM Device Tree status report.
Balau
2011/01/25
nguyễn văn đạt, sorry, I meant on your host computer, before creating the filesystem with “cpio”.
Mohd Anuar
2011/02/21
Nice tutorial! Good job Balau! Even myself is a MS Windows programmer/researcher (allergies to Linux) capable to complete this short course. huh.. it’s take 1 1/2 weeks to complete (+ understand Linux + Embedded).
william estrada
2011/03/01
Hello,
I’m trying to test my embedded kernel under qemu. Having problems creating the DRAM file. I am using this script:
sudo virsh net-start default
rm DRAM > /dev/null 2>&1
dd if=/dev/zero of=DRAM bs=1024 count=256
sudo qemu-system-arm -M versatilepb -m 256 \
-pflash DRAM \
-nographic -kernel u-boot \
-net nic,macaddr=00:16:3e:00:00:01 \
-net tap,vlan=0,ifname=vnet1
But I get this error:
U-Boot 1.1.6 (Feb 27 2011 – 12:25:20)
DRAM: 0 kB
Flash: 0 kB
*** Warning – bad CRC, using default environment
In: serial
Out: serial
Err: serial
Do you have any suggestions??
Balau
2011/03/01
If your problem is the “-pflash” support, you can try these instructions : Using U-Boot and Flash emulation in Qemu
Other than that, you can try a newer u-boot version like the 2010.03, since you are using a version 1.1.6) of 5 years ago and maybe they fixed something.
You can also see that I have similar errors in my output (no DRAM and no Flash), but the execution continues correctly because everything is in RAM.
Vidur Garg
2011/03/13
Hello Balau ,
Thanks a lot for all the posts ! They’ve been highly informative.
Well, I was trying out the different meathods booting linux , and for the most part it worked fine .
In this case however , while execting qemu , i don’t get the auto boot message but get the uboot promt instead.
So I thought i’ll enter bootm 0x0021000 after looking into the figure. This worked and kernel bootup continued. When it came to the rootfs part , the rootfs wasn’t detected. So instead i used bootm 0x0021000 0x0041000 .. didnt solve the problem .
Could you please help me out ?
Balau
2011/03/13
I think you miss some “zeros” at the end of the address you are using. they should be “0x210000” and “0x410000”
In case you have only typed it wrong in this comment but you are using the right addresses in your tests:
What does it say inside the U-Boot prompt if you run “iminfo 0x210000” and “iminfo 0x410000”?
If U-Boot doesn’t auto-boot maybe there’s something wrong in the patching or in the compilation. It should at least give you the same messages that you get when you run “bootm 0×00210000 0×00410000” by yourself. Can you check by using “-kernel u-boot.bin” in the qemu-system-arm command instead of “flash.bin”? It should fail but give you some error messages about booting. In this case, the problem is the creation of the “flash.bin” image with “dd” command. Also, are all the three files that compose “flash.bin” below 2MiB in size?
Vidur Garg
2011/03/14
Hello , thanks for the reply . The zeros were just a typo.
Its now working .. the patching was the issue. instead this is what i did :
After looking through the patch file i modified the image.c file and added : || defined (CONFIG_VERSATILE)
and in the versatile.h i added
#define CONFIG_BOOTARGS “root=/dev/ram mem=128M rdinit=/sbin/init”
#define CONFIG_INITRD_TAG 1
didn’t add the bootm command as i had to create a larger flash.bin file as the rootfs.uimg was over 3 MB , and so had different memory values.
Nevertheless , it works fine . Thanks a ton !
Adithya
2011/04/05
Hey Balau,
What is the difference between “.axf” file and “.bin”. Will the above mentioned procedure work for the u-boot image with .axf extension.
Thanks in Advance.
Regards
B. Adithya
Balau
2011/04/05
“.axf” is an executable file, with ELF format, that contains the code and data, but also information about the loading address, sections information, debugging symbols… It is usually run by a simulator or a debugger.
“.bin” is a pure binary file, containing the code and data that can be written inside a Flash to be run by an hardware platform.
If you run QEMU passing an ELF file with the kernel option, QEMU should be able to recognize the executable. But if you create a binary flash image like I do in my example, and put the .axf file inside it, it could not work.
If you have an “.axf” file, you can generate easily a “.bin” file using the “arm-*-objcopy” (in case of GCC toolchains) or “fromelf” (in case of RVDS) tools.
Adithya
2011/04/21
Hello Balau, I get this error when i try to boot the flash.bin. Both u-boot and zImage boot properly individually. Could you please tel me where i am going wrong.
Wrong Ramdisk Image Format
Ramdisk image is corrupt or invalid
Adithya
2011/04/21
Contd … from above,
I think i forgot to add the file system in the previos comment, Now when i add the filesystem, i get the following error:
Image Name:
Image Type: ARM Linux RAMDisk Image (uncompressed)
Data Size: 1118941 Bytes = 1.1 MB
Load Address: 00800000
Entry Point: 00800000
OK
Starting kernel …
Uncompressing Linux….qemu: fatal: Bad mode 0
R00=73200000 R01=00000000 R02=00000000 R03=c035c804
R04=00000000 R05=e91d7679 R06=00000000 R07=00000000
R08=ffffffff R09=00000000 R10=73200000 R11=73200000
R12=001be704 R13=fffff0d0 R14=700100f4 R15=70023160
PSR=200001db –C- A und32
Aborted (core dumped)
Can u help me plz !!!
Balau
2011/04/21
It seems to me that the code goes into an “undefined” exception, as the PSR value say (The 32 bit PSR) and then the code somehow tries to change the mode to 0 (the code that exits QEMU can be found in the QEMU source, file “target-arm/helper.c”
The registers R14 (link register) and R15 (program counter) have strange values: at memory address 0x70023160 should not be any memory and so any code.
Does the zImage still work individually?
Dan
2011/07/16
Hi, Balau,
In your example, u-boot, Linux kernel, and rootfs are placed at the distance of 2MiB in flash.bin. Is this 2MiB required by u-boot or QEMU. I suspect it is u-boot, right? But I am a little confused because this would limit the kernel size to be less than 2MiB. Also will the flash be loaded at 0x10000 (64KiB) so that QEMU can load u-boot?
Thanks for your contributions!
Dan
Balau
2011/07/16
Actually the 2MiB size is not required, neither by U-Boot nor by Linux. I chose that size because the images of the three components were all less than 2MiB and I needed an easy way to know where they are. You can change that distance if you want, and it doesn’t need to be the same, it could be 3MiB and 5MiB, the only requirement is that it has enough space to contain the binary files. Once you create a flash.bin file with different placement, you must change the U-Boot “bootm” command with the right addresses.
Dan Guo
2011/07/16
Hi, Balau,
Thanks for your reply!
But how could QEMU know these three binaries are 2MiB apart in flash.bin?
Thanks a lot,
Dan
Balau
2011/07/17
QEMU doesn’t need to know. The binary you give to QEMU with the “-kernel” option is placed at 0x10000, then the execution starts at that address. It is U-Boot that needs to know where the kernel and root filesystem are placed, and you need to pass this information with the “bootm” command.
Dan Guo
2011/07/17
Dear Balau,
Thanks a lot for your explanation! I believe “bootm 0x210000 0x410000” in your patch will let u-boot know that the kernel and file system are placed at a distance of 2MiB.
Bests,
Dan
Gareth Ferneyhough
2011/07/21
Thanks very much for the tutorials; they all work wonderfully! Now I hope to get an open core Microblaze clone (openfire2) working on my Spartan3e starter kit board. Then I will hopefully reproduce these experiments on real hardware and be on my way!
-Gareth
srinivas
2011/09/12
Hi Balau,
I am very grateful to your well organized and informative posts.
I am facing an issue while using qemu for booting with flash.bin.
Error:
“can’t open /dev/tty3: no such file or directory” message is being displayed repetitively.
If use ‘ls’ command File system directories are displaying.
Best Regards
Srinivas
Balau
2011/09/12
Maybe the “/dev” directory is not populated correctly, so there could be a problem in “/etc/init.d/rcS” file. Can you check that your rcS file is executable?
srinivas
2011/09/14
Hi Balau,
Again On error after starting qemu with flash.bin
“can’t open /dev/tty3: no such file or directory” message is being displayed repetitively.
On My Host PC(ubuntu-11.04) /etc/init.d/rcS is executable for root.
On QEMU terminal there is no /etc directory.
I tried to execute below command using root privileges but still problem exists.
command:
sudo qemu-system-arm -M versatilepb -m 128M -kernel flash.bin
Could you please tell me what might be the problem.
— Srinivas
Balau
2011/09/14
If you don’t have an /etc directory inside QEMU terminal then the rootfs image file has not been generated correctly.
On your host PC the “/etc/init.d/rcS” is not important, and executing “QEMU” with sudo does not change things. What is important is your custom rcS file that I created in my previous post here:
In my tutorial the file must be placed in “_install/etc/init.d/rcS” into the busybox source tree after busybox compilation. Then with the “cpio” command you create a root filesystem image from the _install directory, and it must contain the local “etc” directory that must appear in the QEMU terminal when you do “ls /”
I hope it’s more clear now.
srinivas
2011/09/15
Hi Balau,
Thank you very much for your quick reply.
Now It’s working. I didn’t fallow your busybox post completely
Thanks
Srinivas
Srinivas
2011/09/26
Hi Balau,
I want to get familiarization with u-boot code for versatile PB.
For that I want use GDB on Qemu. Could you please provide info
for using GDB on QEMU(How to). And also could you please provide good URL’S or docs for learning u-boot functionality from scratch.
Balau
2011/09/26
QEMU can easily act as a GDB server. When QEMU is run with the “-s -S” options, it will start waiting for a GDB connection on port 1234. Then you can connect using the “target remote localhost 1234” command inside a GDB session. See also my old post Hello world for bare metal ARM using QEMU for an example on debugging a bare metal ARM program, such as U-Boot.
Keep in mind that on Ubuntu the QEMU package does not support debugging very well. I had to compile it from source to make it work.
Debugging U-Boot is a little more complicated because it relocates itself. In this page there is a tutorial on how to debug it: Debugging of U-Boot. When you make the u-boot.elf program the debugging symbols should already be included by default (i mean the “-g” option of GCC).
There is much information in the “README” file inside the U-Boot source tree, and some other things in the “doc” directory, but I don’t think there is documentation to explain the internals of the source code.
omer
2011/10/21
Hi Balau,
I want to install linux on arm6410 with sd card or usb.but,when i insert the sd card to arm6410 i can see the documents in the sd card but i can’t start the boot linux.for that what i must do to firstly.can you examine the first steps. or after insert sd card ,must i write some commands for starting install linux. thanks for answer.
Balau
2011/10/22
Unfortunately I am not familiar with the hardware you’re working on. I suppose the hardware came with a manual, so maybe there’s some information about the boot procedure there. The boards often have some configuration switches that change the way the processor behaves during boot (for example they might have a “Boot from SD” configuration).
I think that you need to prepare the SD card from a PC, using a procedure similar to the one I used in this post and then writing directly on the SD card block device instead of a binary file. Then you can insert the SD card in the board and try to boot. I never did this procedure myself, though.
Grant Likely
2011/11/01
For anyone trying to reproduce this, at least on a recent Ubuntu host, you may need to pass “-cpu all” or “-cpu cortex-a8” to qemu. The libgcc that gets linked to u-boot appears to be compiled with thumb2 instructions which are not implemented in the Versatile cpu.
I don’t get any u-boot console output without this flag, and using gdb I can see that the cpu takes an exception during __udivsi3() called from serial_init().
Grant Likely
2011/11/01
Oops, I got the option wrong. Make that “-cpu any”.
Balau
2011/11/03
Thanks for commenting, Grant. As an aside, I really appreciate your work.
The toolchain has “multilibs” and should link the correct libraries based on compiler flags. If I have time I’ll take a look, maybe it’s just a matter of configuring U-Boot for the correct ARM architecture, because the default expects a newer (thumb2-capable) processor.
Ritu
2012/01/27
Hello Balau, This information is really helpful for getting started. I was trying trying to get the same up in Ubuntu. I have not been able to build the image u-boot.bin. I made the patch fixes mentioned above but I am getting some undefined reference errors. Some of the errors are pasted below for reference:
lib_arm/libarm.a(board.o): In function `start_armboot’:
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board.c:304: undefined reference to `flash_init’
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board.c:414: undefined reference to `copy_filename’
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board.c:434: undefined reference to `eth_initialize’
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board.c:442: undefined reference to `BootFile’
lib_arm/libarm.a(board.o):(.data+0x8): undefined reference to `env_init’
lib_arm/libarm.a(board.o):(.data+0x10): undefined reference to `serial_init’
common/libcommon.a(cmd_bootm.o): In function `bootm_load_os’:
Pls suggest if I am missing anything in the setup.
Thanks
Ritu
Balau
2012/01/27
In my “uboot.map” file that is generated I see that all the functions are present in linking stage:
flash_init: drivers/mtd/libmtd.a(cfi_flash.o)
copy_filename: net/libnet.a(net.o)
eth_initialize: net/libnet.a(eth.o)
BootFile: net/libnet.a(net.o)
env_init: common/libcommon.a(env_flash.o)
serial_init: drivers/serial/libserial.a(serial_pl01x.o)
I suggest re-trying again from a clean state using “make distclean” and then redoing the “make CROSS_COMPILE=arm-none-eabi- versatilepb_config” and “make CROSS_COMPILE=arm-none-eabi- all” commands in my post.
If even that doesn’t work, you can retry by setting environmental variable “export ARCH=arm” and recompile.
Hope this helps.
tanaka
2012/02/02
is flash emulation now support in latest qemu.15.0 for arm versatilepbqemu platform?
Balau
2012/02/02
From a quick look at the source code it seems it’s not been added. The VersatilePB is an old hardware so I suppose it may never gain flash support in QEMU.
eng trojan
2012/02/14
now i make the steps as good as i can but when i finally release flash.bin and try to simulate it on qemu i have this error
R00=00000000 R01=33fb9880 R02=00049868 R03=00000000
R04=00000000 R05=00000000 R06=00000000 R07=00000000
R08=00000000 R09=00000000 R10=00000000 R11=00000000
R12=000100fc R13=00000000 R14=000100fc R15=33f801f4
PSR=800001d3 N— A svc32
Aborted
but when i try to simulate without u-boot just with rootfs and zimage, it works good
first i was working with version of u-boot 1.7 , i expected that it was the error but i used the mentioned version in your explain and applied the patch and tried to make flash.bin again but i have the same error :(
Balau
2012/02/14
I replied in this comment.
Patrick
2012/03/14
Hi Balau, I am following your procedure to run the latest linux kernel (stable version, 3.2.10) on an imx51 Freescale board with a cassini root filesystem of GenIVI. The uImage that I generate from my kernel zImage is 2.3MB and I packed it into my boot partition. However it turns out that the rootfile system(a .tgz file) which I downloaded is 723MB and when I tar it into my rootfs partition it has a size of 1.7GB. Is there some mistake? I am not able to correctly set the u-boot parameters as I am confused. I have the u-boot.imx after compiling u-boot sources.This is what I have:
sudo dd if=u-boot.imx of=${DISK} seek=1 bs=1024
Followed by setting of the partitions as follows:
unallocated: 5MB
fat16:boot: 50MB
ext4:rootfs:3.6GB(rest of the 4GB SD card)
I then copy the uImage, boot.scr to the boot partition and then I tar © the rootfs.tgz and kernel sources to the rootfs.
Here is what I set in boot.scr:
setenv bootcmd ‘fatload mmc 0:1 0x90800000 uImage; bootm 0x90800000’
setenv bootargs console=ttymxc0,115200 console=tty0 root=/dev/mmcblk0p2 rootwait ro rootfstype=ext4 mxcdi1fb:1280x720M@60
boot
How do I set the right addresses in the above file? I don’t understand it :(
Perhaps because of this, while I boot up my imx device: I get the following message:
U-Boot 2011.12 (Mar 13 2012 – 14:15:41)
CPU: Freescale i.MX51 family rev3.0 at 800 MHz
Reset cause: POR
Board: MX51EVK
DRAM: 512 MiB
WARNING: Caches not enabled
MMC: FSL_SDHC: 0, FSL_SDHC: 1
MMC: no card present
MMC init failed
Using default environment
In: serial
Out: serial
Err: serial
Net: FEC
Warning: failed to set MAC address
Hit any key to stop autoboot: 0
MMC: no card present
Booting from net …
BOOTP broadcast 1
BOOTP broadcast 2
Balau
2012/03/14
I’m sorry but my method will not work with a root filesystem that big. My method can be used to boot an intermediate initrd (ramdisk) that is able to load some modules and boot the real root. Depending on your hardware you can place the root filesystem on a server on the network, on an SD card, an USB disk/flash or a SATA drive. More information on the usage of initial ramdisk can be found in kernel source in “Documentation/initrd.txt”
Amit kumar
2012/03/19
qemu-system-arm -M versatilepb -m 128M -nographic -kernel u-boot.bin
when i m giving this command then it is saying command not found….
Balau
2012/03/19
It means the “
qemu-system-arm” program has not been correctly installed. The installation depends on the Linux distribution you are using, I already specified the steps in the “prerequisites” section. Be aware that this article has been written in 2010 so the way to install “
qemu-system-arm” may have changed.
Amit
2012/03/27
Hi Balau,
I have build my toolchain through buildroot. while building uboot I am getting following errors
board.c: In function ‘__dram_init_banksize’:
board.c:233: error: ‘CONFIG_SYS_SDRAM_BASE’ undeclared (first use in this function)
board.c:233: error: (Each undeclared identifier is reported only once
board.c:233: error: for each function it appears in.)
board.c: In function ‘board_init_f’:
board.c:279: error: ‘CONFIG_SYS_INIT_SP_ADDR’ undeclared (first use in this function)
board.c:312: error: ‘CONFIG_SYS_SDRAM_BASE’ undeclared (first use in this function)
make[1]: *** [board.o] Error 1
make[1]: Leaving directory `/home/timberline/Android_devel/u-boot-2011.03/arch/arm/lib’
make: *** [arch/arm/lib/libarm.o] Error 2
Balau
2012/03/27
It’s not a problem of toolchain, it’s a problem of u-boot version. There are some versions in which old hardware does not compile properly because they changed some of the internals. If you try to do the same with the 2010.03 or 2011.12 they should compile fine.
Jerzy
2012/04/02
qemu-system-arm -kernel file -initrd file …
What are the QEMU default load address’s for the kernel and initrd files?
Balau
2012/04/02
In the post I already wrote:
Sorry but I don’t understand what information that you need is not present in this sentence.
Jerzy
2012/04/03
Hi Balau,
Thank for your reply.
My question is :
What are the QEMU default load address’s into the emulated memory – not in this case but generally – for the kernel and initrd files without using U-Boot, in command like this
qemu-system-arm -kernel file -initrd file …
Balau
2012/04/03
The default addresses are indeed
0×10000for the kernel and
0×800000for the initrd.
I think I have confused you because in my example I used the same addresses for U-Boot booting.
My plan was:
– I see what QEMU does when I pass kernel and ramdisk from command line
– I recreate the same state using U-Boot
The result is that after the
bootmcommand, the kernel and the ramdisk are in the same addresses that they would have been if I passed them to QEMU from the command line.
I hope I have clarified the situation.
Jerzy
2012/04/13
Is it possible to launch successfull QEMU in the way like this
qemu-system-arm -M versatilepb -m 128M -kernel flash.bin -initrd rootfs.img.gz -serial stdio
where flash.bin = u-boot.bin + zImage.uimg ?
Balau
2012/04/14
When U-Boot executes “
bootm 0x210000 0x410000” it copies the two images into their load addresses and then launches Linux with some parameters.
If you run QEMU as you want to do, you already have the ramdisk in place. For this reason, you don’t need the second argument to
bootm, but you need to tell the kernel that the ramdisk is there. For this, I think you can append “
initrd=0x800000” to the
BOOTARGSthat U-Boot passes to Linux.
Jerzy
2012/04/14
Did you try to do it?
I set of course
#define CONFIG_BOOTCOMMAND “bootm 0x210000”
in UBOOT versatile.h file, and prepared flash.bin
mkimage -A arm -C none -O linux -T kernel -d zImage -a 0x00010000 -e 0x00010000 zImage.uimg
dd if=/dev/zero of=flash.bin bs=1 count=4M
dd if=u-boot.bin of=flash.bin conv=notrunc bs=1
dd if=zImage.uimg of=flash.bin conv=notrunc bs=1 seek=2M
I launched qemu
qemu-system-arm -M versatilepb -m 128M -kernel flash.bin -initrd rootfs.img.gz -serial stdio
Next I stopped it in UBOOT and checked memory
VersatilePB# md.b 0x800000 1000
There wasn’t contents of rootfs.img.gz but only 000…
Balau
2012/04/14
You are right: I just tried and the ramdisk is placed at
0xd00000instead.
I discovered this address my doing “
md 0 64” and inspecting the data that looked like an address.
Then I misinterpreted the initrd parameter, it should be something like “
initrd=0xd00000,2M“, where the value after the comma is the size of the ramdisk (I rounded by eccess).
With these modifications it works for me.
Jerzy
2012/04/16
Thanks Balau.
Any idea why in this case ramdisk is placed at 0xd00000 instead at 0x800000?
Balau
2012/04/16
No idea, but I haven’t investigated either.
It might have something to do with the kernel binary size, but it may also have been changed in QEMU source code.
In my opinion it should not change anything relevant, we could just accept the fact that the ramdisk is placed at an arbitrary address.
Jerzy
2012/04/17
I’d like to launch linux in QEMU, in the way like this
qemu-system-arm –M versatilepb –kernel flash.bin –initrd rootfs.img.gz …
Suppose that I’d like to pass to the linux kernel the following parameters :
console=ttyAMA0 root=/dev/ram rw initrd=0xd00000,2M
Generally, I can pass these parameters, through :
– append option in qemu command
– bootargs in UBOOT environment
– Boot options->kernel command string (at the time of kernel configuration)
It is possible to pass them in every of this mentioned above way but only in one at once?
Sometimes I’ve kernel image compiled with some parameters in kernel command string and u-boot.bin compiled with other parameters in bootargs. At time of software developing the most comfortable way for me is to change the kernel parameters in qemu command in append option.
Can I launch linux in QEMU in the way mentioned above with different parameters in qemu line, u-boot.bin and kernel image? If yes, which parameters will be passed to linux kernel?
Balau
2012/04/17
The kernel parameters in your case are those passed by U-Boot. The one in QEMU “-append” option never reach the kernel.
This is because QEMU prepares ATAGS that U-Boot does not read, and then U-Boot prepares its own ATAGS (from bootargs) to be passed to the kernel.
See Documentation/arm/Booting.txt for information about what should be passed to Linux kernel.
In physical world scenario, U-Boot saves its environment in the flash, so you can have an U-Boot image with default parameters, and then a sector of the flash that contains your parameters.
Are you sure you need to use U-Boot? If you don’t use U-Boot then you can pass the kernel parameters with QEMU without problems.
Jagan
2012/06/23
I have a problem with booting Linux on versatilepb through QEMU.
I have used root=/dev/ram rw…
but still my FS not mounted…Can you help me whether I am missing any bootargs..
Here is the tail logs:
———————–
List of all partitions:
1f00 65536 mtdblock0 (driver?)
No filesystem could mount root, tried: ext2 cramfs minix romfs
Kernel panic – not syncing: VFS: Unable to mount root fs on unknown-block(1,0)
[] (unwind_backtrace+0x0/0xf4) from [] (panic+0x74/0x1c0)
[] (panic+0x74/0x1c0) from [] (mount_block_root+0x1e8/0x228)
[] (mount_block_root+0x1e8/0x228) from [] (mount_root+0xcc/0xf0)
[] (mount_root+0xcc/0xf0) from [] (prepare_namespace+0x160/0x1b8)
[] (prepare_namespace+0x160/0x1b8) from [] (kernel_init+0x158/0x19c)
[] (kernel_init+0x158/0x19c) from [] (kernel_thread_exit+0x0/0x8)
Balau
2012/06/24
You can’t know if you missed any bootargs by looking only at the tail of the log.
You could add “
console=ttyAMA0” to the current bootargs (and QEMU must be launched with “
-serial stdio“) to display more info on the terminal.
Try to find a line near the beginning of the log starting with “
Kernel command line:“. Those are the bootargs.
Then in the middle of the log you should find a line such as “
Trying to unpack rootfs image as initramfs...“. The lines around that could contain useful hints about why the kernel isn’t mounting the filesystem.
Jagan
2012/06/24
Exactly..I missed to give you the details about boot args.
setenv bootargs ‘console=ttyAMA0,115200n8 root=/dev/ram rw’
I have created uImage loaded at addr1 and created ramdisk of mkimage compatible loaded at
addr2 (addr1 > addr2).
I did below command
$ bootm $addr1 $addr2
Balau
2012/06/24
Where’s the “
rdinit=...” bootarg? Why did you remove it?
Jagan
2012/06/24
No, I just need to mount ramdisk not any other app or init file.
I think rdinit required for explicit app running…correct me If am wrong
Balau
2012/06/25
The kernel has to run something (in userspace) when the boot ends, otherwise it panics. This “something” is usually the
initprogram.
I don’t know if using both “
root=/dev/ram” and “
rdinit=/sbin/init” is the cleanest way to do it, but I noticed that without “
rdinit” the kernel does not try to mount the ramdisk and so it panics.
Jagan
2012/06/27
Let me clear the entire scenario.
I have uImage and ramdisk with mkimages.
like uramdisk.img
uImage – load and entry address are 0x800
uramdisk -load and entry address are 0x800000
$ tftp 0x100 uImage
$ tftp 0x4000000 uramdisk.img
$ setenv bootargs ‘console=ttyAMA0,115200 root=/dev/ram rw’
$ bootm 0x100 0x4000000
Found the below issue :
————————–
No filesystem could mount root, tried: ext2 cramfs minix romfs
Kernel panic – not syncing: VFS: Unable to mount root fs on unknown-block(1,0)
[] (unwind_backtrace+0×0/0xf4) from [] (panic+0×74/0x1c0)
[] (panic+0×74/0x1c0) from [] (mount_block_root+0x1e8/0×228)
[] (mount_block_root+0x1e8/0×228) from [] (mount_root+0xcc/0xf0)
[] (mount_root+0xcc/0xf0) from [] (prepare_namespace+0×160/0x1b8)
[] (prepare_namespace+0×160/0x1b8) from [] (kernel_init+0×158/0x19c)
[] (kernel_init+0×158/0x19c) from [] (kernel_thread_exit+0×0/0×8)
Balau
2012/06/28
Let me clear my complete opinion.
I am convinced that if you try “
setenv bootargs ‘console=ttyAMA0,115200 root=/dev/ram rw rdinit=/sbin/init’“, it will work.
This is because, as said in Linux “
Documentation/early-userspace/README” and in other parts of the web, the “initramfs” way of booting Linux expects that the ramdisk is a cpio archive, it mounts it and then tries to execute “
/init“. In our case we don’t have “
/init” so we have two options:
1. creating a link such as “
ln -s ./sbin/init ./init” in the busybox
_installdirectory before creating the cpio archive (I haven’t tried it actually)
2. adding “
rdinit=/sbin/init” to the kernel parameters (as specified in my blog post and in my past replies to you)
I think “
root=/dev/ram” is superfluous, it should work without it because we don’t reach the point where we mount the root filesystem.
But implementing one of the two ways above is necessary to boot Linux with the ramdisk.
If it still doesn’t work, then you should also check the other parts of the kernel messages as I already said, because something could have gone wrong in mounting the initramfs.
Hope this helps.
Jerzy
2012/06/30
Hi Balau,
Why does Uboot informs on the console
DRAM: 0 kB
instead
DRAM: 128 MB ?
Balau
2012/06/30
I don’t know, it seems to be printed by “
display_dram_config” function in “
board.c” file (in u-boot-2010.03 the file is in “lib_arm” directory).
Maybe the new u-boot versions fixed this information, but I don’t remember if they still support VersatilePB.
Jagan
2012/06/30
copy the dram_init code on to
board/armltd/versatile/versatile.c
int dram_init (void)
{
/* dram_init must store complete ramsize in gd->ram_size */
gd->ram_size = get_ram_size((void *)CONFIG_SYS_SDRAM_BASE,
PHYS_SDRAM_1_SIZE);
return 0;
}
Jerzy
2012/07/01
Thanks for your replies.
And what about Uboot commands history ?
Balau
2012/07/02
What do you mean “what about Uboot commands history”? You wanted to ask why it does not work for you?
If that was the question, my answer is still “I don’t know” as before, and I don’t have time right now to check the source code to try to understand why it does not work.
You have (at least) two paths:
I suggest trying 2 and then 1.
Jerzy
2012/07/02
Thanks Balau.
I understand that Uboot 2010.03 commands history on qemu not working at all?
Balau
2012/07/03
In my environment, it is clear that it does not understand the “arrow” keys as “go up in history of commands”.
U-Boot is made to be small, I suppose giving it a command history is considered bloat for what it should do.
I tend to agree, because if everything works you should never need to access U-Boot command shell.
Terence
2012/07/17
This is great Balau, thanks for your articles. It serves as a great reference point for my project which is to get u-boot and a linux kernel up and running on the ST-E U8500 platform. Unfortunately QEMU seems to have issues…
Jerzy
2012/11/30
Hi,
Fortunately uboot linaro has commands history and u-boot.bin size is roughly the same.
psychesnet
2013/01/17
Hi Balau,
I try to practice Qemu by following your blog, but I face some problem, please help me, thanks a lot.
$ mkimage -A arm -C none -O linux -T kernel -d zImage -a 0x00010000 -e 0x00010000 uImage
$ mkimage -A arm -C gzip -O linux -T ramdisk -d rootfs.cpio.gz -a 0x00800000 -e 0x00800000 rootfs.uimg
$ dd if=/dev/zero of=flash.bin bs=1 count=10M
$ dd if=u-boot.bin of=flash.bin conv=notrunc bs=1
$ dd if=uImage of=flash.bin conv=notrunc bs=1 seek=2M
$ dd if=rootfs.uimg of=flash.bin conv=notrunc bs=1 seek=4M
VersatilePB # sete bootargs console=ttyAMA0 mem=128M root=/dev/ram rw rdinit=/sbin/init
VersatilePB # bootm 0x210000 0x410000
## Booting kernel from Legacy Image at 00210000 …
Image Name:
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 1517816 Bytes = 1.4 MB
Load Address: 00010000
Entry Point: 00010000
Image Name:
Image Type: ARM Linux RAMDisk Image (gzip compressed)
Data Size: 2579307 Bytes = 2.5 MB
Load Address: 00800000
Entry Point: 00800000
OK
Starting kernel …
Uncompressing Linux… done, booting the kernel.
…..
TCP: cubic registered
NET: Registered protocol family 17
VFP support v0.3: implementor 41 architecture 1 part 10 variant 9 rev 0
drivers/rtc/hctosys.c: unable to open rtc device (rtc0)
RAMDISK: Couldn’t find valid RAM disk image starting at 0.
List of all partitions:
1f00 131072 mtdblock0 (driver?)
No filesystem could mount root, tried: ext2 cramfs squashfs vfat msdos romfs
Kernel panic – not syncing: VFS: Unable to mount root fs on unknown-block(1,0)
How do I fix this rootfs problem????
By the way, it is working when I use
$ qemu-system-arm -M versatilepb -kernel zImage -initrd rootfs.cpio.gz -nographic -append “console=ttyAMA0 mem=128M”
But why following command would fail with u-boot rootfs ?
$ qemu-system-arm -M versatilepb -kernel zImage -initrd rootfs.uimg -nographic -append “console=ttyAMA0 mem=128M root=/dev/ram rw”
It seem like first problem ?
Need your help, Thanks a lot~
Balau
2013/01/17
About your first question:
a. you could use the exact same versions that I used and the exact same configuration to make it work, and then little by little change from my setup to yours to see when things start to go bad. I used Linux 2.6.33, U-Boot 2010.03 and busybox 1.16.0. For example I see that your root filesystem is bigger than mine, in particular bigger than 2MiB. I don’t know if that could be a problem.
b. you could launch QEMU with -s -S options and then attach with arm-…-gdb using “target remote localhost:1234”, then put a breakpoint on the start of Linux execution (for example using “file vmlinux” and putting a breakpoint on start_kernel) and when the breakpoint is reached display the content of 0x00800000 to see if ramdisk has been corrupted (check if the data is the same as rootfs.cpio.gz).
About your second question:
rootfs.uimg is just rootfs.cpio.gz with a U-Boot header attached at the beginning. Linux can’t understand U-Boot headers so the second command will not work and I did not expect otherwise.
hemal
2013/01/18
Hello,
I am using U-Boot(compressed) and two kernel Image(uImage). I want to add some code in U-Boot which will select kernel based of time stamp(or using any other way if you have in mind). I am using MIPS architecture.
For example:-
If kernel-1 is new, U-Boot will boot Kernel-1. and leave kernel-2 as it is.
If kernel-2 is new, U-Boot will boot kernel-2. and leave kernel-2 as it is.
Questions:-
Is it possible to do so?
How can I add such functionality in U-boot?
Where to chage the code for the same?
Balau
2013/01/18
I don’t think U-Boot was made for something like that.
You could modify the source code of U-Boot around the autoboot functionality, and use the timestamp added by mkimage to choose.
I don’t think it’s simple, you could ask U-Boot mailing lists.
Take a look at this to understand what can be done without modifying the source code:
hemal
2013/01/18
thank you for your reply.
Can you just tell me from where u-boot put the kernel image into RAM?
so that I can tel u-boot to put the proper image of kernel to RAM.
Balau
2013/01/20
If I search the displayed message “Booting kernel from” in U-Boot source code (2010.03), it’s present in “
common/cmd_bootm.c“, in function
boot_get_kernel. Following back the calls in the same C file it’s quite easy to find the point where the kernel is loaded.
Geo
2013/03/22
Hi Balau. I have been following your post to run linux via uboot on qemu. I followed your steps and when I run the “flashed” image on qemu, i always get the error “Uncompressing Linux… done, booting the kernel.
Bad ram offset 8000000”.
I can run u-boot by itself and kernel also by itself (although with kernel, i keep getting spew about /dev/ttyxxx not found). But when I create a flash image, i get this error.
Wondering if you knew anything about it.
thanks in advance
Balau
2013/03/23
The error says “8000000” (0x08000000), but in my post I talk about address 0x00800000. Are you sure you didn’t put a zero more in the mkimage command or something like that?
Geo
2013/03/23
Thanks for the reply! One important thing i should have mentioned is that i am running osx qemu.
balaji
2013/04/16
Hi Balau,
I am using zynq_zc702 based U-Boot 2011.03 source for running on zynq’s based qemu. Individually i am able to run the u-boot.bin and zimage with rootfs from the qemu. As you suggested I combined u-boot, zimage and rootfs into a single image(flash.bin) for supporting autoboot and I made the changes to include/configs/zynq_common.h.
#define CONFIG_BOOTARGS “root=/dev/ram mem=128M rdinit=/sbin/init”
#define CONFIG_BOOTCOMMAND “bootm 0x210000 0x410000”
#define CONFIG_INITRD_TAG 1
When I run with the following command
./arm-softmmu/qemu-system-arm -M xilinx-zynq-a9 -m 1024 -serial null -serial mon:stdio -kernel flash.bin -nographic
I got the following error.
ram size=40000000
error reading QSPI block device
error no mtd drive for nand flash
a0mpcore_priv: smp_priv_base f8f00000
error no sd drive for sdhci controller (0)
error no sd drive for sdhci controller (1)
Number of configured NICs 0x1
ram_size 40000000, board_id d32, loader_start 0
U-Boot 2011.03 (Apr 16 2013 – 12:13:30)
DRAM: 256 MiB
MMC: SDHCI: 0
Using default environment
In: serial
Out: serial
Err: serial
Net: zynq_gem
Hit any key to stop autoboot: 0
Wrong Image Format for bootm command
ERROR: can’t get kernel image!
when i give the following command at u-boot level
iminfo 0x210000 gave the following information.
## Checking Image at 00210000 …
Unknown image format!.
I am not able to see any content at 0x210000 location with md command.
I created flash.bin as you suggest and cross check it with hexdump command. Nothing wrong with flash.bin.
Please help me in this if it is a relevant question to you.
Thanks
balaji
Balau
2013/04/22
Two possibilities:
My suggestion is to try to run QEMU with -s -S options, attach with ARM GDB, analyze step by step the first instructions and check the memory with “x” GDB command.
balaji
2013/04/23
Thanks Balau
Giridhar (@giridhart)
2013/07/25
Hi Balau,
Are there u-boot build config options to enable more verbose output from u-boot?
I could see CONFIG_TRACE but could not find how to enable this.
Regards,
Balau
2013/07/27
I believe it’s just a matter of adding “
#define DEBUG 1” somewhere like in “
include/config_defaults.h“.
U-Boot is full of “
debug(...)” calls that are enabled by this macro to be expanded as
printf.
You can increase the value of
DEBUGto print also “
debugX(level, ...)” messages.
These macros are defined in “
include/common.h“.
Shashi
2013/09/30
I’m new to work on u-boot, it will be very helpful if someone let us know how to simulate port on qemu u-boot. thanks in advance
Balau
2013/10/04
What do you mean by “port”? If you mean “serial port”, you are probably looking for “
-serial stdio” option when running qemu-system-arm.
ML
2013/12/29
How am I boot on QEMU WM8650-SD-linux-image (at)
Balau
2013/12/29
QEMU doesn’t emulate WM8650 (“
qemu-system-arm -M ?” doesnt’ show it) so you can’t do that.
ML
2013/12/30
on SD are 2 partitons:
1(fat)-uzImage.bin, wmt_script
2(ext3)-files from ArchLinuxARM-armv5te-latest.tar.gz, and from -xjf alarm-wm8650-modules.tar.bz2
and otherwise you can not emulate the filesystem of this uzImage.bin (or uImage.bin)?
Nicholas
2014/01/04
hi, when i use
qemu-system-arm -M versatilepb -m 128M -kernel zImage -initrd rootfs.img.gz -append “root=/dev/ram mem=128M rdinit=/sbin/init” -serial stdio,
everything works fine.
But if i use
qemu-system-arm -M versatilepb -m 128M -kernel flash.bin -serial stdio
uboot is able to find kernel image and ramdisk image, but when kernel starts, kernel is not able to find ramdisk.
Do you where is the problem?
Balau
2014/01/06
@ML
The first partition is probably used only by the boot (u-boot?) to run the kernel with the chosen parameters. The second seems to be the root filesystem.
You can’t emulate u-boot, the kernel or the modules for the wm8650 with QEMU because they depend strictly on the hardware and the memory map, and QEMU does not emulate wm8650.
Balau
2014/01/06
@Nicholas
Is it possible that the ramdisk is too big (> 2MiB)?
You can also run QEMU with -s option, then when the kernel fails you connect to it with arm gdb, by executing “target remote localhost:1234” in the gdb prompt, and then check that the content of the memory containing the ramdisk is as expected, for example by executing “dump binary mem.bin 0x00800000 0x00A00000” and check that mem.bin corresponds to rootfs.img.gz (you can do an hexdump -C of both files and diff them graphically).
Sasq
2014/03/08
Hello,
i got some problems with patchng u-boot from code posted above. I’m using same u-boot version(u-boot-2010.03). Error from applying patch is :
patch -p1 < ~/u-boot-2010.03.patch
patching file common/image.c
Hunk #1 FAILED at 941.
1 out of 1 hunk FAILED — saving rejects to file common/image.c.rej
patching file include/configs/versatile.h
Hunk #1 FAILED at 124.
1 out of 1 hunk FAILED — saving rejects to file include/configs/versatile.h.rej
Any suggestions why this happened?
Balau
2014/03/08
I don’t know why it happened but I recommend changing the source code manually since it’ a few lines of code, and in the process try to see if the source code is different from what it’s expected.
Another explanation is that you copied also the line numbers from the site, they don’t have to be copied.
hackembed
2014/04/05
Hi Balau, i followed your tutorial to boot flash.bin from qemu. MY problem is that when i start the qemu i got his error
U-Boot 2010.03 (avril 05 2014 – 11:47:27)
DRAM: 0 kB
Unknown FLASH on Bank 1 – Size = 0x00000000 = 0 MB
Flash: 0 kB
*** Warning – bad CRC, using default environment
In: serial
Out: serial
Err: serial
Net: SMC91111-0
Hit any key to stop autoboot: 0
qemu: hardware error: pl011_write: Bad offset ff8
CPU #0:
R00=56190527 R01=00000000 R02=00000010 R03=00000000
R04=00210000 R05=00210000 R06=00fddef4 R07=00000003
R08=00fddfe0 R09=00000000 R10=01014ffc R11=01017e8c
R12=00fddd03 R13=101f4000 R14=010105ac R15=010105a4
PSR=600001d3 -ZC- A svc32
When i test without u-booot it works perfectlly. So, i wanna know waht’s wrong.
Please, help me.
Regards.
Balau
2014/04/05
The error is generated while executing U-Boot, Linux is not yet started.
R15 is program counter, R14 is return address; you can see where the program crashed from U-Boot disassembly. You can disassemble it by running something like
arm-none-eabi-objdump -S u-boot >u-boot.dis. U-Boot should already be compiled with debugging symbols, otherwise try to enable them by adding
-gto
CFLAGS.
You can also try to run QEMU with
-s -Soptions and then attach to it with
arm-none-eabi-gdbusing
u-bootas file for symbols and debug info. Then you can break at
do_bootm_linux(that’s the last function U-Boot should execute) or at
abort_boot(that’s the last thing your U-Boot prints) and try to debug from there.
Nitin
2014/05/05
Hi Balu
I try to debug decompress part of linux kernel. But my Breakpoint does not hit.
To run linux on qemu i ran following command.
qemu-system-arm -M versatilepb -m 128M -s -S -kernel arch/arm/boot/zImage
and on gdb side ran this command
arm-none-eabi-gdb target remote localhost:1234
after that
file ./arch/arm/boot/compressed/vmlinux
then add breakpoint
like b __setup_mmu
None of my breakpoint hit .
Only break point after MMU_ENABLE hit like start_kernel
Thanks,
Nitin
Balau
2014/05/05
The part of software that runs before the decompression is position independent code. In my case (probably also in yours) the zImage is loaded in 0x60010000, and that’s the address containing
start, but in the
vmlinuxELF the address is 0. I tried the GDB command
add-symbol-file arch/arm/boot/compressed/vmlinux 0x60010000instead of
file arch/arm/boot/compressed/vmlinuxand it seems to load the symbols to their right addresses, try it also in your setup.
Nitin
2014/05/06
Hi Balau,
I followed your steps as mentioned.But Still not able to hit the breakpoints.
I checked with gdb and dump the 0x60010000 location.
x/10wx 0x60010000
0x60010000: 0x00000000 0x00000000 0x00000000 0x00000000
0x60010010: 0x00000000 0x00000000 0x00000000 0x00000000
0x60010020: 0x00000000 0x00000000
It shows nothing . So might be in my case load address of zImage will be different.
I have question:-
1) How to find the address where zImage loaded in qemu.
Nitin
2014/05/06
Hi Balau,
I checked with gdb and dump the location 0x00010000 location. I got this location when i searched for zImage header magic number 0x016f2818.
I matched with my zImage Hexdump but when i load the elf file with add-symbol-file arch/arm/boot/compressed/vmlinux 0x00010000 and put some breakpoint.
It halt that place and show function input_data() with no code.
Thanks
Nitin
Nitin
2014/05/06
Hi Balu,
I checked with add-symbol-file arch/arm/boot/compressed/vmlinux 0x60010000
but still breakpoints not hitting. When i dump the 0x60010000 on gdb it shows
0x00000000 . When i dump the 0x00010000 on gdb it has same footprint as my zImage.
But when i add-symbol-file arch/arm/boot/compressed/vmlinux 0x00010000 and put breakpoint on this address. It stops there but function it shows input_data(). Please let me know how you find the load address 0x60010000 on your system.
Thanks,
Nitin
Balau
2014/05/06
I launched QEMU with
-s -S(so it’s stopped before executing anything) and then connected with gdb. With something like
x/10i $pcyou can see the code at current program counter. At the beginning QEMU puts a couple of its own instructions to jump to the user code. So I
stepia few times until it jumps, and at that point it jumps to the beginning of the binary passed by
-kerneloption. That address should be the offset that you pass to
add-symbol-file. I tried with versatilepb to make it similar to your setup and I find your same problem, and it is strange, but it is easily worked around if you
stepiuntil you reach
startor if you
break startand then
continue.
Nitin
2014/05/10
Hi Balau,
i used this command :-
add-symbol-file ./arch/arm/boot/compressed/vmlinux 0x00010000 -s .piggydata 0x00014610
and now i am able to put break points and debug the code.
I found out that in arch/arm/boot/compressed/vmlinux
.piggydata 001d28e0 00004610 00004610 0000c610 2**0
which means .piggydata starthe at 0x4610 and length 001d28e0 which overlaps the 0x00010000 address. i.e. gdb not able put the breakpoints . so remap that section also .
Thanks for your help,
Nitin
Cruise
2014/05/28
Hi Balau,
I compiled U-Boot and run QEMU with “u-boot” (ELF file) and I can see u-boot message.
$ qemu-system-arm -M vexpress-a9 –kernel u-boot -nographic
But I just saw nothing when using “u-boot.bin”:
$ qemu-system-arm -M vexpress-a9 –kernel u-boot.bin -nographic
The cross-compiler I use is “arm-linux-gnueabi” and my linux distrubution is Ubuntu 12.04.
I also tried to re-compiled U-Boot with “versatile_defconfig” and run qemu with “versatilepb”. I still can’t see any boot message.
Do you have any idea?
Thanks.
Balau
2014/05/29
I am quite sure that if you give QEMU an ELF it will load it using the information about the segments of data, code, etc. and then it will execute from the entry point. But if you run a binary it will simply place it as is into a given address (different for each machine) and then jump to that address. You can try to run QEMU with
-s -Sand attach to it with GDB by running
arm-linux-gnueabi-gdb u-bootand then
(gdb) target remote localhost:1234; in this way you can run step-by-step and see what is happening with program counter and memory content.
Cruise
2014/06/05
Hi Balau,
I ran QEMU with GDB but u-boot.bin just can’t be executed.
I tried to decode u-boot ELF file and found entry point is 0×60800000.
So, I generated image file with mkimage and set entry point to 0×60800000. In this way, it worked.
Giab
2014/09/12
Hi Balau,
great work!
I used it with latest kernel (linux-3.16.2) and u-boot (u-boot-2014.07) with these patch:
——————————– common/image.c ——————————–
index 11b3cf5..4a92b6a 100644
@@ -933,6 +933,15 @@ int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t images,
return 1;
}
}
+#if defined(CONFIG_VERSATILE)
+ /
+ * We need to copy the ramdisk to SRAM to let Linux boot
+ /
+ if (rd_data) {
+ memmove ((void *)rd_load, (uchar *)rd_data, rd_len);
+ rd_data = rd_load;
+ }
+#endif / CONFIG_VERSATILE */
} else if (images->legacy_hdr_valid &&
image_check_type(&images->legacy_hdr_os_copy,
IH_TYPE_MULTI)) {
————————- include/configs/versatile.h ————————-
index 29c32fe..56e4818 100644
@@ -15,6 +15,8 @@
#ifndef __CONFIG_H
#define __CONFIG_H
+#define CONFIG_ARCH_VERSATILE_QEMU
+
/*
* High Level Configuration Options
* (easy to change)
@@ -90,6 +92,9 @@
#define CONFIG_CMD_NET
#define CONFIG_CMD_PING
#define CONFIG_CMD_SAVEENV
+#define CONFIG_CMD_RUN
+#define CONFIG_CMD_SOURCE
+#define CONFIG_CMD_BOOTZ
/*
* BOOTP options
@@ -100,9 +105,11 @@
#define CONFIG_BOOTP_SUBNETMASK
#define CONFIG_BOOTDELAY 2
-#define CONFIG_BOOTARGS “root=/dev/nfs mem=128M ip=dhcp “\
– “netdev=25,0,0xf1010000,0xf1010010,eth0 “\
– “console=ttyAMA0,38400n1”
+#define CONFIG_BOOTARGS “root=/dev/ram mem=128M rdinit=/sbin/init console=ttyAMA0”
+#define CONFIG_BOOTCOMMAND “bootm 0x210000 0x410000”
+#define CONFIG_INITRD_TAG 1
+
+
/*
* Static configuration when assigning fixed address | https://balau82.wordpress.com/2010/04/12/booting-linux-with-u-boot-on-qemu-arm/ | CC-MAIN-2015-35 | refinedweb | 11,756 | 64.91 |
".
Article Series
Part 1: The WP REST API for Remote Control WordPress (You are here!)
Part 2: OAuth Fun with OAuth1
Part 3: Remote Control WordPress at Scale
We designate one install as the "control", where we configure network settings, and then the other 30 "client" installs get their network settings from the control.
It's going to take me several articles to lay this all out. I hope you pore over every pain-staking and obscure detail. This method has the potential to save us dozens of man-hours per year, and also greatly reduces the chance for human error. Fewer clicks means fewer mistakes! It's a tricky approach and new approach, but I'm stoked about it.
Here's an overview, before we dig in deeper:
- The control install exposes data via the WP REST API V2 plugin.
- The control install runs a custom plugin to add network settings to the WP API (they're not in there by default). This custom plugin also registers a global variable that gives us a programmatic way to distinguish between the control install and the other 30 client installs.
- The control install runs the Oauth1 plugin to secure the settings from public browsing, yet expose them to our scripted requests from the client installs.
- Both the control install and our 30 client installs run many "feature" plugins: custom network plugins that provide common WordPress hackery, such as a custom logo on the wp-login screen.
- Both the control install and our 30 client installs run a custom plugin for managing network settings. It provides an abstraction layer for our feature plugins to get their settings from the control install.
What You'll Need to Follow Along
- Two WordPress multisite installs: One will be the control install, and the other will act as a client install. In my examples, the control install will be my personal website, and the client install will be my local MAMP. At time of writing, both installs are on WordPress 4.5.3. In this first article, we'll only need the control install. Subsequent articles will involve the client install.
- A total of five plugins, as I eluded to above. Some of them are on GitHub and some of them are in the .org repo. Some of them are written by me, and some of them are written by people way smarter than me. Some of them will likely be part of core someday, and some of them are just for demonstration. I'll address them each as they're needed. This first article will require two of the five plugins.
- The theme doesn't really matter, but my examples will depict twentysixteen. If you have any problems following along, mimicking that would be a good practice.
Are you with me so far? I realize this has been a fast overview, but just like at the end of middle school dances, we're about to slow things down. Our goal for the rest of this article is to expose network settings to the WP API on our control install. We'll get to the rest of the components in subsequent articles. Fire up your test installs and follow along!
JSON Returns
Alright, on your control install, try browsing. This should get you a 404 error.
Now install and network activate the WP REST API V2 plugin and browse
/wp-json/wp/v2/posts again. You should get something like the following:
Sweet! You have JSON data now. Surf around for a bit, using the endpoints in the docs as a guide -- or better yet, the link urls in the JSON response itself. For more details, also see this excellent article by Andy Adams on fetching posts via the API.
You might notice in the docs that network options are not available for fetching, but we'll fix that soon. For now, just load
/wp-json/css_tricks_wp_api_control/v1/ url on your control server and note the 404. Then, install and network activate my CSS Tricks WP API Control plugin. That
/wp-json/css_tricks_wp_api_control/v1/ url should work for you now, returning some data about the
network_settings route my plugin registers.
If you squint hard enough, you'll pick up on the most interesting part of the response:
"args":{"meta_key":{"required":true}}
That's telling you that my endpoint accepts one argument, called
meta_key, and that it's required.
So,
/wp-json/css_tricks_wp_api_control/v1/network_settings -- what's that url all about? The
/wp-json/ portion is ever-present for the WP API. That just means you're getting JSON. The
/css_tricks_wp_api_control/ portion is the namespace for my plugin. Note that core uses the namespace
/wp/, such as in the posts example above. The
/v1/ indicates that this is version 1 of the endpoint that my plugin is using. I could update this version number if I want to break backwards compatibility, but otherwise I would not, say, update this each time I update the version number of my plugin itself. Finally, I've chosen to register the
/network_settings/ endpoint for getting network settings.
Digging into the Control Plugin
The control plugin has two purposes. First, you'll see that it registers a global variable,
CSS_TRICKS_WP_API CONTROL, which other plugins can sniff for in order to determine if they are running on the control install or a client install.
Second, you'll see that it registers network options for querying in the WP API. That file is thoroughly commented -- please give it a quick read. For now, I'll highlight two functions:
callback() is what returns the network settings from the database. It requires a
GET variable for meta_key, giving us a way to get a specific network option. You can see that it's required if you try to load
/wp-json/css_tricks_wp_api_control/v1/network_settings without tacking on a
?meta_key=whatever: You get a 400 admonishing you for failing to provide a meta key.
permission_callback() designates that, when requesting data from our custom route, the we must provide some authentication in order to see the network settings in the WP API, otherwise we'd probably have a security problem. We'll do this via the OAuth1 plugin in the next article. For now, you can see that auth is required if you try to load
/wp-json/css_tricks_wp_api_control/v1/network_settings?meta_key=whatever: In this case, you get a 403 spanking you for failing to authenticate.
If you're interested in exploring the
network_settings endpoint without dealing with authentication, you can omit the call to
permissions_callback, or make it always return
TRUE, but beware that it's a security hole.
This file could have been written much differently. For a more complex endpoint, you'd be better off extending the WP Rest Controller. I think that would be overkill for our case, and certainly would be a tutorial unto itself.
Next Steps
There are a few different things you should be wondering about at this point.
One is authentication. How are the client installs supposed to make it past
permission_callback()? We'll accomplish this in the next article via a long and brutal battle with the OAuth1 plugin.
Another is DRY/WET. If our 30 client installs run many feature plugins, wouldn't it be a drag if all of those feature plugins hard-coded a query to the control install? Therefore, we're going to write an abstraction layer that all of our feature plugins can use to query the control blog. The control blog will even use it to get settings from itself! Heady stuff; I'll save that for the third and final article in this series.
Then there's performance. We're going to make an http request each time we need a lousy setting? Nope. We're gonna cache the results, which I'll also demonstrate in the third article.
More generally, you might just have the objection that this seems like a lot of work. To this I'd say, compared to what? I'm writing this series because I think it's better than having a staff manage the same settings across 30 installs. I think by the end, you may agree!
Other Resources
If you're having trouble following along thus far, here are the best places to go next:
- Buying the WROX book on plugin development is like buying yourself a career.
- Torque's WP API book. These guys run WP Engine - need I say more?
- The WP API Docs, where the section on extending the API is particularly relevant to the terrain we've covered thus far.
Ready For More?
If you're following so far, brace yourself for a savage dance with OAuth in the next article!
Article Series
Part 1: The WP REST API for Remote Control WordPress (You are here!)
Part 2: OAuth Fun with OAuth1
Part 3: Remote Control WordPress at Scale
In a way it’s kinda odd that this, in some form, hasn’t been addressed in WP / WP MS already.
If I’m reading/skimming this correctly, the control install more or less becomes a dependence for the client installs. Cache aside, doesn’t that mean if the control goes wonky all 30 installs are then as risk.
Or have I misread? (Sorry?)
Thank you for the comment!
I’d say it depends on what you mean by wonky. If you mean that it’s temporarily unavailable, say a ddos attack, there are a couple of options:
1) Maybe you’re hiding behind something like CloudFlare’s “Always Online” thing.
2) You were astute to mention caching. Later on in the series, I will demonstrate caching the results that come from the control by storing them as transients on the client install. If you want, you could have some logic there to not update a transient on the client, if the response from the control is 40x/50x/falsey.
Nice article – looking forward to the day when I really “need” it.
Just FYI: “pour” is to let liquid overflow its container and what I think you are hoping we will do – “pore” is what pimples are made of [Of course I’m not speaking for those back across the pond who are able to do things with “e’s” that none of us over here can make them do]
I was unsure about this as well! I appreciate your concern. I ended up going with the advice here:
Which indicates,
Totally looking forward to your next article… I have had a couple of “long and brutal battles” with the OAuth1 plugin, and been soundly defeated every time…
I’m not sure if I missed on something, but isn’t your use scenario a good example for using WP-CLI?
Depends on who’s typing the commands I guess! Our settings wranglers are not at a skill level or a career path where the idea of them with command line access to a thousand live domains makes a lot of sense.
Even if they were, it sounds like you’re talking about a control-pushes-to-client scenario. I’m more comfortable with a client-pulls-from control scenario because there’s less potential of a bug corrupting client data. | https://css-tricks.com/wp-rest-api-remote-control-wordpress/ | CC-MAIN-2016-36 | refinedweb | 1,868 | 71.95 |
User Name:
Published: 01 Sep 2009
By: Gabriel Schenker
Download Sample Code I will introduce the auto mapping feature of Fluent
NHibernate. Using this feature the task of mapping a domain model to an underlying data model becomes a snap. The framework will do most of the work
for us and we only have to add our own mapping related code if we want to fine tune the mapping process.
In the previous parts [1, 2] of this series I have introduced a simple but still useful domain model describing an order entry system. I have
shown how this model can be mapped to a database model with the aid of Fluent NHibernate [3]. In the following I will use FNH as an acronym for
Fluent NHibernate. The mapping has been done for each class of the domain. Although the mapping was very simple and straight forward as well as type
safe there is still one disadvantage; if we have a domain with many classes the manual mapping of them can become quite a burden.
Fortunately
there exists a solution: We can let FNH do the work for us and just let it automatically map the domain model to a corresponding data model. When
doing so FNH will analyze the classes defining the domain and use conventions to map them to underlying tables (and relations) in the database.
Although the conventions used by FNH are quite reasonable we can still apply our own conventions. These conventions are fine grained thus we have
extensive tuning possibilities.
Let’s again implement our (simple) domain model for an order entry system from scratch as simple as possible.
Here is the class diagram
And here
the code
The above code probably reflects the simplest way to implement our domain model. I will later on extend improve the code as needed.
But for the moment this is enough.
Let’s now configure our system to automatically map our domain to a data model. We do this by using the fluent configuration API offered by FNH.
In my sample I’ll use two different databases to explicitly show how (Fluent) NHibernate produces database specific schemas. The first database is
SQLite [4] and the second one is SQL Server Compact Edition. Both are easy to set up and use and are file based.
Let’s start with the
configuration for SQLite. What I want to do is define a method that creates a session factory configured to use a SQLite database
I can use the class Fluently defined by FNH as well as one of the various predefined configuration classes. In our case it is the
SQLiteConfiguration class. I tell the system that I want to use SQLite in file mode using a file with the name provided by the constant
DbFile.
The Mappings(…) part of the configuration defines where or how the mapping between the domain model and the data model
is defined. In our class we want to let FNH do the hard work and use its auto mapping feature. FNH offers the class AutoPersitenceModel for this
purpose.
Mappings(…)
The mappings method expects a lambda expression. Our expression auto-creates mappings for all types found in the assembly where the
class Customer is defined but only those types whose namespace ends with “Domain”. If we would not have the where clause to filter the set of types
to map then FNH would try to just map every class in the assembly which is certainly not what we want.
If I want to use SQL Server Compact
Edition instead the only change I have to make in the above code is replacing the .Database(…) line with the following code
snippet
.Database(…)
In this case I use the pre defined class MsSqlCeConfiguration and explicitly define a connection string to use. The above connection
string just instructs the database to use a file called AutomappingSample.sdf.
When using SQLite as database the schema generation script will
be the following
And for SQL Server compact edition we get this schema generation script (which is the same for SQL server)
Please especially note the following
Id
_id
This is the result of the default conventions that were applied during the generation of the database schema script. We can now start to
fine tune this by defining our own conventions.
A convention is defined in a class that has to implement an interface pre defined by FNH. As I already told previously the conventions are really
fine grained thus loads of different interfaces are defined which we can implement if needed. As a simple sample let’s say that we want our
properties of type string to always be mapped to have a maximal length of 100 characters. Any of the possible convention interfaces to implement
ultimately inherits from the base interface IConvention<T> which defines the two methods Accepts(T target) and Apply(T
target). Thus we will have to implement exactly those two methods in our class.
Accepts(T target)
Apply(T
target
The Accepts method defines when a convention can be applied and the Apply method contains the logic which
applies the convention to the given element. In the above case we accept any target that is of type string and in the Apply method we
define the maximal string length to be used in this case.
Accepts
Apply
In a previous post I have mentioned that it is an anti-pattern to use identity
fields as primary keys for SQL Server in conjunction with NHibernate. It is preferable to e.g. use the HiLo generator if using numbers as primary
key; another alternative would be the usage of Guids as primary keys. For performance reasons use the GuidComb generator when using Guids as primary
keys. Having said this let’s define our own id convention which uses the HiLo generator instead of the identity generator. In this case we write a
class that implements the interface IIdConvention.
We want to apply this convention for any entity in our domain so we just return true in the Accept method. In the Apply method we
define which (id) generator we want to use. In this case it is the HiLo generator with an interval of 1000. Why we have to define the “maxLo”
value as string and not as a number is not clear; probably it’s a bug.
Now we have to tell the system to use these conventions instead of
the default conventions. We can do this either by explicitly add each convention to the configuration of NHibernate or by letting FNH scan an
assembly for implementations of conventions. Let’s start with the former. We can add a convention by using the ConventionDiscovery
method of the AutoPersistenceModel class.
ConventionDiscovery
After modifying the configuration with our own conventions the schema generation script for SQL Server looks like this
An additional table called hibernate_unique_key is created which is used for the management of the ids by NHibernate. Ids are no
longer columns of type identity but just of type int. Not SQL Server manages the ids now but NHibernate does it. Furthermore we can see that the
properties of type string are mapped to columns of type NVARCHAR(100).
In the above configuration we use the ExposeConfiguration method which expects a delegate to a method that will be called during
the configuration process. In our case the delegate points to a method called BuildSchema. This method has one parameter of type
Configuration. We use the configuration object to create the database schema with the aid of the SchemaExport utility class of NHibernate.
ExposeConfiguration
BuildSchema
Note that in a productive environment you would omit this part since the database schema is generated only once; probably by a
DBA.
Our domain model has some weaknesses so far. Part of those are discussed in detail here [2] and here [5]. One weakness is that entities do not
implement the functionality do determine whether two instances represent the same entity. Equality is based on the id (primary key) of an entity. If
two instances have the same id then they are the same. A possible implementation is given in [5]. Since every entity has an id and every entity
needs to be comparable and to keep our code DRY it is best to define a base class for all entities which implements this common logic. Let’s call
our base class EntityBase. All entities will now inherit from this class. For further details please consult the code provided with this
article.
If we were to run this now, we wouldn't get the mapping we desire. FNH would see EntityBase as an actual entity and map it with all
other entities (e.g. Customer or Order) as subclasses; this is not what we desire, so we need to modify our auto mapping configuration to reflect
that.
After MapEntitiesFromAssemblyOf<EntityBase>() we need to alter the conventions that the auto mapper is using so it
can identify our base-class.
MapEntitiesFromAssemblyOf<EntityBase>()
We've added the WithSetup call in which we replace the IsBaseType convention with our own. This convention is used to identify whether
a type is simply a base-type for abstraction purposes, or a legitimate storage requirement. In our case we've set it to return true if the type is
an EntityBase.
With this change, we now get our desired mapping. EntityBase is ignored as far as FNH is concerned, and all the properties (Id
in our case) are treated as if they were on the specific subclasses.
SMILE and be HAPPY!!!
bird influenza
Please login to rate or to leave a comment.
Link to us
All material is copyrighted by its respective authors. Site design and layout
is copyrighted by DotNetSlackers.
Advertising Software by Ban Man Pro | http://dotnetslackers.com/articles/ado_net/Your-very-first-NHibernate-application-Part-3.aspx | crawl-003 | refinedweb | 1,628 | 62.07 |
Table of Contents
- What is the OTT Details API?
- How does the OTT Details API work?
- Target Audience for the OTT Details API
- How to connect to the OTT Details Tutorial – Step by Step
- OTT Details API Endpoints
- Integrating the OTT Details API to an Application
- Alternatives to the OTT Details API
- Benefits of the OTT Details API
- Summary
OTT or Over The Top providers that deliver movies and TV shows via the internet have become increasingly popular among people nowadays. The reason is that OTT providers like Netflix, YouTube, and HBO allow you to view content on different devices and switch multiple services offering you much flexibility. There is a considerable growth of content at OTTP providers every day. Therefore, searching and browsing content in various OTT streaming services can be a hectic task.
Luckily, there are many APIs in the market that help users search and view the content on various OTT streaming services. OTT Details API is one such robust API that provides various details about movies and TV shows.
What is the OTT Details API?
OTT Details API is an API that can retrieve streaming details of Movies and TV Shows. It supports 150+ Streaming platforms in the US and India, such as HBO, YouTube, Netflix, Prime Video, Hotstar, Hulu, etc. In addition to streaming information, it also provides essential details on any given movie title.
Moreover, the API has five subscription plans, including a free subscription. It supports various programming languages such as Python, PHP, Ruby, NodeJS, and Javascript. In this article, we will see how to use this API with multiple programming languages and SDK.
How does the OTT Details API work?
OTT Details API works using simple API logic. It sends the request is to a specific endpoint and obtains the necessary output as the response. When sending the request, it includes ‘x-RapidAPI-key’ and ‘x-RapidAPI-host’ as authentication parameters to validate its authenticity. The body of the API request contains the parameters required to process it. Once the API server has received the request, the back-end application will process the request. It will retrieve the required information from a database, formulate the response, and send it to the client in JSON format.
Target Audience for the OTT Details API
Application Developers
People often use searching applications to search and browse for their favorite movies and TV Shows. If you aim to build such an application or website that helps users see all the various streaming services, this API is what you need. Because OTT Details API has all the streaming data, you need to build powerful search and browse experiences for your users. Using its variety of API endpoints, you can build search and browse by title, genres, imdb id, streaming platform, and many more.
Learners
OTT Details API is easy to learn and integrate with a lot of programming languages. It has a free plan, and its Pro plan only costs $10. Therefore, anyone who learns about APIs or wants to keep an up-to-date private movie or TV show database can make use of this API at a low cost.
How to connect to the OTT Details Tutorial – Step by Step
Step 1 – Sign up and Get a RapidAPI Account.
You can use RapidAPI to search and connect to thousands of APIs using a single SDK, API key, and Dashboard. RapidAPI is the world’s largest API marketplace used by more than a million developers worldwide.
To create a RapidAPI account, go to rapidapi.com and click on the Sign Up icon. You can use your Google, Github, or Facebook account for Single Sign-on (SSO) or manually create an account.
Step 2 – Search the API Marketplace
Next, Navigate to the Marketplace and search for “OTT Details API.” Then, select the ‘OTT Details API” from the search results.
Step 3 – Test the API
After loading the API page, navigate to the ‘Endpoints’ section of the API page, which shows all the available endpoints. Then, select the endpoint you want to test and add the required values for the parameters. Each API endpoint has code snippets in multiple languages, and it automatically adds the API keys, host, and accept parameters.
Finally, click on the “Test Endpoint” Button to test the API. Upon successful testing of an API endpoint, you will get the response with a 200 status code. It will output an error code and message if there is an error in the request.
OTT Details API Endpoints
Currently, RapidAPI provides eight endpoints in OTT Details API.
/getPlatforms
From this endpoint, you can get information about all the OTT streaming platforms the API supports. Currently, the API supports only the USA and India regions. The only required parameter for this endpoint is the ‘region’ parameter. Enter the region as ‘US’ if you want to get providers in the USA or ‘IN’ for India. You will get a JSON object array as the output in which the ‘label’ attribute contains the name of the OTT provider. Apart from that, it contains the value and a shortened name for the OTTP provider.
/search
This endpoint allows you to search for movies or TV shows based on a specific title. For example, if you want to search for movies having the title ‘ inception’, enter the movie title in the ‘title’ parameter and optionally specify the number of pages you want to return. You will get an array of movie objects that have the title’ Inception.’ In addition, it contains details like genre, IMDB id, released year, image URL, and synopsis.
/getParams
Using this endpoint, you can get an array of values that you can use as parameters in the advanced search endpoint. Or else, you can get an array of genres or languages that you can use as the filter in an advanced search.
/advancedsearch
This endpoint allows you to search for a movie or tv show based on various parameters such as release year, IMDB rating, genre, language, etc. The following table shows a description of the parameters you can use for this endpoint.
/getnew
This endpoint can retrieve the latest TV show or movie arrivals. You need to specify the region of OTT providers and optionally the number of pages. For example, the following image shows the list of new TV shows and movie arrivals in the US.
/getadditionalDetails
You can get additional details for a movie or TV show like reviews, quotes, plot summary, number of votes, trailer URL, cast details, etc., from getadditionalDetails endpoint. All you need to specify is its IMDB id.
/getitleDetails
This endpoint retrieves basic information on a movie or tv show such as
- IMDB id
- Title
- Genre
- Runtime
- IMDb rating
- Language,
- Synopsis
- Type
- Image URLs,
- Streaming platforms info
You need to specify the IMDB id of the TV show or movie you want to search about
/getcastDetails
Using this API endpoint, you can get information on a cast such as a name, profession, birth and death year, bio, poster, best titles, etc. This endpoint requires you to include ‘people which you can get from the getadditionalDetails endpoint. The following image shows the response for the people ‘nm0000375’.
Integrating the OTT Details API to an Application
This section will see how to integrate the OTT Details API into a software application with Python, PHP, Ruby, and Javascript providing example code snippets from the API site. We will be using its “getPlatforms” endpoint throughout all the code snippets.
In each code, you need to define values for the ‘X-RapidAPI-key,’ ‘X-RapidAPI-host,’ and ‘accept’ parameters and include them in the request header. The “accept” parameter should always be ‘application/JSON because it has been built to return the response in the JSON format. You can take these values from the API website.
Python Code Snippet (requests)
First of all, install the ‘requests’ python module on your computer. The following python code uses the “requests” library to send a GET request to the endpoint. Define the mandatory search term in the “query string” variable. Then use the URL, header, and the query string in the Request object’s request method to send the API call programmatically. You can also use requests.post method for this purpose.
import requests url = "" querystring = {"region":"IN"} headers = { 'x-rapidapi-key': "cJvLRNK0GfdM9WSMbQe3inU7REn8JVy5", 'x-rapidapi-host': "ott-details.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text)
PHP Code Snippet (HTTP v2)
First, create a client and a request class object. Then you need to set the API url, request method, query string containing the search keyword, and the header separately from the request object. Finally, send the request through the client objects’ send method.
<?php $client = new http\Client; $request = new http\Client\Request; $request->setRequestUrl(''); $request->setRequestMethod('GET'); $request->setQuery(new http\QueryString([ 'region' => 'IN' ])); $request->setHeaders([ 'x-rapidapi-key' => 'cJvLRNK0GfdM9WSMbQe3inU7REn8JVy5', 'x-rapidapi-host' => 'ott-details.p.rapidapi.com' ]); $client->enqueue($request)->send(); $response = $client->getResponse(); echo $response->getBody();
Ruby (net::http)
Suppose you are using Rubys’ net::http module, import OpenSSL and URI modules in the beginning. In this instance, bypass SSL certification verification by setting it to ‘VERIFY_NONE..’ Unlike in the above code examples, you can directly set the search keyword"] = 'ott-details.p.rapidapi.com' response = http.request(request) puts response.read_body
Javascript (Axios)
Integrating this API into a Javascript application is pretty straightforward and requires a few lines of code. The following code snippet shows how to call this API using its ‘axios’ module. You can define the parameters, url, headers, and the request method in one javascript object and use Axios. The request method to send the request and retrieve the response.
import axios from "axios"; const options = { method: 'GET', url: '', params: {region: 'IN'}, headers: { 'x-rapidapi-key': 'cJvLRNK0GfdM9WSMbQe3inU7REn8JVy5', 'x-rapidapi-host': 'ott-details.p.rapidapi.com' } }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); });
Alternatives to the OTT Details API
Following are the similar OTT Movies and TV Series details APIs available on the RapidAPI site.
- Movies/TV show Data (IMDB) API – This API allows you to get Movies and TV Series data that includes results in a JSON format and includes items such as movie & TV Shows specifications, images, posters, trailers, ratings, and more
- Data-imdb API – Retrieves a collection of IMDB information for movies, TV shows, actors. Includes awards, complete biography, youtube trailer url, and many other valuable pieces of information.
- Movies/TV series streaming shows API – You can get any Movie or TV Series or Show streaming links by their IMDB IDs with this API.
Benefits of the OTT Details API
Extensive Functionality
This API is not limited to only a single functionality. It covers basic to advanced TV and movie information like genres, plot summaries, synopsis, reviews, IMDB ratings, image URLs, etc. Therefore, developers can build comprehensive movie and TV series search applications without depending on other APIs.
Easy to Integrate
Almost all the endpoints of OTT Details API need just a few parameters. Thus, you do not have to spend a lot of time writing complicated code. In addition, you can find example code snippets in many programming languages with two or more frameworks or modules. Because of this simplicity, even someone with little to no background using APIs can master the API reasonably quickly.
Freemium API
OTT Details API is a simple and API that costs you only $50 per month to get its full capabilities. It also allows developers to get most of its capabilities free of charge. It will be a huge benefit, particularly for students who learn about APIs and application developers to build innovative applications.
Summary
OTT Details API is a comprehensive and robust API that you can use to get a lot of helpful information about movies and TV shows from OTT providers. This article discussed how to subscribe for it, its available endpoints, benefits, for whom it will be helpful, and provided sample code snippets in Python, PHP, Ruby, and Javascript to show how to use it in an application. | https://rapidapi.com/blog/ott-details-api-with-python-php-ruby-javascript-examples/ | CC-MAIN-2021-31 | refinedweb | 2,015 | 62.58 |
Update:;
using System.Collections.ObjectModel;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.Monitoring;
namespace Jakub_WorkSamples
{
partial class Program
{
static void DriveSystemConnectorLibraryTestManagementPack()
{
// Connect to the sdk service on the local machine);
}
}
}
}
Could not manage to import the demo MP provided in this blog. I'm running SCOM Beta2 . This is the error message i'm getting ...
Invalid Management Pack
Invalid Management Pack : D:\Shared\MP\Sample MPs\Microsoft Demo MPs\System.Connectors.Library.Test.xml .: XSD verification failed for management pack. [Line: 439, Position: 24]
The 'AlertMessage' attribute is not declared.
Yeah, localized alert descriptions were not supported in Beta 2, but instead the alert name and description were directly part of the configuration. You can try removing these references, or most preferably, move to a more recent RC0 build.
Alright, i will wait for the RC then. I guess it should be available to the public by this month end from the connect website , rite?
Yes, we are working on an RC1 right now. Should be available relatively soon, although I am not 100% sure of the date.
I wanted to go through and outline some of the changes we made for MCF since our last release. The things
I was testing out this example and the MP with the RC1. I just got a few questions to ask.
1. In the MP, under the ModuleTypes tag, there is a line saying,
<ClassID>2325018e-eef4-41a3-8c17-db831b85c93b</ClassID>
I'm just curious what is this ClassId, Is it the classId of the computerClass? Can't we use some variables, instead of coding the classId directly?
2. Same as my previous question, also for
<ChannelId>5BD75C47-95C4-4c33-99B4-BFF75A1C0764</ChannelId> under the WriteActionModuleType tag.
3. Is it possible to do thresholding only for a particular counter from the sdk inserted data?
I also noticed that you create a new event for every Performance Data insert. Is n't that will create so many events ? Is n't that bad for system's performance??
1. and 2. - These are hardcoded values that normally would not be "public" but need to be to allow for the added functionality I talked about.
3. I am not entirely sure I understand your question, but if I do, then yes, you just need to match on the counter name in a condition expression filter.
In terms of creating one CustomMonitoringPerformanceData for every insert, this is the only way to do it and as always, performance should be a consideration, but regarding this, probably not a concern. What kind of scale are you looking for?
For the CustomMonitoringPerformanceData, I'm looking at a possibility that (approximately), Every 15 mins, 3000 devices will report performance. So that should be about 4,320,000 inserts just per day. And i 've not included the PerformanceCounters in this calculation. So is it okie to create events for each of them?
BTW, is there any way to clear the previously inserted PerformanceData? I figured out that removing the MP which defined the class causes the PerformanceData to disappear also. But i was wondering is there any possibility from the SDK or CommandShell. And when i remove the MP what happens to all of those PerformanceData? are they completely deleted from the database or archived somewhere?
That should be fine in terms of scale. The performance data is deleted based on your grooming settings and if you want to archive it, you need to move it to reporting.
If possible, can u explain in detail about where to set the grooming settings and how to move it to reporting?
How about clearing the alerts, is it the same way also ?
Reporting is not my area so I don't know much about that; I would suggest reading through our docs and if that does not suffice, posting to the beta newsgroups.
Regarding grooming, yes, alerts are the same. The settings for this can be changed via the UI in Administration -> Settings -> Database Grooming.
For the alerts it does not work. Even after i 've removed the management pack which defines the particular class the alerts still exist. Previously the alertname was like "Alert for instance MyInstance" , but after i remove MP with the class definition, it becomes "Alert for instance {xxxx-xxx-xxx}" with the GUID. I was testing by inserting Performance data, loading from a CSV file. That got almost 10000 lines of data. Somehow my thresholding condition went wrong, and i got 10000 alerts in the screen now. And i don't know how to clear them out from the screen. Even i close the alarms it still stays in the screen.
The worse part is, when i click on the alert view, it takes lots of time to download all the alarms to the screen (Almost 5 to 10 mins). And i also noticed, it creates some files in my temp directory, which are as big as almost 1.5 GB, seems to me that the UI is caching these alarms there.
Sometimes when i click on the alert view, after 5 mins i receive a message saying , the UI was disconnected from the server (Seems to me like a timeout setting somewhere).
Pls.. Is there any way? i just want to clear all those alarms and get rid of them from my system :((.
Operational data does not get removed when classes get removed.
You can do this from the database:
DELETE FROM dbo.Alert
This will delete ALL alerts. Do this at your own risk, I take no responsibility for damage caused by editing the database directly. | http://blogs.msdn.com/b/jakuboleksy/archive/2006/09/27/sample-alert-and-state-change-insertion.aspx | CC-MAIN-2015-14 | refinedweb | 934 | 65.83 |
At 21:10 2002-11-05 +1300, Graeme Andrew wrote: >I know this is bad programming practice but I am desperate to set a global >variable that can be shared between modules. You can't to that. But you can use whatever module you like to store it in. H:\python\notglobal>type writeshared.py import shared shared.value = 'Hello' H:\python\notglobal>type readshared.py import shared print shared.value H:\python\notglobal>type shared.py pass H:\python\notglobal>python Python 2.2.1 (#34, Sep 27 2002, 18:37:42) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import writeshared >>> import readshared Hello >>> ^Z The four byte file shared.py can basically be seen as a free form non-persistent database here. :) Watch the power of dynamic programming! As usual, you are driving without any seat belts. It's up to you to make sure that you don't overwrite anything or make any mistake about assumed types, existing values etc. Putting "value = ''" in shared.py might be an indicator for its use, and will prevent an attribute error if it's read before it's written. If that's what you want... >I have a TKinter class module >that had a 'get' method to return what button was pushed. I want to store >the result of that 'get' call in a global variable that is accessable to all >the modules in the application. (the TKinter class is destroyed immediately >after the 'get' method is called) A more conventional and OO approach might be that a longer lasting class instance is responsible for shoving up the dialog that asks the questions, and that the dialog returns this value, which is then stored as an attribute in the calling class. The calling class would then pass either this attribute or self to those who need to access it. >As I undestand it the key word 'global' only pertains to the module it is >used in ?? Yes. >Any other ideas ? Would importing a 'global module' that has global >variables be the correct path to follow ?? I guess you mean what I showed above. Obviously it works. How do you mean "correct"? If you mean "politically correct", it depends on your political colour. ;) You are keeping the data confined in a particular name space at least. On the other hand, someone who inspects "sharedpy" might be confused--unles he is used to this idiom, in which case it will seem normal... If you overuse such a namespace, you will end up with a bad spaghetti structure that makes your program difficult to maintain. Whatever keeps the program as simple as possible is good. It's dificult to know what this might be. Some ways of working are excellent in small systems, but can't scale. Others are useful in large systems but overkill in simple apps. Am I confusing you? Maybe you should study more zen... ;) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 mailto:magnus@thinkware.se | https://mail.python.org/pipermail/tutor/2002-November/018353.html | CC-MAIN-2014-15 | refinedweb | 523 | 75.5 |
Using
will show you how to develop simple Struts Tiles
Application. You will learn how to setup the Struts Tiles and create example
page with it.
What is Struts...
Developing Simple Struts Tiles Application
tiles using struts2
tiles using struts2 hello,
im implementing tiles using struts2 in eclipse. i am having following problem occurred during execution.i have created.../struts-tiles.tld
org.apache.jasper.compiler.DefaultErrorHandler.jspEr Plugin
Tiles Plugin I have used tiles plugin in my projects but now I am... code written in tiles definition to execute two times and my project may has become slow.
Hi Friend,
Please visit the following link:
http
Struts
redirect with tiles - Struts
specify in detail and send me code.
Thanks. I using tiles in struts 2. And i want redirect to other definition tag by url tag. Please help me
tiles - Struts
Struts Tiles I need an example of Struts Tiles I want to create tiles programme using struts1.3.8 but i got jasper exception help me out
how to create an xml file in following clear format
how to create an xml file in following clear format anyone please help me out to create this file,,.
<Tasks>
<Taskid>1
<Taskname>Coding
<Project>CeMIC
<Date> tiles framework
struts tiles framework how could i include tld files in my web application
create a form using struts
create a form using struts How can I create a form for inputting text and uploading image using struts
Hey - Java Beginners
Hey How to program linear regression , and correalation coefficient while reading in two inputs from a file? using java with no applets Console
visually edit Struts, Tiles and Validator configuration files.
The Struts Console... Struts Console
The Struts Console is a FREE standalone Java Swing Tutorial
,
internationalization, error handling, tiles layout etc. Struts framework is also... the model
from view and the controller. Struts framework provides the following three... support of the utility and helper classes. Following is the view of the Struts
XML
XML create flat file with 20 records. Read the records using xml parser and show required details
Java - Struts
Java hello friends,
i am using struts, in that i am using tiles framework. here i wrote the following code in tiles-def.xml... doubt is when we are using struts tiles, is there no posibulity to use action class
Session management using tiles
Session management using tiles hi i am working on elearning project ..my problem is i am not able to maintain session over login's page..suppose if i logged in one user..and if i open another tab and logged in another account
Struts Articles
to Create Secure Web Applications with Struts
This article will focus..., but the examples should work in any container. We will create a Struts plugin class... can be implemented in many ways using Struts and having many developers working
read xml using java
read xml using java <p>to read multiple attributes and elements from xml in an order....
ex :component name="csl"\layerinterfacefile="poo.c...;
Please visit the following link:
Read XML data
Hey Guys really need to learn - Java Beginners
Hey Guys really need to learn Im a java beginner and i want to know how can i input 3 value.. Wath i mean is in C, to you to be able to input number... the following code to input three integers from the command prompt.
import
Hey neighbor, can you lend some Hammers?
Hey neighbor, can you lend some Hammers? import java.util.Date;
public class AccountProblem {
public static void main(String[] args) {
//create an instance object of class Stock
Account myAccount = new
;
Programming Jakarta Struts: Using Tiles... Tag Library. Using Tiles. The JSTL and Struts. Internationalization (I18N... Struts, and it is quite easy to implement the MVC architecture using the standard
struts
struts shopping cart project in struts with oracle database connection shopping cart project in struts with oracle database connection
Have a look at the following link:
Struts Shopping Cart using MySQL
Struts Tutorials
is provided with the example code. Many advance topics like Tiles, Struts Validation....
Using the Struts Validator
Follow along as Web development expert Brett... application development using Struts. I will address issues with designing Action
Struts Links - Links to Many Struts Resources
you how to develop Struts applications using ant and deploy on the JBoss... like Tiles, Struts Validation Framework, Java Script validations are covered... an application using Struts.
* use the Struts bean and html tags.
* process user
xml - XML
xml hi
convert xml document to xml string.i am using below code... Friend,
Please visit the following link:
Hope that it will be helpful for you
Jakarta Struts & Advanced JSP Course
Using Struts actions and action mappings to take control of ....
Using persistent data in a Struts application with
JDBC...
Basic XML
Jakarta Struts Training Course Outline
Java code for following
Java code for following Create a function that returns day difference between two dates (inclusive), without using any function provided by the platform or external library. The function must work for all dates in the range of 1
Create XML File using Servlet
Create XML File using Servlet
In this section, you will learn how to create xml file
using Servlet We have created file XmlServlet.java. It
creates
Create - XML File (Document)
Create - XML File (Document)
In this section, you will learn to create a XML
document using the DOM APIs. This XML document uses 1.0 version
and UTF-8
Using following-sibling in XPath
Using following-sibling in XPath
...
how one can use "following-sibling" axis in to the XPath
expression. "following-sibling" has some other working rather
than "
Developing Struts Application
outline of Struts, we can
enumerate the following points.
All requests... are also using
struts-tags named as 'html' tags. (for simplicity, we.... This is not JSTL
but Struts Tag Library. We should note the following very carefully
struts
the following links:... technologies like servlets, jsp,and struts.
i am doing one struts application where i doing validations by using DynaVAlidatorForm
in that have different fields
Struts Projects
learning easy
Using Spring framework in your application
Project in STRUTS Framework using MYSQL database as back end
Struts Projects are supported be fully...
Web Client to Search the database using Struts Hibernate Plugin
Struts Project Planning - Struts
Struts Project Planning Hi all,
I am creating a struts application.
Please suggest me following queries i have.
how do i decide how many classes and which they i should create??
My application wil be using database so
Developing Struts PlugIn
. There are many PlugIns available for struts e.g. Struts Tiles PlugIn, Struts... can create
your own PlugIn.
Understanding PlugIn
Struts PlugIns are configured using the <plug-in>
element within the Struts configuration
How to create XML from Swings
How to create XML from Swings How to create XML using Swings. I have a Swing GUI and capturing all data from it.When i click on submit, an xml... components and display it in xml file.
import java.io.*;
import java.util.*;
import
JAXB Create XML File And Get Data From XML
. In
this example at first we will create Java Classes to create an XML file using
Java...JAXB Create XML File And Get Data From XML
In this section we will read about how to create XML file and how to convert
XML file's data to Java Object
XML Tutorial
XML and HTML. You will also learn how to start using XML in your applications... following this kickstart tutorial. But you'll understand the basics of XML. And you'll... the kind of data that's been sent. By using XML everybody knows that the same
Using tiles-defs.xml in Tiles Application
Read XML using Java
Read XML using Java Hi All,
Good Morning,
I have been working... of all i need to read xml using java . i did good research in google and came to know...();
}
}
}
Parse XML using JDOM
import java.io.*;
import org.jdom.
java - Struts
java how can i get dynavalidation in my applications using struts... :
*)The form beans of DynaValidatorForm are created by Struts and you configure in the Struts config :
*)The Form Bean can be used
Create XMl dynamically - XML
Create XMl dynamically Hi
I am retreiving the list from database which i need to display in an XML file with some nodes
How can I do
create the SQL tables from an XML schema
create the SQL tables from an XML schema I'm using Eclipse,
Please let me know if anyone developped an application that would automatically create the SQL tables from an XML schema
covert the following using java
covert the following using java how to convert (for eg : 2.89) . this decimal to binary in java
How to prepare XML file?
How to prepare XML file? Hi,
I want to prepare XML File, can you tell me how should I do it?
Thanks.
Hello,
Following links can help you create an XML file..
Create XML File using Servlet
How to generate
Interview Questions - Struts Interview Questions
for your View.
See more at...?
Answer: tiles-def.xml is is an xml
file used to configure tiles... or Template tag library - For the application using tiles
* Nested tag
Struts - Struts
Struts Is Action class is thread safe in struts? if yes, how... safe. You can make it thread safe by using only local variables, not instance variables.
For more information, visit the following link:
http
struts - Struts
struts Hi,
I need the example programs for shopping cart using struts with my sql.
Please send the examples code as soon as possible.
please... visit the following link:
What is XML?
and create well formatted XML
document.
What is XML Document?
Some facts about XML..., SMIL, XHTML
etc. are created using XML
XML is markup language much...What is XML?
In the first section of XML tutorials we will learn the basics
Why XML?, Why XML is used for?
using database and flat files are
difficult.
XML is also used to create... is used?
We developers uses the XML files for following purposes:
Storing.... are using the XML language
We developers can used the XML data files to generate
Create XML - XML
Create XML
Hi,
Can you please provide java code,that will create xxx.XML file where all the attributes and values of those attributes... elements in your XML file: ");
String str = buff.readLine();
int developing - XML
xml developing I want to develop XML document with following DTD file with XML format. I have also XSL file as a externatl file to represent my xml in browser.
my problem is i want to create AUTO unique ID & checksum for each
validation in struts2 using .xml file
validation in struts2 using .xml file how to do xml validation in struts2 on dynamic fields
Hello Friend,
Please visit the following link:
Thanks
Struts 2.0.1
of enhancements and new features
Following are improvements made to Struts 2... Validator
* Struts plugin framework
* Create 'toolbox' module...
Struts 2.0.1
Now the new release
Hello World XML
To begin working with XML, you need to learn how to create xml file and how...:
In Mozilla:
In steps above, you learned how to create xml file and view it in browers.
Using CSS in XML:
6. Now you will see, how to add css (Cascading
with Struts Tiles |
Using
tiles-defs.xml in Tiles Application |
Struts... directory Structure |
Writing Jsp, Java and Configuration files |
Struts 2 xml... | Site
Map | Business Software
Services India
Struts 2.18 Tutorial Section
Error - Struts
create the url for that action then
"Struts Problem Report
Struts has detected....... will help you in writing your first Struts 2 applications using
Eclipse IDE. You can... in Struts 2, deploy on Tomcat 7 and test on browser.
Steps to Create Struts 2 Hello
XML in java - XML
XML in java Write a program using SAX that will count the number of occurrences of each element type in an XML document and display them... arguments. Hi Friend,
Please visit the following link:
http
Struts - Struts
in struts?
please it,s urgent........... session tracking? you mean session management?
we can maintain using class HttpSession.
the code follows... for u.the true keyword indicates that if no session is exist before,it will create new
Downloading Struts & Hibernate
the following steps to accomplish this:
1. Create a directory in you c: drive...-documentation.war, struts-examples.war,
struts-mailreader.war and tiles... the following
out put:
C:\Struts-Hibernate-Integration\code\WEB-INF
Struts Alternative
discussion forum.
<stxx/>
Struts for transforming XML with XSL (stxx) is an extension of the struts framework to support XML... not force you to go the XML route, both technologies will work side by side. Struts
XML and Velocity
XML and Velocity How to create xml file using velocity template engine | http://roseindia.net/tutorialhelp/comment/11852 | CC-MAIN-2014-15 | refinedweb | 2,145 | 65.62 |
I.
So the idea presented in the video is practically a series, where each term is shown as below:
Besides the alternating positive and negative sign, each term’s denominator is an odd number as well,
By summing up the series (it is a divergent series) up to
n elements, and multiply it by 4, we should be able to estimate a value close to Pi. So in short, the value we are looking for is
Surprisingly, the above statement can be represented in a line of python code (assuming
n = 100) without importing any package.
4 * sum((1 if k % 2 == 0 else -1) / ((2 * k) + 1) for k in range(100))
It is also noted in the video, where the estimated value of Pi is always alternating below and above the real value of Pi. In order to have an idea of how it looks in real life, I have expanded the code as follows:
import matplotlib.pyplot as plt from itertools import count from math import pi import pandas from sympy import * def f(k): return Rational(1 if k % 2 == 0 else -1, (2 * k) + 1) def item(): for k in count(): yield k, f(k) total = 0 history = {'k': [], 'pi': []} for k, item in item(): total += item print('k = {}: {}'.format(k, (4 * total if k < 6 else 4 * total.evalf()))) history['k'].append(k) history['pi'].append(float(4 * total.evalf())) if input('Continue? [Y|n]: ').strip().lower() == 'n': break pandas.Series(history['pi'], index=history['k']).plot() plt.show()
So running it (only tested with Python3, which is my default code target from now on) by allowing it to loop until
k = 20 yields the result below:
The estimation does seem to be approaching the real value of Pi as
n inceases. The reason I imported SymPy was to try seeing how the fraction grows, however it becomes increasingly difficult to make sense of after n > 5 hence I dropped the idea and show the result in decimal numbers instead.
So there it is, a quick and fun and short exercise in Python. | https://cslai.coolsilon.com/2016/03/20/sx-html/?color_scheme=default | CC-MAIN-2018-51 | refinedweb | 349 | 50.3 |
In this program user ask to check whether the number is even, odd, -ve, +ve. For this user need to use control statement like if-else. User put the condition if (a==0) then number is zero. if (a%2==0 && a>0) number is even and positive. if (a%2==0 && a<0) number is even and negative or if (a%2!=0 && a>0) number is odd and positive these are some conditions to verify the number pahse. And display result on the screen.
Problem Statement:
This is C program that asks user to check out the number positive, negative or zero.
Here is C source code for checking number phase. The output of this program shown below.
#include <conio.h>
void main ()
{
int a;
clrscr();
printf ("\nEnter a Number : ");
scanf ("%d",&a);
if (a==0)
printf ("\n\nThe Entered number is 0");
if (a%2==0 && a>0)
printf ("\n\nThe Number is Even and +ve");
if (a%2==0 && a<0)
printf ("\n\nThe Number is Even and -ve");
if (a%2!=0 && a>0)
printf ("\n\nThe Number is Odd and +ve");
if (a%2!=0 && a<0)
printf ("\n\nThe Number is Odd and -ve");
getch();
}
Output :
Enter a Number : 10
The Number is Even and | http://ecomputernotes.com/c-program/to-find-if-the-number-is-odd-or-even-ve-or-ve-or-zero | CC-MAIN-2019-04 | refinedweb | 212 | 82.75 |
I've blogged several times about how I like to handle services in Silverlight. For two key posts, take a look at:
- Abstracting Service Calls in Silverlight 3 (works well for 4, too)
- Simplifying Asynchronous Calls in Silverlight using Action
In this post we'll explore the difference between using the actual contract for a WCF service in Silverlight versus using the generated client. The difference is subtle but important, and involves not only the event-based model and the Asynchronous Programming Model (APM) but also some nuances with threads.
There is no code project for this because the nuance is in the way you call the service, not the example itself, but there should be enough code in this post for you to recreate the example if you want to test it yourself.
Here's the rub: let's create a simple service that adds two integers and returns the result. The contract is simply:
[ServiceContract(Namespace = "")] public interface IAddService { [OperationContract] int Add(int x, int y); }
Now we can implement it - just add the numbers and return the value:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class AddService : IAddService { public int Add(int x, int y) { return x + y; } }
So that's easy enough (and we've jumped through our first Silverlight hoop by flagging the service with the compatibility attribute). Now we'll fire up a new Silverlight application and reference the service. I'm not doing anything fancy, just discovering the service within the project and letting Silverlight generate the code. Now things get a little more interesting.
Let's add two list boxes that will race each other for results. They are bound to a simple list of integers:
<UserControl.Resources> <DataTemplate x: <TextBlock Text="{Binding}"/> </DataTemplate> </UserControl.Resources> <Grid x: <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="1*"/> </Grid.ColumnDefinitions> <TextBlock Text="Events"/> <TextBlock Text="APM" Grid. <ListBox x: <ListBox x: </Grid>
As you might have already guessed, we're going to use the event model and the APM model. Let's wire some code.
First, two collections to hold the results. I also bind the data context to itself so I can bind to the series in the code-behind.
private const int MAX = 999999999; public ObservableCollection<int> Series1 { get; private set; } public ObservableCollection<int> Series2 { get; private set; } public MainPage() { InitializeComponent(); Loaded += (o, e) => LayoutRoot.DataContext = this; Series1 = new ObservableCollection<int>(); Series2 = new ObservableCollection<int>(); if (DesignerProperties.IsInDesignTool) return; _Series1(); _Series2(); }
The Main Event
Now let's implement a Fibonacci sequence using the event-based model:
private void _Series1() { var y = 1; var x = 1; var client = new AddServiceClient(); Series1.Add(1); client.AddCompleted += (o, e) => { x = e.Result; Series1.Add(x); var z = y; y = x; if (x < MAX) { client.AddAsync(x, z); } }; client.AddAsync(x, y); }
Notice how we recursively call the service. What is also important to note, however, is that there is no special use of the dispatcher. I know for a fact this will come back to me on the UI thread. Why? Because I registered the event on the UI thread, and that registration is where the return call will go. I can prove it because despite the fact the series is databound to the UI, it populates without any issue.
Switching to the Asynchronous Programming Model
Now, let's wire the same service using the Asynchronous Programming Model (APM). I'm going to kick it off the same way and in the same context as the event-based version. Notice that because Silverlight creates the client proxy using the event-based model, I actually have to cast the client to the interface in order to take advantage of the APM model.
The APM call adds two methods. One is an
AsyncCallback delegate that will be called when the service is done fetching results, and the other is an optional object to store state (this is passed to the callback so you can reference data from the original call).
private void _Series2() { // add the first item Series2.Add(1); var client = (IAddService) new AddServiceClient(); AsyncCallback end = null; end = ar => { var state = ar.AsyncState as Tuple<IAddService, int>; if (state == null) return; var x = state.Item1.EndAdd(ar); var y = state.Item2; Deployment.Current.Dispatcher.BeginInvoke(() => Series2.Add(x)); if (x < MAX) { state.Item1.BeginAdd(x, y, end, Tuple.Create(state.Item1, x)); } }; client.BeginAdd(1, 1, end, Tuple.Create(client,1)); }
There's a bit going on there - I preserve the original client along with the current value in the state by casting them both into a tuple, and unroll them in the callback. The call is recursive until the max is reached, just like the event model, and using an anonymous method. However, there is a subtle difference between the
AddAsync method we called earlier and the
BeginAdd method here.
The difference? Our "end" callback is not invoked on the UI thread! The APM model lets the result come back on a different thread. If you take out the dispatcher call I use to populate the series and add the value directly, you'll get a cross-thread exception.
So what does this mean?
Most of the time, quite frankly, not much. In my tests, the bulk of the time for the process to run is taken in the service call going over the wire and coming back, and there is little noticeable difference between staying on the UI thread or not (even on a local machine).
However, if you are receiving a result and doing heavy processing before displaying the data, you don't want to return on the UI thread. It's wasteful and can causing blocking, the exact thing the asynchronous pattern is supposed to avoid! While you could send your work to a background worker, the easiest solution is to use the APM model. You'll return on a background thread where you can do all of your heavy lifting and simply dispatch the result when you're ready.
Bottom line: when using services in Silverlight, know where your results land! | https://csharperimage.jeremylikness.com/2010_11_01_archive.html | CC-MAIN-2017-39 | refinedweb | 1,017 | 55.44 |
I need help with some math.....
Suppose I need to decrease a value from 255 to 0, in x amount of milliseconds. What amount of value would I need to decrease each millisecond so it is 0 when the x amount of milliseconds have passed?
Sorry I'm not that good at math
@AHK1221 Divide 255 by the total number of milliseconds and then multiply that number by the number of milliseconds that elapse each frame and subtract it from your running total.
That seems to work in my head.
@LeeC2202 Seems to work after doing some calcs on the calculator, will test in code. Thanks!!
I'm not good at math either but, assuming you mean What amount of value would you need to decrease per second, so it is zero when X amount of milliseconds have passed. If you mean what value you would need to decrease per millisecond then you would be dealing with microseconds, and there are 1000µs(Microseconds) in a single millisecond. In that case, this would start to get confusing for me. Reducing 255 to 0, would take 255 microseconds if decreased at a rate of 1 per microsecond. It would take half that time if decreased at a rate of 2 per microsecond. I'm pretty sure I'm correct, but like I said. I'm not good at math. 😂 So let's see here.. We have a integer of 255, if we take 1 from that every 1000 milliseconds, it's gonna be at 0 in 255,000 milliseconds, or 255,000,000 microseconds. If we take 1 from it every 500 milliseconds, it would be at 0 in [Now Divide 255 by 2 and get 127.5] half the time.
255; -=1/s(1000ms)=[4.250 Minutes] 255s {255000ms}
255;-=2/s(1000ms)= [2.125 Minutes] 127.5s {127500ms}
255;-=3/s(1000ms)= [1.416 Minutes] 84.96s {84960ms}
255;-=4/s(1000ms)= [1.060 Minutes] 63.60s {65600ms}
255;-=5/s(1000ms)= [0.850 Minutes] 51.00s {51000ms}
So if you reduce 255 by 5 every 1000ms, those are the times it would take to reach 0.
Reducing 255 to 0 takes 255,000 milliseconds if reduced by 1 every 1000 milliseconds.
Reducing 255 to 0 takes 127,500 milliseconds if reduced by 2 every 1000 milliseconds.
Reducing 255 to 0 takes 84,960 milliseconds if reduced by 3 every 1000 milliseconds.
Reducing 255 to 0 takes 65,600 milliseconds if reduced by 4 every 1000 milliseconds.
Reducing 255 to 0 takes 51,000 milliseconds if reduced by 5 every 1000 milliseconds.
Do you have any Ibuprofen now?
My approach to this problem was starting like this.
We know that if we have 255, that it will be 0,
If decreased by 1 every millisecond, that it would take 255 milliseconds to get to down to 0.
If we divide 255 by 2, it would take half the time. Now we're reducing it twice as fast.
If decreased by 2 every millisecond, it would take 127.5 milliseconds.
You could start cutting the milliseconds in half if you needed to, 1 millisecond is 1000 microseconds. Reduce it by 1 every millisecond or reduce it by 1 every half a millisecond if you can only take 1 at a time away. There's many ways to do it, it depends on exactly what you need to do.
So from that point you just divide 255 by 3, 4 or 5 and that's how many milliseconds it would take to reduce 255 to 0.
255 - 5 every millisecond = 51 milliseconds.
So, what hellacious script are you working on now? It's not that car spawning script is it?
@JZersche He isn't looking for the time it would take for 255 to get to zero.
Time is a variable factor, 255 is a fixed constant and what he was looking for was the amount to decrease 255 by with a variable time factor.
To break that down into amount per millisecond, you simply divided 255 by the total number of milliseconds. On a 60Hz display, each frame could be either 16ms or 17ms (1000 / 60), so multiplying that number gives you the amount to decrement by per display update.
Basically:
AmountToDecrementBy = (255 / TotalTimeInMilliseconds) * elapsedMillisecondsPerFrame
So no matter what you change the time to, 255 will always end up at 0 at the end of that time period.
@LeeC2202
"What amount of value would I need to decrease each millisecond so it is 0 when the x amount of milliseconds have passed?"
You would need to decrease 1 each millisecond so it's 0 when 255 amount of milliseconds have passed.
You would need to decrease 0.5 each millisecond so it's 0 when 500 amount of milliseconds have passed.
You would need to decrease 0.3 each millisecond so it's 0 when 765 amount of milliseconds have passed.
You would need to decrease 0.25 each millisecond so it's 0 when 1020 amount of milliseconds have passed.
That's the way I read it.
The way you did it is more logical, that's just the way I would think of working it out, I couldn't figure out the procedure in such a simple formula in my head like you could, I have to think about it.
@JZersche x is an unknown factor. Therefore x could be 1000 milliseconds or it could be 4000 milliseconds.
So what he is asking, is what percentage of 255 do I need to decrease by, to make sure that no matter how long x is, it is always 0 at the end of that time period.
@LeeC2202
Yeah it's whatever, Math gives me a headache. I was providing a way to figure it out by using 255 as a reference.
By starting at 255, you could divide 255 and cut it in half or double it, and that's another way of working that out. I followed the same procedure you did actually only I used seconds in the second place. The difference is the fact that I got a headache while doing it and you likely didn't.
255;-=2/s(1000ms)
Would better be interpreted as 255 / 2000ms * (1000ms)
Although I didn't realize changing the 2nd numbers to ms, and multiplying it by the third would give the answer to his question.
But at least I did the math correctly.
I barely knew what I was doing and ended up with the same order of events sort of lol. I think I got confused when the amount of time passing between each decrement was unclear as he stated 'each millisecond'
255 / TotalTimeInMilliseconds) * elapsedMillisecondsPerFrame
@JZersche I use a similar kind of process in my camera mod to ensure that a probe rotates through 360 degrees in a fixed period of time. One might rotate that amount every 2 seconds, another might rotate that amount in 5 seconds.
Using the elapsed time ensures that if the FPS fluctuates, the time calculations compensate to maintain a consistent movement value.
@LeeC2202
I take it you're well knowledged in programming.
Edit: I just thought about the way you did it in more detail, and it makes perfect sense. This thread has made me 'slightly' better at math.
@JZersche I'm actually an artist by profession. I started working on games in 1985, it's something I have always been around. I learned to programme to get more involved in game creation. I'm not particularly good at it but I get by.
@LeeC2202 Well, theres been a lot of thought process that went into this problem.. I used your formula(?) and it works for the most part except... it takes nearly a lot of time(i didnt measure so...) when I input 1000 ms. To get the result I wanted, I had to input 20 as the timeout. Heres most of the code:
static float alpha = 255; public static void Timer_Tick(object sender, EventArgs e, int interval) { if(isShowing && timePassed <= timeout) { DrawRect(new Vector2(0, 0), 2, 2, Color.FromArgb((int)alpha, 255, 255, 255)); float numToSubtract = (255f / timeout) * interval; alpha -= numToSubtract; timePassed += interval; } else if(timePassed >= timeout) { isShowing = false; timePassed = 0; timeout = 0; alpha = 255; } }
timeout is the unknown factor(x) in my original question, and timePasssed is.... timePassed.
@AHK1221 Let me just copy this into a file so I can read it outside this scrolling box.
What values are getting passed in as interval? Are they something like 16 or 17?
@LeeC2202 For my sanity's sake, I've set the interval(in other script) as 1. So the interval is always 1. Though I suppose Game.LastFrameTime would work fine?
@AHK1221 Interval must be the number of milliseconds between the last time it was called and this time. An interval of 0 (for the OnTick update rate) will update every 16 or 17 milliseconds on a 60Hz display with VSync on.
I always have this in my OnTick to calculate that:
CurrentGameTime = Game.GameTime; ElapsedGameTime = CurrentGameTime - LastGameTime; LastGameTime = CurrentGameTime;
Along with these variables.
private int CurrentGameTime; private int ElapsedGameTime; private int LastGameTime;
So with a timeout of 1000ms, you should get (255 / 1000) * 16 = 4.08
@LeeC2202 So.. I need to pass Game.GameTime as the Interval?
@AHK1221 You need to pass the difference between the last Game.GameTime and the current Game.GameTime, or calculate it in that function.
I think there is also Game.LastFrameTime, which usually reports back as something like 0.016, which you can also use as a multiplier. 255 * 0.016 = 4.08. So if you had the timeout in seconds, rather than milliseconds, for 4 seconds you could do something like this.
int NumSecs = 4; var NumToDec = (255f * Game.LastFrameTime) / NumSecs;
I think that should work the same... I haven't done it that way though.
@LeeC2202 I'm sorry, I really dont get the gist of this.
timeout is in milliseconds, so that doesnt work for me.
Passing in the ElapsedGameTime results in the same way Game.GameTime does... it appears for what appears to be a second? 500 ms? A quick flash. Even if the value is increased, to say, 10 seconds.
@AHK1221 Give me a couple of ticks and I'll see if I can put it in a better format.
Going off my inability to explain things today, I could be adding to the confusion... will only be a couple of minutes.
If no-one can figure this out. I have a buddy I could talk to, he'll know. He's a last resort though, he's always busy and no promised response, but he'll definitely know how to do whatever it is you're trying to do in your script. I'm guessing this is C++ or C? What is the script for particularly? (Message me that information if you want)
@LeeC2202 ATM I'm using the same method that made me pass in 30 for it to stay for around 2-3 secs. At least it works.. right?
@AHK1221 Okay, paste this into a .cs file.
using System; using GTA; namespace TimeOutTest { public class cTimeOutTest : Script { private int CurrentGameTime; private int ElapsedGameTime; private int LastGameTime; float PseudoAlpha1; float PseudoAlpha2; const int TimeOut = 10000; const int TimeOutSecs = 5; public cTimeOutTest() { this.Tick += onTick; Interval = 0; PseudoAlpha1 = 255; PseudoAlpha2 = 255; LastGameTime = Game.GameTime; } private void onTick(object sender, EventArgs e) { CurrentGameTime = Game.GameTime; ElapsedGameTime = CurrentGameTime - LastGameTime; LastGameTime = CurrentGameTime; DoAlpha1(ElapsedGameTime); DoAlpha2(); string display = string.Format("Alpha 1: {0}, Alpha 2: {1}", PseudoAlpha1, PseudoAlpha2); UI.ShowSubtitle(display); } private void DoAlpha1(int ElapsedGameTime) { float NumToDec = (255f / TimeOut) * ElapsedGameTime; PseudoAlpha1 -= NumToDec; if (PseudoAlpha1 < 0) PseudoAlpha1 = 255; } private void DoAlpha2() { float NumToDec = (255f * Game.LastFrameTime) / TimeOutSecs; PseudoAlpha2 -= NumToDec; if (PseudoAlpha2 < 0) PseudoAlpha2 = 255; } } }
That shows both ways of decrementing the value, using both the ElapsedTime and the Game.GameTime method.
@LeeC2202 Wait nvm im stuped .
@AHK1221 Look at the consts, Alpha 2 is on a 5 second fade, Alpha 1 is on 10 seconds. I just made them different so you could see something different happening. | https://forums.gta5-mods.com/topic/9880/i-need-help-with-some-math | CC-MAIN-2021-31 | refinedweb | 2,018 | 74.59 |
This C Program calculates the roots of a quadratic equation. First it finds discriminant using the formula : disc = b * b – 4 * a * c. There are 3 types of roots. They are complex, distinct & equal roots. We have to find the given equation belongs to which type of root.
Here is source code of the C program to calculate the roots of a quadratic equation. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to find out the roots of a quadratic equation
* for non-zero coefficients. In case of errors the program
* should report suitable error message.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main()
{
float a, b, c, root1, root2;
float realp, imagp, disc;
printf("Enter the values of a, b and c \n");
scanf("%f %f %f", &a, &b, &c);
/* If a = 0, it is not a quadratic equation */
if (a == 0 || b == 0 || c == 0)
{
printf("Error: Roots cannot be determined \n");
exit(1);
}
else
{
disc = b * b - 4.0 * a * c;
if (disc < 0)
{
printf("Imaginary Roots\n");
realp = -b / (2.0 * a) ;
imagp = sqrt(abs(disc)) / (2.0 * a);
printf("Root1 = %f +i %f\n", realp, imagp);
printf("Root2 = %f -i %f\n", realp, imagp);
}
else if (disc == 0)
{
printf("Roots are real and equal\n");
root1 = -b / (2.0 * a);
root2 = root1;
printf("Root1 = %f\n", root1);
printf("Root2 = %f\n", root2);
}
else if (disc > 0 )
{
printf("Roots are real and distinct \n");
root1 =(-b + sqrt(disc)) / (2.0 * a);
root2 =(-b - sqrt(disc)) / (2.0 * a);
printf("Root1 = %f \n", root1);
printf("Root2 = %f \n", root2);
}
}
}
$ cc pgm7.c -lm $ a.out Enter the values of a, b and c 45 50 65 Imaginary Roots Root1 = -0.555556 +i 1.065740 Root2 = -0.555556 -i 1.065740. | http://www.sanfoundry.com/c-program-roots-quadratic-equation/ | CC-MAIN-2017-39 | refinedweb | 309 | 76.93 |
On Wed, Sep 14, 2011 at 2:40 AM, Terry Ellison <terrye@apache.org> wrote:
> As has been pointed out by posters on this DL, I've now "resigned" twice
> from the project. On the first occasion I said I was leaving but committed
> to finish off my forum / wiki work first as long as we could avoid a
> ping-pong of personal criticisms / hostile posting on the ooo-dev DL. The
> second time I dropped this commitment because it became clear to me that we
> were again slipping into personal attacks. Even so, what I don't want to
> happen is for my decision to leave to cause a "denial of service" because of
> my being a "single point of failure" for some activities. However, I won't
> discuss this thread further on this DL. I leave this to TJ et al. I will
> reply to constructive personal emails, and am happy for any recipients to
> quote that content here.
>
> In the case of the forums, the bulk of the setup work had already been
> completed and so I have been working with Drew Jensen in the background to
> transfer their support and administration to him should the project decide
> to proceed with this migration. I have pretty much documented these tasks.
>
> The wiki is a somewhat different issue, because this work wasn't so far
> along, and so I wanted to make some statement on the DL on this. We have a
> stable build of MW 1.15.5 (albeit not in svn) running on
> ooo-wiki.apache.org with a stale but recent clone of the production wiki
> on it, as the only material content updates have been by a user Hohenheim to
> some of the OOoES NL pages. I have also activated TJ's account and upgraded
> this to admin / bureaucrat, and I am willing to offer TJ the same occasional
> support that I am currently providing to Drew whilst he gets up to speed.
>
Also if there is something we could do to support the migration we have a
couple of VPS running with available space and bandwith. Unfortunately at
the moment we still have some todo with the BZ skinning and templates for
the issues.apache.org/ooo site. should this be renamed to
isuess-ooo.apache.org?
Regards.
>
> Whatever the project's long term plans for the wiki, it will remain provide
> a useful reference resource from which to migrate content if the Oracle
> service is shut down. IIRC, a couple of contributors / committers have
> asked for a copy of the schema and content so that they can work on it and
> on any data migration. So making this available seems to be a sensible way
> ahead since the vast majority of the content is already publicly accessible
> and could used / scraped under the terms of the PDL, etc. I will place this
> on the usOOo site. So please expect to see a file
>
next at the weekend which will explain how to download this content.
>
I'll dl that to our servers just in case we need extra redundancy.
>
> The issue that I need to be careful about (really on behalf of Oracle / the
> old OOo projects) is that some data elements are not already publicly
> accessible and which could in my view be deemed to be personal data falling
> under EU Data Protection legislation, so I would need to be a little careful
> about how I expunge these from any copy for developers. As far as I can see
> these could all be mangled to avoid such issues:
>
> *user_password*
> This is already stored in highly mangled (MD5 including salt) format so is
> not readily attacked apart from brute force guessing. What I will do is to
> replace 3 internal letters by 3 pseudo random letters to make such this
> attack more impractical. (see note 1)
>
> *user_real_name
> *This field is not made publicly available, and is only used for content
> attribution. I will therefore blank this in the dump. However I will keep
> a copy and make this accessible to any PPMC member who warrants that this
> will be used for the purposes of content attribution.
>
> *user_email*
> This field is not publicly available. I will replace it by
> strcat(md5(user_email), '@dummy.com') (see note 1)
>
> *watchlist
> *Remove all watchlist entries. Users can always recreate their own list.
>
How was this part handled for OOo's BZ? My guess is that there was no public
download so this was never an issue.
>
> *Notes:
> *
> 1. Part of my reason for doing this was a point that Rob made: that Apache
> should require users to explicitly acknowledge some form of ToU as part of
> re-registering to recover any existing account. I have already started to
> develop a MediaWiki extension form on my VM MW 1.17.0 version which would
> allow any user to "reconnect" to his/her account if either (i) they knew the
> existing password, or (ii) knew the existing email address and could issue
> email confirmation from that address. Any competent PHP/MW developer could
> easily do this with the above data element mangling.
>
> 2. I will delete all accounts that have made no contributions to the Main
> or User namespaces.
>
> 3. I am still concerned about this whole issue of content attribution.
> IIRC, under the old OCA contributors only vested joint rights to Sun/Oracle
> and free licence on any patents. The base copyright and patents were
> maintained by the originator. The PDL is even tighter of contributor rights
> retention. So far we have discarded all audit of contribution in svn and
> are currently considering doing likewise for documentation content, dropping
> contribution audit trails and defaulting to blanket Apache copyright. As
> some third parties might take a different view on this, I propose to keep a
> full private archive of the D/B myself as an independent audit reference.
>
> With these changes, I would be happy to put a copy of the wiki dump on one
> of the old OOo servers so that it could be pulled by any ooo-dev developers.
>
--
*Alexandro Colorado*
*OpenOffice.org* Español
fingerprint: E62B CF77 1BEA 0749 C0B8 50B9 3DE6 A84A 68D0 72E6 | http://mail-archives.apache.org/mod_mbox/incubator-ooo-dev/201109.mbox/%3CCAMK9kTgn66R_S4rWKqRLEdK2TF-hfpy_Y=Pi8xGE9MqMPzqpTg@mail.gmail.com%3E | CC-MAIN-2016-22 | refinedweb | 1,029 | 68.2 |
Guest blog by Charig Yang. I am a second-year engineering student at the University of Oxford and Microsoft Student Partner.
I am interested in electronic and information engineering, particularly in telecommunications and digital control systems. I also have enthusiasm in education and science communication. I teach part-time as a tutor during term time and organise educational camps during my holidays. Outside academics, I am into dogs and board games.
Introduction
In this project, I built a model for a temperature regulation system that can be used for small-scale temperature control. Admittedly the motor output can be too weak to have a high influence in non-trivial scale systems, but the underlying principles are still the same. A simplified flowchart of how things work looks like this:
Simplified block diagram of the process
I intend to make this blog beginner-friendly, starting with what to do after getting the Pi, setting up, and the problems that might be encountered.
Part 1: Setting Up the Raspberry Pi
In this part I will cover how to setup the Raspberry Pi and start using it. To do this, you need a Raspberry Pi, an SD card (which should come with your Pi) with an adapter, a power supply connected through the micro-USB port (bottom left), an Ethernet cable
Do note that if you are using wifi for internet connection, you will need to check whether your version of Raspberry Pi has pre-installed wifi capability (Raspberry Pi 3), if not you will need a wifi dongle. Be careful here as not all wifi dongles are supported in the IoT Core. Check [] before you buy one!
I got mine from [].
Instructions
- Download Windows 10 IoT Core Dashboard here:
- You will see this page, click on Set up a new device
- Fill in your device name and password, make sure you get the Device type right, then click on Download and Install
- The installation should take a while, but will be ready in a bit. Once it is ready, plug in your SD card into the slot at the left side, from below the board.
- Optionally, you may want to connect your Pi in a similar manner to a computer. (Without this you can still control your Pi through your PC, which will be illustrated in a while)
The extra connection to the right are the mouse and keyboard. The small thing lying on top is the Wifi dongle (but I am using Ethernet here, so that is not needed). Below is a connection to a monitor screen via a HDMI(digital, left)-to-VGA(analog, right) converter. The Pi only has a digital output (left), so you will need a converter if your screen is analog (right). I got mine from []
- Here’s a fully set-up Raspberry Pi using IoT Core - it functions just like a computer! The picture shows the Pi playing a Youtube video.
- You can also access the Pi from your computer by using the Windows Device Portal. Once connected, re-open the IoT Core Dashboard (the one that is used for IoT Core installation). Under My Devices tab (which was empty), you can now open the Windows Device Portal
With the Device Portal, you can do several stuff from your PC such as Capture Screenshot (under Device Settings)
Run Command under the Processes tab (see the command list and what they do at [])
Or even run an app! This is done under the Apps Manager section
Part 2: FEZ Hat and Hardware Setup
This time we will be using a FEZ Hat (stands for Fast and Easy) to do the project. It is pretty convenient as you can just put the Hat on top of the Pi. The setup looks like this:
Raspberry Pi Set-up
Note the breadboard behind is unrelated, but it shows how a temperature sensor, button, and LED separately, but they are all built-in within the FEZ Hat, so we will stick to that.
The connections to the Pi might look a lot, but they are things that are very close to us! Clockwise from the top are
- a Wifi Dongle (Raspberry Pi 2 does not come with wifi connection, so this allows the Pi to connect to the internet
- an extender that connects to a mouse and a keyboard
- an Ethernet cable that connects the Pi to the PC
- a connection to a monitor screen via a HDMI(digital)-to-VGA(analog) converter. Raspberry Pi only has a digital output, but my screen is analog, so that is needed
- a power supply
- a servo motor (which, in practice, can be replaced by a fan, heater, or something of similar nature)
Things to note:
The FEZ Hat has to be plugged into the Pi, simply putting it on top of the Pi, while it actually looks secure, does not connect them. Also make sure you plug into the right socket, it is quite easy to miss it by one pin, and doing so will short the Pi.
Also, the wires of the servo are connected this way, with positive at red, negative at black, and signal at orange/yellow. Some other servos may use other colours for signal but positive and negative should always be red and black.
Part 3: Using FEZ Hat’s Temperature Sensor
Before we begin, it is necessary to have Microsoft Visual Studio downloaded, it can be downloaded via this link []
To create a new project, follow the instructions in the photo below, note that it would be convenient to set the name of the project as FEZHATDemo so that it matches the code, but the code can be edited if the name is different, not a big issue here.
In Microsoft Visual Studio, there is a Package by the FEZ Hat provider called GHIElectronics.UWP.Shields.FEZHAT which commands the locations within the Hat (otherwise we won’t know where the temperature sensor is!).
This can be installed via Nuget, shown below
The code that reads the status of the FEZ Hat is pasted here, it can be downloaded from
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using GIS = GHIElectronics.UWP.Shields;
namespace FEZHATDemo {
public sealed partial class MainPage : Page {
private GIS.FEZHAT hat;
private DispatcherTimer timer;
private bool next;
private int i;
public MainPage() {
this.InitializeComponent();
this.Setup();
}
private async void Setup() {
this.hat = await GIS.FEZHAT.CreateAsync();
this.hat.S1.SetLimits(500, 2400, 0, 180);
this.hat.S2.SetLimits(500, 2400, 0, 180);
this.timer = new DispatcherTimer();
this.timer.Interval = TimeSpan.FromMilliseconds(100);
this.timer.Tick += this.OnTick;
this.timer.Start();
}
private void OnTick(object sender, object e) {
double x, y, z;
this.hat.GetAcceleration(out x, out y, out z);
this.LightTextBox.Text = this.hat.GetLightLevel().ToString("P2");
this.TempTextBox.Text = this.hat.GetTemperature().ToString("N2");
this.AccelTextBox.Text = $"({x:N2}, {y:N2}, {z:N2})";
this.Button18TextBox.Text = this.hat.IsDIO18Pressed().ToString();
this.Button22TextBox.Text = this.hat.IsDIO22Pressed().ToString();
this.AnalogTextBox.Text = this.hat.ReadAnalog(GIS.FEZHAT.AnalogPin.Ain1).ToString("N2");
if ((this.i++ % 5) == 0) {
this.LedsTextBox.Text = this.next.ToString();
this.hat.DIO24On = this.next;
this.hat.D2.Color = this.next ? GIS.FEZHAT.Color.White : GIS.FEZHAT.Color.Black;
this.hat.D3.Color = this.next ? GIS.FEZHAT.Color.White : GIS.FEZHAT.Color.Black;
this.hat.WriteDigital(GIS.FEZHAT.DigitalPin.DIO16, this.next);
this.hat.WriteDigital(GIS.FEZHAT.DigitalPin.DIO26, this.next);
this.hat.SetPwmDutyCycle(GIS.FEZHAT.PwmPin.Pwm5, this.next ? 1.0 : 0.0);
this.hat.SetPwmDutyCycle(GIS.FEZHAT.PwmPin.Pwm6, this.next ? 1.0 : 0.0);
this.hat.SetPwmDutyCycle(GIS.FEZHAT.PwmPin.Pwm7, this.next ? 1.0 : 0.0);
this.hat.SetPwmDutyCycle(GIS.FEZHAT.PwmPin.Pwm11, this.next ? 1.0 : 0.0);
this.hat.SetPwmDutyCycle(GIS.FEZHAT.PwmPin.Pwm12, this.next ? 1.0 : 0.0);
this.next = !this.next;
}
if (this.hat.IsDIO18Pressed()) {
this.hat.S1.Position += 5.0;
this.hat.S2.Position += 5.0;
if (this.hat.S1.Position >;= 180.0) {
this.hat.S1.Position = 0.0;
this.hat.S2.Position = 0.0;
}
}
if (this.hat.IsDIO22Pressed()) {
if (this.hat.MotorA.Speed == 0.0) {
this.hat.MotorA.Speed = 0.5;
this.hat.MotorB.Speed = -0.7;
}
}
else {
if (this.hat.MotorA.Speed != 0.0) {
this.hat.MotorA.Speed = 0.0;
this.hat.MotorB.Speed = 0.0;
}
}
}
}
}
<;Page x:
<;StackPanel
<;StackPanel
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;/StackPanel>
<;StackPanel>
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;TextBlock
<;/StackPanel>
<;/StackPanel>
<;/Page>
Double click the names in bold in your file and paste the whole code into that. Edit all entries after the word namespace to make sure they match
Leave the rest of the code as it is. We also have to configure the remote debugging in the Raspberry Pi in order to send the code to the Pi and run it there, instructions below
We are finally ready to go!
If you connect your Pi to a screen you should see the program running on the screen after clicking the Remote Machine button. Otherwise you should be able to see it running in the Windows Device Portal, under the Apps Manager tab
It would be useful to gain some insight to what the code is doing, consider this:
this.timer = new DispatcherTimer();
this.timer.Interval = TimeSpan.FromMilliseconds(100);
this.timer.Tick += this.OnTick;
this.timer.Start();
This means the timer ticks every 100 milliseconds (0.1 second)
private void OnTick(object sender, object e)
this.LightTextBox.Text = this.hat.GetLightLevel().ToString("P2", CultureInfo.InvariantCulture);
this.TempTextBox.Text = this.hat.GetTemperature().ToString("N2", CultureInfo.InvariantCulture);
this.Button18TextBox.Text = this.hat.IsDIO18Pressed().ToString();
this.Button22TextBox.Text = this.hat.IsDIO22Pressed().ToString();
This reads the value and shows it on every tick
Note that the code is not continuous! It is extracted for user-friendliness
Potential Errors and Fixes:
Make sure you
- Adjust the time [ under Setting Date_Time on IoTCore.docx]
- Label all the indexes correctly, especially the words after namespace in each code
- Make sure you connected the Pi to the PC (check through IoT Core Dashboard)
- Make sure you plugged in the Pi all the way in
Aside: Temperature Sensors and Signal Conditioning
This is not related to the main project, but just some insight to how a temperature sensor works. You might know that a thermistor is a resistor that changes its resistance when it is heated. The question remains: how then does it becomes a numerical reading of temperature? This is how it begins, the circuit measures Vin and Vout and hence can find the value of R and X
If we know R, Vout, Vin, we can find X. And if we compare it to reference value of X (e.g. X will be this at this temperature) then we know what temperature this is. This sounds straightforward in concept, but not mathematically. It is possible to build circuits that can be used configured to make sure that the temperature deviation is (largely) proportional to the change in the output voltage, and hence Vout can be used directly.
After we know the temperature we will have to send the (analog) signal to wherever we want. To do this, we need to amplify first (because Vout is normally in micro- to millivolts, if we just want to measure the level there is no need for a big voltage anyway) However do note that the output voltage cannot be too small as there might be random noises, and we have to make sure that the noise does not alter the reading. Then we pass it through a converter to make it a digital signal (zeros and ones). You can read on bridge circuits, instrumentation amplifiers and analog-to-digital converters if you are interested in this.
Part 4: The “I” in IoT - Connecting Data to Azure
This part concerns sending the data received from the sensors to Azure IoT Hub. The instructions are fully laid out in this link [] under the section Send telemetry data to the Azure IoT Hub. What we will focus in this section, however, is how to transfer data from the IoT Hub into a table format after we have connected the data.
First, we need to create a storage account. Do remember to use the existing resource group that is the same one used for IoT Core
Then we create Stream Analytics, this can be seen as a bridge linking the data between the IoT Hub and Storage Account
We select the input as the IoT Hub (named Raspberrypi here) and the output as Table. Each of them has to be configured individually.
The diagram shows that we are selecting data from [Raspberrypi] into [Table]
Do note that Stream Analytics is much more capable than this - it can take several inputs (say in an engine: pressure, temperature, velocity, etc) and present them in a single table. Not only this saves time, but it also makes sure that the data points are, to a large extent, synchronised.
As an example, let’s say if we want to control the temperature of a computer. We can activate the fan once the temperature is high enough, but that’s pretty much all we can do. If we have enough data, however, we can be a lot more predictive than that. We will know in average how long is required before the computer gets to a certain temperature, and protect it defensively rather than waiting for it to exceed. In a shorter term, we can also gain insight to the rate of increase of the temperature at the moment and guess when it will reach critical level.
As a side note, we could have used the Event Hub instead of IoT Hub up to this point, as the Event hub only allows Azure to receive data from the device, but not the other way round. Anything after this requires IoT Hub to send the data to the device.
Up to this point, we should have a table of the data recordings, and for the next section we will focus on how to use them.
Aside: The Servo Motor
Although knowing how to control the servo is useful, in actual temperature sensing systems we will instead connect to something like a fan or a heater, so going into detail about the servo might not be very useful.
The servo motor here is designed to resemble a fan or a heater in actual practice, but I replaced it with the motor for convenience. Note that in actual fact this motor would be a bad choice, as it can only turn 180 degrees (half a round) and maximally at 100 rotations per minute (which can hardly cool something down. That being said, the principles are similar. After we know what to do we then send the signal back to the FEZ Hat (using the same way, see above).
The pseudocode is simple (remember the motor doesn’t spin all the way, but half a round)
Turn left all the way;
Turn right all the way;
repeat;
Do note that the actual principle behind controlling a servo motor is quite fascinating, it can be read here:, but since it is very likely to be replaced by something else in practice it is not of interest.
Part 5: The Controller
What is of our interest, however, is when do we have to switch on the control mechanism. This section will explore methods of doing that. Note that for this we will focus on #0 and #1 (because there isn’t a lot to do with the servo) but everything else is possible to implement.
#0 Manual
Let’s assume the situation to be a heater that switches the room off after it’s getting too hot
Read temperature sensor
If it is >;25 degrees,
Switch LED on
This is more of a manual system where it just tells us that the temperature is high, and then does nothing to stop it. Not a bad choice to use in sensors where there is human supervision, such as fire alarms, but could have been more automatic. See the next section on Implementation of the Controller for how to do this.
#1 Automatic, One-way
Read temperature sensor
If it is >;25.5 degrees, and it was on
Switch off
Else, if it is <;24.5 degrees, and it was off
Switch on
Else, do nothing
This sounds like a good start! Note that we avoided the use of 25 degrees exactly as we didn’t want the the heater to fickle on and off repeatedly. This works in simple systems, but in actual engineering we might need more than that.
Other ways of controlling
#2 Two-way
Let’s assume now that we want to keep the temperature of a box that contains living cells constant at 5 degrees and we have both a heater and a cooler
Read temperature sensor
If it is >;5.1 degrees,
Heater off cooler on
Else, if it is <;4.9 degrees,
Heater on cooler off
Else, do nothing
This sounds okay, but what this lacks is the magnitude of how much we change things.
#3 Proportional
Read temperature sensor, let it be x
If x>;5, apply cooler level proportional to (x-5)
If x<;5, apply heater level proportional to (5-x)
This sounds quite good, in a sense that if suddenly the cell is moved to a 20 degrees room, it gets more cooling than if it is just a slight disturbance. The constant of proportionality can be found experimentally by trying what is good. (Although in some sensitive systems doing random trials may not be a choice, in that case proper calculation will be required.
However, all three previous cases has an unaddressed problem, we switch off the heating system at a certain temperature, but the heat already released will still make an effect towards the temperature drop - so in a sense we are inefficient! (An analogy to this would be the car doesn’t stop after we release the pedal, but goes a long way). A bigger problem with this is that it will never reach equilibrium! Because if we heat up to the temperature we want we then have some heat left that will heat it further, same for cooling.
#4 Predictive
Let’s say we are doing a cooling system
Read temperature sensor, let it be x
Look at the temperature graph, draw a best fit line try to extrapolate where it will reach 5 degrees
Gradually reduce the heat so that it reaches 5 degrees and stop there
*note that a more proper way of doing this is called integral control
This is the first use of our table we tabulated! We could not have done this if we only have the present values, but not any of the past. The math here seems a little more complicated.
A disadvantage of this is that it will obviously be slower to reach the desired temperature than the normal case. This could be made better by using something called a differential controller.
Implementation of the Controller
The instructions on how to control the LED and the servo is at [] under Send commands to your device. The files associated with that blog can be downloaded from []
Aside: Discrete and Continuous Control
The schematic steps of what we are doing here looks like this
Read temperature value (analog) every T milliseconds
Convert it to digital, send to computer
Let the computer decide what to do digitally
Convert it to analog, send to device
execute
Note that this is called the discrete way of doing it, because the data we have and the action we execute happen every T milliseconds. While this is close to real time, we have an alternative which is a continuous control system, which works like this
Temperature value has an analog output Vout
Pass through a circuit that has inputs of Vout and the reference voltage (what we want it to be), and an output of the voltage needed to make the change
Send that output to the device
Doing it in analog makes it a little more difficult to control things, because we have to use circuits instead of coding, but allows us to really do it in real time.
The circuit is called the Proportional-Differential-Integral (PID) Controller and is very extensively used in the production industry to keep the level of heat, acidity, humidity and more. It basically calculates the Error (current value minus desired value) and tries to mitigate this error through three different ways - which the combined effect can mitigate the error quickly and reliably.
Aside: Connecting a Motor
After much theory, we can actually connect the motor to the circuit! Connect the ground to the negative terminal of the battery, and PWM12 to the motor.
Summary and Synthesis
I hope to show that the principle behind each step is actually quite simple, before they come into a program. To summarise, the program does
Fetch temperature data;
Send it to the cloud;
Calculate what to do next; (or perhaps let the cloud do it!)
Send the instructions back; (if any)
Execute;
Repeat;
Looking at it more generally, we can solve two problems with such a system, first is disturbance rejection, where we want to keep a value constant and mitigate any changes that are happening. Second is less straightforward, but we can do some tracking with it, which means that we have a graph of how fast a temperature should change, and we want the temperature to rise according to that graph, not too fast or too slow.
A possible extension to this project is to consider the fact that we have logged all the data and we can analyse that into some useful relationship about temperature, for example what is the relationship between increasing the speed of the fan to the rate of change of temperature afterwards, or more simply how long does it take for temperature to rise to a certain level, and whether or not that is consistent over a longer period of time.
We can also analyse the effectiveness of different fan speeds using the data we have. By comparing the temperature profile, we can estimate the effectiveness of using different types of controllers.
References and Useful Links
Transmitting Data from FEZ Hat to Azure:
FEZ Hat Schematic Diagram
Servo Motors
Data Transfer from Pi to Azure
Necessary files | https://blogs.msdn.microsoft.com/uk_faculty_connection/2018/04/30/temperature-sensing-and-control-using-raspberry-pi/ | CC-MAIN-2018-30 | refinedweb | 3,730 | 55.58 |
I just realized I was so busy lately that I haven’t blogged for a while!
Here’s a quiz that left me clueless for some time (courtesy of our C# MVP Ahmed Ilyas):
using System;using System.Diagnostics; public class Examples{ public static void Main() { string stringToTest = "Hello"; Stopwatch equalsTimer = new Stopwatch(); equalsTimer.Start(); stringToTest.Equals("hello", StringComparison.OrdinalIgnoreCase); equalsTimer.Stop(); Console.WriteLine("Equals Timer: {0}", equalsTimer.Elapsed); Stopwatch compareTimer = new Stopwatch(); compareTimer.Start(); String.Compare(stringToTest, "hello", StringComparison.OrdinalIgnoreCase); compareTimer.Stop(); Console.WriteLine("Compare Timer: {0}", compareTimer.Elapsed); }}
On my machine, this prints out:
Equals Timer: 00:00:00.0009247
Compare Timer: 00:00:00.0000012
We looked at the source code of string.Equals and string.Compare and it was essentially the same (modulo very minor details which shouldn’t cause issues).
So what’s wrong? Why would the first call be 770 times slower than the second one? Jitting? No. Cache hit/miss? No.
After a while, we figured it out [UPDATE: So I thought!]. The first method is a virtual instance method, so a callvirt is emitted by the compiler:
callvirt instance bool [mscorlib]System.String::Equals(string, valuetype [mscorlib]System.StringComparison)
callvirt instance bool [mscorlib]System.String::Equals(string, valuetype [mscorlib]System.StringComparison)
While the second method is a static one, so the call instruction is used instead:
call int32 [mscorlib]System.String::Compare(string, string, valuetype [mscorlib]System.StringComparison)
call int32 [mscorlib]System.String::Compare(string, string, valuetype [mscorlib]System.StringComparison)
In this case, the method body was insignificant compared to the costs of doing virtual dispatch vs. a direct call. If you’d measure this in a loop of 1000000, the results will average out. So will they average out if you compare long strings, when the method body execution time dwarfs the call costs.
UPDATE: As always, Kirill jumps to conclusions too fast. Ahmed pointed out that if you swap the order of the calls, then the results are way different again! So it’s not the callvirt cost. Still puzzled, maybe it IS the JITter compiling the BCL code for the two method bodies.
Interesting... | http://blogs.msdn.com/b/kirillosenkov/archive/2010/09.aspx?PostSortBy=MostViewed&PageIndex=1 | CC-MAIN-2015-40 | refinedweb | 355 | 53.27 |
.
There are quite a few implementations of Python to choose from in Windows, but for purposes of this guide, I'll be using the .msi installer found on python.org.
python -V.
The list of downloads on python.org has .dmg installers for the Mac users out there. Here are the steps to install one of them:
python -V. The installation's version should appear.:
tar zxvf Python-2.<Your version>.tgz
./configureto generate a makefile..
/usr/bin/where most Python scripts look for the interpreter. If you have root access, then run
make installas root. This will install Python in the default location and it will be usable by everyone on your machine.
python -V.:
pythonon the command line.
from xml.etree import ElementTreeFor older versions, enter:
from elementtree import ElementTree
:
./setup.py installfrom the unpacked archive's main directory.
./setup.py install --home=<your home directory>.
In some cases, you want to avoid installing the modules altogether. To do that, modify your
PYTHONPATH environment variable to include
a directory which contains the
gdata and
atom directories for the Google data Python client library. For instructions on modifying your
PYTHONPATH,
see the Appendix at the end of this article..
Now that you've installed and tested the Google data Python client library, you're ready to start writing the next great application using:
As you continue to develop your application, you may hit a snag. If so, please check out the list of resources below:
If you happen to think of a great new feature for the library (or by chance find a bug), please enter it in the discussion group. We're always interested in your feedback!
Happy coding :-). | http://code.google.com/apis/gdata/articles/python_client_lib.html | crawl-002 | refinedweb | 281 | 67.15 |
> Guido van Rossum wrote: > > I'm in. Given how low you set your stakes, I don't think you're very > > confident, so I'd like to call your bluff. :-) > > Any opinion on where to spend effort? I was thinking of dusting off the > register VM code (aka rattlesnake). OTOH, perhaps the non-local > namespace optimizations would give more bang for the buck. > > Neil I was thinking it might be most effective to have a little conversation with Dan's potential sponsors. But maybe that's because my first name is Guido... ;-) Seriously, I expect Dan to lose without any effort on our part, but if we want to make an effort, I think that there could be some low-hanging fruit in inlining certain builtins (e.g. len, range, xrange) that as far as we know aren't shadowed by globals. Is that what you call non-local namespace optimizations? A new VM design would be a major upheaval, but if we can pull it off it would certainly not be a bad idea. John Aycock and some of his students have a design of a new VM that might be worth looking into. --Guido van Rossum (home page:) | http://mail.python.org/pipermail/python-dev/2003-February/032843.html | crawl-002 | refinedweb | 200 | 82.14 |
Vizualizare: Vizualizați totală
MainFullscreen
Click pe
To change the view to 'fit all' use the
Alternatively the
MainFullscreen
Std Base
User documentation
Outdated translations are marked like this.
Next: ViewFitSelection
Descriere
Efectuarea unui zoom/se micșorează până când toate obiectele vizibile sunt afișate în vizualizarea 3D.
The Std ViewFitAll command zooms and pans the camera so that all visible objects fit inside the active 3D view.
Utilizare
Click pe
sau alegeți View → Standard views →
Fit all din meniul de sus/top.
Comanda este de asemenea disponibilă în vizualizarea 3D (și nu are nimic pre-selectat).
- There are several ways to invoke the command:
- Press the
Std ViewFitAll button.
- Select the View → Standard views →
Fit all option from the menu.
- Select the
Fit all option from the 3D view context menu.
- Use the keyboard shortcut: V then F.
Notes
- It is also possible to zoom to 'fit all' via the Mini-cube menu of the Navigation Cube.
Scripting
See also: FreeCAD Scripting Basics.
To change the view to 'fit all' use the
fitAll method of the ActiveView object. This method is not available if FreeCAD is in console mode.
import FreeCADGui FreeCADGui.ActiveDocument.ActiveView.fitAll()
Alternatively the
SendMsgToActiveView method of the FreeCADGui object can be used. This method is not available if FreeCAD is in console mode.
import FreeCADGui FreeCADGui.SendMsgToActiveView('ViewFit')
Next: ViewFitSelection
> | https://wiki.freecadweb.org/Std_ViewFitAll/ro | CC-MAIN-2022-05 | refinedweb | 223 | 67.86 |
I have two classes that represent 3D objects :
1) Mesh, which contains a single simple Mesh
2) Model, which is basically a vector of meshes
Here are my headers :
Code:#include "mesh.hpp" #include <vector> using namespace std; class Model { public: void addObject(Mesh *newObject); void draw(); void description(char * s); private: vector<Mesh*> objects; };I implement the addObject method like thisI implement the addObject method like thisCode:class Mesh { public: /*------- public methods, getters and setters -----*/ private: unsigned int numVertex; unsigned int numFaces; GLfloat (* vertex)[3]; unsigned int (* face)[3]; unsigned int numTVertex; GLfloat (* tVertex)[2]; unsigned int numTVFaces; unsigned int (* tFace)[3]; GLfloat (* faceNormal)[3]; GLfloat (* vertexNormal)[3]; };
I initialize a Model like this :I initialize a Model like this :Code:void Model::addObject(Mesh *newObject) { objects.push_back(newObject); }
The Mesh initializing code works very well, I can see that for each i, newMesh is what I want it to be. But I have two problems.The Mesh initializing code works very well, I can see that for each i, newMesh is what I want it to be. But I have two problems.Code:Mesh *newMesh; for(i=0;i<objectCount;i++) { /*---- newMesh initializing code here -----*/ model->addObject ( newMesh ); }
1) The addObject only works for the first. After that I get insane values for the next objects I add.
2) the newMesh pointer is valid only in the scope of the initializing function. Once the program that function, all my vector points to NULL.
If anyone has an idea for any of the two problems, please help. Thanks everyone. | http://cboard.cprogramming.com/cplusplus-programming/58921-vector-pointers-scope.html | CC-MAIN-2014-10 | refinedweb | 260 | 58.32 |
Non-Programmer's Tutorial for Python 3/Intro to Object Oriented Programming in Python 3< Non-Programmer's Tutorial for Python 3
Object Oriented ProgrammingEdit
Up until now, the programming you have been doing has been procedural. However, a lot of programs today are Object Oriented. Knowing both types, and knowing the difference, is very important. Many important languages in computer science such as C++ and Java, often use OOP methods.
Beginners, and non-programmers often find the concept of OOP confusing, and complicated. This is normal. Don't be put off if you struggle or do not understand. There are plenty of other resources you can use to help overcome any issues you may have, if this chapter does not help you.
This chapter will be broken up into different lessons. Each lesson will explain OOP in a different way, just to make sure OOP is covered as thoroughly as possible, because IT IS VERY IMPORTANT. Before the lessons, there is an introduction which explains key concepts, terms, and other important areas of OOP, required to understand each lesson.
IntroductionEdit
Think of a procedure as a function. A function has a specific purpose. That purpose may be gathering input, performing mathematical calculations, displaying data, or manipulating data to, from, or in, a file. Typically, procedures use data which is separate from code for manipulation. This data is often passed between procedures. When a program becomes much larger and complex, this can cause problems. For example, you have designed a program which stores information about a product in variables. When a customer requests information on a product, these variables are passed to different functions for different purposes. Later on, as more data is stored on these products, you decide to store the information in a list or dictionary. In order for your program to function, you must now edit each function that accepted variables, to now accept and manipulate a list or dictionary. Imagine the time that would take for a program that was hundreds of megabytes, and hundreds of files in size! It would drive you insane! not to mention, errors in your code, are almost guaranteed, just because of the large volume of work and possibilities to make a typo or other error. This is less than optimal. Procedural programming is centered on procedures or functions. But, OOP is centered on creating Objects. Remember how a procedural program has separated data and code? Remember how that huge program was hundreds of files and would take FOREVER to edit? Well, think of an object as a sort of "combination" of those files and data into one "being". In a technical sense, an Object is an entity which contains data, AND procedures (code, functions, etc.).
Data inside an object is called a data attribute.
Functions, or procedures inside the object are called methods.
Think of data attributes as variables.
Think of methods as functions or procedures.
Let's look at a simple, everyday example. The light and light switch in your bedroom. The data attributes would be as follows.
- light_on (True or False)
- switch_position (Up or Down)
- electricity_flow (True or False)
The methods would be as follows.
- move_switch
- change_electricity_flow
The data attributes may or may not be visible. For example, you cannot directly see the electricity flowing to the light. You only know there is electricity, because the light is on. However, you can see the position of the switch (switch_position), and you can see if the light is on or off (light_on). Some methods are private. This means that you cannot directly change them. For example, unless you cut the wires in your light fixture (please don't do that, and for the sake of this example, assume that you don't know the wires exist), you cannot change the flow of electricity directly. You also cannot directly change if the light is on or off (and no, you can't unscrew the bulb! work with me here!). However, you can indirectly change these attributes by using the methods in the object. If you don't pay your bill, the
change_electricity_flow method will change the value of the
electricity_flow attribute to FALSE. If you flip the switch, the
move_switch method changes the value of the
light_on attribute.
By now you're probably thinking, "What does this have to do with Python?" or, "I understand, but how do I code an Object?" Well, we are almost to that point! One more concept must be explained before we can dive into code.
In Python, an object's data attributes and methods are specified by a class. Think of a class as a blueprint to an object. For example, your home - the object that you live in - you can also call it your pad, bungalow, crib, or whatever, was built based on a set of blueprints; these blueprints would be considered the class used to design your home, pad, crib, ahem, you get the idea.
Again, a class tells us how to make an object. In technical terms, and this is important here, a class defines the data attributes and methods inside an object.
To create a class, we code a class definition. A class definition is a group of statements which define an object's data attributes and methods.
Lesson One
Below is a Procedural program that performs simple math on a single number, entered by a user.
# Program by Mitchell Aikens # No Copyright # 2012 # Procedure 1 def main(): try: # Get a number to maniuplate num = float(input("Please enter a number to manipulate.\n")) # Store the result of the value, after it has been manipulated # by Procedure 2 addednum = addfive(num) # Store the result of the value, after it has been manipulated # by Procedure 3 multipliednum = multiply(addednum) # Send the value to Procedure 4 display(multipliednum) # Deal with exceptions from non-numeric user entry except ValueError: print("You must enter a valid number.\n") # Reset the value of num, to clear non-numeric data. num = 0 # Call main, again. main() # Procedure 2 def addfive(num): return num + 5 # Procedure 3 def multiply(addednum): return addednum * 2.452 # Procedure 4 def display(multi): # Display the final value print("The final value is ",multi) # Call Procedure 1 main()
If we were to enter a value of "5", the output would be as shown below.
Please enter a number to manipulate. 5 The final value is 24.52
If we were to enter a value of "g", and then correct the input and enter a value of "8", the output would be as shown below.
Please enter a number to manipulate. g You must enter a valid number. Please enter a number to manipulate. 8 The final value is 31.875999999999998
Below, is a Class, and a program which uses that class. This Object Oriented Program does the same thing as the procedural program above. Let's cover some important OOP coding concepts before we dive into the Class and program. To create a class, we use the
class keyword. After the keyword, you type the name you want to name your class. It is common practice that the name of your class uses CapWords convention. If I wanted to create a class named dirtysocks, the code would be:
class DirtySocks
The Class is shown first. The program which uses the class is second.
# Filename: oopexample.py # Mitchell Aikens # No Copyright # 2012 # OOP Demonstration - Class class Numchange: def __init__(self): self.__number = 0 def addfive(self,num): self.__number = num return self.__number + 5 def multiply(self,added): self.__added = added return self.__added * 2.452
The program which uses the class above, is below.
# Filename: oopexampleprog.py # Mitchell Aikens # No Copyright # 2012 # OOP Demonstration - Program import oopexample maths = oopexample.Numchange() def main(): num = float(input("Please enter a number.\n")) added = maths.addfive(num) multip = maths.multiply(added) print("The manipulated value is ",multip) main()
After looking at that program, you are probably a bit lost. That's OK. Lets start off by dissecting the class. The class is named "Numchange" There are three methods to this class:
- __init__
- addfive
- multiply
These three methods each have a similar code.
def __init__(self): def addfive(self,num): def multiply(self,added):
Notice how each method has a parameter named "self". this parameter must be present in each method of the class. This parameter doesn't HAVE TO be called "self", but it is standard practice, which means you should probably stick with it. This parameter is required in each method because when a method executes, it has to know which object's attributes to operate on. Even though there is only one Object, we still need to make sure the interpreter knows that we want to use the data attributes in that class. So we play it safe...and use the "self" parameter.
Lets look at the first method.
def __init__(self):
Most Classes in python have an
__init__ which executes automatically when an instance of a class is created in memory.(When we reference a class, an instance (or object)of that class is created). This method is commonly referred to as the initializer method. When the method executes, the "self" parameter is automatically assigned to the object. This method is called the initializer method because is "initializes" the data attributes. Under the __init__ method, we set the value of the
number attribute to 0 initially. We reference the object attribute using dot notation.
def __init__(self): self.__number = 0
The
self.__number = 0 line simply means ""the value of the attribute "number", in the object, is 0"".
Let's look at the next method.
def addfive(self,num): self.__number = num return self.__number + 5
This method is named "addfive". It accepts a parameter called "num", from the program using the class. The method then assigns the value of that parameter to the "number" attribute inside the object. The method then returns the value of "number", with 5 added to it, to the statement which called the method.
Let's look at the third method.
def multiply(self,added): self.__added = added return self.__added * 2.453
This method is named "multiply". It accepts a parameter named "added". It assigns the value of the parameter to the "added" attribute, and returns the value of the "added" attribute multiplied by 2.452, to the statement which called the method.
Notice how the name of each method begins with two underscores? Let's explain that. Earlier we mentioned that an object operates on data attributes inside itself using methods. Ideally, these data attributes should be able to be manipulated ONLY BY METHODS IN THE OBJECT. It is possible to have outside code manipulate data attributes. To "hide" attributes, so only methods in the object can manipulate them, you use two underscores before the object name, as we have been demonstrating. Omitting those two underscores in the attribute name, allows for the possibility of manipulation from code outside the object.
Lets look at the program which uses the class we just dissected.
Notice the first line of non comment code.
import oopexample
This line of code imports the class, which we have saved in a separate file (module). Classes do not have to be in a separate file, but it is almost always the case, and thus is good practice to get used to importing the module now.
The next line:
maths = oopexample.Numchange()
This line creates an instance of the Numchange class, stored in the module named "oopexample", and stores the instance in the variable named "maths". The syntax is:
modulename.Classname() Next we define the main function. Then, we get a number from the user.
The next line
added = maths.addfive(num) sends the value of the "num" variable to the method named "addfive", which is part of the class we stored an instance of in the variable named "maths", and stores the returned value in the variable named "added".
The next line
multip = maths.multiply(added) sends the value of the variable "added", to the method named "multiply", which is part of the class we stored an instance of in the variable named "maths", and stores the returned value in the variable named "multip".
The next line prints "The manipulated value is <value of multip>". The last line calls the main function which executes the steps outlined above. | https://en.m.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Intro_to_Object_Oriented_Programming_in_Python_3 | CC-MAIN-2016-07 | refinedweb | 2,057 | 66.74 |
Tracking down bugs is what programming is all about :) you will gradually learn techniques as you get more experienced. Some starting points:
Put asserts in you code. Asserts are really useful because they can show up bugs before the bugs become a big problem. Basically an assert is you saying 'I assert that something is true at this point in my program'. So for example if you have a function that works on a passed pointer and you are sure the pointer must not be null but must be valid you assert this fact at the top of your function. If the pointer ever is null you will trap it before it goes on to cause havoc!
E.g.
#include <cassert>
void SetName(char *name){ assert(name!=NULL); strcpy(m_name,name);}
Other times you may want to use asserts is to check array bounds (another common cause of bugs) so if you had a function to return an object by its array index you would want to assert that the index is in the correct range,
CObject *GetObjectByIndex(int index){ assert(index>=0 && index < m_numEntries); return m_objects[index];}
Another common way of tracking bugs is to output values to the output pane in Viz. You can use OutputDebugString to do this (see the next question).
If an assert fails or your program crashes with some other error you can use the Visual Studio debugger to help find problems. This only works if you have run the program in the debugger (press F5) and not used the execute button (the exclamation mark - runs outside of the debugger).
When the error occurs you will have the option to press retry. Pressing this drops you into the debugger. Depending on your set-up you will have a number of different debug windows. To change which can be seen go to the View menu and select from the debug windows list.
The Call Stack window shows you the last few calls that were made prior to the crash. You can click on previous ones to go back through the code. At each point you can hover the mouse over variables to see what values they contain or use the watch window to type variables into. This way you can check to see what values variables have and deduce where the problem is. It takes a bit of detective work.
If you still find you have problems and your code activity is high you may think of logging what is happening either to a file or to the debug pane in Viz (or both). To output to the debug pane you write:
OutputDebugString("This is some output to the debug pane\n");
#pragma provides a way of setting options for the compiler. This is often compiler specific. In this case we are using 'once' which means we are telling the compiler that opening this file once has the same effect as opening it multiple times. Note that this is a hint to the compiler and not a guard condition. This helps speed up compilation when you include the same header file in many source files. Other #pragma uses are to turn off a warning message from the compiler (normally you do not want to do this as every warning is a potential problem). To turn off a warning message you write #pragma warning(disable: #) where # is the warning number.
Note: you often see headers use both #pragma once and the #ifndef #define (or !defined) guard method of forcing a header to be compiled only once. This is the correct way of using the pragma because it is a hint to the compiler and not a guard condition itself. Having said that you can just use #pragma once without a guard condition and often get the same effect but be aware of what you are doing.
#define is used to define values and macros that are replaced in code at compile time. It is important you remember this is done at compile time and not at run time. There are a number of commands you can use:
#define - defines a symbol to be a value or result of a calculation#ifdef - if a symbol is defined carry out the following, you can also use: #if defined#ifndef - if a symbol is not defined.#endif - end of the if section#else - just like a normal else#elif - combines else and if
An example use of #define might be:
#define GRAVITY 0.98f
Anywhere in your code you can now use GRAVITY instead of writing 0.98f, this allows you to adjust the value in just one place at a later date. However this is no longer thought to be the best thing to do, the problem with defines is they have no type. For the above example you would be better defining a constant global instead, which allows you to specify type:
const float kGravity=0.98f;
So when can you use #define? Well it is useful for turning code on and off e.g. you may want to measure frame rate and put lots of timer checks in your code - but you don't want this on all the time. So instead of having to comment all the code out you use a define. e.g.
At the top of your file you may have:
#define ENABLE_FRAME_RATE
#ifdef ENABLE_FRAME_RATE float gLastTime=timeGetTime(); int gFrameCount=0#endif
Then later in your code where you want to measure the frame rate (after your render loop) you might have:
#ifdef ENABLE_FRAME_RATE float timeNow=timeGetTime(); float timeOfFrame=timeNow - gLastTime; .. etc.#endif
Now to disable the frame rate calculations we just comment out the #define
Another example of #define is to define a macro. A classic example is one to find the minimum of two values e.g.
#define MIN(a,b) (( (a) < (b) ) ? (a) : (b))
The ? means if the condition is true return the first variable else return the second (after the colon). So the above reads - if a is less than b return a else return b. All the brackets are essential as you may be using this define in a complex expression. In fact this is one of the problems with defines, its very easy to forget the brackets and get the wrong results (often in just a few unusual cases). This define does take advantage of the fact that any type can be passed in so can be used on any type that defines the < operator. Some example uses might be:
float smallestHeight=min(heightA,heightB);smallestHeight=min(smallestHeight,heightC);
As an example of the bracket problem imagine for some weird reason you want to define a macro to add 10 to a value, you might wrongly define it as
#define ADD_TEN(a) a+10
Then you may use it in the following cases:
int a=6;int b=ADD_TEN(a)
In this case you would get the right answer, if you expand the define (as the compiler does at compile time) the expression would read:
int b=a+10;
Now as an example of where it goes wrong, say you used it in a calculation:
int a=2;int b=8;int c=ADD_TEN(a)*b
You might expect c to now equal 12 * 8 = 96, but in fact it equals 82. The reason is clear once you replace the macro to see what is happening, the expression becomes:
int c=a+10*8'
Since multiplication has a higher precedent than addition the 10 is multiplied by the 8 and then added to a giving you 82. So the solution is simply to put brackets in.
#define ADD_TEN(a) (a+10)
Then the expression is:
int c=(a+10)*8;
This is a very simple and contrived example of the problem, just be careful using defines that you don't fall into this kind of trap.
When strict is defined certain type casts and parameter passing in libraries are enforced more strictly. It is a good idea to have this defined to help track down bugs. Since it is a define it may be defined in a number of places so it is usual to do this:
#ifndef STRICT #define STRICT#endif
CTRL-F2 - places a bookmark on the current line (CTRL-K, CTRL-K in .net)F2 - jumps to the next bookmark (CTRL-K, CTRL-N) in .net)F5 - compile and runF9 - places a breakpoint at the current lineF10 - steps through code, does not step into function callsF11 - steps through code and does step into function callsF1 - help for the word following the current cursor position.
The const keyword specifies that a variable or object is not modifiable. This is very useful to enforce rules about objects and often helps trap problems at compile time (it can also aid the compiler in optimizing code). You should use const from the start of your application as switching later is more difficult. An example of the use and benefits of const follows:
Say we have a large structure that we need to pass to a function for it to carry out some calculations. Perhaps it contains some values relating to a monsters stats, e.g. health, hit points etc. and the function needs to work out if the monster is healthy.
{
TMonster monster; if (IsMonsterHealthy(monster)) {...}}
bool IsMonsterHealthy(TMonster monster){ if (monster.health<10 && monster.hitPoints==0) return false; return true;}
Note: this is an example only, if I were to implement the above in reality I would make monster a class and make IsHealthy a member function.
We are passing the monster structure to the function for it to carry out some calculations involving its member variables. The problem with the above is that we are passing the whole structure so a copy of the structure will be used in the function. This is not good as it creates slow code (a lot of data is copied). Also, if we pass an object, a copy is made and a new object created for the lifetime of the function only (if it were a class instance a constructor would be called and destructor on exit). So instead we might just pass a pointer to the function which is very quick as it is normally just 4 bytes:
if (IsMonsterHealthy(&monster))...
bool IsMonsterHealthy(TMonster *monster){ assert(monster); ... etc.}
That looks much better, however in this case because we are passing a pointer to our structure and not a copy the function could alter the member variables of monster. We may say that we will ensure it does not but there is always a risk especially when working in large teams of programmers, a programmer may be tempted to modify the data or just accidentally modify it due to a bug. E.g. if they forgot to put two = signs in the hitPoints comparison it would assign 0 to hitPoints instead of check if it is zero. Much better is for us to enforce the fact that the function will not modify the structure variables.
So we could instead pass in a const reference or pointer to the structure which enforces that the values in it cannot be changed. The use of a reference or pointer means a copy is not made and the const means any attempt to assign values to the structures member variables produces an error at compile time. So we could change the function to:
bool IsMonsterHealthy(const TMonster &monster){ // any attempt to modify the variables will produce an error e.g. monster.hitPoints=0 will not compile ....}
Note: it is perfectly valid to use a const pointer rather than a const reference however I prefer the reference because it cannot be NULL where as a pointer can be. Generally if you want to pass a parameter that is an object that must exist and you do not want it modified use const T& however if the object may not exist use a pointer (const T*). The choice depends on the circumstance.
You should get into the habit of using const in function definitions, after a while it becomes second nature. It also forces you to think about what you are doing and what the scope of a variable is. A lot of bug solving is achieved by enforcing the rules you know should exist. It is similar to using asserts, with asserts you are saying 'This must be true' with constness you are saying 'this function will not modify this parameter'.
I have created a small word document that details most of the uses of const, you can access it here: Const Correctness.doc
For more information on the use of const look at the online C++ FAQ question on Const Correctness.
You cannot. You could raise an exception but you cannot return a value. I normally just initialise member variables to defaults in constructors and nothing else. Any memory allocation or other initialisation I tend to place in an Initialise() member function. This function can also then return a success Boolean. However this does cause its own issues like how do you stop someone calling Initialise more than once? How do you make sure they call initialise at all? However if we look back at the idea of using exceptions we have another problem to do with memory allocation. If we allocate memory for a number of objects in a constructor and an exception is raised you may be left with undeleted memory because the object is only half created. There are solutions to this like using smart pointers and doing as much in initialisation lists as you can but it can then become complex. Probably the big question is do you want to use exceptions in your game code? Exceptions are a very good method of solving error situations but unfortunately there is a cost to using them. They make code larger and slower which is not what we want for our game so a lot of game programmers turn off exception handling completely (via settings in Viz). However if they improve the robustness of your code they may save a lot of development time and hence be worthwhile.
There is a useful flag you can set to cause memory leaks to be displayed in the output pane of the visual C++ IDE. At the beginning of your program you need this:
#if defined(DEBUG) | defined(_DEBUG) #define CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h>#endif
At the entry point of your application e.g. in WinMain you will need to add this:
#if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );#endif
In order to put break points on memory allocation numbers see this Microsoft link: How to: Set Breakpoints on a Memory Allocation Number
When writing in C++ you should prefer new and delete. What you must definitely not do is mix the two. So if you use new you must use delete and not free, likewise if you use malloc you must not use delete. Another gotcha is to forget to use the array form of delete. E.g. say you wanted to reserve memory for 10 integers:
int *intArray=new int[10];....delete []intArray;
You must use [] when deleting memory created using the array form of new.
Another side issue is that it is normal to check a pointer is not null before freeing the memory. The C++ spec. does however allow delete to be used on a NULL pointer - its not illegal. However you will often see code like this that checks if it is null, if it is not it deletes the memory and sets the pointer to NULL:
if (intArray){ delete []intArray; intArray=NULL;}
Note: you will also often see macros in DirectX sample code that do the above for you e.g. SAFE_DELETE
The one thing that C style memory allocation provides that is not so easily provided by the C++ form is to be able to alter the size of allocated memory using realloc. However if you find this is what you want to do an alternative storage form may be a better choice, e.g. use one of the standard library interfaces like list or vector.
Well there is certainly a body of thought that says arrays are evil and you should never use them. The reason is that going beyond the bounds of an array is a very common cause of bugs. I now avoid arrays wherever possible and instead use the standard library vectors or lists. Vectors have the advantage of being able to grow and still allow array-like access (random) to data. They are much more robust however and can control access to the data much better than an array. The argument against vectors is that they are slow, this is an argument often stated by games programmers, however I wonder if these programmers have ever really tested the relative speeds? I have done some tests myself and found vectors to be very fast (its actually a requirement of the C++ specification that they perform to a set speed order). Vectors are slow if you are removing elements a lot. I have found the std lists to be not quite as fast as my own home-grown ones. At the end of the day, with game code now so large, you should aim to use the safest method that leads to less potential bugs. Optimisation techniques can be applied later when the code is feature complete.
As a final point if you want to access data sequentially using a vector use an iterator for best speed, when accessing data randomly use the array form. If using an iterator to change values use container_type::iterator but if just reading values use container_type::const_iterator. You may also want to use reserve(...) to reserve memory in a vector before use. Also see the next item.
Note: you are not limited to just the standard library there are also other libraries available. The most popular one is the boost library that is free and is very well supported and used extensively.
If you are not going to be inserting or deleting elements very much use a vector otherwise use a list. Vectors are optimised for fast random access while lists are optimised for fast insertion and deletion.
It can become quite painful having to write std:: before everything. The reason it is there is to tell the compiler to look in the standard namespace for the functions. There is a way around it though via the using keyword. So instead of writing:
std::vector <int> intVector;
at the top of our source file we write :
using std::vector
This says that we intend to use the name vector to mean std::vector exclusively, and we do not intend to define anything named vector ourselves. We are importing an individual symbol from the standard library into our code scope. So we can now write:
vector <int> intVector;
We could also allow our code to use the whole of the standard namespace using:
using namespace std;
This means we are importing every symbol from the std namespace into our code scope. I think you should not use this method but instead import each symbol as it is needed, this makes it clearer what you are intending to another reading your code and keeps the benefits of namespaces.
The left hand side of an assignment must be a non-temporary object. You have probably tried to use a temporary object in an assignment.
Both increase the value of x by one. The first is a post increment operator and the second a pre-increment one. It is important to realise the differences as, when applied to objects, using the post increment operator can cause a temporary object to be created.
x++ This increments x, returns the original value of x so requires a temporary object.
++x This increments x, returns the incremented value of x so no temporary object needed (potentially faster)
In general you should use ++x
It was so easy in the days of C character strings to write into a buffer e.g.
char buf[2048];sprintf(buf, "The value of integer a is %d and float f is %f \n",a,f);
There are problems with this though. It is prone to buffer overruns as sprintf does not take the size of the buffer and so relies on the buffer being big enough. Another problem is with character sets where you need to use alternative forms for UNICODE etc. Also the format specifies can be confusing. So with C++ it is logical to use the STL string for all text operations. The standard string has many functions but does not have a way of doing the above. Instead you need to use a string stream e.g.
std::ostringstream buf ;buf << "The value of integer a is " << a << "and float f is "<< f << endl ;std::string str = buf.str() ;
Please see the fuller notes on using C++ strings here: String Handling
A reference must be assigned to something at creation (unlike a pointer a reference cannot be NULL) so it may seem impossible to use one as a member variable. You can do it though if you initialize it in the constructor using an initialization list e.g.
class MyClass{private: TSomething &m_var; public: MyClass(TSomething &var_, ...); };MyClass::MyClass(TSomething &var, ...): m_var(var) // constructs m_var from var { // }
I use two macros to do this. The process of creating them is a bit long-winded so I have created a page describing the process, it can be found here: Macros In Viz (Viz 6.0 only). For .net macros take a look on the CodeProject site they have plenty available. I would recommend you take a look at Kings Tools for example.
Normally you can just type the name of a variable into the watch window where you can then examine its value, however with vectors this does not work. What you have to do is use the _first member variable of a vector, so to watch the ith element of a vector called entityVector you would enter the following to watch:
entityVector._Myfirst+i
You could also see all the elements (if you know how many there are) by using ,x in the watch window. This indicates there are x elements so to examine the first 10 elements in the vector you could do this:
entityVector._Myfirst,10
Note: under Viz 6 you have to use entityVector._first instead of _Myfirst
There is a converter available here: prjconverter
The academic version has the same functionality as the full professional version. The only difference is that you are not allowed to sell any software you write with it. Now there is a way around this, all you have to do is download the Visual Studio 2003 professional compiler from microsoft.com (for free) and compile your code with it. This frees you from the restraints of the academic version.
You can load Visual C++ 6.0 project (dsp) and workspace (dsw) files into .net just be loading them. To go the other way (from dsw and dsp to .net solution (sln) you can use this useful tool:
By correctly using precompiled headers. I stress correctly because I had been using them incorrectly for a long time until I discovered how to use them properly. The MSDN help on using precompiled headers is not very clear. Once you get them working properly compilation speed is improved enormously. I was surprised at how much of a speed gain they give. The way to get them to work is to set your project to use them through a header and select one source file as the creator of the precompiled data and all other files to use it. Below I describe the steps required to use precompiled headers in Visual Studio .net
If you get any compile errors after this make sure all the source files in your project have the same settings e.g. if one is set to use run time type checking and the others are not you may get errors.
New: Microsoft have released a patch for Intellisense that improves matters a bit. See the blog entry and follow the link here: Performance Improvements in Visual C++
Intellisense is the name given to the feature in Visual Studio that provides drop down lists of functions etc. It is a bit flakey to say the least! The first thing to do if it is not working for you is to make sure there is not an error in your code prior to the point you are trying to use Intellisense. Next you should do a build and then a rebuild all if that does not work. Even after doing this it still often does not work correctly. You can purchase other systems like the highly recommended Visual Assist. | http://www.toymaker.info/Games/html/c__.html | CC-MAIN-2015-27 | refinedweb | 4,145 | 68.6 |
The regular expression is a popular topic in system administrators and developers. A at these regex functions in detail.
Import Re or Regular Expression Library
In order to work with regular expressions in python, we need to import regular expression library which is named as a shortcut of
regular expression as
regex .
import regex
Match
The match function is one of the most popular functions which will apply regex pattern into the given string. We will use
match function with
pattern and
string parameters. There is also
flags parameter which can be used to provide some flags like the case, interpretation, etc. If we do not provide
flags there will be no error.
re.match(PATTERN,STRING,FLAG)
In this example, we want to find words that are delimited by spaces in the given string. Each word provides single match and those matches will be grouped.
line="This is an example about regular expression" matches = re.match('\w+',line) matches.group(0)
Groups
In the previous part, we have simply printed the first group which index is
but we may have more than one word to match in a line. It is called a group in the regex. We can match multiple different patterns in a single match.
In this example we will match words starts with
T and
a into two groups.
line="This is an example about regular expression" matches = re.match('(T\w+).*example\s(a\w+)',line) matches.group(0) #'This is an example about' matches.group(1) #'This' matches.group(2) #'about'
As we see matched pattern results are assigned into groups. We can get them by providing an index about these groups.
Search
Search is similar to the match function but the main difference is match looks up to the first match and then stops but the search will look at to the end of the string and will find multiple matches if exists. The syntax of the
search function is the same
match functions.
re.search(PATTERN,STRING,FLAG)
line="This is an example about regular expression" matches = re.search('(T\w+).*example\s(a\w+)',line) matches.group(0) #'This is an example about' matches.group(1) #'This' matches.group(2) #'about'
Search and Replace
Python regex functions support finding given text and replacing the text with a new one. We will use
sub functions in order to replace.
sub function supports the following syntax.
re.sub(PATTERN,NEWTEXT,STRING,FLAG)
We will change
regular word with
unregular word in this example.
line="This is an example about regular expression" matches = re.sub('regular','unregular',line) print(matches)
.
matches = re.sub('regular','unregular',line,re.I) | https://www.poftut.com/python-regular-expression-operations-regex/ | CC-MAIN-2021-04 | refinedweb | 444 | 58.08 |
Running Jekyll Serve in Development Mode
With Jekyll I've gotten used to always change my _config.yml setting for url and imgurl like this when getting ready to commit my changes for the production version:
url: '' urlimg: '' #url: '' #urlimg: ''
And then like this for development:
#url: '' #urlimg: '' url: '' urlimg: ''
This not only is an annoying extra step, but it can lead to problems if you deploy to production and forget to swith the comments back in the _config.yml file. It turns out however that there's a much easier way: having a _config_dev.yml file. In that file you would have something like this:
url: '' urlimg: ''
And then, when you want to work on your website in development mode, it's as simple as running this:
jekyll serve --config _config.yml,_config_dev.yml
With that command, the _config_dev.yml overwrites the settings from your regular _config.yml
Obviously, the problem now is that this jekyll serve --config _config.yml,_config_dev.yml is quite a mouthful to type in each time. A simple solution is to have a simple rake task for it. Create a file in your project's directory called rakefile and add the following to it:
def execute(command) system "#{command}" end desc 'Jekyll Serve' task :serve do execute("jekyll serve --config _config.yml,_config_dev.yml") end
Now all you have to do to run a jekyll development server is this:
rake serve
And there you have it! A good handful of seconds saved each time you want to start working on your Jekyll website locally. | https://alligator.io/jekyll/development-mode/ | CC-MAIN-2017-30 | refinedweb | 260 | 59.64 |
The Checkbox class provides a text label and an associated on/ off state indicator. It is used to implement check buttons and, in conjunction with the CheckboxGroup class, radio buttons. The major resources of this class are presented in Table 2.11.
Table 2.11 Major resources of the Checkbox class.
A Checkbox instance has three data attributes, the label which it will display, the CheckboxGroup to which it might belong and the state (on or off) of its indicator. If a Checkbox instance is not a member of a CheckboxGroup it will behave as a check button and its state can be set or unset independently of all other Checkbox buttons. If a Checkbox instance is a member of a CheckboxGroup it will behave as a radio button, where only one member of the group can be checked at any one instant and checking one of the buttons in the group will automatically unset all other buttons.
The first two constructors are comparable to the first two constructors of the Label class given above. The third constructor specifies its initial state, the last the initial state and the CheckboxGroup to which it belongs. The first six methods allow each of the three data attributes to be queried or set. The last two register and remove the Checkboxes' listener object.
Whenever the state of the Checkbox is changed it will generate a ItemEvent instance which is dispatched to its registered listeners. The ItemEvent class is used by a number of different AWT Components and its major resources are listed in Table 2.12. For an ItemEvent generated by a Checkbox instance, the getItemSelectable() method returns the identity of the instance which generated it and the getItem() method will return its label.
Table 2.12 Major resources of the ItemEvent class.
The following header and init() method, from a class called CheckExample which extends Applet, creates four Checkbox components configured as check buttons, which might be a part of an interface which selects the formatting options for a font. The CheckExample class also implements the ItemListener interface, allowing it to be registered with each of the Checkboxes (this) as the destination of the ItemEvents generated when they are checked or unchecked.
0001 // Filename CheckExample.java. 0002 // Provides an example of the AWT Checkbox class, 0003 // configured as a check box buttons. 0004 // Written for the Java interface book Chapter 2 - see text. 0005 // 0006 // Fintan Culwin, v 0.2, August 1997. 0007 0008 import java.awt.*; 0009 import java.applet.*; 0010 import java.awt.event.*; 0011 0012 0013 public class CheckExample extends Applet 0014 implements ItemListener { 0015 0016 private Checkbox boldButton; 0017 private Checkbox italicButton; 0018 private Checkbox underlineButton; 0019 private Checkbox smallcapsButton; 0020 0021 public void init() { 0022 this.setLayout( new GridLayout( 2, 2, 5, 5)); 0023 0024 boldButton = new Checkbox( "Bold"); 0025 boldButton.addItemListener( this); 0026 this.add( boldButton); 0027 0028 italicButton = new Checkbox( "Italic"); 0029 italicButton.addItemListener( this); 0030 this.add( italicButton); 0031 0032 underlineButton = new Checkbox( "Underline"); 0033 underlineButton.addItemListener( this); 0034 this.add( underlineButton); 0035 0036 smallcapsButton = new Checkbox( "Small Capitals"); 0037 smallcapsButton.addItemListener( this); 0038 this.add( smallcapsButton); 0039 } // End init.
The appearance of the interface produced by this code is shown in Figure 2.5 and shows that both the Italic and Underline Checkboxes have been selected by the user. A two by two GridLayout layout manager is installed into the Applet Panel in order to obtain the required visual appearance. From a consideration of the code and the image it can be seen that components are added in a left right/ top down manner.
Figure 2.5 Checkbox example configured as check buttons.
In order to implement the ActionListener interface the CheckExample class must declare an itemStateChanged() method, as follows.
0042 public void itemStateChanged( ItemEvent event) { 0043 System.out.print( "Item Selectable is "); 0044 if ( event.getItemSelectable() == boldButton) { 0045 System.out.println( "bold Button"); 0046 } else if ( event.getItemSelectable() == italicButton) { 0047 System.out.println( "italic Button"); 0048 } else if ( event.getItemSelectable() == underlineButton) { 0049 System.out.println( "underline Button"); 0050 } else if ( event.getItemSelectable() == smallcapsButton) { 0051 System.out.println( "small caps Button"); 0052 } // End if. 0053 0054 System.out.println( "Item is " + event.getItem()); 0055 0056 System.out.print( "State Change is ... "); 0057 if ( event.getStateChange() == ItemEvent.SELECTED) { 0058 System.out.println( "Selected"); 0059 } else { 0060 System.out.println( "Deselected"); 0061 } // End if. 0062 0063 if ( event.getID() == ItemEvent.ITEM_STATE_CHANGED ) { 0064 System.out.println( "ID is ITEM_STATE_CHANGED."); 0065 } // End if. 0066 System.out.println( "\n"); 0066 } // End itemStateChanged.
The CheckExample class also declares a main() method, which doers not differ significantly from the ClickCounterTranslation main() method from Chapter 1. When the application was launched and the Italic Checkbox selected and immediately deselected the output produced was as follows.
Item Selectable is italic Button Item is Italic State Change is Selected ID is ITEM_STATE_CHANGED. Item Selectable is italic Button Item is Italic State Change is Deselected ID is ITEM_STATE_CHANGED.
The first line of each output is produced by lines 0043 to 0052 and shows that the getItemSelectable() method returns the identity of the Checkbox used. The second line is produced by line 0054 and shows that the getItem() returns the Checkbox's label. The third line differs between the two outputs and shows the use of the getStateChange() method on line 0057. Finally the only ID value which will be returned from a Checkbox is ITEM_STATE_CHANGE, used on line 0063.
In order to configure Checkbox instances as radio buttons an instance of the CheckboxGroup class has to be created and specified as the group attribute of the set of buttons. The major resources of the CheckboxGroup class are given in Table 2.13.
Table 2.13 Major resources of the CheckboxGroup class.
The CheckboxGroup class encapsulates the identities of the Checkboxes which comprise its group and maintains knowledge of which one is currently selected. It has a single default constructor and an enquiry and a modifier method for the currently selected component. The following init() method, from a class called RadioExample, creates four Checkbox components configured as radio buttons which might be a part of an interface which selects the formatting options for a paragraph.
0013 public class RadioExample extends Applet 0014 implements ItemListener { 0015 0016 private Checkbox leftButton; 0017 private Checkbox rightButton; 0018 private Checkbox justifyButton; 0019 private Checkbox centerButton; 0020 0021 public void init() { 0022 0023 CheckboxGroup theGroup = new CheckboxGroup(); 0024 0025 this.setLayout( new GridLayout( 2, 2, 5, 5)); 0026 0027 leftButton = new Checkbox( "Left", false, theGroup); 0028 leftButton.addItemListener( this); 0029 this.add( leftButton); 0030 0031 rightButton = new Checkbox( "Right", false, theGroup); 0032 rightButton.addItemListener( this); 0033 this.add( rightButton); 0034 0035 justifyButton = new Checkbox( "Justify", true, theGroup); 0036 justifyButton.addItemListener( this); 0037 this.add( justifyButton); 0038 0039 centerButton = new Checkbox( "Centre", false, theGroup); 0040 centerButton.addItemListener( this); 0041 this.add( centerButton); 0042 } // End init.
As all four Checkbox buttons have the same CheckboxGroup specified in their constructor they will behave as a single group of radio buttons and as the Justify button has been constructed with its state specified true it will be initially shown as selected. The appearance of the interface produced by the code, using a two by two GridLayout and with the Right radio button selected is shown in Figure 2.6.
Figure 2.6 Checkbox example configured as radio buttons.
The examples in Figures 2.6 and 2.
Item Selectable is centre Button Item is Centre State Change is Selected ID is ITEM_STATE_CHANGED.
CheckExample.javaCheckExample.java
CheckExampleCheckExample
RadioExample.javaRadioExample.java
RadioExampleRadioExample
2.7 The Choice class2.7 The Choice class
2.5 The Button class2.5 The Button class | https://flylib.com/books/en/2.195.1.20/1/ | CC-MAIN-2019-18 | refinedweb | 1,273 | 50.84 |
Recently, I was wondering how best to decouple the code needed to track certain form submissions (e.g. conversion tracking in Google Analytics or Matomo) from the business logic of the forms.
Hooks are often used to solve these types of problems. Using hooks makes it possible to decouple our components responsible for handling business logic from the purely optional tracking logic, which we can then keep in one place instead of scattering across all our components.
The setup
Before we take a look at how this technique can decouple tracking from the rest of the application logic, we begin by setting up our hook system.
// src/utils/hooks.js const hooks = []; export function addHook(hook) { hooks.push(hook); } export function runHooks(context) { return hooks // Only run hooks that fulfill their condition. .filter(hook => hook.condition(context)) .map(hook => hook.callback(context)); } export function withHooks(func, context) { return (...args) => { const result = func(...args); if (result.then) { result .then(payload => runHooks({ ...context, payload })) .catch(error => runHooks({ ...context, error })); return result; } runHooks({ ...context, payload: result }); return result; }; }
The code above makes it possible to add Hook objects to a stack of Hooks which are triggered as soon as
runHooks() is called. Each Hook is an object with a
condition and a
callback. The given
callback() function is only called if the
condition() function returns
true. Both functions are passed the
context of the current method which is called.
Event tracking with Hooks
Now we’re ready to use our Hook module to build a decoupled event tracking system. In the following code snippet you can see the code of the
ContactFormContainer component which is responsible for injecting the dependencies for the
ContactForm component.
<template> <ContactForm/> </template> <script> // src/components/ContactFormContainer.vue import { post } from '../services/contact-form'; import { withHooks } from '../utils/hooks'; import ContactForm from './ContactForm.vue'; export default { components: { ContactForm, }, provide: { // We pass an additional `id` context // property to make it easier to identify // calls of `post()` when running our Hooks. post: withHooks(post, { id: 'contact-form.post' }), }, }; </script>
If you’re also interested in the code of the
ContactForm component you can take a look at it here.
By wrapping the
post() method
withHooks() all Hooks are now executed every time the provided
post() method is called in the
ContactForm component.
Register tracking event Hooks
There are currently no Hooks that could be executed as we have not added any Hooks yet. Let’s change that by adding a new file where we can register all our tracking Hooks.
// src/utils/tracking.js import { addHook } from './hooks'; const CONTACT_FORM = 'contact-form.post'; addHook({ condition({ error, id }) { return !error && id === CONTACT_FORM; }, callback(context) { // This is where you'd trigger your Google // Analytics or Matomo tracking event. console.log('track contact form submission', context); } });
Here you can see that we add a new Hook which is only fired if there is no error and the
id context parameter matches the
CONTACT_FORM id. In the
callback() function we’d usually trigger an event in our tracking service of choice but because this is only a demo we simply trigger a
console.log().
Do you want to learn more about advanced Vue.js techniques?
Register for the Newsletter of my upcoming book: Advanced Vue.js Application Architecture.
Prevent tracking in certain environments
You most likely do not want to send tracking events in your development environment or, for example, when running unit tests. Because we have everything in one place with this approach, we can easily prevent tracking in certain environments.
// src/utils/tracking.js import { addHook } from './hooks'; const CONTACT_FORM = 'contact-form.post'; const TRACKING_ENABLED = process.env.NODE_ENV !== 'development'; if (TRACKING_ENABLED) { addHook({ condition({ error, id }) { return !error && id === CONTACT_FORM; }, callback(context) { // This is where you'd trigger your Google // Analytics or Matomo tracking event. console.log('track contact form submission', context); } }); }
Error tracking with Hooks
In the following example you can see how we can also use Hooks to implement a centralized error tracking system.
// src/utils/tracking.js // ... addHook({ condition({ id }) { return id === USER_CREATED; }, callback(context) { if (context.error) { // This is where you'd trigger an event in // Sentry or some other error tracking service. return console.log('track error', context.error); } console.log('track new user', context); } });
If the
context contains an
error property we don’t track a Google Analytics or Matomo event but send an error event to our error tracking service instead.
Click tracking with Hooks
Hooks are especially useful for intercepting API requests but we can basically use it for everything we want. But keep in mind that this pattern is best with an all or nothing approach. You might run Hooks for every API request and you might build a custom router link or button component to run Hooks every time a link or a button is clicked. But I’d recommend you to not use
withHooks() for individual cases.
If you use
withHooks() to trigger Hooks only if a certain button in you application is clicked, you might later remove the Hook which is listening for this button click which means it is now unnecessary to run Hooks when this specific button is clicked. You might later add a Hook listening for this button to be clicked again but other people on your team might have no idea that this is even an option. On the other hand if you have a generic button component which always runs Hooks you’re free to add or remove Hooks at any time.
Wrapping it up
As with almost every advanced pattern in programming, hooks also have their downsides. First of all, they add another layer of complexity. Adding tracking logic directly into the code of your components may not be the cleanest solution, but it is definitely the most straightforward. Especially if your application is very small, using Hooks might only make your codebase more complicated instead of making it simpler.
I strongly recommend that you first think about all the advantages and disadvantages before deciding whether you want to implement this pattern or not. However, in the right circumstances, it can greatly improve the overall architecture of your Vue.js app. | https://markus.oberlehner.net/blog/build-decoupled-vue-applications-with-hooks/ | CC-MAIN-2019-43 | refinedweb | 1,025 | 55.64 |
Author: Miguel Sofer <[email protected]> Author: David S. Cargo <[email protected]> State: Final Type: Project Vote: Done Created: 20-Sep-2008 Post-History: Keywords: tailcall,NRE Tcl-Version: 8.6
Abstract
This TIP recommends adding proper tailcalls to Tcl.
Proposal
We propose to add a new command:
tailcall cmd ?arg ...?
The command can only be invoked in a procedure or lambda body.
The effect of this command is very similar to:
return [uplevel 1 [list [namespace which cmd ] ?arg ...?]]
with the sole exception that the invocation of cmd happens after the currently executing body returns and is not visible in Tcl's call stack.
Rationale
The new Non-Recursive Engine (NRE) implemented in Tcl 8.6 allows support for a number of interesting features that have previously been difficult or impossible to implement efficiently in Tcl. One such feature is support for proper tailcalls, an important feature for functional-style programming. The new command allows unbounded recursion and enables programming in continuation passing style.
Effect on Tcl's Call Stack
tailcall is implemented as a new command, as opposed to an optimization that would be done automatically by the bytecode compiler, due to the effect it has on Tcl's call stack.
Consider the following example:
proc showStack {} { set depth [info frame] set res {} for {set i 1} {$i <= $depth} {incr i} { lappend res [info frame $i] } return $res } proc one cmd {join [$cmd] \n} proc two {} {uplevel 1 showStack} proc three {} {tailcall showStack}
When run at the interactive prompt, we obtain
% one two type eval line 1 cmd {one two} level 2 type proc line -1 cmd {$cmd} proc ::one level 1 type proc line 1 cmd {uplevel 1 showStack} proc ::two type eval line 1 cmd showStack proc ::two type proc line 5 cmd {info frame $i} proc ::showStack level 0 % one three type eval line 1 cmd {one three} level 2 type proc line -1 cmd {$cmd} proc ::one level 1 type proc line 5 cmd {info frame $i} proc ::showStack level 0 %
Remark how tailcall completely removed the proc three from Tcl's call stack. This effect is also apparent on error traces.
Implementation
An experimental implementation of tailcalls is available in Tcl 8.6a2 in CVS on sourceforge, in the ::tcl::unsupported namespace.
This document has been placed in the public domain. | https://core.tcl-lang.org/tips/doc/trunk/tip/327.md | CC-MAIN-2019-43 | refinedweb | 387 | 57.71 |
that's a good work around until I find a better way to do it, but that
means that all of my shipped scripts need to have import xxx reload xxx in
them, more to the point this is a hassle that I really didn't want to have
to expose to the user. I didn't realize that there was so mush shared state
between separate invocations of PythonInterpreter. Why create a new Object
if all you are getting is a reference to an existing shared environment?
Makes me wonder just how thread safe it is.
Guy
-----Original Message-----
From: Kevin Butler [mailto:kbutler@...]
Sent: Monday, February 11, 2002 8:21 AM
To: Guy Gascoigne-Piggford
Cc: 'jython-dev@...'
Subject: Re: [Jython-dev] import problem with changed modules
> I figured that I would be much more likely to get an answer to my
> problem if I explained it a bit more carefully J
Yes - I didn't have an answer for the previous version. :-)
> So, if I have two modules, mod_A and mod_B, and mod_A imports mod_B,
> if create a PythonInterpreter and exec mod_A, and then whilst the
> system is running edit mod_B, and then in a new Interpreter exec modA
> the old version of mod_B is what gets imported. It doesn't seem to
> matter whether I edit mod_A or not.
> Is there something I can do to force the new PythonInterpreter to
> re-read mod_B?
Simply make mod_A start:
import mod_B
reload( mod_B )
kb
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/jython/mailman/jython-dev/thread/654B0720BF355D4E93461DD58993086EEC5327@VIPERFISH/ | CC-MAIN-2017-30 | refinedweb | 290 | 68.2 |
Tech Off Thread33 posts
zero-length string == nothing ??
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.
Pagination
Is this supposed to evaluate to TRUE in vb.net?
--------------------
Dim strMessage as String
If strMessage = "" Then
'if true, do some stuff here
End If
-------------------
strMessage, in debug mode, shows a value of "Nothing".
Is "Nothing" supposed to equal a string of zero length?
I would have thought Nothing == Null.....which is different than ""
VB will use its own library to do string comparisons, of which is will essentially say that, null is nothing, zero length is nothing. If you pull the IL apart, you'll find VB calling a visual basic compiler services method of some sort.
Kinda one of the reasons I don't like VB, brings a ton of crap with it (althought I think I heard you can tell the compiler not to do this now).
static bool String.IsNullOrEmpty(String str);
I appreciate the addition, but that really makes me sound like I've been doing .NET for 3 days or something
Option Strict On ?
But its more if you drastically need compilation control I guess.. plus- it doesn't stop vb from trying to call that method.. but it does mean you get to define the method yourself.
You could probably use:
to walk around the "problem" of VB.NET. This will fall back to the bahaviour that you expect.
I just tried this in VS2008 and it does evaluate to true....wow...does 0 equal nothing too, since that's the default value of an Integer....wow that does too....who made that decision?.
No such luck. It's default behavior like most here suggested.
My practice is to declare a string with a default value of either String.Empty or just plain "".
In this case, I either forgot or someone else forgot to do this.
Good point on String.Compare
if you like that more. It also returns a Boolean instead of an Integer and it's also what the == operator on String uses internally.
strMessage Is String.Emptyalso works.
Well, in VB.NET Nothing has a very different meaning than Null in C#. In C#, null refers only to reference types and means there is no reference assigned to the reference variable. Nothing, on the other hand is the default value of any particular data type or object.
Comment removed at user's request.
static bool IsNullorEmpty(string s){
return ((object)s == null) || (s.Length == 0);
} | https://channel9.msdn.com/Forums/TechOff/412464-zero-length-string--nothing- | CC-MAIN-2017-09 | refinedweb | 442 | 76.62 |
This article originates from a post I ding on the ASP.NET Dynamic Data Forum here Re: A few problems with my dynamic data website, Rick Anderson suggesting that it would be a useful post to link to in his FAQ. So here it is for easy access rather than having to search the forum for it.
Firstly the idea is that you want to show the name of the entity but not link to if from the ForeignKey FieldTemplate.
Figure 1 - Category has Navigation disabled
The code we need for this comes in three parts
- The Attribute
- The modification the the FieldTemplate
- The Metadata.
The Attribute
[AttributeUsage(AttributeTargets.Property)] public class AllowNavigationAttribute : Attribute { public Boolean Show { get; private set; } public AllowNavigationAttribute(Boolean show) { Show = show; } // this will allow us to have a default set to false public static AllowNavigationAttribute Default = new
AllowNavigationAttribute(true); }
Listing 1 – AllowNavigation attribute
Note the use of the Default see Writing Attributes and Extension Methods for Dynamic Data for the details on why.
The modification the the FieldTemplate
Now we need to add a little change to the ForeignKey.aspx.cs file which can be found in the ~/DynamicData/FieldTemplates folder of your Dynamic Data site.
protected string GetNavigateUrl() { var allow = Column.Attributes.OfType<AllowNavigationAttribute>() .DefaultIfEmpty(new AllowNavigationAttribute(true)) .FirstOrDefault().Show; if (!AllowNavigation || !allow) { return null; } if (String.IsNullOrEmpty(NavigateUrl)) { return ForeignKeyPath; } else { return BuildForeignKeyPath(NavigateUrl); } }
Listing 2 – ForeignKey FieldTemplate modifications
All we’ve done here is get the attribute into the allow variable and the add it to the checks in the if statement so that:
- If the internal AllowNavigation is set then null is returned.
- If the custom attribute is set null is returned.
The Metadata
[MetadataType(typeof(ProductMD))] public partial class Product { public partial class ProductMD { //EntityRef [AllowNavigation(false)] public object Category {get;set;} } }
Listing 3 – sample Metadata
Now if you attribute a foreign key column up with the AllowNavigationAttribute you can turn off the hyperlink.
Happy Coding and remember You’re a PC
16 comments:
Hei,
where should I write the first part(The Attribute)?Metadata,...?
That depends, I always asume a website not a Web Application Project, you put in a class file:
Website: ~/App_Code
Web App: anywhere - but remember it must have a namespace here.
Steve :D
Hi,
It works very well, the link is disabled. But the ForeignKey FieldTemplate still become underlined and blue when the mouse went on it! Please, how can I correct this?
I'll look into it e-mail me direct as I'm watching Tech.days till late tonight :D my e-mail is top right of the page.
Steve
Here's the new post sadly LiveWriter only allows me to post a new version :(
Steve :D
Anybody have a VB version of this?
I woudl do search for a C# to VB converter and convert the listings and then paste them into a VB project.
Steve
Tried that but could not get it to work :(
I'll look at doing a VB convetion I will post the code along side the C# here or in a new article (Livew writer sometime posts to a new article if the article I'm updating is very old)
Steve :D
Tried to get it to work with .Net 4.0... No go!
Only spent about 30 Minutes looking into issue. I suspect this is a case of outdated information, where information needs to be slightly tweaked to work for next version.
You are right there will be some minor issue between DD1 and DD4
Steve
Hi Steve,
I tried your above code, but the hyperlink doesn't get disabled in edit mode.
How can we disable the foreign key hyperlink during edit?
Please help.
Thanks
Rag
Hi Raghu, I'm away at the moment so send me an e-mail reminding me about this and I'll test and fix when I get back.
Steve :)
Hi Steve,
Just a gentle reminder about my previous question on disabling hyperlinks in edit mode.
Thanks,
Raghu
still away sorry :)
Steve
Hi raghu, I'm back now an will have a look as soon as I get a moment.
Steve | http://csharpbits.notaclue.net/2009/01/allow-navigation-on-foreignkey.html | CC-MAIN-2017-30 | refinedweb | 691 | 58.62 |
Step 1:
I'm sure with most code editors the first program you will ever see is this fun little > 10 line chunk of code here:
#include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; }
As simplistic as this "program" is, I thought this was the coolest thing ever when I saw it for the first time last semester. I made my computer talk with a pop up window on my desktop! What else could I make my computer do?
Step 2:
Now let's go a step further. Let's do some math!
- To begin take out your cout hello world line....
- Replace that line with
cout << "Enter two numbers you want to perform addition, subtraction, multiplication, and division on:" << endl;
Not much has changed. You are still telling the your program to output text with "cout <<". Except this time, we are asking the user to do something. We want them to input two integers to begin our arithmetic. How do we save those responses? Well...instead of outputting information with cout....we could TAKE IN information with cin >>.
-Right below your new cout line, place this code.
double x, y; cin >> x >> y;
- We have told our compiler that the user is inputting two double numbers, x and y.
- A double number is taken out multiple decimal places (great for division).
- Take note that the above is the same thing as:
double x; double y; cin >> x; cin >> y;
- Notice how much more efficient the first code was. Why waste time typing all of that (2nd code)?
Step 3:
Now we need to perform our operations with the numbers provided to us. How do we add, subtract, etc? This is a good time to introduce functions. Think of a C++ program as a house; inside that house are rooms with shut bedroom doors and living rooms. Think of the living rooms as the main () function and the bedrooms as our other functions. Inside of those bedrooms there are instructions doing their own thing and don't care what their housemates are doing outside their room. Let's see what is going on in the addition room.
-Above the main function but below using namespace std; Type the following:
double add(double a, double b) { double r; r = a + b; return (r); }
- double is the "type" of our function
- add is simply the "name" of our function
- the items inside of the (....) are our parameters (allow us to pass arguments to the function when it is called)
What does that stuff inside the {} mean? Well, we are saying that a double (integer) r exists. We are also saying that r is equal to a + b. I.E one number plus another number. Finally, we are saying, "spit out the answer" with return r; when we ask for it. I bet you can think of what we are going to do for subtraction and the rest.
Step 4:
Below the addition function finish up by coding in the other functions:
double subtract(double a, double b) { double r; r = a - b; return (r); } double multiply(double a, double b) { double r; r = a * b; return (r); } double divide(double a, double b) { double r; r = a / b; return (r); }
-Inside all of these other rooms you may notice it is the same kind of setup as our addition. Only our logic (arithmetic) has changed.
Step 5:
Let's get some answers! Alright, now remember the metaphor about the bedrooms? Let's pretend we are writing down some numbers (x, y) on a piece of paper and sliding them under the door to our functions. Once inside the room our scribbled down numbers are being manipulated by the instructions. Keep in mind the final instruction in each "room" was a return statement. That means that the function will slip our paper under the door back to us in the living room with an answer when it is finished!
-Type this code inside our main function below our cin >> line where we first asked for our two numbers (x, y).
cout << "The result of addition is:" << [b]add(x, y)[/b] << endl;
-We called our add function by "calling its name from the living room". We also slid it some numbers under the door. Notice how our call is similar to "add (double a, double b)"? The function is using our new numbers (x, y) as (a, b) so that they may be manipulated.
- The process to call the other functions is the same.
Step 6:
The final program....
#include <iostream> using namespace std; double add(double a, double b) { double r; r = a + b; return (r); } double subtract(double a, double b) { double r; r = a - b; return (r); } double multiply(double a, double b) { double r; r = a * b; return (r); } double divide(double a, double b) { double r; r = a / b; return (r); } int main() { cout << "Enter two numbers you want to perform addition, subtraction, multiplication, and division on:" << endl; double x, y; cin >> x >> y; cout << "The result of addition is:" << add(x, y) << endl; cout << "The result of subtraction:" << subtract(x, y) << endl; cout << "The result of multiplication is:" << multiply(x, y) << endl; cout << "The result of division is:" << divide(x, y) << endl; return 0; //This tells our program to GTFO we are done with it. }
I hope I did not bore any viewers. The reason I drug this out so much was because, being a beginner, I know it is necessary for some people to need to see a program come together with explanations instead of slapping them with a finished product saying "here it is, learn" when they have no idea what is going on inside. Any thoughts from professionals are welcome and please feel free to add suggested changes as I'm sure somewhere it could have been coded more elegantly. Though, for a simple program, I feel it is sufficient to learn some basics.
Happy coding! | http://www.dreamincode.net/forums/topic/322601-simple-arithmetic-program/page__pid__1860393__st__0 | CC-MAIN-2016-07 | refinedweb | 997 | 69.82 |
Monday, October 27, 2014¶
A thing which had been waiting for a long time because it is purely
internal: I changed the format of the atelier config file. This had
become necessary because recent changes had broken the possibility to
manage Sphinx doctrees without a corresponding Python module. It
caused a welter of subtle changes which influence the configuration of
atelier.
Manuel stumbled over a bug that had passed the test suite on my development machine because I had not tidied up my .pyc files for several months.
The bug itself was trivial,
lino.modlib.pages still did:
from lino.modlib.plain.renderer import PlainRenderer
Which (since 2014-07-29) should have been:
from lino.modlib.bootstrap3.renderer import Renderer
But it is of course rather time-consuming to diagnose such bugs.
How can I make sure to avoid this problem? IOW How to tidy up .pyc files in a repository which I never pull from outside? Okay I wrote a fab pyc command which removes .pyc files that don’t have a corresponding .py file. But will I remember to run this command when it is time to do so? | http://luc.lino-framework.org/blog/2014/1027.html | CC-MAIN-2019-13 | refinedweb | 191 | 67.86 |
On Sun, Aug 23, 2015 at 2:01 PM, wm4 <nfxjfg at googlemail.com> wrote: > On Sat, 22 Aug 2015 22:48:39 -0400 > Ganesh Ajjanagadde <gajjanagadde at gmail.com> wrote: > >> On Thu, Aug 20, 2015 at 7:27 PM, Ganesh Ajjanagadde >> <gajjanagadde at gmail.com> wrote: >> > Fixes -Wunused-function from >> > >> > >> > Signed-off-by: Ganesh Ajjanagadde <gajjanagadde at gmail.com> >> > --- >> > libavformat/hls.c | 3 ++- >> > 1 file changed, 2 insertions(+), 1 deletion(-) >> > >> > diff --git a/libavformat/hls.c b/libavformat/hls.c >> > index 82dd744..8a83e40 100644 >> > --- a/libavformat/hls.c >> > +++ b/libavformat/hls.c >> > @@ -495,6 +495,7 @@ static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url >> > return 0; >> > } >> > >> > +/* unused >> > static int open_in(HLSContext *c, AVIOContext **in, const char *url) >> > { >> > AVDictionary *tmp = NULL; >> > @@ -506,7 +507,7 @@ static int open_in(HLSContext *c, AVIOContext **in, const char *url) >> > >> > av_dict_free(&tmp); >> > return ret; >> > -} >> > +} */ >> > >> > static int url_connect(struct playlist *pls, AVDictionary *opts, AVDictionary *opts2) >> > { >> > -- >> > 2.5.0 >> > >> >> ping, just making sure this was not missed. > > Why comment it instead of removing it? It is a non-obvious function that may be used later (see the #if 1 and #endif in the same file), and it is easier to read the source than a git log. See recent patches I sent out, I left most things commented out instead of deleting them due to similar reasoning. I could remove it if that is what people want, and personally don't care either way. If we are going with the delete, then we are prioritizing "clean code", in which case I would remove the #if 1 business as well. > _______________________________________________ > ffmpeg-devel mailing list > ffmpeg-devel at ffmpeg.org > | http://ffmpeg.org/pipermail/ffmpeg-devel/2015-August/177769.html | CC-MAIN-2019-30 | refinedweb | 275 | 64.2 |
Subject: [Boost-bugs] [Boost C++ Libraries] #12408: cpp_dec_float_50 x = x*x*x gives wrong result!!!
From: Boost C++ Libraries (noreply_at_[hidden])
Date: 2016-08-23 11:42:26
#12408: cpp_dec_float_50 x = x*x*x gives wrong result!!!
---------------------------------------+------------------------------
Reporter: Dave Nalepa <denalepa1@â¦> | Type: Bugs
Status: new | Milestone: To Be Determined
Component: None | Version: Boost 1.61.0
Severity: Problem | Keywords:
---------------------------------------+------------------------------
I'm a beginner with C++ and with boost so I won't be surprised if I'm
making some blunder but in case there's a real problem here, here goes:
Using the multiprecision cpp_dec_float_50 I get a enormous error when I
cube a variable.
I'm using Microsoft VS2015 Community and making a console program (since
my attempts at using boost with a cli program failed miserably).
The core code (I think) is
#include <boost/multiprecision/cpp_dec_float.hpp>
using boost::multiprecision::cpp_dec_float_50;
// both at the global level = before main(){...
I set f2 to this and then use the line
f2 = f2*f2*f2; //to compute (f2)³
when f2 = 1.0335055959... I get the new f2 as 1.140909... which isn't even
close to the correct value of 1.10392227...
When I use a temporary variable, f3, it works just fine
f3= f2*f2*f2 // f3 = 1.1039...
It is probably some error the compiler is making, I don't know. This is
obviously a worrisome bug. Simple arithmetic shouldn't give results that
are off by 3% !!
I'm not skilled enough in VS2015 to know what else to tell you about the
switches that are or are not selected; I compile and run in the VS IDE.
//===================================== here's the entire program (stub)
// I've shortened 1.03559... but I still get the wrong value.
#include <iomanip>
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
using boost::multiprecision::cpp_dec_float_50;
int main()
{
cpp_dec_float_50 f2 = (cpp_dec_float_50)(1.03559);
f2 = f2*f2*f2;
std::cout << "f2 = " << f2 << std::endl;
// gives me 1.15.... which is wrong should be 1.1106...
// it is actually the value of f2*f2*f2*f2, or close to it.
return 0;
}
-- Ticket URL: <> Boost C++ Libraries <> Boost provides free peer-reviewed portable C++ source libraries.
This archive was generated by hypermail 2.1.7 : 2017-02-16 18:50:20 UTC | https://lists.boost.org/boost-bugs/2016/08/45875.php | CC-MAIN-2019-43 | refinedweb | 377 | 75.61 |
This page contains some KiSS utilities in source-code format. They are written in strict ANSI C, so they should be easily portable across hardware and Operating System architectures. They have all been tested on several architectures, including RISC OS, Windows and *ix.
All this source code is released under the terms of the GNU General Public License (GPL) aka CopyLeft. Some of the code is based on RISC OS applications available elsewhere on this site which were also written by me - these other programs are FREEWARE, not GPL (yet).
Supports the full FKISS 4 syntax.
#include <stddisclaimer.h>
Need I say more?
Return to index. | http://tigger.orpheusweb.co.uk/KISS/nfcode.html | CC-MAIN-2019-13 | refinedweb | 106 | 66.74 |
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
namiml/nami-apple
Nami SDK
Why Nami?
Nami is on a mission to help app developers make more money by providing you tools to successfully sell your apps, not your users.
With Nami you can focus on your core app experience, not integrating and testing StoreKit and building in-app purchase or subscription offer screens. Our platform moves the critical elements to the cloud so you can make changes without making app updates.
1. Create your Nami account
2. Add your App to Nami
After creating your account, add your app to the Nami Control Center.
Watch a walkthrough video or read a step-by-step guide for adding your app.
3. Download the Nami Framework
Clone or download this repository!
Requirements
- iOS 11+, iPadOS 13+
- Built for Xcode 12, if you still use Xcode 11.3.1 use the framework located in Xcode11 folder and follow the "Add Manually" instructions below.
4. Add the Nami Framework to your Xcode project
Using CocoaPods
Add the following line to your Podfile. See the example in this repo
Podfile.example.
pod "Nami", "2.5.1"
Then run the command
pod install
Using Carthage
Temporarily removed Carthage support until XCFramework support is fully resolved.
Add Manually
The XCFramework added via the Swift Package Manager and Cocoapods is built for Xcode 12. If you are using Xcode 11.3.1, you'll need to add the Nami framework manually to your project - you can also use this technique in Xcode 12 if you wish.
For Xcode 11.3.1, you can download the version of the Nami framework in the "Xcode11" directory, in a file named Nami-xcode11_3_1.xcframework.zip. Unzip that file after downloading to extract the framework and follow the instructions below.
For Xcode 11.6 and higher, you can just download the Nami.xcframework directory in the top level of the Nami GitHub repository.
After downloading the Nami framework from GitHub in the Nami repository, move to your application Project settings page in Xcode, and go to the General tab. Scroll down until you can see the "Frameworks and Libraries" section, and drag Nami.xcframework from the finder into this area.
A dialog will come up to verify, opt to "copy" the framework into the project so that your application has a copy of the framework to check into source control.
When complete, you can verify the Nami framework has been added properly by adding
import Nami to the
AppDelegate.swift file and then compiling your project. If everything is configured properly, the app will build and link with the Nami library. If you receive errors, try cleaning the build folder or removing the Nami framework from your project and try re-adding it.
Make sure the option to "Embed and Sign" is chosen instead of just "Embed".
Note: Updating the Nami Framework Manually
When a new version of the Nami framework is released, just drag it over your old Nami framework in your application project directory - make sure to select "replace" instead of "merge". After the framework has been copied over the old one, make sure to select "Clean Build Folder" in Xcode so it properly refreshes the binary from the framework.
5. Setup the Nami Framework in your App
In your application delegate, the Nami SDK is configured and passed your unique app ID, You can find the Nami App ID under the Developer tab of the Nami Control Center's App Settings section.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Configure Nami Nami.shared.configure(appID: "YOUR_APP_ID_GOES_HERE") return true }
It is recommended that you move the Nami setup code to its own method if you start adding other configuration calls (we'll cover these other possible calls later). Also if you have existing code in the
didFinishLaunchingWithOptions method, please call the Nami configure method as soon as possible to help the system initialize quickly and be ready for purchases.
Try building again to make sure all is well, then you are set up and ready to move to the next step.
6. Add Products
Add your App Store in-app purchase products to the Nami platform to use them from your cloud-based paywalls.
Products are managed from the Nami Control Center > Products
Watch a walkthrough video or read a step-by-step guide for adding products.
7. Add Your First Cloud-Controlled Paywall
The Nami framework supplies the views and view controllers you need to offer your products to your users. Since these Nami-powered screens are managed in the cloud, you can make changes without app updates.
Paywalls are managed from Nami Control Center > Paywalls
Learn more about adding a paywall.
8. Create a Campaign
How and when you present paywalls to your users are governed by business rules specified in a campaign.
Campaigns are managed from Nami Control Center > Campaigns
Learn more about creating a campaign.
Take your campaign live and you will see your paywall presented once business rule conditions are met.
Next Steps: Dive Into Additional Functionality
For more details on using the SDK, check out our help documentation at.
Github
You may find interesting
Releases
v2.5.1 - 2021-02-17T16:16:01. | https://swiftpack.co/package/namiml/nami-apple | CC-MAIN-2021-10 | refinedweb | 877 | 63.29 |
This page describes the life cycle of a Django project managed using zc.buildout. The files used for this document are available in the template module in Subversion.
This is preliminary documentation. I'm just starting to use this in practice so we will undoubtedly discover that some initial assumptions don't hold or are just plain incorrect. Eventually it should be trivial to add zc.buildout to an existing Django project.
To start a project, download bootstrap.py and save it to your project directory. bootstrap.py is a Python script which downloads zc.buildout itself, along with setuptools if necessary, and creates a wrapper script for the buildout command.
Run bootstrap.py with your choice of Python interpreter (2.4 or newer). The interpreter used to run bootstrap.py will be set as the default interpreter for all scripts generated by the buildout process.
Running bootstrap.py creates (among other things) a bin subdirectory, along with a buildout script. The buildout script reads the buildout configuration (named buildout.cfg by default) and assembles the software described in it. It can be run any time you update the dependencies of your project to retrieve eggs. Running buildout also checks for newer versions of dependencies (including zc.buildout and setuptools) and downloads them if possible.
After running bootstrap.py (a one-time thing), we're ready to write our initial buildout configuration and run ./bin/buildout. Our initial configuration will do the only thing we can do at this point -- download Django and make create the django-admin script.
Our buildout.cfg will look something like this:
# Minimal Django Buildout
#
#
[buildout]
bin-directory = ./bin
find-links =
parts = django
[django]
recipe = zc.recipe.egg
eggs = Django==0.95 django_buildout
Since this is our first time running buildout, it is useful to examine the features of buildout.cfg used in the template.
As with Python code, # indicates a comment. Taking the file section-by-section, the [buildout] section is the only one whose name is fixed. This section contains information for our entire buildout. The bin-directory setting tells buildout where we want our scripts to be stored. The find-links setting tells buildout where to look (beside the Python Package Index) for packages. The parts setting is the most important: it tells buildout which "parts" make up our application. For some background on buildout terminology, see the buildout documentation.
In our case the file says that a single part will be installed -- django. The part names coorespond to other configuration section titles.
Looking at the django part definition, we see two parameters: recipe and eggs. Every part has a recipe which performs the actual functionality. The zc.recipe.egg recipe installs Python eggs and their dependencies. The eggs to install are specified by the eggs setting. You can specify multiple eggs, separated by spaces.
Run ./bin/buildout which will read the buildout configuration file and install Django (and any dependencies it might declare) in the eggs sub-directory. It will also create news script in bin, including django-admin. This version of django-admin has your preferred Python interpreter set, as well as code to add any Python eggs necessary to the PYTHONPATH before calling the actual Django code.
More Information:
It can be useful to store the source files for your project in the src sub-directory of your project. To start our new Django project, we'll create the src sub-directory and then run django-admin, just like you would normally do.
$ mkdir src
$ cd src
$ ../bin/django-admin startproject myproject
At this point you your Django project started in the myproject directory. You'll also want to write a setup.py for the project. This will declare the dependencies for your project, and will allow zc.buildout to install them. The setup.py should go in the same directory as your buildout.cfg. A basic setup.py would look something like this:
# Minimal Django Buildout setup.py
#
#
from setuptools import setup, find_packages
setup(
name = "myproject",
version = "0.1",
packages = find_packages('src'),
package_dir = {'':'src'},
# scripts and dependencies
dependency_links = [
"",
""],
install_requires = ['setuptools',
'Django==0.95',
'django_buildout',
],
include_package_data = True,
zip_safe = False,
# author metadata
author = 'Nathan R. Yergler',
author_email = 'nathan@yergler.net',
description = 'A simple Django app for demonstrating django-buildout.',
url = '',
)
You'll also want to add the following line to the [buildout] section of buildout.cfg:
develop = .
This tells zc.buildout to construct a develop-egg from the current directory. A develop-egg is a special "pointer" file that tells setuptools to treat a path on the filesystem (in this case probably src) as an egg. This allows you to continue developing your project without re-building it as an egg every time you make a change.
You can re-run ./bin/buildout now and it will process your setup.py and the new develop line in buildout.cfg. It will also update the django-admin script it creates to include your project on the Python path.
NOTE: The manage.py created in your project will not have its Python path configured correctly. The django-buildout egg generates a manage script for you (placed in the bin directory) that you can replace the provided manage.py with. Yes, this is a wart.
You can declare dependencies by adding them to the list of requirements in setup.py. Dependencies needed for execution should be added to the install_requires parameter. Dependencies needed to test your application can be specified in the test_requires parameter. For details on the setup() parameters and how to format package declarations, see the [ setuptools documentation].
XXX needs example
XXX
XXX When deploying with mod_python you can use django-buildout to generate the basic configuration for you. | http://code.google.com/p/django-buildout/wiki/ProjectLifecycle | crawl-003 | refinedweb | 948 | 60.21 |
[Advertisement]
The formatting here will probably get hosed, but for what it's worth:
<exec program="${vs.dir}\devenv.com">
<arg value="/rebuild" />
<arg value="${configuration}" />
<arg value="the_project_file.sln" />
</exec>
My argument for breaking code up into assemblies. Is based off of reuse scenarios. If you will always need the full sebang your argument rings true. If you ever want to ship just parts than splitting them up maybe a good idea.
Kyle Bailey invited some criticism in his article, so I'm going to deliver it. You can read the...
No, I don't do what you're suggesting. Here's my response:
dotnettricks.com/.../704.aspx
Kyle,
There are good reasons to want to have the same structure in both scenarios. Repeatability and consistency is one of them.
I don't want to have to deal with different release version when I need to solve a problem.
That said, I am beginning to lean toward the two projects system. One for the app, one for the tests, and that is it.
And creating a build script is usually a matter of few minutes.
I'm all for the single-assembly-per-location approach. But as Ayende says, you want to test your build under the same circumstances. That's why I use nant to build (and test) before commiting and in the CI server. I just use msbuild(VS) when I am making quick changes and want to check that the thing compiles. But I always end up with a nant build.
I like the idea of one assembly per physical location, although there is a specific need for a single module in my application to be upgradeable (there's a really good reason, just trust me). I may modify my production build to just make a single assembly after reading this.
I hate relying on Visual Studio projects and solutions to tell me how to build also. It's nice if ctrl-shift-b will build my project so I can debug it easily. However, projects do not necessarily show all the files that are physically in the directory, so it's easy to have leftover files that are no longer in use but not part of the project. A build script will detect these as long as it doesn't rely on the projects or solutions to tell it what to build. Also, a build script is your environmental documentation and it's much easier to show how your application is structured and what is referenced in a build script (since you have to do it explicitly) than in Visual Studio (because then I have to open each project and click "references" and it doesn't show me where they are without clicking properties, etc.).
Kyle Bailey invited some criticism in his article, so I'm going to deliver it. You can read the original
@Josh: Yes, you're absolutely right. If you are planning to re-use anything in the very near future. But that's another topic. The summary: Building re-usable components before you know how they'll be re-used will make them that much less re-usable.
@Fregas: You can set up NAnt to compile all .cs or .vb files in a folder into an assembly (including all subfolders). If I had to update my build file every time I added a class, I sure wouldn't be recommending this practise. And yes, you're right, doing this with the hopefully-now-defunct project-less web sites is likely to cause a world of hurt. But then, doing anything with project-less web sites is plenty painful. Let's not discard potentially useful practises because of a minor lapse in reasoning in Redmond.
@Ayende and Alberto: If you were to compile all your C# files into a single assembly, does that alter the structure of the underlying IL compared to if they were in different assemblies? That's not a rhetorical question because I honestly don't know. I.E. If you have three projects, each with a different namespace and a single C# file in them, and you compile them into three separate assemblies, are there any scenarios where that will act differently than if you were to compile all three files into a single assembly?
@Kyle,
I wondered about the possibility of compiling a whole folder, and indeed what you mentioned sounds better, but i'm not entirely convinced--yet. For example, you still run into issues if you've excluded a file in VS.NET but its still in the folder for the nant script to pick up. I do this at times to remove code i don't want to compile at the moment or is going to worked on later. Now you have to have some way of also excluding it from the nant build. Not AS BIG of an issue, but still an issue. The fact is, there's a chance that the behavior or your app is going to very slightly, from one build process to another. Then you get surprises. I don't like surprises.
Craig
@Craig
Yes, you're right. That's an issue if you do exclude files from VS. On the other hand, I like the fact that NAnt includes everything because in the past, it's helped me locate stray classes that are either in the wrong physical location or that have been long-abandoned and just not deleted.
Also, I'm not talking about wild variations in my build process. Remember, this is a CI environment. As long as you use the same build process as my CI server before you check-in, surprises should be minimal. Besides which, surprises aren't a bad thing. After all, that *is* why you have a CI process: to catch them early.
Keep in mind that I'm not totally convinced yet either. I'm basing this solely on conversations with someone who I know would not use the practice if it didn't reduce a great deal of pain for him. My final judgement is still reserved but Donald's a smart guy. Which is probably why he left me to blog about this instead of doing it himself...
Pingback from » Daily Bits - February 12, 2008 Alvin Ashcraft’s Daily Geek Bits: Daily links, development, gadgets and raising rugrats.
Currently I use the same method you described - exec msbuild on solution file, but now I have encountered a situation when I want to target my build separately for .NET and Mono. I want Mono to use different versions of some 3rd party libraries (log4net, for example), but I don't see a way to do this using the VS project structure.
One way of dealing with this would be to XSLT-translate VS project files into NAnt csc targets. This way you still get the benefits of maintaining your projects in one place (VS), but you can modify certain aspects of the build procedure (changing references, for example). The whole thing would have to be executed within the script, off course.
Kyle,
Yeah I can see how CI would definitely catch that kind of stuff early on, rather than right before you go to production or testing. We don't use Ci at my work, but we integrate fairly regularly. Right now our stuff is mall enough and our team is small enough that it doesn't matter as much, but we're looking into getting CruiseControl going.
Kyle, we went through this last gig didn't we? We were compiling all the app code into one assembly, and another into a test one. I thought that was good for testing and when it came to deployment you didn't need the test assembly. Maybe one is too big and I would favor breaking it up for a pure Smart Client solution where you can trickle down individual assemblies for updating (rather than the big bang we would do). I personally thought creating csc tasks to mimic the VS structure was overkill and made things complicated.
Yes, but that was my crappy implementation. I shouldn't have tried mimicking the VS structure via <csc> tasks. That was a bit of madness that I can't rightly justify now that I look back. To do it the way Donald suggests, I would have one <csc> task to compile all the WinForm code (i.e. all the Infrastructure projects plus the domain plus the data access) into a single executable (not including Windsor, CAB, etc, etc). Plus there would be one assembly for each of the web services. So five <csc> tasks total, if I remember correctly, which is one per physical location.
The good part about this is that as you mention, we were already compiling the app code for testing into single assemblies using <csc>. We just needed to expand that idea and compile them based on physical architecture. That way, we could have used the same task to compile the code for testing *and* to compile the code for releases.
But you bring up another interesting point. This doesn't take into consideration ClickOnce deployments which, frankly, I still don't understand completely. They seem to be more msbuild-oriented so if that's the deployment mechanism, this might not work as smoothly.
I'm hoping Donald will expand on this himself and maybe fill in the gaps because I think something may have got lost in my translation.
You could always build the solution file using the msbuild task and then call ILMerge to merge certain assemblies into one.
John
Can anyone please send me the entire (sample) build script for a web application project at my email id johvicky@gmail.com.
The two project solution
How do you build your application details | http://codebetter.com/blogs/kyle.baley/archive/2008/02/11/how-do-you-build-your-application.aspx | crawl-002 | refinedweb | 1,636 | 71.85 |
Table of Contents
If you find this EDG documentation helpful please consider DONATING! to keep the doc alive and current.
Expresso Event Notification is a subsystem that handles letting key users know when important events are completed, or when problems have occured. Utilizing the standard JavaMail API and the Java Activation Framework, Expresso provides easy access from your application to email.Expresso Event Notification is a subsystem that handles letting key users know when important events are completed, or when problems have occured. Utilizing the standard JavaMail API and the Java Activation Framework, Expresso provides easy access from your application to email.
The event-driven processing feature allows any system event (e.g. the publication of a report, a system error, a server being restarted) to trigger email notifications to be sent to a specified list of users (both local and remote (internet)). Any message or attachment can be included with the notification, and an event can be set to trigger other events if required (e.g. a data load might trigger a report to be run). The list of messages and users to be notified is maintained in a series of database tables. When a server-side task, such as loading data into a data warehouse, is completed, it triggers an event with a specific code. The event is then broadcast to a list of specified users that are subscribed to receive the event.
The goal of the Expresso event system is to send email messages to a specified number of people when a specified event occurs. The configuration of the Event system is done through database tables, while the triggering of an Event can take place in one line of code. Events are always asynchronous, and depending on how the system administrator sets up the website, when events are triggered, it is possible that nothing will happen.
An example of an event is a system error - this is a pre-defined event that comes with the system. This event can then have a list of users associated with it that get notified when the event occurs, in the case of a system error, you would probably want to notify your system administrator.
The developer then simply has to specify that an event is triggered and the appropriate notifications are sent out automatically by the system.
Every event is either "successful" (such as a load completing correctly) or "unsuccessful" (such as a load aborting due to a database problem). Successful events can have a different group of users from unsuccessful events - for example, a number of people might want to know that the data load is completed, but you might want to tell the system administrator only if the load fails. Of course, the same people can also be notified of both success and failure if so desired.
The Event configuration tables can be reached through the Operations page from the main Expresso frame. The two tables are:
Event Definitions - This table contains a list of all defined events. An example of a defined Event is SYS_ERROR
Event Email Recipients - This table contains data on who to send email notices to when a particular event triggers
The Event Definitions table is fairly straight forward. The two fields are event name and event description. A pre-built example is SYSERROR which has the description of "System Error." The name SYSERROR is the name of the event that gets triggered in code as will be demonstrated shortly.
The Event Email Recipients contains the rest of the Event configuration information. When adding a new recipient, you decide on who to send the notification to, what event, and why. For SYSERROR, for example, you could select "System Error." from the dropdown box for Event code, and 3 for the user ID (Usually Administrator).
Now the last part of the Event Email Recipient is a little bit different. Each Event has a status associated with it: Success or Failure. For example, if a user successfully downloaded a file, the download controller could trigger a DOWNLOAD event with a success status, whereas if the connection died for some reason, the download controller could trigger a DOWNLOAD event with failure status. Each of these statuses is configurable with who gets what notifications. For example, you could send a DOWNLOAD success event to an automated mail archival system for statistical reference, while you would want to send failure events to the administrators so they can see if there are an unusual number of failures occurring.
You can trigger an event from code with very little code:
import com.jcorporate.expresso.core.misc.EventHandler; EventHandler.Event("default", "SYSERROR","Successful Test Message", true);
EventHandler.Event is an asynchronous call. If you watch the runtime logs, you will see the mail going out a few seconds after the call. The parameters for the call are:
The data context (or db name) in this case default
The name of the event to fire as defined in the Event Definitions Table
The message to dispatch when the event is fired. This will be the text of the email message that the Event dispatches.
The final parameter is set to true if this is a 'success' message, and false if it is a 'failure' message.
The framework has email integration as part of its base feature set. Instead of the application programmer having to develop his/her own email notification system, there is a base level email integration built right in. From that base email class, there are several different classes that make use of the email notification class.
Some facilities provided for email include:
Event notifications: Discussed above, Expresso's event notification mechanism uses email by default to inform users when specific events, including system errors, occur.
User notifications: The ability to send email to particular users.
Login Verification: An optional portion of the registration process allows users to be emailed in order to verify their email address before authorizing their account for login, assuring your user data is up-to-date.
Attachments: An easy mechanism is provided to attach one or more files to any email being sent to a user, the contents of which can be created by your custom application.
The Job class, a class to provide cron or batch like functions, has a mechanism for emailing certain parties that can be customized to alert the certain recipients when the job has started, when the job has finished, and/or when the job encounters in error.
There are times that an email needs to be sent to particular users and to those users explicitly. The EventHandler and UserInfo objects can work together to send an email to the user. An example of this is in com.jcorporate.eforum.dbobj.ForumMessage where it sends an email to everyone subscribed to get email in a forum.
EventHandler.notify(dataContext, // the database context tSubscribe.getFieldInt(ThreadSubscribe.FLD_UID), // the user id to send email to msgSubject, // the email subject message); // the email message
The User, DefaultUserInfo, and UserLDAP classes, which handles the registration and manipulation of users within the Expresso framework, has an email conduit already setup. This email conduit allows verification of the user, deterring spammers from registering, and keeping the database up-to-date.
The following persons have contributed their time to this chapter:
David Lloyd (JGroup Expert)
Mike Rimov
Mike Traum (JGroup Expert)
Tino Dai. | http://www.jcorporate.com/expresso/doc/edg/edg_event.html | crawl-001 | refinedweb | 1,225 | 51.28 |
If authentication model like Gmail.
To solve that issue we need a bit if coding so you will have the functionality to add an Email Server you like with User Credentials in runtime, thankfully SSIS have the Script Task which we can use for a lot of reasons, adding more flexibility to the already powerful SSIS tool. With script task you can extend in developing using VB.Net or C#.Net
So this will be our solution developing our own Send Email Function with option for User Credentials.
Now lets start.
You only need 2 main things 1 is the variables and another one is the script.
First – To declare variables in SSIS. Here are the minimum variables you might need for your custom send email function.
Second – After creating those variables you then need to create your script, open the script task editor by double clicking on the icon you may already have on the designer
and it will open a script task editor window now click edit script, this will fire up the Visual Studio Scripting Task. So if you are a .Net developer this will be familiar.
Now to access your variables inside the Script all you have to do 2 steps, make it visible to your script which I will explain later and referencing to the script like this:
Dts.Variables["YourVariableName"].Value.ToString()
Now all you have to do is develop your Sending Email functionality and here is how I have done mine:
public void Main() { string sSubject = "Test Subject";["sEmailServer"].Value.ToString(); string sEmailPort = Dts.Variables["sEmailPort"].Value.ToString(); string sEmailUser = Dts.Variables["sEmailUser"].Value.ToString(); string sEmailPassword = Dts.Variables["sEmailPassword"].Value.ToString(); string sEmailSendTo = Dts.Variables["sEmailSendTo"].Value.ToString(); string sEmailSendCC = Dts.Variables["sEmailSendCC"].Value.ToString(); string sEmailSendFrom = Dts.Variables["sEmailSendFrom"].Value.ToString(); string sEmailSendFromName = Dts.Variables["sEmailSendFromName"], ";"); string[] sEmailCC = Regex.Split(sEmailSendCC, ";");]); } } }; } //You can enable this for Attachements. SingleFile is a string variable for the file path. //foreach (string SingleFile in myFiles) //{ // Attachment myAttachment = new Attachment(SingleFile); // message.Attachments.Add(myAttachment); //} message.Subject = sSubject; message.IsBodyHtml = true; message.Body = sMessage; smtpClient.Send(message); return true; } catch (Exception ex) { return false; } }
Now on the top you need to add the following references
using System.Text.RegularExpressions; using System.Net.Mail;
And that’s your code. That simple. Now all you have to do is making the variables visible to your script. Once you exit the Script Editor you go back to this window and tick the variables you want to use.
Wonderful Article. Thanks a lot friend.
Thank you.
I tried this but its showing error as 0x8 at Script Task: The script returned a failure result.Help me to solve this | http://www.macaalay.com/2010/06/02/send-email-from-ssis-with-option-to-indicate-email-user-and-password/?replytocom=102 | CC-MAIN-2019-18 | refinedweb | 449 | 51.85 |
I2C and C++
- larry biscuits last edited by larry biscuits
Hey all,
I have been toying with the I2C driver in C++, however I am running into a problem. I got the header files and .so files on the Omega2+ (some were already loaded) and finally got the make to run correctly. However, the debugger is throwing an error with a method such as i2c_readByte. I will post the actuall error message tomorrow morning (not by the Omega at the moment). It almost seems like there needs to be an I2C object declared similar to the python version. However, I can't find the constructor in any of the source files. Is there one? How would I call a method without having on object defined?
I haven't slept well in the past few days, so I might be completely overlooking something.
Thanks,
N
Edit: The error messages
OnionBME280.cpp:(.text+0x3c): undefined reference to `i2c_readByte'
Edit: The very simple test code
#include <stdio.h> #include <stdlib.h> #include <onion-i2c.h> int main() { int status, rdByte; status = i2c_readByte(0, 0x76, 0x88, &rdByte); // Print Results printf("The result is: %i", status); return 0; }
Are you compiling on the Omega2 or cross compiling? Have you used the
-lonioni2cflag?
Agains what binary file are you linking? I've found that when I try to link against the
libonioni2c.sothat is provided in the package, linking fails. That's why I recompiled the libraries and then linking works.
See e.g. and.
I2C definetly works with C++, because I've written (see
SC18IS602B.cpp) and that worked.
- larry biscuits last edited by
@Maximilian-Gerhardt I am compiling on the Omega2. I do have the flag in the make file. I am using the binary from that was pre-compiled; though I am not sure if I installed it from the GitHub Repo or it it already existing on the Omega2 out of the box.
My make file:
# main compiler CC = g++ TARGET1 := OnionBME280 LIBS := "-loniondebug -lonioni2c" all: $(TARGET1) $(TARGET1): @echo "Compiling C program" $(CC) $(CFLAGS) $(TARGET1).cpp -o $(TARGET1) $(LDFLAGS) $(LIB) clean: @rm -rf $(TARGET1) $(TARGET2)
I will take a stab at recompiling the dynamic library, though I am not a g++ guru (which may be very obvious from my makefile) and I may have issue compiling it.
Thank you for the example, I will definitely take a look. I learn in odd manners and an effective way to use an existing example and toy around with it.
I see Kit Bishop posts here and has a library on GitHub. Any benefit to using that over Onion's?
Thank you for your input!
@larry-biscuits I'm only ever cross-compiling my programs for the Omega2. Your issue may well be that you either can't link against the I2C library or GCC can't find it.
For the latter, make sure you
opkg update && opkg install libonioni2c. You can give GCC a path to the folder where the
libonion2c.sois using the
-Lflag. The path should be
/usr/lib/..or something.
When you want to try cross-compiling, you should use a Xubuntu 17 virtual machine (Ubuntu 18 needs a small patch to work) and compile LEDE and the toolchain as instructed in. Takes several hours. Or use their docker container.
After you have a working
mipsel-openwrt-linux-g++you can cross-compile or just use the one from my omega2-libs folder above. With that, you can cross-compile your
OnionBME280.cppand link against the
libonioni2c.so.
Or, even easier, you can try downloading the
libonioni2c.sofrom my repo above and try to compile and link it on the Omega2. Just make sure you use
-L .to reference the current directory as a library path so that it wil maybe try to use the local
.sofile instead of the system's installed one..
- larry biscuits last edited by
Definitely got it up and running, though I got some really weird data out of a BME280 Temp, Press, Humidity sensor. It appeared one of the registers was not being read correctly. I am thinking there might be an issue with the I2C library? I compiled the same code on a Pi and it worked without problem. On the Omega, the data seemed fine until the temperature rose above a certain value (a few degrees C above room temp, heat from my finger). Once it got above this value, it seemed the read on one of the registers turns negative which doesn't seem correct.
I recorded the register data from the Python version of the BME280 code run on the Omega and compared against the C++ code on the Omega. I couldn't find anything in the code; I even stepped through all of the raw data. It appeared that the difference/error between the Python and the C++ code was in the raw data from the I2C read function.
I am cranking on something else at the moment and I will have to find time to crack this nut. If anyone is interested, I can post the code to see if there may be something wrong with the I2C C++ library. I have not been able to find a whole of example code, etc. for the Omega's using C++. The overwhelming majority of code out there is in Python. I am chasing down the C++ path since I am trying to build a fairly complicated program for performing analysis and need the interop so I can have the ability to blast code to an ARM, or other processor architecture.
Again, total disclosure, I could be the one messing something up. I do a lot of dumb things.
@Maximilian-Gerhardt thanks again for your guidance. I do believe the hiccup I initially hit was due to the .so library file. Once recompiled, it seemed fine.
.
@larry-biscuits exactly how did you get it working? I have the exact same problem and have tried all suggestions in this post and nothing has worked.
@Brian-Franklin What exact code are you running and what exact problem do you have?
// This is my main.cpp
#include <iostream>
#include <onion-i2c.h>
// confirmed /usr/include/onion-i2c.h exists
// confirmed /usr/lib/liboniondebug.so exists
// confirmed /usr/lib/libonioni2c.so exists
int main(int argc, char* argv[])
{
std::cout << "\nTest I2C Start\n" ; int status, val; status = i2c_readByte(0, 38, 0, &val); std::cout << val; std::cout << "\nTest I2C End\n\n" ; return 0;
}
during the linking
g++ main.o -o minitesti2c -loniondebug -lonioni2c
main.o: In function 'main':
/sources/minitesti2c/main.cpp: undefined reference to 'i2c_readByte'
/sources/minitesti2c/main.cpp: undefined reference to 'i2c_readByte'
collect2: error: ld returned 1 exit status
From the above suggestions I changed the test function to i2c_write
i2c_write(0, 56, 0, 112);
and the errors that come back are
/sources/minitesti2c/main.cpp: undefined reference to 'i2c_write'
/sources/minitesti2c/main.cpp: undefined reference to 'i2c_write'
so then I copied the files /usr/lib/liboniondebug.so and /usr/lib/libonioni2c.so to the local directory and changed the link to
g++ -L/sources/minitesti2c/ main.o -o minitesti2c -loniondebug -lonioni2c
same error(s)
so then I copied the libraries reference above from
put them in the /sources/minitest2c/ directory
same errors(s)
I can confirm that my i2c chip is wired correctly
i2cdetect -y 0 shows device at 0x38
i2cset -y 0 0x38 0x70 works!
i2cget -y 0 0x38 works. return 0x70!
I don't know what to try next.
This post is deleted!
@Brian-Franklin said in I2C and C++:
so then I copied the libraries reference above from
put them in the /sources/minitest2c/ directory
same errors(s)
You should temporarily rename the
.solibraries
// confirmed /usr/lib/liboniondebug.so exists
// confirmed /usr/lib/libonioni2c.so exists
to something else so that the linker doesn't attempt to link against these. Then add
-L .to the compiler options to add the current directory (
.) to the linker search path.
@Maximilian-Gerhardt Thank You.
I have been fighting against an error where it looked like the linker was not finding my the shared libonioni2c.so. Your suggestion about first renaming the current files /usr/lib/libonioni2c.so to /usr/lib/libonioni2c.so.XX and /usr/lib/liboniondebug.so to /usr/lib/liboniondebug.so.XX was a good suggestion.
My error changed to libonioni2c.so not found. So it shows me the linker was finding the correct shared object but there was something wrong with that libonioni2c.so share object. then I copied the shared objecs from github and put them in /usr/lib and everything worked!!!
2 weeks I have wasted.
Now I don't know what is in those shared objects or what is different but at least I can continue building my project.
From my 2 weeks of trying everything I have concluded that the shared object libraries provided in the standard distribution for the 2+ libonioni2c.so and/or liboniondebug.so are defective. | https://community.onion.io/topic/3178/i2c-and-c/10?lang=en-GB | CC-MAIN-2021-49 | refinedweb | 1,496 | 67.86 |
error connection rosserial via bluetooth arduino notebook
Can not run rosserial via bluetooth.
Arduino Uno
Blutooth module HC-06
Notebook with bluetooth Ubuntu 12.04 Ros Hydro
Arduino sketch:
#include <ros.h> #include <std_msgs/String.h> ros::NodeHandle nh; std_msgs::String str_msg; ros::Publisher chatter("chatter", &str_msg); char hello[13] = "hello world!"; void setup() { nh.getHardware()->setBaud(9600); nh.initNode(); nh.advertise(chatter); } void loop() { str_msg.data = hello; chatter.publish( &str_msg ); nh.spinOnce(); delay(1000); }
In terminal:
sudo rfcomm connect 0 98:D3:31:20:03:19 1
Connection is established, the red LED on the Bluetooth lit.
In new terminal:
$ rosrun rosserial_python serial_node.py _port:=/dev/rfcomm0 [INFO] [WallTime: 1401040615.342558] ROS Serial Python Node [INFO] [WallTime: 1401040615.353809] Connecting to /dev/rfcomm0 at 9600 baud [ERROR] [WallTime: 1401040632.468633] Unable to sync with device; possible link problem or link software version mismatch such as hydro rosserial_python with groovy Arduino
How to fix this error? If connecting by the usb cable, everything works.
Does serial over bluetooth work when you're not using a rosserial sketch? Is the baud rate on your bluetooth module set correctly?
Yes I used to work with this Bluetooth module via serial data is transferred. Baud rate correct.
Have you solve this? I'm having the same problem now. its annoying!
Actually I've solve my problem. It truns out that my bluetooth chip is a china made cheap one and not a real HC-06. And there is something like only a single post in some unkown forum that provides the datasheet. Generally speaking, it's the fault of baud rate (not usable if exceed certain rate). | https://answers.ros.org/question/169366/error-connection-rosserial-via-bluetooth-arduino-notebook/ | CC-MAIN-2021-39 | refinedweb | 274 | 62.24 |
- Introduction
- Roundtrip and Postback
- ASP.NET Intrinsic Objects
- ASP.NET Application
- State Management
- Navigation Between Pages
- Chapter Summary
- Apply Your Knowledge
ASP.NET Intrinsic Objects
Use and edit intrinsic objects. Intrinsic objects include response, request, session, server, and application.
Retrieve values from the properties of intrinsic objects.
Set values on the properties of intrinsic objects.
Use intrinsic objects to perform operations.
ASP.NET provides intrinsic objects to enable low-level access to the Web application framework. With the help of these intrinsic objects, you can work directly with the underlying HTTP streams, server, session, and application objects. The intrinsic objects can be accessed in a Web form through the properties of the Page class. Table 3.1 lists the important intrinsic objects and the properties of the Page class to which they are mapped.
Table 3.1 Intrinsic Objects and Their Mappings to the Page Class Properties
I'll discuss the HttpRequest, HttpResponse, and HttpServerUtility objects in the following section. The other two objects, HttpApplicationState and HttpSessionState, are discussed later in this chapter in the section "State Management."
The HttpRequest Object
The HttpRequest object . represents the incoming request from the client to the Web server. The request from the client can come in two waysGET or POST. GET attaches the data with the URL, whereas POST embeds the data within the HTTP request body.
The requested page and its details are encapsulated in an HttpRequest object. The HttpRequest intrinsic object can be accessed by the Request property of the Page class. Tables 3.2 and 3.3 list the properties and methods of the HttpRequest class, respectively. Because the HttpRequest class provides information about the request sent by the client, all the properties are read-only except the Filter property.
Table 3.2 Properties of the HttpRequest Class
Table 3.3 Methods of the HttpRequest Class
CurrentExecutionFilePath
This property of the HttpRequest class returns the file path of the currently executing page. When using the server-side redirection methods such as Server.Execute() and Server.Transfer(), the FilePath property returns the path to the original page, whereas CurrentExecutionFilePath returns the path to the currently executing page.
Step by Step 3.3 displays some of the path-related properties of the HttpRequest object and calls the MapPath() method to get the physical file system path for a specified virtual path. It also displays the header information sent by the client to the server when the StepByStep3_3.aspx page is requested from the server.
STEP BY STEP
3.3 Using the HttpRequest Intrinsic Object
Add a new Web form to the project. Name the Web form StepByStep3_3.aspx. Change the pageLayout property of StepByStep3_3.aspx as the start page in the project.
Run the project. You should see the Web form displaying the properties for the current request, as shown in Figure 3.3.
using System.Text;
private void Page_Load( object sender, System.EventArgs e) { StringBuilder sbInfo = new StringBuilder(); // Display some of the path related properties // of the HttpRequest object sbInfo.Append("The Url of the ASPX page: " + Request.Url + "<br>"); sbInfo.Append("The Virtual File Path: " + Request.FilePath + "<br>"); sbInfo.Append("The Physical File Path: " + Request.PhysicalPath + "<br>"); sbInfo.Append("The Application Path: " + Request.ApplicationPath + "<br>"); sbInfo.Append("The Physical Application Path: " + Request.PhysicalApplicationPath + "<br>"); // Display the request header sbInfo.Append("Request Header:"); sbInfo.Append("<br>"); NameValueCollection nvcHeaders = Request.Headers; String[] astrKeys = nvcHeaders.AllKeys; // Iterate through all header keys // and display their values foreach (String strKey in astrKeys) { sbInfo.Append(strKey + ": " + nvcHeaders[strKey].ToString()); sbInfo.Append("<br>"); } // Call MapPath() method to find the physical path // of StepByStep3_2.aspx sbInfo.Append( "The physical path of StepByStep3_2.aspx: "); sbInfo.Append( Request.MapPath("StepByStep3_2.aspx")); lblInfo.Text = sbInfo.ToString(); }
Figure
3.3 The Request property of the Page class returns an
HttpRequest object that gives access to the HTTP values sent by a client
during a Web request.
Some properties of the HttpRequest objectsuch as Form, QueryString, Headers, and so onreturn a NameValueCollection containing a collection of key-value pairs of their contents. Step by Step 3.3 shows how to iterate through this collection by iterating through the keys of the Headers collection and displaying the key and value of each header sent by the client.
The HttpResponse Object
The HttpResponse object represents the response sent back to the client from the Web server. It contains properties and methods that provide direct access to the response stream and allow you to set its behavior and operations. The Response property of the Page class provides access to the HttpResponse object. Tables 3.4 and 3.5 list the properties and methods of the HttpResponse class, respectively.
Table 3.4 Properties of the HttpResponse Class
Caching Policy
The properties CacheControl, Expires, and ExpiresAbsolute are provided for backward compatibility. You should instead use the HttpCachePolicy object's methods to set the caching policy. This object is returned by the Cache property. Setting caching policy is discussed in Chapter 15, "Configuring a Web Application."
Table 3.5 Methods of the HttpResponse Class
Step by Step 3.4 shows the use of HttpResponse object methods and properties to create a response that displays the File Download dialog box and allows the user to download a text file from the Web server to the client's machine.
STEP BY STEP
3.4 Using the HttpResponse Intrinsic Object
Add a new Web form to the project. Name the Web form StepByStep3_4.aspx. Change the pageLayout property of the DOCUMENT element to FlowLayout.
Add a text file to the project that contains some data that needs to be downloaded. Name it Summary.txt.
Add a LinkButton control (lbtnDownload) to the Web form with its Text property set to Download Summary.txt.
Double-click the lbtnDownload control and add the following code to the Click event handler:
Set StepByStep3_4.aspx as the start page in the project.
Run the project. Click the link button. You should see a File Download dialog box, as shown in Figure 3.4. After the download, open the file to verify that the file has been successfully downloaded.
private void lbtnDownload_Click(object sender, System.EventArgs e) { // Append a Header to the response to force a // Download of Summary.txt as an attachment Response.AppendHeader("Content-Disposition", "Attachment;FileName=" + "Summary.txt"); // Set the Content type to text/plain // As the download file is a TXT file Response.ContentType = "text/plain"; // Write the file to the Response Response.WriteFile("Summary.txt"); // Stop further execution of the page Response.End(); }
Figure
3.4 The File Download dialog box provides the interface to download a file
from the Web server.
The HttpServerUtility Object
The HttpServerUtility object contains utility methods and properties to work with the Web server. It contains methods to enable HTML/URL encoding and decoding, execute or transfer to an ASPX page, create COM components, and so on. The Server property of the Page class provides access to the HttpServerUtility object. Tables 3.6 and 3.7 list the properties and methods of the HttpServerUtility class, respectively.
Table 3.6 Properties of the HttpServerUtility Class
Table 3.7 Methods of the HttpServerUtility Class
STEP BY STEP
3.5 Using the HttpServerUtility Intrinsic Object
Add a new Web form to the project. Name the Web form StepByStep3_5.aspx. Change the pageLayout property of DOCUMENT element to FlowLayout.
Add the following code to the Page_Load() event handler:
Set StepByStep3_5.aspx as the Start page in the project.
Run the project. You should see that the browser does not parse the HTML <title> elements written to the response, as shown in Figure 3.5, because of the use of the HtmlEncode() method of the HttpServerUtility class.
private void Page_Load( object sender, System.EventArgs e) { // Write to the response // using the Server.HtmlEncode() method // so that the browser does not parse // the text into HTML elements Response.Write(Server.HtmlEncode( "To include a title in the title bar, " + "enclose your chosen title between the " + "pairs of the <title>...</title> element " + "in the HTML <head> element. ")); Response.Write(Server.HtmlEncode( "For example, <title> " + "Using the HtmlEncode() method </title>.")); }
Figure
3.5 The HtmlEncode() method of the HttpServerUtility object.
HTML encodes a string to be displayed in the browser.
I will discuss various other methods of the HttpServerUtility object throughout the course of this book.
Guided Practice Exercise 3.1
Several Web sites collect statistics about the browsers, operating system, and other settings on their users' computers. This data helps the Web sites customize their contents to target a large number of users. A common requirement for Web applications is to find out the browser versions of their users and then serve them files that are optimized for that particular browser version.
In this exercise, you are required to create a Web form that displays the following information about the client browser: the browser name, version, platform of the client's computer, the CLR version installed, JavaScript support, ECMA version, MS DOM version, and the W3C XML DOM version supported by the browser.
You can use the Request.Browser property to get access to the HttpBrowserCapabilities object that provides various properties that contain information on the capabilities of the client's browser.
How would you create a Web form that allows the Web page to get information about the browser?
You should try working through this problem on your own first. If you are stuck, or if you'd like to see one possible solution, follow these steps:
Open the project 315C03. Add a new Web form GuidedPracticeExercise3_1.aspx to the project. Change the pageLayout property GuidedPracticeExercise3_1.aspx as the start page in the project.
Run the project. You should see the Web form displaying the properties of the browser as shown in Figure 3.6.
using System.Text;
private void Page_Load( object sender, System.EventArgs e) { StringBuilder sbText = new StringBuilder(); // Get the reference to the // HttpBrowserCapabilities object HttpBrowserCapabilities browser = Request.Browser; // Display the properties of the // HttpBrowserCapabilities Class sbText.AppendFormat("Browser : " + browser.Browser + "<br>"); sbText.AppendFormat("Browser Version: " + browser.Version + "<br>"); sbText.AppendFormat("Client's Platform: " + browser.Platform + "<br>"); sbText.AppendFormat(".NET CLR Version: " + browser.ClrVersion + "<br>"); sbText.AppendFormat("ECMA Script Version: " + browser.EcmaScriptVersion + "<br>"); sbText.AppendFormat("JavaScript Support: " + browser.JavaScript + "<br>"); sbText.AppendFormat( "Microsoft HTML Document Object Model Version: " + browser.MSDomVersion + "<br>"); sbText.AppendFormat( "World Wide Web (W3C) XML Document " + " Object Model Version: " + browser.W3CDomVersion + "<br>"); lblInfo.Text=sbText.ToString(); }
Figure
3.6 The HttpBrowserCapabilities object provides access to the capabilities
of the client's browser.
If you have difficulty following this exercise, review the section "The HttpRequest Object" earlier in this chapter and perform Step by Step 3.3. Also, look at the .NET Framework documentation for the System.Web.HttpBrowserCapabilities class. After doing this review, try this exercise again.
REVIEW BREAK
Web applications are disconnected in nature. Values of page variables and controls are not preserved across the page requests.
You can use the Page.IsPostBack property to determine whether a page is being loaded for the first time or in response to a postback operation.
ASP.NET has a feature called smart navigation that can greatly enhance the user experience of a Web page for the users of Internet Explorer 5.0 or higher browsers.
ASP.NET provides intrinsic objects to enable low-level access to the Web application framework. With the help of these intrinsic objects, you can work directly with the underlying HTTP request, HTTP response, server, session, and application objects. | http://www.informit.com/articles/article.aspx?p=30270&seqNum=3 | CC-MAIN-2017-51 | refinedweb | 1,903 | 52.46 |
vars editOne annoying thing is the variable command - you can't just give it a list of variables you want the code to access in a namespace, you have to have multiple variable statements, one for each, as the semantics don't take a list per se but must alternate with an initializer. With:
proc vars { args } { foreach var $args { uplevel "variable $var" } }You can say
vars a b cand that is the equivalent of
variable a variable b variable cA minor convenience but makes for more concise code.
access editNot infrequently, I find myself wanting to execute something in a namespace but to access vars in a surrounding proc context. Using {} defeats just calling $whatever in the namespace since the proc variables are not visible. You either have to use " and " - thereby putting one in quoting hell - or you have to have a prefix and body where the prefix is done with quotes and then appended to the body, to pass in vars. Here's a nicer way to do that:
proc access { args } { foreach var $args { set t [split $var >] if {[llength $t] == 2} { set left [lindex $t 0] set right [lindex $t 1] } else { set left $var set right $var } set temp "[uplevel uplevel set $left]" regsub -all {"} $temp {\"} temp set cmd "set $right \"$temp\"" uplevel $cmd } }with this you can do:
proc foobar { this that args } { namespace eval foo { access args this that set arglist $args puts "I was passed $this and $that" } }and it works as expected. Access also allows you to rename things.
proc foobar { this that args } { namespace eval foo { access args>arglist this>mythis that>mythat puts "I was passed $arglist, $mythis and $mythat" } }
SEH -- Been messing around a lot lately with juggling levels and access, so I thought I'd try my hand:
proc access {args} { set nspace [uplevel namespace current] foreach arg $args { lassign [split $arg >] left right set $left [uplevel 2 set $left] set ${nspace}::[lindex [concat $left $right] end] [set $left] } }
alink editKPV -- When debugging via a console, I use the following function to create linked variable in the global namespace to a variable in a namespace. For example, typing alink ::foo::bar will create the variable bar which is the same as ::foo::bar. This allows me to paste in code from a procedure in a namespace into the console and have it access the correct variables.
proc alink {var} { uplevel \#0 upvar \#0 $var [lindex [split $var ":"] end] } | http://wiki.tcl.tk/38143 | CC-MAIN-2018-05 | refinedweb | 412 | 51.35 |
Introduction to Square Root in C++
Today here, let’s learn about one of the well-known mathematical calculations, Square Root. And we are going to use C++ programming in finding the square root of a given number. As already known, C++ is an extension of C programming language with the concept of OOPS being introduced; let’s begin in making our own square root function in C++.
Logic of Square Root in C ++
For having our square root function, we need to understand the proper logic of how actually this square root is being calculated.
There are actually many ways to understand the logic too, but we would first start from the basic level.
- We know that the square of a number is a power of 2. In the same way square root, a number would be the power of ½. For this, we can use a pow function under the h package library.
Let’s see how we can represent this in C++.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int num;
float result;
cout<<"Enter number: ";
cin >> num;
result = pow(num,0.5);
cout << "Square root of given number is " << result;
return 0;
}
Output:
- In another method, we can have logic in a reverse way. Like, the square of the final result obtained should be the number which we chose.
Let’s see how we can represent this in C++.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int num;
float result =0 ;
double sq;
cout<<"Enter number: ";
cin >> num;
sq = result*result;
while (sq < num)
{
result = result + 1;
sq = result*result;
if(num == sq)
{
cout<< result;
break;
}
}
cout<< " square root lies between "<< result-1 << " and " << result;
return 0;
}
I will not consider the above one perfect, as the output comes properly, only if it is a perfect square. This is because; we are increasing the result value by an integer 1 directly. So, if it is not a perfect square we can show the output as below.
We can even write the same logic in such a way that it calculates the exact square root with decimals too. Find it below.
Finding Root
So, obviously there are many ways in finding the square root of a number. The above two methods can also be used in obtaining the root. Now, lets’ see how we can write the square root logic code more precisely and logically.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float num,i;
cout<<"Enter number: ";
cin >> num;
for(i=0.01;i*i<=num;i=i+0.01);
if(num==0)
{
cout<<"Square root of given number is 0";
}
else if(num==1)
{
cout<<"Square root of given number is 1";
}
else if( num < 0 )
{
cout<<"Enter a positive number to find square root";
}
else
{
std::cout << std::fixed;
std::cout << std::setprecision(3);
cout<<"Square root of given number is " <<i;
}
}
Yes, code seems short and simple. Here goes the logic:
- We are declaring our two values, a number which is taken as input and one is our result.
- Asking the user to input a number for which we need to write the square root.
- In for loop, we are going to initiate i value to 0.01 as we need our results to be in decimal points.
- Then, we are going to execute that for a loop until the square of i value would be less than the user inputted value.
- And we are going to increase i value with 0.01 only, as we need decimal points and we have to increase i value proportionally as per the declaration.
- If observed, we have kept a semicolon at the end of for loop, which makes the loop run without executing any inner statements until the condition is satisfied.
- Now, we can make if a condition for the inputted value is zero, and then return 0 instantly.
- In the same way give the output as 1, if the inputted value is one.
- In the next else if condition we gave a condition of any negative value that is given as user input.
- On the else condition we are going to output i value.
- Here, we have used a set precision method and fixed the number of decimal places till 3 digits, so that the output we obtain will be uniformly obtained.
Note: The declaration of iomanip package and including in the program is mandatory to use this set precision method.
The output is attached below:
This way we can easily calculate the square root of a number perfectly. As an exercise, can you try finding the square root of a number through any other way?
Conclusion
So, in this way, we can have our own square root function in C++. We can even find square root using Euclidian, Bayesian and even through sorting techniques. And as everyone in anyways is aware of, we can even directly calculate the square root using sqrt function.
Recommended Articles
This is a guide to the Square Root in C ++. Here we discuss the introduction and logic of square root in C ++ along with root finding. You may also look at the following articles to learn more – | https://www.educba.com/square-root-in-c-plus-plus/?source=leftnav | CC-MAIN-2021-39 | refinedweb | 867 | 70.63 |
This guide presents Qt Script for Applications, a tool for making C++ applications scriptable, using Qt Script, an interpreted scripting language. Some basic knowledge of scripting is needed to get the most out of this guide.
This guide provides an introduction to Qt Script for Applications, and its tools.
Here is a brief overview of the chapters:
This chapter gives a brief overview of the Qt Script for Applications toolkit.
Qt Script for Applications is a cross-platform toolkit for making C++ applications scriptable using an interpreted scripting language, Qt Script. The Qt Script for Applications toolkit is made up of the following components:
The tutorial chapters that follow show you how to make an application scriptable and how to write a simple script for the application.
This chapter demonstrates how to write a C++ Qt application which integrates Qt Script for Applications to make the application extensible and customizable through scripting. The goal is to write a simple spreadsheet application which can be extended by the user. To do this, the spreadsheet will provide interfaces to its sheets. The script code can access the sheets, so the user can write Qt Script code that presents dialogs to accept user preferences, and which can access and manipulate the spreadsheet data. The code for this example can be found in examples/spreadsheet.
Additional examples that demonstrate other Qt Script for Applications usage are also included in the examples directory.
To make a Qt/C++ application scriptable, you need the libqsa library that is included in the Qt Script for Applications package. To use libqsa and get other QSA specific build options, add the following line to your .pro file:
CONFIG += qsa
The libqsa library provides the QSInterpreter class. A default instance of QSInterpreter is available, for convenience, by using the function QSInterpreter::defaultInterpreter().
To make application functionality available to scripts, the application must provide QObjects or QObject subclasses which implement the application's functionality. By passing an object to the scripting engine (using QSInterpreter::addTransientObject() or QSProject::addObject()), this object and all its signals, slots, properties, and child objects are made available to scripts. Because Qt Script for Applications uses Qt's meta object system, there is no need to implement any additional wrappers or bindings.
If no parent object of the object that is passed into the interpreter has been made available yet, the new object is added as a toplevel object to the scripting engine. This means that it is available through Application.object_name to the script writer.
If a parent object of the object has been previously added via a addObject(), the new object is not added as a toplevel object, and is available through Application.parent1.parent2.object_name (given that parent1 has been added previously via addObject()). The reason for doing that is because the object can be used as a namespace or context later, and code can be added in the context of that object.
In most cases we do not pass QObjects which are directly used in the C++ application to the scripting engine because this would expose too many slots. Instead we implement interface QObjects which offer the signals, slots, and properties that we want to offer to the scripts and which will be simply implemented as forward function calls.
In our spreadsheet example we will add interface objects for the sheets. The interface objects implement slots and properties to query and set selection ranges, retrieve and set cell data, etc.
In other cases it might be possible to use an application's existing QObjects as application objects in the scripting language. An example of this approach is shown in the examples/textedit example, which is a slightly modified, scriptable, version of the Qt textedit example.
To read about how to design and implement application objects, see the How to Design and Implement Application Objects chapter.
Qt Script for Applications always works with one current scripting project that contains all the forms and files in which all the functions and classes are implemented.
An instance of QSInterpreter can be used on its own, but to get full access to the functionality of Qt Script for Applications, use QSProject. To use a stand alone QSInterpreter use QSInterpreter::defaultInterpreter() or QSInterpreter::QSInterpreter(). To create an interpreter that runs with a project, create the project using QSProject::QSProject() and access its interpreter using QSProject::interpreter().
If you work with a project, you can either choose to use functionality in Qt Script for Applications to take care of everything (saving, loading, etc.) or you can decide to take care of most functionality yourself, giving you more flexibility.
If you choose to have Qt Script for Applications take care of everything for you, Qt Script for Applications then loads and saves the whole project from one file or one data block which you can specify. In this case all project data is compressed in the data block or file and extracted temporarily when loading. If you choose to take care of the functionality yourself, then open an empty project and use QSProject's API to add scripts manually and then retrieve them and save or store them however you'd like.
If you choose the first option, do the following:
Create a new QSProject and load in a scripting project using QSProject::load().
Loading a project can be called in one of two ways:
If you choose the second option, simply create a new QSProject and use its functions to add scripts and save the project at your convenience.
Of course it is possible to use a combination of both approaches, e.g. using the first approach, but later adding script code programmatically.
Note that when saving a project, the functions in QSInterpreter will add transient content to the interpreter, while the functions in the project will add persistent content to the interpreter. This means that content that is added to the project can be saved and will remain even if the interpreter state is cleared, while the content added using the QSInterpreter will not be saved and will be cleared along with the interpreter state.
In the spreadsheet example we use one scripting project for the whole application, and we let Qt Script for Applications save this to disk as an individual file that is opened on startup. The following code is used to initialize QSProject (adding application objects and opening the project):
In some cases it might be sufficient to offer a basic editor widget which allows the user to write code. For example, you might want to embed the code editor directly into your application's user interface, and you don't want to open another toplevel window (such as QSA Workbench) for the user. In other cases, you want the users to be able to add and remove scripts, to have intelligent completion and hints in the editor, and to use GUI controls in the script. For these cases, including QSA Workbench is the best option.
There are two ways for the end user to use QSA Workbench.
There are different ways to provide the scripting functionality to the end user depending on the type of application. For a typical end-user application you can offer one or both of the approaches to scripting mentioned above. For example you can provide a menu option and a toolbar button to launch QSA Workbench, and an editable combobox which lists all the global functions. If the user enters a function name that doesn't exist they are given the opportunity to create a new function of that name. If the user chooses an existing function, QSA Workbench is launched with the cursor at that function, ready for editing. A 'Run' toolbar button can be placed beside the combobox, so that the user can choose a function and click 'Run' to execute it.
Other approaches include enabling a user to: define functions to validate data of data entry forms, to customize the functionality of an editor, to customize the user interface of a complex 3D graphics application or to provide scripting modules for an image processing application.
The usage of application scripting can greatly vary depending on the type of application. The spreadsheet application described in this chapter is an example of a typical end-user application. This example will make you familiar with most of the important scripting concepts. Following this example will teach you how to use Qt Script for Applications to make your applications scriptable, even if the way your end users will use application scripting might be very different from what we describe here.
We define a macro as a stand-alone global function. Create a QSScript using QSProject::createScript() to create a script in global context. Call QSScript::addFunction() to add a new macro to the script. You can then open the editor and edit the newly created function.
In the spreadsheet example the following slot is called to open QSA Workbench:
In our spreadsheet example we want to enable the user to add macros as actions to the toolbar and menu which they can associate with a function that will be called when they activate the action. To add macros, we provide a dialog through which the user can either choose an existing global function to edit, or add a new function (as described in Macros). If the user adds a new function, a new action and icon are created along with a menu option and toolbar button.
The following code is used in the macro dialog to initialize the combo box which lets the user choose a script function:
When the user clicks OK in this dialog, the following slot is executed. If the function the user specified doesn't exist, the user is asked if this function should be added to the project, in which case, addFunction() is called:
At the end of the function, the newScript() signal which is connected to the addScript() slot in the spreadsheet is emitted. The addScript() function creates an action for the macro and adds a menu option and toolbar button for the macro. In addition, the action's triggered() signal is connected to runScript(). To find out which function this macro (action) will call, the action and its associated function are inserted into the scripts map:
It would be tedious for users if they had to launch QSA Workbench and click Run every time they want to execute a script. For this reason it is normal practice to provide a means by which the user can execute a function from within the application itself. How this is acheived depends to some extent on the application and on the functionality of the script.
One approach to providing the user with access to their script functions is to provide a list, e.g. a popup list, from which they can pick the function they wish to execute. (This approach is taken in the textedit example.) A list of existing global functions in the current project is obtained by calling QSInterpreter::functions(). To call a script function, use QSInterpreter::call().
In the spreadsheet example we have seen that each macro (global function) is associated with an action and has a corresponding menu option and toolbar button. Now we'll see how clicking a macro menu option or toolbar button will cause the macro to be executed.
When the user invokes an action, the runScript() slot is triggered by the action, and we have to find which function should then be executed. For every slot, we call sender() (implemented in QObject), to find out what action triggered that slot. We cast the sender() to a QAction pointer (since we know it is a QAction) and then look up this pointer in the scripts map. Each action is mapped to the name of the function that it is associated with, so we can now call QSInterpreter::call() with the action's associated function name to execute it:
It is possible to connect script functions to an application objects signals by letting the user edit scripts in QSA Workbench. These connections are established when the project is evaluated. When the user opens QSA Workbench, the project is paused for as long as QSA Workbench is open, and no connections are active during this time. When a scripting function is executed while QSA Workbench is opened or when play is pressed, the project is run again each time so that changes to the script become active. When QSA Workbench is closed again, the project is re-run once more and all connections are re-established.
If an error occurs, the QSInterpreter emits a QSInterpreter::error() signal.
We have shown that script programmers can easily access application instances of QObject subclasses if the class is made available to the interpreter. This is sufficient for most situations, but sometimes it may be desirable to allow script programmers to instantiate their own object instances. One solution is to expose an application object which has a slot that acts as a factory function, returning new QObject instances. Another solution is to allow the script writer to directly instantiate their own objects from C++ classes, with script code like this:
var a = new SomeCppObject( arg1, arg2 );
To make a QObject subclass available as a constructable object in Qt Script, use the QSObjectFactory class. This class makes it possible to create new C++ data-types and make them available to Qt Script.
Qt Script for Applications automatically wraps every QObject you pass to it. It also wraps every QObject which is returned from a slot or passed into a slot. But you often have non-QObject datatypes in C++ which you want to make available to the script writer as well. One possibility is to change your C++ API and convert all those datatypes to QObject subclasses. From a design and efficiency point of view, this is a bad way to go; imagine the effects of having every item of a listview being a QObject subclass.
Qt Script for Applications provides an innovative solution by offering the QSWrapperFactory class. This class allows you to define non-QObjects that you can wrap. A QSWrapperFactory basically offers a QObject which can wrap a known C++ datatype. If Qt Script runs accross an unknown C++ datatype it will ask all installed QSWrapperFactories if it knows the type. If one of the QSWrapperFactories knows the datatype, a wrapper for that datatype is instantiated and used.
We have demonstrated the flexibility that Qt Script offers for making applications scriptable. In the next chapter, we will extend the applications functionality to end users by teaching them to create scripts with a simple, but complete example.
This chapter explains how to implement application objects and provides the necessary technical background material.
Making C++ classes and objects available to a scripting language is not trivial since scripting languages are more dynamic than C++ and it must be possible to introspect objects (query information such as functions names, function signatures, properties, etc., at runtime). Standard C++ doesn't providet Script for Applications.
To make an object available in Qt Script, it must derive from QObject. All classes which derive from QObject are introspective and can provide the information needed by the scripting engine, e.g. classname, functions, signatures, etc., at runtime. Because we obtain the information we need about classes dynamically at run time, there is no need to write wrappers for QObject derived classes.
The meta object system makes information about slots dynamically available at runtime. This means that for QObject derived classes, only the slots are automatically made available to scripts. This is very convenient, because in practice we normally only want to make specially chosen functions available to scripters.
When you create a QObject subclass, make sure that the functions you want to be available to scripters are public slots:.
In the previous example, if we wanted to get or set a property using Qt Script we would have to write code like the following:
var obj = new MyObject; obj.setEnabled( true ); debug( "obj is enabled: " + obj.isEnabled() );
Scripting languages often provide a property syntax to modify and retrieve properties (in our case the enabled state) of an object. Many script programmers would want to write the above code like this:
var obj = new MyObject; obj.enabled = true; debug( "obj is enabled: " + obj.enabled );
To make this possible, you must define properties in the C++ QObject subclass. The class declaration of MyObject must look like the following to declare a property enabled of the type bool, which should use the function setEnabled(bool) as its setter function and the function isEnabled() as its getter function:; private: .... };
The only difference from the original code is the use of the macro Q_PROPERTY, which takes the type and name of the property, and the names of the setter and getter functions as arguments.
In the Qt object model, signals are used as a notification mechanism between QObjects. This means one object can connect a signal to another object's slot and every time the signal is fired (emitted) the slot is called. This connection is established using the QObject::connect() function. This mechanism is also available to Qt Script programmers. The C++ code for declaring a signal is no different for a C++ class that is to be used by Qt Script than a C++ class used with Qt.; signals: // the signals void enabledChanged( bool newState ); private: .... };
The only change this time is to declare a signals section, and declare the relevant signal in it.
Now the script writer can write a function and connect to the object like this:
function enabledChangedHandler( b ) { debug( "state changed to: " + b ); } function init() { var obj = new MyObject; // connect a script function to the signal connect( obj, "enabledChanged(bool)", this, "enabledChangedHandler" ); obj.enabled = true; debug( "obj is enabled: " + obj.enabled ); }
The previous section described how to implement C++ objects which can be used in Qt Script. Application objects are the same kind of objects, and they make your application's functionality available to Qt Script you make available. The implementation of these objects simply calls the functions in the application which do the real work. So instead of making all your QObjects available to the scripting engine, just add the wrapper QObjects. For an example of this technique, see the implementation of an application object in the SheetInterface (examples/spreadsheet/sheetinterface.{cpp|h}).
In this chapter we'll demonstrate how to create scripts for a scriptable application using QSA Workbench, a scripting environment for managing, creating, and running scripts. QSA Workbench provides a code completion feature that makes writing scripts easier. We will explain how to create a dialog using Qt Script and then create and implement a convertToEuro() function. We will write the scripts using the spreadsheet application that we created in the previous chapter.
Settings for Euro Converter Finished Dialog
A 'Macro' is simply a global Qt Script function.
Run the spreadsheet application if it isn't already running. Click the New button located on the Scripts toolbar to invoke the New Macro dialog. Once we create a new macro, a toolbar button will appear on the Scripts toolbar as a shortcut to execute the macro.
New Macro Toolbar Button
Follow the steps below to create the new macro:
Click OK when you have entered the information in the New Script dialog. The Add Function message box will pop up, saying The function doesn't exist. Do you want to add it?. Click Yes.
Adding the New Function
QSA Workbench opens with the new empty function added to it. We will implement the scripting function in the following section.
In this section, we will implement the functionality of the convert-to-euro macro. We want to present the user with a dialog in which they can: 1) enter a range of rows and columns which are read from the spreadsheet, 2) specify where in the spreadsheet the results should be written, and 3) select a currency type to convert into Euros.
In the QSA Workbench editor, we write the code to calculate the input values which are the input column, start row, end row, and ouput column. We initialize these variables to 1, but if the user selects a range in the spreadsheet, we then use the selection for the initial values.
var inputCol = 1; var startRow = 1; var endRow = 1; var outputCol = 1; if ( Application.sheet1.numSelections > 0 ) { var sel = Application.sheet1.selection( 0 ); inputCol = sel.x + 1; outputCol = inputCol + 1; startRow = sel.y + 1; endRow = sel.bottom + 1; }
In Qt Script, we have some global objects. The most important one for our example is called Application. This object contains application objects. Application objects are the objects that the C++ application makes available to our script. In the spreadsheet example, the sheets are available this way, e.g., Application.sheet1.
To create a new dialog, write the following code. An explanation of the code will follow.
d = new Dialog; d.caption = "Settings for Euro Converter"; d.okButtonText = "Calculate"; d.cancelButtonText = "Cancel";
Every dialog includes an Ok and Cancel button by default. After creating the new dialog, simply change the caption property to Settings for Euro Convertor. Change the text of the OK Button to 'Calculate'. Change the text property of the Cancel button to 'Cancel'.
The Settings for Euro dialog consists of three spinboxes for selecting the columns and rows on the spreadsheet, a spinbox to output the result of the conversion, a group box to lay out the spinboxes, three radiobuttons in a group box to select the currency to convert from, and text labels for each of the widgets. If you run the dialog application and resize it, all the widgets scale properly. The layout of the widgets is determined by the order in which you add them to the dialog or the group box.
We'll start with the first group box and its widgets. Write the following code in the editor to create the group box:
var g = new GroupBox; g.title = "Conversion Range:"; d.add( g );
This code creates the new group box. Set its title to Conversion Range:. Then add the group box to the dialog. Note that every time a widget is created, it must be added its parent.
Write the following code to add multiple spin boxes and text labels to the group box:
var spinColumn = new SpinBox; spinColumn.label = "Column:"; spinColumn.minimum = 1; spinColumn.maximum = 100; spinColumn.value = inputCol; g.add( spinColumn ); var spinStartRow = new SpinBox; spinStartRow.label = "Start at Row:"; spinStartRow.minimum = 1; spinStartRow.maximum = 100; spinStartRow.value = startRow; g.add( spinStartRow ); var spinEndRow = new SpinBox; spinEndRow.label = "End at Row:"; spinEndRow.minimum = 1; spinEndRow.maximum = 100; spinEndRow.value = endRow; g.add( spinEndRow ); var spinOutput = new SpinBox; spinOutput.label = "Output Column:"; spinOutput.minimum = 1; spinOutput.maximum = 100; spinOutput.value = outputCol; g.add( spinOutput );
With this code, we create the first spin box in the group box and and name it spinColumn. This spin box corresponds to the column in the spreadsheet from which the numbers will be read. Set the label property to Column:. Set the minimum property to 1 and the maximum property to 100. Set the number property to the calculated input column. Add the spin box to the group box.
Create the second spin box and name it spinStartRow. This spin box corresponds to first row in the spreadsheet from which the numbers will be read. Set the label property to Start at Row:. Set the minimum property to 1 and the maximum property to 100. Set the number property to the calculated start row. Add the spin box to the group box.
Create the third spin box and and name it spinEndRow. This spin box corresponds to the last row in the spreadsheet from which the numbers will be read. Set the label property to Start at Row:. Set the minimum property to 1 and the maximum property to 100. Set the number property to the calculated end row. Add the spin box to the group box.
Create the fourth spin box and and name it spinOutput. This spin box corresponds to the column in the spreadsheet to which the converted values will be returned. Set the label property to Start at Row:. Set the minimum property to 1 and the maximum property to 100. Set the number property to the calculated output column. Add the spin box to the group box.
We'll add a column to the dialog to set layout so that the new group box will be added beside the current group box.:
d.newColumn();
Now we'll add the second group box and its widgets. Write the following code to create the second group box:
var g = new GroupBox; g.title = "Conversion Range:"; d.add( g );
This code creates the new group box similar to the first group box we created earlier in the chapter. Change the title property to Convert From:. Add the group box to the dialog.
Write the following code to add multiple radio buttons to the group box:
var radioUSD = new RadioButton; radioUSD.text = "USD"; radioUSD.checked = true; g.add(radioUSD); var radioYEN = new RadioButton; radioYEN.text = "YEN"; g.add(radioYEN); var radioNOK = new RadioButton; radioNOK.text = "NOK"; g.add(radioNOK);
We create the first radio button and name it radioUSD. Set its text property to USD . Set the checked property to true to make this radio button checked. Add the radio button to the group box.
Create the second radio button and name it radioYEN. Set its text property to YEN . Add the radio button to the group box.
Create the third radio button and name it radioNOK. Set its text property to NOK . Add the radio button to the group box.
To run the dialog, click the Call Function button in QSA Workbench. The Call Function dialog pops up with a drop down list of functions you created. Select convertToEuro and click OK. The Output Window displays errors found in the code.
The first block of code reads what currency the user chose and then initializes the divisor accordingly.
var divisor; if( radioUSD.checked ) divisor = 0.930492; else if( radioYEN.checked ) divisor = 0.007677; else if ( radioNOK.checked ) divisor = 0.133828;
The second block of code reads the range that the user has entered in the dialog.
inputCol = spinColumn.value - 1; outputCol = spinOutput.value - 1; startRow = spinStartRow.value - 1; endRow = spinEndRow.value - 1;
The third block of code checks that the entered range is valid. If it is not valid, a warning is issued and the operation is canceled.
if ( endRow < startRow ) { MessageBox.critical( "Cannot calculate!", "Error" ); return; }
The fourth block of code reads the value from the spreadsheet, calculates the results and then writes the results to the spreadsheet.
for ( var i = startRow; i <= endRow; ++i ) { var input = Application.sheet1.text( i, inputCol ); Application.sheet1.setText( i, outputCol, Math.round( input / divisor * 100 ) / 100 ); }
We are now ready to run the macro and invoke the dialog we just created.
We have now coded a dialog and written the code to provide its functionality, all purely using Qt Script. This should provide a taste of the power and flexibility that Qt Script for Applications can provide for your Qt C++ applications. | http://doc.trolltech.com/qsa-1.2.2/getting-started.html | crawl-001 | refinedweb | 4,540 | 64.2 |
wrong post url
Splash › Forums › Rewrite Users › wrong post url
This topic contains 13 replies, has 3 voices, and was last updated by
lyahim 2 years, 10 months ago.
- AuthorPosts
Hi All!
Unfortunatelly I don’t have more idea, must write the problem what I found.
I use now prettyfaces but I checked the Rewrite too.
I have a simple web project and I want to make a contact form with url what contains parameter. When I try to submit the form, it try to process with the view-id and redirect to there too.
For example:->
At the background I got a null source exception:
(http-localhost-127.0.0.1-8080-4) null source: javax.servlet.ServletException: null source
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:606) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
My pattern is: /#{lang}/contact
And view-id is: /res/pages/contact.xhtml
I used the annotation way, the full annotation is:
@URLMapping(id = “contact”, pattern = “/#{lang}/contact”, viewId = “/res/pages/contact.xhtml”)
or
@Join(path = “/{lang}/contact”, to = “/res/pages/contact.xhtml”)
I use JBoss AS 7.1
When don’t use parameter in url(/contact), it works right.
I tried to read about it on many forums, but i found nothing.
Thanks for helping.
Mihaly
So you say that the FaceServlet throws this exception only if you have a path parameter in your pattern, right?
Could you please post the full stacktrace?
Also, could you try to use 2.0.5.Final instead of 2.0.7.Final. There was a report regarding problems with parameters in another forums post after updating from 2.0.5.Final to 2.0.7.Final.
Dear Christian!
Sorry fot late reply. I try to check what is the exactly failure and I found it.
The null source exception is forgottable, because it caused by a null object in my ViewHandler and the stacktrace was wrong.
My other problem is the post url.
I use the 2.0.5.Final library. And make a small project for present the situation.
I attach the project, what you can access in “baseURL/en/test” url for example.
But after click any submit button, will be send to “baseURL/res/pages/test.xhtml”.
Thank you,
Mihaly
Attachments:
Hey,
thanks. A small project that reproduces an error is always handy. I’ll have a look at it as soon as possible.
I just had a quick look at the RAR file and found something that you could try. Could you also add the
rewrite-integration-facesmodule to your project and try again. There have been reports that adding this module leads to weird ClassNotFoundExceptions. If this happens, you could (for a temporary test) add the module directly to the Glassfish lib directory and check if this works.
Christian
Hello Christian!
I copy the rewrite-integration-faces module into the project, but has no effect. I solved the nullpointer exception, but the form action url even bad. Could you check the attachment?
Regards,
Mihaly
Lincoln Baxter IIIKeymaster
Hi. We recently fixed a few bugs in 2.0.8.Final that may cause this issue. Could you try upgrading and let us know if that solves your issue? Thanks!
Hello Lincoln!
I try the latest release, but the wrong behavior stay. And after I created a ConfigurationProvider and there defined a similar rule
ConfigurationBuilder.begin().addRule().when(Direction.isInbound().and(Path.matches(“/{lang}/contact”))
).perform(Forward.to(“/res/pages/contact.xhtml”))
but the behaviour didn’t changed.
Regards,
Mihály
Lincoln Baxter IIIKeymaster
Could you perhaps upload a sample application that reproduces this? I think we need to look at the code to see what is wrong here.
Thanks,
Lincoln
Hello Lincoln!
I attach a simple project, what contains the required codes for test the situation.
I read more and more your documents and don’t understand why not work for my this function because that is well documented. Therefore maybe more important I use Jboss AS 7.1 server.
When you get the ‘base_url/’ or ‘base_url/correct’ link you can start the test.
Cheers,
Mihaly
Attachments:
I just had a look at your project. There are two issues.
First, if you have a join with a parameter, you have to specify the value of that parameter if you want to use
h:linkto navigate to this page.
<h:link <f:param </h:link>
Second, you have to add
rewrite-integration-faces-2.0.8.jarto your
WEB-INF/lib. After doing this, the form postback URLs will be rewritten and you won’t be sent to the plain JSF URL any more when clicking one of the buttons.
I hope this helps. 🙂
Hello All!
Thank you for kind help! Christian the last post was very helpful. I try many cases because the simple app worked, but the original project didn’t. Therefore I dig a bit in my code and i found the bug.
When I use a ViewHandler the form action use viewId instead of pattern.
I attach the updated project.
Regards,
Mihaly
Attachments:
I wasn’t able to run your sample app due to missing dependencies, but I think I can tell you what is going wrong.
Actually your custom view handler is incorrect. It looks like you are trying to extends the existing default view handler of Mojarra by creating a subclass. If you do it this way, the RewriteViewHander will be completely ignored which is why you are getting problems.
As there may be multiple view handlers in a single application, you have to use some kind of wrapper pattern instead. Something like this:
public class ReverseProxyViewHandler extends ViewHandler { private ViewHandler parent; public ReverseProxyViewHandler(ViewHandler parent) { this.parent = parent; } @Override public Locale calculateLocale(FacesContext context) { return parent.calculateLocale(context); } @Override public String calculateRenderKitId(FacesContext context) { return parent.calculateRenderKitId(context); } /* more */ }
This way you will get a “chain” of view handlers. So if you want to do some custom stuff, you will typically add some code to one of the methods, but keep calling the parent view handler to do the real stuff.
Here is another example of how to create a custom view handler that delegates calls to the parent (default) view handler.
Or simply extend this class which does most of the delegation work for you:
- AuthorPosts
You must be logged in to reply to this topic. | http://www.ocpsoft.org/support/topic/wrong-post-url/ | CC-MAIN-2016-50 | refinedweb | 1,067 | 67.96 |
- Task
Demonstrate how to check whether the output device is a terminal or not.
- Related task
Contents
Ada[edit]
We use the interface to C library functions
isatty() and
fileno().
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;
procedure Test_tty is
begin
if Isatty(Fileno(Stdout)) = 0 then
Put_Line(Standard_Error, "stdout is not a tty.");
else
Put_Line(Standard_Error, "stdout is a tty.");
end if;
end Test_tty;
- Output:
$ ./test_tty stdout is a tty. $ ./test_tty > /dev/null stdout is not a tty.
C[edit]
Use
isatty() on file descriptor to determine if it's a TTY. To get the file descriptor from a
FILE* pointer, use
fileno:
#include <unistd.h> // for isatty()
#include <stdio.h> // for fileno()
int main()
{
puts(isatty(fileno(stdout))
? "stdout is tty"
: "stdout is not tty");
return 0;
}
- Output:
$ ./a.out stdout is tty $ ./a.out > tmp $ cat tmp stdout is not tty $ ./a.out | cat stdout is not tty
Common Lisp[edit]
(with-open-stream (s *standard-output*)
(format T "stdout is~:[ not~;~] a terminal~%"
(interactive-stream-p s)))
- Output:
$ sbcl --script rc.lisp stdout is a terminal $ sbcl --script rc.lisp | cat stdout is not a terminal $ sbcl --script rc.lisp > foo.txt $ cat foo.txt stdout is not a terminal
Crystal[edit]
File.new("testfile").tty? #=> false
File.new("/dev/tty").tty? #=> true
STDOUT.tty? #=> true
Factor[edit]
You have to know 1 is the correct file descriptor number:
IN: scratchpad USE: unix.ffi
IN: scratchpad 1 isatty
--- Data stack:
1
Go[edit]
package main
import (
"os"
"fmt"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
if terminal.IsTerminal(int(os.Stdout.Fd())) {
fmt.Println("Hello terminal")
} else {
fmt.Println("Who are you? You're not a terminal.")
}
}
- Output:
> hello Hello terminal > hello | cat Who are you? You're not a terminal.
Haskell[edit]
module Main where
-- requires the unix package
--
import System.Posix.Terminal (queryTerminal)
import System.Posix.IO (stdOutput)
main :: IO ()
main = do
istty <- queryTerminal stdOutput
putStrLn (if istty
then "stdout is tty"
else "stdout is not tty")
- Output:
$ runhaskell istty.hs stdout is tty $ runhaskell istty.hs | cat stdout is not tty
Javascript/NodeJS[edit]
node -p -e "Boolean(process.stdout.isTTY)"
true
J[edit]
3=nc<'wd'
Explanation:
J does not have a concept of an "output device", so we approximate that by seeing whether we have bothered to define a the code which typically does graphical output.
The use of the phrase "output device" suggests that we are thinking about something like the unix `isatty` command. Here, stdout might be a file or might be a terminal. But in J we are often hosting our own user interaction environment. It's not uncommon for a J user to be on a web page where hitting enter sends a form request to a J interpreter which in turn composes an updated html presentation of current state which it sends to the browser. Or, the J user might be talking to a Java program which similarly wraps the J session (though this is older technology at this point). Or, the J user might be interacting with Qt. Or, sure, we might be talking to a tty and J might be sending its output straight to the tty. (But we can't know if that tty is hosted in emacs, running under control of a script on a remote machine via ssh, talking directly to a human user who happens to be in direct control of the session, or whatever else...)
The point being that in the general case the J programmer cannot know whether the concept of "terminal" has any relevance to the user.
But, like everyone else, we can certainly use heuristics.
But, correctness requires us to keep in mind that these will only be heuristics, and will sometimes be incorrect (hopefully not often enough to matter a lot...).
Julia[edit]
if isa(STDOUT, Base.TTY)
println("This program sees STDOUT as a TTY.")
else
println("This program does not see STDOUT as a TTY.")
end
- Output:
This program sees STDOUT as a TTY.
Nemerle[edit]
There is no explicit way (ie isatty())to do this; however, if we assume that standard out is a terminal, we can check if the output stream has been redirected (presumably to something other than a terminal).
def isTerm = System.Console.IsOutputRedirected;
OCaml[edit]
let () =
print_endline (
if Unix.isatty Unix.stdout
then "Output goes to tty."
else "Output doesn't go to tty."
)
Testing in interpreted mode:
$ ocaml unix.cma istty.ml Output goes to tty. $ ocaml unix.cma istty.ml > tmp $ cat tmp Output doesn't go to tty. $ ocaml unix.cma istty.ml | cat Output doesn't go to tty.
Perl[edit]
The -t function on a filehandle tells you whether it's a terminal.
$ perl -e "warn -t STDOUT ? 'Terminal' : 'Other'"
Terminal
$ perl -e "warn -t STDOUT ? 'Terminal' : 'Other'" > x.tmp
Other
Perl 6[edit]
The .t method on a filehandle tells you whether it's going to the terminal. Here we use the note function to emit our result to standard error rather than standard out.
$ perl6 -e 'note $*OUT.t' True $ perl6 -e 'note $*OUT.t' >/dev/null False
Python[edit]
Pretty much the same as Check input device is a terminal#Python.
from sys import stdout
if stdout.isatty():
print 'The output device is a teletype. Or something like a teletype.'
else:
print 'The output device isn\'t like a teletype.'
Racket[edit]
(terminal-port? (current-output-port))
REXX[edit]
Programming note: The comment about the REXX statements have to be on one line isn't quite true,
but because the REXX special variable SIGL is defined where it's executed, it makes coding simpler.
SIGL is set to the REXX statment number where:
- a CALL statement is used
- a function is invoked
- a SIGNAL statement is used
Method used: since REXX has no direct way of determining if the STDIN is a terminal or not, the REXX code (below)
actually raises (which is no way to run a railroad) a syntax error when attempting to read the 2nd line from STDIN,
which causes a routine (named syntax:) to get control, determines where the syntax error occurred, and returns an
appropriate string indicating if STDIN is a terminal (or other).
Note that under VM/CMS, this can be accomplished with a (host) command within REXX and then examining the results.
On IBM mainframes, a user can have STDIN defined, but the terminal can be disconnected.
/*REXX program determines if the STDIN is a terminal or other. */
signal on syntax /*if syntax error, jump──► SYNTAX*/
say 'output device:' testSTDIN() /*displays terminal ──or── other */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────TESTSTDIN subroutine────────────────*/
testSTDIN: syntax.=1; signal .; .: z.=sigl; call linein ,2; ..: syntax.=0
return z.. /* [↑] must all be on one line.*/
/*──────────────────────────────────SYNTAX subroutine───────────────────*/
syntax: z..='other' /*when SYNTAX occur, come here. */
if syntax. then do /*handling STDIN thingy error? */
if sigl==z. then z..='terminal'; signal .. /*stdin ?*/
end /* [↑] can't use a RETURN here.*/
/* ··· handle other REXX syntax errors here ··· */
output
output device: terminal
Ruby[edit]
f = File.open("test.txt")
p f.isatty # => false
p STDOUT.isatty # => true
Rust[edit]
/* Uses C library interface */
extern crate libc;
fn main() {
let istty = unsafe { libc::isatty(libc::STDOUT_FILENO as i32) } != 0;
if istty {
println!("stdout is tty");
} else {
println!("stdout is not tty");
}
}
Tcl[edit]
To detect whether output is going to a terminal in Tcl, you check whether the
stdout channel looks like a serial line (as those are indistinguishable from terminals). The simplest way of doing that is to see whether you can read the -mode or
-xchar channel options, which are only present on serial channels:
set toTTY [dict exists [fconfigure stdout] -mode]
puts [expr {$toTTY ? "Output goes to tty" : "Output doesn't go to tty"}]
At the system call level, when Tcl is setting up the channels that correspond to the underlying stdout (and stdin and stderr) file descriptors, it checks whether the channels are network sockets (with
getsockname()) or serial lines (with
isatty()). This allows Tcl scripts to find out information about their calling environment (e.g., when they are run from inetd) with minimal code.
- Demonstrating:
Assuming that the above script is stored in the file istty.tcl:
$ tclsh8.5 istty.tcl Output goes to tty $ tclsh8.5 istty.tcl | cat Output doesn't go to tty
Channel type discovery with older Tcl versions[edit]
Before Tcl 8.4, this discovery process is impossible;
stdout always looks like it is going to a file. With 8.4, you can discover the channel type but you need slightly different (and less efficient, due to the thrown error in the non-tty case) code to do it.
set toTTY [expr {![catch {fconfigure stdout -mode}]}]
UNIX Shell[edit]
#!/bin/sh
if [ -t 1 ]
then
echo "Output is a terminal"
else
echo "Output is NOT a terminal" >/dev/tty
fi
zkl[edit]
On Unix, check to see if stdout's st_mode is a character device.
const S_IFCHR=0x2000;
fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() }
S_ISCHR(File.stdout).println();
- Output:
$ zkl bbb # from the command line True $ zkl bbb | more False $ zkl bbb > foo.txt $ cat foo.txt False | http://rosettacode.org/wiki/Check_output_device_is_a_terminal | CC-MAIN-2017-04 | refinedweb | 1,538 | 67.25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.