text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
> From: Peter Reilly [mailto:peter.reilly@corvil.com] > As regards the xml ns hell, I must agree - I still think that nested > elements discovered through reflection should be in the ant core > namespace as well as the namespace of the enclosing type/task. Well, I'm not following, but I'm not surprised, as my head hurts when I try to think at the issues related to XML NS handling in Ant... > You are missing a bm prefix from a nested include of a fileset element in > a bm:lsync (i think) element. Not really, and this is where I think I may have stumbled on a possible bug or flow of the current design... Going back to the macro definition, simplified: <macrodef name="compile"> <element name="sources" /> <!-- <<< Declaration --> <sequential> <javac ...> <sources/> <!-- <<< Use in Javac - default NS --> </javac> <bm:sync ...> <fileset dir="src"> <sources/> <!-- <<< Use in lsync - BM NS --> </fileset> </bm:lsync> </sequential> </macrodef> See how the macro element 'sources' is used in two different tasks, from two different namespaces, the default/Ant NS, and my custom NS. Apparently, it's currently impossible to use that same macro element in the two places/tasks, when they are in different namespaces. So is this a bug, design flaw, or user error??? And I can assure you all uses of the macro, as exemplified below, all have the name attribute. This build has been working for weeks now, and I was just trying to add the <sync> or <bm:lsync> additional step to it. <compile name="dsp-test-utils"> <sources> <include name="com/lgc/testing/junitplus/**"/> <include name="com/lgc/testing/utils/**"/> <none> <contains text="import com.lgc.infra."/> </none> </sources> </compile> <compile name="dsp-util"> <sources> <include name="com/lgc/java/**"/> <include name="com/lgc/javax/**"/> </sources> </compile> > Also, is "sources" a typedef? No, a macro element, as explained above. Please help. --DD --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-dev/200402.mbox/%3C830BF4914C3C4B4EB1C438D93ABF897A04D93E@lgchexch011.ad.lgc.com%3E
CC-MAIN-2016-07
en
refinedweb
#include <windows_message_handler.hpp> List of all members. Class that manages a message handling function attched to a win32 HWND. Definition at line 30 of file windows_message_handler.hpp. Function prototype for the message handling function. Definition at line 43 of file windows_message_handler.hpp. callback_t() Attach the message handler to the window with a specific string handle. A given string handle can be attached to a window at most once, attempting to re-install a handler with the same string handle on a given window is an error. Attempting to install a message handler to two windows at the same time is an error. Note that the ProcName template argument is a const char*, which requires a very specific coding style to be used by clients. The string being passed must be staticly defined, but cannot be a string literal, as the following example demonstrates: extern const char my_proc_name_k[] = "my-unique-proc-name"; extern const char my_proc_name_k[] = "my-unique-proc-name"; message_handler_t handler(&my_handler_func); handler.install<my_proc_name_k>(my_hwnd); message_handler_t handler(&my_handler_func); handler.install<my_proc_name_k>(my_hwnd); Definition at line 66 of file windows_message_handler.hpp. Definition at line 71 of file windows_message_handler.hpp. Definition at line 74 of file windows_message_handler.hpp. Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy. Search powered by Google
http://stlab.adobe.com/classadobe_1_1message__handler__t.html
CC-MAIN-2016-07
en
refinedweb
post I will show you how bundling and minifying works in ASP.NET MVC. What is bundling and minifying? Bundling helps you to download files of same type using one request instead of multiple requests. This way you can download styles and scripts using less requests than it takes to request all files separately. Minifying helps you make files smaller by removing unnecessary whitespace. Together these two lessen the amount of requests and bytes to get page loaded by browser. How bundling and minifying works in ASP.NET MVC In ASP.NET MVC 4 web application you can find BundleConfig.cs file under App_Start folder. This file contains BundleConfig class that has only one method – RegisterBundles(). In this method files that must be downloaded with one request are added to bundles.")); } Here all files in each bundle are concatenated together and downloaded as one file. It means that this method defines the following URL-s to download files: - ~/bundles/jquery - ~/bundles/jqueryui - ~/bundles/jqueryval - ~/bundles/modernizr - ~/Content/css - ~/Content/themes/base/css Take a good look at file definitions. You can see that you can specify files not only by name but also by name pattern. Special placeholder {version} in file name means that file name may contain version number. This name pattern is specially good for jQuery that is updated often. When you replace your old jQuery file that has version number in its name with newer version then you don’t have to rename the file. It is enough when file has different version number in its name. NB! In debug-mode bundling is switched off by default. To force bundling in debug-mode add the following line in the beginning of RegisterBundles() method:BundleTable.EnableOptimizations = true; If you open _Layout.cs view of your application you can see how style and script bundles are included to page: @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") @Scripts.Render("~/bundles/jquery") Although we have more bundles defined these are there for using with pages where they are actually needed. ScriptBundle and StyleBundle If you noticed then script bundle and style bundle have different classes. ScriptBundle is targeted to scripts and you shouldn’t add any other files to script bundles. Same with styles goes for StyleBundle. Both of these classes extend general Bundle class that offers bundling functionality. Taking care of minifying is tricky. Neither of these classes have no functionality like this. All they do is they add correct minifier to their transforms collection. There are two minifying classes defined in System.Web.Optimizations namespace: These are the classes that make the actual work. Same way can everybody write minification transforms one needs and if it is desired to keep same style as built-in bundles then one can create new bundle class that adds custom minifier to transforms collection when new bundle is created. Switching off minifying Yesterday I found out that CssMinify gets stuck with some style files. In the case of problems bundlers write problems out as comments to file they are transforming. Problems are reported in the beginning of file. While developers try to find out what is wrong with those style files we cannot keep minifying turned on for styles but we still want bundling to work. There are two ways how to do it. - Use Bundle class. Bundle class that other bundling classes extend is not abstract class. We can create instance of it. This way we can bundle whatever files we want. - Clear transforms collection of StyleBundle. Clearing transforms collection is same as using Bundle class with empty transforms collection. Tips and tricks Here are some tips and tricks related to bundling. - Bundles are cached. If not specified differently in bundle class then bundle is created on first request and cached on server. All following requests for bundles are served from cache. - Always test bundling. Bundling may seems like what-can-go-wrong feature. You just turn it on before deploying your system to production. But don’t forget these to transform classes I introduced. These classes may face unexpected situations they are not able to handle. Before deploying your system to production make sure that bundling and minifying works like expected. - Be careful with styles. When bundling style sheets make sure that bundle path is same “deep” as style sheet path. If style sheet refers to images or other styles using relative URL-s and you change depth of path then all these references are broken. Conclusion Bundling and minifying is powerful feature that helps us optimize our web pages. Bundles are easy to use and they are supported out-of-box. Actually almost all ASP.NET MVC templates use bundles. Thanks to easy and flexible API we can control almost every aspect of bundling. Also we can create our own custom bundle types and define custom transforms that are applied to files in bundles. Although bundling is very good it has its own limits and tricks you must know to use them successfully. Good thing is – there are only few things that can go wrong. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/bundling-and-minifying-aspnet?mz=110215-high-perf
CC-MAIN-2016-07
en
refinedweb
- OSI-Approved Open Source (248) - GNU General Public License version 2.0 (135) -) - Other License (14) - Public Domain (14) - Creative Commons Attribution License (3) - Windows (283) - Grouping and Descriptive Categories (235) - Modern (144) - Linux (128) - Mac (88) - BSD (75) Top Apps - Audio & Video - Business & Enterprise - Communications - Development - Home & Education - Games - Graphics - Science & Engineering - Security & Utilities - System Administration Link Creation Shell Extension Link Creation Extension is a nifty shell extension which enables users to create symlink to directories and hardlink to files. It also provides property sheets and shell columns.13 infotrace The final goal of this software is to ease to go back to the workflow from the final output. For example, you can find the original word file by right-clicking the final output PDF file. Doxygemplate Doxygemplate is an accessory software which semi-automatically generates a template of Doxygen comment block for C/C++. Doxygemplate is text editor independent, since it uses clipboard for generating and editing template.29 weekly downloads VisualuRuby This is a GUI library for Ruby just only on MS Windows. It needs no other prepared libraries such as VCL,Tk,Gtk and so on. This project will provide you easy GUI scripting on Windows with Ruby.3 VESMA VESMA is a Java package which provids classes used in educational virtual environments constructed using ELM-VE epo "epo" is an advanced archiving system on Windows platforms. It tightly integrates into Explorer through its shell namespace extension and offers very easy-to-use archivingod Winamp support plugin ml_ipod is a Winamp Media Library plugin that allows you to send and get songs off your iPod from Winamp's Media Library.264 weekly downloads DIOWave Visual Storage DIOWave Visual Storage is a Web server which displays DICOM images. The look and feel of the Web pages are similar to imaging workstations.28 weekly downloads dcrteam Suite of diverse free tools under the platform win32 destined to help to increase the safety and ergonomics, of the users of internet of simple and comfortable way100 weekly downloads Bok Project management suite with extensible capability to provide a variety of agile project methodologies. Integration with Kuu is available to provide time management capability. Ruby/FLTK Ruby/FLTK is a Ruby extension library for the FLTK GUI Toolkit library Mona Font, a Japanese font for text arts Mona Font is a Japanese proportional font which allows you to view Japanese text arts correctly.61 weekly downloads Bagel Bagel is a web browser for the Windows platform based on the Gecko, Apple WebKit, and Trident layout engine. It is inspired by Donut(). XKeymacs XKeymacs provides key bindings like Emacs for applications running on Windows. You can also configure bindings for each application. Squarer Navigator Please, visit our project website: weekly downloads
http://sourceforge.net/directory/natlanguage%3Ajapanese/environment%3Awin32/?sort=update&page=6
CC-MAIN-2016-07
en
refinedweb
Hi all, Just wondering if there's been any information or hints yet about potential release dates for either a CTP or BETA release of Visual studio 2010 and .net framework 4.0? Now that Windows 7 Beta 1 is out, I'm chomping at the bit to do some multitouch development experiments on my HP Touchsmart computer (have already installed win 7 and the multitouch driver for it). As I'm a managed coding type of guy, that means WPF and the System.Windows.Input.Touchpoint/TouchPointCollection namespaces in .net 4.0. I know there's a VPC image of early CTP available here which is the same VPC image we got at PDC but it doesn't come on a Win 7 OS so it's not much use to me. Not really bothered about specific dates, just want to know if we are weeks or months away from an installable CTP/BETA. We're seeing quite a few new videos on Channel 9 for vs.net 2010, so I'm guessing there may be something coming soon, but I've not seen any information confirming/denying this. Thanks all! Hi all, nothing definitive. but rumors are around Mix timeframe. Rumors are early views of silverlight 3 and blend 3 also. ymmv Douglash Dont wait on VS 2010 for multitouch.. start NOW!! I suspect we might not see a proper VS2010 beta until PDC, which is in November. That's when you can expect a release, not a beta. All bets are on RTM in that time frame, with official release in at the Jan/Feb time frame.warren said:I suspect we might not see a proper VS2010 beta until PDC, which is in November. It was exactly 2 years between VS2005 and VS 2008, so the same may happen with VS 2010 for sure!wkempf said:warren said:*snip* 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.
http://channel9.msdn.com/Forums/Coffeehouse/453144-Any-hints-yet-on-VS-2010net-4-CTP-or-BETA-release-date
CC-MAIN-2014-10
en
refinedweb
Instant GSON [Instant] — Save 50% Learn to create JSON data from Java objects and implement them in an application with the GSON library with this book and ebook In this article, by Sandeep Kumar Patel, the author of Instant GSON, you will learn about the top features supported by the GSON library. You will also learn about how to implement these features. (For more resources related to this topic, see here.) Java objects support Objects in GSON are referred as types of JsonElement: The GSON library can convert any user-defined class objects to and from the JSON representation. The Student class is a user-defined class, and GSON can serialize any Student object to JSON. The Student.java class is as follows: public class Student { private String name; private String subject; privateint mark; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public int getMark() { return mark; } public void setMark(int mark) { this.mark = mark; } } The code for JavaObjectFeaturesUse.java is as follows: import com.google.gson.Gson; import com.packt.chapter.vo.Student; public class JavaObjectFeaturesUse { public static void main(String[] args){ Gsongson = new Gson(); Student aStudent = new Student(); aStudent.setName("Sandeep"); aStudent.setMark(128); aStudent.setSubject("Computer Science"); String studentJson = gson.toJson(aStudent); System.out.println(studentJson); Student anotherStudent = gson.fromJson(studentJson, Student.class); System.out.println(anotherStudentinstanceof Student); } } The output of the preceding code is as follows: {"name":"Sandeep","subject":"Computer Science","mark":128} True The preceding code creates a Student object with name as Sandeep, subject as Computer Science, and marks as 128. A Gson object is then instantiated and the Student object is passed in as a parameter to the toJson() method. It returns a string that has the JSON representation of the Java object. This string is printed as the first line in the console. The output JSON representation of the Student object is a collection of key/value pairs. The Java property of the Student class becomes the key in the JSON string. In the last part of the code, the fromJson() method takes the JSON generated string as the first input parameter and Student.class as the second parameter, to convert the JSON string back to a Student Java object. The last line of the code uses an instance of Student as the second-line operator to verify whether the generated Java object by the fromJson() method is of type Student. In the console, it prints True as the output, and if we print the values, we will get the same values as in JSON. Serialization and deserialization GSON has implicit serializations for some classes, such as Java wrapper type (Integer, Long, Double, and so on), java.net.URL, java.net.URI, java.util.Date, and so on. Let's see an example: import java.util.Date; import com.google.gson.Gson; public class InbuiltSerializerFeature { public static void main(String[] args) { Date aDateJson = new Date(); Gsongson = new Gson(); String jsonDate = gson.toJson(aDateJson); System.out.println(jsonDate); } } The output of the preceding code is as follows: May 29, 2013 8:55:07 PM The preceding code is serializing the Java Date class object to its JSON representation. In the preceding section, you have learned how GSON is used to serialize and deserialize objects, and how it supports custom serializers and deserializers for user-defined Java class objects. Let's see how it works. Also, GSON provides the custom serialization feature to developers. The following code is an example of a custom serializer: classStudentTypeSerializer implements JsonSerializer<Student>{ @Override publicJsonElement serialize(Student student, Type type, JsonSerializationContextcontext) { JsonObjectobj = new JsonObject(); obj.addProperty("studentname", student.getName()); obj.addProperty("subjecttaken", student.getSubject()); obj.addProperty("marksecured", student.getMark()); returnobj; } } The following code is an example of a custom deserializer: classStudentTypeDeserializer implements JsonDeserializer<Student>{ @Override public Student deserialize(JsonElementjsonelment, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObjectjsonObject = jsonelment.getAsJsonObject(); Student aStudent = new Student(); aStudent.setName(jsonObject.get("studentname").getAsString()); aStudent.setSubject(jsonObject.get("subjecttaken").getAsString()); aStudent.setMark(jsonObject.get("marksecured").getAsInt()); return aStudent; } } The following code tests the custom serializer and deserializer: import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class CustomSerializerFeature { public static void main(String[] args) { GsonBuildergsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Student.class, new StudentTypeSerializer()); Gsongson = gsonBuilder.create(); Student aStudent = new Student(); aStudent.setName("Sandeep"); aStudent.setMark(150); aStudent.setSubject("Arithmetic"); String studentJson = gson.toJson(aStudent); System.out.println("Custom Serializer : Json String Representation "); System.out.println(studentJson); Student anotherStudent = gson.fromJson(studentJson, Student.class); System.out.println("Custom DeSerializer : Java Object Creation"); System.out.println("Student Name "+anotherStudent.getName()); System.out.println("Student Mark "+anotherStudent.getMark()); System.out.println("Student Subject "+anotherStudent.getSubject()); System.out.println("is anotherStudent is type of Student "+(anotherStudentinstanceof Student)); } } The output of the preceding code is as follows: Custom Serializer : Json String Representation {"studentname":"Sandeep","subjecttaken":"Arithmetic","marksecured":150} Custom DeSerializer : Java Object Creation Student Name Sandeep Student Mark 150 Student Subject Arithmetic is anotherStudent is type of Student true Summary This section explains about the support of Java objects and how to implement serialization and deserialization in GSON. Resources for Article : Further resources on this subject: - Play Framework: Binding and Validating Objects and Rendering JSON Output [Article] - Trapping Errors by Using Built-In Objects in JavaScript Testing [Article] - Class-less Objects in JavaScript [Article] About the Author : Sandeep Kumar Patel Sand. Post new comment
http://www.packtpub.com/article/gson-feature
CC-MAIN-2014-10
en
refinedweb
Skip navigation links java.lang.Object javax.servlet.sip.ar.SipApplicationRoutingRegion public class SipApplicationRoutingRegion A class that represents the application routing region. It uses the predefined regions in the Enum SipApplicationRoutingRegionType and also allows for implementations to have additional or new regions if it is so required. This could be useful in non telephony domains where the concept of of a caller and callee is not applicable. public static final SipApplicationRoutingRegion ORIGINATING_REGION public static final SipApplicationRoutingRegion TERMINATING_REGION public static final SipApplicationRoutingRegion NEUTRAL_REGION public SipApplicationRoutingRegion(java.lang.String label, SipApplicationRoutingRegionType type) SipApplicationRoutingRegionTypemay be null in cases when a custom region is defined. public java.lang.String getLabel() public final SipApplicationRoutingRegionType getType() public java.lang.String toString() toStringin class java.lang.Object
http://docs.oracle.com/cd/E23943_01/apirefs.1111/e17883/javax/servlet/sip/ar/SipApplicationRoutingRegion.html
CC-MAIN-2014-10
en
refinedweb
Mark Hammond wrote: > > I struck a bit of a snag with the Unicode support when trying to use the > most recent update in a C++ source file. > > The problem turned out to be that unicodeobject.h did a #include "wchar.h", > but did it while an 'extern "C"' block was open. This upset the MSVC6 > wchar.h, as it has special C++ support. Thanks for reporting this. > Attached below is a patch I made to unicodeobject.h that solved my problem > and allowed my compilations to succeed. Theoretically the same problem > could exist for wctype.h, and probably lots of other headers, but this is > the immediate problem :-) > > An alternative patch would be to #include "whcar.h" in PC\config.h outside > of any 'extern "C"' blocks - wchar.h on Windows has guards that allows for > multiple includes, so the unicodeobject.h include of that file will succeed, > but not have the side-effect it has now. > > Im not sure what the preferred solution is - quite possibly the PC\config.h > change, but Ive include the unicodeobject.h patch anyway :-) > > Mark. > > *** unicodeobject.h 2000/03/13 23:22:24 2.2 > --- unicodeobject.h 2000/03/14 01:06:57 > *************** > *** 85,91 **** > --- 85,101 ---- > #endif > > #ifdef HAVE_WCHAR_H > + > + #ifdef __cplusplus > + } /* Close the 'extern "C"' before bringing in system headers */ > + #endif > + > # include "wchar.h" > + > + #ifdef __cplusplus > + extern "C" { > + #endif > + > #endif > > #ifdef HAVE_USABLE_WCHAR_T > I've included this patch (should solve the problem for all inlcuded system header files, since it wraps only the Unicode APIs in extern "C"): --- /home/lemburg/clients/cnri/CVS-Python/Include/unicodeobject.h Fri Mar 10 23:33:05 2000 +++ unicodeobject.h Tue Mar 14 10:38:08 2000 @@ -1,10 +1,7 @@ #ifndef Py_UNICODEOBJECT_H #define Py_UNICODEOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif /* Unicode implementation based on original code by Fredrik Lundh, modified by Marc-Andre Lemburg (mal@lemburg.com) according to the @@ -167,10 +165,14 @@ typedef unsigned short Py_UNICODE; #define Py_UNICODE_MATCH(string, offset, substring)\ (!memcmp((string)->str + (offset), (substring)->str,\ (substring)->length*sizeof(Py_UNICODE))) +#ifdef __cplusplus +extern "C" { +#endif + /* --- Unicode Type ------------------------------------------------------- */ typedef struct { PyObject_HEAD int length; /* Length of raw Unicode data in buffer */ I'll post a complete Unicode update patch by the end of the week for inclusion in CVS. -- Marc-Andre Lemburg ______________________________________________________________________ Business: Python Pages:
https://mail.python.org/pipermail/python-dev/2000-March/002599.html
CC-MAIN-2014-10
en
refinedweb
Dec 27, 2010 03:57 PM|GEM1204|LINK I ‘m learning ajax and have created some pages and practiced using the ajax controls. I’m using visual studio 2007 on a windows xp machine with .net 3.5 . The site I’m practicing with is the ajax sample web site that I’ve downloaded. I’m just adding pages to this site as practice. Using a tag prefix of ajaxToolkit <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %> I have read on this site and serveral other sites that you can register the assembly and the tag prefix by placing code in the web config, so Between the assemblies Tags of the we congif I entered <add assembly="AjaxControlToolkit, Version=3.5.40412.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/> And between the <controls> tag the web config I added <add tagPrefix="ajaxToolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit, Version=3.5.40412.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/> This didn’t work because when an ajax control is added from the toolbox get asp tag <asp:ScriptManager </asp:ScriptManager> <asp:ComboBox </asp:ComboBox> Can someone help me with this? Member 479 Points Dec 27, 2010 04:47 PM|habdulrauf|LINK Right click in tool box, click choose items, then browse to the folder where ajaxcontroltoolkit.dll is present. select it and press ok then the ajax control toolkit controls will be in the tool box, then you can drag drop controls from toolbox on the form. configuration changes will automatically made in web.config and on the aspx page you don't need to do extra. If you want to use update panel then in tool box locate the section which says ajax extensions and drop update panel on the form. Ask again if not clear. Please mark as answer if it helps you. Dec 27, 2010 06:42 PM|GEM1204|LINK Thanks for the response. The only reason I care about the tag prefix is because I am going through some of the tutorials on the asp website and in the tutorials the ajax controls have the tag prefix “ajaxToolkit” and I would like to follow along with the tutorial with out constantly have to change the tag prefix form “asp” to “ajaxToolkit”. The tag prefix of ajax controls is confusing – I seen the prefix “cc1” as well as “ajaxToolkit”. I have now idea what the standard is. I tried following you instructions and I created a new web site and the first thing I did was add the tag prefix to the web.config <add tagPrefix="ajaxToolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit, Version=3.5.40412.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/> I then deleted the Ajax control tools tab and recreated the ajax tools tab and then selected choose items and went out and selected the AjaxControlToolkit.dll and all of the controls were re-added to the Ajax Controls Tool Tab. When I created a page and added a script manager and a combo box I got: <asp:ToolkitScriptManager </asp:ToolkitScriptManager> <asp:ComboBox </asp:ComboBox> At the top of the page I also got <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> If I remove the register asembly at the top of the page and change the tag for the script manager and combobox prefix from “asp” to “ajaxToolkit” it works, so apparently the tag prefix is being picked up from the web.config. But If a add another ajax control I get the register assembly at the top of the page again trying to register the tag prefix ‘asp’ for the ajax controls. I guess the only problem I have is the Register assembly for "asp" being added to the top of the page every time I add an ajax control. Any ideas on how to prevent this from happening? Thanks All-Star 71009 Points Dec 28, 2010 03:29 AM|chetan.sarode|LINK 1. Install the Ajax Control Toolkit as described in: 2. Modify the web.config by adding the entries below. a. <add assembly="AjaxControlToolkit, Version=3.5.40412.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/> Goes between <assemblies></assemblies> tag. b. <add tagPrefix="ajaxToolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit, Version=3.5.40412.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/> Goes between <controls></controls> tag. If you’ve installed some other version of the tool kit then make sure to replace a value of the Version attribute of both entries above. To get the version just right click on the AjaxControlToolkit.dll and get the value of Assembly Version. Here is what you’d need to use an ajax control on your page. 3 replies Last post Dec 28, 2010 03:29 AM by chetan.sarode
http://forums.asp.net/t/1636720.aspx
CC-MAIN-2014-10
en
refinedweb
30 August 2011 08:01 [Source: ICIS news] By Clive Ong ?xml:namespace> SM buyers expect spot prices to slip next month on increased supply of the material, and with demand for downstream plastic resins usually waning towards the second half of September, as the seasonal peak in the Chinese manufacturing season for exports draws to a close. Limited availability of spot cargoes throughout August helped prop up SM prices at an average of around $1,510/tonne (€1,042/tonne) in August, against a backdrop of widely fluctuating crude prices, according to ICIS. Crude prices traded at a wide range of $76-87/bbl in August. Spot inventories along the eastern Chinese shore tanks were at 50,000-60,000 tonnes in August, compared to 70,000-85,0000 tonnes in July, market sources said. “[SM] supply in the region would most likely improve in September as some SM plants will come back on stream”, said a Korean trader. Shanghai Secco Petrochemical’s 500,000 tonne/year SM unit in eastern Elsewhere in Meanwhile, Zhenhai Lyondell Chemical’s 620,000 tonne/year SM plant restarted on 29 August after suffering an outage on 26 August because of technical problems, market sources said. Taiwan Styrene Monomer Corp’s 180,000 tonne/year No 1 line in Lin Yuan is expected to restart production in mid-September. Mechanical problems shut the plant in late July, market sources said. Meanwhile, Formosa Chemical and Fibre Corp’s 250,000 tonne/year No 1 unit and its 350,000 tonne/year No 2 unit in Mailiao have remained shut since mid-May, following a fire incident that hit the petrochemical complex of the Petrochemical Corporation of Meanwhile, Ellba Eastern Chemical’s 550,000 tonne/year SM plant at SM is a liquid chemical used to make plastic resins like polystyrene (PS) and acrylonitrile-butadiene-styrene (ABS), as well as synthetic rubbers. (
http://www.icis.com/Articles/2011/08/30/9488579/tight-asia-sm-supply-to-ease-as-plant-turnarounds-end-in-sept.html
CC-MAIN-2014-10
en
refinedweb
Increase Your Struts Productivity - Attend the BaseBeans Public Struts Training!!!! We have a 11 hour public class in DC and in NYC in January. Washington DC Class -- January 18th 2003 NYC Class -- January 24th 2003 This class is taught by baseBeans Engineering, the company voted to have the best hands on training class by JDJ for their "Fast Track to Struts" class. Get your training from the #1 trainer with a money back guarantee!!!! You will pay $50 to register and be billed the balance. Upon registration, you will be shipped a CD that contains the tools needed for the class, such as an IDE, App. Server, some sample working source code, Struts, etc. Follow this link to register: At the training, we will cover Struts, Java Server Faces, JDO, DAO, JDBC,etc. A pre-requisite for attendance is some Struts knowledge or at least Servlet and SQL knowledge. This class is targeted at tech leads. Bring your questions and receive practical advice from the baseBeans team. You can FedEx a check or a PO for the balance to BaseBeans. Prior paid students and clients are free for this class, as always, but we need to know you are coming. Hope to see you there, JOHN
https://lists.debian.org/debian-user/2003/01/msg00606.html
CC-MAIN-2014-10
en
refinedweb
This program is awesome! This program is awesome! If you just want to change the year, you can do this: import time t = time.localtime(1222988400.0) t = (t[0] - 30,) + t[1:] unix_time = time.mktime(t) print unix_time Is this too crude? Why do you need this? Are you building a time machine? I'd say that PyS60 is around 10 times faster and easier to develop than Symbian C++. But I can't ever seem to sign an install anything. (So in that respect I might as well just write stories about... Hey Neil, Just out of curiosity, what did you find? I think I remember seeing a pure Python implementation and a PYD module, but didn't have any luck when I tried to find them for you. You should probably try to stick to one or two threads and give them titles that indicate what they're about. "Editor" isn't too bad but "Plz plz plz" could mean anything. When someone runs a... Thank you Croozeus. That's what I was doing for a long time but still haven't had any luck. :( Does anyone have an example of creating a PYD installer? Mine is just like this: python... I guess you guys are mostly using "Open Signed Offline" for testing? If the key and certificate files are supplied for Ensymble, this is what it must be, right? "Open Signed Online" sure doesn't... Haha, I remember that. I was a big fan of all those games as a kid. Also Microsoft Word skipped from 2 to 5 in order to keep up with WordPerfect. But I still wonder why Nokia skipped 4. I guess... Yeah, I'm building a UREL version for 3rd Ed. FP1. I haven't frozen anything because I don't know how. But right now there's just one function for testing that multiplies 2 numbers. :) I've been using WTFWMSFI for months now, and it's very helpful. But in the case of my PYD's SIS, it says there's nothing wrong. Now I'm getting "Unable to install" messages. That's about as... Version 5? What ever happened to 4? :confused: You can also return tuples, arrays or dictionaries if you want multiple outputs: def swap(x, y): return y, x (x, y) = swap(2, 1) Thank you for asking, but no, I haven't had any success yet. I'm not even trying to install Python or my app now. I'm just trying to install the PYD by itself in the c:\sys\bin folder. But still,... MOD music never dies! It just loops back around to the beginning. Thanks, that looks pretty useful. I was hoping for some way to integrate extra fields right into the calendar database, but I wasn't really expecting it. I wonder why in that FAQ about e32dbm... Thanks Bogdan. Some of those posts were made to help me. :) Hi, I need to update the device's calendar (to-do list, appointments, anniversaries, etc.) with entries from my company's system. After that, my program needs to know how to synchronize, so I... It looks interesting but I'm not able to download Bazaar. I can confirm it's a lot of fun on the N95. You can pretend you're Stephen Hawking and sound smart. To create a SIS, I just use Ensymble's simplesis option and apply the UID via the command line (using a batch file). This is only intended for now to install a PYD for testing. Thanks, I'll try... I'd be glad to show you but no .pkg file seems to exist here. I tried just compiling an existing project made by someone else, pys60usb, using the command line, packing into a simple SIS with Ensymble, then signing it online. But I get the message "Unable... It used to work for me, but at some point stopped working. I'm currently trying to write an extension that will monitor incoming and outgoing MMS. My main problem is that when I create a DLL (PYD), and try to import it, I get a corruption error.
http://developer.nokia.com/community/discussion/search.php?s=4ca073fd1680fe19509412d0ae4d9d00&searchid=1953317
CC-MAIN-2014-10
en
refinedweb
This guide explains how you can quickly get started issuing queries to the Earth Engine REST API from Python using Google Colab. The same concepts apply to accessing the API from other languages and environments. Note: The REST API contains new and advanced features that may not be suitable for all users. If you are new to Earth Engine, please get started with the JavaScript guide. Before you begin Follow these instructions to: - Apply for Earth Engine - Create a Google Cloud project - Enable the Earth Engine API on the project - Create a service account Set up your Colab notebook If you are starting this quickstart from scratch, you can create a new Colab notebook by clicking NEW NOTEBOOK from the Colab start page and enter the code samples below into a new code cell. Colab already has the Cloud SDK installed. This includes the gcloud command-line tool that you can use to manage Cloud services. Alternatively, run the demo notebook from the button at the start of this page. Authenticate to Google Cloud The first thing to do is login so that you can make authenticated requests to Google Cloud. In Colab, you can run: PROJECT = 'my-project' !gcloud auth login --project {PROJECT} (Or if you're running locally, from a command line, assuming you have the Cloud SDK installed:) PROJECT='my-project' gcloud auth login --project $PROJECT Accept the option to log in using your Google user account and complete the sign-in process. Obtain a private key file for your service account Before you can use the service account to authenticate, you must download a private key file. To do that in Colab, downloading to the notebook VM: SERVICE_ACCOUNT='foo-name@project-name.iam.gserviceaccount.com' KEY = 'my-secret-key.json' !gcloud iam service-accounts keys create {KEY} --iam-account {SERVICE_ACCOUNT} Or alternatively from command line: SERVICE_ACCOUNT='foo-name@project-name.iam.gserviceaccount.com' KEY='my-secret-key.json' gcloud iam service-accounts keys create $KEY --iam-account $SERVICE_ACCOUNT Accessing and Testing your Credentials You are now ready to send your first query to the Earth Engine API. Use the private key to get credentials. Use the credentials to create an authorized session to make HTTP requests. You can enter this into a new code cell of your Colab notebook. (If you are using command line, you will need to ensure that the necessary libraries are installed). from google.auth.transport.requests import AuthorizedSession from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file(KEY) scoped_credentials = credentials.with_scopes( [' session = AuthorizedSession(scoped_credentials) url = ' response = session.get(url) from pprint import pprint import json pprint(json.loads(response.content)) If everything is configured correctly, running this will produce output that looks like: {'id': 'LANDSAT', 'name': 'projects/earthengine-public/assets/LANDSAT', 'type': 'FOLDER'} Pick a Dataset You can search and explore available datasets using the Earth Engine Code Editor at code.earthengine.google.com. Let's look for some Sentinel 2 data. (If this is your first time using the Code Editor then you will be prompted to authorize it to access Earth Engine on your behalf when you sign in.) In the Code Editor, search for "sentinel" in search box at the top. Several raster datasets appear: Click on "Sentinel-2: MultiSpectral Instrument (MSI), Level-1C": Dataset description pages like this one include the critical information you need in order to use any dataset in the Earth Engine Public Data Catalog, including a brief description of the dataset, links to the data provider to get additional details, information about any usage restrictions that may apply to the dataset, and the dataset's Earth Engine asset ID. In this case we see on the right side of the window that this is an image collection asset whose path is COPERNICUS/S2. Query for Particular Images This Sentinel-2 dataset includes over two million images covering the world from 2015 through the present. Let's issue a projects.assets.listImages query against the image collection to find some data from April, 2017, with low cloud cover that includes a particular point in Mountain View, California. import urllib coords = [-122.085, 37.422] project = 'projects/earthengine-public' asset_id = 'COPERNICUS/S2' name = '{}/assets/{}'.format(project, asset_id) url = ' name, urllib.parse.urlencode({ 'startTime': '2017-04-01T00:00:00.000Z', 'endTime': '2017-05-01T00:00:00.000Z', 'region': '{"type":"Point", "coordinates":' + str(coords) + '}', 'filter': 'CLOUDY_PIXEL_PERCENTAGE < 10', })) response = session.get(url) content = response.content for asset in json.loads(content)['images']: id = asset['id'] cloud_cover = asset['properties']['CLOUDY_PIXEL_PERCENTAGE'] print('%s : %s' % (id, cloud_cover)) This script queries the collection for matching images, decodes the resulting JSON response, and prints the asset ID and cloud cover for each matching image asset. The output should look like: COPERNICUS/S2/20170420T184921_20170420T190203_T10SEG : 4.3166 COPERNICUS/S2/20170430T190351_20170430T190351_T10SEG : 0 Evidently there are two images over this point that were taken in this month and have low cloud cover. Inspect a Particular Image It looks like one of the matching has essentially zero cloud cover. Let's take a closer look at that asset, whose ID is COPERNICUS/S2/20170430T190351_20170430T190351_T10SEG. Note that all public catalog assets belong to the project earthengine-public. Here's a Python snippet that will issue a projects.assets.get query to fetch the details of that particular asset by ID, print the available data bands, and print more detailed information about the first band: asset_id = 'COPERNICUS/S2/20170430T190351_20170430T190351_T10SEG' name = '{}/assets/{}'.format(project, asset_id) url = ' response = session.get(url) content = response.content asset = json.loads(content) print('Band Names: %s' % ','.join(band['id'] for band in asset['bands'])) print('First Band: %s' % json.dumps(asset['bands'][0], indent=2, sort_keys=True)) The output should look like something like this: Band Names: B1,B2,B3,B4,B5,B6,B7,B8,B8A,B9,B10,B11,B12,QA10,QA20,QA60 First Band: { "dataType": { "precision": "INTEGER", "range": { "max": 65535 } }, "grid": { "affineTransform": { "scaleX": 60, "scaleY": -60, "translateX": 499980, "translateY": 4200000 }, "crsCode": "EPSG:32610", "dimensions": { "height": 1830, "width": 1830 } }, "id": "B1", "pyramidingPolicy": "MEAN" } The list of data bands corresponds to what we saw earlier in the dataset description. We can see that this dataset has 16-bit integer data in the EPSG:32610 coordinate system, or UTM Zone 10N. This first band has the ID B1 and a resolution of 60 meters per pixel. The origin of the image is at position (499980,4200000) in this coordinate system. The negative value of affineTransform.scaleY indicates that the origin is in the north-west corner of the image, as is usually the case: increasing y pixel indices correspond to decreasing y spatial coordinates (heading south). Fetching Pixel Values Let's issue a projects.assets.getPixels query to fetch some data from the high resolution bands of this image. The dataset description page says that bands B2, B3, B4, and B8 have a resolution of 10 meters per pixel. This script fetches the top-left 256x256-pixel tile of data from those four bands. Loading the data in the numpy NPY format makes it easy to decode the response into a Python data array. import numpy import io name = '{}/assets/{}'.format(project, asset_id) url = ' body = json.dumps({ 'fileFormat': 'NPY', 'bandIds': ['B2', 'B3', 'B4', 'B8'], 'grid': { 'affineTransform': { 'scaleX': 10, 'scaleY': -10, 'translateX': 499980, 'translateY': 4200000, }, 'dimensions': {'width': 256, 'height': 256}, }, }) pixels_response = session.post(url, body) pixels_content = pixels_response.content array = numpy.load(io.BytesIO(pixels_content)) print('Shape: %s' % (array.shape,)) print('Data:') print(array) The output should look like this: Shape: (256, 256) Data: [[( 899, 586, 351, 189) ( 918, 630, 501, 248) (1013, 773, 654, 378) ..., (1014, 690, 419, 323) ( 942, 657, 424, 260) ( 987, 691, 431, 315)] [( 902, 630, 541, 227) (1059, 866, 719, 429) (1195, 922, 626, 539) ..., ( 978, 659, 404, 287) ( 954, 672, 426, 279) ( 990, 678, 397, 304)] [(1050, 855, 721, 419) (1257, 977, 635, 569) (1137, 770, 400, 435) ..., ( 972, 674, 421, 312) (1001, 688, 431, 311) (1004, 659, 378, 284)] ..., [( 969, 672, 375, 275) ( 927, 680, 478, 294) (1018, 724, 455, 353) ..., ( 924, 659, 375, 232) ( 921, 664, 438, 273) ( 966, 737, 521, 306)] [( 920, 645, 391, 248) ( 979, 728, 481, 327) ( 997, 708, 425, 324) ..., ( 927, 673, 387, 243) ( 927, 688, 459, 284) ( 962, 732, 509, 331)] [( 978, 723, 449, 330) (1005, 712, 446, 314) ( 946, 667, 393, 269) ..., ( 949, 692, 413, 271) ( 927, 689, 472, 285) ( 966, 742, 516, 331)]] To select a different set of pixels from this image, simply specify the affineTransform accordingly. Remember that the affineTransform is specified in the image's spatial coordinate reference system; if you want to adjust the location of the origin in pixel coordinates instead, use this simple formula: request_origin = image_origin + pixel_scale * offset_in_pixels Generating a Thumbnail Image We can use a similar mechanism to generate an RGB thumbnail of this image. Instead of requesting data at its native resolution, we will specify a region and image dimensions explicitly. To get a thumbnail of the entire image, we can use the image's footprint geometry as the request region. Finally, by specifying the red, green, and blue image bands and an appropriate range of data values, we can obtain an attractive RGB thumbnail image. Putting this all together, the Python snippet looks like this (using the Colab IPython image display widget): url = ' body = json.dumps({ 'fileFormat': 'PNG', 'bandIds': ['B4', 'B3', 'B2'], 'region': asset['geometry'], 'grid': { 'dimensions': {'width': 256, 'height': 256}, }, 'visualizationOptions': { 'ranges': [{'min': 0, 'max': 3000}], }, }) image_response = session.post(url, body) image_content = image_response.content from IPython.display import Image Image(image_content) Here is the resulting thumbnail image:
https://developers.google.cn/earth-engine/reference/Quickstart
CC-MAIN-2022-21
en
refinedweb
Parallel and concurrent iterators Project description iterlib A library for easy iterator-based concurrency and parallelism. What is this? Have you ever been working with map or a generator and gotten annoyed with how slow lazy evaluation made some tasks? Have you ever wondered "could I run this generator in the background?" This library exists as the answer to that question. It implements asynchronous preloading generators and parallel map. Both the preloaders and the parallel map implementations support multiprocessing and threading as backends. How do I use it? Preload Here's a simple example of preloading a generator: from iterlib import thread_preload gen = (x**2 for x in range(100000)) preloaded_gen = thread_preload(gen, buffer_size=100) That's it! The generator will now preload up to 100 items in the background. When you call next(preloaded_gen), either directly or indirectly through a for statement, it will return values from the preloaded queue. Parallel Map Preloading generators has a significant limitation: it's impossible to use more than one background executor because access to iterators requires synchronization. However, most generators tend to be maps over other iterators, which opens an opportunity. We can't parallelize reads from an iterator, but we can parallelize function calls. Use one of threaded_map or process_map when you know your generator is a map: from iterlib import thread_map gen = [x for x in range(100000)] mapped_gen = thread_map(lambda x: x**2, buffer_size=100, num_workers=4) This will create an ItemizedMap named mapped_gen. When you call iter(mapped_gen), a generator will be created in the background that will preload up to 100 samples per worker (so 400 total in this example). Careful: These functions has different semantics than the regular Python map! If you mapover an indexable collection (like a list or numpy array) the returned ItemizedMapwill also be an indexable collection that lazily evaluates the mapfor each element you access! Only when iteris called (in a for loop or directly) will it return an asynchronous generator. 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/iterlib/
CC-MAIN-2022-21
en
refinedweb
Pandas Tricks – Calculate Percentage Within Group Pandas groupby probably is the most frequently used function whenever you need to analyse your data, as it is so powerful for summarizing and aggregating data. Often you still need to do some calculation on your summarized data, e.g. calculating the % of vs total within certain category. In this article, I will be sharing with you some tricks to calculate percentage within groups of your data. Prerequisite You will need to install pandas if you have not yet installed: pip install pandas #or conda install pandas I am going to use some real world example to demonstrate what kind of problems we are trying to solve. The sample data I am using is from this link , and you can also download it and try by yourself. Let’s first read the data from this sample file: import pandas as pd # You can also replace the below file path to the URL of the file df = pd.read_excel(r"C:\Sample Sales Data.xlsx", sheet_name="Sheet") The data will be loaded into pandas dataframe, you will be able to see something as per below: Let’s first calculate the sales amount for each transaction by multiplying the quantity and unit price columns. df["Total Amount"] = df["Quantity"] * df["Price Per Unit"] You can see the calculated result like below: Calculate percentage within group With the above details, you may want to group the data by sales person and the items they sold, so that you have a overall view of their performance for each person. You can do with the below : #df.groupby(["Salesman","Item Desc"])["Total Amount"].sum() df.groupby(["Salesman", "Item Desc"]).agg({"Total Amount" : "sum"}) And you will be able to see the total amount per each sales person: This is good as you can see the total of the sales for each person and products within the given period. Calculate the best performer Now let’s see how we can get the % of the contribution to total revenue for each of the sales person, so that we can immediately see who is the best performer. To achieve that, firstly we will need to group and sum up the “Total Amount” by “Salemans”, which we have already done previously. df.groupby(["Salesman"]).agg({"Total Amount" : "sum"}) And then we calculate the sales amount against the total of the entire group. Here we can get the “Total Amount” as the subset of the original dataframe, and then use the apply function to calculate the current value vs the total. Take note, here the default value of axis is 0 for apply function. [["Total Amount"]].apply(lambda x: 100*x/x.sum()) With the above, we should be able get the % of contribution to total sales for each sales person. And let’s also sort the % from largest to smallest: sort_values(by="Total Amount", ascending=False) Let’s put all together and run the below in Jupyter Notebook: df.groupby(["Salesman"])\ .agg({"Total Amount" : "sum"})[["Total Amount"]]\ .apply(lambda x: 100*x/x.sum())\ .sort_values(by="Total Amount", ascending=False) You shall be able to see the below result with the sales contribution in descending order. (Do not confuse with the column name “Total Amount”, pandas uses the original column name for the aggregated data. You can rename it to whatever name you want later) Calculate the most popular products Similarly, we can follow the same logic to calculate what is the most popular products. This time we want to summarize the sales amount by product, and calculate the % vs total for both “Quantity” and “Total Amount”. And also we want to sort the data in descending order for both fields. e.g.: df.groupby(["Item Desc"])\ .agg({"Quantity": "sum", "Total Amount" : "sum"})[["Quantity", "Total Amount"]]\ .apply(lambda x: 100*x/x.sum())\ .sort_values(by=["Quantity","Total Amount"], ascending=[False,False]) This will produce the below result, which shows “Whisky” is the most popular product in terms of number of quantity sold. But “Red Wine” contributes the most in terms of the total revenue probably because of the higher unit price. Calculate best sales by product for each sales person What if we still wants to understand within each sales person, what is the % of sales for each product vs his/her total sales amount? In this case, we shall first group the “Salesman” and “Item Desc” to get the total sales amount for each group. And on top of it, we calculate the % within each “Salesman” group which is achieved with groupby(level=0).apply(lambda x: 100*x/x.sum()). Note: After grouping, the original datafram becomes multiple index dataframe, hence the level = 0 here refers to the top level index which is “Salesman” in our case. df.groupby(["Salesman", "Item Desc"])\ .agg({"Total Amount" : "sum"})\ .groupby(level=0).apply(lambda x: 100*x/x.sum())\ .sort_values(by=["Salesman", "Item Desc","Total Amount"], ascending=[True, True, False]) You will be able see the below result which already sorted by % of sales contribution for each sales person. Conclusion This is just some simple use cases where we want to calculate percentage within group with the pandas apply function, you may also be interested to see what else the apply function can do from here.
https://www.codeforests.com/2020/07/18/calculate-percentage-within-group/
CC-MAIN-2022-21
en
refinedweb
i have tried the above on the picture however is saying it can find $store. - s.molinari last edited by Are you using Vuex? Is it installed properly? Scott - jannerantala last edited by This post is deleted! - jannerantala last edited by @thamibn I always set the Axios header after the login. Before the login all requests are made without the Bearer token: this.$ { username: this.email, password: this.password }) .then(res=> { localStorage.token = res.token; this.$ = 'Bearer ' + localStorage.token; }) if you use axios, you can try this. import axios from 'axios' setAxiosHeaders (token) { axios.defaults.headers.common['Authorization'] = 'Bearer ' + token } @s-molinari yes it is installed properly @jannerantala AND @KevinYang thanks you so much guys this worked!!!
https://forum.quasar-framework.org/topic/2988/how-can-i-set-a-default-header-with-the-jwt-token-in-all-the-request-after-login/5?lang=en-US
CC-MAIN-2022-21
en
refinedweb
Acceptance Tests To create an acceptance test, run ember generate acceptance-test <name>. For example: ember g acceptance-test login This generates this file: import { test } from 'qunit'; import moduleForAcceptance from 'people/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | login'); test('visiting /login', function(assert) { visit('/login'); andThen(function() { assert.equal(currentURL(), '/login'); }); });('should add new post', function(assert) { visit('/posts/new'); fillIn('input.title', 'My new post'); click('button.submit'); andThen(() => assert.equal(find('ul.posts li:first').text(), 'My new post')); }); Test Helpers One of the major issues in testing web applications is that all code is event-driven,. test('should add new post', function(assert) { visit('/posts/new'); fillIn('input.title', 'My new post'); click('button.submit'); andThen(() => assert.equal(find('ul.posts li:first').text(), 'My new post')); });: export default Ember.Test.registerAsyncHelper( 'shouldHaveElementWithCount', function(app) { });: export default Ember.Test.registerHelper('shouldHaveElementWithCount', function(app, assert, selector, n, context) { const el = findWithAssert(selector, context); const count = el.length; assert.equal(n, count, `found ${count} times`); } ); // shouldHaveElementWithCount(assert, 'ul li', 3); Here is an example of an async helper: export default Ember.Test.registerAsyncHelper('dblclick', function(app, assert, selector, context) { let $el = findWithAssert(selector, context); Ember.run(() => $el.dblclick()); } ); // dblclick(assert, '#person-1') Async helpers also come in handy when you want to group interaction into one helper. For example: export default Ember.Test.registerAsyncHelper('addContact', function(app, name) { fillIn('#name', name); click('button.create'); } ); // addContact('Bob'); // addContact('Dan'); Finally, don't forget to add your helpers in tests/.jshintrc and in tests/helpers/start-app.js. In tests/.jshintrc you need to add it in the predef section, otherwise you will get failing jshint tests: { "predef": [ "document", "window", "location", ... "shouldHaveElementWithCount", "dblclick", "addContact" ], ... } In tests/helpers/start-app.js you need to import the helper file: it will be registered then. import Ember from 'ember'; import Application from '../../app'; import Router from '../../router'; import config from '../../config/environment'; import './should-have-element-with-count'; import './dblclick'; import './add-contact';
https://guides.emberjs.com/v2.3.0/testing/acceptance/
CC-MAIN-2022-21
en
refinedweb
- Creating Users - Step 2 - Getting the Signed In User - Step 3 - Run It Again - Step 4 - Wrap Up Step 1 - Creating Users In the previous step, we applied permissions to the User entity so that only users with the User role can create entries. This is generally secure, but we want to enable new users to also create an account. Instead of modifying the endpoint for creating a user, we will build a new endpoint specifically allowing a new user to be created. Open server/src/auth/auth.service.tsin your IDE. In the AuthServiceclass you'll see that there already exists a method, login, that validates a user and, if it is a valid user, returns an access token. Here we will add a method to enable the users to sign up. Copy the below method after the loginmethod, and take the time to read through the comments to get a better understanding of what this code does. async signup(credentials: Credentials): Promise<UserInfo> { // Extract the username and password from the body of the request const { username, password } = credentials; // Here we attempt to create a new user const user = await this.userService.create({ data: { username, password, roles: ['todoUser'], // Here we assign every new user the `Todo User` role }, }); // If creating a new user fails throw an error if (!user) { throw new UnauthorizedException("Could not create user"); } // Create an access token for the newly created user //@ts-ignore const accessToken = await this.tokenService.createToken(username, password); // Return the access token as well as the some details about the user return { accessToken, username: user.username, roles: user.roles, }; } With the logic in place to create a new user, a new endpoint needs to be created in the AuthController. Open server/src/auth/auth.controller.tsand copy the following method into the AuthController. Something that may look different if you haven't had exposure to TypeScript is this: @Post("signup"). The POSTendpoint, with the path of @Post("signup") async signup(@Body() body: Credentials): Promise<UserInfo> { return this.authService.signup(body); } Finally, open server/src/auth/auth.resolver.tsand copy the following method into the AuthResolverclass. Like above, this method also is using a decorator, specifically a Mutationdecorator. This is used to set up the @Mutation(() => UserInfo) async signup(@Args() args: LoginArgs): Promise<UserInfo> { return this.authService.signup(args.credentials); } Step 2 - Getting the Signed In User Besides allowing for new users to be created, we also want to be able to get information about the user currently signed in. Open server/src/auth/token.service.ts. Here the TokenServiceclass is exported and is responsible for creating JWT tokens when a user signs in. The JWT token is the access token that authorizes our application to make requests to our backend and stores the username of the current user. We will want to be able to extract the username to find them in the Userentity. So add the following method to this class: /** * @param bearer * @returns the username from a jwt token */ decodeToken(bearer: string): string { return this.jwtService.verify(bearer).username; } Return to server/src/auth/auth.service.tsand replace the imports at the top of the file with this: import { Injectable, UnauthorizedException, NotFoundException, } from "@nestjs/common"; // @ts-ignore // eslint-disable-next-line import { UserService } from "../user/user.service"; import { Credentials } from "./Credentials"; import { PasswordService } from "./password.service"; import { TokenService } from "./token.service"; import { UserInfo } from "./UserInfo"; import { User } from "../user/base/User"; Add the new memethod to the AuthServiceclass. This method will take the authorization header of an HTTP request, decode the JWT token to get the usernameof the current user, and then fetch and return the user object belonging to the user. To make this request via an HTTP call or a GraphQL query, we'll need to expose it in the AuthControllerand AuthResolveras we did with the async me(authorization: string = ""): Promise<User> { const bearer = authorization.replace(/^Bearer\s/, ""); const username = this.tokenService.decodeToken(bearer); const result = await this.userService.findOne({ where: { username }, select: { createdAt: true, firstName: true, id: true, lastName: true, roles: true, updatedAt: true, username: true, }, }); if (!result) { throw new NotFoundException(`No resource was found for ${username}`); } return result; } Open server/src/auth/auth.controller.tsand replace the imports at the top of the file with below. This method uses the Getdecorator, meaning it's for GETrequests as it's only used to fetch data. There are two other new decorators attached to this method as well: ApiBearerAuthand ApiOkResponse. While neither of them is necessary, they allow for the UI used to read our documented endpoints to show meaningful data for this endpoint. It says that a request to this endpoint must be authorized, that way we can get the JWT access token. Also, we are defining what type of object is being returned by this request; a Userobject. import { Body, Controller, Post, Get, Req } from "@nestjs/common"; import { ApiBearerAuth, ApiOkResponse, ApiTags } from "@nestjs/swagger"; import { Request } from "express"; import { AuthService } from "./auth.service"; import { Credentials } from "./Credentials"; import { UserInfo } from "./UserInfo"; import { User } from "../user/base/User"; Add the new memethod to the AuthControllerclass. @ApiBearerAuth() @ApiOkResponse({ type: User }) @Get("me") async me(@Req() request: Request): Promise<User> { return this.authService.me(request.headers.authorization); } Open server/src/auth/auth.resolver.tsand replace the imports at the top of the file with this: import * as common from "@nestjs/common"; import { Args, Mutation, Query, Resolver, Context } from "@nestjs/graphql"; import { Request } from "express"; import * as gqlACGuard from "../auth/gqlAC.guard"; import { AuthService } from "./auth.service"; import { GqlDefaultAuthGuard } from "./gqlDefaultAuth.guard"; import { UserData } from "./userData.decorator"; import { LoginArgs } from "./LoginArgs"; import { UserInfo } from "./UserInfo"; import { User } from "../user/base/User"; Add the new memethod to the AuthResolverclass. @Query(() => User) async me(@Context('req') request: Request): Promise<User> { return this.authService.me(request.headers.authorization); } Step 3 - Run It Again With the necessary updates to our backend in place let's spin up the backend and explore our self-documented REST endpoints. Run the following command: npm run start:backend Once the backend is running, visit and scroll down to the authsection. A new POSTendpoint, /api/signup, will appear. The endpoint can be tested right there in the browser. Click the endpoint to show more details, then click Try it out. Change the value of usernameand passwordto any string value and click Execute. After clicking Execute, scroll down to see the result of the request. Step 4 - Wrap Up We will eventually need to make a few more changes to our backend, but now users can create an account as well as sign in with their existing account. Check back next week for step four, or visit the Amplication docs site for the full guide now! To view the changes for this step, visit here. Discussion (0)
https://dev.to/amplication/amplication-react-adding-custom-endpoints-3ipm
CC-MAIN-2022-21
en
refinedweb
getFromFile Signature def getFromFile(fileName: String)(implicit resolver: ContentTypeResolver): Route def getFromFile(file: File)(implicit resolver: ContentTypeResolver): Route def getFromFile(file: File, contentType: ContentType): Route Description Allows exposing a file to be streamed to the client issuing the request. The unmatchedPath (see extractUnmatchedPath) of the RequestContext RequestContext is first transformed by the given pathRewriter function, before being appended to the given directory name to build the final file name. To files from a given directory use getFromDirectory. import akka. import ContentTypeResolver.Default val route = path("logs" / Segment) { name => getFromFile(s"$name.log") // uses implicit ContentTypeResolver } // tests: Get("/logs/example") ~> route ~> check { responseAs[String] shouldEqual "example file contents" } - Java source import static akka. import static akka. final Route route = path(PathMatchers.segment("logs").slash(segment()), name -> getFromFile(name + ".log") ); // tests: testRoute(route).run(HttpRequest.GET("/logs/example")) .assertEntity("example file contents");
https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/file-and-resource-directives/getFromFile.html
CC-MAIN-2022-21
en
refinedweb
JSR-330: Using reflexivity to auto-inject Introduction Kodein-DI offers a module that implements reflexivity injection based on the JSR-330 javax.inject.* annotations. There are two reasons to use this module: You are moving a code base from a Java injection library (such as Guice or Dagger) and want the Java code to work the same while there still is injected java code. You want to easilly use Kodein-DI in a Java code. That’s it! Using this module with Kotlin code means adding a lot of reflexivity at run-time that can easily be avoided in Kotlin (but not in Java). Install With Maven <dependency> <groupId>org.kodein.di</groupId> <artifactId>kodein-di-jxinject-jvm</artifactId> <version>7.8.0</version> </dependency> JavaX injections Constructor injection di.jx in Kotlin, or Jx.of(di) in Java. val controller = di.jx.newInstance<MyJavaController>() MyJavaController controller = Jx.of(di).newInstance(MyJavaController.class); Field injection You can inject fields of a class by annotating them with @Inject. public class MyJavaController { @Inject Connection connection; @Inject FileSystem fs; /* ... */ } You can then inject existing instances of such classes by using di.jx in Kotlin, or Jx.of(di) in Java. val controller = MyJavaController() di.jx.inject(controller) MyJavaController controller = new MyJavaController(); Jx.of(di).inject(controller); Method injection You can have @Inject annotated method be called at injection. public class MyJavaController { @Inject public setIO(Connection connection, FileSystem fs) { /* ... */ } /* ... */ } You know the drill, use di.jx in Kotlin or Jx.of(di) in Java the exact same way as for field injection. Being specific Qualifiers annotations javax.inject libraries use the concept of "qualifier annotations", which serves the same purpose as DI’s tag system. The @Named annotation is a qualifier provided by default, and is supported by default in Kodein-DI-JxInject. In Java, any field or method / constructor parameter annotated with @Named("whatever") will use the String value as tag. public class MyJavaController { @Inject @Named("SQL") Connection connection; (1) @Inject setConnection(@Named("SQL") Connection connection) { /*...*/ } (2) } <1>: Field injection. <2>: Method injection. To inject the connection field, DI will essentially retrieve as di.instance<Connection>(tag = "SQL"). For any other qualifier annotation, you need to provide a function that will transform a qualifier annotation to a tag. val di = DI { import(jxInjectorModule) /* Other bindings */ jxQualifier<MyQualifier> { MyTag(it.value) } (1) } <1>: Transforms a MyQualifier qualifier annotation into a MyTag DI tag. Using erased bindings If you need to inject erased binding, you can annotate the field or method / constructor parameter with the @ErasedBinding annotation. public class MyJavaController { @Inject @ErasedBinding List<Connection> connections; } Optionnal injection If you need to inject something only if it was bound (and set it to null otherwise), you can use the @OrNull annotation. public class MyJavaController { @Inject @OrNull Connection connectionOrNull; } Provider & Factory injection You can inject a provider, either by using javax.inject.Provider or kotlin.jvm.functions.Function0. Note that if you are using the latter, you need to use the @ProviderFun annotation. public class MyJavaController { @Inject Provider<Connection> connectionJXProvider; @Inject @ProviderFun Function0<Connection> connectionKotlinProvider; } To inject a factory, you need to use kotlin.jvm.functions.Function1 annotated with @FactoryFun. public class MyJavaController { @Inject @ProviderFun Function1<String, Connection> connectionFactory; }
https://docs.kodein.org/kodein-di/7.8/extension/jsr330.html
CC-MAIN-2022-21
en
refinedweb
public class ResourceBundleViewResolver extends AbstractCachingViewResolver implements Ordered, InitializingBean, DisposableBean ViewResolverimplementation that uses bean definitions in a ResourceBundle, specified by the bundle basename. The bundle is typically defined in a properties file, located in the classpath. The default bundle basename is "views". This ViewResolver supports localized view definitions, using the default support of PropertyResourceBundle. For example, the basename "views" will be resolved as class path resources "views_de_AT.properties", "views_de.properties", "views.properties" - for a given Locale "de_AT". Note: This ViewResolver implements the Ordered interface in order to allow for flexible participation in ViewResolver chaining. For example, some special views could be defined via this ViewResolver (giving it 0 as "order" value), while all remaining views could be resolved by a UrlBasedViewResolver. ResourceBundle.getBundle(java.lang.String), PropertyResourceBundle, UrlBasedViewResolver suffixes. For example, a base name of "views" might map to ResourceBundle files "views", "views_en_au" and "views_de".enames(java.lang.String...), ResourceBundle.getBundle(String), ResourceBundle.getBundle(String, Locale) public void setBasenames(String... basenames) ResourceBundleconventions. The default is a single basename "views". ResourceBundle supports different locale suffixes. For example, a base name of "views" might map to ResourceBundle files "views", "views_en_au" and "views_de". The associated resource bundles will be checked sequentially when resolving a message code. Note that message definitions in a previous resource bundle will override ones in a later bundle, due to the sequential lookup.ename(java.lang.String), ResourceBundle.getBundle(String),(String defaultParentView) ResourceBundle. This avoids repeated "yyy1.(parent)=xxx", "yyy2.(parent)=xxx" definitions in the bundle, especially if all defined views share the same parent. The parent will typically define the view class and common attributes. Concrete views might simply consist of a URL definition then: a la "yyy1.url=/my.jsp", "yyy2.url=/your.jsp". View definitions that define their own parent or carry their own class can still override this. Strictly speaking, the rule that a default parent setting does not apply to a bean definition that carries a class is there for backwards AbstractCachingViewResolver Subclasses are not forced to support internationalization: A subclass that does not may simply ignore the locale parameter. loadViewin class AbstractCachingViewResolver viewName- the name of the view to retrieve locale- the Locale to retrieve the view for nullif not found (optional, to allow for ViewResolver chaining)
https://docs.spring.io/spring-framework/docs/5.2.10.RELEASE/javadoc-api/org/springframework/web/servlet/view/ResourceBundleViewResolver.html
CC-MAIN-2022-21
en
refinedweb
Weekly Challenge #1 Good Morning/Afternoon/Evening/Night to all beautiful replers! Today we are starting something very requested set of events. That's right! TODAY WE START WEEKLY CHALLENGES ONCE AGAIN! For the new users who were not around the last time, we were hosting these. These are short coding challenges that you are required to finish within 1 week. A new challenge is posted every weekend and you have until the next challenge is posted, to finish that challenge. At the end of every month, the total score of the 4 challenges held within that month is your score. The one with the highest score at the end of every month will be awarded free replit hacker plan! To post your submission, just publish your repl onto apps and make sure to include the tag #weekly{n} and replace {n} with the number of the weekly challenge in the title. For example, for the submission to this weekly challenge, publish the repl that contains your submission on apps and include the tag weekly1. More guidelines - You are allowed to make only 1 submission. Only submit after you're completely sure about submitting your submission. Your score won't be updated once your submission is scored. - If there is any sort of condition in which your submission does not satisfy the challenge's requirement, its score will be 0. And that's it! Now, let's get back to this week's weekly challenge. SQUARE ROOT! Inspired by the last year's first challenge, you have to write a program that finds a number's square root. BUT, as usual, with a twist! You are not allowed to use the arithmetic operators *and /(some languages use these for operations other than multiplication and division so they're fine there). You can also not use any external libraries, or the square root functions of any internal libraries of any language you might be using, or any special square root or square operators specific to your language. Same goes for exponentiation operators/pre-defined functions - not allowed. It is also fine if your program cannot find the square root in case the number is not a perfect square, the minimum requirement is for the program to be able to detect at least the square roots of perfect squares. Note that first your output is judged and only if it can be figured out without having to look at the code, will the code be judged. Basically, you just have to add prompts that tell the user what to enter and what each value is. For example: This is wrong > 25 5 This is right Please enter a number: 25 The square root of 25 is 5. If you have any further questions, you can ask them via the comments section, and if you don't, I would still recommend going through the comments section as they may contain some extra information. The criteria for scoring is subjective but there are points for creativity, uniqueness, clean code, etc. Also, you may find @DynamicSquid hosting these alongside me so just know that those are official too and you will be getting scores for those. Good luck to all the replers, have fun and hack away! @JeffreyChen13 You can do multiplication and exponents using addition. eg: function mult(a, b) { let result = 0; for (let i = 0; i < a; i++) result += b; return result; } console.log(mult(0, 6)); // -> 0 console.log(mult(6, 5)); // -> 30 console.log(mult(9, 9)); // -> 81 @JeffreyChen13 In python: def mult(a, b): result = 0 for i in range(a): result += b return result print(mult(0, 6)); # -> 0 print(mult(6, 5)); # -> 30 print(mult(9, 9)); # -> 81 @MattDESTROYER Haha yes! I thought of that. It is multiplying but in the way of repeated addition. I thought of that too, just working on the Pygame parts in my code : ) @JeffreyChen13 Yep, you got it. Nice :) You can even do long division manually, I used these tricks in my project. @JeffreyChen13 Just repeated addition in a for loop, I did it like this: def square(root): sum = 0 for i in range(root): sum += root return root @MattDESTROYER And to say, you really don't need that extra parameter b, because a and b are the same thing, you can just substitute b with a! Clean code there, yay! def mult(a): result = 0 for i in range(a): result += b return result @JeffreyChen13 The parameter b was to enable you to do multiplication as well as squares. To be honest I think I recreated all the operators in my project manually lol. I also took a different approach to getting square roots to everyone else as far as I can tell. @FlaminHotValdez You're really enjoying low-key flexing on everyone that you found such a unique solution, aren't you :P @RayhanADev Not Babylonian. I don't think the method has a name, it's just based on logic. You can easily derive the result from simple algebra. (Ik this coz we used the same method) I gave an explanation on my spotlight page if you want to see it. @kannibalistic Yeah. Don't worry, it's rare for plagiarism to happen. And if it does, just let me know :) Also for your scores, you'll get a comment on your repl once it has been marked @LavernieChen No, if you move top to the post, today it will say "Posted 4 days ago" only if you live right now in America PST haha, if you are in another time zone, please convert, which means it would have started at July 1 (in my time zone), so it must be due at July 8. @JeffreyChen13 Haha, Yes only in america not sure if time zone in america matters, should be same day @cuber1515 Do you have discord? Just DM Drone the submission. Or reply to my comment with your submission Hey, for C++ am I allowed to include 'iostream' or that other library that imports the printf statement? Also, when is the submission date. @Whippingdot Yes you can use that library, and the due date is anytime between when you publish to apps and the next challenge good cause i deleted my python one when i learned that you could only submit it in one language :( @FlaminHotValdez @DynamicSquid so you can't use it in any way where it will be dividing or multiplying something, string or integer? Is hard-coding the solutions allowed? e.g a single massive object with key-value pairs of perfect squares and their square roots xD @EducatedStrikeC well, you'd need an infinite object, as the set of perfect squares is infinite... @TheDrone7 @EducatedStrikeC the other option would be to use psychic powers and predict exactly which numbers will be tested, and hard-code those only. @TheDrone7 great, thanks, I wasn't sure if it might be banned because idk if it uses /behind the scenes I made a version in python, not sure if it fits requirements though, still working on it I'm confused @TheDrone7 , So you can't add multiplication or division to put in your code? @DEANKASOZI This doesn't require advanced programming knowledge-just your brain! Basic knowledge should be all that's necessary @FlaminHotValdez ik, im trying to figure it out with my brain. i mean, im pretty sure im on the right track, though it depends on the answer for this question: for python, can we use the "pow(x, y)"? where's the frontend part ew frontend @Lord_Poseidon What's wrong with frontend? .-. @MrVoo nah I just suck at it @Lord_Poseidon 😭 @Bookie0 frontend requires knowledge of several specific languages/libraries, this requires nothing but your brain @FlaminHotValdez precisely @FlaminHotValdez idk, frontend seems easier for me but ¯\_(ツ)_/¯ @Bookie0 yeah but it requires knowledge of specific things. This challenge requires your brain and only the most basic programming knowledge(variables, loops, if, input/output). Hmm.. I do know those basics, but I just can't think of something lol (most likely because this week I've been rahter distracted and away). Oh well! :D @FlaminHotValdez
https://replit.com/talk/announcements/Weekly-Challenge-1/142232
CC-MAIN-2022-21
en
refinedweb
Core Challenge 4: Create a negative pickup This challenge was a lot more complex than I was expecting. The idea is simple enough, create a powerup with negative consequences. A friend suggested have the enemies create ‘homing lasers’ for a short time and I thought that was a great idea so went with that. After creating the powerup image, I gave it an id of -1 and prefabbed it as well as throwing it into the spawn queue. If you’ve been following the powerup programming, you’ll be pretty familiar with implementation, but since this deals with Enemy ships and not the player, we’ll be modifying enemy code as well as the game manager since this is a timed event, we just want the enemies shooting homing missiles for only around 7 seconds. So we pick our negative powerup up. It will run through the code and hit our modular switch statement: What’s this? We’re calling something in the game manager? Indeed we are! and this was made possible via making the game manager a singleton. A singleton is what it says it is. Since there’s only going to be one game manager in the entire game, we make a singleton out of it and it makes it easy for other classes to access it as you can see by just using the name and “Instance”. As a bonus in this article, here’s a basic singleton pattern using the GameManager as an example: You first make a static variable of GameManager type and assign the name _instance to it. Static variables assure that the variable is available instantly across your program as it’s a member of the class now instead of just an object, meaning you can just access the class directly without the need of importing a gameobject into your script. You do that with the second half of this pattern in creating a public static of the GameManager type and put it into a variable called Instance with a capital I. It gets a little convoluted, but in the Awake function, _instance becomes the entire class with _instance = this. _instance then gets returned whenever it’s accessed through the public Instance. However if for whatever reason a new GameManger gets instantiated, it will be immediately destroyed when it’s discovered another already exists. It may be a little confusing at first, but what you need to know is this gives your class a level of protection with the public class so no outside classes can make modifications to the class. In short, instead of assigning a game object to a variable, and then using GetComponent<> to access the class, you can now just use: GameManage.Instance. to access anything inside of it! And that’s in ANY class! We also set a new variable, _negativePowerUpActivated to false. Remember since GameManager.Instance is available anywhere, it means GameManager.Instance._negativePowerUpActivated will be too. I’m sure you see where this is going. :) So let’s move on to the function being called in the GameManager: Ok, So the powerup calls ActivateNegativePowerup1, this then starts a corotuine called TemporaryHomingLasers. So far so good! So all that’s happening is it’s setting a boolean called _negativePowerupActivated to true, waiting 7 seconds, and then changing it back to false. Who would need to know the negative powerup’s been activated? Since the lasers will be changing behavior, we’ll enter the laser code. In the Start() function, we first tell the laser it will only have a lifespan of 5 seconds before self destructing with a Destroy(gameObject) inside of the DestroyLasers function. We then do a simple if check to see if the negative powerup’s been activated using the GameManager.Instance._negativePowerupActivated boolean directly! Cool, huh? Next, we assign the player object into a holding variable since we’ll need to know his position. the next variable, _laserHomingDirection takes the playerposition, subtracts our position and normalizes the distance. In a nutshell, we keep the direction of the player but not its distance. We just want to know what angle to shoot, everything else is irrelevant. Next I created a variable called _laserDirection which will be used in the MoveDown function which merely has a skeleton transform.Translate function inside. Depending on the negative powerup, we choose either a homing laser, or a laser that just moves down. And that’s it! It seems like it’s a complex feature, and it kind of is, but if you break things down into simple English pseudocode as recommended in best practices, the code does practically write itself! Here it is in action, looks like we need to tweak the game a bit but it works!
https://stevethedragon.medium.com/core-challenge-4-create-a-negative-pickup-147bdbc11d35?source=post_internal_links---------3-------------------------------
CC-MAIN-2022-21
en
refinedweb
is there any way to have two seperate def forward, functions. I am asking because I want to create two seperate run throughs of my network which are slightly different from one another. If there is a simpler way to do this please feel free to share, the two seperate forward functions just seemed the most obvious path. You could use one forward method with a condition calling two other functions or just running different code: def forward(self, x): if cond: output = forward1(x) # or output = your calculation ... else: output = forward2(x) # or output = your calculation ... return output
https://discuss.pytorch.org/t/two-seperate-def-forward-calls/14402
CC-MAIN-2022-21
en
refinedweb
Objective C Interview Questions and Answers Most Frequently Asked Objective C Interview Questions. Objective-C was created by Tom Love and Brad Cox at their company Stepstone in the early 1980s. Apple released Objective-C 2.0 at the Worldwide Developers Conference in 2006. It is its latest version. A protocol announces a programmatic interface that a class chooses to implement. It enables two classes that are related by inheritance to “talk” with each other in order to accomplish a goal.. #import function ensures a file is included only once so that you do not have a problem with recursive include. import is a super set of include and it ensures file is included once. NSMutableArray is the subclass of NSArray and they both manage collections of objects known as arrays. NSArray is responsible for creating static arrays, whereas NSMutableArray is responsible for creating dynamic arrays. The object is a collection of as an array or set of Cocoa classes that may include the collection classes. This collection of classes adopts the NSFastEnumeration protocol. This protocol can be used to retrieve elements that are held by an instance by using a syntax that is similar to a standard C for loop. Look at this instance: NSArray *anArray = // get an array; for (id element in anArray) { /* code that acts on the element */ } @synthesize creates getter and setter for the variables and allows you to specify attributes for variables. When you @synthesize the property to the variable, you generate getter and setter for that variable. This is how you call a function: [className methodName] For announcing methods in same class, use this: [self methodName] The dot syntax is a shortcut for calling getter and setter. You can use this: [foo length] foo.length are exactly the same, as are: [foo setLength:5] foo.length = 5 NSObject is the root class from which a lot of other classes inherit. When an object encounters another object, it interacts using the basic behavior defined by the NSObject description. Atomic is the default behavior that ensures the present process is completed by the CPU. Non-Atomic is not the default behavior and may result in unexpected behavior.. KVC stands for Key-Value-Coding. It refers to accessing a property or value using a string. id someValue = [myObject valueForKeyPath:@”foo.bar.baz”]; Which could be the same as: id someValue = [[[myObject foo] bar] baz]; KOC stands for Key-Value-Observing. It allows programmers to observe changes in property or value. In order to observe a property using KVO, you should identify the property with a string. The observable object must be KVC compliant. [myObject addObserver:self forKeyPath:@”foo.bar.baz” options:0 context:NULL]; You can dealloc for memory management. Once an object “retainCount” reaches 0, a dealloc message is sent to that object. Never call dealloc on objects unless you call [super dealloc]; around the close of a overridden dealloc. (void)dealloc { [ivar release]; //Release any retained variables before super dealloc [super dealloc]; //Only place in your code you should ever call dealloc } Blocks are language-level features that are added to Objective C, C, and C++. Blocks allow you to create segments of code that can be passed to methods or functions as values. Syntax to define a block uses the caret symbol (^): NSLog(@”This is a block”); } ^{ Responder chain is a series of responder objects that are linked together. A chain starts with the first responder and ends with the app object. However, when the first responder is unable to handle an event, it forwards it to the next responder in the chain. - Well-tested and mature language - Documented frameworks. - Strong online support. - Works smoothly with C and C++. - Stable language. It is a pointer to any type, but unlike a void *, it points to an object. For instance, you add anything of type id to an NSArray as long as those objects are responding to retain and release it. @interface A: NSObject; @end @interface B : A @end Here, the init method is inherited from A to B. However, the method has a different return type in both classes. No. Objective-C does not support overloading, so you will need to use a different method.. Because it is a synchronous process. The idea of dispatch_once() is to perform a task only once, no matter how violent the threading becomes. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];You would write: // Code benefitting from a local autorelease pool. [pool release]; @autoreleasepool { // Code benefitting from a local autorelease pool. }
https://www.bestinterviewquestion.com/objective-c-interview-questions
CC-MAIN-2022-21
en
refinedweb
Example 1: Using a for loop The content of the file my_file.txt is honda 1948 mercedes 1926 ford 1903 Source Code def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 print(file_len("my_file.txt")) Output 3 Using a for loop, the number of lines of a file can be counted. - Open the file in read-only mode. - Using a for loop, iterate through the object f. - In each iteration, a line is read; therefore, increase the value of loop variable after each iteration. Example 2: Using list comprehension num_of_lines = sum(1 for l in open('my_file.txt')) print(num_of_lines) Output 3 - Open the file in read-only mode. - Using a for loop, iterate through open('my_file.txt'). - After each iteration, return 1. - Find the sum of the returned values.
https://www.programiz.com/python-programming/examples/line-count
CC-MAIN-2022-21
en
refinedweb
Technical Articles Install Gardener on Rancher Update 2022 Previously, I Install Gardener on Rancher, wondering what Gardener might add to Prepare your SAP Data Intelligence installation with Rancher. Coming from Make your SAP Data Hub Distributed Runtime work on the SUSE CaaS Platform, I had been leveraging SUSE Linux Enterprise Server to start with. Lately, I have been having also good experience with Ubuntu though, resulting in some additional optimizations described in this blog along the 5 steps: - Load Balancer - Vertical Pod Autoscaler - DNS Provider - Storage Class - Gardener Load Balancer I continue to leverage MetalLB on premise which is easy enough to install choosing the Helm option. Helm Ubuntu optimized sudo snap install helm --classic MetalLB helm repo add metallb helm install metallb metallb/metallb -f values.yaml Example values.yaml configInline: address-pools: - name: default protocol: layer2 addresses: - 192.168.2.128/32 Vertical Pod Autoscaler Gardener still requires a Vertical Pod Autoscaler that does not come with Gardener but it remains not difficult to install. git clone cd autoscaler/vertical-pod-autoscaler/ ./hack/vpa-up.sh DNS Provider Gardener requires External DNS Management for the DNS controller manager artefact. I continue to choose Clouflare DNS service, but since The DNSProvider resource of type cloudflare-dns is only implemented in gardener/external-dns-management, which currently is a hard dependency of g/g, I continue have to implement it manually. Additionally, I create a test DNSEntry. DNS controller manager git clone cd external-dns-management helm install charts/external-dns-management --generate-name --namespace=default --set configuration.identifier=garden Secret apiVersion: v1 kind: Secret metadata: name: cloudflare-credentials namespace: default type: Opaque data: CLOUDFLARE_API_TOKEN: <Your Cloudflare API token> DNSProvider apiVersion: dns.gardener.cloud/v1alpha1 kind: DNSProvider metadata: name: cloudflare namespace: default spec: type: cloudflare-dns secretRef: name: cloudflare-credentials domains: include: # this must be replaced with a (sub)domain of the hosted zone - <Your domain> DNSEntry apiVersion: dns.gardener.cloud/v1alpha1 kind: DNSEntry metadata: name: mydnsentry namespace: default spec: dnsName: "myentry.architectsap.de" ttl: 600 targets: - 192.168.2.128 There is a plan Move DNSProvider capabilities out of g/g though. Storage Class Gardener requires persistent storage. Previously, I Provision Volumes on Kubernetes and Nomad using Ceph CSI by Kidong Lee. However, lately I switched to Longhorn, that does not require another proprietary cluster but runs natively on Kubernetes instead and is better integrated with Rancher as well. kubectl apply -f kubectl patch storageclass longhorn -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' kubectl get storageclass Longhorn appears in my cluster respectively. From where I can reach the dashboard. Gardener Ubuntu optimized Given the above, installing Gardener is straight forward. git clone mkdir landscape cd landscape cp ~/.kube/config kubeconfig git clone " crop cd .. sudo su cd sow export PATH=$PATH:$PWD/docker/bin cd ../landscape sow order -A sow deploy -A sow url As a result, Gardener is running and I create a cluster in preparation for my SAP Data Intelligence installation on Gardener.
https://blogs.sap.com/2022/05/09/install-gardener-on-rancher-update-2022/
CC-MAIN-2022-21
en
refinedweb
- Advertisement Christopher CrainMember Content Count25 Joined Last visited Community Reputation189 Neutral About Christopher Crain - RankMember Login Server Question Christopher Crain posted a topic in Networking and MultiplayerI want to separate my login process from my game server, but I am trying to wrap my head around this... This is my understanding / thoughts on how to implement the login server. 1. The client connects to the login server. 2. The client provides username and password 3. The server authenticates the username and password. 4. The server stores a unique code in database for the username. 5. The server sends the account id and unique code to the client. 6. The client tries to connect game using the account id and unique code. 7. The Game Server validates the unique code is within the allotted time between login and game server connection. 8. Client is now connected to the Game Server. I may be completely off, since I have never done anything like this. Thoughts? Ideas? ISO quick max distance check Christopher Crain replied to Christopher Crain's topic in Math and PhysicsOk so here is the implementation I got working last night, there is one piece I didnt fully understand though and it might be wrong. float Velocity = 0.9f; public void ClientPositionUpdate(Vector3 ppu) { try { _timer.Stop(); float timeSinceLastUpdateInSeconds = ((float)_timer.Elapsed.TotalMilliseconds / 1000.0f); Vector3 diff = _currentPos - ppu; float maxDistance = _speedLimit * timeSinceLastUpdateInSeconds; float actualDifferenSquared = diff.LengthSquared(); float maxDistanceSquared = (maxDistance * maxDistance); if (actualDifferenSquared > maxDistanceSquared) { Console.SetCursorPosition(0, 15); Console.WriteLine(string.Format("Player might be cheating...{0} / {1}", actualDifferenSquared, maxDistanceSquared)); Console.SetCursorPosition(0, 4); } else { } _currentPos = ppu; _timer.Restart(); } catch (Exception ex) { } } private void SetSpeedLimit(float add) { _speedLimit = (Velocity + add) * 5.5f; } SetSpeedLimit(0.0f); So I set it up so that I could adjust the speed limit on the player in-case they got a buff that increased or decreased their velocity. So after tweaking the speed limit the 5.5f multiplier seems to catch the player if they somehow adjust their velocity on the client side without the server velocity being updated. I guess I should just leave it be, but I dont understand the whole 5.5f part. ISO quick max distance check Christopher Crain replied to Christopher Crain's topic in Math and PhysicsAwesome, thanks guys! I will try implementing this tonight. ISO quick max distance check Christopher Crain posted a topic in Math and PhysicsI am currently allowing the client to update the server of the players latest position updated every ~2 seconds. I am trying to extrapolate out a max distance the player can travel from the last update to the current position being reported. I tried doing a _currentPos * deltaTime * Velocity and some huge number comes out they would probably never be able to achieve. For example Current Position = (X=54, Y=1, Z=30) * 2.0f * 0.9f = I get number in the 200 range for X, Y dont care, Z is 144 ish. Any help would be appreciate thank! public void ClientPositionUpdate(Vector3 ppu) { float distance = Vector3.Distance(ppu, _currentPos); if(distance == 0.0) { } else { float maxDistance = <=== NEED help here. if(distance <= maxDistance) { } else { // flag for cheating... } } _currentPos = ppu; } Level Loading on the Server Christopher Crain replied to Christopher Crain's topic in Networking and MultiplayerAhh good point on tagging certain places in the zone, thanks. I think I will explore this path for the server. Level Loading on the Server Christopher Crain replied to Christopher Crain's topic in Networking and MultiplayerSorry hplus0603, the Client is created in Unity3D version 5 and I am using the Lidgren Network library to connect to a custom server built in a C# console application. I am trying to find the best approach to extract the geometry from the scenes I create in Unity3D into a file that my server can read. Currently I am exporting the terrain to a .obj file but I may see about just exporting just the triangles since the server doesn't care about textures. I want the server to do all the raycasting (line of sight) for spell casting and ranged combat, also have the server calculate the walkable areas for players / npc's via a navigational mesh (SharpNav). Has anyone used SharpNav? Are there any other navmesh libraries in C#? The setup I am aiming for for raycasting / walkable areas using the geometry file on the server is this the best approach? I love the way EQEmulator folks have the server implemented, so I would like to model mine in a similar way but in C#. () Level Loading on the Server Christopher Crain posted a topic in Networking and MultiplayerI just want to ensure I am going about this the right way, since I am still trying to wrap my head around all this. I guess this is more of a design question, but it's alot to do with multi-player / servers. 1. Create a scene in Unity and exporting the geometry to a file. - Done 2. Load the geometry file in my server code. - Done Things I am about to attempt, this is where I need to know if this is the correct approach? 3. Create a Navigational Mesh from the Geometry? I am about to test out SharpNav () 4. Use the Navigational Mesh and RayCasting for the players and npc's line of sight and walkable area's? winsock UDP not working Christopher Crain replied to lomateron's topic in Networking and MultiplayerSome things you may want to try: Allow the port to receive data from the outside world: You may want to just disable your firewall for testing purposes right now to ensure that is or isnt the issue. Try running the application for the server in "admin" mode as well. You may also want to download Wireshark to help with your debugging: Interpolation Issue Christopher Crain replied to Christopher Crain's topic in Networking and MultiplayerThanks for the replies, I will check out the article and code linked. The 160msec rate is that too much time between update packets? This game is not a FPS so I figured a little bit longer delay on position updates would be ok and then I would be able to balance the load of sending out state data on specific zones on different iterations. For example: on iteration 0 I would send out zone001 states, next server cycle (~16msec) send out zone002, next zone003 etc... Perhaps there is a better approach I am not sure, I am open to suggestions! Interpolation Issue Christopher Crain posted a topic in Networking and MultiplayerI am tweaking my client code to interpolate movements between the server position and the client's current position. This seems to work "ok" but I still notice a little bit a jitter when the NPC is being interpolated to his destination. Hopefully someone could inspect this code and see what I am doing wrong. I ported this from another post I found.. To test this I am setting up an NPC on the server side to move 0.3f every ~16 msec, BUT I send the position packet at ~160 msec. Perhaps this test case is wrong or inaccurate? Note : the "Update" method is manually called from an entity manager class every frame. using UnityEngine; using System.Collections; using SharedNetworkLibrary.Types; public class EntityType { public int ID { get; private set; } private GameObject _gameObject; private Vector3 _displayPosition; private Vector3 _latestPosition; private float _latestPositionTime; private string _currentAnimation = "idle"; private Vector3 _previousPosition; private bool _isMoving = false; private const float _interpolationPeriod = 0.3f; private Animation _animation; public EntityType(int id, GameObject gameObject) { ID = id; _gameObject = gameObject; _animation = _gameObject.GetComponentInChildren<Animation> (); } // Update is called once per frame public void Update () { if (_isMoving == true) { float t = 1.0f - ((_latestPositionTime - Time.time) / _interpolationPeriod); _displayPosition = Vector3.Lerp (_previousPosition, _latestPosition, t); } else { _displayPosition = _latestPosition; } _gameObject.transform.position = _displayPosition; } public void UpdateAnimation(string animation) { _currentAnimation = animation; } public void UpdatePosition(EntityStateType entityType) { if (entityType.IsMoving == true) { _isMoving = true; _latestPosition = new Vector3 (entityType.X, entityType.Y, entityType.Z); _latestPositionTime = Time.time + _interpolationPeriod; _previousPosition = _displayPosition; if(_animation.isPlaying == false) { if(_currentAnimation.Length > 0) { _animation.Play (_currentAnimation); } } } else { _isMoving = false; } } } [Visual C#] Help with passing an object between forms Christopher Crain replied to sp00kymulder's topic in For Beginners's ForumWell you could add a static class to hold character creation in and all form can access this data without having a reference. For example public static class CharacterCollection { public static Dictionary<string, Character> Characters = new Dictionary<string, Character>(); private static string _currentCharacter = string.Empty; static CharacterCollection() { } public static Character SelectCurrent() { if (Characters.ContainsKey(_currentCharacter) == true) { return Characters[_currentCharacter]; } return null; } public static void Add(Character character) { if(Characters.ContainsKey(character.Name) == false) { Characters.Add(character.Name, character); } else { Characters[character.Name] = character; } } public static bool SetCurrent(string name) { if (Characters.ContainsKey(name) == true) { _currentCharacter = name; return true; } return false; } } Usage: FormA: Character newPlayer = new Character("PlayerA", 1, 1); CharacterCollection.Add(newPlayer); CharacterCollection.SetCurrent(newPlayer.Name); FormB Character player = CharacterCollection.SelectCurrent(); This will give you the ability to navigate multiple forms without having to pass a reference to each form or the game, just grab it out of the collection. Sending 'command duration' from client to server Christopher Crain replied to sheep19's topic in Networking and MultiplayerThis article helped me understand some of this process, I ultimately decided I didnt need this type of protocol for my RPG. But this may help you Help Selecting a 3D Engine Christopher Crain replied to Christopher Crain's topic in Engines and MiddlewareThanks for the replies, I was able to find a terrain script to export the scene geometry. I may still look at the unreal tournament. Unity Help Selecting a 3D Engine Christopher Crain posted a topic in Engines and MiddlewareI am venturing into the 3D realm for creating a game idea I have but I am having difficulty selecting a 3D game engine. Hopefully someone can help guide my decision. Here is the criteria: - 3D Level / Scene Editor with the ability to export a vertices file (.map or similar) - Easily import Blender content (.fbx, .dae or .obj) - C# - User Interface with UI designer - Free or relatively cheap (under $200) I am leaning toward Unity 5 but I havent seen a way to generate a vertices file with unity yet for the scene. This will be needed for the server to test collisions and LOS. Thanks for your time. Packet safety Christopher Crain replied to rigel's topic in Networking and MultiplayerPerhaps we should analyze the data you are wanting to send from the client that you dont want to be injected? - Advertisement
https://www.gamedev.net/profile/220769-lakedoo23/
CC-MAIN-2019-22
en
refinedweb
Every business application interacts with a data source, which can be a relational database, object-oriented NoSQL database, an LDAP repository (Lightweight Directory Access Protocol), a file system, a web service SOAP or REST, or any other external system. Whatever the data sources are, the application must interact with these through CRUD (create, retrieve, update, and delete) operations, thus allowing to create, retrieve, update and delete objects of the same. There are several ways to utilize a data source, andits implementation may vary widely. For example, there are different types of SQL dialects depending on the technology, such as PostgreSQL and Oracle. Thus, the main objective standard Data Access Object (DAO) is to encapsulate access to the data source providing an interface to the various other application layers to communicate with the data source. The rest of the article will discuss the DAO pattern, how it is implemented in the Java EE platform and what are the other types of technologies and standards that can be used to implement it. We will see in more detail how we can use JPA API, which helps a lot in implementing the DAO pattern. Standard Data Access Object The DAO pattern is defined in the book "Core J2EE Patterns" as: "the standard used to abstract and encapsulate all access to the data source DAO manages the connection to the data source to obtain and store information.." Through this abstraction and the data source encapsulation, the biggest problem that existed before its creation has been resolved and, therefore, the application is not dependent on the implementation of a specific data source. This decouples the business layer from the data source layer. Thus, if the source data changes, such as changing from an Oracle database for Postgree database, the decoupling significantly reduces any impact that could occur. It is unusual in the corporate world to change between suppliers of the same data source, such as an Oracle database for Postgree database. This happens a lot in government agencies looking for a major update in technology and switching to other emerging or free software. However, it is more common to change, for example, a database to an XML file system, or an LDAP repository, or to a web service. In this case, the gain is found to possess a DAO pattern in a software project. Another gain with this pattern is when the project has mocks and unit tests, in which the DAO pattern significantly helps keep the structured and clean code. Some developers also claim a gain in DAO pattern of use in the encapsulation of legacy storage systems or where it seeks to simplify access to complex implementations of data sources. Regarding the implementation of the DAO pattern is that this encapsulates CRUD operations on an interface that must be implemented by a concrete class. This interface could be mocked and easily tested, preventing a connection to the database, for example. As is known, the use of tests with mocks is easier and recommended than the database with integration tests, as these tend to mess the database, even if the data entered is removed, and do not offer simplicity and focus in the tests. Finally, the concrete implementation of DAO uses low-level APIs, such as JPA and Hibernate to perform CRUD operations. Implementation of the Standard DAO The implementation of the DAO standard involves several components, such as the DAO interface and its practical implementation, the plant (or Factory) DAO and DTO (Data Transfer Object), all optional. The DTO (Data Transfer Object) is a standard responsible for transporting the recovered or persisted data in a database through the logical layers of software. For example, to transfer a list of "User" objects with a user's information, such as your name, id and address, which were retrieved from a "Data Access Layer" to the layer "Web", the layer of "Service "would be responsible for transferring a DAO for DTO the requested data. Why the DTO is also referred to as a VO (Value Object), which is another well-known standard for Java developers. The book "Core J2EE Patterns" DTO defines as "responsible for carrying multiple elements containing information between software layers." Another advantage of DTO is that it reduces the number of remote requests by network applications that make calls many methods for enterprise beans. This therefore results in a significant improvement in performance. A very common situation in use of the DTO is when not all information returned by the database is needed in another software layer. For example, in cases where it is only necessary to display some information for a user on the Web layer. Thus, DTO reduces the search to bring only the necessary information by layer, thus optimizing the transfer of information through the layers. An API that can be important in implementing the DAO pattern is the JPA (Java Persistence API), which manages the interactions between applications and the data source, greatly reducing the time of developers who previously had to worry about these issues. JPA specifies how to access, persist and manage information between application objects and the data source. JPA does not perform the CRUD or any operation related to the information, this is just a set of interfaces and implementations necessary. However, an application server must provide support for its use. One of the novelties of the JPA in newer versions is that it now overwrites the old EJB 2.0 container-managed persistence (CMP) that was very complex and cumbersome, and rarely used. Why persistence frameworks such as Toplink and Hibernate, have been widely used to replace the CMP EJB?. With that came the specification of the JPA (released along with the EJB 3.0), in which were gathered all the qualities of the Toplink and Hibernate in a standard specification and official. The JPA is based on the concept of an entity (former entity bean EJB 2) which is an object capable of being persisted in a database. The big advantage is that an entity in JPA is a POJO (Plain Old Java Object) that its members are recorded and mapped to a field in the data source. Therefore its implementation is quite simple and clean. In Listing 1 is an example of an entity in JPA Listing 1. Example of an entity in JPA @Entity public class Movie { @Id @GeneratedValue private Long id; private String title; private String description; private Float price; public Movie() {} // getters e setters da classe public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } } This is a simple class with only three notes, which already makes it persistent. The class annotated with @Entity indicates that this should be treated as an entity class, and @Id and @Generated notes mark the id member as a self-generated ID field, as stated in the jargon of databases. This means that when the entity is persisted, the id field is automatically generated according to the rules of a field as self-manageable. If the data source is a database, then all the fields in this entity are persisted to the database table named Movie. It is not necessary any other annotation or implement any interface or class to indicate that the fields are persistent. Implementing the DAO pattern in the Java EE platform The implementation of the DAO standard Java EE platform is better assimilated by a more complete example. As an example, we can imagine that the data source is a relational database and we want to implement a movie rental store. First we start with the creation of an entity and annotate this class with appropriate annotations JPA, as shown in Listing 2. Listing 2. Example of an entity for the film class package com.mrbool.dataaccessobject; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQuery; @Entity public class Movie implements Serializable { private static final long serialVersionUID = -6580012241620579129 L; @Id @GeneratedValue private int id; private String title; private String description; private int price; //This annotation indicates that the attribute is not persistent @Transient private int runtimeId; public Movie() {} //getters and setters public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return this.price; } public void setPrice(int price) { this.price = price; } public int getRuntimeId() { return this.runtimeId; } public void setRuntimeId(int runtimeId) { this.runtimeId = runtimeId; } } The class is a simple POJO with the appropriate JPA annotations. The @Entity note in class indicates that the class should be treated as an entity and should be managed by a persistence provider. This class entity must obey some rules, such as having a constructor with no arguments, which must be public or protected, although it may also have other builders. An entity also needs a high-class level, or may not be an enum or interface and should not be a final class. Moreover, none of the persistent instance variables or its getters and setters methods may be ending. The organization must also implement the Serializable interface. The notes of the id attribute with @Id and @GeneratedValue mark the id attribute as a primary key and self-generated. All entities must have a primary key, which can be a single attribute or a combination of attributes. The primary key can be one of the following: any primitive type (byte, char, short, int, long), any Wrapper class of primitives (Byte, Character, Short, Integer, Long), any array of primitives or wrapper (byte [], Byte [], short [] Shot [], int, Integer [], long [], long [], etc.) or any Java type (String, BigInteger, Date). All the entity class attributes are automatically mapped to the fields of the same name in the database Movie table, minus the annotated fields @Transient. Thus, the entity's id attribute is mapped to the table id field in the database and so it is with the other fields of the entity. In the code in Listing 3 one DAO interface is created that should define the basic CRUD methods and some that may be useful. Listing 3. Example of the DAO interface package com.mrbool.dataaccessobject; import java.util.List; public interface MovieDAO { public void addMovie(Movie movie); public Movie getMovie(int id); public void removeMovie(int id); public void updateMovie(Movie movie); public List getAllMovies(); } The Listing 4 code has the practical implementation of DAO interface displayed. In this code, we have the implementation of CRUD, which can be noted that the constructor accepts an instance of EntityManager, which is associated with a persistence context that is defined in the file persistence.xml. The EntityManager API provides functionality to create, remove, and can create queries. It is noteworthy that any transient field is not saved or retrieved from the database. Listing 4. Implementation of the DAO interface. package com.mrbool.dataaccessobject; import java.util.List; import javax.persistence.EntityManager; public class MovieDAOImpl implements MovieDAO { private EntityManager em; public MovieDAOImpl(EntityManager em) { this.em = em; } @Override public void addMovie(Movie movie) { em.persist(movie); } @Override public Movie getMovie(int id) { return getAllMovies().get(id); } @Override public void removeMovie(int id) { em.remove(getMovie(id)); } @Override public void updateMovie(Movie movie) { em.merge(movie); } @Override public List getAllMovies() { return em.createQuery("SELECT movie FROM Movie movie", Movie.class).getResultList(); } } In code of the Listing 5 has is an example of a DAO factory. The EntityManager is created and injected into this class and then passed as a constructor argument for criarMovieDAO method that creates the DAO object. Listing 5. Example of implementation of a factory DAO package package com.mrbool.dataaccessobject; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @ApplicationScoped public class MovieDAOFactory { @PersistenceContext(unitName = "moviePU") private EntityManager em; @Produces public MovieDAO criarMovieDAO() { // In MovieDAOImpl we pass the created Entity Manager return new MovieDAOImpl(em); } } Existing in the application entities are persistence unit calls, which are defined in the persistence.xml configuration file. This file should be in the "META-INF" application. The most significant elements of the persistence.xml file are: - Persistence Unit Name: where you can set a name of a persistence unit where several persistence units can be defined and selected at run time; - Persistence Unit Transaction: In a Java SE application, the default transaction type is RESOURCE_LOCAL, while in the Java EE environment the default transaction type is JTA. This indicates that the EntityManager participates in the transaction; - Provider: This element identifies the class that provides the factory to create the EntityManager instance; - Class: Classes that are used in the application entities should be listed in the class element; - Property: Additional properties may be specified, such as connection properties to the database and persistence provider properties, as well as options to delete and create new tables. The EntityManager is associated with a persistence context that is defined in the persistence.xml file, as shown in the example in Listing 6. Listing 6. Example of the persistence.xml file org.eclipse.persistence.jpa.PersistenceProvider jdbc/sample com.mrbool.dataaccessobject.Movie The source specific date is set in the persistence.xml file. In this example, we set the database Derby using Eclipse Link Provider. The transaction was set to JTA type because this is a Java EE implementation. Additionally, an entity class called Film has been set. In this case, you must put all com.mrbool.dataaccessobject.Movie package. The client code is defined in the example in Listing 7. The client receives an instance of the injected DAO and use it to return all the movies. Listing 7. Example of client code using the default structure created DAO. package com.mrbool.dataaccessobject; import javax.ejb.Stateless; import javax.inject.Inject; import java.util.List; @Stateless public class Customer { @Inject MovieDAO movieDAO; public List getAllMovies() { return movieDAO.getAllMovies(); } } I hope you enjoyed the article..
http://mrbool.com/implementing-data-access-object-in-java-enterprise-edition/34228
CC-MAIN-2019-22
en
refinedweb
> Me and a team of 5 have been working on an app game for about 2 months but out of no where our coder up and disappeared, its been close to like 5 months now and what we can manage on our own is no comparison to what he could do. Is there a way that we could run those files on the project editor and continue work from a build game file and data or are we just screwed You won't be able to recover the source code from a built release version of a project. You had no source control management? No Backups? No access to the unity project? And if you had access to the unity project, why isn't the source code there? we sent him all the objects and art to work into it and he'd send us built versions for consulting and one day just stopped talking to us, thanks for all the comments but we've just moved on. The source could should be available unless he stripped everything and took it with him. Otherwise the ONLY way to reverse engineer anything is to look at the machine code and rebuild the code by translating that. This is an extremely high level topic that people will get paid a hole bunch of $ to do. So unless you can get your hands on that original source code.....yes your screwed. There is a reason why you cant do this, you know... for hacking and reselling a game etc Answer by nullgobz · Jul 31, 2015 at 12:28 AM Well there is one way to acually get the sourcecode but its not pretty. You could decompile the game dll file. Look in your game folder: [gamename]_Data/Managed/ For these dlls: Assembly-CSharp.dll -> for c# scripts Assembly-UnityScript -> for js scripts Open that file/files with a decomilation software like: dotPeek. If you use dotPeek, select the dll, namespace or "root namespace" right click a class and "decompile source" Also use source control in the future if you care about your project :) Best of luck! Yeah, it kinda sucks when a programmer ups and dissapears. :/ Answer by Bunny83 · Jul 31, 2015 at 12:40 AM The script source code uaually can be restored without much problems except it has been manually obfuscated. A Unity build doesn't compile to machine code as we use Mono. All your scripts are compiled to CIL code (common intermediate language). The best decompiler i know is ILSpy. It can view the classes in IL and can also decompile to C# or VB.NET. Asset files can partially be restored but you never get back to the original files. It also depends what kind of "build" you have. In standalong builds you can access the assemblies directly. An android apk file is actually just a zip file. So you can open it with most zip tools and extract the dlls. There are even solutions to "unpack" a webplayer create an agenda or timetable system? 1 Answer Facebook cannot find my Unity data file. 1 Answer Developing a 3d data editor 3 Answers PlayerPrefs.GetString returns wrong value 3 Answers How do you copy PersistentDataFolder between devices? 2 Answers
https://answers.unity.com/questions/1018427/is-there-a-way-to-reverse-engineer-a-built-project.html?sort=oldest
CC-MAIN-2019-22
en
refinedweb
In this Google flutter code example we are going to learn how to use IntrinsicHeight 'intrinsicheighticHeight(), ); } } intrinsicheight.dart import 'package:flutter/material.dart'; class BasicIntrinsicHeight extends StatelessWidget { //A widget that sizes its child to the child's intrinsic height. //This class is useful, for example, when unlimited height is available and you would like a child that would //otherwise attempt to expand infinitely to instead size itself to a more reasonable height @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("IntrinsicHeight Widget")), body: Center( child: IntrinsicHeight( child: Container( height: 100.0, width: 40.0, color: Colors.red, child: Container(color: Colors.blue, height: 50.0), ), ), ), ); } } If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.
https://inducesmile.com/google-flutter/how-to-use-intrinsicheight-widget-in-flutter/
CC-MAIN-2019-22
en
refinedweb
TYPE - displays the file contents command 1. Function: Display the contents of the ASCII file. 2. Type: Internal command. 3. Format: TYPE [drive:] [path] <file name> 4. Instructions for use: (1) shows the ASCII text file consisting of code, right. E lt, parameters, wildcards, split screen, ascii file, drive path, ascii text fileSeptember 8 1. Dbexport Download the database in ASCII mode. This command is used to migrate the database. Such as: command dbexport-o / informix / db_export stores7, database stores7 download / informix/db_export/stores7.exp directory. Database schema files sto logs, configuration parameters, conjunction, cr, database schema, directory database, model output, informix, rowid, chunks, ascii file, data recovery, chunk, catalog table, ascii mode, repair tool, consistency check, system catalog, cc check, cd checkJuly 4 Character DB2 Data Import (Import) Export (Export) (Load) The so-called DB2 data movement, including: 1. Data import (Import) 2. Data Export (Export) 3. Data load (Load) DB2 Import and load the relevant commands database table, database management system, quot quot, quot 15, ascii character, common interface, different systems, data stream, character stream, ascii file, db2 database, 15 quot, data export, delimiters, database management systems, relevant commands, delimited ascii, midwest chicago, stream line, atlantic 10September 10 View from the way the encoding of the document can be divided into ASCII files and binary code code of two files. ASCII files, also known as text files, such files when stored on disk corresponds to one byte per character, used to store the correspon utf 8, source file, byte, carriage return, binary code, ff, input and output, asc, character stream, ascii code, ascii file, decimal code, windows notepad, bf, big endian, reading material, rpg games, original concept, ascii files, physical signsJuly 15 Hex Edit command is used to select the active window of the edit mode. Is in hexadecimal and ASCII to switch between. ASCII-based file in edit mode is commonly used for any ASCII (text). In ASCII mode, UltraEdit allows all functions of the normal ope ultraedit, two spaces, byte values, dialog box, binary file, ascii text, hexadecimal value, ascii file, search menu, hexadecimal number, mode support, ascii mode, hex mode, format ascii, hexadecimal format, ascii hex, printable ascii characters, hexadecimal mode, character object, paste commandsJuly 5 DB2 file import and export common command summary DB2 data migration, the most commonly used is the import and export functions, and import and export command seems very simple, but in fact contains mystery, ever-changing, too easy, then full of mist variable length, different ways, data migration, personal attention, export data, ascii file, line separator, mystery, import data, table definitions, export command, wsf, type import export, length ascii, binary characters, export operationMay 27 See online are transferred in binary mode to replace the fan a little buzz Operation is as follows: Ctrl + H to Ascii file into Hex mode Ctrl + R to switch to the replacement mode (I want to here ";" replace ";" + (ENTER) + (wrap) Here quot quot, abc, regular expression, 3b, ascii file, newline character, ascii mode, hex mode, little buzzApril 17 package com.example.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.net.; import org.ap import java, import org, ioexception, public void, public int, fileinputstream, gbk, string username, string password, b9, bufferedinputstream, 9b, 7d, fileoutputstream, bufferedoutputstream, string hostname, ascii file, ftp tools, password string, b7March 29 Chinese characters in the mysql database containing documents from the command line into mysql database, easy garbled, This article describes the sql file into mysql database, not garbled a solution: 1, open the sql file, the first line in the SQL fi lt, quot, utf 8, intention, notepad, root directory, microsoft word, chinese characters, virtual host, byte stream, phpmyadmin, two minutes, sequences, ascii file, bf, weekday, bom, import command, unix style, cron jobsMarch 26 log4j androidnetui session message hidetdapiole80.tdconnection attachments slowhttp::; t.cnrzvr19ghttp: 219.148.7.14:9080 agent index.jspython JsonUtil.readhttp: yiyankm.11ka.cnhttp: 2.8.56.139.35:8088 jpwspx
http://www.quweiji.com/tag/ascii-file/
CC-MAIN-2019-22
en
refinedweb
Urho3D::Light Class Reference Public Member Functions | Static Public Member Functions | Protected Member Functions | Private Member Functions | Private Attributes | List of all members Urho3D::Light Class Reference #include <Urho3D/Graphics/Light.h> Inheritance diagram for Urho3D::Light: Collaboration diagram for Urho3D::Light: Detailed Description Light component. The documentation for this class was generated from the following files: - Source/Urho3D/Graphics/Light.h - Source/Urho3D/Graphics/Light.cpp
https://urho3d.github.io/documentation/HEAD/class_urho3_d_1_1_light.html
CC-MAIN-2019-22
en
refinedweb
We went to the interview in time, often face such questions: the code you two classes, the relationship between them is inherited, each class constructor method, only some variables, there may well constructor the value of the variable section of cod java code, public string, string args, relationship, main string, test case, constructor, execution, static variables, public static string, static system, variable values, string field, static variableDecember 5 1.static modified (class variables) an attribute field, then the property of field will be the class of their own resources, public modified as common, can be outside the class to access the property through test.a; any place within the class can be implementation code, object reference, println, public class test, class variables, static type, constructor function, example test, memory space, static properties, method implementation, test public, abstract classes, static initializer, memory resources, own resources, code result, private test, initial default, test t1July 20 To reproduce the problem Let us first look at the following procedure: public class StaticInitSequence { //-------------------Static fields------------------- private static int staticIntVar = 10; private static int staticComputeIntVar = (int)(Math.r instance variables, static variables, static string, static int, static object, static field, public void print, static fields, instance fields, sequence problemSeptember 26 Implementation of HashSet For the HashSet, it is the realization based on HashMap, HashSet uses HashMap to hold the bottom of all the elements, it is relatively simple implementation of HashSet, HashSet view the source code, you can see the following lt, hashset, java code, map, serializable, source code, code java, elements, cloneable, java implementation, realization, public int sizeApril 27 Java initialization order: (static variables, static initialization block) "(a variable, initialization block)" constructor, for those that inherited the case is based on a static class late father - "sub-class static -" the the order java class, constructor, 163 com, static variablesMarch 29 Today, the training time, to demonstrate the java class initialization process, I wrote a class. But because there is no ready, leading to demonstration failed. Hehe Now I put together about ideas to make this case to re-write a bit. The code is as f implementation, string name, string args, java class, param name, doubts, main string, new java, demonstration, java files, annex, thinking in java, static system, f system, new flag, class flagMarch 29 1, define an array of type [] arrayName; Note: 1, the array definition (C language statement), you can not specify the array length. 2, defined only in the stack is specified in a reference variable, heap memory is not allocated, so the initializatio habit, c language, heap memory, stack, array length, initial value, double 0, static initialization, array initialization, array definition, loatOctober 28 Disclaimer: This article reproduced, provenance unknown, only individual learning 1, static Please read the following this procedure: 1. 2. Public class Hello ( 3. Public static void main (String [] args) (/ / (1) 4. System. Out.println ( "Hello, wor java lang, string args, public void, main string, java java, string x, java program, hello world, provenance, j2se, static method, level languages, java byte code, java compiler, core java, printstream, java documentation, java usage, manual input, break downAugust 18 Why use Lazy Instantiation when static initialization is more efficient? Well, there are pros and cons to both, and there is no firm answer. The Singleton article gave one solution for implementing global variables, but it wasn't the only solution. J constructor, global variables, code segment, class variables, singleton, time one, static method, instance variable, instantiation, static variable, static initializer, class myclass, pros and consMarch 27 We all know that, for static variables, static initialization block, variables, initialization blocks, constructors, and their order of this is a static variable initialization> static initialization block> Variables> Initialization Blocks> co succession, java code, public string, string args, main string, test code, constructor, static variables, public static string, compliance, final result, static system, string field, static variable, variable initializationMarch 30 1, in addition to other types of Object outside the class did not inherit class Base { protected static int a = 3; protected int b = 5; static{ System.out.println("a = " + a); } { System.out.println("b = " + b); } public Base(){ System lt, implementation, string args, principle, main string, static variables, object initialization, static system, class loading, static initialization, executive membersMarch 30 1, the class created only when the call using the New JAVA class loader will be loaded 2, JAVA class when the first load, will the static member variable or method that an initial, but the method is not called is not implemented, static member variab public void, member variables, abstract class, new java, subclass, class instance, class inheritance, int age, father and son, initialization code, static code, static system, static member, instance creation, int radius, java class loader, initialization blocks, zt, radius system, sageApril 26 1. Two-dimensional array can be viewed as elements of an array array; 2.Java in the two-dimensional array declaration and initialization should follow from high dimensional to low-dimensional order. Example: Static initialization: Array2.java: Code p lt, java code, string args, println, quot quot, main string, elements, array array, dimensional array, initialization code, string 3, static initialization, array declarationApril 28 1. Built-in type of initialization 1.1 Create the built-in type of static initialization "Static creation" refers to the variables in the data segment or stack definitions. Create a built-in static, there are two types of initialization: direct definition of variables, stack, 000000, initial value, floating point, definitions, printf, three ways, dynamic creation, pi, heap, bool, data segment, static initialization, lf, initialization valueMay 5 static analysis If initialized with the domain to change the location, there will be corresponding changes in output, as static (or static) initialization and domain, the basic implementation in accordance with the conclusion, class subclass, priority, variables, class instance, execution, distinction, static method, initialized, static class, static analysis, father and son, method implementation, static initialization, variable domain, variable initialization, static elementsJune 15 1, Static Please read the following this procedure: public class Hello ( public static void main (String [] args) (/ / (1) System.out.println ("Hello, world!"); / / (2) ) ) Seen this process, for most studied Java From, is not unfamiliar. If not java lang, string args, public void, main string, java java, string x, java program, hyperlink, hello world, sun, static method, level languages, core class, java byte code, java compiler, printstream, static variable, java documentation, program implementation, usage of javaJune 25 The role of java in the static Sometimes you want to define a class member, use it completely independent of any object class. Typically, class members must pass its class object access, but can create such a member, it can be its own use, without re instance variables, inheritance, string args, class member, main string, static void, static methods, class instance, global variables, static variables, static method, class members, x system, static system, static members, static variable, static data, static statementsJuly 21 There is always recent program was a strange question .... Ever on the search a bit .... to find relevant information related to this article .... a sense of shared harvest Tingzhi the ..... Share ....... On the Java initialization, a number of artic stack trace, lt, implementation, existence, translator, contrary, strange question, thinking in java, designers, shortcomings, realization, program flow, text translationAugust 8 1, not a succession of @ Static variables @ Static initialization block @ Variable @ Initialization block @ Constructor 2, a succession of @ Parent - static variables @ Parent - the static initialization block @ Sub-categories - static variables @ Su succession, static variables, sequence 1, initialization sequenceAugust 8 1, constructor initialization ① The concept of "creating" and "initialization" are two different things, in java, the two are bundled together and inseparable. java provides a constructor to initialize the object, when users have the a garbage collection, default constructor, parameters, type conversion, memory, exceptions, garbage collector, c program, two different things, new ways, method parameter, java compiler, storage area, parameter type, static storage, type declaration, finalize method, incoming data, chapter summaryAugust 22 1. Source file using the static definition of function that is access: only in the source code can access the function, it corresponds to the function extern modified. (Note that the static function does not refer to a static class members) 2. Functi object oriented programming, global variables, static variables, static int, initialized, time function, oriented program, keyword usage, oriented design, static member, storage area, static members, variable storage, static variable, global data, static initialization, static class members, static cSeptember 18 Description : Contains main() The class contains a static class ,static Class initialized before class Bowl1 { Bowl1(int marker) { System.out.println("Bowl(" + marker + ")"); } void f1(int marker) { System.out.println("f1(" + string args, main string, static variables, f system, class a1, initialization timeSeptember 21 1) In Java, the class designer can guarantee initialization of every object by providing a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So default constructor, match, error message, expression, cleanup, syntax, convenience, argument types, narrowing conversionOctober 1 java array is static, and javaScript array is dynamic. When the array is initialized, the length of the array variable was not. java array program must be initialized before they can use. The so-called initialization, is allocated for the array of me class interface, two ways, string str, main string, programmer, array element, array length, array elements, data types, initial value, initial values, java array, static java, static initialization, javascript array, element array, memory elementsNovember 11 public class Test4 { static{ System.out.println(" Static initialization blocks ..."); } { System.out.println(" Initialization block ..."); } Test4(){ System.out.println(" Construct method ..."); } /** * @param args */ public inheritance, implementation, public string, string args, java class, string str, main string, public static string, string str2, static system, test4November 15 First we look at the members of reference type initialization We look at one example class Program { static void Main (string [] args) { DriveB d = new DriveB (); } } class BaseA { static DisplayClass a = new DisplayClass ("base class static member i instance variables, implementation, string args, member variables, main string, class instance, constructor, instance variable, initialized, c class, conclusions, class members, static member, static members, static initialization, impleNovember 30 static methods java difference between static block In general, if some code must start when the project implementation, the need to use static code block, this code is active implementation; need to initialize when the project started, in the case d attribute, static methods, pay attention, static variables, static method, project implementation, static code, n1, static members, static initializationDecember 6 We went to the interview in time, often face such questions: the code you two classes, the relationship between them is inherited, each class constructor method, only some variables, there may well constructor the value of the variable section of cod public string, string args, interview questions, relationship, doubts, main string, test case, static variables, public static string, compliance, variable values, string fieldDecember 26 Be a question in the written examination on the class variables and methods of implementation of the order of initialization issues, then a little bit for a few details of the recall is not very clear, turn the next few days specifically TIJ, summed implementation, string args, main string, marker, constructor, execution, little bit, class variables, few days, necessary time, static object, static variable, static initialization, static data, variable initialization, static tableJanuary 4 We all know that in java there is a static initialization block, which is the static {}, they will be called when the class is loaded. If the class contains an instance initialization block, which is the {} block, when it will be called yet. Let's lo string args, main string, constructor, static system, static initializer, static initializationJanuary 12 信经过Map的了解之后,学习Set会容易很多.毕竟,Set的实现类都是基于Map来实现的(HashSet是通过HashMap实现的,TreeSet是通过TreeMap实现的). 首先,我们看看Set架构. (01) Set 是继承于Collection的接口.它是一个不允许有重复元素的集合. (02) AbstractSet 是一个抽象类,它继承于AbstractCollection,AbstractCollection实现了Set中的绝大部分函数,为Set的实现类提供了便利. (03) Has November 28 对于HashSet而言,它是基于HashMap来实现的,底层采用HashMap来保存元素.所以如果对HashMap比较熟悉,那么HashSet是so easy!! 一.定义 public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable HashSet继承AbstractSet类,实现Set.Cloneable.Serializable接口 May 7 Summary and keywords generics, type safe, type parameter (variable), formal type parameter, actual type parameter, wildcards (?), unknown type,? extends T,? super T, erasure, translation, cast, instanceof, arrays, Class Literals as Run - time Type To java language, type conversion, line 3, integer type, misunderstanding, c templates, variable assignment, run time error, linkedlist, type parameter, time type, core idea, grammatical structure, type abstraction, container types, covariant, typical usage, generic version, literals, language extensionsMarch 29 Java1.5 generic guide to the Chinese version <switch> Abstract and keywords 1. Introduction 2. The definition of simple generic 3. Generic and sub-class inheritance 4. Wildcards (Wildcards) 4.1. Limited wildcard (Bounded Wildcards) 5. Generic method java language, variable type, chinese version, type conversion, integer type, class inheritance, c templates, run time error, linkedlist, time type, grammatical structure, generic method, generic class, generic java, container types, typical usage, literals, language extensions, generic code, generic guideApril 12 hibernate tutorial first part of the official entry - the first Hibernate program First we will create a simple console (console-based) Hibernate program. We use the built-in database (in-memory database) (HSQL DB), so we do not install any database confusion, persistent class, lib directory, log4j, memory database, download page, database server, chinese translation, translator, third party, library files, java library, hsql, first class, development directory, library collection, javabean class, party libraries, party library, readmeAugust 21 1) If an object appears in a string concatenation expression (involving '+' and String objects), the toString () method is automatically called to produce a String representation for that object. 2) RTTI (Runtime Type Information) means: At run time, implementation, java code, java virtual machine, run time, expression, tostring, checks, thinking in java, string objects, special needs, java api, java virtual machine jvm, class loaders, string concatenation, default class, string representation, rtti, web server applications, primordial class loader, bad javaOctober 1 1, procedures 1 results: class A{ static{ System.out.println("load a"); } A(){ System.out.println("create a"); } } class B extends A{ static{ System.out.println("load b"); } B(){ System.out.println("create b"); } } implementation, string args, java class, variables, main string, java object, constructor, execution, java objects, java lang object, modifiers, static system, static initialization, executable statementsOctober 19 Chapter 2, everything is an object one. All objects must be established by you 1. Where stored 1. Register: We can not control in the program 2. Stack: the basic types of data storage and object reference, but the object itself is not stored in the s data storage, object reference, stack, initial value, constants, return values, storage space, programming ideas, class members, java programming, storage array, heap, static member, relational operators, static storage, program flow, hard drives, storage storage, n1 n2, memory referenceOctober 30 ConcurrentHashMap and CopyOnWriteArrayList comparison. Blog categories: Java ConcurrentHashMap ConcurrentHashMap introduced Segment, each Segment is a hashtable, the equivalent of two Hash table, and then lock in the Segment level, and increased conc implementation, data storage, map, object reference, implements, interface, efficiency, conflict, elements, opera, hash table, iteration, reference point, hashtable, drawback, random access, data segment, entire collection, accurate dataSeptember 18 Introduction: Spring Security watch, when to see more use of the Servlet Listener, filter and so on. Filter done, listener never. Therefore want from the Internet to find a closer look at the servlet specification, go thorough investigation, there is java sun, technical staff, java servlet api, english translation version, application server provider, application development tool, javadoc documentation, target audience, web application development, translation translation, inappropriate place, normative reference, specification documents, tool providers, version v2, netizen, jsr, solid foundation, inconsistencies, closer lookFebruary 28 Arithmetic exception classes: ArithmeticExecption Null pointer exception classes: NullPointerException Abnormal type cast: ClassCastException Negative abnormal array subscript: NegativeArrayException Cross-border abnormal array subscript: ArrayIndexO java lang, java virtual machine, anomaly, anomalies, array, abstract methods, null pointer exception, initialization procedure, occurrence, abnormal type, initialization procedures, abnormal operation, security breach, format error, domain field, input and output, arithmetic, assertion, dependence, visibilityApril 5 Inside JDBC (1) Now the Java application development, database operations related to time, we often think first of all are the ORM like Hibernate framework. More and more Java developers less willing to study in depth the use of, or JDBC, or in fact database products, java database, sun microsystems, jdbc specification, database operations, java developers, development database, java implementation, database product, java application development, open source database, odbc bridge, microsoft odbc, jar archive, java standards, database number, database vendor, database vendors, learn java, database databaseJune 10 root cause java.lang.ExceptionInInitializerError cn.tofishes.util.HibernateUtil.<clinit>(HibernateUtil.java:17) cn.tofishes.servlet.AddEvent.doGet(AddEvent.java:34) javax.servlet.http.HttpServlet.service(HttpServlet.java:617) javax.servlet.http.Http root cause, java lang, lt, javax, dialect, anomaly, wrapper class, cn, halo, httpservlet, servlet http, exceptionininitializererror, english documents, official document, doc reference, initialization code, dogetJune 18 Originally used to write the project hibernate3.2, kind of like to try replacing 3.3 Notes First official hibernate3.4GA a hibernate3.3 and two bags, to find the beginning of the study documents the In fact, the original discovery and there is no dif long time, dialect, project test, google, xml file, mistake, discovery, halo, java files, god, translation, ga document, study documents, contemptOctober 18 Do you think it is a Java expert right? Sure they have complete control of the Java exception handling mechanism? The code below, you can quickly identify the six exception handling problem? 1 OutputStreamWriter out = ... 2 java.sql.Connection conn = java sql, sql connection, anomaly, java programmer, conn, printstacktrace, c program, programming problems, java expert, java programming, java exception handling, notorious problem, getstring, distress signal, unusual things, bad habits, rare cases, general principles, scourge, complete controlOctober 25 Chapter VII of the types of life-cycle 1, type load, links, and initialization Java Virtual Machine through the loading, linking and initializing a Java type, so that the type of running can be used by Java programs. Among them, loading Java types is java virtual machine, authentication, java type, java types, subclass, life cycle, class variables, initial value, three steps, byte code, static class, uncertainty, static field, java programs, reflection methods, loading java, symbolic reference, symbolic references, cycle 1, cloningMarch 29 1. A hungry man, single cases of type package pattern.singleton; / / Hungry man, single-class cases. Initialized when the class has been instantiated on their own public class Singleton1 ( / / Private default constructor private Singleton1 () () / / default constructor, java language, efficiency, class implementation, perspective, point of view, singleton, synchronization, designers, java implementation, first instance, resource utilization, multiple threads, hungry man, instantiation, static factory method, reaction timeMarch 29 Arithmetic exception classes: ArithmeticExecption Null pointer exception class: NullPointerException Type cast exception: ClassCastException Array of negative subscript Exception: NegativeArrayException Subscript array bounds exception: ArrayIndexOut java lang, java virtual machine, anomalies, java exception, file java, java classes, null pointer exception, security breach, input output, exception class, static class, exception java, method declaration, string conversion, abstract method, array bounds, assertion failure, class nullpointerexception, incompatible class change, operational problemsMarch 29 public class Stack { static { a = 6;// ---- 1 System.out.println(a);// ---- 2 } static double a = 3.234; public static void main(String[] args) { System.out.println(a); } public void go() { a = 7; System.out.println(a); int a; } } The code above one instance variables, string args, java sun, public int, main string, public class test, static variables, static int, left hand side, static system, test public, static initializer, class stack, interface c, assignment type, void foo, body c, public test, simple c, static xMarch 29 getResource().getFile() returns bad windows pathjboss log4j ipPowered by JForum back packshttp: 10.16.64.232 afmis.index.isphttp: 58213129204infomsandroid opengl refresh ratehttp: 192.1681.100:8081怎么使用pycharm导入scrapy创建的工程baixar cn blah brasil updwodhttp: 192.168.2.200:8086 qcpt
http://www.quweiji.com/topic/static-initialization-of-hashset/
CC-MAIN-2019-22
en
refinedweb
It's back! After a two month-ish extended holiday hiatus, I'm back with a new Wednesday wrap-up of all the Tarot Tuesday happenings! I'd been thinking recently about starting these up again, then yesterday a new member of our Discord channel (waves hello to @viking-ventures) brought up the subject, so I figured the time must be right. We both agreed that it's a good idea to get things back on track before the crowds return (and they always come back when the market goes back up, which is now loooooong overdue to happen... 😊 ) For those new to this, each week this will be the place to look for news about the community, along with a curation type post of all the links that were resteemed for Tarot Tuesday. Also, if you have any questions about the Steemit Tarot community, please feel free to shout out over at our Discord channel, or drop it down below in the comment section. NEWS While this isn't specifically Steemit Tarot news, it does relate to our community, because the news in question pertains to a group that has been extremely supportive of me, and by extension, this account. Yep, I'm talking about my @steemitbloggers (aka #powerhousecreatives) family. I think this video that @zord189 created earlier today demonstrates how amazing this community is (and be sure to keep an eye open for the word, "unique" because three guesses who's face it's plastered over...LOL!)... That being said, I've already done some begging & pleading in a post or two, so I'll just say this little bit again - if you want to do @steemittarot a wicked solid by casting a vote for @steemitbloggers to win a 10K SP delegation, here's how you do it - - Click the below link. - Login to steemconnect - Select 'steemitbloggers' - And you're done!! Also, if you're interested in joining our family, here's how to go about it - So who wants join the POWER HOUSE CREATIVES? Now on to the cartomancy coolness! These are the card-related posts resteemed by the account yesterday. TAROT TUESDAY RECAP Woodlands Livestream #30 Playing Woodlands! 1/27/2019 2PM Eastern by @woodlands Oracle Card Board Game Show... Long Format Game Play & 7 Card Chakra Reading. If you would like a 4 Card Reading Donate $20.00 via the Paypal link in banner. Sunday 1/27/2019 2PM Tarot Tuesday reading for the week of January 29 2019 by @traciyork Hello! The Policy of Truth: Tarot and Clubbing in DC by @roomerkind Cagney's was the best place if you wanted to dance. It was a wonderful place, smack dab in the center of everything right on Dupont Circle. The owner of Cagney's called everyone Sport, and sported a very British mustache (he was British), and he ran a fun establishment. His name was Jack. Cagney's had curtained booths in the back where I did Tarot readings because Jack was cool about letting me do readings and charging for them, and so it was the perfect place for Tarot. This eventually led to me doing Tarot at The 15 Minute Club so named because everyone gets their 15 Minutes of Fame. The devil card. XV by @kerbcrawlerghost This card has a great influence in all of us, its about addictions, lust, temptation, darkness, domination, bondage, false truth, fears... but at the same time its about physical pleasure, luxury and creativity...the path of self satisfaction at all costs. Very dangerous but fun... would you live your life deliciously? Weekly Cards are Up. Pick one and have some fun! by Sunscape by @sunscape Sunscapes Weekly CardsPick a card from the following to receive this weeks timely advice that your spirit/soul guides would like to share with you. - Choose the card that feels right to you, number 1, 2 or number 3. - Choose before you scroll down to see what the cards have to say. - Enjoy this magical and fun way to see what spirit has to say to you. - This is purely for entertainment purposes only. - If you are drawn to a second card as well, then that would represent an underlying energetic movement working in your field as well. 💖Tarot Tuesday 🌟Top of the Morning Tarot 🌟 😍🌎🌙🏆💰 by @kimmysomelove42 Today's picks are from my Native American Tarot Deck by Magda and J. A. Gonzalez. You can pick card 1, 2, 3 or any combo of them.. Tarot Tuesday - Lenormand Introduction by @viking-ventures I've been reading cards for a number of years now. For me, it's a way of connecting to the ether around all of us and finding the answers that lurk just out of reach. Tarot didn't really speak to me - although I still keep a deck, I don't work with it often because it requires more of an intuitive level that doesn't work well with me. I like structure and concreteness quite a bit with cards. That's why one of my favorite decks is actually my Mahjong Oracle. I will share that one sometime, but not yet. Daily Tarot card : 27 by @evayer Three of Wands - A great opportunity is coming your way and you know what you need to do because everything around your plans is going smoothly... (continued on post) Congratulations @steemittarot! Thank you, @steemitboard! Downvoting a post can decrease pending rewards and make it less visible. Common reasons: Submit Thanks for the shout out, @steemittarot! 😉 💜 Downvoting a post can decrease pending rewards and make it less visible. Common reasons: Submit
https://steemit.com/steemittarot/@steemittarot/january-30th-2019-steemit-tarot-weekly-wednesday-wrap-up
CC-MAIN-2019-22
en
refinedweb
Laravel queue supervisor doesn't reread the updates I use Laravel's queues mostly for API jobs, I store the API token in database, everything works okay until the token is needed to be refreshed. For some reason queue doesn't reread the new token from database. I guess it is cached somehow, but php artisan cache:clear doesn't change anything. I run the test with the commands and queue. If I dump the token in the command, it is shown updated, but queue shows the old token. supervisorctl restart appname fixes the issue, but I want to make it work without restarting the queue. Any tips? 1 answer - answered 2018-11-08 08:54 Odyssee Queue workers are long-lived processes and store the booted application state in memory. As a result, they will not notice changes in your code base after they have been started. So, during your deployment process, be sure to restart your queue workers. php artisan queue:restart See also questions close to this topic - How get link shared media with google photo api I implement a function create album and upload a media video use google photo api. I created share album and upload a video into album. Data return is: { "id":", "baseUrl":"", \/photo\", "mimeType":"video\/mp4", "album":{ "id":", "coverPhotoBaseUrl":"", "coverPhotoMediaItemId":"", "shareableUrl":"https:\/\/photos.app.goo.gl\/nmxkduVUQi7cHnS36", } } I want to create a link share of video the same under example:[albumId]/photo/[mediaId]?key=cjhUT0xrZjM5NGN2SVRLOVptZU5SMUlKV0lQYWpB API return url and id of album and video, I don't know how get value of param key. API don't return this value. Please help me. - how to to automaticly get a multiple form I'm doing a HTML form, it's meant to create step to pass on a game and I want to be able to enter a number and when for example I enter 5 it instantly show me 5 form to fill and create new step but when I try it doesn't appear how can I do please? <h3>Insertion des étape :</h3> <form action="InsertionEtape.php" method="post"> <input type="number" name="quantity" min="1" max="5"> <br> <?php for ($i=0; $i < $_GET['quantity']; $i++) { ?> <h5>Nom de l'étape</h5> <input type="text" name="NomEtape" size="40" maxlength="40"> <br> <h5> Description de l'étape </h5> <textarea name="DescriptionEtape" rows="8" cols="80"></textarea> <br> <br> <input type="submit" value="Valider"> <?php } ?> </form> - Can't Upload Multiple Files to the Server using PHP I'm trying to upload multiple images to the server at once. I'm using an upload script that works for single images. However upon adding the for loop, the script no longer seems to work. I've commented out the move_upload_file function for tested purposes and replaced them with echo statements. Upon trying to upload multiple files I get the error handler: "You can't upload files of this type!". And after adding some echo statements for the file name and extensions, it displays either as "Sis" or 000. Any suggestions on how to fix this issue would be greatly appreciated. My PHP code is shown below: <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); if (!isset($_POST['submit'])) { $total = count($_FILES['file']['name']); for( $i=0 ; $i < $total ; $i++ ) { $file = $_FILES['file']; $fileName = $_FILES['file']['name'][$i]; $fileTmpName = $_FILES['file']['tmp_name'][$i]; $fileSize = $_FILES['file']['size'][$i]; $fileError = $_FILES['file']['error'][$i]; $fileType = $_FILES['file']['type'][$i]; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); // File types allowed $allowed = array('jpg', 'jpeg', 'png', 'gif'); if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize < 9000000) { $fileNameNew = uniqid('', true).".".$fileActualExt; $fileDestination = 'images/Showroom-images/'.$fileName; /*move_uploaded_file($fileTmpName, $fileDestination); echo "Success!";*/ echo $fileName; echo $fileDestination; } else { echo "Your file is too big!"; } } else { echo "There was an error, please try again"; } } else { echo $fileName + "<br>"; echo $fileType + "<br>"; echo $fileActualExt + "<br>"; echo "You can't upload files of this type!"; } }} ?> Here's the HTML form as well: <form action="test.php" method="post" enctype="multipart/form-data"> <input name="file" id="file" type="file" multiple="multiple" /> <input type="submit" value="submit" id="submit"/> </form> - Laravel Route Middleware auth:admin not working for all Routes I'd like to pre check two different Route Groups by the auth:admin middleware. This works perfectly for the first Route Group inside but not for the second which is in an other Namespace. My Routes file looks like this: Route::group(['middleware' => ['auth:admin']], function(){ Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){ Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']); }); Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){ Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']); }); }); If I'm not logged in and try to go to admin/dashboard, I'm redirected to login/admin. But if I try to go to team/1/dashboard it says Error 'Trying to get property 'headers' of non-object'. How can I get the auth:admin Middleware to work with my Team Routes too? - Laravel get unamed "GET" parameter id from URL I am trying to get a value from the url that looks more or less like this: This number 7 passed in the url as a parameters is an ID in which i submit from the blade form as a request for an action i perform in the controller but i cant get this value in anyway. This is what i tried so far: I tried to use this in the controller in which i submitted the form $request->route('company_id'); I also tried to get this as a proper GET parameter: <input type="hidden" name="company_id" id="company_id" value="{{app('request')->input('company_id')}}"> and i also tried this: <input type="hidden" name="company_id" id="company_id" value="{{Input::get('company_id')}}"> and this: <input type="hidden" name="company_id" id="company_id" value="{{$_GET['company_id']}}"> None os these options work and i still receive an empty value. Any ideas or suggestions on how can i get this variable? Thank you! - Localizing a resource::route url but keeping the names I have a resource route defined as such: Route::resource('event.invite', 'EventInvitesController'); I would like to be able to localize my url's but maintain the route and parameter names. I've tried doing something like this $eventInviteNames = [ 'create' => 'event.invites.create', 'store' => 'event.invites.store', 'index' => 'event.invites.index', 'update' => 'event.invites.update', 'destroy' => 'event.invites.destroy', 'edit' => 'event.invites.edit', 'show' => 'event.invites.show', ]; if($lang = 'de') { Route::resource( 'veranstaltung.einladung', 'EventInvitesController', ['names'=>eventInviteNames] ); } else if($lang = ... But not only is this rather verbose but it doesn't fix parameter names. I've also tried a few things like Route::resource('veranstalltung{event}.einladung{invite}', 'EventInvitesController'); So how would I go about localizing resource route url's? - How can I optimize high cpu usage with laravel workers? I have a job that chunks data from the database and then queues up between 10000 to 20000 emails. I have only two processes running but during the time we are processing all these emails our cpu usage spikes to around 50%. During times when we have no jobs our cpu usage sits at 0% supervisord.conf [program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /home/user/www/production/artisan queue:work database --queue=high,default,low --sleep=3 --tries=3 user=user autostart=true autorestart=true redirect_stderr=true numprocs=2 I've looked at a few other posts talking about this but most of them are dealing with issues from older versions of laravel. How can I reduce the cpu usage and is there an easy way for me to debug this? - supervisord not working with stderr_logfile to /var/log/ directory I'm using supervisor to run Django application. Here is my configuration for the application app_config.conf [supervisord] [program:qcgbackend] command=/var/www/html/qcg-backend/scripts/activate_environment.sh directory=/var/www/html/qcg-backend/ autostart=true autorestart=true loglevel=debug stderr_logfile=/var/log/supervisor/qcg-backend.err.log stdout_logfile=/var/log/supervisor/qcg-backend.out.log running the command supervisord -c app_config.conf -n gives error INFO spawnerr: unknown error making dispatchers for 'qcgbackend': EACCES removing stderr_logfile and stdout_logfile is working fine. Also changing the path of the log file to the current directory is working. But this directory is cleaned up every time an update is pushed. So logging here will delete the logs every time. How can I set the log file? - Permission denied - Unlink file I can upload a file but not delete it. I have a nginx, laravel, and redis containers. When I upload my queue create files and folders into /var/www/storage/app/public (laravel container) This folder is share with the host by a docker volume. When I try to remove the file and the folder I can't because I don't have permissions... I tried to change php-fpm user from www-data to root in I tried to launch supervisord queue process and fpm as root user ; Unix user/group of processes ; Note: The user is mandatory. If the group is not set, the default user's group ; will be used. user = www-data group = www-data supervisord.conf [program:php-fpm] command=/usr/local/sbin/php-fpm -F autostart=true autorestart=true priority=5 stdout_events_enabled=true stderr_events_enabled=true [program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /var/www/artisan queue:work redis --sleep=3 --tries=3 autostart=true autorestart=true user=root numprocs=8 priority=10 redirect_stderr=true stdout_logfile=/var/www/storage/logs/worker.log
http://quabr.com/53203014/laravel-queue-supervisor-doesnt-reread-the-updates
CC-MAIN-2019-22
en
refinedweb
Ticket #1879 (closed enhancement: wontfix) Identity should use a sql query to get the user's permissions Description Currently Identity iterates through all of a user's groups and individually pulling all the permissions for each group and then adding them to a set before returning them. It should instead use an appropriate query that will return the unique permissions from all the user's groups. Christoph Zwerschke suggested two SA methods for doing this: def permissions(self): return set(Permission.query.distinct().join(['groups', 'users']).filter_by(user_id=self.user_id)) def permissions(self): return set(Permission.query.filter(Permission.groups.any( Group.users.any(User.user_id==self.user_id))).all()) The disadvantage of the first is that the join will gather all the duplicate permissions and then strip them out with the distinct clause. This is probably slower than the second method that uses an exist clause. The problem with the second is that it is not compatible with SA 0.3.x. Attachments Change History comment:2 Changed 11 years ago by faide more info in this thread: comment:3 Changed 11 years ago by Janzert Before working on trying to get a SA 0.3 compatible statement I decided to check the speed difference of the different options. To my surprise the current method of iterating through the groups in python was much faster. python -m timeit -s"import perm_test;perm_test.iter()" "perm_test.iter()" 10000 loops, best of 3: 94.9 usec per loop python -m timeit -s"import perm_test;perm_test.join()" "perm_test.join()" 100 loops, best of 3: 13.1 msec per loop python -m timeit -s"import perm_test;perm_test.exist()" "perm_test.exist()" 100 loops, best of 3: 14.7 msec per loop These were done using SA 0.5 and postgresql 8.3.1. I also tested with sqlite and the results were very similiar. In order to test I initialized the database with one user having 20 groups each group having 11 out of 60 permissions. I will attach the project with the scripts I used to test. To initialize the database first do "tg-admin sql create" then "python init.py". Then the timings can be tested using the commandlines above. You can also vary the number of groups, permissions and permissions per group in the init.py script. Unless someone else shows why my timing method is wrong or comes out different for them I'll go ahead and close this in a few days. Changed 11 years ago by Janzert - attachment dbtest.zip added quickstarted project with scripts to test query speeds. comment:4 Changed 11 years ago by chrisz I can reproduce the numbers with your test, but as I wrote in the thread above, the test is not realistic because it queries the permissions in a loop in the same database session, where the group.permissions are all kept in memory. In reality, the requests run in different sessions and need to requery the database. If you simulate this using turbogears.database.session.expire_all(), then the results reverse - the old method is then 2-3 times slower. As suggested in the thread above, we may consider some caching to cover the case that permissions are queried multiple times in the same database session. I can also reproduce that the second method using exists is somewhat slower than the method using join (no matter whether I use SQLite or Postgres 8.3, or whether I add additional indices and ANALYZE the tables), contrary to what we expected. Maybe this is because the database cannot optimize the chained exists clause for using indices. comment:5 Changed 11 years ago by chrisz This is the SQL query used in the first method: SELECT DISTINCT permission_name FROM permission JOIN group_permission USING (permission_id) JOIN user_group USING (group_id) WHERE user_id = $1 And this is the SQL query used in the second method: SELECT permission_name FROM permission WHERE EXISTS (SELECT 1 FROM group_permission WHERE permission_id = permission.permission_id AND EXISTS (SELECT 1 FROM user_group WHERE group_id = group_permission.group_id AND user_id = $1)) (The actual queries issued by SQLAlchemy are a bit more complicated because tg_user and tg_group are joined which is actually not necessary). I tested these with PostgreSQL 8.3 and even larger numbers of groups and permissions, and it turned out that the second query is indeed much slower (of course I did an analyze on the database so that it can do an index scan). I then did another test with the following third SQL query: SELECT permission_name FROM permission WHERE permission_id IN (SELECT permission_id FROM group_permission WHERE group_id IN (SELECT group_id FROM user_group WHERE user_id = $1)) It turned out that this query is even faster than the others, contrary to all we learned in school about how bad "in" is compared with "exists". Does anybody have a good explanation for this and an idea how to elegantly express the last query with SQLAlchemy? comment:6 Changed 11 years ago by Janzert It's certainly not anything close to elegant, but at least to get started here is a method that will use the "in" query to get the permissions. @property def in_perms(self): from sqlalchemy import sql g_ids = sql.select([user_group_table.c.group_id], user_group_table.c.user_id == self.user_id) p_ids = sql.select([group_permission_table.c.permission_id], group_permission_table.c.group_id.in_(g_ids)) return set(Permission.query.filter( Permission.permission_id.in_(p_ids))) Also only tested with 0.5 and guessing that it needs >=0.4. It does slightly beat out the join query (~14ms to ~15.5ms). Also as a side note, explicitly caching the permissions results in it being about 10,000 times faster for subsequent checks. I'd be a bit worried about ending up with stale results if someone hangs onto a User object long term though. comment:7 Changed 11 years ago by chrisz That doesn't look so bad. I find it a bit more readable if you rewrite it as below (and this also works with SA 0.3.10): from sqlalchemy.sql import select ... @property def permissions(self): perm = permissions_table.c group_perm = group_permission_table.c user_group = user_group_table.c return set(Permission.query.filter(perm.permission_id.in_( select([group_perm.permission_id], group_perm.group_id.in_( select([user_group.group_id], user_group.user_id == self.user_id)))))) The database sessions usually last only one request, so I wouldn't worry about stale results. It may be even an advantage if permissions cannot change during one request. comment:8 Changed 11 years ago by Janzert Yes, your formulation is certainly better. I also would like to change to returning a frozenset to emphasize that this is a read-only view of the permissions. Changing that and adding caching it ends up as: @property def permissions(self): """ Get the User's permissions. This just returns a static view of the permissions and cannot be used to change them. """ try: return self._permissions except AttributeError: perm = permissions_table.c group_perm = group_permission_table.c user_group = user_group_table.c p = frozenset(Permission.query.filter(perm.permission_id.in_( select([group_perm.permission_id], group_perm.group_id.in_( select([user_group.group_id], user_group.user_id == self.user_id)))))) self._permissions = p return p If that looks good to everyone I'll work on getting a patch together for the quickstart templates. I'll be out of town for the latter half of the week though so it'll probably be next week before I have anything. comment:9 Changed 11 years ago by chrisz Returning a frozenset makes sense (the identity methods already do that). We'll probably not want to patch this in TG 1.0 (only critical bugfixes there), so you should base your patch on TG 1.1/1.5. Btw, we should also make a similar change to the SQLObject model. comment:10 Changed 11 years ago by Janzert Yep, I'm working with a checkout of the 1.1 branch. I can't find any way to get access to the intermediate tables in order to use sqlobject's sqlbuilder. Raw sql can be used, which gives the following: _get_permissions(self): try: return self._permissions except AttributeError: p = frozenset(Permission.select("""permission.id IN ( SELECT group_permission.permission_id FROM group_permission WHERE group_permission.group_id IN ( SELECT user_group.group_id FROM user_group, tg_user WHERE user_id = tg_user.id))""")) self._permissions = p return p This seems like fairly straight up sql but I wonder if it will run into database compatibility problems? I also still need to take a look at an Elixir version, but hopefully that can be based off the sqlalchemy one. comment:11 Changed 11 years ago by Janzert The following works for Elixir but is quite ugly to get a hold of the intermediary tables. @property def permissions(self): perm = Permission.c user_group = self._descriptor.properties['groups'].secondary.c group_perm = Permission._descriptor.properties['groups'].secondary.c p = frozenset(Permission.query.filter(perm.permission_id.in_( select([group_perm.permission_permission_id], group_perm.tg_group_group_id.in_( select([user_group.tg_group_group_id], user_group.tg_user_user_id == self.user_id)))))) self._permissions = p return p I'm thinking at this point that unless someone can find a cleaner way to do this for sqlobject and elixir, maybe this should only be changed in sqlalchemy. comment:12 Changed 11 years ago by faide - Milestone changed from 1.5 to 1.1 comment:13 Changed 11 years ago by faide - Milestone changed from 1.1 to 1.1 maintenance Is that worth the effort? Did someone bench the real implementation to get an idea? comment:14 Changed 10 years ago by Chris Arndt I'd say if nobody comes up with an implementation soon, then close this ticket. It's working as it is after all. And if somebody really needs more speed, it's always possible to write a custom identity provider. comment:15 Changed 10 years ago by Janzert I basically gave up on this because there doesn't appear to be a clean way to make the queries in Elixir or SQLObject. I could make a patch for just SA if wanted, otherwise this should just be closed. comment:16 Changed 10 years ago by Janzert - Status changed from new to closed - Resolution set to wontfix Marking wontfix as no one has enough interest to make the needed changes and it's likely a very small effect in most applications anyway.
http://trac.turbogears.org/ticket/1879
CC-MAIN-2019-22
en
refinedweb
Site.CreateMigrationJob method This method creates a new migration import job and queues it up for later processing by a separate timer job. The job will consume a well formed (pre-defined format) import package that is located in the Azure Blob Storage Container(s) specified in this method. The Service Level Agreement (SLA) for migration job processing is controlled through pre-configured queue and work load throttling settings, and there is no guaranteed SLA or return time for a submitted job. Namespace: Microsoft.SharePoint.Client Assembly: Microsoft.SharePoint.Client (in Microsoft.SharePoint.Client.dll) Syntax 'Declaration Public Function CreateMigrationJob ( _ gWebId As Guid, _ azureContainerSourceUri As String, _ azureContainerManifestUri As String, _ azureQueueReportUri As String _ ) As ClientResult(Of Guid) 'Usage Dim instance As Site Dim gWebId As Guid Dim azureContainerSourceUri As String Dim azureContainerManifestUri As String Dim azureQueueReportUri As String Dim returnValue As ClientResult(Of Guid) returnValue = instance.CreateMigrationJob(gWebId, _ azureContainerSourceUri, azureContainerManifestUri, _ azureQueueReportUri) public ClientResult<Guid> CreateMigrationJob( Guid gWebId, string azureContainerSourceUri, string azureContainerManifestUri, string azureQueueReportUri ) Parameters gWebId Type: System.Guid The unique identifier of the destination web for the package import. Additional information and identifiers for the import are specified within the import package itself. This identifier can be found programmatically by querying the target web using the SharePoint Client API. azureContainerSourceUri Type: System.String A valid URL, including SAS token for accessing the Azure Blob Storage Container which contains the binary files of type block. The SAS token must be created with only Read and List permissions or the migration job will fail. The SAS token should have (at least) a lifetime that starts no later than when the job was submitted, until a reasonable time has passed for successful import to have concluded. azureContainerManifestUri Type: System.String The valid URL including SAS token for accessing the Azure Blob Storage Container which contains the block blobs for the manifest and other XML files that describe the package. This location will also be used for the log output. This container cannot be the same as the one used for the azureContainerSourceUri. The SAS token must have been created with only Read, List and Write permissions or the migration job will fail. The SAS token should at least have a lifetime that starts no later than when the job was submitted, until a reasonable time has passed for successful import to have concluded. azureQueueReportUri Type: System.String The valid URL including SAS token for accessing the user provided Azure Queue used for migration job progress notifications. This value can be null if no notification queue will be used during import. If this value is not null and proper access is granted in the SAS token in this URI, it will be used for real time status update. Return value Type: Microsoft.SharePoint.Client.ClientResult<Guid> The unique identifier for the migration job is returned if the job is successfully queued, or if unsuccessful, a null value will be returned. You can get the job status using this unique identifier and the GetMigrationJobStatus method. You can delete the migration job using this identifier and the DeleteMigrationJob method. Remarks The container specified in azureContainerSourceUri must have the following permissions: (SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List). All files in the container must have at least a single snapshot applied to them to ensure that no file modification can occur from the customer during import. Any file that does not have a snapshot will be skipped during import and an error will be thrown, although the job will attempt to continue to import. The import pipeline will use the latest snapshot of the file available at the time of import. The following is an example of code that you could use to create a snapshot on a file after it is uploaded to Azure Blob Storage: CloudBlockBlob blob = blobContainerObj.GetBlockBlobReference(file); blob.UploadFromStream(stm); blob.CreateSnapshot() All files in the container specified by azureContainerManifestUri must have at least a single snapshot applied to them to ensure that no file modification can occur from the customer during import. Any file that does not have a snapshot will cause failures during import and will throw an error, potentially causing the entire migration job to fail. The queue specified in azureQueueReportUri should have the following permissions: (SharedAccessQueuePermissions.Add | SharedAccessQueuePermissions.Read | SharedAccessQueuePermissions.Update) Once accepted, the job ID will be written to the notification queue if it was provided and access is valid. The notification queue can be used for multiple migration jobs at the same time, as each job will identify itself in values sent back to the notification queue. Examples Guid MigrationJobId = TargetSite.CreateMigrationJob( TargetWebId, azureContainerSourceUri, azureContainerManifestUri, azureQueueReportUri); See also Reference Microsoft.SharePoint.Client namespace
https://docs.microsoft.com/en-us/previous-versions/office/sharepoint-server/mt143031(v=office.15)
CC-MAIN-2019-22
en
refinedweb
Urho3D::Octree Class Reference Public Member Functions | Static Public Member Functions | Private Member Functions | Private Attributes | List of all members Urho3D::Octree Class Reference Octree component. Should be added only to the root scene node More... #include <Urho3D/Graphics/Octree.h> Inheritance diagram for Urho3D::Octree: Collaboration diagram for Urho3D::Octree: Detailed Description Octree component. Should be added only to the root scene node The documentation for this class was generated from the following files: - Source/Urho3D/Graphics/Octree.h - Source/Urho3D/Graphics/Octree.cpp
https://urho3d.github.io/documentation/HEAD/class_urho3_d_1_1_octree.html
CC-MAIN-2019-22
en
refinedweb
This class provides for a framework to construct a shell or a solid along a spine consisting in a wire. To produce a solid, the initial wire must be closed. Two approaches are used: More... #include <BRepOffsetAPI_MakePipeShell.hxx> This class provides for a framework to construct a shell or a solid along a spine consisting in a wire. To produce a solid, the initial wire must be closed. Two approaches are used: Constructs the shell-generating framework defined by the wire Spine. Sets an sweep's mode If no mode are setted, the mode use in MakePipe is used. Adds the section Profile to this framework. First and last sections may be punctual, so the shape Profile may be both wire and vertex. Correspondent point on spine is computed automatically. If WithContact is true, the section is translated to be in contact with the spine. If WithCorrection is true, the section is rotated to be orthogonal to the spine?s tangent in the correspondent point. This option has no sense if the section is punctual (Profile is of type TopoDS_Vertex). Adds the section Profile to this framework. Correspondent point on the spine is given by Location. Warning: To be effective, it is not recommended to combine methods Add and SetLaw. Builds the resulting shape (redefined from MakeShape). Reimplemented from BRepBuilderAPI_MakeShape. Removes the section Profile from this framework. Returns the TopoDS Shape of the bottom of the sweep. Implements BRepPrimAPI_MakeSweep. Returns a list of new shapes generated from the shape S by the shell-generating algorithm. This function is redefined from BRepOffsetAPI_MakeShape::Generated. S can be an edge or a vertex of a given Profile (see methods Add). Reimplemented from BRepBuilderAPI_MakeShape. Get a status, when Simulate or Build failed. It can be BRepBuilderAPI_PipeDone, BRepBuilderAPI_PipeNotDone, BRepBuilderAPI_PlaneNotIntersectGuide, BRepBuilderAPI_ImpossibleContact. Returns true if this tool object is ready to build the shape, i.e. has a definition for the wire section Profile. Returns the TopoDS Shape of the top of the sweep. Implements BRepPrimAPI_MakeSweep. Transforms the sweeping Shell in Solid. If a propfile is not closed returns False. Returns the list of original profiles. Sets a Discrete trihedron to perform the sweeping. Set the flag that indicates attempt to approximate a C1-continuous surface if a swept surface proved to be C0.. Define the maximum V degree of resulting surface. Define the maximum number of spans in V-direction on resulting surface. Sets a Frenet or a CorrectedFrenet trihedron to perform the sweeping If IsFrenet is false, a corrected Frenet trihedron is used. Sets a fixed trihedron to perform the sweeping all sections will be parallel. Sets a fixed BiNormal direction to perform the – sweeping. Angular relations beetween the section(s) and <BiNormal> will be constant. Sets support to the spine to define the BiNormal of the trihedron, like the normal to the surfaces. Warning: To be effective, Each edge of the <spine> must have an representaion on one face of<SpineSupport> Sets an auxiliary spine to define the Normal For each Point of the Spine P, an Point Q is evalued on <AuxiliarySpine> If <CurvilinearEquivalence> Q split <AuxiliarySpine> with the same length ratio than P split <Spline>. Else the plan define by P and the tangent to the <Spine> intersect <AuxiliarySpine> in Q. If <KeepContact> equals BRepFill_NoContact: The Normal is defined by the vector PQ. If <KeepContact> equals BRepFill_Contact: The Normal is defined to achieve that the sweeped section is in contact to the auxiliarySpine. The width of section is constant all along the path. In other words, the auxiliary spine lies on the swept surface, but not necessarily is a boundary of this surface. However, the auxiliary spine has to be close enough to the main spine to provide intersection with any section all along the path. If <KeepContact> equals BRepFill_ContactOnBorder: The auxiliary spine becomes a boundary of the swept surface and the width of section varies along the path. Give section to sweep. Possibilities are : Sets the following tolerance values. Sets the transition mode to manage discontinuities on the swept shape caused by fractures on the spine. The transition mode can be BRepBuilderAPI_Transformed (default value), BRepBuilderAPI_RightCorner, BRepBuilderAPI_RoundCorner: Simulates the resulting shape by calculating its cross-sections. The spine is devided by this cross-sections into (NumberOfSection - 1) equal parts, the number of cross-sections is NumberOfSection. The cross-sections are wires and they are returned in the list Result. This gives a rapid preview of the resulting shape, which will be obtained using the settings you have provided. Raises NotDone if <me> it is not Ready. Returns the spine.
https://dev.opencascade.org/doc/refman/html/class_b_rep_offset_a_p_i___make_pipe_shell.html
CC-MAIN-2019-22
en
refinedweb
Difference between revisions of "Nftables" Revision as of 13:36, 15 May 2016. You can also visit the official nftables wiki page for more information. The first release is available in Linux 3.13, which is in the core repository (linux), and nftables (the user-space components) is available in the extra repository (nftables), and on the AUR in package nftables-gitAUR. Contents - 1 Overview - 2 nft - 3 Tables - 4 Chains - 5 Rules - 6 File Definitions - 7 Getting Started - 8 Samples - 9 Practical examples - 10 Loading rules at boot - 11 Logging to Syslog - 12. /etc/nftables.confwhich has a "filter" table. Rules in this table are designed to allow some protocols and reject everything else. It works in a fashion similar to ifconfig or iproute2. The commands are a long, structured sequence rather than using argument switches like in iptables. For example: nft add rule ip6 filter input ip6, see section on family below. Tables The purpose of tables is to hold chains. Unlike tables in iptables, there are no built-in tables in nftables. How many tables one uses, or their naming, is largely a matter of style and personal preference. However, each table has a (network) family and and only applies to packets of this family. Tables can have one of five families specified, which unifies the various iptables utilities into one: Family ip (i.e. IPv4) is the default family and will be used if family is not specified. IPv6 is specified as ip6. To create one rule that applies to both IPv4 and IPv6, use inet. This requires Linux >=3.15. in The nft list table foo command will list all the chains in the fooftft (for a more complete list, see man 8 nft):) - return (stop traversing the chain) - jump <chain> (jump to another chain) - goto <chain> (jump to another chain, but do not return). # File Definitions File definitions can be used by the nft -f command, which acts like the iptables-restore command. However, unlike iptables-restore, this command does not flush out your existing ruleset, to do so you have to prepend the flush command. /etc/nftables/filter.rules flush table ip filter table ip filter { chain input { type filter hook input priority 0; ct state established,related accept ip saddr 127.0.0.1 accept tcp dport 22 log accept reject } } To export your rules (like iptables-save): # nft list ruleset Getting Started The below example shows nft commands to configure a basic IPv4 only firewall. If you want to filter both IPv4 and IPv6 you should look at the other examples in /usr/share/nftables or just start with the default provided in /etc/nftables.conf which already works with IPv4/IPv6. To get an iptables-like chain set up, you will first need to use the provided IPv4 filter file: # nft -f /usr/share flush ruleset table firewall { chain incoming { type filter hook input priority 0; # established/related connections ct state established,related accept # invalid connections ct state invalid drop # loopback interface iifname lo accept # icmp icmp type echo-request accept # open tcp ports: sshd (22), httpd (80) tcp dport {ssh, http} accept # everything else drop } } table ip6 firewall { chain incoming { type filter hook input priority 0; # # everything else drop } } Limit rate IP/IPv6 Firewall firewall.2.rules table firewall { chain incoming { type filter hook input priority 0; # no ping floods: ip protocol icmp limit rate 10/second accept ip protocol icmp drop ct state established,related accept ct state invalid drop iifname lo accept # avoid brute force on ssh: tcp dport ssh limit rate 15/minute accept reject } } table ip6 firewall { chain incoming { type filter hook input priority 0; # no ping floods: ip6 nexthdr icmpv6 limit rate 10/second accept ip6 nexthdr icmpv6 drop ct state established,related accept ct state invalid drop # loopback interface iifname lo accept # avoid brute force on ssh: tcp dport ssh limit rate 15/minute accept reject } } } } Practical examplesname: - use kernel >=3.18 (true if you use the default kernel) - } } To automatically load rules on system boot, simply enable the nftables systemd service by executing systemctl enable nftables The rules will be loaded from /etc/nftables.conf by default. /etc/modules-load.d/nftables.confwith all of the nftables related modules you require as entries for the systemd service to work correctly. You can get a list of modules using this command: lsmod | grep nfOtheriwse, you could end up with the dreaded Error: Could not process rule: No such file or directoryerror. Logging to Syslog If you use a Linux kernel < 3.17, you have to modprobe xt_LOG to enable logging.
https://wiki.archlinux.org/index.php?title=Nftables&diff=prev&oldid=435088
CC-MAIN-2019-22
en
refinedweb
Phoenix v1.2.4 Phoenix.Presence behaviour Provides Presence tracking to processes and channels. This behaviour provides presence features such as fetching presences for a given topic, as well as handling diffs of join and leave events as they occur in real-time. Using this module defines a supervisor and allows the calling module to implement the Phoenix.Tracker behaviour which starts a tracker process to handle presence information. Example Usage Start by defining a presence module within your application which uses Phoenix.Presence and provide the :otp_app which holds your configuration, as well as the :pubsub_server. defmodule MyApp.Presence do use Phoenix.Presence, otp_app: :my_app, pubsub_server: MyApp.PubSub end The :pubsub_server must point to an existing pubsub server running in your application, which is included by default as MyApp.PubSub for new applications. Next, add the new supervisor to your supervision tree in lib/my_app.ex: children = [ ... supervisor(MyApp.Presence, []), ] Once added, presences can be tracked in your channel after joining: defmodule MyApp.MyChannel do use MyApp.Web, :channel alias MyApp.Presence def join("some:topic", _params, socket) do send(self, :after_join) {:ok, assign(socket, :user_id, ...)} end def handle_info(:after_join, socket) do push socket, "presence_state", Presence.list(socket) {:ok, _} = Presence.track(socket, socket.assigns.user_id, %{ online_at: inspect(System.system_time(:seconds)) }) {:noreply, socket} end end In the example above, Presence.track is used to register this channel’s process as a presence for the socket’s user ID, with a map of metadata. Next, the current presence information for the socket’s topic is pushed to the client as a "presence_state" event. Finally, a diff of presence join and leave events will be sent to the client as they happen in real-time with the “presence_diff” event. The diff structure will be a map of :joins and :leaves of the form: %{joins: %{"123" => %{metas: [%{status: "away", phx_ref: ...}]}, leaves: %{"456" => %{metas: [%{status: "online", phx_ref: ...}]}, See Phoenix.Presence.list/2 for more information on the presence datastructure. Fetching Presence Information Presence metadata should be minimized and used to store small, ephemeral state, such as a user’s “online” or “away” status. More detailed information, such as user details that need to be fetched from the database, can be achieved by overriding the fetch/2 function. The fetch/2 callback is triggered when using list/1 and serves as a mechanism to fetch presence information a single time, before broadcasting the information to all channel subscribers. This prevents N query problems and gives you a single place to group isolated data fetching to extend presence metadata. The function must return a map of data matching the outlined Presence datastructure, including the :metas key, but can extend the map of information to include any additional information. For example: def fetch(_topic, entries) do query = from u in User, where: u.id in ^Map.keys(entries), select: {u.id, u} users = query |> Repo.all |> Enum.into(%{}) for {key, %{metas: metas}} <- entries, into: %{} do {key, %{metas: metas, user: users[key]}} end end The function above fetches all users from the database who have registered presences for the given topic. The fetched information is then extended with a :user key of the user’s information, while maintaining the required :metas field from the original presence data. Summary Functions Returns presences for a topic Types Functions Returns presences for a topic. Presence datastructure The presence information is returned as map with presences grouped by key, cast as a string, and accumulated metadata, with the following form: %{key => %{metas: [%{phx_ref: ..., ...}, ...]}} For example, imagine a user with id 123 online from two different devices, as well as a user with id 456 online from just one device. The following presence information might be returned: %{"123" => %{metas: [%{status: "away", phx_ref: ...}, %{status: "online", phx_ref: ...}]}, "456" => %{metas: [%{status: "online", phx_ref: ...}]}} The keys of the map will usually point to a resource ID. The value will contain a map with a :metas key containing a list of metadata for each resource. Additionally, every metadata entry will contain a :phx_ref key which can be used to uniquely identify metadata for a given key. In the event that the metadata was previously updated, a :phx_ref_prev key will be present containing the previous :phx_ref value. Callbacks Specs Specs track(Phoenix.Socket.t, key :: String.t, meta :: map) :: {:ok, binary} | {:error, reason :: term} Specs untrack(Phoenix.Socket.t, key :: String.t) :: :ok Specs update(Phoenix.Socket.t, key :: String.t, meta :: map) :: {:ok, binary} | {:error, reason :: term}
https://hexdocs.pm/phoenix/Phoenix.Presence.html
CC-MAIN-2017-30
en
refinedweb
104 Joined Last visited Community Reputation485 Neutral About AmzBee - RankMember Personal Information - LocationLiverpool, UK - URL - Pyro is back! - This week I talk about the resurrection of Pyro, the scene builder for our engine Phobius... - AmzBee replied to Medo Mex's topic in Graphics and GPU ProgrammingDaft question, but why are you multiplying the normal by the world matrix in your vertex shader? Out.Normal = mul(IN.Normal, (float3x3)World); Aimee AmzBee replied to PhillipHamlyn's topic in Graphics and GPU Programming Aimee AmzBee replied to PhillipHamlyn's topic in Graphics and GPU ProgrammingOh. Aimee AmzBee replied to PhillipHamlyn's topic in Graphics and GPU ProgrammingIt took me a few minutes to figure out what you were asking, but I think I understand now and no it's not really practical. This is how I understand it: You want distant meshes to instead draw as cubes that each have an individual cube map representing the view of the mesh at each face (6 in total). Using which ever faces the view matrix can see, you wish the mesh to be "reconstructed" to look as if it is a fabrication of a mesh (like a billboard). If I have understood it correctly, this means there are some unfortunate flaws as follows: This means you will be storing a cube map per mesh that would be subject to this technique, which will likely consume far more vram than a large number of vertices and indices. Here is a quick example: For example a 512 * 512 * 6 faces * 4 bytes = approximately 6 megabytes per cube map where each face is 512 x 512 pixels in 32 bit. Versus (300,000 vertices * 20 bytes stride) = 5.72 megabytes per 100,000 unique triangles where each vertex is a VertexPositionTexture. When looking at this I think most people would rather distribute 100,000 triangles between meshes than have to store 6 MB per single mesh, more efficient. I have seen a technique talked about by Renaud Bédard (guy who programmed fez) where a Texture3D is linearly sampled in shader, technically this could be used to achieve what you asked, but it is complicated and very shader heavy. Should be noted he used the technique to store many tiles in one texture, so in his case although a 3D texture is to the power of 3 pixel wise (far larger than a cube map) it was a worth while trade off versus texture swapping. Even if you do elect this technique, it will mean on start-up of the scene you will need to make the user wait while each face is rendered for each cube map, the waiting time may not be noticeable with a few cube maps in the scene, but I bet it becomes more and more undesirable the more you cube maps you throw in the mix,. Aimee AmzBee replied to Ivan Ivanovski's topic in Graphics and GPU Programming - AmzBee replied to antipathy's topic in Graphics and GPU ProgrammingConsider something, in order for your game to render fast it needs to call Draw() and Update() as often as possible (update is not required to but that's going off topic). This means if you have something that requires a certain amount of time to execute after it is triggered, the action will have to last for longer than 1 draw call. Here is an example of such a technique used in XNA 4.0: using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace AnimationExample { public class Game1 : Game { class Bullet { public Vector2 Position, Velocity; public bool IsDead; public Bullet(Vector2 position, Vector2 velocity) { this.Position = position; this.Velocity = velocity; } } List<Bullet> Bullets = new List<Bullet>(); Random Random1 = new Random(); GraphicsDeviceManager Graphics; SpriteBatch Batch1; KeyboardState OldState, NewState; Texture2D ProjectileTexture; float HalfTextureH, QuaterTextureH; public Game1() { Graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void LoadContent() { Batch1 = new SpriteBatch(GraphicsDevice); ProjectileTexture = Content.Load<Texture2D>("tex1"); HalfTextureH = ProjectileTexture.Height / 2.0f; QuaterTextureH = ProjectileTexture.Height / 4.0f; } protected override void Update(GameTime gameTime) { OldState = NewState; NewState = Keyboard.GetState(); // detect key press. if (NewState.IsKeyDown(Keys.Space) && OldState.IsKeyUp(Keys.Space)) ShootBullet(); // update any existing projectiles. Bullets.ForEach(UpdateBullet); // remove any projectiels that are dead. Bullets.RemoveAll(t => t.IsDead); Window.Title = Bullets.Count + " projectile(s) are alive."; } void ShootBullet(float minSpeed = 2f, float maxSpeed = 10f) { // get a random y starting coordinate. float yPos = ((GraphicsDevice.Viewport.Height - HalfTextureH) * (float)Random1.NextDouble()) - QuaterTextureH; // calculate speed. float xVel = MathHelper.Clamp(maxSpeed * (float)Random1.NextDouble(), minSpeed, maxSpeed); // add the projectile. Bullets.Add(new Bullet(Vector2.UnitY * yPos, Vector2.UnitX * xVel)); } void UpdateBullet(Bullet bullet) { bullet.Position += bullet.Velocity; // check if the bullet has gone off the screen. if (bullet.Position.X > 800) bullet.IsDead = true; } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); Batch1.Begin(); Bullets.ForEach(DrawBullet); Batch1.End(); base.Draw(gameTime); } void DrawBullet(Bullet bullet) { Batch1.Draw(ProjectileTexture, bullet.Position, Color.White); } } } A screenshot for good measure :) Here is the texture I used if you wish to try the example out: Note, it is important to understand that if you wish something to happen over a duration of time longer than a single update/draw call, then you will always have to keep track of the state of that action, this is called state management. Each important state of something usually requires a logic update each time Update() is called, this is a core principle of game development. Side Notes The example will likely run slow if you were to run it on the Xbox 360 or Windows Phone because it is unoptimized and creates a lot of garbage. This could easily be rectified by using a fixed array as a resource pool where we only ever create a number of Bullet instances once, each bullet would need an extra bool to say if it was being used or not, however this is out of scope so if you come across that problem later on in development, feel free to PM me. Aimee - Photo: A screenshot of Radius in fabuloso purple theme, phoaaa! AmzBee replied to QBTAS's topic in General and Gameplay ProgrammingIt's answers like the one frob gave that make the time spent on gamedev.net such a joy :) He's absolutely right, so to add my two cents I would also say it is probably more important to learn to create a game first, from experience I have found it's a lot easier to pick up other languages after a while, but learning to make a game is difficult whichever you choose. On the compatibility track, MonoGame for the most part is making a good effort to make sure people who learn XNA can port their games, there are still a few niggles, but nothing that would stop you making your game for Windows 8 for example. Aimee AmzBee replied to IcedCrow's topic in Graphics and GPU ProgrammingTip, in visual studio when you see a class that looks unfamiliar, type it out into the code editor then right click and choose "Go To Definition" or click on the text and press F12. This will take you to a window that shows how the class is seen by reflection. In this case you can see the DrawableGameComponent class inherits the GameComponent class, and the IDrawable interface. So basically it's a derivative of the GameComponent class that implements methods found in IDrawable including the Draw method. This however doesn't meant it's the only one you can use, in fact you could write your own version of DrawableGameComponent that includes your own set of methods, the XNA team created this class as a prefabricated example of how to make a customized GameComponent Aimee AmzBee replied to IcedCrow's topic in Graphics and GPU ProgrammingI've made a cube sky box for a free game we are building so you can have a look at the example project I made for it if you wish: It's been created to work specifically with the free Spacescape software so you shouldnt have any problem making your own sky textures. Aimee AmzBee replied to ChristianFrantz's topic in Graphics and GPU ProgrammingShort answer is not quite :) what you could do is group the cubes by texture, then set the texture only when you start to draw another group. Like I said in a previous thread if this is not possible, then your next option is to pack all the textures you need into 1 big texture, this involves manipulating the UV texture coordinates in order for that particular "sub-texture" to be used. If you get stuck feel free to pm me on skype (XpodGames). Aimee AmzBee replied to Icebone1000's topic in Graphics and GPU ProgrammingBefore my response Id like to express my concern towards the language you are using, swearing 3 times just because you are frustrated on a forum where young creative people regularly visit does not seem very becoming of someone who's been a member for almost 5 years. I am sure many other members of the forum would agree with me that if you truly wish to have help from us, that refraining from that sort of behaviour in the future would be appropriate. At this time I'll take it that you didn't realise your language would offend, I'll try to help this time. OK to the question you asked, if you are allowing non-integer positioning and scaling of the geometry then the pixels you output may not necessarily ever map to the screen coordinates you are hoping for, to make matters worse even if you get it to work on your computer, it may not look right on others. There are some work around's like adding a half texel (not pixel) offset to your UV's, but it really depends on what interpolation method you are relying upon. In the end there are only a few options when it comes to this sort of thing, either accept it the way it is, try using higher resolution textures so the sampler can give better results, play with the half texel hack and hope it works for other computers, and/or stick to integer positioning and scaling to help the correct positioning of pixels. Aimee AmzBee replied to IcedCrow's topic in Graphics and GPU ProgrammingIf you intend on drawing an explorable star field, especially in XNA, mesh instancing is definitely the way to go. Mesh Instancing Mesh instancing works by storing a mesh on the graphics card only once (If you think about it, why bother having many copies of a mesh you will be reusing, it's inefficient, memory wasteful, and could actually act as a bottleneck when drawing many copies). Coupled with something called an instance buffer (bit like an IndexBuffer that stores an array of structs that describe position, scale, and rotation for each copy), You simply call GraphicsDevice.DrawInstancedPrimitives once each draw cycle and the graphics card takes care of drawing all of the copies. The benefits are obvious, you can draw thousands of copies of the same mesh and yet only store 1 copy of the mesh on the graphics card. As the instance buffer can be dynamic (only if you need), this enables the ability to animate instances (copies) as seen in particle system examples. Also offloading this sort of task to the graphics card is particularly useful in XNA as it helps get round the overhead .Net throws at you. Cameras In regards to cameras, it's important you get a good understanding of how matrices work in XNA. The view matrix for example represents how the user views the world, which means you only have to alter the view matrix to move, twist, turn etc.. through your star field. As you are using XNA, Riemer has an excellent tutorial on this sort of camera that I think would be of benefit, even though the site is old, I thoroughly recommend you give it a go: > Further Reading Funnily enough Microsoft have provided a number of excellent code examples that show you how to perform instancing in XNA, so here's a few links to ones I think are most relevant to your goals: > (Mesh Instancing Example) > (Particle System Example) Also to answer your question about 'straight up pixel particles', yes I can imagine a way doing something like that could be possible with shaders, but it's a very complicated way of accomplishing what you get easily with mesh instancing, I recommend you give what works a go first to build your confidence in this field. Good luck, and keep us in the loop with how you get on :) Aimee
https://www.gamedev.net/profile/181364-tarika/?tab=posts
CC-MAIN-2017-30
en
refinedweb
. A future version of the SVG specification might include instructions for defining industry-specific profiles. The flowRoot element specifies a block of graphics and text to be rendered with line wrapping. It contains at least one flowRegion element, defining regions into which the children elements of the flowRoot should be flowed. The following is an extract of an XML Schema that describes the flowRoot element. <xs:element > In order to reduce the burden on Tiny implementations, the Working Group is considering allowing flowPara as a child of flowRoot. This would mean that the Tiny module could require only a single flowPara. 3.1.2 The flowRegion element The flowRegion element contains a set of shapes and exclusion regions in which the text content of a parent flowRootRootRoot> 3.1.3 The flowRegionExcludeRoot then it describes exclusion regions for all flowRegion children of the flowRoot.> 3.1.4 The flowDiv element The flowDiv element specifies a block of text and/or graphics to be inserted into the layout, and marks it as a division of related elements.> 3.1.5 The flowPara element The flowPara element marks a block of text and graphics>. Flowing text using system fonts is a difficult operation. Content developers should not expect reproducible results between implementations. The most likely scenario for a reproducible result, although still not completely guaranteed, will be achieved by using SVG Fonts. For details refer to the CSS3 Text Module. Note that SVG does not allow the value "string" for this property, and that the values "left" and "right" have been replaced by the internationalized equivalents, "before" and "after". Vertical alignment in flowing text is provided by the vertical-align property from CSS2. In the situations where the text and graphics associated with a flow do not fit into the defined regions an OverflowEvent is raised. The OverflowEvent contains information on the amount of text and graphics that could not be placed into the region. The next draft of this specification will fully specify the behaviour of overflow. 3.1.17 Example) 3.2 Editable Text Fields. 3.2.1 The editable attribute The text and flowDiv elements have an editable attribute which defines if the contents of the elements can be edited in place. editable = "true" | "false". They should also support system functions such as copy/paste and drag/drop if available. 3.3 Text Selection The SVGSelection interface allows the user to obtain details on the current text selection. When the user selects some text in a text or flowRoot element, the SVGSelectionEvent event is dispatched to the top-level svg element. interface SVGSelection { readonly attribute boolean active; // true if something is selected readonly attribute string text; readonly attribute dom::Element firstElement; readonly attribute SVGElementInstance firstElementInstance; // index in characer data for the first selected character readonly attribute unsigned long firstIndex; // index in character data for the first non-selected character readonly attribute unsigned long lastIndex; readonly attribute dom::Element lastElement; readonly attribute SVGElementInstance lastElementInstance; }; interface SVGSVGElement { .... readonly attribute SVGSelection selection; }; // sent to the top-level svg element when selection changes in any way interface SVGSelectionEvent : events::Event { }; The SVGSelectionEvent is named "SVGSelectionChanged". 4 Rendering Custom Content SVG 1.2 adds the ability to associate behavior or extensions with arbitrary XML markup within an SVG file. This feature is referred to as Rendering Custom Content (RCC). The RCC feature set is expected to be moved to a separate specification from the next publication of this document. Discussions are already under way to merge the functionality with the XML Binding Language (XBL) that has been implemented in some HTML browsers. This will not delay the SVG 1.2 specification, and will allow the features to be used in multiple document formats (including both SVG and XHTML). A new XBL specification is being developed by the SVG Working Group with liaison with other W3C Working Groups. It is highly likely that the first official W3C version of XBL will address the requirements of SVG 1.2, where future versions add some features needed by other document languages. The transformer element is likely to be removed from the next draft of SVG 1.2, due to the high burden on implementation and the difficulty in optimization.: -. The transformation code specified by the transformer element is run on document load and every time there is a mutation anywhere in the document."/> < A trait is a potentially animatable parameter associated with an element. A trait is the value that gets assigned through an XML attribute or CSS style or SMIL animation. In the case of RCC, it describes an attribute on a custom element, allowing it to be exposed to the animation engine. Traits for custom elements are described using the traitDef element. <xs:element <xs:complexType> <xs:sequence> <xs:attribute <xs:attribute <xs:attribute <xs:attribute </xs:sequence> </xs:complexType> </xs:element> The name and namespace attributes respectively specify the name and namespace of the attribute. The type attribute is similar to the corresponding type attribute from animation elements. It allows the values "CSS" and "XML". The default is "XML". The valueType attribute specifies the type of the attribute. It only supports existing values, such as "SVGMatrix", "SVGLength", etc. Need to define exact list of valueTypes. Below is an example that defines traits for the x, y, width and height attributes for a custom foo:button element. <elementDef name="button" namespace=""> <traitDef name="x" valueType="SVGLength"/> <traitDef name="y" valueType="SVGLength"/> <traitDef name="width" valueType="SVGLength"/> <traitDef name="height" valueType="SVGLength"/> <prototype> .... </prototype> </elementDef> and SVG). a element - the text and flowDiv elements with editable set to "true" - the top-level svg element 5.2.2 Navigation By default, the tab key navigates between elements that can obtain focus (ie. elements for which the value of the focusable property evaluates to "true"). In the author wishes to change the default tab order, they must catch the input event related to the navigation (such as the tab keypress) and then cancel the event. Navigation order is determined using the nav-index property from the CSS 3 Basic User Interface Module. In most cases, the value 'auto' will cause the user agent to use document order for navigation order. This property only applies to focusable elements. Keyboard equivalents can be assigned to focusable elements using the key-equivalent property from the CSS 3 Basic User Interface Module. This property only applies to focusable elements. 5.2.3 Obtaining focus When the user agent gives an element focus it receives a DOMFocusIn event. The SVGElement and SVGElementInstance interfaces have a focus() method that, when called, requests that the User Agent give focus to the particular element. Calling focus() on an element that is not focusable has no effect. Should this be the case? Should the focus() API ignore the property? The SVGDocument interface have next() and previous() methods which move the focus onto the respectively next or previous focusable element. The following open issues are yet to be discussed: -. SVG 1.2 makes the following modifications"/> ="" xmlns: <rect id="myRect" x="10" y="20" width="200" height="300" fill="red"/> <ev:listener ev: <handler id="myClickHandler" type="application/java" xml: <foo:offset>10</foo:offset> <.svg has been temporarily placed in the SVG package/namespace. The SVG Working Group will liaise); } 6.2 The handler </xs:complexType> </xs:element> Attributes:"/> <ev:listener ev: <handler id="myClickHandler" type="application/java" xlink: ., page> 7.5 Timing and Synchronization. 7.6 More SMIL test attributes and events, timeerror. 7.7 Animating the timeline's clock The animateClock element allows the timeline of the referenced element to modified. It controls the clock on the timeline container or animation element. For a timeline modification, animateClock updates the timeline's clock with its specified by or to values. For example, the current clock time is 20s. A value of to="10s" would set the clock to 10s. A value of by="5s" would set the clock to 25s. For an animation element clock modification, animateClock updates the animation's begin value to accomodate the to or by value specified on animateClock. For example, suppose there is an animation element with a begin time of 15s and the current clock value is 30s. To fast forward the animation by 5s, animateClock would use by="5s", effectively setting the animation begin value to 10s (animation now appears it has been running for 20s). To rewind the animation by 5s, animateClock would use by="-5s", effectively setting the animation begin value to 20s (animation now appears as if it has been running for 10s). To set the animation as if it started 10s ago, animateClock would use to="10s", effectively setting the animation begin time to 20s. To set the animation to start in 10s, animateClock would use to="-10s", effectively setting the animation begin time to 40s. A schema for animateClock will be provided in the next draft. 7.8 Time Manipulation SVG 1.2 adds the speed attribute from the SMIL 2.0 Timing Manipulations Module. can only play backwards if there is sufficient information about the simple and active durations. Specifically: -. If the cascaded speed value for the element is negative and if either of the above two conditions is not met, the element will begin and immediately end (i.e. it will behave as though it had a specified active duration of 0). The SVG Working Group is considering adding more timing manipulation controls, in particulat the accelerate and decelerate attributes. 8 Multiple Pages). Each page can have animation timing attributes that specify the duration a page should be visible. A pageSet element acts like a seq element. A page can have transition effects apply as the user agent moves from one page to the next. Below is an example of an SVG document with multiple pages: <svg xmlns="" version="1.2" streamable="true"> <defs> <.. The timelineBegin attribute only affects time containers. A future draft will explicitly state which elements can have nested timelines. For now it is only svg and page elements.. - - masks, which are container elements which can contain graphics elements or other container elements which define a set of graphics that is to be used as a semi-transparent mask for compositing foreground objects into the current background.. 10.1.2 Alpha compositing Graphics elements are composited onto the elements already rendered on the canvas based on an extended Porter-Duff compositing model, in which the resulting color and opacity at any given pixel on the canvas depend on the 'comp-op' specified.: Various container elements calculate their bounds prior to rendering. For example, rendering a group generally requires an off-screen buffer, and the size of the buffer is determined by calculating the bounds of the objects contained within the group. SVG 1.0 implementations generally calculated the bounds of the group by calculating the union of the bounds of each of the objects within the group.. The following variables are used to describe the components of the background, group and extra opacity channel buffers. Sc Non-premultiplied source color component Sca Premultiplied source color component Sra Sga Sba Premultiplied source color component Sa Source opacity component Dc Non-premultiplied destination color component Dca Premultiplied destination color component Dra Dga Dba Non-premultiplied destination color component Da Destination opacity component Da(d) Extra opacity buffer containing the percentage of the background channel in the group buffer. D<n> Destination buffer <n> where the background is 0, groups in the top level svg element 1, nested groups 2 and so forth D' The results of the destination post a compositing step The operation used to place objects onto the background is as follows: Dca' = f(Sc, Dc).Sa.Da + Y.Sca.(1-Da) + Z.Dca.(1-Sa) Da' = X.Sa.Da + Y.Sa.(1-Da) + Z.Da.(1-Sa) Depending on the compositing operation, the above equation is resolved into an equation in terms of pre-multiplied values prior to rendering. The following are specified for each compositing operation: X, Y, Z, f(Sc, Dc) defined as: f(Sc,Dc) The intersection of the opacity of the source and destination multiplied by some function of the color. (Used for color) X The intersection of the opacity of the source and destination. (Used for opacity) Y The intersection of the source and the inverse of the destination. Z The intersection of the inverse of the source and the destination. Depending on the compositing operation, each of the above values may or may not be used in the generation of the destination pixel value. 10.1.3 The clip-to-self property clip-to-self Value: true | false | inherit Initial: false Applies to: container elements and graphics elements Inherited: no Percentages: N/A Media: visual Animatable: yes. Note that most compositing operations do not remove the destination and as such for these operations, the clip-to-self property has no effect. The compositing operations that remove background are described in the comp-op property diagram and can be easily identified as those that remove the blue region in the right of each of the diagrams. These are clear, src, src-in, dst-in, src-out and dst-atop. For all other operators the clip-to-self property has no effect. The clip-to-self property provides compatibility with Java2D. View this image as SVG (SVG-enabled browsers only) Container elements where the clip-to-self property is set to true only effect the pixels within the extent of the elements within the container element. For example, if a container element contains two circles, and the container element has the clip-to-self property set to true, then nothing outside the circles is effected. To perform this operation, the renderer needs to keep track of the extent of each of the elements within the container element and ensure that nothing outside the elements is modified. This can be produced by converting each object to a clipping path and unioning the clipping paths together to produce a clipping path that represents the extent of all the elements within the container element. Where a container element contains nested container elements, the operation is performed within the sub-container elements to produce the final path. When the group is composited onto the page, it is composited through the clipping path generated and thus nothing outside the extent of all the elements within the container element is modified. For filled and stroked shapes and text, the object is directly converted to a clipping path. For images and filters, the bounds of the object is converted to a (possibly transformed) rectangular clipping region. Implementation Note: For some container elements where the clip-to-self property is set to false, the container element might effect the background outside bounds of the container element. View this image as SVG (SVG-enabled browsers only) 10.1.4 The enable-background property enable-background Value: accumulate | new [ x y width height ] | inherit Initial: accumulate Applies to: container elements Inherited: no Percentages: N/A Media: visual Animatable: no For a container element container element with enable-background set to "accumulate", the corresponding area of the canvas is copied into the container element's buffer. A second buffer which has only an opacity channel is also created. This buffer Da(d) stores the percentage of the background in the group buffer and is initially opaque (which is consistent because the background has just been copied into the group buffer). The group buffer is treated as the canvas for the children of the group as usual. Additionally, as objects are placed into the group buffer, the Da(d) buffer is also drawn into using one of the operations listed below. Before the group buffer is composited onto the canvas, any remaining background color in the group buffer is removed using the values in the Da(d) buffer. Other post rendering steps such as the opacity are performed after this step, and before compositing the result onto the canvas. In addition the compositing operation used to place a group with enable-background set to accumulate onto its background is modified to apply any reduction to the background caused by any of the objects in the group. When drawing elements within a container element with enable-background set to "accumulate", the standard equations as listed below are used to draw the object into the group buffer. Depending on the compositing operation, one of two operations listed below are used to draw the object into the extra transparency buffer Da(d). For the operations clear, src, src-in, dst-in, src-out and dst-atop: Da(d)' = 0 For all other compositing operations: Da(d)' = Da(d).(1 - Sa) When compositing the group buffer onto the background, rather than the standard compositing operation listed above, the following operations should be used: Dca0' = f(Dc1,Dc0).Da1.Da0 + Y.Dca1.(1-Da0) + Z.Dca0.(1-Da1(d)) Da0' = X.Da1.Da0 + Y.Da1.(1-Da0) + Z.Da0.(1-Da1(d)) Note that the last term in the above equations uses the Da(d) buffer rather than Da. Elements containing a comp-op property value of clear, src, dst, dst-over, src-in, dst-in, src-out, dst-out, src-atop, dst-atop, xor can potentially reduce the opacity of the destination and are only valid where one of the elements ancestor container element has the enable-background property set to new. For elements without an ancestor with the enable-background property set to new , these operations are technically an error. A user agent should ignore the operation specified and render the element using the src-over compositing operation. Filters have access to the nearest ancestor group's buffer through the BackgroundImage and BackgroundAlpha images. The buffer created for the ancestor. Where a filter references an area of the background image outside the area specified by x, y, width, height, transparent is passed to the filter. View this image as SVG (SVG-enabled browsers only) 10.1.5 The knock-out property knock-out Value: true | false | inherit Initial: false Applies to: container elements Inherited: no Percentages: N/A Media: visual Animatable:: Dca1' = f(Sca, Sa, Dca1, Da1) Da1' = f(Sa, Da1) For knock-out = true, enable-background = new: Dca1' = f(Sca, Sa, 0, 0) Da1' = f(Sa, 0) For 'knock-out' =true ,'enable-background' = accumulate: Dca1' = f(Sca, Sa, Dca0, Da0) Da1' = f(Sa, Da0) Note that an element in a knockout group that does not have the clip-to-self property set, in effect clears all prior elements in the group. View this image as SVG (SVG-enabled browsers only) This definition of knock-out may differ to PDF and may be reviewed.. f(Sc,Dc) = Sc X = 1 Y = 1 Z = 1 Dca' = Sca.Da + Sca.(1 - Da) + Dca.(1 - Sa) = Sca + Dca.(1 - Sa) Da' = Sa.Da + Sa.(1 - Da) + Da.(1 - Sa) = Sa + Da - Sa.Da The following diagram shows src-over compositing: View this image as SVG (SVG-enabled browsers only). f(Sc,Dc) = 0 X = 0 Y = 1 Z = 1 Dca' = Sca.(1 - Da) + Dca.. plus The source is added to the destination and replaces the destination. This operator is useful for animating a dissolve between two images. f(Sc,Dc) = Sc + Dc X = 1 Y = 1 Z = 1 Dca' = Sca.Da + Dca.Sa + Sca.(1 - Da) + Dca.(1 - Sa) = Sca + Dca Da' = Sa.Da + Da.Sa + Sa.(1 - Da) + Da.(1 - Sa) = Sa + Da multiply The source is multiplied by the destination and replaces the destination. The resultant color is always at least as dark as either of the two constituent colors. Multiplying any color with black produces black. Multiplying any color with white leaves the original color unchanged. f(Sc,Dc) = Sc.Dc X = 1 Y = 1 Z = 1 Dca' = Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa.Da + Sa.(1 - Da) + Da.(1 - Sa) = Sa + Da - Sa.Da The following diagram shows multiply compositing: View this image as SVG (SVG-enabled browsers only) screen The source and destination are complemented and then multiplied and then replace the destination. The resultant color is always at least as light as either of the two constituent colors. Screening any color with white produces white. Screening any color with black leaves the original color unchanged. f(Sc,Dc) = Sc + Dc - (Sc.Dc) X = 1 Y = 1 Z = 1 Dca' = (Sca.Da + Dca.Sa - Sca.Dca) + Sca.(1 - Da) + Dca.(1 - Sa) = Sca + Dca - Sca.Dca Da' = Sa + Da - Sa.Da The following diagram shows screen compositing: View this image as SVG (SVG-enabled browsers only) overlay Multiplies or screens the colors, dependent on the destination color. Source colors overlay the destination whilst preserving its highlights and shadows. The destination color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the destination. if 2.Dc < Da f(Sc,Dc) = 2.Sc.Dc otherwise f(Sc,Dc) = 1 - 2.(1 - Dc).(1 - Sc) X = 1 Y = 1 Z = 1 if 2.Dca < Da Dca' = 2.Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa) otherwise Dca' = Sa.Da - 2.(Da - Dca).(Sa - Sca) + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa + Da - Sa.Da The following diagram shows overlay compositing: View this image as SVG (SVG-enabled browsers only) darken Selects the darker of the destination and source colors. The destination is replaced with the source when the source is darker, otherwise it is left unchanged. f(Sc,Dc) = min(Sc,Dc) X = 1 Y = 1 Z = 1 Dca' = min(Sca.Da, Dca.Sa) + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa + Da - Sa.Da or if Sca.Da < Dca.Sa src-over() otherwise dst-over() The following diagram shows darken compositing: View this image as SVG (SVG-enabled browsers only) lighten Selects the lighter of the destination and source colors. The destination is replaced with the source when the source is lighter, otherwise it is left unchanged. f(Sc,Dc) = max(Sc,Dc) X = 1 Y = 1 Z = 1 Dca' = max(Sca.Da, Dca.Sa) + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa + Da - Sa.Da or if Sca.Da > Dca.Sa src-over() otherwise dst-over() The following diagram shows lighten compositing: View this image as SVG (SVG-enabled browsers only) color-dodge Brightens the destination color to reflect the source color. Painting with black produces no change. if Sc + Dc >= 1 f(Sc,Dc) = 1 otherwise f(Sc,Dc) = Dc.1/(1-Sc) X = 1 Y = 1 Z = 1 if Sca.Da + Dca.Sa >= Sa.Da Dca' = Sa.Da + Sca.(1 - Da) + Dca.(1 - Sa) otherwise Dca' = Dca.Sa/(1-Sca/Sa) + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa + Da - Sa.Da The following diagram shows color-dodge compositing: View this image as SVG (SVG-enabled browsers only) color-burn Darkens the destination color to reflect the source color. Painting with white produces no change. if Sc + Dc <= 1 f(Sc,Dc) = 0 otherwise f(Sc,Dc) = (Sc + Dc - 1)/Sc X = 1 Y = 1 Z = 1 if Sca.Da + Dca.Sa <= Sa.Da Dca' = Sca.(1 - Da) + Dca.(1 - Sa) otherwise Dca' = Sa.(Sca.Da + Dca.Sa - Sa.Da)/Sca + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa + Da - Sa.Da The following diagram shows color-burn compositing: View this image as SVG (SVG-enabled browsers only) hard-light < 1 f(Sc,Dc) = 2.Sc.Dc otherwise f(Sc,Dc) = 1 - 2.(1 - Dc).(1 - Sc) X = 1 Y = 1 Z = 1 if 2.Sca < Sa Dca' = 2.Sca.Dca + Sca.(1 - Da) + Dca.(1 - Sa) otherwise Dca' = Sa.Da - 2.(Da - Dca).(Sa - Sca) + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa + Da - Sa.Da The following diagram shows hard-light compositing: View this image as SVG (SVG-enabled browsers only) soft-light < 1 f(Sc,Dc) = Dc.(1 - (1 - Dc).(2.Sc - 1)) otherwise if 8.Dc <= 1 f(Sc,Dc) = Dc.(1 - (1 - Dc).(2.Sc - 1).(3 - 8.Dc)) otherwise f(Sc,Dc) = (Dc + (Dc^(0.5) - Dc).(2.Sc - 1)) X = 1 Y = 1 Z = The following diagram shows soft-light compositing: View this image as SVG (SVG-enabled browsers only) difference Subtracts the darker of the two constituent colors from the lighter. Painting with white inverts the destination color. Painting with black produces no change. f(Sc,Dc) = abs(Dc - Sc) X = 1 Y = 1 Z = 1 Dca' = abs(Dca.Sa - Sca.Da) + Sca.(1 - Da) + Dca.(1 - Sa) = Sca + Dca - 2.min(Sca.Da, Dca.Sa) Da' = Sa + Da - Sa.Da The following diagram shows difference compositing: View this image as SVG (SVG-enabled browsers only) exclusion Produces an effect similar to that of 'difference', but appears as lower contrast. Painting with white inverts the destination color. Painting with black produces no change. f(Sc,Dc) = (Sc + Dc - 2.Sc.Dc) X = 1 Y = 1 Z = 1 Dca' = (Sca.Da + Dca.Sa - 2.Sca.Dca) + Sca.(1 - Da) + Dca.(1 - Sa) Da' = Sa + Da - Sa.Da These equations are approximations which are under review. Final equations may differ from those presented here. The following diagram shows exclusion compositing: View this image as SVG (SVG-enabled browsers only) The SVG 1.1 specification does not make it clear when an image that is not being displayed should be loaded. In SVG 1.2,. 11 Painting Enhancements 11.1 The solidColor Element. SVG 1.2 supports the CSS3 Color Module rgba() value syntax for color properties. This provides an opacity value for a solid color value. This opacity is multiplied into the processing of SVG colors before the other opacity values (such as stop-opacity, fill and stroke opacity and the opacity property). SVG 1.1 allows a target object to be denoted, either with a view element or with a viewTarget as part of an SVG view specification in a fragment identifier. The target object(s) are to be highlighted. Just checking, the spec allows multiple viewTarget s in a fragment identifier, yes?) } What happens if the target object is a group, a hyperlink, or some other container object which does not itself have a visual representation? Suggested resolution: inherited properties have their usual effect on the children. 11.15 More rendering hints. Should these have prefixes? The names are quite generic. During the later stages of the SVG Mobile 1.1 specifications it became obvious that there was a requirement to subset the SVG and XML DOM in order to reduce the burden on implementations. SVG 1.2 adds new features to the SVG DOM, allowing a subset to be taken that includes as much necessary functionality as possible. SVG 1.2 also proposes a subset, suitable for SVG Tiny implementations. Furthermore, it should be possible to implement the DOM subset on devices that support SVG Tiny 1.1 although, in this case, the scripting would be external to the SVG document (since SVG Tiny 1.1 does not support inline scripting). The goal is to provide an API that allows access to initial and animated attribute and property values, to reduce the number of interfaces, to reduce run-time memory footprint using necessary features of the core XML DOM, as well as the most useful features from the Full SVG DOM (such as transformation matrix helper functions). The new SVG 1.2 DOM features and subset are described in Appendix A. 17.3 Media Interfaces }; Note that the getPixel() method on SVGImage may return invalid data in the cases where the image has not yet been loaded..AndStartInterval(in long timeout) // Creates an SVGTimer with delay=timeout, interval=timeout that will // be started if start is true. SVGTimer createInterval(in long timeout, boolean start) }; 17.7 Better network data interface. 17.7.1 URLRequest interface The URLRequest interface enables a client to retrieve data that is addressable by a URL.) readonly attribute unsigned short requestState; attribute DOMString requestText; // body of the request, can only // set in INITIAL state iterator, only in COMPLETED state NameValuePair getResponseHeader( in unsigned long index ); // response header count, only in COMPLETED state readonly attribute unsigned long responseHeaderCount; // parsed body of the response, only in COMPLETED state dom::Node parseXML( in dom::Document contextDoc ); // initialize request, not allowed in PENDING state, // sets the state to INITIAL void init( in DOMString method, in DOMString url ); // abort the request, only in PENDING state, // sets the state to ERROR void abort(); // submit the request, sets the state to PENDING void submit(); }; interface NameValuePair { readonly attribute DOMString name; readonly attribute DOMString value; }; A URLRequest object is created using SVGWindow. interface SVGWindow { ... URLRequest createURLRequest(); }; The functionality of the common postURL() method is equivalent to the following code: // code for today's postURL: function postURL( url, body, callback ) { var req = createURLRequest() req.addEventListener( "URLResponse", callback, false ) req.requestText = body req.submit() } 17.7.2 Raw Socket Connections The Connection interface provides a client with a method to use raw sockets for communication. interface ConnectionEvent : events::Event // "ConnectionData" event { readonly attribute DOMString data; }; interface Connection : events::EventTarget { readonly attribute boolean connected; void setEncoding( DOMString value ); // might be called before connect void connect( in DOMString url ) raises(SVGException) void send( in DOMString data ); void close(); }; A Connection object is created using SVGWindow. interface SVGWindow { ... Connection createConnection(); }; 17.7.3 Security Note that these interfaces expose. The SVGWindow interface stores global information and factory methods. The file upload functionality adds a single method that initiates a file dialog. interface SVGWindow { ... FileDialog createFileDialog ( ); ... } The createFileDialog method takes no parameter and returns a FileDialog object. The FileDialog object inherits from EventTarget and it is this possible to attach event listeners to it using the addEventListener method. This method does not produce a user dialog, it merely produces the object with which a file dialog can be opened. 17.9.2 Interface FileDialog The FileDialog interface is created with a call to SVGWindow::createFileDialog. Its purpose is to control the apparition of a file dialog, and to register the event listeners that will handle the selection of files.(); It would be possible to provide a less verbose API, but it would make it less extensible. For instance, a future specification may add file selection filtering, other events (e.g cancel), and so forth. 17.9.3 Interface FilesSelected; } 17.9.4 Interface). Is there any need to provide for adding to the list? 17.9.5 Interface File. Should we do more to avoid race conditions? 17.9.6 URLRequest additions. Should it also have addContentFromFileList ( in FileList fileList ) as a convenience method? We need to describe how the file being sent might be encoded. For things like PUT requests it needs to be sent as is, but for HTML form emulation we should support at least multipart/form-data. 17.9.7 Connection additions. Should it also have sendFileList ( in FileList fileList ) as a convenience method? How does this interact with the encoding set on the Connection? 17.9.8 Security considerations. 17.10 Filtering DOM Events When an event listener is attached to an element, that listener receives all matching events dispatched by the element. In many cases the listener only requires events that match certain criteria (e.g. a particular attribute name for DOM mutation events or only events in the bubbling phase). The SVGEventFilter interface is an event listener and event target that filters some events, allowing the script or user agent to only process what is necessary. interface SVGEventFilter : events::EventTarget, events::EventListener { // value for phase and button that prevents filtering const unsigned short DONT_FILTER = 0xFFFF; attribute unsigned short phase; attribute EventTarget target; // null does not filter out anything attribute unsigned short button; // for mouse events // for mouse motion events, false does not filter out anything attribute boolean dragOnly; // for mutation events, null does not filter out anything attribute DOMString attrLocalName; // for mutation events, active only when attrLocalName is non-null attribute DOMString attrNamespace; }; SVGEventFilters are created using the SVGWindow interface. interface SVGWindow { ... SVGEventFilter createEventFilter(); ... }; The default state of the created filter does not filter any events. The user must set the properties in order to filter. SVGEventFilter is an event listener and is also an event target, so that other event listeners can be registered with it. It matches the event it receives against the set of criteria that are expressed as properties and either passes that event object to all of its own event listeners if it finds a match or ignores the event if it does not find a match. 17.11 Persistent Client-side Data storage Many applications benefit from the ability to store data between sessions on the client machine. SVG 1.2 adds a simple set of methods to store data specific to the SVG Document in the client. interface SVGWindow { ... void setPersistentValue( in DOMString name, in DOMString value ); DOMString getPersistentValue( in DOMString name ); ... }; any of the limits are exceeded then the values are silently discarded. 18 Document Object Model Subset. 19 RelaxNG Schema for SVG 1.2 A modularized RelaxNG schema for SVG 1.2 is available. This schema should not be considered to be complete or without error..
https://www.w3.org/wiki/ScalableVectorGraphicsDraft
CC-MAIN-2017-30
en
refinedweb
I need guidence to solve a problem i'm having with a program (Exercise), When I enter -1 why does the "Enter miles used" show up. It should just print " The overall average miles / gallon was" and if no data is entered print "No Data entered" PLEASE I dont want the answer just direction so I can learn for meself. Thank for your timeThank for your timeCode:#include <stdio.h> /* fuction main begins program execution*/ int main(void) { /* intialization phase */ int counter = 0; /* number of tanful entered/ intialize loop counter */ int miles = 0; /* miles value */ float total = 0; /* sum of tankful/ intialize total */ float gallons; /* gallons value */ float tankful; /* number with decimal point for average */ float average; /* process phase */ /* get gallons used from user */ printf("Enter gallons used, -1 to Exit: "); /* prompt for input */ scanf("%f", &gallons); /* read gallons from user */ printf(" Enter miles used: "); /* prompt for input */ scanf("%d", &miles); /* read miles from user*/ tankful = miles / gallons; /* calculate average */ printf("The miles / gallons for this tank was %f", tankful); /* loop while sentinel value not yet read from user */ while(gallons != -1) { total = total + tankful; /* add average to total */ counter = counter + 1; /* increment counter */ /* get next gallonful from user */ printf("\nEnter gallons used, -1 to Exit: "); /* prompt for input */ scanf("%f", &gallons); /* read gallons from user */ printf(" Enter miles used: "); /* prompt for input */ scanf("%d", &miles); /* read miles from user */ tankful = miles / gallons; printf("The mile / gallons for this tank was %f", tankful); } /* end while */ /* termination phase */ /* if user entered at least one tankful*/ if(counter != 0) { /* calculate average of all the tankfuls entered*/ average = (float) total / counter; /* avoid truncation*/ /* display average with six digits of precision*/ printf("The overall average miles / gallon was %f\n", average); } /* end if */ else { /* if no tankfuls were entered, output message*/ printf("\nNo data entered\n"); } /* end else */ return (0); /* indicate program ended ok */ } /* end fuction main */ Nurofen
https://cboard.cprogramming.com/c-programming/101715-guidence-program-c.html
CC-MAIN-2017-30
en
refinedweb
View Complete Post Hi, im hanging on a simple function call in my mainpage.aspx.vb. I want to get the physical server path to the Database1.mdb-file. Dim strMypath As String strMypath = mypath() then in my global.asax.vb I have this function: Public Function mypath() As String mypath = "" Return Server.MapPath("/App_Data/Database1.mdb") End Function But this call doesnt work. I get a message in my mainpage.aspx.vb "The name "mypath" was not declarated." Can anyone help???! Will. Hello, I'm using a static Timer in my Global.asax to run a method at regular intervals. When the method throws an exception, my application is stopped. I have used an empty catch to prevent exceptions from stopping the application something like below code. Is there a disadvantage to use such an approach? protected void Application_Start(object sender, EventArgs e) { TimerStarter.StartTimer(); } public class TimerStarter { private static System.Threading.Timer threadingTimer; public static void StartTimer() { if (null == threadingTimer) { threadingTimer = new System.Threading.Timer(new System.Threading.TimerCallback(CheckData),HttpContext.Current, 0, 50000); } } private static void CheckData(object sender) { try { // a method that reading xml file from another url } catch(Exception) { // empty catch to prevent stopping the application } } } Hi, I I've moved away from using sqldatasources, and now I exeucte all my sql in my code behind. However, I'm looking to make my codebehind a little more cleaner/neater. For example, on one page, there are three stored procedures that must execute, and All three have these same 8 lines of code for each of my three stored procedures. How can I condense my code behind to not always have to add this... SqlConnection conn = default(SqlConnection); SqlCommand comm = default(SqlCommand); SqlDataReader reader = default(SqlDataReader); string connectionString = ConfigurationManager.ConnectionStrings["xyz"].ConnectionString; conn = new SqlConnection(connectionString); comm = new SqlCommand(); comm.Connection = conn; comm.CommandType = System.Data.CommandType.StoredProcedure; Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/14473-function-globalasax-is-not-running.aspx
CC-MAIN-2017-30
en
refinedweb
Hello, I'm trying to create a structure in C# with byte alignment, which "include" unions as well. The code is compiling, unfortunately I get an exception linked to data alignment : "it contains an object field at offset 10 that is incorrectly aligned or overlapped by a non-object field" the code is something like this: [StructLayout(LayoutKind.Explicit)] public class A { [System.Runtime.InteropServices.FieldOffset(0)] Byte b1; [System.Runtime.InteropServices.FieldOffset(0)] Byte b1_2; [System.Runtime.InteropServices.FieldOffset(1)] Byte b2; [System.Runtime.InteropServices.FieldOffset(1)] Byte b2_2; ... [System.Runtime.InteropServices.FieldOffset(10)] Byte[] bArray; // 20 bytes whatever allocated by the constructor } from what I understand, I should use the Sequential option for LayoutKind (ie with Pack=2 ;-)), but in this case, I'm loosing the possibility to have multiple fields at the same position. Any idea regarding this ? Regards, samuel
https://www.daniweb.com/programming/software-development/threads/203645/data-field-alignment-and-union
CC-MAIN-2017-30
en
refinedweb
On Tue, 28 Mar 2000, Jack Jansen wrote: > > On Sat, 25 Mar 2000, David Ascher wrote: > > > This made me think of one issue which is worth considering -- is there a > > > mechanism for third-party packages to hook into the standard naming > > > hierarchy? It'd be weird not to have the oracle and sybase modules within > > > the db toplevel package, for example. > > > > My position is that any 3rd party module decides for itself where it wants > > to live -- once we formalized the framework. Consider PyGTK/PyGnome, > > PyQT/PyKDE -- they should live in the UI package too... > > For separate modules, yes. For packages this is different. As a point in case > think of MacPython: it could stuff all mac-specific packages under the > toplevel "mac", but it would probably be nicer if it could extend the existing > namespace. It is a bit silly if mac users have to do "from mac.text.encoding > import macbinary" but "from text.encoding import binhex", just because BinHex > support happens to live in the core (purely for historical reasons). > > But maybe this holds only for the platform distributions, then it shouldn't be > as much of a problem as there aren't that many. Assuming that you use an archive like those found in my "small" distro or Gordon's distro, then this is no problem. The archive simply recognizes and maps "text.encoding.macbinary" to its own module. Another way to say it: stop thinking in terms of the filesystem as the sole mechanism for determining placement in the package hierarchy. Cheers, -g -- Greg Stein,
https://mail.python.org/pipermail/python-dev/2000-March/002884.html
CC-MAIN-2017-30
en
refinedweb
Xamarin.Forms XAML Basics Getting Started with Cross-Platform Markup for Mobile Devices. - PDF for offline use - - Sample Code: - - Related Articles: - - Related Samples: - Let us know how you feel about this Translation Quality 0/250 XAML—the eXtensible Application Markup Language—allows developers to define user interfaces in Xamarin.Forms applications using markup rather than code. XAML is never required in a Xamarin.Forms program, but it is often more succinct than equivalent code, more visually coherent, and potentially toolable. XAML is particularly well suited for use with the popular MVVM (Model-View-ViewModel) application architecture: XAML defines the View that is linked to ViewModel code through XAML-based data bindings. XAML Basics Contents - Overview - Part 1. Getting Started with XAML - Part 2. Essential XAML Syntax - Part 3. XAML Markup Extensions - Part 4. Data Binding Basics - Part 5. From Data Binding to MVVM In addition to these XAML Basics articles, you can download preview chapters of our upcoming book Creating Mobile Apps with Xamarin.Forms. XAML topics are covered in more depth in many chapters, including: These chapters can be downloaded for free. Overview XAML is an XML-based language created by Microsoft as an alternative to programming code for instantiating and initializing objects, and organizing those objects in parent-child hierarchies. XAML has been adapted to several technologies within the .NET framework, but it has found its greatest utility in defining the layout of user interfaces within the Windows Presentation Foundation (WPF), Silverlight, and the Windows Runtime. XAML is also part of Xamarin.Forms, the cross-platform natively-based programming interface for iOS, Android, and Windows Phone mobile devices. Using XAML, the Xamarin.Forms developer can define user interfaces using all the Xamarin.Forms views, layouts, and pages, as well as custom classes. The XAML file is parsed at build time to locate named objects, and again at runtime to instantiate and initialize objects, and to establish links between these objects and programming code. XAML has several advantages over equivalent code: - XAML is often more succinct and readable than equivalent code. - The parent-child hierarchy inherent in XML allows XAML to mimic the parent-child hierarchy of user-interface objects with greater visual clarity. - XAML can be easily hand-written by programmers, but also lends itself to be toolable and generated by visual design tools. Of course, there are also disadvantages, mostly related to limitations that are intrinsic to markup languages: - XAML cannot contain code. All event handlers must be defined in a code file. - XAML cannot contain loops for repetitive processing. (However, several Xamarin.Forms visual objects—mostly notably ListView—can generate multiple children based on the objects in its ItemsSourcecollection.) - XAML cannot contain conditional processing (However, a data-binding can reference a code-based binding converter that effectively allows some conditional processing.) - XAML generally cannot instantiate classes that do not define a parameterless constructor. (However there is sometimes a way around this restriction.) - XAML generally cannot call methods. (Again, this restriction can sometimes be overcome.) There is not yet a visual designer for generating XAML in Xamarin.Forms applications, so all XAML must be hand-written. Although the XAML editor in Xamarin Studio supplies some syntax suggestions and automatic completion, the XAML editor in Visual Studio does not. In addition, some XAML errors slip through the build process and are not revealed until runtime. Programmers new to XAML might want to frequently build and run their applications, particularly after anything that might not be obviously correct. Even developers with lots of experience in XAML know that experimentation is rewarding. XAML is basically XML, but XAML has some unique syntax features. The most important are: - Property elements - Attached properties - Markup extensions They are discussed in detail in the articles below, which conclude with an introduction to using XAML for implementing MVVM. Requirements This article assumes a working familiarity with Xamarin.Forms. Reading An Introduction to Xamarin.Forms is highly recommended. This article also assumes some familiarity with XML, including understanding the use of XML namespace declarations, and the terms element, tag, and attribute. When you're familiar with Xamarin.Forms and XML, start reading Part 1. Getting Started with XAML..
https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/
CC-MAIN-2017-30
en
refinedweb
Go Unanswered | Answered Screensavers ~300 answered questions Parent Category: Software and Applications (non-game) Screensavers are applications that run when a computer is idle. Their purpose is to prevent damage to computer monitors and/or provide entertainment. 1 2 3 > How can you convert a flash file into a Windows screensaver? You can convert Shockwave Flash (*.swf) files into Screen Saver files (*.scr) using a program like InstantStorm, see the related link for their homepage. With a FlV converter, convert FLV or .swf files to gif or aiv.… Popularity: 85 Your screensaver comes up nothing else? go to google images type what u want click see full size image .right click on piture ,click set as background and hey presto Popularity: 2 How can you keep your screensaver when music is playing on the computer? Right click on your desktop and click personalize after that personalization window will appear, click on screen saver and set the minutes into a large number. Also, in the screen saver settings click change power settings and click change when the computer sleep and set the display settings. Popularity: 1 How do you create screensavers? MS PowerPoint Popularity: 11 Why are screensavers necessary? According to my knowledge this is because screen savers increases the life of your monitorUpdated 6/7/10your knowledge is correct Popularity: 13 How do you apply the digital time on your screensaver? computer screensaver configuring SCREENSAVER To get a screensaver to show digital time on your computer do the following as below: - - Take your mouse cursor to an empty area on your desktop and right click on the empty area. - The display properties dialog will come up on which you click screen… Popularity: 6 Does a LCD monitor need a screensaver? NOT REALLY, Older displays used technology that used Phosphors that were charged to make colors display. When an image was on the screen too long the phosphors would sometimes "burn out" with the constant energy and leave that ghastly image on the screen called "BURN IN". A LCD screen uses a complet… Popularity: 31 Whats wrong with your computer screen if whenever it goes in the black screen mode after the screensaver and you move your mouse and your screen go to desktop then black over and over again? Usually try a friends computer if your computer is experiencing difficulties. Otherwise make the year you were born in lower than 1900 because the site might think you are not old enough if you have a 1997 date.There are 3 step to repair blue screen error If you got blue screen error then there is … Popularity: 25 Where can you get a screensaver for WWE wrestler edge? Answer i love edge unchained wrestling wallpapers no 1 source for wwe tna and ecw wrestling wallpapers Popularity: 19 Where can you download Daniel Craig screensaver as James Bond in swimming trunks? type in "Daniel Craig + James bond swim suit" on Google images. Popularity: 2 What is a screensaver? A screensaver is the image, or video etc. that your computer puts on the screen when it goes into a lower power system (similar to "sleep" mode). Popularity: 1 How do you get rid of crawlercomI was trying to get a free screensaver and I got Crawlercom as my home page for Mozilla Firefox I have tried all that I know to delete it Please advise Thank you? just do a system restore.It worked for me Popularity: 1 Where does Windows save screensavers? I found this info On the net for Screan savers: SCR-files If the downloaded file is of 'scr' type, you need to move it manually to c:\windows unless author's instructions tell you otherwise (sometimes needs to go to c:\windows\system or c:\windows\system32). *Go to 'my computer', open c:\, then 'wi… Popularity: 8 How do you convert C source code into a screensaver for Linux? Most screensavers on Linux are modules run by Xscreensaver: I don't know exactly how to convert a program to a module, check the Xscreensaver documentation. Popularity: 2 What is Freeze Screen Saver exe Is it good or bad. Should I remove it from PC? freezescreensaver.exe is adware and should be removed immediately. Popularity: 2 What website does the best Pokemon Charmander screensavers? I would suggest using image sites. There is a good one in the related links below. Popularity: 5 In Windows XP whenever the screensaver comes on it goes back to the user login screen and how do you stop it from doing that? Right click on desktop/Properties On label "Screen saver" (the 3rd label, don't know how it's called exactly, as i don't use English XP) you can find a checkbox called password security or something similar. Check it out. NB: If you use a remote desktop connection while the screen saver turns on, … Popularity: 1 Where can you find the old screensaver where Barney The Dinosaur dies in various ways? I found only a link that does not work. But I also found what is supposedly the email address of the person who made it: Karl_A._Bunker@bcsmac.bcs.org I haven't written to it so I don't know if it will work or not. Popularity: 1 Delete pictures off screensaver and desktop? If you have a windows system you can do it two ways. One way is to go into the picture files and delete all pics or you can go into appearance and hit screen saver tab. When that comes up you will see what is programmed as your screen saver and you can change that with the drop down menu there. Same… Popularity: 2 Why does your computer need a Screen-saver? Computers these days do not need a screen saver at all, the monitors and screens have developed since the start. Originally the screens used to be CRT green screens which displayed the characters and information by sending a beam of light against a florescent background. When the computers were lef… Popularity: 4 What is the windows version of apple leopard mosaic screensaver? 2012 05 29 I found that in my search for windows version of this mosaic leopard screesaver: and 'version beta Regards, Myke974 Popularity: 2 How do you make screensaver for mobile phone? go to RED DOO Popularity: 9 Where is the screensaver island with three palm trees? roatan, honduras Popularity: 3 How can you get a spyro dawn of dragon screensaver on YouTube? You don't. But there's a cool free one that I got from spyroslair.com! Popularity: 1 A screensaver is best described as an? as an image or animation used to prevent desktop images from burning into the monitor. Back when CRT monitors were still used, any image left on the screen for an extended period of time would 'burn' into the monitor, and when you changed the image you could still see outlines of the image that w… Popularity: 2 What is the purpose of a screen saver on a computer? To save the screen. Popularity: 6 How do you put a screensaver on my computer screen? For Windows Users: In order to switch on the screen saver, you can right click on the desktop and select 'properties'. Then select the tab marked 'Screensaver'. It is turned on or off here. If you want to put on a screen saver than left click on your desktop. If you have Vista click personalise. Xp… Popularity: 5 How do you make a screensaver? You can use adobe flash player. Once you have downloaded it you should go to the start button and click on multimedia then on the flash player with the red icon.Hope this helps! Popularity: 3 Where can you find twilight screensavers? You can download Twilight screen savers from the link in related links. Popularity: 4 In your desktop properties screen saver and desktop is not showing i think some files are missing or get corrupted but how it will be resolved? This may be due to some spyware or adwares try to download the anti spywares. Popularity: 1 Where you can find Morning Glory Korean stationery company screensavers? Hey there. You can go in lots of places . There's one in bankstown, campsie,cabramatta and lots more Jenniferrr Popularity: 1 Make a picture a screensaver? if you have a PC put your mouse pointer over the picture you want as your screensaver and click the right side button of your mouse then somewhere in that list of words it says (set as backround) select that and you should have a sceen saver on your desk top. Popularity: 3. Popularity: 3 Where can you get a Yankees screensaver? Yankees.com has some cool ones. Otherwise just google image search Yankees and see what comes up. Popularity: 2 How do you change your screensaver? It Depends On Which Computer You Use. If You Have Windows Vista: 3: Find "Personalize" 4: Find "Screen Savers" 5: Select The Screen Saver and click OK. ------------------------------------------------------------------------------ If You Have Windows XP: 1:Right Click Desktop Note: You Mus… Popularity: 3 Where can you find screensavers for free? There are a few on yoyogames.com. Popularity: 3 Where can you get a WWE raw screensaver? On wwe.com/screen savers Popularity: 1 How do you make a slide show screensaver on a hp? on your screen have to left click then click properties on it says themes, desktop,screen saver, apperance,settings you wanna click screensaversthen click the down arrow button and pick which screen saver you want and that's how you get a screensaver Popularity: 2 Have the samsung tocco have moving images as screensavers and how can you do it if so? When You Open Images I Wont Move But When You Apply It As A Walpaper It Moves Popularity: 1 How do you make a screen saver? If you have a PC, you can go to the (paint) aplication on your start menu. You can there make a design or put a picture on the page. After you are completely done, Click the (File) icon, then click Save As. Name it anything you like. (DO NOT CLICK SAVE. MAKE SURE YOU CLICK SAVE AS!) From there you m… Popularity: 1 Are screensavers free? Most are free unless it says you have to pay. If it says you have to pay you have to pay. Popularity: 3 How do you change the screensaver on the xbox 360? Very carefully Popularity: 0 What is the optimal wait time before a screensaver kicks in? 10 minute delay before the screen saver kicks. my answer is (d) 10 minutes. Popularity: 2 What is the best wait time before a screensaver kick in? I put mine at 5 min. Popularity: 4 What the best time to put on you screensaver? When you ain't using the computer. Popularity: 6 A screen saver is best described as a? B. moving full-screen graphic Popularity: 3 Source code in C for moving circle screensaver? #include <stdio.h>#include <conio.h>#include <math.h>#include <graphics.h>#include<stdlib.h>void main(){ int dr,md,midx,i, midy,dx,dy,mx, my,k,x,y,xdir,ydir,oldx,oldy; double pi,tpi,a,t; void *ball; unsigned imgsize; dr = DETECT; initgraph(&dr, &md, "c:\\tc\\bgi… Popularity: 1 How do you retrieve a screensaver? Either right clik on your mouse or go to start and hit paint you can create your own screensavers there that's what i always do! Popularity: 3 Is bad dog screensaver still available? You really shouldn't want that screen Saver anyway... But in anycase I really don't know Popularity: 1 Need a screen saver? There are many places online where you can search for a screensaver, including screensavers.com. Popularity: 3 Where can you find a twilight screensaver? You can find a Twilight screen saver on Google Images. Just type in what image you want in the box then press search and it will give you all different picture that you can turn into screensavers. When you find the one that you want double click on it and then at the top of the screen press full siz… Popularity: 1 How do you set your screensaver? Right click on your desktop, then you click on "properties", then go to the "screensaver" tab and pick the screen saver that you want. Popularity: 3 Can you put music on your screensaver? Yes,we can put music on our screensaver . Popularity: 1 How do you set up a screensaver? To set up a screensaver, simply go to the desktop (which is the first screen you see after you log in or with the icons.) Right click on the background then go to propterties. There should be a tab at the top of the screen that opened, called screensavers. There you can change your screen saver. To… Popularity: 2 Why are screensavers used on computers? It keeps the computer screen from being burned of a still image on the glass because of the radiation of the catharay tubes. Popularity: 1 What is the name of the painting featured on the laptop screen-saver used by the art restorer in Palermo Shooting? Still Life with Oysters, Lemons and Grapes by Cornelis de Heem Popularity: 1 Why doesn't my screensaver doesn't come on? Well if you have set your screensaver to come on after the PC or laptop has not been used for 30 minutes and you have been sat there for ONLY 10 minutes then keep sitting there for another 20 minutes then you might see your screensaver? Popularity: 5 Screensavers blue beach sand with DELL? do you mean where can you get beach screen savers from dell ?? Popularity: 1 Rugby League State of Origin screensavers? You can check this site out ;) Regards, Literati Popularity: 15 How do you change the screensaver on an ASUS Eee PC running Linux? See: Popularity: 1 Can you change the screensaver on the samsung impression? Yes Popularity: 1 How do you make a video as a screensaver? If it's an existing video on YouTube, download the free "Video Saver" from . Enter the URL to the video on YouTube in the settings and click on "Save Settings" - done. If the video is not on YouTube, you could just upload it and set then e… Popularity: 4 Can you make a PowerPoint your screensaver? not since 2006 Popularity: 2 How does a screensaver function? Right click your mouse in the wallpaper click properties select screensaver then choose one and type what minute will it appear then click OK.Screensaver is a anti virus protection when you use it Popularity: 1 Can you change the screensaver on a samsung tocco? No. Popularity: 5 How can you make a YouTube video into a screensaver on a computer with optional sound? It's easy. just download the free "Video Saver" from . In the settings, enter the URL to the video on YouTube and hit "Save Settings" - you now have a new screensaver using a YouTube video. Popularity: 1 Where can you get a screensaver with the theme of gangster paradise? you can install it on one of those old dell computers they proboly don't sell them any more so i sugust u give up Popularity: 3 Does nokia 5800 have a clock screensaver? Not now but yes in a few years Popularity: 11 Are free screensavers safe to download? That is what I asked you.. I wouldn't have asked if I knew the answer. Popularity: 1 What is the difference between a screensaver and wallpaper? Wallpaper (also known as a desktop background) is a usually static image placed on the desktop area of many personal computers that use a graphical interface. Screen savers are programs that display moving / rotating images or animations after a certain amount of time with no user input has occurred… Popularity: 5 Where can you get 3d screensavers that move? Try doing a google search. Popularity: 2 How do you set screensaver in nokia 5800 express music mobile phone? download Popularity: 2 You want to set a screensaver on your laptop which consumes least energy? In Control Panel, power settings, select maximum battery life. Popularity: 1 A screensaver is best described as a? desktop background pattern or wallpaper Popularity: 3 Sai baba wallpapers and screensavers free download? Is chaitanya going to marry me Popularity: 1 If you unplug one monitor and hook up another monitor will you lose all of your screen savers? No, The screensavers are stored in the computer, not the monitor. Popularity: 1 You lost your screensaver for Mac pro? i have an mac pro, when I go into system preferences my screensaver is not there when i go into system preferences the screensaver is not there Popularity: 5 What do you call screensavers that move. Not the 3d ones but the ones where the characters in the screensavers move? Animated? Popularity: 3 How do you make gifs work as desktop wallpaper? Just download a working or moving gif and set that as desktop background and yes they do work that way. Popularity: 1 Where are the best Britney Spears screensavers? who gives a $hit. Popularity: 1 How do you put the screensaver on an iBook G4? Screen savers are set up in the DeskTop and Screen saver section of the System Preferences. After selecting which screen saver you wan to use you can either set a time delay so the screen saver starts after the computer has not been used for a few minutes or set a Hot Corner which will activate the… Popularity: 3 What is the benefit of using a screensaver? Benefit of a screen saver: Protects monitor screen from burning during idle monitors by screen saver utility program. This prolongs the life of the monitor.The Advantages of a Screen SaverIn past decades, computer monitors comprised of cathode-ray tubes often suffered "screen burn." A static image … Popularity: 0 What is the most popular screensaver for people's cellphone? a multi-colored zebra background, or a peace sign Popularity: 3 Where can you find good free moving screensavers? just go to your search bar and type in "free moving screen savers" youll be surprised at how many they are-its safe for ur computer and can be fun as well.i wish i could remember a couple for you,its been a while.i went back to the regular s.savers.lol good luck Popularity: 1 Does a computer virus effect the screensaver? Yes, Normally it will change the screen to blue. Popularity: 1 What are the uses of screen saver? They have no actual use nowadays, but back when computers with CRT screens first came out, they had 'burn in' problems. What would happen is the screens back then used a more powerful ion beam, and would burn holes in the screen if left too long. The purpose of the screen saver was to quite literall… Popularity: 2 Does screensavers give viruses? a lot of the "free" ones do! Popularity: 4 How can you use more than one screensaver? You will have to be more specific: Do you have two or more monitors, or just one? What operating system do you have? (e.g. Ubuntu, MS-DOS, Mac OS 9, Windows XP, etc.) Only after these questions are answered can this question be answered. Popularity: 4 Who invented screensavers? Adam Megilgot has a creeper mustach Popularity: 2 How do you make your screensaver your desk top image? for a mac go to terminal and paste this after it says your computer info (you have to set up a screen saver first) what to paste /System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background Popularity: 1 Where can you find your name in cool bubble letters for your screensaver? im not sure maby they might make a website bubbles letters Popularity: 1 Is screensaver saves computer power? yes,because it put the monitor into very low power consumption state,then you will be able to save lot of power Popularity: 1 Is it truth that screensaver can slow the PC? Uh, No Popularity: 1 In gta 4 theres a mission where you sneak into a guys house and then you go on his laptop and his screensaver is liesdamnliescom and i cant find that that house is it near the carnival? In the mission Right Is Wrong, Oleg Minkov's apartment is in Iroquois Avenue, Hove Beach, which is the street behind Niko's original safehouse in Broker. Popularity: 1 How do you add a new screensaver to your Control-Panel-Display drop-down choices list if you have already added the SCR file to your windows-System32 folder? Right click the scr file, click install. Popularity: 2 Where can you find free Barbie Doll screensavers to download? just research in the google free barbie screensavers Popularity: 3 Does Nexon have a Maple Story screensaver? Yes, the Zakum are available at their website. Popularity: 4 What is justin bieber's computer screensaver? That is a very strange question, as no-one could possibly know, and I don't see the point in knowing... but my answer is that there are so many screensavers out there that it could be anything! Popularity: 2 Can you put screensaver on Samsung C5220? Yes Popularity: 4 Does a screensaver conserve battery life? No, it doesn't. When your phone/laptop/tablet is idling and a screensaver is running, it uses CPU and it doesn't conserve battery life. Popularity: 1 1 2 3 >
http://www.answers.com/Q/FAQ/17177
CC-MAIN-2017-30
en
refinedweb
An Oracle White Paper June 2010 Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) Executive Overview ........................................................................... 3 Introduction ....................................................................................... 4 Rebranding .................................................................................... 4 Personalization .............................................................................. 5 Customization ................................................................................ 5 About Oracle ADF ............................................................................. 6 About Oracle Metadata Services ....................................................... 7 How MDS Manages Customization and Personalization ............... 7 Enabling Customization and Personalization ............................... 10 ADF Faces Change Persistence Framework ................................... 14 Change Manager ......................................................................... 15 Application Personalization Flow with MDS ..................................... 15 When MDS customization changes are persisted ........................ 17 How-to manually configure components for MDS persistence ..... 18 Identifying the user ...................................................................... 19 Configuring change persistence for a single component instance 22 How-to apply component changes in Java................................... 22 How to control personalization through authorization ................... 27 What you should know about regions or templates ...................... 29 Seeded Customization with MDS .................................................... 29 Understanding MDS Configuration in Oracle JDeveloper ............ 29 The CustomizationLayerValues.xml configuration file .................. 30 Default Customization Layers provided by ADF ........................... 32 Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) Building your own Customization Layer ....................................... 34 Defining Seeded Customization for ADF Applications ..................... 38 Starting Oracle JDeveloper in Customization Developer Role ..... 38 Customizing Pages ...................................................................... 41 Testing customized ADF applications .............................................. 45 Common MDS Customization Development Requirements ............. 45 How-to read attributes from the http session ................................ 45 How-to read context parameters defined in the web.xml file ........ 46 How-to read URL request parameters into a customization class 46 Using ADF Security in MDS customization and personalization....... 50 About the OPSS Resource Permission ........................................ 50 How-to check OPSS Permissions in Java ................................... 51 How-to protect MDS customization with OPSS ............................ 51 A Developer Check List for implementing MDS Customizations ...... 53 Summary ......................................................................................... 54 Appendix: Redirecting a JSF view to itself ....................................... 55 Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 3 Executive Overview A quote by Charles Darwin [1809-1882] is adapt to organizational changes, differences in end user preferences and changes in the business they support. Developers who create software for commercial or in house use, have the requirement to tailor their application to specific customer needs in a way that survives the installation of maintenance and error correction patches to the application over time. The ability of applications to adapt to changes is not a luxury in Enterprise 2.0. It is a necessity that needs to be considered in the application design and that should the drive selection of the development platform and architecure. Oracle Fusion Middleware (FMW) and the Oracle Fusion development platform combine proven technologies for application developers to build, deploy and run robust Java EE and SOA applications. With metadata on all tiers, the Oracle Fusion development platform, including the Oracle Application Development Framework (ADF), supports organizations in building cutting edge rich enterprise business applications (REA) that are customizable and personalizable in all dimensions. Oracle Metadata Services (MDS) is the customization and personalization framework integral to Oracle Fusion Middleware. It is a key differentiator of the Oracle development platform compared to other Rich Internet Application (RIA) and SOA solutions on the market. MDS seamlessly integrates with state of the art Java EE and Ajax technologies used in Oracle Fusion application development and the declarative programming paradigm promoted by the Oracle JDeveloper IDE and the Oracle ADF framework. This paper focuses on how-to build customizable business applications with the Oracle Fusion development stack, including ADF. It steps you through the basics of the Metadata Services architecture and demonstrates how you might integrate it into your custom applications. In addition, this paper covers advanced topics such as the integration of ADF Security, and how to programmatically persist component and attribute changes. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 4 Introduction A good investment is one with longevity. This is also true for custom applications you build. Worldly wisdom says that nothing is as certain as change. Therefore, to protect your investment in enterprise application development, the need to react to change should be considered a part of the application design and not as an optional nice-to-have. The ability of an application to change in response to external conditions, like the needs of the individual user working with it, also helps to ensure good usability and leads to higher rates of end-user adoption. “It is not the strongest of the species that survives, nor the most intelligent that survives. It is the one that is the most adaptable to change” - Charles Darwin [1809-1882] Before metadata customization, software developers used triggers and events built into an application to ensure that at runtime the application user interface (UI) tailors itself to the needs of the authenticated user, his or her responsibilities and organisational role and vertical. The areas in which customization is used include Rebranding Personalization Customization Rebranding The Brand is the visual identity of an application that associates it with a company, industry or market. The visual style of an application may change for various reasons, including acquisition, regional differences, modernization or other, for example seasonal, reasons. Look and feel definitions, like images and cascading style sheets (CSS) that have hard coded references in the application program code make it diffcult to change the look and feel dynamically and therefore should be avoided. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 5 Personalization Every end user is unique.. Even when sharing the same education, skills and job description, application users tend to have different preferences when it comes to how they like the user interface to be rendered. For example, agents that help customers online may have individual preferences of how the customer call history is displayed. Some agents may prefer a summary table to show the problem statements first, while others want to see the date of previous calls to be shown first. Similar, some agents may prefer list of values when querying or inputing data, while others don’t. Personalization, or user customization as it is also referred to allows users to make themselves at home within an application. Throughout this paper, we use the terms personalization and user customization interchangeably. Customization Application developers define customizations in cumulative layers that are applied at runtime to change a base application to the needs of a specific installation or user group. The customization layer itself is pre-configured and referred to as “seeded”. Customization may adapt an application to regional or industry differences, or just change its behavior and UI according to the responsibility of a user or group. Figure 1 shows a user interface that is customizable for normal users and power users. Compared to normal mode, the power user mode replaces list of values in the table filters with input fields and wizards with a single input form. A similar, very popular requirement expressed by customers is to show more or fewer attributes on an input form based on the configured user roles within an application. This requirement can be achieved easily using MDS customization. Another aspect of customization is security, which is not an obvious use case. However, using seeded customization to tailor the UI and navigation for the indvidual user helps to suppress the display of sensitive information if a user is not authorized to see it. Though all the above can be achieved using conditional statements in Java, such a practice would become unmanageable quickly. Source code, added declaratively or in Java, that does not add to the application core business functionality should not go into an application as it makes maintenance harder and more expensive. To address the Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 6 requirement for rebranding, personalization and customization efficiently, applications should be designed such that differences between the versions are kept external to the base application. Figure 1: Customized user web interface, adapting to the user role as “normal” and “power” users. The difference shows in the select options in the table filter, as well as in the input form, which for normal users is read only as they are supposed to use a multi step wizard. About Oracle ADF Oracle ADF is anchored in the UI binding work Oracle proposed for standardization in Java EE as JSR-227. ADF is actually the family name for a whole set of integrated technologies that help developers of different programming backgrounds to productively and quickly build leading edge Java EE web applications. These applications leverage standards such as JavaServer Faces, XML, CSS, a selection of Java EE business services, elements of Service Oriented Architecture (SOA) and the aforementioned binding layer. ADF uses XML where ever possible, to configure and drive these technologies. This use of metadata is a key component of the overall ADF architecture. Unlike other meta-information technologies like Java annotations, XML enables out-of-the box customization and personalization as it does not require application code to be compiled to apply changes to the application behavior or user interface. Oracle ADF is a core technology component within Oracle Fusion Middleware used by Oracle for its own in-house product development teams and customers alike. Because Oracle uses the same version of ADF that customers do, customers get a mature and future safe development stack that is already proven for building large scale business applications for the enterprise. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 7 About Oracle Metadata Services Oracle Metadata Services (MDS) is the personalization and customization engine within Oracle Fusion Middleware that manages all of this XML metadata of behalf of components such as JDeveloper and ADF. Metadata is used by the following components ADF Faces rich client Java Server Faces components ADF Faces Data Visualization Tools (DVT) ADF Task Flow ADF Binding layer ADF Business Components Oracle WebCenter How MDS Manages Customization and Personalization Customization and personalization are dynamic structure and property changes to the metadata of application documents like views, bindings and task flow definition files. Modifications that, for example, are applied as customization to a page or a page fragment include the addition, removal or property changes of UI components. An application that is customized with MDS consists of a base application and one or many customization layers that hold the modifications that are applied at runtime. A customization layer is defined by a set of metadata documents that are stored in a metadata store on the file system or the MDS database repository, and a customization layer object, a Java class that determines when to apply the changes. This customization layer class determines the conditions under which a specific customization is applied to the application at runtime. As you will see in this paper, using Java gives you great flexibility and control over how sophisticated customization use cases can be implemented. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 8 Figure 2: Customization layers are applied to construct the final user view of the application As shown in figure 2, each document in a customization layer defines changes for a single base application document, like for a page or page fragment. The runtime appearance and behavior of an application then is the outcome of the merged content of a base application with its document change definitions stored in the MDS repository. Customization in MDS is applied hierarchically in the order customization layers are defined for an application. This way, possible conflicts that may occur when different layers change the same setting of a component, are handled in a predictable way. As you will see later, the order of the layers is not necessarily statically defined but can also be influenced by the customization class object and thus the developer. MDS stores its customization definitions separately from the base application so that changes applied to the base application, such as a patch, have no impact on customization unless components are removed, in which case no customizations for this component are applied at runtime. If modifications of a base document remove a metadata element that has pending customizations, then no customization is applied for the missing artifacts, and he application continues running with no errors. Figure 3 shows another view of the layered customization architecture, including a personalization layer, in which customizations defined by the end user users at runtime is always added as the topmost layer. Note however that availability of user personalization points is also under the control of the application developer. The developer can define which elements of the UI can be both changed and persisted in response to user interaction. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 9 Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 10 the application definition but rather is stored in a separate metadata file specific to this layer and laver value. Enabling Customization and Personalization By default, Oracle Metadata Services is not enabled for Oracle Fusion web applications and all runtime changes of a component that are performed by the application user, such as reordering of table columns are transient and only last until the page is next refreshed. To configure component changes to last longer, application developers need to enable change persistence in Oracle ADF Faces. Change persistence is a component level framework in ADF Faces that tracks UI changes by the application user or programmatically applied by the application developer in response to a user action. This allows these changes to persist for the duration of the application user session. Oracle MDS can then be used to further extend the change persistence behavior to persist changes across application restarts. This enhanced behavior is enabled through a simple options dialog shown in Figure 4. Under the covers, these options make changes to the web.xml and the adf-config.xml configuration files for the application. Figure 4: View layer project properties to enable Change Persistence and MDS Figure 4 shows the two check boxes provided by the view layer projects ADF View settings. These are used to enable user runtime customization and seeded (design time) customization. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 11 User customization, or personalization, saves UI changed applied declaratively by the user or programmatically by the application developer in response to a user action. Personalization can be saved for the duration of the user session or across session re-starts using MDS. The following context parameter gets added to the web.xml configuration file if session scope persistence was chosen. <context-param> <param-name> org.apache.myfaces.trinidad.CHANGE_PERSISTENCE </param-name> <param-value>session</param-value> </context-param> Saving changes in the user session is an all or nothing choice. The developer cannot refine which components and which changes should be persisted. If there is a change on a component, for example the collapse of a particular panel box that the developer wanted to exclude, then the only option would be to override the change using Java. Choosing MDS persistence, the following entry is added to the web.xml file <context-param> <param-name> org.apache.myfaces.trinidad.CHANGE_PERSISTENCE </param-name> <param-value> oracle.adf.view.rich.change.FilteredPersistenceChangeManager </param-value> </context-param> <context-param> <param-name> oracle.adf.jsp.provider.0 </param-name> <param-value> oracle.mds.jsp.MDSJSPProviderHelper </param-value> </context-param> The FilteredPersistenceChangeManager class extends the default Apache Trinidad persistence and, for each component change request, verifies that no restrictions have been applied by the developers to individual component instances, using the component persist and dontPersist attributes, or to a component type as a whole. The following ADF Faces components expose the persist and dontPersist properties in the Oracle JDeveloper Property Inspector af:panelBox af:showDetail Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 12 af:showDetailHeader af:showDetailItem af:column af:tree af:treeTable af:panelSplitter af:calendar If no instance specific restrictions exist for a component, then restrictions are validated on the component type level. This is handled by a global configuration in the adf-config.xml file. The document change is passed to the document change manager configured in the adf-config.xml file to write it to MDS if no restriction is found. Document change requests that fail are still persisted for the current Session. Note: Figure 6 depicts the change request evaluation in MDS Note: To personalize ADF applications using MDS, you need to have at least one customization layer defined in form of a customization class specified in the adf-config.xml file. MDS provides default customization classes, for example UserCC that can be used to handle changes specific to a user. How to configure customization classes in adf-config.xml and how to enable changes persistence for components in MDS is covered later in this paper. If the view layer project does not already contain ADF bound components when enabling customization with MDS, two additional components are added to the web.xml file <filter> <filter-name>ADFLibraryFilter</filter-name> <filter-class> oracle.adf.library.webapp.LibraryFilter </filter-class> </filter> … <servlet> <servlet-name>adflibResources</servlet-name> <servlet-class> oracle.adf.library.webapp.ResourceServlet </servlet-class> </servlet> The ADFLibraryFilter and the ResourceServlet are used by ADF to load documents from ADF library archive files (JAR) if they are not found in the document root of the class path. All static Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 13 content found in ADF Libraries are either copied to the document root or directly added to the servlet response. The view layer project setting "Enable Seeded Customization" updates the web.xml with the configuration required for MDS-JSP integration. <context-param> <param-name>oracle.adf.jsp.provider.0</param-name> <param-value>oracle.mds.jsp.MDSJSPProviderHelper</param-value> </context-param> The configured MDSJSPProviderHelper class returns the requested page definition as merged XML document loaded from MDS. When enabling MDS, another ADF configuration file, adf-config.xml in the .adf/META-INF directory of the application, is updated as shown below <persistent-change-manager> <persistent-change-manager-class> oracle.adf.view.rich.change.MDSDocumentChangeManager </persistent-change-manager-class> </persistent-change-manager> In Oracle JDeveloper, the adf-config.xml file is accessible from the Application Navigator where it is located under Application Resources | Descriptors | ADF META-INF. You can open the configuration overview editor with a double click on the adf-config.xml entry. The adf-config.xml overview editor contains a “MDS Configuration” category and a “View” category, which both are used to configuring MDS for an application. The “MDS Configuration” category allows you to define customization layers for an application, for example the UserCC customization layer that is located in the oracle.adf.share.config package and that ship with ADF. The MDSDocumentChangeManager extends the SessionChangeManager class, the Apache Trinidad base handler for persisting component changes, and updates the MDS metadata document associated with a page. The MDSDocumentChangeManager is referenced by the FilteredPersistenceManager configured in the web.xml file after the document change request has been validated against restrictions defined in the adf-config.xml file. Note: Editing the web.xml file to replace the FilteredPersistenceChangeManager class with the MDSDocumentChangeManager class bypasses the change restrictions. While this may sound like a good idea, beware that doing so can reduce performance because of an increase in IO traffic between the application and MDS. In addition, you lose control over which component and component instances to persist changes. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 14 Figure 5: adf-config.xml file in Oracle JDeveloper ADF Faces Change Persistence Framework The change persistence framework has its origins in the Apache Trinidad open source project that provides the foundation for the ADF Faces rich client framework. The framework supports implicit and explicit persistence and restoration of component changes. Implicit component changes are performed by the ADF Faces component renderers, for example; saving the changed column order index of a table component or the disclose state of a ShowDetailHeader. Explicit component changes, on the other hand, are initiated by the application developer in Java. For example, developers may use Java to persist the changed order of panel boxes in a PanelDashboard, or the order of input text fields in a PanelFormLayout. Implicit and explicit component changes both usually occur in response to a user-UI interaction and can include Change to an attribute value Addition or removal of a child component Re-ordering of children within the same parent Movement of a child component into a different parent Addition or removal of a facet Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 15 Based on the configuration, the change persistence framework saves changes as temporary component changes in the session or as permanent document changes in the MDS repository. Developers that use the change persistence Java API for implementing explicit component changes don’t need to worry about handling this distinction as the programming interface – the ChangeManager API – automatically handles the distinction between component and document changes based on the configuration. Change Manager As mentioned, the change persistence framework is used for implicit and explicit component changes. Implicit component changes are automatically applied by the component renderer, whereas explicit changes require the developer to execute Java code in a managed bean method in response to events such as a button press. Both, implicit and explicit changes are controlled by an instance of the ChangeManager class. A single instance of the ChangeManager class exists in ADF Faces applications to persist changes that are applied during a request. Application developers access the ChangeManager from the AdfFacesContext to programmatically apply component changes. These changes can be applied during any phase of the JSF lifecycle once the server side in memory component tree is available. But wait – let’s not jump the gun and get into coding too quickly. ChangeManager coding examples will come later in this paper. For now it is important to understand that customization and personalization is a framework feature of ADF Faces that you can extend with seeded customization defined by MDS. Application Personalization Flow with MDS Personalization is the process in which application users make themselves at home within an application. As shown, the duration of a change is configured at the application level and may last for the length of a user session or survive application restart. Changes applied by these personalizations are added on top of other (seeded) customization layers defined by an administrator or the developer. As shown in the diagram below, in personalization the component change is initiated by a user action, like collapsing a panel header. With the next request, the change is passed to the server. If user customization is configured to use MDS, the MDS mode, whether customization is through the ADF view layer or Web Center Composer, determines how the change request continues. Without MDS, component changes are only persisted for the duration of the session, and are stored in a session variable, indexed by their viewId and componentId. They can then be applied upon subsequent page requests. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 16 Note: The runtime personalization of components contained in a page template are applied to the instance of the current view only. This is because the changes are indexed by the combination of viewId and the component Id and the viewId in this is the viewId of the page or page fragment that consumes the page template, not the template itself Figure 6: Personalization Flowchart If MDS is configured as a persistence store and the change request comes from the ADF view layer, then the configured FilteredPersistenceChangeManager checks if the requested customization is restricted on the component instance or in general for the component type. If customization is restricted in MDS then the component change is written to the user session only and will be forgotten when the session is abandoned. In addition, messages similar to the one shown below will appear in the log output <FilteredPersistenceChangeManager><_addDocumentChangeImpl> The DocumentChange is not configured to be allowed for the component: RichColumn[UIXFacesBeanImpl, id=c4] To persist changes for a specific component in MDS the adf-config.xml file needs to be edited to add the component and the attributes to store changes for. For this, open the adf-config.xml file Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 17 that is located in the Application Resources | Descriptors | ADF META-INF node of the Oracle JDeveloper Application Navigator. Figure 7: Configure ADF Faces components and attributes for global component type persistence in MDS Type persistence shown in figure 7 applies to all instances of a component within an application unless a component instance dontPersist attribute setting disallows persistence for a particular usage of the component. On the other hand, if a component type as a whole is not selected for runtime customization, the persist attribute can be used on a component instance level to enable personalization for this particular usage of the component. If the customization is not restricted, then as a last check, authorization is verified using the customization allowed property to ensure that only authorized users perform changes that are persisted to MDS. As mentioned earlier, to make user customization work, you need to configure a customization layer that identifies the current user. The supplied user customization layer in ADF is UserCC, which returns the name of the Java EE authenticated user for MDS to save changes. In the following section, we explain how to configure the UserCC customization class and what it does for you. When MDS customization changes are persisted Application UI changes that are applied by the user, for example when collapsing a PanelHeader component or PanelBox are persisted with the next request. For this, MDS is integrated into the ADF lifecycle as shown in figure 8. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 18 Figure 8: Metadata commit operation in the ADF page request lifecycle As shown in figure 8 above, the metadata changes are written to the MDS repository after the JSF Invoke Application phase. Note: When adding a component customization from Java, which we explain in the “How-to apply component changes in Java“, you don’t need to wait for a subsequent request to persist a change to MDS. How-to manually configure components for MDS persistence The “View” category in the adf-config.xml editor that is shown in figure 7 lists components that are configurable to use the ChangeManager API of the change persistence framework. The editor lists only components and attributes that are modifiable through the UI, for example when the user uses the mouse to rearrange the size of position of a component or component area. However, only because attributes are not listed to be modified through the UI doesn’t mean they cannot be changed and those alterations cannot be persisted in MDS. Later in this paper we illustrate explicit runtime customization in Java using the example of disabling the column reorder functionality of a table. This is accomplished by setting the “disableColumnReordering” attribute to true. In the example we use the AttributeComponentChange class to persist the attribute state change – true or false – to the session. To persist this change into MDS, in addition to persisting it to the user session, you must manually configure the adf-config.xml file as shown below. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 19 <tag name="table"> … </attribute> <attribute name="disableColumnReordering"> <persist-changes> true </persist-changes> </attribute> </tag> This configuration in adf-config.xml can be created for all components that you intend to change attribute state for programmatically. The syntax for this metadata is always the same and uses the tag element to specify the component, followed by the one or more attribute elements for which attribute states should be saved. Note: To enable all attributes of a component as candidates for MDS persistence, an asterisk ‘*’ can be used as a wildcard attribute name in the component tag configuration. This way you don’t need to list all possible attributes explicitly. Another example, explained later in this paper, when manual configuration of the adf-config.xml file is required is when child components are re-ordered, added or removed. For example, if child components of an af:panelFormLayout component are changed, for example a new field added, using drag and drop, then the following configuration must be added to the to the taglib-config | taglib section of the adf-config.xml file <tag name="panelFormLayout"> <persist-operations> all </persist-operations> … optionally add attributes to persist … </tag> Identifying the user If changes should be persisted beyond session scope, then MDS needs to know about the user identity to persist the changes for. This requires Java EE authentication and the UserCC customization layer to be configured for an application. To implement Java EE authentication, you can configure ADF Security to enforce authentication for an application. To use ADF Security, select Application | Secure | Configure ADF Security from the JDeveloper menu. In the first wizard screen, select the authentication only option and continue, accepting all the default settings. You can later re-run this wizard to enable Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 20 authorization or change the authentication from the default basic authentication to form based or other. Choose Application | Secure | Users from the Oracle JDeveloper menu to create user accounts to use during application testing with MDS. Note: Please also read “Enabling ADF Security in a Fusion Web Application” of the Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework 11g Release 1, available online 1 . The next step is to configure a customization layer that persists the component changes for a user. If you run the MDS enabled application without configuring a customization layer the following error message is displayed in the log when you perform a component change. <MDSDocumentChangeManager><getDocument> ADFv: Trouble getting the mutable document from MDS. oracle.mds.exception.ReadOnlyStoreException: MDS-01273: The operation on the resource /<page name> failed because source metadata store mapped to the namespace / BASE DEFAULT is read only. As explained in the customization flow shown in figure 6, if MDS change persistence fails, the change is only saved for the user session. Without a valid customization layer configured in the adf-config.xml file, the metadata store is read only and no changes can be persisted – hence the log message. UserCC customization class Customization layers are represented by Java objects, the customization classes, which determine when a specific customization should be applied at runtime. One of the default customization class provided by ADF is UserCC, which identifies the Java EE authenticated user to MDS. To configure UserCC for an application, open the adf-config.xml file in Oracle JDeveloper and select the “MDS Configuration” category. Click the green plus icon to search the class path for the UserCC class, as shown in the image below. The username is accessed from the ADF security context, which reads the name from the security principal of the authenticated session. Though the UserCC layer accesses the ADF security context, it is not mandatory to use ADF Security for user authentication and plain container managed security configured in the web.xml file of a web application is sufficient. 1 Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 21 Figure 9: Configuring UserCC customization class for an application Searching the view layer project class path, you’ll find more predefined customization classes provided by ADF. Note: The AdfUserCC and SiteUserCC classes are deprecated and should no longer be used in custom applications. Note: Creating and configuring your own MDS customization is simple and is covered later in this paper. For example, applications that handle user authentication within the program code, without using Java EE container authentication, may extend the UserCC class and override the getValue method to return the user name authenticated by their application login handling routine. The example we’ll show later in this paper to explain customization class development illustrates the use case of switching between power user and normal user modes for an application. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 22 Configuring change persistence for a single component instance Using MDS, change persistence that is saved across the individual user session can be configured for single component uses in a view, overriding the global component type definition in the adf- config.xml file. This provides developers with fine grained control over changes saved in MDS. To do this, developers set a value to the persist and dontPersist properties available on many ADF Faces components. Allowed values are space delimited names of component attributes that hold a component state, as well as the keyword “all” to persist or don’t persist all attributes. How-to apply component changes in Java So far, this paper has covered declarative user customization, which allows developers to implicitly save component changes performed by the application user. In the following, we explain how application developers can apply and persist component changes from Java using the ChangeManager API that is implemented by the MDSDocumentChangeManager, the FilteredPersistenceChangeManager and the SessionChangeManager classes introduced earlier. The ChangeManager change API is accessible from the AdfFacesContext object as shown below AdfFacesContext adfFacesContext = null; adfFacesContext = AdfFacesContext.getCurrentInstance(); ChamgeManager cm = adfFacesContext.getChangeManager(); Using the ChangeManager instance, component changes can be applied during any phase of the JavaServer Faces lifecycle in which the server side in memory component tree exists, i.e. after the JSF RestoreView phase. How-to persist attribute changes in Java In JavaServer Faces, component properties are defined by developers entering static values to the page source, dynamically using Expression Language, or even by using Java. Programmatic changes to component properties are temporary change and are reset when the component is removed from the JSF server side memory tree. This means that when the user navigates away from the current view, the change will be forgotten when they return. For a property change to survive navigation, a further step is required, in which the ChangeManager API is called to stored the change in the user session or, as we discuss later across application restarts in MDS. For example, the following menu item calls a managed bean to enable or disable the column reordering functionality of a table. <af:menuBar <af:menu Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 23 <af:commandMenuItem </af:menu> </af:menuBar> The onToggleColumnOrdering managed bean method is shown below. The current reorder behavior is read from the table component and then reversed. The persistAttributeChange helper method shown here is generic and can be used in your custom application developments as well. public void onToggleColumnOrdering(ActionEvent event){ //get access to the table instance handle, which is created //in the managed bean using the component “binding” property RichTable table = getEmployeeTableInstance(); boolean reorderingDisabledVal = (Boolean)table.getAttributes().get("disableColumnReordering"); //toggle component attribute value table.getAttributes().put("disableColumnReordering", !reorderingDisabledVal); //persist the change for the duration of the user session or //beyond using MDS this.persistAttributeChange("disableColumnReordering", table, !reorderingDisabledVal) } //private helper method to persist attribute changes private void persistAttributeChange(String attribute, UIComponent component, Object value){ AttributeComponentChange attributeChange = null; attributeChange = new AttributeComponentChange(attribute, value); FacesContext facesCtx = FacesContext.getCurrentInstance(); AdfFacesContext adfFacesCtx = null; adfFacesCtx = AdfFacesContext.getCurrentInstance(); //ChangeManager is of type oracle.adf.view.rich.change. //ChangeManager. ChangeManager manager = adfFacesCtx.getChangeManager(); manager.addComponentChange(facesCtx, component, attributeChange); } Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 24 As you can see from the code lines above, the use of the ChangeManager is independent of the type of persistence – session or MDS – that is used. To configure MDS for this change, edit the adf-config.xml file using the Oracle JDeveloper source view and add the following content <tag name="table"> … </attribute> <attribute name="disableColumnReordering"> <persist-changes> true </persist-changes> </attribute> </tag> Note: The oracle.adf.view.rich.change.ChangeManager class is deprecated and the Apache MyFaces Trinidad ChangeManager class should be used instead. However, due to a class incompatibility this is not yet possible. Until a fix is provided, please continue using the deprecated Oracle ChangeManager. Note: The Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework 11g product documentation provides an additional example that shows how to save a component’s disclosure state. How-to persist re-ordering of child components in Java Another popular personalization use case is to change the order in which components appear on a view. For example, an application may allow users to change the order of input components in an af:panelFormLayout using drag and drop. The following example code shows the page and managed bean source of an input form that allows users to move af:inputText components within the af:panelFormLayout, as shown in figure 10. These changes are then persisted. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 25 Figure 10: Changing and persisting the location change of an input text component using drag and drop and the ReorderChildrenComponentChange class To enable drag and drop on ADF Faces components, you use operation tags provided in the ADF Faces component library. The example below defines each inputText component as a drag source and drop target, which means that each component can be moved within the form. If a component is dropped onto another, then the drop component’s drop listener is invoked, which calls a managed bean method, “handleInputTextMove” in the example. Note: to learn more about drag and drop in Oracle ADF Faces applications, please refer to the “Adding Drag and Drop Functionality” section of the Oracle Fusion Middleware Web User Interface Developer's Guide for Oracle Application Development Framework <af:panelFormLayout <af:inputText value="#{bindings.DepartmentId.inputValue}" ...> <f:validator .../> <af:convertNumber .../> <af:componentDragSource/> <af:dropTarget <af:dataFlavor </af:dropTarget> </af:inputText> ... more input components ... </af:panelFormLayout> The managed bean method that is invoked by the dropTarget uses the drop event to determine the dragged component and the drop component to change the component order in the form layout. The changes are then persisted in MDS using the ChangeManager API. public DnDAction handleInputTextMove(DropEvent dropEvent) { FacesContext fctx = FacesContext.getCurrentInstance(); //access the payload of the drag and drop operation Transferable transferable = dropEvent.getTransferable(); Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 26 //get the UI component that is moved in the layout container UIComponent dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR); //get the component that received the drop. The dragged //component will be placed right below this component UIComponent dropComponent = dropEvent.getDropComponent(); //the parent layout component af:panelFormLayout UIComponent dropParent = dropComponent.getParent(); if (dragComponent != null && dragComponent != dropComponent) { //get the number of input components in the panelFormLayout int childCount = dropParent.getChildCount(); //create a list to hold the component Ids in the new order List<String> newComponentList = new ArrayList<String>(childCount); List<UIComponent> inputfields = dropParent.getChildren(); //iterate over all panelFormLayout children and compare the //child with the drag and the drop component to create the //new component order for (UIComponent currComponent : inputfields) { String currComponentId = currComponent.getId(); if (!currComponentId.equals(dragComponent.getId())) { newComponentList.add(currComponentId); if (currComponentId.equals(dropComponent.getId())) { newComponentList.add(dragComponent.getId()); } } } //Persist the changed component order ReorderChildrenComponentChange reorderedChildChange = new ReorderChildrenComponentChange(newComponentList); reorderedChildChange.changeComponent(dropParent); AdfFacesContext adfFacesCtx = AdfFacesContext.getCurrentInstance(); ChangeManager cm = adfFacesCtx.getChangeManager(); cm.addComponentChange(fctx, dropParent, reorderedChildChange); //Tell the parent panelForm to re-draw adfFacesCtx.addPartialTarget(dropParent); return DnDAction.MOVE; } Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 27 return DnDAction.NONE; } Note: If you use MDS to persist component changes, ensure that the adf-config.xml file is configured to allow customization of the parent container component; af:panelFormLayout in the example. For example, to allow component changes in MDS, the following entry needs to be added to the taglib-config | taglib section of the adf-config.xml file for the example above <tag name="panelFormLayout"> <persist-operations> all </persist-operations> … optionally add attributes to persist … </tag> More Component Change APIs In the Java API examples above, the following two APIs were used: AttributeComponentChange and ReorderChildrenComponentChange. There are more component change classes developers can use to persist user customization settings in MDS, all which are documented online in the “Allowing User Customizations at Runtime” section of the Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework product documentation. Additional options include: AddChildDocumentChange AttributeDocumentChange MoveChildComponentChange RemoveChildComponentChange SetFacetChildComponentChange SetFacetChildDocumentChange RemoveFacetComponentChange How to control personalization through authorization As explained, many ADF Faces components expose the persist and dontPersist property for developers to define a blank character delimited list of attributes to include in or exclude from personalization on the component instance level. The component level definition always overrides the configuration defined in the adf-config.xml file. The persist and dontPersist properties Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 28 do not, however, handle the case in where a defined group of users should be allowed to persist component changes whereas another group is not. For authorizing customization on the component level, the “Customization allowed by” property can be set to a username or security role name, as shown in figure 11. The information about component instance level customization authorization is not stored within the page or view source but in the view layer project’s mdsys | mdx folder. The folder is automatically created by Oracle JDeveloper when using one of the customization properties exposed for a component. The component change shown in the image below is configured in the mdx folder as shown <rdf:Description rdf: <customizationAllowed xmlns=""> true </customizationAllowed> <customizationAllowedBy xmlns=""> app_manager </customizationAllowedBy> </rdf:Description> Note that “t1” in the example code above is the Id property of the table configured in this example. The role name used can be the name of a Java EE security group, which we refer to as an Enterprise group, or an application role. Application roles are a specific semantic concept of the Oracle Platform Security Service (OPSS) that we talk a bit more about later in this paper. Note: If the default role based component instance level authorization is not what you want, then you can write your own implementation of ChangeManager to exclude user groups from customization on a global level, for example using JAAS permissions and ADF Security. The FilteredPersistenceChangeManager class and the MDSDocumentChangeManager classes however are both marked as final and cannot be subclassed, so the starting point for any such custom development is the SessionChangeManager class in Apache Trinidad. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 29 Figure 11: Customization authorization on the component level What you should know about regions or templates The ChangeManager saves and restores component changes in the context of the current view Id. A change that is applied for a component that resides in a region or page template, then this change is persisted only for the region or template instance on the current parent page or view. It does not affect any uses of the same region or page template in other pages or views. Seeded Customization with MDS Seeded customization allows developers to pre-define application settings for individuals or groups of users. For example, the salary attribute of an employee table might only be shown to managers, for all other roles it is completely removed from the page, something which is more secure than just trying to hide the data in the UI layer. While user customization is created at runtime and applied at runtime, seeded customization is pre-defined during application development and dynamically applied to a document request at runtime. Customization includes changes on the UI layer, the controller layer, the binding and the business services layer, if ADF Business Components is being used. Understanding MDS Configuration in Oracle JDeveloper Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 30 Seeded customization is enabled in the ADF view setting of the view layer project properties by checking the “Enable Seeded Customizations” checkbox in the project properties. Figure 12: Enabling seeded customization in the view layer project properties In addition, the Oracle JDeveloper design time needs to know about the customization layers and their possible values to display when running Oracle JDeveloper with the Customization Developer role. The CustomizationLayerValues.xml configuration file At design time, MDS customization layers are represented by a physical object, the customization class, and an entry in an Oracle JDeveloper wide configuration file that defines the customizable layers and their values. The configuration file is CustomizationLayerValues.xml and is located in the <JDeveloper WLS installation home>\jdeveloper\jdev directory. A valid layer configuration entry in the CustomizationLayerValues.xml file looks as shown below <cust-layers <cust-layer name="…" value-set-size="…" Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 31 <cust-layer-value </cust-layer-value> … </cust-layer> … </cust-layers> The following table explains the individual configuration elements and attributes used in the CustomizationLayerValues.xml file ELEMENTS AND ATTRIBUTES MEANING OF VALUE cust-layer One to many entries that define the allowed customization layers for which a customization class exist. name The name of the layer as defined in the customization class. The UserCC customization class for example has a name defined as “user” which also must be the name of the configured customization layer when used with seeded customization value-set-size Allowed values are “no_values”,”small”, “large”. Setting the value to “no_values” hides the layer from the design time in which case it is used at runtime only. A value of “small” displays the list of allowed layer values in Oracle JDeveloper in a single select list, which is good to use for a smaller value sets. Using “large” as the size information renders the allowed layer values in a LOV id-prefix Optionally, but useful, MDS allows to specify an id for the layer itself that will be added as a prefix to the customization layer id. Setting an id-prefix for the layer helps avoiding conflicts that may occur for cust-layer-value definitions that use the same id prefix. cust-layer-value Defines one or more allowed values for a customization layer. The values are displayed in Oracle JDeveloper after selecting the customization layer and allow developers to define metadata changes for a specific group of users or site of installation value A value returned by the getValue method of the customization class. The UserCC class for example returns authenticated user names, whereas the AdfRoleCC class returns the roles the authenticated user is a member of. display-name A user friendly name that is shown in the Oracle JDeveloper IDE when working in the Customization Developer role id-prefix A unique string in the context of the customization layer that is used as the namespace for the customization metadata created for the cust-layer-value Table 1: CustomizationLayerValues.xml configuration elements Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 32 Note: The CustomizationLayerValues.xml doesn’t belong to the application but is an IDE wide artifact. This means that it will not be part of the source code tree for a particular workspace and therefore will not be under the same version control as the application. To version customization layer information with the application, we suggest to provide application specific customization layer definitions in a text file in a custom folder within the view layer project. For runtime and deployment this file is not required. Default Customization Layers provided by ADF As mentioned earlier, customization layers are identified by customization classes at runtime. Or to put this differently, every customization layer defined in CustomizationLayerValues.xml has a physical object representation at runtime that defines which customization to apply. JDeveloper contains a set of default customization classes that include the UserCC, AdfRoleCC and SiteCC objects. UserCC As we have seen, the UserCC customization class is used to identify user session for personalization. However, it can also be used for seeded user customization, although this is less common. The UserCC class reads the user name from the authenticated user principal class in the Java EE session. If the user information is stored in another location, like RDBMS, LDAP or a JSF managed bean, then developers can extend UserCC, overriding the GetValue method, or write a complete custom implementation of the “user” layer. To enable the UserCC layer for seeded customization, edit the CustomizationLayerValues.xml configuration file and add an entry for the customization layer and its values as shown below. Note that “user” is the name returned by the UserCC customization class’s getName method. <cust-layer <cust-layer-value <cust-layer-value </cust-layer> Opening Oracle JDeveloper in Customization Developer role shows an entry “user” for the customization layer, as well as “Steven King” and “A. Hunold” as the two options to provide seeded customization for. All changes that are configured for the user “Steven King” are stored in MDS using the “user_sk” namespace prefix, whereas document changes defined for “A.Hunold” have “user_ah” added as a prefix. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 33 AdfRolesCC The AdfRolesCC class reads user role memberships from the ADF security context. Security roles that are defined on the Java EE container are referred to as enterprise roles whereas roles defined in the jazn-data.xml configuration file are referred to as application roles. The difference between the two types of roles is their scope. Enterprise roles are Java EE container wide roles that can be accessed and used by all applications deployed on a server. Application roles are specific for a single application and are mapped to enterprise roles upon deployment. Application roles are used for fine grained authorization by the Oracle Platform Security Services (OPSS) and ADF Security. The enterprise role membership of a user is determined by the identity management system that is accessed by the authentication provider handling the user login in Oracle Weblogic Server (WLS). Application roles have a narrow scope as they are defined for a single application only. They are mapped to users and/or enterprise roles that are available in the identity management system. In the example configuration below, the application roles are defined as employees and managers. You configure the AdfRolesCC layer in the CustomizationLayerValues.xml configuration file as shown below. <cust-layer <cust-layer-value <cust-layer-value </cust-layer> Note: The AdfRoleCC layer name is defined as “role” in the customization class. SiteCC The SiteCC layer returns a single value “site” and allows developers to customize an application for a point of installation. To make SiteCC configurable, you can override the getValue method in a subclass. For example, in the Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework 11g documentation, an example is provided in which the site information is read from a properties file that allows developers and administrators to easily change between the configured site. Other custom implementations may read site information from a database or the application context. <cust-layer <cust-layer-value </cust-layer> Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 34 Note: An interesting custom implementation of SiteCC that also shows how to integrate ADF Security in MDS customization layers is documented in the “How-to read URL request parameters” section later in this paper. Building your own Customization Layer Developers can build their own customization layers to shape the application runtime. To build a custom layer, the following steps are required: A customization class needs to be built that defines the customization layer name, as well as the values used to identify the change metadata to apply to a document. Non default customization classes need to be deployed as an Oracle JDeveloper extension into the <JDeveloper WLS installation home>\jdeveloper\jdev\lib\patches directory so they become accessible for the IDE when started in customization role The customization layer must be configured in the CustomizationLayerValues.xml file How to develop and deploy custom customization classes Customization classes are not usually application specific and so should be built in their own Oracle JDeveloper project. When creating a new customization class project, configure the project libraries to include the “MDS Runtime” and the “MDS Runtime Dependencies” libraries. Customization classes extend the abstract oracle.mds.cust.CustomizationClass or an existing implementation of it, such as UserCC. They must provide an empty constructor, be thread safe and should be tuned as they are called for each user request. Customization classes that require access to external resources, such as LDAP or RDBMS serves, should release the resource handle at the end of a call and where possible cache values queried from the resource to reduce the need for repeated access to the external resource. Furthermore, the cache hint value returned by a customization class should make MDS to keep customization definitions in memory for as long as possible. Note: The CustomizationClass abstract class has more public methods developers can override. For ADF application development and deployment purposes however we don’t yet see a need for developers to change the default behavior of these. When starting your own customization class development, you will need to provide implementations for the getName , getCacheHint and getValue methods at the very least: getName A customization is identified by the name and the possible values of the customization layer. The getName method defines the name for a customization layer, for example “user” for the UserCC layer that is used by developers in Oracle JDeveloper to select and customize the layer. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 35 public String getName() { return "powerUserCC"; } Note: The name value returned by the customization class must match one of the cust-layer names when defined in the CustomizationLayerValues.xml file. getCacheHint The cache hint information provides information about how long a change definition read from the MDS repository should be kept in memory and whether, or not, internally it should be cached for multiple users. The cache hint returned by a customization class can have one of the following values ALL_USERS – The customization is applied to all users of an application and therefore needs to stay in the cache much longer than other definitions MULTI_USER – The customization is applied to a group of users across application sessions USER – The customization is applied to an individual application user session, which is defined as the HTTP servlet session for web based application. REQUEST – The customization is for a single request only, it does not need to remain in memory public CacheHint getCacheHint() { return CacheHint.ALL_USERS; } getValue The getValue method determines the selected value for a customization layer. Because document changes in seeded customization are defined by a customization layer / value pair, the value(s) returned by the getValue method is the part that influences the visual appearance and behavior of an application. The getValue method has two arguments, RestrictedSession and MetadataObject. The RestrictedSession represents a handle to the MDS session and provides developers with information about the MDS context and configuration through the SessionOptions object that it returns. Note: Information like the user locale is directly exposed on the MDS RestrictedSession object. The direct access however is deprecated and will be removed in a future version. Use the SessionOptions object instead to access this type of information. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 36 The MetadataObject argument provides developers with a handle to the top level metadata document and its element hierarchy exposed as JAXB compliant bean objects. The use of this object is an advanced concept that goes beyond the scope of this whitepaper. The value returned by the getValue method is an array of String values. Each string in the array represents a customizable layer value for which developers can define seeded customization in Oracle JDeveloper. If the getValue method returns more than one value, then all of the defined customization changes are applied to the requested document in the order in which the values appear in the array. The document change definition of the first value in the array is applied to the base document, followed by the change definitions of the second value, and so on. The order of the values in the array is important as it determines which layer value wins in cases where two layer values lead to modification of the same metadata object. Customization class template Provided below is a skeleton template that you can build on for your own customization classes import oracle.mds.core.MetadataObject; import oracle.mds.core.RestrictedSession; import oracle.mds.cust.CacheHint; import oracle.mds.cust.CustomizationClass; public class MyCustLayerCC extends CustomizationClass{ public MyCustLayerCC () { super(); } public CacheHint getCacheHint(){ return CacheHint.<YOUR CHOICE>; } public String getName() { return "mycustlayer"; } public String[] getValue( RestrictedSession restrictedSession, MetadataObject metadataObject) { //determine an array of return string, each representing //a customization layer value. return new String[0]; } } Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 37 How to configure custom Customization Layers in Oracle JDeveloper To use a custom customization class in Oracle JDeveloper, you need to deploy it in a JAR file to the <JDeveloper WLS installation home>\jdeveloper\jdev\lib\patches directory. The custom layer class needs to be configured in the adf-config.xml file, which is accessible in Oracle JDeveloper from the Application Navigator. To edit this file, select Application Resources | Descriptors | ADF META-INF and double click onto the adf-config.xml file entry. Use the MDS Configuration panel and press the green plus icon to search and select the customization class, as shown in figure 13 below: Figure 13: Searching or customization classes in the class path After this, configure the customization layer name returned by the customization class in the CustomizationLayerValues.xml. In the case of the PowerUserCC customization class example shown in the image above, the layer name is “powerUserCC”. If a user is a power user, then the customization class getValue method returns “poweruser” as a value, which can be used to define seeded MDS customizations configuration in the CustomizationLayerValues.xml, which is located in the <JDeveloper WLS installation home>\jdeveloper\jdev directory. <cust-layer <cust-layer-value value="poweruser" display-name="Power User" Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 38 </cust-layer> Defining Seeded Customization for ADF Applications In this section, we continue with the power user customization layer example that will be used to configure the application to display an advanced – dialog, LOV and wizard free, user interface to users that run an application in power user mode. To define seeded customization for an application, start Oracle JDeveloper in the Customization Developer role to shape the IDE to only allow changes to customizable metadata. All other files, such as Java classes or project properties, are read only and cannot be changed in this mode. For all document changes, Oracle JDeveloper creates a change document for the selected customization layer that contains MDS change directives for the modifications made by the application developer. At runtime, the change document based on the application MDS configuration and the value evaluation of the customization class, is merged with the base document. Starting Oracle JDeveloper in Customization Developer Role To start Oracle JDeveloper in Customization Developer role select this option in the “Select Role” dialog that shows by default when starting the IDE. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 39 Figure 14: Select Role dialog displayed when starting Oracle JDeveloper Another option to start Oracle JDeveloper in Customization Developer role is to use the Roles option in the Oracle JDeveloper Preferences dialog that you open from the Tools | Preferences menu option. This dialog also allows you to re-enable the default JDeveloper behavior to always show the role selection dialog at IDE startup. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 40 Figure 15: Selecting the Customization Developer role in the Oracle JDeveloper Preferences dialog Starting Oracle JDeveloper in Customization Developer role shows an additional panel to select a customization layer and value from options defined in the CustomizationLayerValues.xml. Seeded customization metadata is then created based for that particular combination. Figure 16: Customization layer selection window in Customization Developer role In figure 16 above, customizations are created for the “America Deployed” value of the site customization layer, a custom implementation of the default SiteCC class, shown here: Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 41 public class DynamicSiteCC extends SiteCC{ public DynamicSiteCC() { super(); } @Override public String[] getValue(RestrictedSession restrictedSession, MetadataObject metadataObject) { String[] _values = null; //determine site values … //americas, emea, apac return _values; } } Note: Later in this paper we come back to the DynamicSiteCC class and how to determine its site value The Tip Layer selection shown in figure 16 defines the layer which has “design focus” in the IDE and for which new MDS metadata is created. However, customizations configured on other layers, for example the “powserUserCC” layer are active as well and display in the Oracle JDeveloper visual design editor when customizing the site layer. This behavior at design time mirrors the runtime behavior of MDS in which the resulting document is the merger of the base document with the tip layer and all other layers between. It also allows developers to override customizations performed in one of the other layers if they are not desired in the context of a specific tip layer value. The “CustomizationContext” message outlined in figure 16 provides developers with the information about which customization layers and values contribute to the current document view. In this case, the resulting document is the outcome of the base document merged with the user layer set to the “sking”, the powerUserLayer set “poweruser” and the site layer set to “America Deployed”. Note: When changing from the “Default Role” to the “Customization Developer” role in Oracle JDeveloper, pay extra attention to the selected workspace after the Oracle JDeveloper restart to avoid accidentally editing the wrong base application. It is probably a good idea to start the IDE with the –noreopen flag to ensure that the editor area is initially empty and does not contain open files from the wrong workspace. Customizing Pages When running in Customization Developer role, the Oracle JDeveloper IDE looks the same as in Default Role, which is used to build the base application. The only visual differences are a lock Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 42 overlay icon shown next to base application documents that are not customizable (such as Java source files) and the appearance of the Customization Layer Selection panel. Figure 17: Overlay icons in Customization Developer role view Note: MDS customizes metadata information only. To customize Java Objects like managed beans, create different versions of the Java Objects in the base application and change the bean reference in the task flow metadata definition in Customization Developer role. MDS change documents are stored under a specific “mdssys” folder that is created for each customization layer and value combination. As developers create seeded customizations for the base document the metadata changes are stored in this directory tree in the form of XML “diff” files that contain the name of the changed base document. To edit a JSF page document for a customization layer, double click the document so it opens in the visual page editor. The document can then be edited in the normal way, for example, you can use the component palette to add ADF Faces components to a document. In the following example we show the change document created for the allEmployees.jspx page when the power user customization (powerUserCC) layer value is configured for “poweruser” Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 43 (See figure 18). In this case, all wizards and dialogs are replaced with input fields for faster data entry. <mds:customization version="11.1.1.55.36" xmlns: <!—- Replace af:selectOneChoice in table filter with af:inputText --> <mds:replace <mds:insert parent="c3(xmlns(f=))/ f:facet[@name='filter']" position="last" xmlns: <af:inputText xmlns: </mds:insert> <mds:replace <mds:insert parent="c2(xmlns(f=)) /f:facet[@name='filter']" position="last" xmlns: <af:inputText xmlns: </mds:insert> <!—- Delete af:commandButton that launches dialog to edit user data in bounded task flow --> <mds:replace <!—- Show additional af:inputText fields for the power user to edit employee data --> <mds:modify <mds:attribute </mds:modify> … </mds:customization> Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 44 Note: Explicitly closing and re-opening the base document forces a refresh of the document display in Oracle JDeveloper. Though it is not recommended to manually edit the MDS change documents located in the mdssys folders, if you do, then closing and then reopening the base document will apply and display the changes in the visual editor. Figure 18: Application Navigator in Customization Developer role showing MDS change documents for an ADF binding definition and JSF document Note: MDS change documents that are created when customizing an application cannot be deleted within the Customization Developer role. To delete a customization document that is no longer required, switch to the Default Role and delete it from the Application Navigator. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 45 Testing customized ADF applications For the purposes of this paper, testing and deployment is with and to the integrated Weblogic server (WLS) in Oracle JDeveloper 11g. To test MDS customizations from Oracle JDeveloper 11g, select a page document and choose the run icon from the menu or context menu. Implicitly this creates all the required deployment artifacts to deploy and run the application. Like any other web application you run from Oracle JDeveloper, you can do so both in debug and non-debug mode. For the integrated WLS to find custom customization classes, they must be deployed with the application. To ensure this, either reference the customization classes in a JAR file from the web layer project or add the customization class project to the list of dependencies. If you add JAR files configured as an Oracle JDeveloper library, make sure to select the Deployed by Default check box when creating the new library. Common MDS Customization Development Requirements The more flexible a customization should be in for a particular ADF application, the more likely it is that customization classes need to access the application or runtime context. In the following example we illustrate how developers can access the current user session, web.xml file context parameters and URL request parameters all from within customization classes. How-to read attributes from the http session The HTTP Session is accessible in a customization class through the ADFContext class. The ADFContext class is located in a shared JAR file that is added to the classpath when the MDS Runtime Dependencies Library is configured for an Oracle JDeveloper project. To access the http session object in the customization code, you need to add the Servlet Runtime library to the project as well. import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import oracle.adf.share.ADFContext; … ADFContext adfCtx = ADFContext.getCurrent(); Object _request = adfCtx.getEnvironment().getRequest(); if (_request != null && _request instanceof HttpServletRequest) { HttpSession _session = null; _session = ((HttpServletRequest)_request).getSession(true); Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 46 … } This allows you to read information from the session to configure a customization layer, for example, in response to user preference settings. How-to read context parameters defined in the web.xml file Instead of reading initial customization layer settings from a properties file, as it is explained in the Oracle product documentation, you can also read them from context parameters in the web.xml file, as shown below //accessing the MDS session SessionOptions so = restrictedSession.getSessionOptions(); ServletContext servletContext = null; servletContext = (ServletContext) so.getServletContextAsObject(); //read context parameter Object powerUserServletContextFlag = servletContext.getInitParameter("powerUserCC"); The restrictedSession variable is of type RestrictedSession and is provided by default as an argument to the customization class’s getValue method. How-to read URL request parameters into a customization class Using the ADFContext object, it is possible to access request parameters directly from the customization layer. In practice, however, this approach proves difficult to use because of the ADF Faces lifecycle. The default behavior in ADF Faces is to lazily load data for better performance when rendering views. For this, multiple partial requests are submitted to the server to fetch data behind the scenes during page rendering. Only the first GET request in this sequence will have the request parameter added to the URL. Therefore developers need to make sure the value of the parameter is persisted so it survives subsequent partial requests used to populate the page. Even if developers can ensure that subsequent requests do not override the parameter value defined on the initial request, for example by detecting the partial submit nature of a request, the value must be stored somewhere so it is available for read in the customization class. One option is to write the parameter value as a property into the MDS session. However, the MDS session only lives for the duration of the request, which means that subsequent requests will grab a new MDS session and not include this information. Therefore, a better option is store the value onto the HTTP Session and use the technique that we have already demonstrated for utilizing that value from within the getValue() method. Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 47 Another, alternative to using the HTTP Session directly is to use a servlet filter to write the request parameter to the session and to enforce security on the parameter usage. The use case shown to illustrate this technique is a customization that reads the site customization value from a context parameter configured in the web.xml file. Using a URL request parameter – siteCC – MDS administrators can temporarily override the site value defined in the web.xml file, for example to test seeded customization. To protect the ADF application from malicious use of this request parameter, the request parameter is restricted by a JAAS permission enforced by ADF Security. If the authenticated user is not allowed to override the site customization then the request parameter is ignored. The code for the servlet filter that implements this shown next: final String SITE_URL_PARAM = "siteCC"; final String SITE_CC_SESSION_ATTIBUTE = "adf.sample.cc.SiteCC.value"; … public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException //check if siteCC parameter is on the request URL HttpServletRequest _req = (HttpServletRequest) request; HttpSession _session = _req.getSession(false); Object siteCCUrlParam = _req.getParameter(SITE_URL_PARAM); //set parameter if user is authorized to override the //site customization value if(siteCCUrlParam!= null && isAllowedOverride()){ //if the request value is “reset”, then remove the session //attribute so the default site customization configured in //web.xml shows if(((String)siteCCUrlParam).equalsIgnoreCase("RESET")){ _session.removeAttribute(SITE_CC_SESSION_ATTIBUTE); }else{ _session.setAttribute(SITE_CC_SESSION_ATTIBUTE, siteCCUrlParam); } } chain.doFilter(request, response); } private boolean isAllowedOverride(){ … } Building Customizable Oracle ADF Business Applications with Oracle Metadata Services (MDS) 48 Note: The code to check authorization is explained later in this paper Because the ADF security context is used to check authorization, the servlet filter needs to be configured to execute after the ADF binding filter in the web.xml file. … //adf bindings filter … <filter> <filter-name>SiteCCFilter</filter-name> <filter- class>adf.sample.poicc.servlet.DynamicSiteCCFilter</filter-class> </filter> … //adf binding filter mapping … <filter-mapping> <filter-name>SiteCCFilter</filter-name> <url-pattern>/faces/*</url-pattern> </filter-mapping> Next the DynamicSiteCC customization class is created to read the site value from the web.xml context. If the site information is overridden in the http session and the user has the permission to use it, then this information is used instead. Log in to post a comment
https://www.techylib.com/en/view/streakgrowl/building_customizable_oracle_adf_business_applications_with_oracl
CC-MAIN-2017-30
en
refinedweb
naugaranch wrote: Sounds like Red Hat is doing a MS-type end around. Abandon the RH 8.x series and introduce RH 9 because it doesn't have a bad reputation. When a release puts a better product in the hands of the consumer it is a good and welcome thing. When a release exists for the purpose of revenue generation or as part of a bit of demographic infighting, everybody loses. It's sad to see how prevalent MSing is becoming in the Linux namespace.
https://listman.redhat.com/archives/psyche-list/2003-March/msg01275.html
CC-MAIN-2017-30
en
refinedweb
Start a hosting plan from $3.92/mo and get a free year on Tuts+ (normally $180). Let's get started. Introduction If you're a beginning Android developer with one or two basic applications under your belt, then you should be able to complete these tutorials without much difficulty. The game will have a simple, basic structure so that you can add your own enhancements to it when you've completed the tutorials. Throughout this series, I will point out optional steps you can include to add additional functionality and to improve support for a wider range of Android devices. The user interface, for example, will be simple, but I encourage you to give it more love to make the game more appealing. The following screenshot should give you an idea of what the final result will look like. This tutorial is split up into three distinct parts. - Project Setup - User Interface - Gameplay and Interaction Our game will be a traditional Hangman game. It will choose a random word, presenting placeholders for each letter so that the user knows its length. The game will of course display a gallows area and buttons for each letter of the alphabet. Whenever the user taps a letter, the application will check whether the word includes the letter. If it does, the letter is revealed in the word. If the word doesn't contain the selected letter, one part of the body will be displayed in the gallows area, starting with the head. The user can make up to six wrong guesses and still win the game. However, if they make a seventh mistake, it's game over. If the player needs less than seven guesses, she wins the game. Are you still with me? 1. Create a New Android Project Step 1 Create a new Android project in your IDE (Integrated Development Environment) of choice. In this tutorial, I will use Eclipse. In Eclipse, select New > Project from the File menu. In the Android section, select Android Application Project and click Next. Enter an application, project, and package name. To keep things simple, the application targets API 16, but you may wish to support older versions. If you decide to do so, you'll need to carry out some additional processing. Click Next to continue. Step 2 In the Configure Project window, it is up to you to choose if you'd like to create a custom icon. However, make sure to check the Create activity and the Create Project in Workspace check boxes. Click Next. Set a launcher icon and click Next. In the Create Activity screen, select Blank Activity and click Next. You can modify the activity class and layout names if you prefer, but the default names work just fine as well. Click Finish to create your new project. Now is a good time to configure the themes and styles associated with your application. To match the demo application, set the AppTheme in your res/values/ styles XML file to android:Theme.Holo. The default settings work fine, but your application's user interface will differ from the screenshots in this tutorial. 2. Create the User Interface Images Step 1 Our application will present an intro screen with a play button to the user and a separate screen for the game itself. As you can see in the previous screenshot, the screen used for the game includes a number of images for the gallows and body parts. Beneath the gallows is the area for the word the user needs to guess and a grid with the letters of the alphabet. We will also use an action bar for navigating the game and it will also contain a help button. We'll need quite a number of images for the gallows, the body parts (head, body, arms, and legs), the help button, and a background image for the intro screen. You can find these images in the source files of this tutorial, which you can find at the top of this tutorial. Keep in mind that you need to create additional images if you aim to target a broader set of devices with different screen sizes. Download the images and add them to the drawable folders in your project directory. Make sure that you are using images suited for the various screen densities on Android. Step 2 The application is also going to use some drawable resources that we can define as shapes in XML. These include the background for the letters in the word the user needs to guess and the background for the letters of the buttons (normal and highlighted state). These will also need to be tailored to the different screen densities that you want your application to support. The sample code of this tutorial gives you a good starting point. Let's start with the background of the letters. Create a new file in your project drawables and name it letter_bg.xml. Enter the shape shown in the code snippet below. <shape xmlns: <stroke android: <solid android: <padding android: <size android: </shape> If you aren't familiar with creating shapes in XML, this may seem a little confusing. The result is an underline, which will be displayed as the background of each letter in the word the user needs to guess. Next, create another file in your project's drawables for the letter buttons in their initial state and name it letter_up.xml. Add the following snippet to the file you've just created. <shape xmlns: <solid android: <corners android: <stroke android: </shape> Feel free to modify the above snippets to style the user interface elements to your liking. It is important to see the resources of this tutorial as a guideline. Create one more drawable and name it letter_down.xml. We'll use this drawable for the letter buttons in their highlighted state, that is, when the player taps the button. <shape xmlns: <solid android: <corners android: </shape> The user can choose only one letter in each round of the game. This means that each letter or button is disabled from the moment the user has chosen the letter. This is reflected by updating the button's background. 3. Create the Main Layout Step 1 Let's create the main layout file for the intro screen. Open the main layout file of the project and update its contents to reflect the snippet below. <RelativeLayout xmlns: <ImageView android: <Button android: </RelativeLayout> As you can see, the code refers to a drawable resource to display in the background. You can omit the ImageView element if you like. If you are including the image, make sure the filename matches this code. The layout includes a single button to play the game, but you can add other buttons later if you like. For example, you could add levels or categories to the application rather than simply choosing a random word from a list as we will do in this tutorial. Step 2 Let's create a few more files that we'll use in the next tutorials. First, add a second activity class to the project for the game itself. Select the package in your project's src directory and choose New > Class from the File menu. Name the class GameActivity and set android.app.Activity as its superclass. We will complete the GameActivity class later in this series. Let's now create a layout file for the class. Add a new file to the project's layout folder and name it activity_game.xml. Replace its contents with the following snippet below. <LinearLayout xmlns: </LinearLayout> We will add items to the layout next time. Add the activity to your project manifest file, after the element for the main activity, inside the application element: <activity android: We set the screen's orientation to portrait. If you decide to also support a landscape orientation in your game, then you need to remove the orientation attribute. We also specify the main activity as parent, which means that the action bar can be used for navigating the game. We will talk more about this a bit later in this tutorial. 4. Start the Game Activity Step 1 Let's finish this tutorial by starting the gameplay activity when the user taps the play button. Open the file of the MainActivity class and begin by adding the following import statements. import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; Eclipse should have pre-populated the MainActivity class with an Activity class outline, including an onCreate method in which the content view is set. After the setContentView line, retrieve a reference to the play button you added to the main layout and set the class to listen for clicks. Button playBtn = (Button)findViewById(R.id.playBtn); playBtn.setOnClickListener(this); We can find the button by using the identifier we set in the layout XML. Extend the opening line of the class declaration to implement the click listening interface as follows. public class MainActivity extends Activity implements OnClickListener Step 2 Add the onClick method after the onCreate method as shown below. @Override public void onClick(View view) { //handle clicks } Inside this method, we check if the play button was clicked and, if it was, start the gameplay activity. if (view.getId() == R.id.playBtn) { Intent playIntent = new Intent(this, GameActivity.class); this.startActivity(playIntent); } This won't have much of an effect at the moment since we haven't implemented the gameplay activity yet. That is something we'll do in the next tutorial. Conclusion In this tutorial, we've created the foundation for the Hangman application. In the next tutorial, we will build the game's interface elements and, in the final part, we will focus on the interactive aspects of the application. Along the way, we will explore adapters and the action bar. We will also store the word answers in XML, retrieving them when the app launches, and choosing one at random every time the user plays a game.
http://code.tutsplus.com/tutorials/create-a-hangman-game-project-setup--mobile-21797
CC-MAIN-2015-06
en
refinedweb
A potentially significant amount of performance gain and code size reduction can be achieved by making use of internal fields rather than designing applications with a blanket use of public properties. Public properties are frequently blindly considered a “good programming practice” without giving thought to whether that practice is applicable. Optimization removes much, but not all, of the penalty of properties in the .NET environment. We present some of the philosophical arguments in the conclusion. When a value requires exposure to other developer’s assemblies, defining it as a property has merit. For example, in version 1 of our assembly we define the following property and field: public int MyProperty { get; set; } public int MyField; In time, others are now using our assembly and are dependent on it. Later we find an issue that we must address, such as the values must always be positive. We can change our property as below to be tolerant to consumers of our assembly passing negative values. public int MyProperty { get { return this.myProperty; } set { this.myProperty = value >= 0 ? value : 0; } } private int myProperty; Users of our assembly do not have to recompile to make use of our update. However, we cannot do the same to our field. To add the value checking code to our field, we must first turn it into a property, and if we do so, we break compatibility with previous versions. This would make public fields not a “good programming practice.” There is a cost to using a property rather than a field. A field is essentially a location in memory that we can get and set values with a single instruction to the CPU (“mov” in the case of the X86). However a property is a way of auto-generating code. The two methods below are the resulting code: public int get_MyProperty() { return this.myProperty; } public void set_MyProperty(int value) { this.myProperty = value >= 0 ? value : 0; } private int myProperty; We are no longer using a single CPU instruction to access our value, but are calling methods to get or set the value. The CPU must now execute a call instruction to the method and the method must do the “mov” instruction and then a return instruction. Adding to the additional instructions are the pushing and popping of the instruction pointer to the stack. The result is at least five times the amount of work for a property as compared to a field. There are many techniques used in CPU hardware to increase efficiency, such as doing the pushing and popping in parallel, but that is beyond our scope. We see that using properties for public values has merit and a cost that we must bear. However, this weight does not have to be applied to values that are used internally within our assembly. If a given value, at least for the current version, is used only within our assembly, we should not expose it publicly, but rather keep it internal as below. internal int MyValue; The overhead of properties is eliminated by using a field. If we are now coding version 2 of our assembly and find that we have to add our validation logic, we can simply change our field into a property and recompile. Typically, no other parts of our assembly are impacted, and no compatibility issues arise. internal int MyValue { get { return this. myValue; } set { this. myValue = value >= 0 ? value : 0; } } private int myValue; We can gain some internal efficiency with public properties by internally exposing the underlying values. This allows our assembly to make use of the value as a field while allowing for updates in future versions. public int MyProperty { get { return this.myProperty; } set { this.myProperty = value; } } internal int myProperty; If we find we have to add our validation logic, we can do a search on all internal references to our field and change them as appropriate to using the public property. Since the changes we are making impact only our assembly, there is no impact on other users. When multiple assemblies are used in our solution, but those assemblies are not shared outside of our solution, we can make use of public fields in the same way we have described for internal fields. Even when we have a large team working on a single solution, we can expose values as public fields, as the “MyValue” example above. Anyone can change a field into a property when necessary without disrupting the efforts of the other members of the team. By employing this policy, we can achieve a balance of efficiency and updatability. MyValue The compilers in the Microsoft .NET Framework offer significant optimization. The “debug” version performs as described above, but the “release” code removes the call to the getter and setter and accesses the backing field directly. This optimization performs remarkably, but is not complete. Incrementing a field is a single instruction, while incrementing a property remains three. This optimization may also be present in future versions of the compiler. libraryClass.MyField++; inc dword ptr [esi+8] libraryClass.MyProperty++; mov eax,dword ptr [esi+4] inc eax mov dword ptr [esi+4],eax Note: To view the disassembly of optimized code in Visual Studio 2008, you must change some of the default options. Click "Tools" then "Options". In the "Debugging General" uncheck "Enable Just My Code (Managed Only)" and "Suppress JIT optimization on module Load (Managed Only)". However, a property’s getter and setter definitions remain and the JIT compiler must perform the optimization each time the application loads. Fields are, in essence, optimized before the JIT compiler starts, and require one entry into the assembly’s manifest which results in a smaller file. Some will argue that it is simplest to use properties always and let the compiler make the decisions. We suggest that when you write code, you should write what you intend to have executed. Properties sometimes execute as fields, whereas fields always execute as fields. If you write for more than one environment, then you cannot assume the optimizations will carry forward. The concepts of properties and fields are essentially universal, even with 8-bit embedded processors, but optimization is not. In many cases, such as many data binding scenarios, properties are required and fields are not an option. Many times, especially in internal applications, the debug version is the version that goes into production use. When this is the case, the optimization advantage is gone. Compile time during application development, application start time, and file sizes are all impacted by the choice of properties versus fields. For one instance, the impact is insignificant. For complex applications, the impact is real. The great value of public properties comes into play when we are developing assemblies that are used by others outside of our solution. When we own the solution and make blind use of properties, we add significant, unnecessary overhead to our development effort and impair the application’s performance. For a solo programmer or a large team, a refined policy of using fields and properties wisely can result in a performance gain and code size reduction. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) namespace CodeProjectTest { class Program { static void Main(string[] args) { System.Diagnostics.Stopwatch sw1 = new System.Diagnostics.Stopwatch(); System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch(); ClassLibrary1.Test t = new ClassLibrary1.Test(); sw1.Start(); for (int i = 0; i < 100000000; i++) { t._myfield++; } sw1.Stop(); sw2.Start(); for (int i = 0; i < 100000000; i++) { t.Myfield2++; } sw2.Stop(); Console.WriteLine("Field access 100 million times=" + sw1.Elapsed.ToString()); Console.WriteLine("Property access 100 million times=" + sw2.Elapsed.ToString()); Console.ReadLine(); } } } namespace ClassLibrary1 { public class Test { public int _myfield = 0; private int _myfield2 = 0; public int Myfield2 { get { return _myfield2; } set { _myfield2 = value; } } } } .method public hidebysig specialname instance int32 get_Myfield2() cil managed { // Code size 12 (0xc) .maxstack 1 .locals init ([0] int32 CS$1$0000) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldfld int32 ClassLibrary1.Test::_myfield2 IL_0007: stloc.0 IL_0008: br.s IL_000a IL_000a: ldloc.0 IL_000b: ret } // end of method Test::get_Myfield2 .method public hidebysig specialname instance int32 get_Myfield2() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 ClassLibrary1.Test::_myfield2 IL_0006: ret } // end of method Test::get_Myfield2 00000058 xor eax,eax 0000005a inc dword ptr [esi+4] 0000005d inc eax 0000005e cmp eax,5F5E100h 00000063 jl 0000005A 00000073 xor edx,edx 00000075 mov eax,dword ptr [esi+8] 00000078 inc eax 00000079 mov dword ptr [esi+8],eax 0000007c inc edx 0000007d cmp edx,5F5E100h 00000083 jl 00000075 General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/38835/Boosting-Performance-with-Fields?msg=3152808
CC-MAIN-2015-06
en
refinedweb
I want to have an exception for my stack class that is thrown if new memory cannot be allocated for a push. From my book, I entered the following into my program: Implementation file:Implementation file:Code:#include <exception> #include <string> typedef int StackType; using namespace std; class StackException : public exception { public: StackException(const string & Message = "") : exception(Message.c_str()) {} }; class Stack { public: Stack(); ~Stack(); bool isEmpty(); void push(StackType[2]) throw(StackException); void pop(StackType[2]); private: struct StackNode { StackType info[2]; //data item on the stack StackNode *next; //a pointer to the next node }; StackNode *topOfStack; //a pointer to the first node in stack }; When I went to compile my app it ran out with over a hundred errors! What's the deal? I'm sure I'm missing something easy.When I went to compile my app it ran out with over a hundred errors! What's the deal? I'm sure I'm missing something easy.Code:void Stack::push(StackType newitem1[2]) { StackNode *newPointer = new StackNode; if (newPointer == NULL) NULL; throw StackException("StackException: stack push cannot allocate memory"); else { newPointer->info[0] = newitem1[0]; newPointer->info[1] = newitem1[1]; newPointer->next = topOfStack; topOfStack = newPointer; } }
http://cboard.cprogramming.com/cplusplus-programming/35457-exceptions-should-easy.html
CC-MAIN-2015-06
en
refinedweb
Keep Your Flash Project's Memory Usage Stable With Object Pooling Start a hosting plan from $3.92/mo and get a free year on Tuts+ (normally $180). private var _lifeTime); } } The code above is the code responsible for the particle's removal from the screen. We create a variable called _lifeTime to: private var _oldTime:uint; private var _elapsed:uint; private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); // entry point stage.addEventListener(MouseEvent.CLICK, createParticles); addEventListener(Event.ENTER_FRAME, updateParticles); _oldTime = getTimer(); } private function updateParticles(e:Event):void { _elapsed = getTimer() - _oldTime; _oldTime += _elapsed; for (var i:int = 0; i < numChildren; i++) { if (getChildAt(i) is Particle) { Particle(getChildAt(i)).update(_elapsed); } } } private function createParticles(e:MouseEvent):void { for (var i:int = 0; i < 10; i++) { addChild(new Particle(stage.mouseX, stage.mouseY)); } } The code for updating the particles should be familiar to you: it's the roots of a simple time-based loop, commonly used in games. Don't forget the import statements: import flash.events.Event; import flash.events.MouseEvent; import flash.utils.getTimer;: private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); // entry point stage.addEventListener(MouseEvent.CLICK, createParticles); addEventListener(Event.ENTER_FRAME, updateParticles); addChild(new Stats()); _oldTime = getTimer(); } Don't forget to import net.hires.debug.Stats: package { public interface IPoolable { function get destroyed():Boolean; function renew():void; function destroy():void; } } Since our particles will be poolable, we need to make them implement IPoolable. Basically we move all the code from their constructors to the renew() function, and eliminate any external references to the object in the destroy() function. Here's what it should look like: /* INTERFACE IPoolable */ public function get destroyed():Boolean { return _destroyed; } public function renew():void { if (!_destroyed) { return; } _destroyed = false; graphics.beginFill(uint(Math.random() * 0xFFFFFF), 0.5 + (Math.random() * 0.5)); graphics.drawRect( -1.5, -1.5, 3, 3); graphics.endFill(); _angle = Math.random() * Math.PI * 2; _speed = 150; // Pixels per second _lifeTime = 1000; // Miliseconds } public function destroy():void { if (_destroyed) { return; } _destroyed = true; graphics.clear(); } The constructor also shouldn't require any arguments any more. If you want to pass any information to the object, you'll have to do it through functions now. Due to the way that the renew() function works now, we also need to set _destroyed to true in the constructor so that the function can be run. With that, we have just adapted our Particle class keyword: package { public class ObjectPool { private static var _instance:ObjectPool; private static var _allowInstantiation:Boolean; public static function get instance():ObjectPool { if (!_instance) { _allowInstantiation = true; _instance = new ObjectPool(); _allowInstantiation = false; } return _instance; } public function ObjectPool() { if (!_allowInstantiation) { throw new Error("Trying to instantiate a Singleton!"); } } } } The variable _allowInstantiation: package { public class ObjectPool { private static var _instance:ObjectPool; private static var _allowInstantiation:Boolean; private var _pools:Object; public static function get instance():ObjectPool { if (!_instance) { _allowInstantiation = true; _instance = new ObjectPool(); _allowInstantiation = false; } return _instance; } public function ObjectPool() { if (!_allowInstantiation) { throw new Error("Trying to instantiate a Singleton!"); } _pools = {}; } } } class PoolInfo { public var items:Vector.<IPoolable>; public var itemClass:Class; public var size:uint; public var active:uint; public var isDynamic:Boolean; public function PoolInfo(itemClass:Class, size:uint, isDynamic:Boolean = true) { this.itemClass = itemClass; items = new Vector.<IPoolable>(size, !isDynamic); this.size = size; this.isDynamic = isDynamic; active = 0; initialize(); } private function initialize():void { for (var i:int = 0; i < size; i++) { items[i] = new itemClass(); } } } The code above creates the private class which will contain all the information about a pool. We also created the _pools object to hold all object pools. Below we will create the function that registers a pool in the class: public function registerPool(objectClass:Class, size:uint = 1, isDynamic:Boolean = true):void { if (!(describeType(objectClass).factory.implementsInterface.(@type == "IPoolable").length() > 0)) { throw new Error("Can't pool something that doesn't implement IPoolable!"); return; } var qualifiedName:String = getQualifiedClassName(objectClass); if (!_pools[qualifiedName]) { _pools[qualifiedName] = new PoolInfo(objectClass, size, isDynamic); } } This code looks a bit trickier, but don't panic. It's all explained here. The first if statement looks really weird. You may have never seen those functions before, so here's what it does: - The describeType() function creates a XML containing all the information about the object we passed it. - In the case of a class, everything about it is contained within the factorytag. - Inside that, the XML describes all the interfaces that the class implements with the implementsInterfacetag. - We do a quick search to see if the IPoolableinterface is among them. If so, then we know we can add that class to the pool, because we will be able to successfully cast it as an IObject. The code after this check just creates an entry within _pools if one didn't already exist. After that, the PoolInfo constructor: public function getObj(objectClass:Class):IPoolable { var qualifiedName:String = getQualifiedClassName(objectClass); if (!_pools[qualifiedName]) { throw new Error("Can't get an object from a pool that hasn't been registered!"); return; } var returnObj:IPoolable; if (PoolInfo(_pools[qualifiedName]).active == PoolInfo(_pools[qualifiedName]).size) { if (PoolInfo(_pools[qualifiedName]).isDynamic) { returnObj = new objectClass(); PoolInfo(_pools[qualifiedName]).size++; PoolInfo(_pools[qualifiedName]).items.push(returnObj); } else { return null; } } else { returnObj = PoolInfo(_pools[qualifiedName]).items[PoolInfo(_pools[qualifiedName]).active]; returnObj.renew(); } PoolInfo(_pools[qualifiedName]).active++; return returnObj; } statement at the beginning of the function. We can now modify our Main class and use the object pool! Check it out: private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); // entry point stage.addEventListener(MouseEvent.CLICK, createParticles); addEventListener(Event.ENTER_FRAME, updateParticles); _oldTime = getTimer(); ObjectPool.instance.registerPool(Particle, 200, true); } private function createParticles(e:MouseEvent):void { var tempParticle:Particle; for (var i:int = 0; i < 10; i++) { tempParticle = ObjectPool.instance.getObj(Particle) as Particle; tempParticle.x = e.stageX; tempParticle.y = e.stageY; addChild(tempParticle); } }: public function returnObj(obj:IPoolable):void { var qualifiedName:String = getQualifiedClassName(obj); if (!_pools[qualifiedName]) { throw new Error("Can't return an object from a pool that hasn't been registered!"); return; } var objIndex:int = PoolInfo(_pools[qualifiedName]).items.indexOf(obj); if (objIndex >= 0) { if (!PoolInfo(_pools[qualifiedName]).isDynamic) { PoolInfo(_pools[qualifiedName]).items.fixed = false; } PoolInfo(_pools[qualifiedName]).items.splice(objIndex, 1); obj.destroy(); PoolInfo(_pools[qualifiedName]).items.push(obj); if (!PoolInfo(_pools[qualifiedName]).isDynamic) { PoolInfo(_pools[qualifiedName]).items.fixed = true; } PoolInfo(_pools[qualifiedName]).active--; } } object that has fixed length. Due to that, we can't splice() it and push() objects back. The workaround to this is to change the fixed property); ObjectPool.instance.returnObj keyword (meaning the creation of an instance), replace it with a call to the function that gets an object for you. Don't forget to implement the methods that the interface IPoolable requires!!
http://code.tutsplus.com/tutorials/keep-your-flash-projects-memory-usage-stable-with-object-pooling--active-10909
CC-MAIN-2015-06
en
refinedweb
MVC stands for Model View and Controller. It basically defines how you structure your code, more precisely as you may know we structure any problem or bring an order to reduce its complexity and to control it. The need of following the pattern of MVC is pretty much the same. Suppose you are working on a projects in java, you have all the idea and amenities to complete the project but do not know how to start with or organize your code in java classes. In this scenario MVC pattern can pave the path. But how? Before answering this question lets demystify the notion of MVC. An Analogy The analogy is to get a picture of the scenario, however a one to one correspondence between them may not exists but nonetheless it will help you to get a first hand view of its working methodology. Thus the Java objects responsible for displaying the output or getting the input into the system are in general part of the View. Controller acts as a manager between model and view and decides what goes where, when and how based on some business rules in the system. Model is manipulated through a set of business rules on which the system is built upon, for example if your software uses database, the rules based upon which data are fetched are called business rules. Starting to code MVC Now lets take upon an example: login web application to start Java code based upon the MVC pattern. We shall have a login page to collect the user name and password. Once the user submits the user name and password, we shall validate the credentials and if the credentials are found OK then we show the login successful page with greetings and if the credentials are not valid, we redirect back to the login page. This simple example shall give you an overview of an MVC application design. The components according to MVC pattern will be as follows: - Controller (LoginServlet.java): In our case it will be a servlet. When the request for login is initiated, the user name and password is passed on to the controller who collects the data. The controller then passes the data on to the business service. - Business Service (LoginService.java): Our business service is a simple POJO (Plain Old Java Object) responsible for validating the user. In real world application the data model is fetched from a database. But in our case to reduce complexity and focus on the MVC pattern only, database part is omitted. Most of business critical code of an MVC application are in general are contained in business services. - Model (User.java): This is the data access object or the model class representing data on which the business rules apply and interact with. - View (login.jsp, login_success.jsp): This is basically a JSP/HTML files for streaming in/out request/response from the browser. Step 1: Start Netbean IDE and click on File, New Project. Select Java Web from categories list and Web Application from projects list. Click Next Step 2: Give the name of the project and leave the other options as it is, and then click Next. Step 3: Select Server Apache Tomcat and click Finish Step 4: Create the file structure as shown in the project explorer and write/copy paste the following code. Controller: LoginServlet.java package org.loginmvcapp.controller; import java.io.IOException;.loginmvcapp.model.User; import org.loginmvcapp.service.LoginService; @WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName=request.getParameter("userName"); String password=request.getParameter("password"); LoginService loginService=new LoginService(); if(loginService.isValidUser(userName, password)){ User user=loginService.getUser(); request.setAttribute("user", user); RequestDispatcher requestDispatcher = request.getRequestDispatcher("login_success.jsp"); requestDispatcher.forward(request, response); }else{ response.sendRedirect("index.jsp"); } } } Business Service: LoginService package org.loginmvcapp.service; import org.loginmvcapp.model.User; public class LoginService { private User user; public LoginService(){ user=new User(); user.setUserName("admin"); user.setPassword("admin"); } public boolean isValidUser(String userName, String password){ if(userName.equals(user.getUserName()) && password.equals(user.getPassword())){ return true; } return false; } public User getUser(){ return user; } } Model: User.java package org.loginmvcapp.model; public class User { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } View: index.jsp <%@page <title>Login Page</title> </head> <body> <h1>Login</h1> <form action="login" method="post"> <table> <tr><td>User Name</td><td><input type="text" name="userName"/></td></tr> <tr><td>Password</td><td><input type="password" name="password"/></td></tr> <tr><td></td><td><input type="submit" value="Login"/></td></tr> </table> </form> </body> </html> login_success.jsp <%@page <title>Login Success</title> </head> <body> <% User user=(User)request.getAttribute("user"); %> <h1>Hello <%=user.getUserName()%></h1> <h2>You have successfully logged in</h2> </body> </html> Step 5: To deploy the project press F6 or select Run Project from Run menu. The project shall run in a browser as shown below. Conclusion In a nutshell MVC is nothing but a blueprint of the code organization in a project to cope up with the complexity of large projects. This though is simplified rather oversimplified explanation but once you get your fist MVC application up and running you shall definitely get enthusiasm and confidence to delve deeper in to the realm of Java MVC.
http://forum.codecall.net/topic/72183-mvc-application-in-java/
CC-MAIN-2015-06
en
refinedweb
Main Page | Modules | Namespace List | Class Hierarchy | Class List | File List | Namespace Members | Class Members | File Members | Related Pages hugin1/PT/PanoToolsInterface.h File Reference #include <panotools/PanoToolsInterface.h> Include dependency graph for PanoToolsInterface.h: This graph shows which files directly or indirectly include this file: Go to the source code of this file.
http://hugin.sourceforge.net/docs/html/hugin1_2PT_2PanoToolsInterface_8h.shtml
CC-MAIN-2015-06
en
refinedweb
>Just 1%, gg? Damn... I guess it's time to bring out CheetOS XS (extra special). It'll primarily be for the Wombat gaming system that I spoke about in a much earlier thread, but its cross-platform compatibility spreads to refrigerators, freezers (we finally broke the ice-cube matrix!), and thumbtacks. < Oh yeah you get 2% take a persent from the fruitOS [commplety of topic] Since windows has x-box and cheezOS has Wombat Who do you think sony and nintendo would pair up with. My guess is sony would creat sony linux and Nintendo would team up with Mac. [/completly of topic] >Dos = Unix(actuallly dos was bought) Windows = MacOS WindowsNT = Unix Microsoft office = Corel Whatever it was... Windows XP = Linux + Unix + MacOS< It's time I release the SECRET MICROSOFT TEPLETE CODE. I only have the main funcion though Code: #include <otherprogram.h> #inclucde <modify.h> if def win9x void main() if def winnt int main () { convert (company, OriganalToMicrosoft); convert (productName, OriganalToOurs); if (win9X) { createbugs(Lots, restartneeded); } if (winnt) { return 0; } }
http://cboard.cprogramming.com/brief-history-cprogramming-com/843-you-ms-anti-ms-3-print.html
CC-MAIN-2015-06
en
refinedweb
25 September 2009 13:13 [Source: ICIS news] SINGAPORE (ICIS news)--China linear low density polyethylene (LLDPE) and polyvinyl chloride (PVC) futures traded as much as 1.5% lower on Friday as sharp falls in the physical markets dampened sentiment, industry sources said. The November LLDPE contact closed at CNY9,520/tonne on Friday, CNY145/tonne or about 1.5% lower from the previous day’s settlement price, according to data from the Dalian Commodity Exchange (DCE). Imported LLDPE was discussed below $1,200/tonne CFR (cost and freight) ?xml:namespace> November PVC futures meanwhile fell by 1.4% from Thursday’s settlement level to close at CNY6,440/tonne on the back of persistently poor demand in the physical market, a local PVC trader said. The number of open positions also fell to its lowest since late-July, reflecting the sluggish trading sentiment in the futures market, the trader added. ($1 = CNY6.83) Additional reporting by Ng Hun Wei For more on PE,
http://www.icis.com/Articles/2009/09/25/9250482/chinas-plastics-futures-fall-further-on-weak-physical-trade.html
CC-MAIN-2015-06
en
refinedweb
28 January 2009 05:31 [Source: ICIS news] By Ng Hun Wei SINGAPORE (ICIS news)--Polyvinyl chloride (PVC) imports into China in 2008 fell below 1m tonnes for the first time in 10 years, but there is cautious optimism that the decline could be arrested this year on the strength of domestic demand, traders and producers said on Wednesday. The country only imported around 860,200 tonnes of pure PVC (HS code: 39041010 and 39041090) in 2008, compared with 1.014m tonnes imported the previous year, statistics from China's customs agency showed. Import volumes were already lagging year on year by June but plunged further as the US financial crisis deepened in September last year, traders and producers said. “There are many reasons why Chinese PVC imports are down this year but the global economic crisis is surely the most important one,” a Chinese PVC trader said. “Without demand from the US and ?xml:namespace> Major economies, including China, looked set to suffer further because of depressed global demand, but some industry sources believed the country’s appetite for PVC imports was unlikely to diminish further. “In fact, we are already seeing signs of demand picking up in December and January. With crude prices at such low levels, PVC imports are actually quite attractive for Chinese domestic buyers price-wise,” said an Asian PVC producer. Growing demand from Chinese domestic buyers is expected to drive up demand for PVC imports into the country while its re-export market would remain in the doldrums amid the global economic slump, traders and producers said. China’s re-export market was previously the main destination of PVC imports into the country. But with the fall of crude prices from record highs, PVC imports have also found their way into the Chinese domestic market despite the imposition of anti-dumping duties, industry sources said. “I think the market dynamics are quite different from a year ago, or even six months ago. When crude and ethylene prices were at record highs, carbide-based PVC produced locally was often the cheaper option for Chinese domestic buyers. Not anymore,” said a southeast Asian PVC producer. China imports ethylene-based PVC while producing carbide-based PVC locally. The price of calcium carbide was last week heard at more than $500/tonne (CNY3,420/tonne) in China’s domestic market, similar to levels heard just six months ago. Crude prices have fallen by more than 70% to just over $40/bbl over the same period, while ethylene prices have fallen by a similar amount, creating a huge cost advantage for ethylene-based PVC producers. “Even with anti-dumping duties of 5-12%, it still makes sense for Chinese domestic buyers to import PVC because of the huge cost difference between ethylene and carbide-based PVC”, a trader said. Buying interest from the Chinese domestic market could potentially help make up for some of the demand destruction seen in the re-export market, traders and producers said. According to industry estimates, China’s total PVC demand was around 9m tonnes in 2008. At least 70% of this demand was fulfilled by carbide-based PVC producers. But as local carbide-based PVC plants shut down or slash their operating rates due to negative margins, Chinese buyers have little options but to turn to imported PVC. “Of course the situation can be easily reversed if crude prices start surging again. But given the current situation and growth projection, the Chinese domestic market will help support the PVC import market this year,” said a northeast Asian PVC producer, who expects Chinese PVC demand to remain at 9m tonnes in 2009.
http://www.icis.com/Articles/2009/01/28/9188149/china-2008-pvc-imports-fall-domestic-demand-to-halt-decline.html
CC-MAIN-2015-06
en
refinedweb
22 November 2011 04:59 [Source: ICIS news] By Monica Cai SINGAPORE (ICIS)--?xml:namespace> Prices in east In south MMA prices in “MMA imports are likely to be over 10,000 tonnes every month,’’ said a northeast Asian producer. Producers in these regions are holding high inventories because of low demand from their domestic markets and are keen to export their product to On a CFR China basis, discussions for import prices were heard at $1,900-2,000/tonne (€1,406-1,480/tonne) on 21 November. Another factor contributing to the decline in MMA prices is the softening of other related acrylate monomer prices. Butyl acrylate (butyl-A) prices fell by around CNY1,200/tonne last week, according to Chemease data. MMA and butyl-A are used to make emulsions for the construction and automotive industries. Emulsion demand has weakened because of slower growth in the construction sector and sluggish automotive sales, said industry players. “The imports of MMA to Hence, many buyers are adopting a cautious stance and buying on a need-to basis, traders said. ($1 = CNY6.37) ($1 = €0.74) Additional reporting by Junie Lin For more information on MMA, visit ICIS chemical intelligence
http://www.icis.com/Articles/2011/11/22/9510296/chinas-mma-prices-to-fall-further-on-weak-demand-oversupply.html
CC-MAIN-2015-06
en
refinedweb
21 March 2012 13:37 [Source: ICIS news] HOUSTON (ICIS)--Sherwin-Williams has won a multi-year supply deal with property management and apartment rental firm Riverstone Residential Group, the ?xml:namespace> Sherwin-Williams said that under the deal it would supply Riverstone with paint, coatings and flooring products, and it would be Riverstone’s exclusive marketing partner for paint between 2012 and 2014. Dallas, Texas-based Riverstone Residential is one of the largest US providers of rental apartments with more than 170,000 apartments under management. Financial or volume details were not disclosed. Sherwin-Williams added that such longer-term supply agreements can help standardise purchases and stabilise costs. At the same time, Sherwin-Williams can create product specifications, customise on-site training and provide other services to customers,
http://www.icis.com/Articles/2012/03/21/9543768/sherwin-williams-to-supply-us-property-management-firm-riverstone.html
CC-MAIN-2015-06
en
refinedweb
HOUSTON (ICIS) -- The US Army has flown a UH-60 Black Hawk helicopter on a 50/50 blend of ATJ-8 fuel from biomass-derived isobutanol producer Gevo and petroleum-based fuel, the company said on Monday. The helicopter is the first Army aircraft to fly using the isobutanol alcohol-to-jet (ATJ) fuel. ?xml:namespace> The Army is conducting flight tests with renewable fuels as part of a mandate that it certify 100% of its air plaforms on alternative or renewable fuels by 2016. Flight tests with the Gevo isobutanol blend took place over the week of 11 November. Gevo had previously signed a contract to supply over 16,0000 gallons of fuel to the US Army to be used in testing. Flight testing at the Aviation Flight Test Directorate in Alabama are expected to be completed by March 2014. The US Navy conducted tests with ATJ fuel from Gevo in 2012, completing a successful test flight with an A-10 Thunder Bolt jet aircraft in June 2012.
http://www.icis.com/resources/news/2013/12/23/9738386/us-army-tests-isobutanol-fuel-blend-in-helicopter/
CC-MAIN-2015-06
en
refinedweb
First Input Delay (FID) First Input Delay (FID) is an important, user-centric metric for measuring load responsiveness because it quantifies the experience users feel when trying to interact with unresponsive pages—a low FID helps ensure that the page is usable. We it is hard to measure how much users like a site's design with web APIs, measuring its speed and responsiveness is not!! The First Input Delay (FID) metric helps measure your user's first impression of your site's interactivity and responsiveness. What is. What is a good FID score? # To provide a good user experience, sites should strive to have a First Input Delay of 100 milliseconds or less. FID in detail # (a.k. FID only measures the "delay" in event processing. It does not measure the event processing time itself nor the time it takes the browser to update the UI after running event handlers. While this time does affect the user experience, including it as part of FID would incentivize developers to respond to events asynchronously—which would improve the metric but likely make the experience worse. See why only consider the input delay below for more details. Consider the following timeline of a typical web page load: The above visualization shows a page that's making a couple of network requests for resources (most likely CSS and JS files), and—after those resources are finished downloading—they're processed on the main thread. This results in periods where the main thread is momentarily busy, which is indicated by the beige-colored task blocks. Long first input delays typically occur between First Contentful Paint (FCP) and Time to Interactive (TTI) because the page has rendered some of its content but isn't yet reliably interactive. To illustrate how this can happen, FCP and TTI have been added to the timeline: You may have noticed that there's a fair amount of time (including three long tasks) between FCP and TTI, if a user tries to interact with the page during that time (e.g. click on a link), there will be a delay between when the click is received and when the main thread is able to respond. Consider what would happen if a user tried to interact with the page near the beginning of the longest task: Because the input occurs while the browser is in the middle of running a task, it has to wait until the task completes before it can respond to the input. The time it must wait is the FID value for this user on this page. In this example the user just happened to interact with the page at the beginning of the main thread's most busy period. If the user had interacted with the page just a moment earlier (during the idle period) the browser could have responded right away. This variance in input delay underscores the importance of looking at the distribution of FID values when reporting on the metric. You can read more about this in the section below on analyzing and reporting on FID data. What if an interaction doesn't have an event listener? # FID measures the delta between when an input event is received and when the main thread is next idle. This means FID is measured even in cases where an event listener has not been registered. The reason is because many user interactions do not require an event listener but do require the main thread to be idle in order to run. For example, all of the following HTML elements need to wait for in-progress tasks on the main thread to complete prior to responding to user interactions: - Text fields, checkboxes, and radio buttons ( <input>, <textarea>) - Select dropdowns ( - links ( <a>)? # FID. Why only consider the input delay? # As mentioned above, FID only measures the "delay" in event processing. It does not measure the event processing time itself nor the time it takes the browser to update the UI after running event handlers. Even though this time is important to the user and does affect the experience, it's not included in this metric because doing so could incentivize developers to add workarounds that actually make the experience worse—that is, they could wrap their event handler logic in an asynchronous callback (via setTimeout() or requestAnimationFrame()) in order to separate it from the task associated with the event. The result would be an improvement in the metric score but a slower response as perceived by the user. However, while FID only measure the "delay" portion of event latency, developers who want to track more of the event lifecycle can do so using the Event Timing API. See the guide on custom metrics for more details. How to measure FID # FID is a metric that can only be measured in the field, as it requires a real user to interact with your page. You can measure FID with the following tools. FID requires a real user and thus cannot be measured in the lab. However, the Total Blocking Time (TBT) metric is lab-measurable, correlates well with FID in the field, and also captures issues that affect interactivity. Optimizations that improve TBT in the lab should also improve FID for your users. Field tools # - Chrome User Experience Report - PageSpeed Insights - Search Console (Core Web Vitals report) web-vitalsJavaScript library Measure FID in JavaScript # To measure FID in JavaScript, you can use the Event Timing API. The following example shows how to create a PerformanceObserver that listens for first-input entries and logs them to the console: new PerformanceObserver((entryList) => { for (const entry of entryList.getEntries()) { const delay = entry.processingStart - entry.startTime; console.log('FID candidate:', delay, entry); } }).observe({type: 'first-input', buffered: true}); Warning: This code shows how to log first-input entries to the console and calculate their delay. However, measuring FID in JavaScript is more complicated. See below for details: In the above example, the first-input entry's delay value is measured by taking the delta between the entry's startTime and processingStart timestamps. In most cases this will be the FID value; however, not all first-input entries are valid for measuring FID. The following section lists the differences between what the API reports and how the metric is calculated. Differences between the metric and the API # - The API will dispatch first-inputentries for pages loaded in a background tab but those pages should be ignored when calculating FID. - The API will also dispatch first-inputentries if the page was backgrounded prior to the first input occurring, but those pages should also be ignored when calculating FID (inputs are only considered if the page was in the foreground the entire time). - The API does not report first-inputentries when the page is restored from the back/forward cache, but FID should be measured in these cases since users experience them as distinct page visits. - The API does not report inputs that occur within iframes, but to properly measure FID you should consider them. Sub-frames can use the API to report their first-inputentries to the parent frame for aggregation. Rather than memorizing all these subtle differences, developers can use the web-vitals JavaScript library to measure FID, which handles these differences for you (where possible): import {getFID} from 'web-vitals'; // Measure and log FID as soon as it's available. getFID(console.log); You can refer to the source code for getFID) for a complete example of how to measure FID in JavaScript. In some cases (such as cross-origin iframes) it's not possible to measure FID in JavaScript. See the limitations section of the web-vitals library for details. Analyzing and reporting on FID data # Due to the expected variance in FID values, it's critical that when reporting on FID you look at the distribution of values and focus on the higher percentiles. While choice of percentile for all Core Web Vitals thresholds is the 75th, for FID in particular we still strongly recommend looking at the 95th–99th percentiles, as those 95th–99th percentile of desktop users, and the FID value you care about most on mobile should be the 95th–99th percentile of mobile users. How to improve FID # To learn how to improve FID for a specific site, you can run a Lighthouse performance audit and pay attention to any specific opportunities the audit suggests. While FID is a field metric (and Lighthouse is a lab metric tool), the guidance for improving FID is the same as that for improving the lab metric Total Blocking Time (TBT). For a deep dive on how to improve FID, see Optimize FID. For additional guidance on individual performance techniques that can also improve FID, see: - Reduce the impact of third-party code - Reduce JavaScript execution time - Minimize main thread work - Keep request counts low and transfer sizes small.
https://web.dev/fid/
CC-MAIN-2022-05
en
refinedweb
12. Preprocessing Directives The following come from section 6.10 of specification. It will terminate when you see code starting. :-). 1 A new-line character ends the preprocessing directive even if it occurs within what would otherwise be an invocation of a function-like macro. A text line shall not begin with a # preprocessing token. A non-directive shall not begin with any of the directive names appearing in the syntax. When in a group that is skipped (12.1), the directive syntax is relaxed to allow any sequence of preprocessing tokens to occur between the directive name and the following new-line character. - 1 Thus, preprocessing directives are commonly called “lines”. These “lines” have no other syntactic significance, as all white space is equivalent except in certain situations during preprocessing (see the # character string literal creation operator in 12.3.2, for example). Constraints). Semantics The implementation can process and skip sections of source files conditionally, include other source files, and replace macros. These capabilities are called preprocessing, because conceptually they occur before translation of the resulting translation unit. The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.. 12.1. Conditional Inclusion Contraints The expression that controls conditional inclusion shall be an integer constant expression except that: it shall not contain a cast; identifiers (including those lexically identical to keywords) are interpreted as described below; 2 and it may contain unary operator expressions of the form: defined identifier or: defined (identifier) which evaluate to 1 if the identifier is currently defined as a macro name (that is, if it is predefined or if it has been the subject of a #define preprocessing directive without an intervening #undef directive with the same subject identifier), 0 if it is not. - 2 Because the controlling constant expression is evaluated during translation phase 4, all identifiers either are or are not macro names - there simply are no keywords, enumeration constants, etc. Semantics Preprocessing directives of the forms: # if constant-expression new-line group_opt # elif constant-expression new-line group_opt check whether the controlling constant expression evaluates to nonzero. Prior. After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers are replaced with the pp-number 0, and then each preprocessing token is converted into a token. The resulting tokens compose the controlling constant expression which is evaluated according to the rules of constant expressions. For the purposes of this token conversion and evaluation, all signed integer types and all unsigned integer types act as if they hav e the same representation as, respectively, the types intmax_t and uintmax_t defined in the header <stdint.h>. 3 This includes interpreting character constants, which may involve converting escape sequences into execution character set members. Whether the numeric value for these character constants matches the value obtained when an identical character constant occurs in an expression (other than within a #if or #elif directive) is implementation-defined. 4 Also, whether a single-character character constant may have a neg ative value is implementation-defined. Preprocessing directives of the forms: # ifdef identifier new-line group_opt # ifndef identifier new-line group_opt check whether the identifier is or is not currently defined as a macro name. Their conditions are equivalent to #if defined identifier and #if !defined identifier respectively.. If none of the conditions evaluates to true, and there is a #else directive, the group controlled by the #else is processed; lacking a #else directive, all the groups until the #endif are skipped. 5 Forward references: macro replacement (12.3), source file inclusion (12.2), largest integer types (13.18.1.5). - 3 Thus, on an implementation where INT_MAXis 0x7FFFand UINT_MAXis 0xFFFF, the constant 0x8000is signed and positive within a #ifexpression even though it would be unsigned in translation phase 7. - 4 Thus, the constant expression in the following #ifdirective and ifstatement is not guaranteed to evaluate to the same value in these two contexts. #if 'z' - 'a' == 25 if ('z' - 'a' == 25) - 5 As indicated by the syntax, a preprocessing token shall not follow a #elseor #endifdirective before the terminating new-line character. However, comments may appear anywhere in a source file, including within a preprocessing directive. 12.2. Source File Inclusion Constraints A #include directive shall identify a header or source file that can be processed by the implementation. Semantics A preprocessing directive of the form: # include <h-char-sequence> new-line searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. A preprocessing directive of the form: # include "q-char-sequence" new-line causes-char-sequence> new-line with the identical contained sequence (including > characters, if any) from the original directive..) The directive resulting after all replacements shall match one of the two previous forms. 6 The method by which a sequence of preprocessing tokens between a < and a > preprocessing token pair or a pair of ” characters is combined into a single header name preprocessing token is implementation-defined. The implementation shall provide unique mappings for sequences consisting of one or more letters or digits followed by a period (.) and a single letter. The first character shall be a letter. The implementation may ignore the distinctions of alphabetical case and restrict the mapping to eight significant characters before the period. A #include preprocessing directive may appear in a source file that has been read because of a #include directive in another file, up to an implementation-defined nesting limit. Forward references: macro replacement (12.3). 12.3. Macro Replacement Constraints Two replacement lists are identical if and only if the preprocessing tokens in both have the same number, ordering, spelling, and white-space separation, where all white-space separations are considered identical.. There shall be white-space between the identifier and the replacement list in the definition of an object-like macro.. The identifier __VA_ARGS__ shall occur only in the replacement-list of a function-like macro that uses the ellipsis notation in the parameters. A parameter identifier in a function-like macro shall be uniquely declared within its scope. Semantics 7 to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive. A preprocessing directive of the form: # define identifier lparen identifier-listopt ) replacement-list new-line # define identifier lparen ... ) replacement-list new-line # define identifier lparen identifier-list , ... ) replacement-list new-line defines a function-like macro with arguments,. The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments. If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives, 8 the behavior is undefined. If there is a … in the identifier-list in the macro definition, then the trailing arguments, including any separating comma preprocessing tokens, are merged to form a single item: the variable arguments. The number of arguments combined is such that, following merger, the number of arguments is one more than the number of parameters in the macro definition (excluding the …). - 7 Since, by macro-replacement time, all character constants and string literals are preprocessing tokens, not sequences possibly containing identifier-like subsequences, they are never scanned for macro names or parameters. - 8 Despite the name, a non-directive is a preprocessing directive. 12.3.1. Argument Substitution. An identifier __VA_ARGS__ that occurs in the replacement list shall be treated as if it were a parameter, and the variable arguments shall form the preprocessing tokens used to replace it. 12.3.2. The # Operator Constraints Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list. Semantics. Otherwise, the original spelling of each preprocessing token in the argument is retained in the character string literal, except for special handling for producing the spelling of string literals and character constants: a \ character is inserted before each ” and \ character of a character constant or string literal (including the delimiting ” characters), except that it is implementation-defined whether a \ character is inserted before the \ character beginning a universal character name. If the replacement that results is not a valid character string literal, the behavior is undefined. The character string literal corresponding to an empty argument is “”. The order of evaluation of # and ## operators is unspecified. 12.3.3. The ## Operator Constraints A ## preprocessing token shall not occur at the beginning or at the end of a replacement list for either form of macro definition. Semantics. 9 For both object-like and function-like macro invocations, before the replacement list is reexamined for more macro names to replace, each instance of a ## preprocessing token in the replacement list (not from an argument) is deleted and the preceding preprocessing token is concatenated with the following preprocessing token.. The order of evaluation of ## operators is unspecified. 12.3.4. Rescanning and Further Replacement. If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, but all pragma unary operator expressions within it are then processed as specified in 12.9 below. 12.3.5. Scope of Macro Definitions A macro definition lasts (independent of block structure) until a corresponding #undef directive is encountered or (if none is encountered) until the end of the preprocessing. 12.4. Line Control Constraints The string literal of a #line directive, if present, shall be a character string literal. Semantics The line number of the current source line is one greater than the number of new-line characters read or introduced in translation phase 1 while processing the source file to the current token.. A preprocessing directive of the form: # line digit-sequence "s-char-sequenceopt" new-line sets the presumed line number similarly and changes the presumed name of the source file to be the contents of the character string literal. A preprocessing directive of the form: # line pp-tokens new-line (that does not match one of the two previous forms) is permitted. The preprocessing tokens after line on the directive are processed just as in normal text (each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens). The directive resulting after all replacements shall match one of the two previous forms and is then processed as appropriate. 12.5. Error directive Semantics 1 A preprocessing directive of the form # error pp-tokensopt new-line causes the implementation to produce a diagnostic message that includes the specified sequence of preprocessing tokens. 12.6. Pragma Directive Semantics A preprocessing directive of the form: # pragma pp-tokensopt new-line where the preprocessing token STDC does not immediately follow pragma in the directive (prior to any macro replacement) 10 STDC does immediately follow pragma in the directive (prior to any macro replacement), then no macro replacement is performed on the directive, and the directive shall have one of the following forms whose meanings are described elsewhere: #pragma STDC FP_CONTRACT on-off-switch #pragma STDC FENV_ACCESS on-off-switch #pragma STDC CX_LIMITED_RANGE on-off-switch - on-off-switch: one of ON OFF DEFAULT Forward references: the FP_CONTRACT pragma (13.12.2), the FENV_ACCESS pragma (13.6.1), the CX_LIMITED_RANGE pragma (13.3.4). 149). - 10 An implementation is not required to perform macro replacement in pragmas, but it is permitted except for in standard pragmas (where STDCimmediately follows pragma). If the result of macro replacement in a non-standard pragma has the same form as a standard pragma, the behavior is still implementation-defined; an implementation is permitted to behave as if it were the standard pragma, but is not required to. 12.7. Null Directive Semantics A preprocessing directive of the form: # new-line has no effect. 12.8. Predefined Macro Names The following macro names shall be defined by the implementation: __DATE__ The date of translation of the preprocessing translation unit: a character string literal of the form “Mmm dd yyyy”, where the names of the months are the same as those generated by the asctime function, and the first character of dd is a space character if the value is less than 10. If the date of translation is not available, an implementation-defined valid date shall be supplied. __FILE__ The presumed name of the current source file (a character string literal) 11 __LINE__ The presumed line number (within the current source file) of the current source line (an integer constant). 12 __STDC__ The integer constant 1, intended to indicate a conforming implementation. __STDC_HOSTED__ The integer constant 1 if the implementation is a hosted implementation or the integer constant 0 if it is not. __STDC_VERSION__ The integer constant 199901L. 12 __TIME__ The time of translation of the preprocessing translation unit:_IEC_559__ The integer constant 1, intended to indicate conformance to the specifications in annex F (IEC 60559 floating-point arithmetic). __STDC_IEC_559_COMPLEX__ The integer constant 1, intended to indicate adherence to the specifications in informative annex G (IEC 60559 compatible complex arithmetic). _. The values of the predefined macros (except for __FILE__ and __LINE__) remain constant throughout the translation unit. None of these macro names, nor the identifier defined, shall be the subject of a #define or a #undef preprocessing directive. Any other predefined macro names shall begin with a leading underscore followed by an uppercase letter or a second underscore. The implementation shall not predefine the macro _ _cplusplus, nor shall it define it in any standard header. Forward references: the asctime function (13.23.3.1), standard headers (13.1.2). - 11 The presumed source file name and line number can be changed by the #linedirective. - 12 This macro was not specified in ISO/IEC 9899:1990 and was specified as 199409L in ISO/IEC 9899/AMD1:1995. The intention is that this will remain an integer constant of type long int that is increased with each revision of International Standard. 12.9. Pragma Operator Semantics A unary operator expression of the form: _Pragma ( string-literal ). At this point specification material ends here and now we will see usage of above discussed macros. 12.10. Usage Note that for this part the compilation command should be gcc -E filename.c. Let us create two files test.c and test1.c and their contents are given below respectively. 12.10.1. #include #include "test1.c" I am test. #include "test.c" I am test1. Keep both the files in same directory and execute gcc -E test.c you will see following: # 1 "test.c" # 1 "test.c" 1 # 1 "<built-in>" 1 # 1 "<built-in>" 3 # 143 "<built-in>" 3 # 1 "<command line>" 1 # 1 "<built-in>" 2 # 1 "test.c" 2 # 1 "./test1.c" 1 ... In file included from test.c:1: In file included from ./test1.c:1: In file included from test.c:1: In file included from ./test1.c:1: In file included from test.c:1: In file included from ./test1.c:1: ... In file included from test.c:1: ./test1.c:1:10: error: #include nested too deeply #include "test.c" I am test1. # 2 "test.c" 2 I am test # 2 "./test1.c" 2 I am test1. # 2 "test.c" 2 I am test # 2 "./test1.c" 2 I am test1. # 2 "test.c" 2 As you can see test.c includes test1.c and test1.c includes test.c. So they are including each other which is causing nested includes. After processesing for some time preprocessor’s head starts spinning as if it has drunk a full bottle of rum and it bails out. As you know headers are included in all meaningful C programs and headers include each other as well. This inclusion of each other can easily lead to nested inclusion so how do header authors circumvent this problem. Well, a technique has been devised known popularly as header guard. The lines which have the form # number text is actually # line direective. Consider following code: #ifndef ANYTHING #define ANYTHING #include "test1.c" I am test. #endif #ifndef ANYTHING_ELSE #define ANYTHING_ELSE #include "test.c" I am test1. #endif Now what will happen that when test.c is included ANYTHING is defined and when test1.c is included via it ANYTHING_ELSE will be defined. After first round of inclusion no more inclusion can happen as governed by the directives. Please see headers of standard library to see the conventions for ANYTHING. 12.10.2. Why We Need Headers Now that we have seen the #include directive I would like to tell that why we even need header files. Header files contain several elements of libraries which come with C. For example, function prototypes, structure/type, declarations, macros, global variable declaration etc. Actual code resides inside *.a or *.so library files on GNU/Linux os. Now let us consider a case that we want to access a C function of standard library. The compilation phase requires that prototype of function should be known at compilation time. If we do not have headers we have no way to provide this function prototype at compile time. Same stands true for global variables. The declaration of these must be known at compilation time. You take any language there has to be a mechanism to include code from other files. Be it use directive of Perl or import of Python or any other mechanism of any other language. 12.10.3. #define #define and #include are probably the most encountered macro in all C files. There are many usage of it. We will first see the text replacement and function like usage which can be avoided and should be replaced by global constants and inline functions. First let us see what text replacement functionality we get using #define. Consider the following code fragment: #define MAX 5 MAX I am MAX Now run it though gcc -E filename.c and you will get following output: # 1 "test.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "test.c" 5 I am 5 So as you see both the occurrences are replaced by the text 5. This is the simplest form of text replacement which people use to handle many things. Most common are array sizes and symbolic constants. Another form is the form like functions which has been shown in 10.4. The bad part of these two is that both do not enter symbol table and make code hard to debug. The former can be replaced by const variables and latter by inline functions. The other usage of it is to define names. For example, we revisit our old example headers. Header guards usually declare something like this: #ifndef SOMETHING #define SOMETHING /* header code */ #endif As you can see #define is used to define SOEMTHING so second time the conditional inclusion #ifndef will fail. It can also be tested by defiend like if(defined(SOMETHING). Now if SOMETHING has been defined if test will pass successfully. Similarly #ifdef can be used to test it as a shortcut i.e. #ifdef SOMETHING. The normal if-else statements are replaced in preprocessing directives using #if, #elif and #endif. 12.10.4. #undef Anything defined by #define can be undefined by #undef. For example consider the following code: #define test #ifdef test //do something #undef test #ifdef test //do something else #endif If you do this then first something else will be executed while the second will not be. 12.10.5. # and ## You can use following two examples and description given above to understand both of these: #define hash_hash # ## # #define mkstr(a) # a #define in_between(a) mkstr(a) #define join(c, d) in_between(c hash_hash d) char p[] = join(x, y); //char p[]="x ## y" #define FIRST a # b #define SECOND a ## b char first[] = FIRST; char second[] = SECOND; 12.10.6. #error This one is simple. Consider the following: #include <stdio.h> int main() { # error MAX return 0; } If you try to compile this like gcc filename.c then you will get following: gcc test.c test.c:5:5: error: #error MAX # error MAX ^ 1 error generated. You can combine # error with #if but I have yet to see purposeful code written that way. Non-preprocessing constructs are better for handling such situations. Only if you want to test a preprocessing token then it should be used. 12.10.7. #pragma #pragma is dependent on what follows it. You should consult compiler documentation as it is mostly implementation-defined. 12.10.8. Miscellaneous Usage of __LINE__, __FILE__, __DATE__ and __TIME__ is simple and shown in following example: #include <stdio.h> int main() { printf("%s:%d:%s:%s", __FILE__, __LINE__, __DATE__, __TIME__); return 0; } and the output is: test.c:5:Jun 24 2012:11:24:57 This concluded our discussion on macros. Rest of the book will describe the standard library.
https://www.ashtavakra.org/c-programming/macros/
CC-MAIN-2022-05
en
refinedweb
Course Highlights and Why VMware Course in Chennai at FITA Academy? Upcoming Batches Classroom Training - Get trained by Industry Experts via Classroom Training at any of the FITA Academy branches near you - Why Wait? Jump Start your Career by taking the VMware Training in Chennai! Instructor-Led Live Online Training - Take-up Instructor-led Live Online Training. Get the Recorded Videos of each session. - Travelling is a Constraint? Jump Start your Career by taking the VMware Online Course! Syllabus - Introduction to Virtualization - Understanding Data Center Infrastructure - Installation of ESXi Server - Virtual Machine Concepts - Virtual Machine Creation & Management - Configuring and Managing Storage - Configuring Storage - VMFS Datastores - VSAN - Configuring and Managing Virtual Networks - Configuring Standard Virtual Switch Policies - Install & configure vCenter Server - VM Migration - VMware Clusters High Availability - Fault Tolerance - Host Scalability (DRS Cluster) - Patch Management - Data Protection - Veeam Backup - Access and Authentication Control - Resource Management and Monitoring - Scheduled Tasks, Events & Alarms - vSphere Web Client - VMware vShield Endpoint - Advanced Topics:Distributed Switch - VMware vCenter Standalone Converter - Up-gradation of Server - Managing vSphere Using command line interface - Understanding ESXi Server Architecture - Troubleshooting Virtual Interface Have Queries? Talk to our Career Counselor for more Guidance on picking the right Career for you! . Trainer Profile - At FITA, we zealously practice and implement the Experiential method of learning. VMware Mentors at FITA trains the students with the right blend of practical and theoretical knowledge of the Vmware concepts and techniques. - VMware Tutors at FITA trains the students with Industry-specific skill sets. - VMware Instructors at FITA Academy are Expertise and Certified professionals from the Cloud platform. - VMware Mentors at FITA Academy Institute are Real-time professionals from the Cloud domain and they provide hands-on training managing and deploying virtual machines and advanced techniques related to virtualization. - VMware Trainers at FITA Academy broadens the knowledge of the students on the virtualization concepts by training them extensively on the latest practices that are used in the VMware platform. - VMware Mentors at FITA Academy provide equal individual attention to all the students and they provide in-depth training of VMware concepts with complete hands-on training and practice. - VMware Instructors at FITA Academy supports and aids the students in building their resume professionally and enhances their confidence level by conducting numerous mock interview sessions and giving them a mammoth of insights on the handling of the interviews. Training in Chennai About VMware Certification Training in Chennai at FITA Academy VMware Certification Training in Chennai VMware Course Certification is one of the professional accomplishments which demonstrate that the candidate has acquired extensive knowledge of the significance of the virtualization concepts and its techniques. With a real-time project experience provided at the end of the VMWare course, this certification states that the candidate has obtained the necessary in-demand skills to work as a VMware professional. Having this VMware certificate along with your CV aids in boosting your profile at the time of the interview, and also it opens the gate for a wider range of career opportunities. VMware Certification Course in Chennai at FITA Academy imbibe the necessary technical skill sets that are required for professional Developers or Administrators under the guidance of our Real-time professionals.VMware training in Chennai at FITA Academy is provided by professionals who have 8+ years of experience in the VMware Cloud platform. Besides, earning the certificate of the FITA Academy’s VMware Training Course certification, earning a global credential also upsurges the possibilities of accessing lucrative careers. Our VMware Trainers at FITA Academy provides continued guidance and support to clear the global certification exam such as (VCA) – VMware Certified Associate, (VCP)VMware Certified Professional, (VACP) VMware Certified Advanced Professional, and (VCDX) VMware Certified Design Expert and helps you in uplifting your career opportunities. Have Queries? Talk to our Career Counselor for more Guidance on picking the right Career for you! . Job Opportunities After Completing VMware Training in Chennai The demand for IT professionals with Virtualization skills is currently sky-rocketing in the IT domain and it is predicted to have voluminous growth in the upcoming days as well. The prime reason for the increased growth is because of the number of organizations that are rapidly shifting their focus towards cloud and virtualization for cost-cutting, increased efficiency, and scalability of resources. When it comes to virtualization, VMware is the pioneer virtual cloud solution provider for enumerable businesses across the globe. VMware has occupied a prominent position in the marketplace of cloud computing and virtualization owing to its robust features. It can control various types of OS on a single server or computer laterally and therefore it resulted in the whittle down of the expenditure of the IT infrastructure drastically. Also, in the meanwhile ensuring the scalability, flexibility, and agility stupendously. This aided the businesses to be more profitable and agile along with the best security features for its customers. From the above-mentioned points, we can almost say that VMware has created a striking revolution in the IT industry. These are the major reasons on how VMware has managed to survive the competitive edge in the Cloud and virtualization platform. Furthermore, gaining a VMware certification helps you to access a myriad of career opportunities. The common job profiles that are offered upon the completion of the VMware certification exams are – System Engineers, Testers, System Administrators, Developers, Service Providers, and Network Operators. The notable recruiters of the VMware professionals are Cisco, IBM, HCl, TCS, and much more. The average salary offered for an entrant VMware System Administrator is Rs. 7,50,000 to Rs. 10,00,000 per annum. Globally, a VMware System Administrator earns around $ 98,945 yearly. VMware Training in Chennai at FITA Academy imbibes the in-demand professional and technical skills that are needed for a VMware professional under the mentorship of industry experts with certification. Student Testimonials VMware Training in Chennai at FITA Academy was conducted well. I liked their training methodologies. Well-structured VMware Course modules with hands-on training were provided at FITA Academy. Special mention about my VMware Mentor who thought all the concepts of the VMware in-depth. I will suggest the FITA Academy Training Institute for my friends. I am System Administrator by profession. I wanted to learn the VMware course to uplift my career opportunities at my office. I came to know about FITA Academy Training Institute upon the suggestion given by my friend and so I enrolled for the VMWare Course. I should tell you that everything was so very nice here. Best Training Faculty, Updated courseware most of all flexible timings. The Support Team was really so understanding that they ensured that I don't miss even a single session because of my work. If you are a working professional then you can really opt FITA Academy for any Training. Great Work FITA Academy. Keep it up. I am truly happy. My overall experience at FITA Academy's VMware Course in Chennai at FITA Academy was too good. My Trainers extensively thought about the concepts of vSphere, Virtual Machines, vSphere Storage, VMWare Cluster, and other important topics with live-time examples. Also, he was so patient enough to clarify all our doubts. My sincere thanks to him. Good work FITA Academy! I have completed my VMware Training at FITA Academy. Great place to learn about the VMware platform. Comprehensive training on how to configure and handle the vSphere 6.5 was provided. Learned a lot of new things regarding the virtualization concepts as well which I was not familiar with. Thanks to my VMware Trainer who helped me in building my resumes and also widened my knowledge with numerous mock interview practices. Any fresher with no doubts can choose this platform to learn VMware Course. Have Queries? Talk to our Career Counselor for more Guidance on picking the right Career for you! . VMware Training in Chennai Frequently Asked Question (FAQ) - VMware Course at FITA Academy is conducted and curated by Cloud Experts with more than 10+ years in VMware Course in Chennai at FITA Academy. - The Only Training Academy in Chennai that widens the knowledge of the students with the right proportion of theoretical and practical knowledge of the VMware concepts. - Above 30,000+ students trust FITA. - Comprehensive Coverage with 60+ hours of VMware Training in Chennai at FITA Academy. - Nominal Cost of IT working professionals and students in the mind. - Corporate Training in Chennai. - VMware Course timings are scheduled in the manner to suit the timing of the students and working professionals. - Resume Building Support and Interview Tips. - Real-time Virtualization projects and case studies. - FITA Academy has placements tie-ups with more than 1200+ small, medium, and large scale enterprises, and these companies have job openings for VMWare Developer, Administrator, and other professional roles that are related to the Cloud platform. - FITA Academy training institute has a Dedicated Placement Officer to support the students with Placement assistance. - The Placement cell helps the students with various mock interviews and group discussions training sessions for them to face the interview with confidence. You can enroll for the VMware Course in Chennai at FITA Academy VMware Course in Chennai at FITA Academy and will I be given enough practical Training for the VMware Certification Course? - We provide maximum individual attention to the students. The Training batch size is limited for 5 - 6 members per batch. The batch size has been optimized for equal individual attention to all the students and to clear the doubts of the students in complex topics clearly with tutors. - FITA Academy provides the necessary hands-on practical training to students with many Industry case studies and real-time projects. VMware Mentors at FITA Academy are Certified Cloud Experts from the Cloud Computing field. The VMware Trainers at FITA Academy are real-time professionals from the Cloud platform and they provide a holistic training of the virtualization concepts to the students. We accept Cash, Bank Transfer, G Pay, and Card Transactions. FITA Academy provides the best VMware Training in Chennai with wonderful guidance from expertise. Visit FITA Academy and enhance your career knowledge with best guidance. We have various branches in Chennai near by you Additional Information Looking for the best VMware Training Institute in Chennai? Then FITA Academy is the ideal choice for VMware Training in Chennai. Call +91 93450 45466 for VMware Course details. VMware Incorporation is an American based company that offers virtualization and cloud software and services. They offer compatible software products for x86 computers. VMware is a part of EMC Corporation and it’s located in Palo Alto, California. The VMware desktop version is compatible with. VM stands for virtual machines, it is widely installed on operating systems compatible with computers and servers that can host other operating systems, each operating system behaves smoothly as it was installed on an individual machine with its hardware configuration and software. FITA Academy offers the best VMware Training in Chennai by certified professionals as per industry standards. Benefits Of Taking VMware Training Chennai Virtualization is the most advanced technology that powers multiple operating systems in a single computer or server at the same time. It has revolutionized the IT industry and minimizes expenditure invested in IT infrastructure. Virtualization technology will increase flexibility, agility, and scalability while reducing expenditure. Workloads can be deployed quickly, the process becomes automated, and managing IT becomes simpler. As industries continue to use VMware technology, there is a massive demand for skilled and VMware certified professionals. Get trained in VMware Course in Chennai at FITA Academy to broaden your career horizon. Rated As Best VMware Training Institute In Chennai FITA Academy Chennai is a leading VMware Training Institute in Chennai with branches in Tambaram, OMR, Anna Nagar, Velachery, and T Nagar. Our experienced trainers will assist students to gain industry exposure with practical oriented training as per industry standards. Our VMware course syllabus is designed by certified professionals that cover beginner to advanced concepts. With our VMware course in Chennai, you can practically learn advanced concepts. Interested in our VMware Training in Chennai? Call 93450 45466 to have a chat with our experienced career counselor to know about VMware course duration, fee structure, and time. Join us for VMware Course in Chennai to start your dream career in IT. VMware Industry Updates VMware solutions run on the desktop software and the servers.VMware workstation pro is for the operating system or the demo session with the business. Virtualization is the base for cloud computing and the concept of virtualization is a part of cloud computing. The deliverables and networking are handled with a one-stop solution using the VMware solutions. Virtualization is about virtualizing the hardware of the company whereas cloud computing is about the serverless computing for maintaining the infrastructure of the business. VMware vCenter new server od, oc, ob, oa are the previous releases of the VMware. Join the VMware Training in Chennai to gain in-depth knowledge of this technology. The evolution of VMware brings in the different versions and it is essential to use the latest version of the VMware. If you desire to virtualize your computer then the virtual machine’s configurations are important to check. If your version is old and you are installing the latest version of VMware then the new features with the virtualization are not used to the fullest. The hardware versions are essential to be updated as this creates the connectivity between the virtual machine and the host server. VMware vCenter new server update The new options in the new version include the screening for the issues in the VMware, adds the models in the library service for the content, CLI tool, burst filter, HCI cluster feature, App defense V server plugin, compliance check, copy settings, and attach or detach of the files are some of the attributes to the latest version. The screening for the issues deals with the appropriate VMware articles for the knowledge which is easy to solve the issues when handling the new version. The embedded link mode in the vCenter controls the vCenter server appliances. CLI python tool The conversion of the server application to the platform services at an external location is taken care of by the CLI tool. The burst filter in the server prevents the flooding problem due to the identical events in the database for a limited period. The VMware V motion helps support the premises systems which work through on-line and VM ware cloud. The API or V sphere client or V sphere web client is used to using the V motion function. To make use of the new attributes in the VMware updates it is essential with the changes in the on-prem and vCenter system for the server and the new version of 6.7 from the center server. VMware Course in Chennai brings the knowledge and the industry specification into the course to make the students ready for the job. Library for the virtual appliance OVA is a library to maintain content in virtualization and these files are opened at the time of import by unzipping option. This content library is helpful in the deployment of the virtual machines with the library item. The instances in the vCenter help for the control of the reproducing the data with the other controller for the platforms from external sources instances. In the replication mode, the platform for the external services is controlled in all the topologies. The platform for external services is used to control the restored syncs and active peers. Application Management user interface The HCI provides the guided user experience for configuration. It automates the repetitive operations, uses embedded technology for the best practices, and distributes a wizard that is centralized to share the experience of the completed projects. To manage the settings for the firewall in the new version the Application management with the UI is used to edit and configure. The administration is managed from the shell administrator group and can access the vCenter server appliances using the administrator in the shell which is called bash shell. The active directory windows 2016 is supported in the vCenter server new version update. The dark theme and the color for the interface are handled with the color change scheme in the V sphere client display. Plug-in used in the new version The app defense vCenter server plugin in the VMware is the integrated one. The applications running with the help of the V sphere are provided with the app defense to gain multiple pros. App defense aids for the life cycle management, monitoring the behavior of the application with visibility, security calculations, and fixing the issues within the vCenter Server. The client of VSphere is used to check the host profile check regarding the compliance and this check happens during the interval or at a future process. VMware Course in Chennai outnumbers a good number of students every year to match the industry demand for the VMWare professionals. vCenter server is used to take from the host profiles the individual profiles or a group of sub-profiles and create profiles. The wizard with the copy setting helps for creating the profiles. The ESXi hosts along with the clusters are used to attach or detach the host profiles. The dialogue box is used by the cluster to attach or detach. The different patches of the VMware vCenter server new version are the full patch, security patch, product fixes of the third party, and these patches are updated with the version of the JRE. These patches are downloaded using the VMware patch download center. VMware Training in Chennai is the best training to enter into the networking profession. The information regarding the OS updates for the photon is derived from the appliances for the V center that is the photon OS which deals with the interface for appliance management is used to know more about the patching. VMware Course in Chennai is designed with a detailed syllabus and engaged by the expert professionals from the industry. The third-party customization and using builder for the image is known by seeing the installation of the ESXi and the documentation part is set up. The different types of issues are the overall issues, issues related to networking, issues related to security, installation issues, storage issues, issues due to updates, management issues because of virtualization, issues when using the tools, licensing issues, os issues from the guest, configuration problems from the server, issues related to internationalization and V sphere client issues of CIM, vSphere web client issues, vCenter server issues, and API issues are the wide range of issues that are covered in the new version. If the ESXi host is attached version 6.0 through the host profile and the host upgraded to the incremental version 6.7 then this will lead to miscellaneous error. This issue is resolved in this version. When performing the actions like taking out the elements from the host profile, the ESXi host has been changed to version 6.7, the error occurs, and even after the remediation the host appears to be without any complaint. If the filter is used during a system update and it no longer exists then it leads to the vpxd failure. Due to the race with thread, the vpxd service tends to fail. Unable to stage patches through a controller that controls the external sources. If the patches are staged, the update repository will use the patches and try to upstage and this will lead to the error like an error in invocation. After a data refresh, the grid for the old performance values is not retained and the values can be set in a sorting order for column values. The issue is not there in this new version. If the “SAN” field consists of extra details then the v Sphere certificate manager will not change one machine to the other machine. The extra details like the sites, common names, and IP addresses. vSphere manager issue The latest version is released with the fix to these concerns and the vSphere manager will check the name of the system name mentioned with the software. If the ESX host is sacked from the ESXi host then the vCenter server will stop responding to the Startups in the ESXI. The issue is changed with this release. This issue has been handled and fixed in this version. VMware Training in Chennai trains and helps the students to know their potential with real-time projects. The Syslog files grow exponentially and the rotation of the log may stop after the first round. Compression for the Syslog files also stops. The issue is fixed in the new version and enhanced with the postulated services. The LAG issue with the network is corrected with this version. If the group link aggregation is used to import the switch configuration for the Vsphere distribution then LAG information is not inserted in the server database from the vCenter. After restarting the vpxd service some LAGs are missing and the issue is solved in this new release. If the LAG is missing then reimport the v Sphere switch configuration distribution and manually create the LAG which is missing. The cloning of a template or the virtual machine deployment with template leads to VM static MAC conflict alarm and this concern is solved in the new release. VLAN settings provide incorrect health details to check shock with switch port groups along with NSX logical and this is solved in the latest version. The problems in the performance of the VXLAN are fixed in the new release and it uses the lower rates of sampling for the high performance. vCenter server application management The issues from the vCenter management interface for the server appliance lead to the HTTP error and this is solved in the latest release. This improves the label of the user interface and the Supported protocol is provided in the URL field of the server which is proxy. An updated version of the components Postgres in the previous version is now changed and the Procmail is also been changed. cURL with vCenter service appliance has been changed. The version of the Eclipse jetty has been changed. The validation of the XML which utilizes the –schema Validate flag is now disabled in the VMware OVF Tool. The version OpenSSL-1.0.2o is the updated version of the OpenSSL library in the latest release. The SQLite database has a new version. The version of libpng-1.6.34 is updated to the libPNG library. The third-party python library is used with the updated version in the new release. The Tomcat server in the Apache is used with the new change in the version. The libxml library is used with the new version which enhances the services. The updated version is called as a package from Apache belongs to version 3.4.0. The JRE package of the Oracle is updated with the new version. To correct the issues in CVE-1327 and CVE 2018-11776 apache struts is updated as 2.5.17. The glibc is now used with the 2.22-21 versions. Error due to unregistering of the API in the VSphere v Sphere and during the disconnected stage the event and manager for the alarm are not active which leads to error. The disconnected state and the awareness provider concerning the storage create the error. These storage concerns are fixed in the latest version. In the V sphere client, the unauthorized error is shown if the features are not available in the datastore level. It is difficult to use the ISO file using a data store if the features are not available. These types of concerns are fixed in the latest version. VMware Course in Chennai trains the students and prepares them for the interview with the mock interviews from the trainer. The CLI installer in the vCenter server appliance has been changed to the new version. Services from the second platform controller in the existing version might fail and services from the second platform controller with the eternal deployment also go with stage 2 in the existing v Center. The connectivity is upgraded in the latest version and the validation with SSO is updated. During making changes or during the installation the installer named GUI shows an error message. The new version is designed with no such errors and the failure of the first boot creates an error specific message. The DNS security extensions with DNS servers which are used to upgrade the v Center server appliance might fail in the vCenter server system. When resolving the hostname the system uses the RR set signature of the DNSSEC is used in the place of IP address. These issues are related to the upgrading and it is solved in the new version. The new version shows an error stating that the IP address already exists. If the shutdown of the source appliance fails in the 2nd stage of the upgrade of the V center because of a long time due to network issues. The error is due to the network settings in the newly deployed appliance with the target is not active. The issue is taken care of and fixed in the latest version. Different types of issues like the virtual machine management issues, deployment of replication appliance, handling OVF file, undeleted tasks handling and CLS task, OVF tool issues, Guest OS issues, issues related to licensing, internationalization issues, API issues, CMI issues, SNMP issues, VSAN issues, edit customization option with the client of the V Sphere, Paravirtual SCSI disk adapter issues, WebMKS console issues, ESXI issues and fault tolerance issues are resolved in the latest version to enhance the services to the wide range of followers. Management issues The ESX manager server in the vSphere shows an error due to the serialization and deserialization problems. When communicating with the agent manager ESXi the error is seen. These concerns with the v Sphere ESX agent is solved in the recent release. The vSphere replication carries an error message if the cluster does not have shared storage and the deployment fails due to the error. The OVF descriptor becomes invalid. The issue is solved after this release. This error and the problem with the deployment is solved in the latest version. OVF file The namespace and the specified prefix makes the OVF file to fail. The system handles the default namespace and the issue is solved in the latest version. The error in the cross-server migration with vCenter is fixed in the latest version. Dealing with the undeleted tasks When dealing with the undeleted tasks or new tasks in the vCenter server system the content library service will automatically clean the outstanding tasks which lead to the failure of the new tasks also. The issue is settled in the latest version of VMware. A separate library is created by the content library service called SMB share and if it fails then it takes the storage space in the server system of the v Center. The issue with the storage does not disturb the NFS mounts. VMware consists of articles with a knowledge base that also help in solving these issues. Issues with OVF tools When the template is used to deploy the ISO file in the v Center Server or to the ESXIi host the failure happens because the tool finds it difficult to read the content in the ISO file. The issues in the old are changed in the new release. Import operations The import operations in the VMware workstation or fusion in the VMware is done with the help of the paravirtual SCSI in the VMware disk adapter and this may face failure with an error message. This problem is fixed in the latest release of VMware. The card adapters with sound are used for import and export which also ends with error message and failure. The issue is corrected in the latest version. The deployment of a virtual machine with the help of the OVF tool in the VCloud director ends up with failure and vCloud director API versions are the right one to deploy the virtual machines with the latest version. This problem is handled and corrected in the latest version. VMware Course in Chennai is the best course for the students with an interest towards virtualization. When doing the Linux customization the IPV6 loopback is deleted and this problem of deleting the IPV6 entries is taken care of in the latest version. OS issues with virtual machine If RHEL is used for the customization of IP for a test recovery then the host file is empty on the place where it is recovered. The issues in the old are changed in the new release. Issues with licensing The VM ware authority certificate is automatically given to the ESXi hosts who have custom certification. The issue is solved and the vCenter server essential plus gives license capacity for the host to the wireless virtual machine. For the AvSAN 2-cluster host one witness and two hosts are required. The vCenter server takes the witness appliance like a host and because of this the witness also resides in the virtual machine. So, the witness also gets a license for hosting and the issue is fixed in the latest version. Issues with the internationalization The non-ASCII characters in the content library show failure and this will not sync. If it is Chinese or Japanese in the library then it will fail due to the multi-byte in non-ASCII characters. These synchronization issues are solved in the latest release. Join the VMware Training in Chennai and become a follower of the advancement in the VM ware. Issues with the configuration If the SSL protection is active then it is not possible to create an active directory with LDAP source for identification. The error message is shown if the SSL protection is connected to the controller used for the domain. The issues in the old are changed in the new release.
https://www.fita.in/vmware-training-in-chennai/
CC-MAIN-2022-05
en
refinedweb
0.7.1 • Published 10 months ago @talves/use-web-storage v0.7.1 See reference to get aquainted with the Web Storage API The two mechanisms within Web Storage are as follows: Window.sessionStorage Window.localStorage Installation This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies: npm install --save @talves/use-web-storage OR yarn add @talves/use-web-storage Usage import { useWebStorage } from "@talves/use-web-storage"; export default (props) => { const [storage, setStorage] = useWebStorage( "test-data", { site: "tony.alves.dev" } // { type: "sessionStorage" } // default is "localStorage" ); const handleChangeEvent = (e) => { setStorage({ site: e.target.value }); }; return ( <div> <input onChange={handleChangeEvent} defaultValue={storage ? storage.site : ""} /> {storage && <pre>{JSON.stringify(storage, null, 2)}</pre>} </div> ); }; NOTE: This is a module package library for react with jsx. The choice is to resolve the export of main to src/index.js. There is a commonjs version in dist/cjs/index.js if someone needed. IMPORTANT (Must Read): Tracking Changes from other pages/settings. window.addEventListener('storage', function(e) {})does not track changes on the same page. The reason you use the hook for page state. StorageEventis fired whenever a change is made to the Storage object only for localStoragechanges on different pages of the same domain. (Note that this event is not fired for sessionStoragechanges)
https://npm.io/package/@talves/use-web-storage
CC-MAIN-2022-05
en
refinedweb
10. Strings C has intgral types like char, int, long and long long, floating-point types like float and double. However, to treat a sequence of characters which is also called string no new data type is needed. An array of characters or a pointer to character can be used to represent strings. A C string is a sequence of characters stored in contiguous memory locations ended by 0 or \0 or NULL. It is mandatory for strings to have this ending else you will have surprises. A C string typically have one of the following declarations: const char str1[] = "Some string"; char str2[16] = "Some string"; const char* str3 = "Some string"; char* str3=NULL; // Allocate and fill with characters later The first three strings will be on stack while the last one will be on heap as we will need to use malloc to allocate memory for it. Since a C string is either an array or pointer you can use [] operator to get characters by index from string. You can read a string from the stdin i.e. keyboard using deprecated and unsecure gets function or secure fgets function as we have seen in console I/O chapter. We can use realloc function to read an infinite string as shown below. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> int main() { char *inf_str = (char*)calloc(16, sizeof(char)); char c=0; size_t i = 0, j = 1; while((c=getchar()) != '\n') { if(i%16 == 0) { j++; inf_str = (char*)realloc(inf_str, sizeof(char)*16*j); } inf_str[i++] = c; } inf_str[i++] = 0; puts(inf_str); free(inf_str); return 0; } Note that we are allocating 16 bytes to avoid allocation large chunk of memory which may be wasted. Also, if you keep it too small then there will be many calls to realloc. This value depends on how much data you are going to read and accordingly adjusted. We allocate memory for multiple of 16 characters to start with and we read characters from keyboard one by one till we encounter \n. Once 16 characters have been read which is determined by i%16 we allocate 16 more characters. For this we use another counter j. Finally we put 0 at the end of string to NULL terminate it, print it and free the allocated memory. This is a very good program but in one case it will have problem. Suppose you want to read a large string and your memory is fragmented due to which one contiguous sequnce of memory is not available then you cannot read the string in to memory even though total free memory is more than memory required by string. Some languages like Erlang split memory in chunks and create a linked list to store strings. Also, this reallocation may require full scan of string which will cause :math: O(n) time cost. Therefore, there is no one shot solution to read strings into memory. To work with strings you must know functions provided by header string.h otherwise you will be duplicating the functionality. 10.1. Useful Functions 10.1.1. strlen and strlen Functions One of the most common operations is to know length of the string because it is needed as input in many functions. There are two versions of it. strlen is slightly unsecure because it depends on the \0 character of string which means if string is not NULL terminated then strlen will contnue to read past the length of string. strnlen takes an extra argument which is the maximum length of string and beyond that it will not read. I am giving signatures and descriptions below. #include <string.h> size_t strlen(const char *s); size_t strnlen(const char *s, size_t maxlen); The strlen() function calculates the length of the string s, excluding the terminating null byte ( \0). The strlen() function returns the number of bytes in the string s.. The strnlen() function returns strlen(s), if that is less than maxlen, or maxlen if there is no null byte ( \0) among the first maxlen bytes pointed to by s. Let us see examples as to how to use these: #include <stdio.h> #include <string.h> int main() { const char* str1 = "Hello"; const char str2[] = "Universe"; printf("Length of str1 is %Zd\n", strlen(str1)); printf("Length of str2 is %Zd\n", strnlen(str2, 8)); return 0; } Note the use of conversion specifier %Zd because return value of these functions is size_t. The output is: Length of str1 is 5 Length of str2 is 8 You can also implement strlen and strnlen yourself easily. Note that if you are implementing these functions with the same name then do not include the header which has the prototype of the function in this case string.h otherwise you will have error for duplication. For example consider the following program: #include <stdio.h> #include <stddef.h> size_t strlen(const char* s) { size_t i=0; while(*s++) ++i; return i; } size_t strnlen(const char* s, size_t maxlen) { size_t i=0; while(*s++ && (i < maxlen)) ++i; return i; } int main() { const char* str="Hello there!"; printf("%Zd\n", strlen(str)); printf("%Zd\n", strnlen(str, 20)); printf("%Zd\n", strnlen(str, 10)); return 0; } 10.1.2. strcpy and strncpy Functions Another important operation is copying one string to another. For this we have strcpy and its secure version strncpy. You should avoid using strcpy because if destination is smaller than source then strcpy will write past the end of destination length which is a security flaw. strncpy puts additional overhead on programmer which is to provide an extra argument specifying how many bytes to be copied at max. Let us see the synopsis and description of these functions. . Beware of buffer overruns!() writes additional null bytes to dest to ensure that a total of n bytes are written. The strcpy() and strncpy() functions return a pointer to the destination string dest. Some programmers consider strncpy() to be inefficient and error prone. If the programmer knows (i.e., includes code to test!) that the size of dest is greater than the length of src, then strcpy() can be used. One valid (and intended) use of strncpy() is to copy a C string to a fixed-length buffer while ensuring both that the buffer is not overflowed and that unused bytes in the target buffer are zeroed out (perhaps to prevent information leaks if the buffer is to be written to media or transmitted to another process via an interprocess communication technique). If there is no terminating null byte in the first n bytes of src, strncpy() produces an unterminated string in dest. You can force termination using something like the following: strncpy(buf, str, n); if (n > 0) buf[n - 1]= '\0';. The best idea is to have large enough buffer to hold source string and use strcpy. Thus the responsibility of ensuring this is upon you, the programmer. Let us see example programs for these two functions: #include <stdio.h> #include <string.h> #include <stdlib.h> Notice that you need to pass space including the NULL byte in strncpy call. You can also implement your own version of strcpy and strncpy. For example, #include <stdio.h> #include <stdlib.h> #include <stddef.h> char* strncpy(char* dst, const char* src, size_t n) { size_t i = 0; while((i++ < n) && (*dst++ = *src++)); return dst; } char* strcpy(char* dst, const char* src) { while(*dst++ = *src++); return dst; } 10.1.3. strcat and strncat Functions Some high level languages like C++, Java, Python use operator overloading (which is typical to object oriented languages) and use + operator to concatenate strings. However, C is not object oriented and hence we do not have facility of operator overloading but C provides two functions strcat and strncat to achieve the same goal. Let us see their descriptions in man pages. #include <string.h> char *strcat(char *dest, const char *src); char *strncat(char *dest, const char *src, size_t n); The strcat() function appends the src string to the dest string, over-writingbytes from src; and srcdoes not need to be null-terminated if it contains nor. Let us see an example as how we use these functions: #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char *str1 = "Hello"; char str2[] = "world"; char str3[12] = {0}; char *str4 = (char*)calloc(12, 1); strcat(str3, str1); strcat(str3, " "); strcat(str3, str2); puts(str3); strncat(str4, str1, strlen(str1)); strncat(str4, " ", 1); strncat(str4, str2, strlen(str2)); puts(str4); return 0; } We can implement these functions similar to previously implemented functions. For example #include <stdio.h> #include <string.h> #include <stdlib.h> char* my_strncat(char* dst, const char*src, size_t n) { size_t i=0; size_t dst_length; dst_length = strlen(dst); while((i<n) && *src) { dst[dst_length + i] = *src; src++; i++; } dst[dst_length+i] = 0; return dst; } char* my_strcat(char* dst, const char*src) { size_t i=0; size_t dst_length; dst_length = strlen(dst); while(*src) { dst[dst_length + i] = *src; src++; i++; } dst[dst_length+i] = 0; return dst; } int main() { char *str1 = "Hello"; char str2[] = "world"; char str3[12] = {0}; char *str4 = (char*)calloc(12, 1); my_strcat(str3, str1); puts(str3); my_strcat(str3, " "); puts(str3); my_strcat(str3, str2); puts(str3); my_strncat(str4, str1, strlen(str1)); puts(str4); my_strncat(str4, " ", 1); puts(str4); my_strncat(str4, str2, strlen(str2)); puts(str4); return 0; } 10.1.4. strcmp and strncmp Functions There are very frequent requirements for comparison of two values when programming. Integers and characters can be compared easily. Floats can be compared with a very high degree of accuracy. However, comparing strings is to be done character by character and like strcat and strncat object oriented programming languages use same operators for strings which are used for compare integers or characters like == for equality, < for less than and so on. Once again C provides functions not simpler operator comparison to compare two strings. Let us see what man pages say about them: #include <string.h> int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); compares the only first (at most) n bytes of s1 and s2. Let us see an example program for these two functions: #include <stdio.h> #include <string.h> Let us try to implement these functions ourselves: #include <stdio.h> int strncmp(const char* s1, const char* s2, size_t n) { size_t i = 0; while((i < n) && *s1 && (*s1==*s2)) { s1++,s2++; i++; } return *(const unsigned char*)s1-*(const unsigned char*)s2; } int strcmp(const char* s1, const char* s2) { while(*s1 && (*s1==*s2)) s1++,s2++; return *(const unsigned char*)s1-*(const unsigned char*)s2; } 10.1.5. strstr, strchr and strrchr Functions Many times we want to find whether a particular character is in string or not. It is easy to do it in C yourself but we have two functions which help with that. Those are strchr and strchr. Many other times we want to find whether a given string is a substring of another given string. This is simple to do but most of the time those simple solutions will be inefficient. C provides a function strstr for this and compilers usually provide an implementation of a very good algorithm. I will not go into the algorithm provided by gcc now but just describe the function and its example. Let us see what man pages say about these functions: #include <string.h> char *strstr(const char *haystack, const char *needle); char *strchr(const char *s, int c); char *strrchr(const char *s, int c); The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating null bytes ( \0) are not compared. It returns a pointer to the beginning of the substring, or NULL if the substring is not found. The strchr() function returns a pointer to the first occurrence of the character c in the string s. The strrchr() function returns a pointer to the last occurrence of the character c in the string s.. Let us see an example: #include <stdio.h> #include <string.h>; } and the output is: ello (nil) llo lo Helloo (nil) Let us try to implement these three routines ourselves. Now strstr is a complex one. There are lots of very good algorithms. You can find a good list of implementations here. The algorithm which I will present will be a brute force one and should not be used for any good code. I am giving it just to present an example. Giving code for algorithms mentioned in the link is out of scope and will be covered in data structures and algorithms book. #include <stdio.h> char* strstr(const char *haystack, const char *needle) { if (haystack == NULL || needle == NULL) { return NULL; } for ( ; *haystack; haystack++) { const char *h, *n; for (h = haystack, n = needle; *h && *n && (*h == *n); ++h, ++n) { } if (*n == '\0') { return (char*)haystack; } } return NULL; } char* strchr(const char* str, int c) { char *i = NULL; while(*str) { if(*str == c) { i = (char*)str; return i; } str++; } return NULL; } char* strrchr(const char* str, int c) { char *i = NULL; while(*str) { if(*str == c) i = (char*)str; str++; } return i; }; } 10.1.6. strerror Function strerror funciton maps an integer to error message. Typically the value of this integer comes from errno but it will accept any integer argument. A small sample program shows the messages printed. #include <stdio.h> #include <string.h> int main() { for(int i=0; i<135; ++i) printf("%d %s\n", i, strerror(i)); return 0; } and the output is: 000 Success41 Unknown error58 Unknown error 58 134 Unknown error 134 10.1.7. strtok Function There are times when we need to split a string for a set of delimiters. C provides a function called strtok. Note that strtok is not multi-thread safe so if you need to use strtok in a multi-threaded program then consider using its reentrant version strtok_r. #include <string.h> char *strtok(char *str, const char *delim); char *strtok_r(char *str, const char *delim, char **saveptr);. Let us see the example given in man page: #include <stdio.h> #include <stdlib.h> char * strtok(char * str, char *comp) { static int pos; static char *s; int i =0, start = pos; if(str!=NULL) s = str; i = 0; int j = 0; while(s[pos] != '\0') { j = 0; while(comp[j] != '\0') { if(s[pos] == comp); } and the output is: $ ./a.out 'a/bbb///cc;xxx:yyy:' ':;' 1: a/bbb///cc 2: xxx 3: yyy Let us try ti implement strtok ourselves: #include <stdio.h> #include <stdlib.h> char * strtok(char * str, char *delim) { static int pos; static char *s; int i =0, start = pos; if(str!=NULL) s = str; i = 0; int j = 0; while(s[pos] != '\0') { j = 0; while(delim[j] != '\0') { if(s[pos] == delim); } With this we come to an end of our discussion on strings.
https://www.ashtavakra.org/c-programming/strings/
CC-MAIN-2022-05
en
refinedweb
The Prime Equation Primal Wave Interference Where: Expanded form: Solve for 0: Wave function for all integers: (Observe that the wave passes through every integer at y = 0) Wave function of p₁ (i.e. the prime number 2): (Observe that the wave passes through every other integer at y = 0, that is every even number 2, 4, 6…) The interference pattern for both wave functions shows that both waves meet at y=0 only at even numbers: Now that we have defined a waveform that passes through all integers and a waveform passing through the prime number 2 and all multiples of the prime number 2, we can compare the interference pattern of the two waves by solving for zero. Simply dividing p₀ by p₁ (p₀/p₁). The solution of the expression (the vertical purple lines) shows that all even numbers can be expressed through the wave function of p₁, which is the wave function for the prime number 2 and every multiple of the prime number two, that is 4, 6, 8, 10,…,34, etc.: Solving for 0, it is evident only odd numbers are left to be expressed as a wave function and are spaced every other number — which is has been observed as the Twin Prime Conjecture. The first prime wave function (p₁) allows for 50% of all integers to be expressed and what’s left are all the integers where no wave function passes 1, 3, 5, 7, 9, 11 — that is every odd number. Once the equation is solved for p₁, we see that the twin prime conjecture is nothing more than the observation that after solving for P₁, all the even numbers are expressible, and only the odd numbers remain as possible primes, and we know that odd numbers are only one number apart a.k.a. “twins.” Therefore, it can be deduced that there are an infinite number of twin primes possible. N.B. — This does not prove with 100% certainty, that there are an infinite number of twin primes (although this certainly appears to be the case). It only shows that there are infinite number of twin primes POSSIBLE. The only thing that can be deduced with 100% certainty is that there are infinite possible locations for twin primes to show up — thus it is no surprise that twin primes exist. Solving for p₂: Once the function is solved for p₁, the next step is to solve p₂, where the function equals 0 for the waves of all integers and the wave of p₂. Integrating the wave expression of p₂ into the function, it is seen that not only is there now an expression for 3, but also for 9 and 15, etc., ad infinitum. N.B. — Because odd number products alternate between odd and even numbers, and only even numbers currently have a wave expression, we can deduce that p₂ (i.e. the prime number 3) will be a solution for every other number, solving for 3, not 6, 9, not 12, 15, not 18, 21, not 24, ad infinitum. By removing the function we can see an expression of perfect infinite symmetry in the Prime Equation of p₀/(p₁*p₂): Solving for p₃: From the result above, it’s clear the next prime is the number 5. Thus a new wave to express p₃ is required. N.B. — zooming out, it is shown that the wave of p₃ is not only an expression for 5, but also for 25, 35, 55, and all other wave expressions that end in 5, ad infinitum. Thus once the wave expression for p₃ is introduced, there are no prime numbers that end in 5. Inserting the wave expression for p₃ into the formula creates the following result: Solving for p₄: From the result above, it’s clear the next prime is the number 7. Thus a new wave to express the fourth prime i.e. p₄ is required. …………ad infinitum (and beyond)… Conclusion: Primes aren’t random. They’re exactly where they are needed to express a quantity that cannot be expressed with any previous prime. Finding the location of any prime is contingent on solving the dynamic prime equation, where each successive wave expression in the equation, is not only an expression for the next 0 of the function but also for an infinite number of 0s on the y-axis further down the series. Using this equation, it can be seen that the wave patterns of the prime numbers (prime building blocks) overlap and interference with each other — and it quickly becomes apparent that a prime can only end in 1, 3, 7, 9. The key is to understand that it cannot be known for certain which results are primes until the equation has been resolved for all previous primes up to the number being evaluated. Bonus 1: The last statement of the conclusion isn’t 100% accurate. For any number “x” evaluated, it can be known to be a prime with 100% certainty as soon as the function has been run for all numbers ≤ x/2 — that is to say, just over half the number “x” being evaluated. Another way of stating this is to say that: Once the equation is solved for up to P to the nth prime, it is certain that all 0 results of the function greater than P to the nth prime and less than twice the product of P to the nth prime are also prime. This is because, if the equation has been solved for up to P to the nth prime, it is 100% certain that there are no wave expressions greater than P to the nth prime and less than twice the product of P to the nth prime that exist to express the waves where the function is 0. e.g. - p₃ is the wave expression for the prime number 5 - 2*p₃ is the wave expression for the composite number 10 - The function of Pₐ=0 at x=7 - We know that every wave expression <p₃ already exists and any wave expression >p₃ will result in a number greater than 7 - Therefore, it can be known with 100% certainty that 7 is a prime. Build Your Own Equation Expressed as a Dynamic Prime Wave: Desmos | Graphing Calculator Explore math with our beautiful, free online graphing calculator. Graph functions, plot points, visualize algebraic… N.B. — If you find any errata in the above — please comment for me to correct. Addendum: After further research I have encountered a formula that appears to be a variation of the function I have presented which is the Prime Zeta Function a.k.a. Euler’s Product Formula developed by Leonard Euler. Bonus 2: Here’s the start of a Python program that shows the results of the equation above by running the functions for Primes 1–5, i.e. 2, 3, 5, 7, & 11. As you can see each function for the next prime contains all previous equations to compare against. # <<< imported python libraries/commands >>> import math# <<< program functions >>># <<< variables >>> pi =round(2*(math.acos(0.0)), 10) # <<< Comparing wave expression for all integers against wave expression for prime numbers >>>def p1(): x=1 while x >= 1: x += 1 f0 = round(math.sin(pi*x)) f1 = round(math.sin((pi*x)/2)) if f0 == (f1): return(round(x))def p2(): x=1 while x >= 1: x += 1f0 = round(math.sin(pi*x)) f1 = round(math.sin((pi*x)/p1())) if f0 != (f1): return(round(x))def p3(): x=1 while x >= 1: x += 1 f0 = round(math.sin(pi*x)) f1 = round(math.sin((pi*x)/p1())) f2 = round(math.sin((pi*x)/p2())) if f0 != (f1 * f2): return(round(x))def p4(): x=1 while x >= 1: x += 1 f0 = round(math.sin(pi*x)) f1 = round(math.sin((pi*x)/p1())) f2 = round(math.sin((pi*x)/p2())) f3 = round(math.sin((pi*x)/p3())) if f0 != (f1 * f2 * f3): return(round(x))def p5(): x=1 while x >= 1: x += 1 f0 = round(math.sin(pi*x)) f1 = round(math.sin((pi*x)/p1())) f2 = round(math.sin((pi*x)/p2())) f3 = round(math.sin((pi*x)/p3())) f4 = round(math.sin((pi*x)/p4())) if f0 != (f1 * f2 * f3 * f4): return(round(x))
https://aenigmaenterprises.medium.com/the-prime-equation-a9cc04ce8446
CC-MAIN-2022-05
en
refinedweb
Hi experts, I have a problem with an XSLT Mapping. I have multiple mapping steps, first two graphical mappings, then one XSLT mapping. Occurence of the Messages is 0..unbounded. The XSLT mapping fails with the following error: Mapping "urn:namespace/operation_mapping" failed to execute: MappingException: Unexpected error while parsing the multi-structure document, NullPointerException: while trying to invoke the method javax.xml.stream.XMLEventWriter.add(javax.xml.stream.events.XMLEvent) of an object loaded from local variable 'writer' I am aware of SAP notes 1809068 and 1723202 and I also read the other questions in SCN regarding this problem. The notes say that this is an error in XI Adapter Framework which is fixed by some patches. But: We have PI 7.31 SP15 with patch level 25 and this fixes should be included there: And one more interesting thing: If I replace the code of my original XSLT with the following (very simple) one, the error does not occur: This is the original XSLT (it basically reads an authToken from payload an places it in the SOAP:Header): Any ideas how to fix this? Thanks & regards, Stefan
https://answers.sap.com/questions/12042327/xslt-problem-unexpected-error-while-parsing-the-mu.html
CC-MAIN-2022-05
en
refinedweb
WCF Web Progamming 1. Jef 0. OK. So, I picked myself up, dusted off, and got ready for round 2. Now that I have been sufficiently schooled on the virtues of WebServiceHostFactory, I am ready for my next baby steps. But first, I wanted to demo the simple service and do a quick review. I ripped out all of the <system.serviceModel> configuration, slammed in my factory attribute on the servicehost directive: <%@ ServiceHost Language=C# Debug="true" Factory="System.ServiceModel.Web.WebServiceHostFactory" Service="Improving.Samples.WCF.Web.Hello" %> using System.ServiceModel; using System.ServiceModel.Web; namespace Improving.Samples.WCF.Web { [ServiceContract()] public class Hello { [OperationContract] [WebGet()] public string Say() { return "Hello, Cruel World"; } } } read another blog post from Steve to be on the safe side, and hit f5. Ha. Oops. So, I actually know what this problem is. In WCF, endpoints don't map to Services but rather to methods. So when I browse to /Service.svc, I am not actually addressing an endpoint, I am addressing a class that contains methods that are exposed as endpoints in WCF terms. I can fix it by appending the method name to the URL (/Service.svc/Say): I can also (almost) fix it with a wildcarded UriTemplate, but we'll save that for tomorrow. As mentioned, the model is currently a little picky about trailing slashes, so /Service.svc/Say/ yields the first image above. Now. If we revisit the service contract defined above, the only thing excluding the WebServiceHostFactory that is specific to ol' Webby is the WebGet attribute. If we look at the web get attribute, it defines a couple of public properties that allow us to shape the messaging a bit, BodyStyle and UriTemplate. We'll take a glance at BodyStyle first. BodyStyle is an instance of the enumeration type, WebMessageBodyStyle: public enum WebMessageBodyStyle { Bare, Wrapped, WrappedRequest, WrappedResponse } Bare is the default value, and results in the <string ... /> encoding you see above in the browser. It would be a lot more interesting with a more interesting serializable type. WebMessageBodyStyle.Wrapped returns something like: WrappedRequest and WrappedResponse give you control over the individual messages. I won't demonstrate those further. I'll look a little more closely at UriTemplate tomorrow. Following that, I want to pllay around with basic HTTP types of things like cache awareness, content negotiation, json, status codes, headers, chunked encoding, streaming, async models, etc. Once we get all of that squared away, I'll start using the API to do "real" stuff. Then I'll dig into the syndication support, etc. Quick review: Currently, I think that IHttpHandler has a slight leg up on WCF in terms of simplicity and adhering to the principle of least astonishment. One thing I do get from the WCF web programming model is serialization to and from .NET types. That is pretty cheap with DataContractSerializer, XmlSerializer, and friends. Another thing that I get is a more simplistic method of mapping HTTP methods to .NET methods, so I can avoid having a Servlet-like interface and I can avoid writing a switch statement. The Microsoft namespace for serialization is interesting, but I would want to avoid that. It's a bit too leaky an abstraction for me, though I suppose I grok why it's there. We haven't done anything terribly interesting yet, so I am still feeling very positive about the WCF web programming model. There's some good stuff under the hood. UriTemplates, for example. Looking forward to it. Recent Comments
http://integralpath.blogs.com/thinkingoutloud/indigo/
CC-MAIN-2017-17
en
refinedweb
When you start learning a new language, you fear a lot thinking how much trouble to face and concentration is required, as this is the impression left by C/C++ while you learnt. Remember one thing, Java Designers always aim only two things while developing the language – how to make language simple to learn and practice and how to increase the performance. You believe this when you start learning Java programming. Java comes with many features like Platform-independent, Multithreaded and Internet-based etc. Java is easy to practice due to non-support of pointers. Developer need not bother about memory management as is implicit in Java. For this reason, Java does not include functions like sizeof(), malloc(), calloc() and free() etc. Java does not have Destructors but Constructors exist. Java Programming constructs include Classes, Interfaces, Methods, Constructors and Variables like a House constructs are Bricks, Cement and Sand etc. The basic unit of Java programming is class. All the code you write should be placed within the class declaration only. That is, outside the class you are not allowed to write anything. The class declaration starts with a open brace and ends with a close brace. See the following code on Java programming. Then we will discuss further. To compile a program, Java does not require main() method. But to execute, main() is required. As I want to compile and execute the above program, I included main(). The code includes two variables, one constructor, one method and finally main(). Observe, the whole code in included within the open and close braces of the class which Java demands. import java.lang.*; It is equivalent to include statement of C-lang. java.lang is known as package equivalent to a header file of C-lang. A package contains classes and interfaces. The classes we use of this package in our code are String and System. Student std1 = new Student(); std1 is known as object of Student class. Infact, an object in Java is a handle to access the constructs of the class. With std1, the method display() is called. It comes with two parameters of n1 and m1. The method parameters of a method are always treated as local variables as in C/C++. The local variables are assigned to instance variables name and marks. When assigned, the instance variables (known as global variables in C/C++) gets values and can be used from any part of the class. Infact, they are used in main(). Here, I discussed very briefly withtout explaining keywords used, syntax of creating an object, encapsulation, process of compilation and execution etc. Go through the following links in the same order to land smoothly in Java. Following links give you an easy understanding of coding in Java. The examples are precise, easy and answer to the point. 1. OOPS concepts Tutorial 2. Java Example Compilation Execution 3. Java Local Instance Variables 4. Data Binding Data Hiding Encapsulation
http://way2java.com/java-general/introduction-to-java-programming/
CC-MAIN-2017-17
en
refinedweb
Hey All, It appears that the Frost is nearing completion, and the Feature Freeze will be setting in soon. Given this, it's probably a good time to start putting together a list of release blocker bugs, as well as discuss if any features need to be pruned due to them being incomplete. For reference, here are the bugs that are still milestoned for 0.47: Is anyone aware if there currently any major platform specific bugs like we had around 0.46? (win32 printing issue is what I speak of) Also, JonCruz, should we hold back the "Auto" swatch palette from this release? At this point I want to again remind people to ensure that the release notes are as up-to-date as possible! Please take a moment to ensure that your improvements/enhancements/new features are all mentioned with a brief explanation where necessary. Thanks to everyone for your contributions! Cheers, Josh May i suggest to only refactor as much as really needed to close the bugs that are open. Wasn't there this discussion about to use export and import dialogues for non svg file formats where is a potential loss of information and to use open and save only for svg. ... Adib. On Sun, Aug 9, 2009 at 6:56 PM, Maximilian Albert<maximilian.albert@...> wrote: > 2009/8/9 bulia byak <buliabyak@...>: > >>> Yes, right. I got a bit confused from reading the code. :-) I didn't >>> know that there are two types of export dialogs, one of which mimicks >>> the regular Save dialog and is deactivated by default. I have never >>> tried it anyway. Does it work and does anyone use it? >> >> The save-like dialog is for vector output, the "other" one is for >> bitmap export (ctrl+shift+e). > > I'm not sure if I understand which dialog you're referring to because > it sounds like the one you're describing is in regular use. I'm > talking about the one which is defined in ui/dialog/filedialog.cpp > starting from line #240 (as of rev. 22036) and which has #ifdefs > around it. Anyway, I just tried it and it's apparently not currently > used since Inkscape didn't even compile when I uncommented #define > NEW_EXPORT_DIALOG. :-P > > Now I put the whole code which refers to this dialog between #ifdef's > and fixed the build when NEW_EXPORT_DIALOG is defined. However, the > dialog crashes when trying to export any file. I'm wondering if it can > be scrapped completely since it's apparently not in use and doesn't > seem to have been touched since revision 12671. Any opinions? > > Max > > ------------------------------------------------------------------------------ > Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day > trial. Simplify your report design, integration and deployment - and focus on > what you do best, core application coding. Discover what's new with > Crystal Reports now. > _______________________________________________ > Inkscape-devel mailing list > Inkscape-devel@... > > On 12/8/09 14:01, ~suv wrote: > On OS X 10.5.8 using Inkscape 046+devel r22058, when opening the 'Save > as...' dialog for the first time, it defaults to a path inside the > application bundle, Fix in SVN revision 22060 confirmed - on OS X Inkscape 22062 now opens the 'Save as...' dialog at first run in $HOME, like in previous versions (tested: r21924, r22028). thanks, ~suv On Wed, Aug 12, 2009 at 7:26 AM, ~suv<suv-sf@...>” > <> It should warn you in batch export if the target path does not exist. But otherwise this is the expected behavior. I want to be able to mass-export from one master SVG to many PNGs in different dirs, and I want it to remember those dirs per object. I propose to rename this to "Batch export should be more explicit about where it exports stuff". > Bug #170966 in Inkscape: “move export hints from SVG files to prefs” > <> > Bug #168958 in Inkscape: “Privacy concern with export-filename and > sodipodi:absref” > <> The point of export hints is that they are stored per-object. Storing the IDs and export data for all exported objects in all documents in prefs does not sound too elegant and will be hard to keep up to date - any deletion of an object and any ID change will have to go to prefs and update that data so it stays in sync. I don't know if it makes sense to implement all this. Once again: I agree to add a preference option to save export hints (on by default), and/or a command to remove all hints if you want to share your file. But otherwise, the current system is simple, straightforward, and saves a lot of time in real work. -- bulia byak Inkscape. Draw Freely. Thank you for your tip, I didn't know that you could do a debug session with only one file's symbols. To coming back to my question (by-passing libinkscape.a creation) there is a log file here (1.4 Mo) of the building: I think that it's more a MinGW or Code::Blocks limitation because the returned error is a non sense: mingw32-g++.exe: C:\devlibs\li: No such file or directory By surfing, I discovered that ar.exe is an archiver and ".a" just an archive file that can be extracted with a built-in index when ranlib is executed : But even when by using some arguments like: q[f] - quick append file(s) to the archive r[ab][f][u] - replace existing or insert new file(s) into the archive it just create an new file, copy all data from the original, do its stuff and then deleting the old archive, It takes about the same time... I though that it will just update the current archive. Hello all Currently we have some handling for hrefs (in the form of Inkscape::URIReference). It provides some signals and callbacks, but doesn't do everything that I would like it to. To be specific, there are several places when solving the following problems efficiently would be a great thing: 1. Given an object, iterate over all references to it. 2. Given an object, iterate over all objects it refers to. Point 1 is useful for all sorts of things: marking objects for update, compensating clones, deletion, vacuum defs, etc. Point 2 would allow to remove 80% of clipboard code, and implement robust ID changing and clash prevention (which means, one that doesn't have to be updated whenever a new href-like attribute is added). Here is my idea. We define a three-way smartpointer that looks like this: class ObjectRefBase { ... SPObject *obj; ObjectRefBase *next; ObjectRefBase *next_ref; }; template <typename T> class ObjectRef : public ObjectRefBase { ... }; template <typename T> ObjectRef<T> const &getRef(T *obj) { return static_cast<ObjectRef<T> const &>(*obj); } The 'next' and 'next_ref' pointers form a singly-linked cyclic lists. Each SPObject contains such a smartpointer (by protected inheritance: 'class SPObject: protected ObjectRefBase, ... {') that can be accessed using the getRef function, which is a templated friend of SPObject and returns an ObjectRef of correct type. The header of both lists is the pointer contained in the referenced object; it has 'obj' set to itself. 'next' allows us to iterate over references to this object, while 'next_ref' - over references contained in this object. The constructor might look like this: ObjectRefBase(SPObject *owner) { if (owner == this) { obj = this; next = this; next_ref = this; } else { next_ref = owner->next_ref; owner->next_ref = this; obj = NULL; next = NULL; } } If this is the embedded instance from protected inheritance, the the first test will be true and both lists will be initialized as empty (an empty cyclic list is represented by the header node having a next pointer pointing to itself). The assignment operator is as follows: ObjectRefBase &operator=(ObjectRefBase const &other) { if (obj != NULL) { ObjectRefBase *cur = this; while (cur->next != this) cur = cur->next; cur->next = obj->next; } next = other.next; other.next = this; } If the reference pointed to some object, the function walks the list and removes the reference from the linked list of the previous object; it then inserts itself into the linked list of the new object. The destructor works similarly: ~ObjectRefBase() { ObjectRefBase *cur = this; while (cur->next != this) cur = cur->next; cur->next = obj->next; cur = next_ref; while (cur->next_ref != this) cur = cur->next_ref; cur->next_ref = next_ref; } Now we can iterate over the references to an object like this: for (ObjectRefBase *cur = this->next; cur != this; cur = cur->next) { // do something with each reference to this object } And over references contained in an object like this: for (ObjectRefBase *cur = this->next_ref; cur != this; cur = cur->next_ref) { // do something with each reference stored in this object } Testing whether the object has any indirect references is dead simple: this == next. Same for checking whether this object refers to anything: this == next_ref. The owner of a reference can be retrieved in linear time (by walking next_ref until we encounter next_ref == obj). All this of course can be encapsulated into a nice STL-like iterator interface which provides some extra type safety not present in ObjectRefBase (for example, we know that all ObjectRefs which we can reach via 'next' point to the same type). Handling CSS properties with URI references that are not members of the object is easy as well: ObjectRef doesn't need to be a member of the owner for all this to work. There are no boilerplate attach() / release() methods: the assignment operator of ObjectRef takes care of everything. If walking the lists during reassignment and destruction turns out to be a performance problem, we can make both lists doubly-linked rather than singly-linked, where a node can be removed in constant time, at the price of 2 more pointers stored in each reference. Fast owner retrieval additionally requires storing the owner pointer. This gives 5 pointers of overhead, so for 10000 references on a 64-bit machine we get 390KB of overhead - should be manageable. I thought about a trick that can be used to implement constant-time erase on a cyclic single list (the iterator actually points one node before and we use cur->next->value to get the value), but it can't be applied here. Why this is better than keeping pointers to the references in std::list or std::vector? - no memory allocations when adding a reference = better performance. - removing a reference is much simpler, because finding it in the list is not needed. - signals can be put in the ObjectRef class. - simple and elegant implementation. What do you think? Improvements and discussion welcome. Regards, Krzysztof -- View this message in context: Sent from the Inkscape - Dev mailing list archive at Nabble.com. ~suv-2 wrote: > > Do I have to manually clean the Build/share directories when updating > from SVN, or is there a make target that specifically does this instead > of the overall 'make clean'? > Yes. Automake doesn't handle disappearing files well (or in fact at all). By the way, that's one of the reasons there is no way to partially rebuild a Debian package after you make some changes - you either build it from scratch or not at all. > On a side note - the build date (shown in the about screen) also doesn't > update with every make/install/package cycle - though the revision > number is always correct. > That's because currently it's only updated when aboutbox.cpp is rebuilt. You can say 'touch src/ui/dialog/aboutbox.cpp' to update it. The correct solution involves dynamically creating an compiling an additional .cpp file that contains the current date on every 'make'. Bonus points for translating it at runtime. I'll look into this some time after GSoC. Regards, Krzysztof -- View this message in context: Sent from the Inkscape - Dev mailing list archive at Nabble.com. When updating Inkscape to the most recent SVN revision I use: | svn update | make | make install and then build the application bundle for macosx. When files are removed from trunk/share, like recently some extensions (in rev. 22049), those files still exist in 'Build/share/inkscape/extensions' and are not removed when I do 'make' and 'make install' after 'svn update'. Do I have to manually clean the Build/share directories when updating from SVN, or is there a make target that specifically does this instead of the overall 'make clean'? The issue has come up before with packages for win32 which included long gone extension files. On a side note - the build date (shown in the about screen) also doesn't update with every make/install/package cycle - though the revision number is always correct. tia, ~suv On 9/8/09 16:29, Maximilian Albert wrote: > Since my changes already partly achieved this I went ahead and dumped > inkscape:output_extension completely from the code base in rev. 22033, > where I also committed the other fixes to the behaviour of "Save as > ..."/"Save a copy ..." (so that now the various types of save dialogs > should remember their file extensions and paths completely > independently of each other). It turned out that a good deal of code > could be simplified in the process. Although the changes to the code > base are not huge, they are non-neglegible, so I'd like everyone to > test this thoroughly and report any problems. In particular, please > test with all combinations of "Save as ...", "Save as copy ...", > "Export bitmap" and various file types, different folders, several > documents opened at once, etc. (I did a lot of tests myself but I may > have missed some cases). If you are very nitpicky, you can double > check that the saved files are actually of the types indicated by > their file extensions. Feedback like "works fine for me" is also > acknowledged. :-) If people feel uneasy with such a change at this > point I'm also fine with holding it off until after 0.47, although I > believe it could be a major improvement to this release (and it's been > a long-requested fix, too). On OS X 10.5.8 using Inkscape 046+devel r22058, when opening the 'Save as...' dialog for the first time, it defaults to a path inside the application bundle, which is a big 'no-no' place to ever write files created by the user. A related but different problem is when Inkscape sometimes dumps tmp files or 'inkscape_pasted_image_*.png' inside the bundle and never cleans up (see bug #389262 comment 2). > Moreover, the folder is also stored on a per-save-basis, which might > be confusing if you are working with two documents simultaneously each > of which you want to successively "save as ..." in different folders > (because the dialog always presents you with the folder of the last > saved file). Should there be an option somewhere to always choose the > current folder and only remember the last used file extension or is > this overkill because such a workflow is unlikely? Once the user saved a file to a certain location, it is used as default when calling 'Save as...' again. Works for me, but for those who adapted their work flow to the old way? Big change. I think adding an option to always default to the current working directory makes sense. ~suv On Wednesday 12 August 2009 02:15:06 am Krzysztof Kosiński wrote: > I hope you'll tolerate my rather long explanation. If you'd rather get the > fix right away, skip the next paragraph :) > Thank you for having the time to write the exhaustive explanation. > Now the actual solution. You need to put this somewhere in > sp_connector_context_init: > > new (&cc->connpthandles) std::map<SPKnot* , ConnectionPoint>(); > > and this in sp_connector_context_dispose: > > cc->connpthandles.~std::map<SPKnot* , ConnectionPoint>(); > Yes, this solved my problem. Thank you again. Regards, Arcadie On 9/8/09 16:29, Maximilian Albert wrote: > In particular, please test with all combinations of "Save as ...", > "Save as copy ...", "Export bitmap" and various file types, different > folders, several documents opened at once, etc. (I did a lot of tests > myself but I may have missed some” <> Could you have a look at it? What is the status of this attribute? Is it going to be removed as well as discussed in these reports: Bug #170966 in Inkscape: “move export hints from SVG files to prefs” <> Bug #168958 in Inkscape: “Privacy concern with export-filename and sodipodi:absref” <> ~suv Hey Mentors, As you are probably aware the "soft" pencil's down date for the students was yesterday. The more firm date being next Monday, the 17th. They will technically have up until the 24th to get the finishing touches on things as far as grading is concerned. Please talk to your respective students to ensure that you can provide the best mentoring possible for the time they have left and to see what the community can do, if anything, to help them succeed. CCing the devel-list so people know that we're near the end. Cheers, Josh P.S. To the list members... the projects will get merged in when we get 0.47 out the door... so if you're itching for the new features, look at this as a booster shot to help make 0.47 happen that much sooner. ;) ~suv-2 wrote: > > I did not investigate further before posting here - can't you just > revert to an older revision? Are there different access privileges > needed or could I have done it myself (with a normal user account)? > In principle any user can revert to an older rev - just navigate to it, click edit and then save. Why it didn't work in this specific case, I don't know, but maybe the server is dropping requests larger than X bytes. Another thing is that I'm on GPRS at the moment, and might have hit some timeout. Regards, Krzysztof -- View this message in context: Sent from the Inkscape - Dev mailing list archive at Nabble.com. bulia byak wrote: > > What is "real"? Why d= is real but original-d= is not? I think it's > pure terminology issue. The code is the same. > The svg:path that represents the LPE is both a representation of the result of the LPE, and the original path. By a "real object" I roughly mean an object that can be legitimately put in a href. The original-d attribute cannot, so it is not a "real object" in some sense. > No, our href management is adequate for clones. We have all necessary > signals and callbacks. I was referring to the code that compensates > transforms of clones so that they behave logically from the user > viewpoint when the original is transformed. > This code might be useful rather than getting in the way. If create a 'linked' effect usng a clone of some object, I would expect the clone used as the parameter not to move according to the rules for clones. If the behavior is consistent between clones and 'linked' parameters of LPEs, it's a good thing. Moreover the svg:use parameters of LPEs would be created from clones, so it's natural to expect them to behave like clones. As an example, consider linked offset: its behavior is really weird to me, because it does not behave the same way a clone would. As for href management: good href management would allow us to transform clones during dragging (right now they are only transformed when the original's transform finishes - not good) and do other interesting things. > Once again: our code has hundreds of tree traversals. They all work > the same for groups and layers, but they often have to special-case > flowtext because it is special and has special rules. > This shouldn't be more complicated than 'if (SP_IS_VECTOR_EFFECT(item)) continue;', or not adding the children of the effect to SPObject 'children' attribute and instead providing access to them using a different function - if it's more involved then it highlights a larger problem. > Once you add a non-SVG container element, you have to define a lot of > semantics for it: how style is inherited to/from it, how transforms > are handled below it, etc. etc. This is all worked out for svg:g and > is used, often implicitly, in many many places. So this will be a > mess. Now that I think some more about it, I think we should make this > a hard rule: no non-SVG container elements for SVG elements. If you > need a container, subclass svg:g as we did for layers. > A non-SVG element can act exactly like a group, if its SP node is derived from SPGroup. If svg:g can act as the 'generic case' of handling transforms, styles, etc. for container elements, then I don't understand why we cannot have SVG elements in non-SVG ones. >> Are you trying to say that if I put a standard SVG element inside an >> Inkscape-specific element, then an SVG-conforming parser will try to >> render >> the inner SVG element? > > It might. No guarantees here. > I believe there is actually a hard guarantee. The only instance where this might happen that I imagine is when an implementation tries to be actively non-conformant, and descends into unknown elements. Descending into an element is not ignoring it, and implementations are required to ignore unknown elements, therefore SVG implementations are required not to display SVG elements that might reside inside unknown elements. Ultimately, it would be most productive to conduct some tests with actual SVG implementations. The 'move path to defs and make a href' approach is not affected by this issue. > The only guarantee is svg:switch, which > you also have at the upper layer, but it looks wrong below it. Even if > it works fine :) For example, by thus hiding SVG inside non-SVG, you > are also hiding it from SVG validators. > SVG validation is a special case of XML validation. If the XML validator has DTDs for all namespaces in the document, then it should be able to validate even the elements inside non-SVG elements, provided that they have DTDs that specify that SVG elements can be present there. > The point of Inkscape::Selection is the signals it emits. Do you need > those signals? I think not, in which case any GSList or other > container would work just as fine. > I need the equivalent of selection_changed to know when to create or destroy manipulators :) > You won't be able to select > the pattern by Ctrl+click because it is invisible by itself. The only > way to select inside such a "group" would be by using some list or > tree in the dialog. But so you can do with the current system, too. > What's the advantage? > I assume that we're talking about the second idea (change original-d into a href to a path in defs). I would be able to use the selection_changed callback of Inkscape::Selection to create or destroy the manipulators for all path parameters, including the source path. Otherwise I'd have two options: a) use some kind of sub-object selection, so that the user can select whether he wants to edit the LPE itself, the source path, or both b) always show the source path manipulator when the LPE is selected With option b) it wouldn't be possible to only show the knots of the LPE, or only the source path; with complex LPEs or source paths this might be a problem. Regards, Krzysztof --
https://sourceforge.net/p/inkscape/mailman/inkscape-devel/?viewmonth=200908&viewday=12
CC-MAIN-2017-17
en
refinedweb
0 Ive been sitting in 3 hours trying to figure out whats wrong, read in my book, seen the Powerpoint and google search and now im giving up.. This is my last resort and I hope to learn how to do it.. Would appriciate the help guys. Well, here i post my (what I have so far): // *************************************************************** // Salary.java // // Computes the amount of a raise and the new // salary for an employee. The current salary // and a performance rating (a String: "Excellent", // "Good" or "Poor") are input. // *************************************************************** import java.util.Scanner; import java.text.NumberFormat; public class Salary { public static void main (String[] args) { double currentSalary; // employee's current salary double raise; // amount of the raise double newSalary; // new salary for the employee String rating; // performance rating Scanner scan = new Scanner(System.in); System.out.print ("Enter the current salary: "); currentSalary = scan.nextDouble(); System.out.print ("Enter the performance rating (Excellent, Good, or Poor): "); rating = scan.next(); // Compute the raise using if ... // Comparation of String is a little different than int. We use a // String method equals as follow: //HERE i have problem, I think this is the only //Thing thats left to fix.. if (rating.equalsIgnoreCase("Exellent")) { raise = 0.06 } if (rating.equalsIgnoreCase("Good")) { raise = 0.04 } if (rating.equalsIgnoreCase("Poor")) { raise = 0.015 } newSalary = currentSalary + raise; // Print the results NumberFormat money = NumberFormat.getCurrencyInstance(); System.out.println(); System.out.println("Current Salary: " + money.format(currentSalary)); System.out.println("Amount of your raise: " + money.format(raise)); System.out.println("Your new salary: " + money.format(newSalary)); System.out.println(); } } Thx
https://www.daniweb.com/programming/software-development/threads/259620/problem-with-if
CC-MAIN-2017-17
en
refinedweb
Life after AngularJS - Dependency Injection. Our options are very limited as JavaScript does not natively support dependency injection. I have been using Vue.js with TypeScript recently for which there is no dependency injection support. The only way to support both runtime module loading and dependency injection for unit testing is to implement “poor man’s dependency injection”. Poor man’s dependency injection does not use an inversion of control (IoC) container or dependency injection framework to create dependencies that can be provided to a class. It works by a class having knowledge about how to create an instance of a dependency as required. This means that we cannot avoid a coupling between components but we can still satisfy our runtime and testing needs. The way this works is by providing a dependency as a constructor parameter to a class. This supports unit testing where the unit test can provide a stub/mock to the constructor to test the methods of the class. The constructor can then create an instance of its dependency (therefore coupling) if no value has been provided to the constructor. This supports the runtime implementation where the application will create an instance of this class without knowledge of its dependencies. For example: import Plan from "./Plan"; import { Http, IHttp } from "../../services/http"; export interface IPricesService { loadPlans(): Promise<Array<Plan>>; } export class PricesService implements IPricesService { public constructor(private http: IHttp = new Http()) { } public loadPlans(): Promise<Array<Plan>> { return this.http.get<Array<Plan>>("plans"); } }; We can now test this class by providing the Http parameter to the constructor. import { PricesService } from "./pricesService"; import { IHttp } from "../../services/http"; import Plan from "./plan"; const core = require("../../tests/core"); describe("prices.service.ts", () => { let sut: PricesService; let plans: Array<Plan>; let http: IHttp = <IHttp>{ get: async () => { return plans; }, post: () => { return null; } }; beforeEach(function () { sut = new PricesService(http); plans = [<Plan>{name: "Test"}]; }); describe("loadPlans", () => { it("should return plans from http", core.runAsync(async () => { spyOn(http, "get").and.callThrough(); let actual = await sut.loadPlans(); expect(actual).toEqual(plans); expect(http.get).toHaveBeenCalledWith("plans"); })); }); });
http://www.neovolve.com/2017/02/23/life-after-angularjs-dependency-injection/
CC-MAIN-2017-17
en
refinedweb
#include <DivergenceStencil.H> The data holders sent in can be dummies but they must be the right size. disallowed operators. Without code because Jeff says that is better. weak construction is bad. no reason to allow this one either. Take the divergence of the incoming fluxes deep copy for this object would kill performance
http://davis.lbl.gov/Manuals/CHOMBO-RELEASE-3.2/classDivergenceStencil.html
CC-MAIN-2017-17
en
refinedweb
cgiDebug - Set the debug level for CGI programming #include <cgi.h> void cgiDebug (int level, int where); This routine controls debugging for the cgi library. At the moment only level 0 (default, no debugging) and 1 (debugging enabled) are supported. The second argument where specifies if debug output should be written to stdout using HTML (1), to stderr as plain text (0, default), or to syslog (2). This shoud be the first one called from the CGI library. cgiDebug() does not return a value. This CGi library is written by Martin Schulze <joey@infodrom.org>. If you have additions or improvements please get in touch with him. cgiInit(3), cgiHeader(3), cgiGetValue(3).
http://huge-man-linux.net/man3/cgiDebug.html
CC-MAIN-2017-17
en
refinedweb
icetDataReplicationGroupColor -- define data replication. #include <GL/ice-t.h> void icetDataReplicationGroupColor( GLint color );.. None.. This man page should never be installed. It should just be used to help make other man pages.(3), icetDrawFunc(3), icetBoundingVertices(3), icetBoundingBox(3) IceT Reference April 20, 2006icetDataReplicationGroupColor(3)
http://huge-man-linux.net/man3/icetDataReplicationGroupColor.html
CC-MAIN-2017-17
en
refinedweb
One day I was writing some code and had the need to work with the Windows registry. I was so happy that I was coding in .NET using C#. "How I love the framework", I was saying to myself. Then all of the sudden, I found that a critical method was missing. I found that I could not simply call a method in the framework to rename a registry key. To my further amazement, I was surprised that I could not find a code snippet to help do this. I saw a challenge and I was on a mission. So that is the story of why I wrote this code. There is not much code to this at all. In fact there is more code in the test form that demonstrates the utility. Basically what you will find is a solution that contains a form and a class file written in C#. The form has code that sets up and runs the test. The utility code that does the registry key renaming is in a class file named RegistryUtilities.cs. The utility contains two public methods: public CopyKey RenameSubKey The process of renaming a registry key is actually a recursive copy of all the values and sub keys and then a delete of the original key. So when you call RenameSubKey, it actually calls CopyKey. The real work is done in the private method: RecurseCopyKey. RenameSubKey private RecurseCopyKey RecurseCopyKey is responsible for copying all the values and sub keys to a new sub key. The new sub key is placed at the same level in the tree as the one being copied. RecurseCopyKey Blah, blah, blah… You'll probably get more from seeing the code than from reading anything more I could write here. There is a demo available for download. If you run the demo, it creates a new registry key under local user and then renames it. Here is a copy of the entire RegistryUtilities.cs file: using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; // RenameRegistryKey © Copyright 2006 Active Computing namespace RenameRegistryKey { public class RegistryUtilities { /// <summary> /// Renames a subkey of the passed in registry key since /// the Framework totally forgot to include such a handy feature. /// </summary> /// <param name="regKey">The RegistryKey that contains the subkey /// you want to rename (must be writeable)</param> /// <param name="subKeyName">The name of the subkey that you want to rename /// </param> /// <param name="newSubKeyName">The new name of the RegistryKey</param> /// <returns>True if succeeds</returns> public bool RenameSubKey(RegistryKey parentKey, string subKeyName, string newSubKeyName) { CopyKey(parentKey, subKeyName, newSubKeyName); parentKey.DeleteSubKeyTree(subKeyName); return true; } /// <summary> /// Copy a registry key. The parentKey must be writeable. /// </summary> /// <param name="parentKey"></param> /// <param name="keyNameToCopy"></param> /// <param name="newKeyName"></param> /// <returns></returns> public bool CopyKey(RegistryKey parentKey, string keyNameToCopy, string newKeyName) { //Create new key RegistryKey destinationKey = parentKey.CreateSubKey(newKeyName); //Open the sourceKey we are copying from RegistryKey sourceKey = parentKey.OpenSubKey(keyNameToCopy); RecurseCopyKey(sourceKey, destinationKey); return true; } private void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey) { //copy all the values foreach (string valueName in sourceKey.GetValueNames()) { object objValue = sourceKey.GetValue(valueName); RegistryValueKind valKind = sourceKey.GetValueKind(valueName); destinationKey.SetValue(valueName, objValue, valKind); } //For Each subKey //Create a new subKey in destinationKey //Call myself foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames()) { RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName); RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName); RecurseCopyKey(sourceSubKey, destSubKey); } } } } I hope this is useful.
http://www.codeproject.com/Articles/16343/Copy-and-Rename-Registry-Keys?fid=357384&df=90&mpp=25&sort=Position&spc=Relaxed&tid=2487930
CC-MAIN-2014-35
en
refinedweb
WCF Load Balancing : An End To End Example For NetTcpBinding Recently, I worked on prototyping WCF load balancing for our product, FirstPoint. I built a simple example to test the configuration and behavior of load balancing. Since there aren't many end-to-end examples of WCF load balancing on the web, I'm hoping this will be useful (since the Microsoft documentation on this is basically non-existent...well, for NetTcpBindings at least). I will assume that you are already familiar with network load balancing and configuring the NLB on Windows Server 2003. Here's a screenshot of how I've configured my network load balancer: You'll notice that I've configured a specific port range for my service. Also, take note of the cluster address: 192.168.1.220. The two servers that make up the cluster are FPDEV1 (192.168.1.222) and FPDEV2 (192.168.1.223). I've defined a simple service interface which simply echoes the message with a server name: using System.ServiceModel; namespace WcfLoadBalancingSample.Server.Contracts { /// <summary> /// A simple service contract definition which defines an echo operation. /// </summary> [ServiceContract(SessionMode = SessionMode.Allowed)] public interface IEchoService { /// <summary> /// Echoes the specified message. /// </summary> /// <param name="message">The message.</param> /// <returns>The input message with a server identifier attached.</returns> [OperationContract] string Echo(string message); } } And here is the implementation: using System; using WcfLoadBalancingSample.Server.Contracts; namespace WcfLoadBalancingSample.Server.Services { /// <summary> /// Implements the <c>IEchoService</c>. /// </summary> public class EchoService : IEchoService { #region IEchoService Members /// <summary> /// Echoes the specified message. /// </summary> /// <param name="message">The message.</param> /// <returns> /// The input message with a server identifier attached. /// </returns> public string Echo(string message) { return string.Format("[{0}] {1}", Environment.MachineName, message); } #endregion } } As you can see, I've simply prepended the machine name to each response so that we can track which server we are connecting to. Here is the main program which hosts the service: using System; using System.ServiceModel; using WcfLoadBalancingSample.Server.Services; namespace WcfLoadBalancingSample.Server { internal class Program { private static void Main(string[] args) { var program = new Program(); program.Run(); } public void Run() { ServiceHost serviceHost = null; try { serviceHost = new ServiceHost(typeof (EchoService)); serviceHost.Open(); Console.Out.WriteLine("Service ready."); Console.Out.WriteLine("Press any key to terminate."); Console.Out.WriteLine("============================"); Console.ReadKey(); } catch (Exception exception) { Console.Out.WriteLine(exception); Console.ReadKey(); } finally { if (serviceHost != null) { serviceHost.Abort(); } } } } } This should be deployed on your each of your two (or more) servers in your cluster. The magic comes next in the configuration file: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="WcfLoadBalancingSample.Server.Services.EchoService" behaviorConfiguration="WcfLoadBalancingSample.Server.Services.EchoServiceBehavior"> <!-- Service Endpoints --> <!--/// The configured endpoint address is the IP address of the load balanced cluster. The port number has been mapped to the cluster. ///--> <endpoint address ="net.tcp://192.168.1.220:12345/lb/EchoService" binding="customBinding" bindingConfiguration="DefaultCustomBinding" contract="WcfLoadBalancingSample.Server.Contracts.IEchoService"> </endpoint> </service> </services> <bindings> <!--/// A simple custom binding. Note the leaseTimeout setting. This is referenced in the SDK documentation, but not described in any way as to how you're supposed to configure it. ///--> <customBinding> <binding name="DefaultCustomBinding"> <windowsStreamSecurity protectionLevel="None"/> <binaryMessageEncoding/> <tcpTransport> <connectionPoolSettings leaseTimeout="00:00:01"/> </tcpTransport> </binding> </customBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="WcfLoadBalancingSample.Server.Services.EchoServiceBehavior"> <serviceMetadata httpGetEnabled="True" httpGetUrl=""/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> The most important part of this configuration file is the setting for the lease timeout. The SDK documentation references this setting, but does not go into detail on how it's configured. Note that it seems that you can only set the least timeout value in configuration using a custom binding. There is one particularly important thing to note here: I've set the timeout to 1 second for demonstration purposes only. The SDK documentation mentions that this value should be set to 30 seconds. As we'll see later, I have the client creating a new connection every 2.5 seconds (on purpose so we can test connectivity). What I found was that with the default setting (5 minutes, according to the SDK), if you initially connect to server A and server A goes down, it will not automatically connect to server B. I assume this is because of the lease timeout value (it throws an exception). Also note that the endpoint is configured using the IP address of the node balancing cluster and not the individual servers. The client side of it is pretty straight forward as well: using System; using System.Runtime.Remoting.Messaging; using System.Threading; using WcfLoadBalancingSample.Client.LoadBalancedService; namespace WcfLoadBalancingSample.Client { public delegate void EchoDelegate(); public class EchoEventArgs : EventArgs { public EchoEventArgs(string message) { Message = message; } public string Message { get; set; } } internal class Program { private static void Main(string[] args) { var program = new Program(); program.Run(); } public void Run() { // Start the server. Console.Out.WriteLine("Starting client...(press any key to exit)"); // Start second thread to ping the server. EchoDelegate echoDelegate = EchoAsync; echoDelegate.BeginInvoke(EchoAsycCompleted, null); Console.Read(); } /// <summary> /// Asynchronous execution of the call to the server. /// </summary> private void EchoAsync() { try { int count = 0; while (true) { using (var serviceClient = new EchoServiceClient()) { // Call the echo service. string result = serviceClient.Echo( count.ToString()); Console.Out.WriteLine(result); count++; } Thread.Sleep(2500); } } catch (Exception exception) { Console.Out.WriteLine(exception); } } /// <summary> /// Handles the completion of the thread. /// </summary> /// <param name="result">The result.</param> private void EchoAsycCompleted(IAsyncResult result) { var r = (AsyncResult) result; var e = (EchoDelegate) r.AsyncDelegate; e.EndInvoke(r); } } } The only thing to note is that I used a delegate to spin off a second thread to make the call to the server. Adding a reference to the server generates the following configuration file: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <bindings> <netTcpBinding> <binding name="CustomBinding_IEchoService"> <security mode="Transport"> <transport clientCredentialType="Windows" protectionLevel="None" /> <message clientCredentialType="Windows" /> </security> </binding> </netTcpBinding> </bindings> <client> <endpoint address="net.tcp://192.168.1.220:12345/lb/EchoService" binding="netTcpBinding" bindingConfiguration="CustomBinding_IEchoService" contract="LoadBalancedService.IEchoService" name="CustomBinding_IEchoService"> <identity> <userPrincipalName value="Administrator@fpdev.com" /> <servicePrincipalName value="" /> <dns value="192.168.1.220" /> </identity> </endpoint> </client> </system.serviceModel> </configuration> Note that on this side, the binding is generated as a netTcpBinding. And that's it! Deploy the service to your clustered servers and start the services and then start the client. If your cluster has a bias towards one server, you will see that the messages will come from that server. To test that it actually is load balancing, simply stop the service on that server and you should see that the output will be coming from the other server. Here's an example: You can see that after I stop the service on FPDEV1 at the third echo message, it flips over to FPDEV2! Awesome! Here's the full project (VS2008): WcfLoadBalancingSample.zip (16.89 KB) Trackbacks are disabled. April 24th, 2009 - 23:37 I’m looking into load balancing on nettcpbinding, so this article helps, but I have a question. Let say the lease timeout is 10 seconds, and in those 10 seconds 10.000 customers come in, won’t they all go to the same server? If so, then how is that load balancing? Maybe I’m misunderstanding this. April 24th, 2009 - 23:56 Ingi, Your request is intercepted by the load balancer first. The issue with the lease timeout is that it creates a server "bias". The load balancer will redirect the new incoming requests to the server with the least load. - Chuck September 4th, 2009 - 00:33 Thanks for the example – but I have with the same configuration but I have to use HTTP. Problems? Also, as in IIS with SessionState that can be stored to a SQL server, does it work the same for WCF. Can you have perSession, and the associated state, stored to a SQL server? Or am I missing something – as the client would recreate the proxies when the web page returns.
http://charliedigital.com/2009/04/17/wcf-load-balancing-an-end-to-end-example-for-nettcpbinding/
CC-MAIN-2014-35
en
refinedweb
{-# LANGUAGE OverloadedStrings #-} {- | Module : GHC.Vis.Graph Copyright : (c) Dennis Felsing License : 3-Clause BSD-style Maintainer : dennis@felsin9.de -} module GHC.Vis.Graph ( xDotParse ) where import System.IO.Unsafe import Data.Text.IO import qualified Data.Text.Lazy as B import Data.Graph.Inductive hiding (nodes, edges) import Data.GraphViz hiding (Ellipse, Polygon, parse) import qualified Data.GraphViz.Types.Generalised as G import Data.GraphViz.Attributes.Complete import GHC.HeapView hiding (name) import GHC.Vis.Internal import GHC.Vis.Types import Graphics.XDot.Types hiding (name, h) import Graphics.XDot.Parser fontName :: B.Text --fontName = "Times Roman" fontName = "DejaVu Sans" graphFontSize :: Double graphFontSize = 24 nodeFontSize :: Double nodeFontSize = 24 edgeFontSize :: Double edgeFontSize = 24 -- | Take the objects to be visualized and run them through @dot@ and extract -- the drawing operations that have to be exectued to show the graph of the -- heap map. xDotParse :: [(Box, String)] -> IO ([(Maybe Node, Operation)], [Box], Rectangle) xDotParse as = do (dotGraph, boxes) <- dg as return (getOperations dotGraph, boxes, getSize dotGraph) dg :: [(Box, String)] -> IO (G.DotGraph Node, [Box]) dg as = do hm <- walkHeap as --hm <- walkHeapDepth as xDotText <- graphvizWithHandle Dot (defaultVis $ toViewableGraph $ buildGraph hm) XDot hGetContents return (parseDotGraph $ B.fromChunks [xDotText], getBoxes hm) -- | Convert a heap map, our internal data structure, to a graph that can be -- converted to a dot graph. buildGraph :: HeapMap -> Gr Closure String buildGraph hm = insEdges edges $ insNodes nodes empty where nodes = zip [0..] $ map (\(_,(_,c)) -> c) rhm edges = foldr toLEdge [] $ foldr mbEdges [] nodes -- Reversing it fixes the ordering of nodes in the graph. Should run -- through allPtrs and sort by order inside of all allPtrs lists. -- -- When building the graph directly out of [Box] instead of going -- through the HeapMap, then the order of nodes might not be right for -- non-trivial graphs. -- -- In some cases it's impossible to get the order right. Maybe there is -- a way in graphviz to specify outgoing edge orientation after all? rhm = reverse hm toLEdge (0, Just t) xs = case rhm !! t of (_,(Just name, _)) -> (0,t,name):xs (_,(Nothing, _)) -> (0,t,""):xs toLEdge (f, Just t) xs = (f,t,""):xs toLEdge _ xs = xs mbEdges (p,BCOClosure _ _ _ bPtr _ _ _) xs = map (\b -> (p, Just b)) (bcoChildren [bPtr] hm) ++ xs -- Using allPtrs and then filtering the closures not available in the -- heap map out emulates pointersToFollow without being in IO mbEdges (p,c) xs = map (\b -> (p, boxPos b)) (allPtrs c) ++ xs boxPos :: Box -> Maybe Int boxPos b = lookup b $ zip (map fst rhm) [0..] bcoChildren :: [Box] -> HeapMap -> [Int] bcoChildren [] _ = [] bcoChildren (b:bs) h = case boxPos b of Nothing -> let ptf = unsafePerformIO $ getBoxedClosureData b >>= pointersToFollow2 in bcoChildren (ptf ++ bs) h -- Could go into infinite loop Just pos -> pos : bcoChildren bs h getBoxes :: HeapMap -> [Box] getBoxes hm = map (\(b,(_,_)) -> b) $ reverse hm -- Probably have to do some kind of fold over the graph to remove for example -- unwanted pointers toViewableGraph :: Gr Closure String -> Gr String String toViewableGraph cg = emap id $ nmap showClosure cg defaultVis :: (Graph gr) => gr String String -> DotGraph Node defaultVis = graphToDot nonClusteredParams -- Somehow (X11Color Transparency) is white, use (RGBA 0 0 0 0) instead { globalAttributes = [GraphAttrs [BgColor [RGBA 0 0 0 0], FontName fontName, FontSize graphFontSize]] , fmtNode = \ (_,l) -> [toLabel l, FontName fontName, FontSize nodeFontSize] , fmtEdge = \ (_,_,l) -> [toLabel l, FontName fontName, FontSize edgeFontSize] }
http://hackage.haskell.org/package/ghc-vis-0.2/docs/src/GHC-Vis-Graph.html
CC-MAIN-2014-35
en
refinedweb
SpeechRecognizer.SpeechHypothesized Event Occurs when the recognizer has recognized a word or words that may be a component of multiple complete phrases in a grammar. Namespace: System.Speech.RecognitionNamespace: System.Speech.Recognition Assembly: System.Speech (in System.Speech.dll) The shared recognizer can raise this event when the input is ambiguous. For example, for a speech recognition grammar that supports recognition of either "new game please" or "new game", "new game please" is an unambiguous input, and "new game" is an ambiguous input. When you create a delegate for a SpeechHypothesized recognizes phrases such as "Display the list of artists in the jazz category". The example uses the SpeechHypothesized event to display incomplete phrase fragments in the console as they are recognized. using System; using System.Speech.Recognition; namespace SampleRecognition { class Program { static void Main(string[] args) // Initialize a shared speech recognition engine. { using (SpeechRecognizer recognizer = new SpeechRecognizer()) { // Create a grammar. // Create lists of alternative choices. Choices listTypes = new Choices(new string[] { "albums", "artists" }); Choices genres = new Choices(new string[] { "blues", "classical", "gospel", "jazz", "rock" }); // Create a GrammarBuilder object and assemble the grammar components. GrammarBuilder mediaMenu = new GrammarBuilder("Display the list of"); mediaMenu.Append(listTypes); mediaMenu.Append("in the"); mediaMenu.Append(genres); mediaMenu.Append("category."); // Build a Grammar object from the GrammarBuilder. Grammar mediaMenuGrammar = new Grammar(mediaMenu); mediaMenuGrammar.Name = "Media Chooser"; // Attach event handlers. recognizer.LoadGrammarCompleted += new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted); recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized); recognizer.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized); // Load the grammar object to the recognizer. recognizer.LoadGrammarAsync(mediaMenuGrammar); // Keep the console window open. Console.ReadLine(); } } // Handle the SpeechHypothesized event. static void recognizer_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e) { Console.WriteLine("Speech hypothesized: " + e.Result.Text); } //.
http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognizer.speechhypothesized.aspx
CC-MAIN-2014-35
en
refinedweb
Another tale from the ADF (10.1.3.2) project for the Interior Decorator chain of stores. When the sales representative is creating the decoration plan for a home or office building, he or she will typically discuss one room at a time with the customer. The decoration plan may contain several rooms and for each room the plan will have actions (wall papering, floor paneling, painting) and with each action there will be materials associated (paint, carpet, wood). The materials for an action are selected in a List of Values (with advanced search) window. The specific requirement is that this List of Values can easily be filtered to only display materials earlier selected in the plan – since frequently the same materials are used in multiple rooms. This article will discuss an approach to implementing that specific requirement – but in terms of Employees. Employees can be allocated on Projects. Projects are executed for Customers. When the user is allocating employees to a project, he or she should be able to restrict the list of employees to choose from to only those employees that have been allocated on projects for that same customer. Visually: We want to allocate employees on the The Omega Challenge project , that we will run for our customer Global Warming Inc. We bring up the List of Values window from which we can select one or multiple employees. The list initially shows 106 employees. However, we know the customer has a preference for staff that worked on previous projects we did together. An example of such a project for this customer: So the List of Values ideally should allow us to filter on exactly these employees. When we we switch the Radio Group "Only employees previously allocated on a project for this customer?" to Yes and press find, we will only see employees that have worked for Global Warming Inc. before (and also satisfy the other query conditions). The implementation of this functionality is done like this: - Model: add a bind parameter customerId to the EmployeesView that fuels to the List of Values; also modify the underlying where clause in the EmployeesView ViewObject: and ( :customerId is null <br /> or <br /> exists ( select 'x' <br /> from project_allocations pan<br /> , projects pjt <br /> where pjt.ctr_id = :customerId <br /> and pjt.id = pan.pjt_id <br /> and pan.emp_id = Employees.employee_id<br /> )<br /> )<br /> - ViewController: create a managed bean that holds the Customer Id value and a switch whether or not to filter by that customer id; add logic to the Project Administration page to set the managed bean’s Customer Id. In the LovEmployees page, add a radio group to allow filter on /off , add logic to the execute query Since I have used JHeadstart to generate this application, my life is a little bit more simple. The steps in the ViewController project are limited to: - Set the Query Bind Parameters property of the LovEmployees page to customerId=#{LovEmployeesFilterBean.ctrId} (meaning that whenever the LovEmployees ViewObject is queried, the value of the customerId bind parameter will be set to whatever value is read from the ctrId property on the LovEmployeesFilterBean. - Add an unbound item FilterOnCustomer to the LovEmployees Group; it is a Radio Group, based on the YesNoDomain. It is only displayed in the Advanced Search region After generating the application, we need some small post-generation changes (that we could also make part of custom templates in order to maintain the generatability of the application). These post-gen changes are: - change the value attribute of the SearchLovEmployeesFilterOnCustomer item in LovEmployeesTable.jspx to: value="#{LovEmployeesFilterBean.filterOnCtrId}" - add a setActionListener element to the ProjectAdministration.jspx page, as child of the selectInputText element EmpId that is used to invoke the List of Values window: <af:setActionListener<br /> - add a managed bean definition to the faces-config.xml file: <managed-bean><br /> <managed-bean-name>LovEmployeesFilterBean</managed-bean-name><br /> <managed-bean-class>nl.amis.hrm.view.LovEmployeesFilterBean</managed-bean-class><br /> <managed-bean-scope>session</managed-bean-scope><br /> </managed-bean><br /> With these post gen changes, the application will set the Customer Id on the LovEmployeesFilterBean whenever the LOV for Employees is brought up. Every query against LovEmployeesView will retrieve the Customer Id value from that bean and use it to inject the bind parameter. The SearchLovEmployeesFilterOnCustomer item will determine whether or not the LovEmployeesFilterBean returns the value of the Customer Id: package nl.amis.hrm.view;<br /><br />import oracle.jbo.domain.Number;<br /><br />public class LovEmployeesFilterBean {<br /><br /> private Number ctrId;<br /> private String filterOnCtrId = "N";<br /><br /> public LovEmployeesFilterBean() {<br /> }<br /><br /> public void setCtrId(Number ctrId) {<br /> this.ctrId = ctrId;<br /> }<br /><br /> public Number getCtrId() {<br /> if (isDoFilterOnCtrId())<br /> return ctrId;<br /> else<br /> return null;<br /> }<br /><br /> public void setFilterOnCtrId(String filterOnCtrId) {<br /> this.filterOnCtrId = filterOnCtrId;<br /> }<br /><br /> public boolean isDoFilterOnCtrId() {<br /> return "Y".equalsIgnoreCase(this.filterOnCtrId);<br /> }<br /><br /> public String getFilterOnCtrId() {<br /> return filterOnCtrId;<br /> }<br />}<br /> Resources Download the complete JDeveloper 10.1.3.2 Application: LovWithContextFilter.zip.
http://technology.amis.nl/2007/07/07/adf-context-specific-filter-in-list-of-values-only-list-employees-previously-allocated-on-other-project-for-this-customer/
CC-MAIN-2014-35
en
refinedweb
A Last Value Queue is configured with the name of a message header that is used as a key. The queue behaves as a normal FIFO queue with the exception that when a message is enqueued, any other message in the queue with the same value in the key header is removed and discarded. Thus, for any given key value, the queue holds only the most recent message. The following example illustrates the operation of a Last Value Queue. The example shows an empty queue with no consumers and a sequence of produced messages. The numbers represent the key for each message. <empty queue> 1 => 1 2 => 1 2 3 => 1 2 3 4 => 1 2 3 4 2 => 1 3 4 2 1 => 3 4 2 1 Note that the first four messages are enqueued normally in FIFO order. The fifth message has key '2' and is also enqueued on the tail of the queue. However the message already in the queue with the same key is discarded. If the set of keys used in the messages in a LVQ is constrained, the number of messages in the queue shall not exceed the number of distinct keys in use. LVQ with zero or one consuming subscriptions - In this case, if the consumer drops momentarily or is slower than the producer(s), it will only receive current information relative to the message keys. LVQ with zero or more browsing subscriptions - A browsing consumer can subscribe to the LVQ and get an immediate dump of all of the "current" messages and track updates thereafter. Any number of independent browsers can subscribe to the same LVQ with the same effect. Since messages are never consumed, they only disappear when replaced with a newer message with the same key or when their TTL expires. A LVQ may be created using directives in the API's address syntax. The important argument is "qpid.last_value_queue_key". The following Python example shows how a producer of stock price updates can create a LVQ to hold the latest stock prices for each ticker symbol. The message header used to hold the ticker symbol is called "ticker". conn = Connection(url) conn.open() sess = conn.session() tx = sess.sender("prices;{create:always, node:{type:queue, x-declare:{arguments:{'qpid.last_value_queue_key':'ticker'}}}}") from qpid.messaging import Connection, Message def send(sender, key, message): message.properties["ticker"] = key sender.send(message) conn = Connection("localhost") conn.open() sess = conn.session() tx = sess.sender("prices;{create:always, node:{type:queue,x-declare:{arguments:{'qpid.last_value_queue_key':ticker}}}}") msg = Message("Content") send(tx, "key1", msg); send(tx, "key2", msg); send(tx, "key3", msg); send(tx, "key4", msg); send(tx, "key2", msg); send(tx, "key1", msg); conn
http://qpid.apache.org/releases/qpid-0.24/cpp-broker/book/ch01s06.html
CC-MAIN-2014-35
en
refinedweb
qt No options to configure Number of commits found: 42 Retire QT2. QT3 was released a few years ago and QT4 will be released soon. Start the QT2 deorbit by marking all ports that depend non-optional on qt23 DEPRECATED Suggested by: eik SIZEify. Chase the new location of libXft. Add NO_LATEST_LINK Bump PORTREVISION on all ports that depend on gettext to aid with upgrading. (Part 1) No member of the kde@ team has touched anything related to Qt2 in ages, so stop pretending to maintain these ports. Define USE_PERL5_BUILD, not erroneous USE_PERL. Submitted by: Oliver Eikemeier Define USE_PERL to make Perl available for (mostly deprecated) "perl -pi -e" construction. Make WRKSRC overridable by slave-ports. Declare (or resolve) conflicts for KDE and QT. Remove pkg-comment from remaining master/slave port sets. Approved by: portmgr (implicitly) Protect targets with .if target(...) ... .endif for targets that are redefined in slave ports. Slave port maintainers need to check that they aren't actually relying on the master port target to be executed. Exorcise the ghost of objprelink, which was killed and buried with kde2. This should unbreak some things, like some errors from portsdb -Uu, as well as the port build itself. Remove USE_NEWGCC, which is no longer supported or required. Submitted by: Tilman Linneweh <tilman@arved.de> PR: ports/40571 Block installation if Qt3 is already installed to prevent people from clobbering the installations. Submitted by: lioux. Use correct -soname for qtgl shared library, so that libqtgl actually works. Previously libqtgl.so.4 was libked with soname of libqt2.so.4, so that when you link application with -lqtgl you are fine, but when you are trying to run resulting application it dies because libqt2 (which has no GL code) is dynamically linked instead. Not objected by: will fix Makefile, thanks to roam@ Fix OSVERSION, bad me. Pointed out by will. Add NO_QT_OBJPRELINK=yes, let -CURRENT installs smoothly. Remove -frerun-cse-after-loop, a vestige from the days when our compiler was slightly broken [1]. Use ${ECHO_CMD} instead of ${ECHO} where you mean the echo command; the ECHO macro is set to "echo" by default, but it is set to "true" if make(1) is invoked with the -s option while ECHO_CMD is always set to the echo command. Apply objprelink patch and use it only if MACHINE_ARCH=i386 *and* NO_QT_OBJPRELINK isn't defined. This was a little trickier than fixing the KDE stuff, but I think this will work ok. Enable to build this ports when you set MAKE_ENV on your shell environment. Preemptive note to keep people from asking me questions about AA support.. Bump png major Set DIST_SUBDIR=KDE Make MAINTAINER overridable for japanese/qt23. (I forgot to commit this along with other kde* ports) missing manpage. Remove -xft since it doesn't work with older X11. Now will people stop bothering me about putting that in, 'cause I'm not doing it again! Even if you do a patch that checks XFREE86_VERSION! Add one more MASTER_SITE. Update to 2.3.1. Support building QT with debugging turned, keyed off the QT_DEBUG variable. Replicate the fixes in the other two patches when building qt23 with debugging turned on. -pthread --> ${PTHREAD_LIBS} -D_THREAD_SAFE --> ${PTHREAD_CFLAGS} Fix last-minute change to avoid broken packaging for qt2-static.. Ladies and gentlemen, I give you QT 2.3.0! Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD 7 vulnerabilities affecting 11 ports have been reported in the past 14 days * - modified, not new All vulnerabilities
http://www.freshports.org/x11-toolkits/qt23/
CC-MAIN-2014-35
en
refinedweb
can somebody tell me how to create stack array in easy way and can make me and others like me easy to understand? tell me how to create stack array in easy way and can make me and others like me easy to understand? please anyway, im doin some home that my lecturer gave to me, so here what i done so far... import java.util.*; public class Usestack { public static void main(String args[]){ Scanner sc; sc=new Scanner (System.in); int n; System.out.println("enter the size of stack"); n=sc.nextInt(); Stack s=new Stack(); int choice; do{ System.out.print("1. push, 2. pop, 3. display, 0. exit, enter your choice: "); choice=sc.nextInt(); switch(choice){ case 1: int value; System.out.print("enter element to push: "); value=sc.nextInt(); s.push(value); break; case 2: s.pop(); break; case 3: System.out.println(s); break; case 0: break; default:System.out.println("invalid choice"); } }while(choice!=0); } } when i click run the program, it can be 'use', but... my lecturer said that my ARRAY size no function, that true, when i run the program the first line said "enter the size of stack", so i enter 2 or 3 size of stack, but then, the program show that i can push many element as i want, more than what i enter the size of stack, so how to do the stack size(to input)... The Java stack class extends the Vector super class, so it will automatically expand itself when you try to add elements beyond the current size.The Java stack class extends the Vector super class, so it will automatically expand itself when you try to add elements beyond the current size. If you really want to limit the stack size, you need to check the size in case 1 before allowing the user to push more onto the stack: case 1: if (s.size() < n) { // code to add new element to stack } else { System.out.println("You've reached the stack limit!"); } break;
http://www.javaprogrammingforums.com/collections-generics/2274-stack-array.html
CC-MAIN-2014-35
en
refinedweb
What does it take to support several programming languages within one environment? .NET, which has taken language interoperability to new heights, shows that it's possiblebut only with the right design, the right infrastructure, and appropriate effort from both compiler writers and programmers. In this article, I'd like to go deeper than what I've seen published on the topic, to elucidate what it takes to provide true language openness. The experience that my colleagues have accumulated over the last three years of working to port Eiffel on .NET, as well as the countless discussions we've had with other .NET language implementers, informs this discussion. Who Needs More Than One Language? Let's start with the impolite question: Should one really care about multilanguage support? When this feature was announced at .NET's July 2000 debut, Microsoft's competitors sneered that it wasn't anything anyone needed. I've heard multilanguage development dismissed, or at least questioned, on the argument that most projects simply choose one language and stay with it. But that argument doesn't really address the issue. For one thing, it sounds too much like asserting, from personal observation, that people in Singapore don't like skiing. Lack of opportunity doesn't imply lack of desire or need. Before .NET, the effort required to interface modules from multiple languages was enough to make many people stick to just one; but, with an easy way to combine languages seamlessly and effortlessly, they mayas early experience with .NET suggestsstart to appreciate their newfound freedom to mix and match languages. Even more significant is the matter of libraries. Whether your project uses one language or more, it can take advantage of reusable libraries, whose components may have originated in different source languages. Here, interoperability means that you can use whatever components best suit your needs, regardless of creed or language of origin. This ability to mix languages offers great promise for the future of programming languages, as the practical advance of new language designs has been hindered by the library issue: Though you may have conceived the best language in the world, implemented an optimal compiler and provided brilliant tools, you still might not get the users you deserve because you can't match the wealth of reusable components that other languages are able to provide, merely because they've been around longer. Building bridges to these languages helps, but it's an endless effort if you have to do it separately for each one. In recent years, this library compatibility issue may have been the major impediment to the spread of new language ideas, regardless of their intrinsic value. Language interoperability can overturn this obstacle. Under .NET, as long as your language implementation satisfies the basic interoperability rules of the environment (as explained in the following examples), you can take advantage of components written in any other language whose implementers have adhered to the same rules. That still means some work for compiler writers, but it's work they must do once for their languagenot once for each language with which they want to interface.. Everyone will benefit, even the Java community: Now that there's competition again, new constructs aresurprise!again being considered for Java; one hears noises, for example, about Sun finally introducing genericity sometime in the current millennium. Such are the virtues of openness and competition.. Language Operability at Work Multilanguage communication techniques are nothing new. For some time, Eiffel has included an "external" mechanism for calling out to C and other languages, and a call-in mechanism known as Cecil (which is similar to the Java Native Methods Interface). But all this only addresses calls.NET goes much further: - A routine written in a language L1 may call another routine written in a different language L2. - A module in L1 may declare a variable whose type is a class declared in L2, and then call the corresponding L2 routines on that variable. - If both languages are object oriented, a class in L1 can inherit from a class in L2. - Exceptions triggered by a routine written in L1 and not handled on the L1 side will be passed to the caller, whichif written in L2will process it using L2's own exception-handling mechanism. - During a debugging session, you may move freely and seamlessly across modules written in L1 and L2. I don't know about you, but I've never seen anything coming even close to this level of interoperability. Affirmative Action Let's examine how .NET's language interoperation works. Here's the beginning of an ASP.NET page (from an example at dotnet.eiffel.com). The associated system is written mainly in Eiffel, but you wouldn't guess this from the page text; as stated by the ASP.NET PAGE LANGUAGE directive, the program code on the page itself, introduced by <SCRIPT RUNAT="SERVER">, is in C#: <%@ Assembly /* Start of C# code */ Registrar conference_registrar; bool registered; String error_message; void Page_Init(Object Source, EventArgs E) { conference_registrar = new Registrar(); registrar.start(); ... More C# code ... } ... More HTML ... The first C# line is the declaration of a C# variable called conference_registrar, of type REGISTRAR. On the subsequent lines, we create an instance of that class through a new expression, and assign it to conference_registrar; and we call the procedure start on the resulting object. Presumably, REGISTRAR is just some C# class in this system. Presume not. Class REGISTRAR is an Eiffel class. The only C# code in this example application is on the ASP.NET page, and consists of only a few more lines than shown above; its task is merely to read the text entered into the various fields of the page by a Web site visitor and to pass it on, through the conference_registrar object, to the rest of the systemthe part written in Eiffel that does the actual processing. Nothing in the above example (or the rest of the ASP.NET page) mentions Eiffel. REGISTRAR is not declared as an Eiffel class, or a class in any specific language: It's simply used as a class. The expression new REGISTRAR() that creates an instance of the class might look to the unsuspecting C# programmer like a C# creation, but in fact it calls the default creation procedure (constructor) of the Eiffel class. Not that this makes any difference at the level of the Common Language Runtime: At execution time, we don't have C# objects, Eiffel objects or Visual Basic objects; we have .NET citizens with no distinction of race, religion or language origin. In the previous code sample, if we don't tell the runtime that REGISTRAR is an Eiffel class, how is it going to find that class? Simple: namespaces. Here's the beginning of the Eiffel class text of REGISTRAR: indexing description: "[ Registration services for a conference; include adding new registrants and new registrations. ]" dotnet_name: "Conference_registration.REGISTRAR" class REGISTRAR inherit WEB_SERVICE create start feature - Initialization start is - Set empty error message. do set_last_operation_successful (True) set_last_error_message ("No Error") set_last_registrant_identifier (-1) end ... Other features ... The line preceded by dotnet_name says: "To the rest of the .NET world, this class shall be part of the namespace Conference_registration, where it shall be known under the name REGISTRAR." This enables the Eiffel compiler to make the result available in the proper place for the benefit of client .NET assemblies, whether they originated in the same language or in another one. Now reconsider the beginning of the ASP.NET page shown earlier: <%@ Assembly ... The rest as before ... The second line says to import the namespace Conference_registration, and that does the trick. A namespace is an association between class names, a way of saying "The class name A denotes that code over there, and the class name B denotes this other code here." In that association, the class name REGISTRAR will denote the Eiffel class above, since we took care of registering it under that name in the dotnet_name entry of its indexing clause. The basic technique will always be the same: - When you compile one or more classes written in language L1, you specify the namespaces into which they will be compiled and the final names that they must retain in that language. - When you write a system in a language L2the same as L1, or another oneyou specify one or more namespaces to "import"; they will define how to understand any class name to which your system may refer. The details may vary depending on the languages involved. On the producer side, L1, you may retain the original class names or, as in the preceding Eiffel example, explicitly specify an external class name. On the consumer side, you may have mechanisms to adapt the names of external classes and their features to the conventions of L2. Some flexibility is essential here, since what's acceptable as an identifier in one language may not be in another: Visual Basic, for example, accepts a hyphen in a feature name, as in my-feature, but most other languages don't, so you'll need some convention to accept the feature under a different name. What's important is that you can have access to all the classes and features from any other .NET language. Combining Different Language Models How does the interoperability work in practice? The first key idea is to map all software to the .NET Object Model. Once compiled, classes don't reveal their language of origin. Starting from a source language, the compiler will map your programs into a common target, as shown in "Combining Different Language Models." This by itself isn't big news, since we could use the same figure to explain how compilers map various languages to the common model of, say, the Intel architecture. What is new is that the object model, as we've seen in detail, retains high-level structures such as classes and inheritance that have direct equivalents in source programs written in modern programming languages, especially object-oriented ones. This is what allows modules from different languages to communicate at the proper level of abstraction, by exchanging objectsall of which, as .NET objects, are guaranteed to have well-understood, language-independent properties. Object Model Discrepancies Of course, the. The case of non-OO languages is the most obvious: Right from the initial announcements, .NET has included languages like APL and Fortran, which no one would accuse of being object oriented. Even if we restrict our attention to object-oriented languages, we'll find discrepancies. Each has its own object model; while the key notionsclass, object, inheritance, polymorphism, dynamic bindingare common, individual languages depart from the .NET model in some significant respects: - Eiffel and C++ allow multiple inheritance; the .NET object model (as well as Java, C# and Visual Basic .NET) permits a class to inherit from only one class, although it may inherit from several interfaces. - Eiffel and C++ each support a form of genericity (type parameterization): You can declare an Eiffel class as LIST [G]to describe lists of objects of an arbitrary type Gwithout saying what Gis; then you can use the class to define types LIST [INTEGER], LIST [EMPLOYEE], or even LIST [LIST [INTEGER]]. C++'s templates pursue a similar goal. This notion is unknown to the .NET object model, although planned as a future addition; currently, you have to write a LISTclass that will manipulate values of the most general type, Object, and then cast them back and forth to the types you really want. - The .NET object model permits in-class overloading: Within a class, a single feature name may denote two or more features. Several languages disallow this possibility as incompatible with the aims of quality object-oriented development. These object model discrepancies raise a serious potential problem: How do we fit different source languages into a common mold? There are two basic approaches: Either change the source language to fit the model, or let programmers use the language as before, and provide a mapping through the compiler. No absolute criterion exists: Both approaches are found in current .NET language implementations. C++ and Eiffel for .NET provide contrasting examples. The Radical Solution C++ typifies the Procrustean solution: Make the language fit the model. To be more precise, on .NET, the name "C++" denotes not one language, but two: Unmanaged and Managed C++. Classes from both languages can coexist in an application: Any class marked __gc is managed; any other is unmanaged. The unmanaged language is traditional C++, far from the object model of .NET; unmanaged classes will compile into ordinary target code (such as Intel machine code), but not to the object model. As a result, they don't benefit from the Common Language Runtime and lack the seamless interoperability with other languages. Only managed classes are full .NET players. But if you then look at the specifications for managed classes, you'll realize that you're not in Kansas any more (assuming, for the sake of discussion, that Kansas uses plain C++). On the "no" side, there's no multiple inheritance except from (you guessed it) completely abstract classes, no support for templates, no C-style type casts. On the "yes" side, you'll find new .NET mechanisms such as delegates (objects representing functions) and properties (fields with associated methods). If this sounds familiar, that's because it is: Managed C++ is very close to C#, in spite of what the default Microsoft descriptions would have you believe. Predictably, the restrictions also rule out any cross-inheritance between managed and unmanaged classes. The signal to C++ developers is hard to miss: The .NET designers don't think too highly of the C++ object model and expect you to move to the modern world as they see it. The role of Unmanaged C++ is simply to smooth the transition by allowing C++ developers to move an application to the managed side one class at a time. An existing C++ application will compile straight away as unmanaged. Then you'll try declaring specific classes as managed. The compiler will reject those that violate the rules of the managed world, for example, by using improper casts; the error messages will tell you what you must correct to turn these classes into proper citizens of the managed world. For C++, this is indeed a defensible policy, as the language's object modeldefined to a large extent by the constraint of backward compatibility with C, a language more than three decades oldis obsolete by today's standards. Respecting Other Object Models Only time will tell how successful the .NET strategy will be at convincing C++ programmers to move over to the managed world. But even if they wholeheartedly comply, it won't mean that other languages should follow the same approach. This is particularly true of object-oriented languages that have their own views of what OO should be, with perhaps better arguments than C++. If you've chosen a language precisely because it supports such expressive mechanisms as multiple inheritance, Design by Contract and genericity, do you have to renounce them and step down to the lowest common denominator once you decide to use .NET? Fortunately, the answer is no, at least not if "you" here means the programmer. The scheme described in "Combining Different Language Models" doesn't require that all languages adhere to the .NET object model; rather that they map to that model. That mapping can be made the responsibility of compilers rather than programmers, enabling programming languages to retain their normal semantics, and establishing a correspondence between the specific semantics of each language and the common rules of the common object model. Tune in next issue and discover how this all works out.
http://www.drdobbs.com/polyglot-programming/184414854
CC-MAIN-2014-35
en
refinedweb
Skip navigation links java.lang.Object oracle.rules.rl.extensions.ClassFilter public class ClassFilter A filter that passes objects that are instances of a particular class. public ClassFilter(java.lang.String className, RuleSession rs) throws UndefinedException className- the name of the class that the filter should pass instances of. The class may be an RL class or a Java class. Consistent with RL semantics, it looks for an RL class with the specified name first and then looks for a Java class . rs- the RuleSession this filter will be used with. It is used to handle RL classes. UndefinedException public boolean accept(java.lang.Object object) acceptin interface ObjectFilter object- the object to apply the filter to. public void reset() resetin interface ObjectFilter Skip navigation links
http://docs.oracle.com/cd/E15523_01/apirefs.1111/e10663/oracle/rules/rl/extensions/ClassFilter.html
CC-MAIN-2014-35
en
refinedweb
"International cybercrime treaty advances slowly" "The tyranny of code" "Y2K: Only the grin remains" Poised to overtake China as the world's most populous country, and accounting for 30 percent of the world's software engineers, India has entered the 21st century with great potential and challenges. For many reasons, it is in the U.S. government's interest to enter into partnerships with reliable Indian companies. The scale of India's challenges is daunting. Unreliable electrical power, poor roads, harsh climatic conditions that demand rugged equipment and costly services from a monopoly services provider are the major obstacles. The central government will invest $50 million to create satellite-based community Internet access in up to 1,000 population centers in the next two years. It is also partnering with Massachusetts Institute of Technology's Media Lab to promote low-cost wireless Internet access. Human capital is a more complex matter. The existence of 17 official languages magnifies the challenge of providing basic education in information and communication technology skills. At the university level, the demand for skilled ICT engineers and managers is outstripping the capacity of the educational system. On the other hand, retention of skilled young people is improving more than half of the graduates of the best computer institutes now stay in India. Low labor costs continue to be an Indian advantage, belying the fact that more Indian companies than U.S. companies have earned the top rating from Carnegie Mellon University's Software Engineering Institute. India's 1 billion people are only beginning to be affected by this change. Bullock carts overloaded with sugar cane still creep past the telephone access shops that have sprung up in every village the drivers and shop operators unaware of the valuable information about crop markets that lies just beyond their reach in cyberspace. Progress is slowed by a difficult working relationship between the public and private sectors. The crafty denizens of the derisively named "babucracy" are skillful at retaining their middleman status and delaying the potential of e-government to streamline import and export processing, issue permits and otherwise strengthen India's national economy. As a result, the private sector has moved forward where there are fewer obstacles. Call centers, a leading service export, are assisted by cost structures for overseas connections, but held back by regulation in domestic markets. In the meantime, Indian companies and the U.S. companies who have partnered with them are weathering the slowdown in the global information technology industry better than many of their peers. They have been aided in this success by strong onshore/offshore partnerships that are creating a virtuous cycle of human, intellectual and financial capital flows between expatriate and domestic Indian professionals. The opportunity that this situation creates should not go unexamined by the United States, the world's largest buyer of programming services. McConnell, former chief of information policy and technology at the Office of Management and Budget, is president of McConnell International LL:
http://fcw.com/articles/2001/04/23/a-surging-chaotic-power.aspx
CC-MAIN-2014-35
en
refinedweb
User talk:Aburton From OLPC Sorry about the blip with the Main Page. Here are a few suggestions that would minimize wasted space at the top. - get rid of the OLPC macro. It really goes without saying on that page but if it must be said, say it at the bottom. - get rid of redirects. Hunt down any refs to The OLPC Wiki and point them at the main page. It saves the space taken up by the redirect message. - Get rid of the heading OLPC News. That isn't true because there is a separate news page. Since this is the opening page, just get right into the content. - Please keep the Negroponte quote at the top because that is the major misunderstanding out there about the project. GW Carver Sorry, but I must disagree about George Washington Carver. When he was teaching children he tried to teach them real science by having them build real scientific apparatus and do real experiments applying the scientific method. Much of what passes for science in today's educational system is memorization of facts discovered by others or history of science. The OLPC could potentially be used as a tool to involve students in the scientific method which is the core of science. For that to happen we need people to produce content (both texts and applications) that is adpated to this approach. And in particular, since the targetted kids will have no scientific equipment of any kind available, the content needs to begin by instructing students how to scrounge up stuff much like G.W. Carver did. If you know of better examples to illustrate this principle, please add them. --Memracom 16:33, 23 June 2006 (EDT) < includeonly > considered harmless To keep categories and other metadata in templates from being associated with the template itself, use <includeonly> and </includeonly>. All text between those tags will be discarded except on transclusion. (Note that I had to stick them inside <nowiki> tags to get that text to show up here). (When you consider that all wiki pages -- not only Template: namespace pages -- can be transcluded into other pages, this opens the door to some elaborate obfuscated wikitext...) Cheers, Sj 12:19, 26 June 2006 (EDT)
http://wiki.laptop.org/index.php?title=User_talk:Aburton&oldid=187562
CC-MAIN-2014-35
en
refinedweb
In this section, you will import the barcode JavaBean, then create a paper-based report that shows the invoice for a particular customer. This invoice will display the address of the customer, his order, and a barcode that represents the tracking number for the order. The company can scan this barcode to find out the status of the order. To create a paper report using the barcode JavaBean, you must first import two Java classes into Reports Builder. When you import these Java classes, Reports Builder automatically creates the packages you need to build the report. Note:You do not need to perform this task if you are creating a Web report, as you will write JSP code that calls the JavaBean. To import the Java classes: Launch Reports Builder. Note:You must launch Reports Builder now so that the new REPORTS_CLASSPATHis used. Close the Welcome dialog box by clicking Cancel. Choose Program > Import Java Classes to display the Import Java Classes dialog box. Under Select Java Classes, navigate to: oracle.apps.barcode.util.BarCodeConstants Note:If you do not see this class listed, try exiting Reports Builder and make sure the REPORTS_CLASSPATHreads correctly. Then, launch Reports Builder again. Select the class, then click Import. Once the packages have been created, import the second JavaBean: oracle.apps.barcode.BarCodeMaker. Click Close. In the Object Navigator, under the report named MODULE 1, click the Program Units node. You will notice that Reports Builder created two package specifications and two package bodies named BARCODECONSTANTS and BARCODEMAKER. In this report, you want to create a package where the information will be stored. To create a package for storing your information: In the Object Navigator, under your new report, click the Program Units node. Click the Create button in the toolbar to display the New Program Unit dialog box. In the New Program Unit dialog box, type globals. Select Package Spec, then click OK to display the PL/SQL Editor: In the PL/SQL Editor, type the following code: PACKAGE globals IS bcobj ora_java.jobject; barcode_to_use varchar2(256); tempdir varchar2(100); directory_sep varchar2(2); END; Note:You can also enter this code by copying and pasting it from the provided text file called barcode_code.txt. Click Compile to make sure there are no errors in your code. Note:If your code does not compile, make sure you have typed in exactly the code we have provided. Once the code is compiled, click Close. In the Object Navigator, click your report name (for example, MODULE 1). Save the report as shippingmanifest_ your_initials .rdf. You have created a package that will contain the global information for your report. You can use a Before Report trigger to perform specific tasks before the report is run. Here, you will define the type of barcode you want to use in your report, as well as the temporary directory where your barcode images will be stored. To create a Before Report trigger: In the Object Navigator, under SHIPPINGMANIFEST_ your_initials, expand the Report Triggers node, then double-click the icon next to BEFORE REPORT to display the PL/SQL Editor. In the PL/SQL Editor, use the template to enter the following PL/SQL code: function BeforeReport return boolean is begin globals.barcode_to_use := BarCodeConstants.BAR_CODE_128; globals.bcobj := barcodemaker.new(); return (TRUE); end; To modify the type of barcode you want to use, you can change the value BarCodeConstants.BAR_CODE_128 to any other valid value. To determine which values are valid, check the contents of the package by opening the BarCodeConstants package spec in the Object Navigator, under the Program Units node.. Notice how the node icon next to the BEFORE REPORT trigger has changed. Save your report. You have created a trigger that will set up the barcode type for you when you run the report. In this section, you will manually create the query that the report will use to retrieve data from the sample schema. To create the query: In the Object Navigator, under SHIPPINGMANIFEST_ your_initials, double-click the view icon next to the Data Model node to display the Data Model view for your report. In the Data Model view, click the SQL Query tool in the tool palette, then click in an open area of the Data Model view to display the SQL Query Statement dialog box. In the SQL Query Statement field, enter the following SELECT statement: SELECT ALL CUSTOMERS_A1.CUST_FIRST_NAME, CUSTOMERS_A1.CUSTOMER_ID, CUSTOMERS_A1.CUST_LAST_NAME, CUSTOMERS_A1.CUST_ADDRESS.STREET_ADDRESS, CUSTOMERS_A1.CUST_ADDRESS.POSTAL_CODE, CUSTOMERS_A1.CUST_ADDRESS.CITY, CUSTOMERS_A1.CUST_ADDRESS.STATE_PROVINCE, CUSTOMERS_A1.CUST_ADDRESS.COUNTRY_ID, ORDERS.ORDER_ID, ORDERS.ORDER_DATE, ORDERS.ORDER_TOTAL, ORDER_ITEMS.LINE_ITEM_ID, PRODUCTS.PRODUCT_NAME, ORDER_ITEMS.UNIT_PRICE, ORDER_ITEMS.QUANTITY, COUNTRIES.COUNTRY_NAME FROM CUSTOMERS CUSTOMERS_A1, ORDER_ITEMS, ORDERS, PRODUCTS, HR.COUNTRIES WHERE ((ORDER_ITEMS.ORDER_ID = ORDERS.ORDER_ID) AND (ORDERS.CUSTOMER_ID = CUSTOMERS_A1.CUSTOMER_ID) AND (ORDER_ITEMS.PRODUCT_ID = PRODUCTS.PRODUCT_ID) AND (CUSTOMERS_A1.CUST_ADDRESS.COUNTRY_ID = HR.COUNTRIES.COUNTRY_ID)) AND ORDERS.ORDER_ID = :P_ORDER_ID ORDER BY order_ID, line_item_ID Note:You can enter this query in any of the following ways: Copy and paste the code from the provided text file called barcode_code.txt into the SQL Query Statement field. Click Query Builder to build the query without entering any code manually. Type the code in the SQL Query Statement field. Click OK. If you are not connected to a database that contains the sample schema we have provided, you must log in now. If you are not sure what your connection string is, contact your database administrator. Note that this example uses the Order Entry sample schema. When a message displays indicating that the bind parameter p_order_id was created, click OK. In the data model you just created, select all of the following columns using Shift-click, then drag them below the current query to create a detail group: LINE_ITEM_ID PRODUCT_NAME UNIT_PRICE QUANTITY The resulting data model should look like this: Figure 43-2 Data Model for the query In this section, you will create a formula column that will communicate with the JavaBean to create the barcode, then return the file name of the generated image. To create a formula column: In the Data Model view, click the Formula Column tool in the tool palette. Click in the master group (G_CUST_FIRST_NAME) to create a new formula column. Double-click the new formula column object (CF_1) to display the Property Inspector, and set the following properties: Under General Information, set the Name property to ImageFilename. Under Column: Set the Datatype property to Character Set the Width property to 500 Set the Read from File property to Yes Set the File Format property to Image Under Placeholder/Formula, click the PL/SQL Formula property field to display the PL/SQL Editor. In the PL/SQL Editor, use the template to enter the following PL/SQL code: function ImageFilenameFormula return VarChar2 is myFileName varchar2(500); result varchar2(500); barcodeData VarChar2(50) := :customer_ID || :order_ID; begin myFileName := srw.create_temporary_filename; barcodemaker.setBarWidthInch(globals.bcobj, 0.005); barcodemaker.setBaseCodeData(globals.bcobj,barcodeData); barcodemaker.setBarCodeType(globals.bcobj,globals.barcode_to_use); barcodemaker.setFullPath(globals.bcobj, myFileName); barcodemaker.renderBarCode(globals.bcobj); return(myFileName); end;. To create the second formula column: In the Data Model view, create a formula column in the detail group G_LINE_ITEM_ID. Open the Property Inspector for the formula column, and set the following properties: Under General Information, set the Name property to LineTotal. Under Column, make sure the Datatype property is set to Number. Under Placeholder/Formula, click the PL/SQL Formula property field to display the PL/SQL Editor. In the PL/SQL Editor, use the template to enter the following PL/SQL code: function LineTotalFormula return Number is begin return (:quantity * :unit_price); end; Note:You can enter this code by copying and pasting it from the provided text file called barcode_code.txt. Click Compile to make sure there are no errors. When the code is compiled, click Close. Save the report. You have created the data model for your barcode report, which contains a formula column that retrieves the barcode information and displays the barcode image on your report, and another formula column that displays the order total. Your data model and the PL/SQL for the formula column should look similar to this: Figure 43-3 Data Model with two new formula columns Before you can run your report, you must create a layout. To create a paper layout: Under your report's node in the Object Navigator, right-click Paper Layout, then choose Report Wizard. In the Report Wizard, on the Report Type page, select Create Paper Layout Only, then click Next. On the Style page, select Group Above, then click Next. On the Data Source page, click Next. On the Data page, click Next. On the Groups page, make sure the following fields are listed in the Group Fields list (if not, use the arrows to move the field to the appropriate list): ORDER_ID ORDER_DATE CUSTOMER_ID CUST_FIRST_NAME CUST_LAST_NAME STREET_ADDRESSS COUNTRY_NAME CITY STATE_PROVINCE COUNTRY_ID ORDER_TOTAL CF_1 On the Fields page, click the double right arrows (>>) to move all of the fields to the Displayed Fields list, then click Finish. In the Paper Layout view, click the Run Paper Layout button in the toolbar to run your report. In the Runtime Parameter Form, next to P_ORDER_ID, type 2354. Once your report displays in the Paper Design view, you can rearrange your layout objects in the Paper Layout view to make your report look something like Figure 43-4. To create this format: In the Paper Layout view, remove the surrounding parent frame M_G_CUST_FIRST_NAME_GRPFR, then click the Confine Off button and the Flex Off button in the toolbar. Using the shippingmanifest.rdf example report as a guide, add three rectangles and three text objects for: Shipping Details: Set text properties to Arial, 16, bold. Create a frame to add the following fields: cust_first_name, cust_last_name, street_address, city, state_province, postal, country_name. Tracking Details: Set text properties to Arial, 16, bold. Move the ImageFilename object onto this rectangle. Order Details: Set text properties to Arial, 16, bold. Move the labels and fields for Order ID and Order Date onto this rectangle. Move the field F_Order_Total onto this rectangle and set text properties to Courier New, 24, bold. Set the text properties for all other field values to Courier New, 10. Additionally, set F_Line_Total to bold. Format numeric field values to display currency, decimals, and right align them. Set Fill Color for each rectangle, totals field, and table header as desired. Figure 43-4 Paper Design view of the barcode paper report Note:If you are not sure whether you produced the desired results, you can always open the example report called ShippingManifest.pdfin Acrobat Reader. Or, you can run ShippingManifest.rdfto paper and the report will display in the Paper Design view. Save the report. You have now finished building a barcode report for paper.
http://docs.oracle.com/cd/E15523_01/bi.1111/b32122/orbr_barcode002.htm
CC-MAIN-2014-35
en
refinedweb
I.) July 26, 2012 at 12:01 pm | This looks really cool. When I saw the title I figured that SmartCheck used a solver to create inputs maximizing some coverage metric, like DART, Klee, and SAGE. Hasn’t anyone done that yet? If not, do you know why? July 26, 2012 at 5:53 pm | Yes, the name ‘SmartCheck’ may have been a little over zealous. :) I don’t think there’s been much work in concolic-like testing for functional languages. There is some recent work in this direction out of NEU. One challenge is the liberal use of higher-order functions in languages like Haskell or Racket. For example, consider the simple (but contrived) Haskell function: h :: Eq a => (a -> a -> a) -> [a] -> Int h _ [] = 1 h f ls = if head ls == foldl1 f ls then 0 else 1 To test each branch requires symbolically reasoning about the input f, which is a function. (Note though that QuickCheck can generate random monomorphic functions for testing.) But I take it that your point is that by limiting ourselves to inputs like algebraic functions, a symbolic solver might be possible. That’s an interesting idea, but I don’t know of work in this direction. August 10, 2012 at 1:27 pm Thanks for the links Lee and Ranjit. I guess there’s an interesting tension where functional languages are both easier and harder targets for concolic testing than are imperative languages. Wouldn’t some of these issues become easier if testing were done at the whole-program level, rather than at the unit level? In that case inputs are just bits… July 27, 2012 at 10:19 am | Hi John, I believe Suresh Jagannathan is/was also working on this… Ranjit. July 26, 2012 at 6:50 pm | Is this likely to do a better job avoiding exponential runtime explosions when generating recursive data structures? A major problem I have with QuickCheck is using sized and co to prevent it from running forever when generating things like trees. July 26, 2012 at 8:02 pm | Derek, Sorry, this won’t help there. SmartCheck uses QuickCheck as a back-end to generate random values, so it still depends on you using sized to bound the size of the values generated. SmartCheck can help though to see the problem with a failed test, so you don’t need to rerun QuickCheck to generate multiple failing values, so it can cut down the test/debug/rewrite/test loop. July 29, 2012 at 10:51 am | Take a look at gencheck: July 27, 2012 at 12:36 pm | Interesting! I’m still trying to port QuickCheck to languages without lambda and introspection, such as Pascal. The hardest part is often figuring out how to do (apply function-to-test list-of-arguments) without triggering compiler errors, due to the dynamic nature of the argument types. I managed a hack for C, not pretty, but it works. July 31, 2012 at 4:27 pm | I tried using the derive package to get the Arbitrary instance for your example. When I run the code I get: *** Failed! Falsifiable (after 14 tests): D (C 22) (D (D (D (D (A (C (-28)) (C (-26))) (C (-30))) (C (-3))) (C (-8))) (D (A (C 2) (A (C (-23)) (A (C 26) (C (-20))))) (C (-8)))) *** Smart Shrinking … *** Smart-shrunk value: D (C 22) (D (C 0) (C (-1))) *** Extrapolating values … : memory allocation failed (requested 1048576 bytes) The code I use is the same except for removing the Arbitrary instance and adding: {-# LANGUAGE TemplateHaskell #-} import Data.DeriveTH $( derive makeArbitrary ”M ) July 31, 2012 at 6:45 pm | Thanks, Daniel. I tried it myself, and I get the same result. Do you know what the definition of arbitrary that is generated by derive is? August 1, 2012 at 12:27 pm I use ‘ghc -fforce-recomp -ddump-splices ../examples/Div0.hs’ and it gives: instance Arbitrary M where arbitrary = do { x do { x1 do { x1 <- arbitrary; x2 do { x1 <- arbitrary; x2 error “FATAL ERROR: Arbitrary instance, logic bug” } } Yup, there’s no size restriction. I’ll look at the code although it’s TH.
http://leepike.wordpress.com/2012/07/26/smartcheck/?like=1&_wpnonce=ad1ddc05d8
CC-MAIN-2014-35
en
refinedweb
Java Serialization: Persist Your Objects When a Java application is executed, a large number of objects are created. Most of these objects are created and destroyed in the runtime. It would be convenient if Java saved these objects for future use or recreated them from an existing source and then used themeven when the application is re-run after it was stopped. The good news is Java does support this mechanism with the Java Serialization API. Serialization is the process of saving an object's state to a persistence store and also rebuilding the object from the saved information when needed in the future. With Serialization, you can serialize (persist) any object that you don't need or that may have been used in some other application or may be used later. Understanding the Java Serialization API The method writeObject(...) of the ObjectOutputStream class makes the serialization transparent to the developer. You don't need to worry about creating the persistent file, reading the end-of-file, creating a new file, etc., thereby relieving you of a lot of additional effort. As an example, here is a DataAndTimeObject class that can be serialized: import java.io.Serializable; import java.util.*; //This class represents DataAndTimeObject that can be serialized public class DateAndTimeObject implements Serializable { private Date dateAndTime; public DateAndTimeObject() { dateAndTime = Calendar.getInstance().getTime(); } public Date getDateAndTime() { return dateAndTime; } } The difference between the above object and a non-serializable object is that this one implements the Serializable interface. The following code shows how you would serialize the object DataAndTimeObject. import java.io.*; //This class provides methods to serialize a serializable object public class SerializeObject { public static void main(String args[]) { String serializeFileName = "dateAndTime.ser"; if(args.length > 0) { serializeFileName = args[0]; } DateAndTimeObject dateAndTimeObject = new DateAndTimeObject(); FileOutputStream fileOutputStream = null; ObjectOutputStream objectOutputStream = null; try { fileOutputStream = new FileOutputStream(serializeFileName); objectOutputStream = new ObjectOutputStream(fileOutputStream); //The object is being persisted here objectOutputStream.writeObject(dateAndTimeObject); objectOutputStream.close(); System.out.println("Serialize Date and Time : " + dateAndTimeObject.getDateAndTime()); System.out.println("Object serialized in file : " + serializeFileName); } catch(IOException ioe) { //Close all I/O streams ioe.printStackTrace(); //Handle the exception here } } } Here is the output from the above code. The class SerializeObject has an implementation that can serialize the object DataAndTimeObject. This implementation also takes an argument for the serialize object file name, ignoring whether or not the file name would be dateAndTime.ser. The writeObject(...) method of the ObjectOutputStream class facilitates the serialization process. As discussed previously, the I/O streams take care of the file-handling overhead. Here is the code for creating the object from the file dateAndTime.ser. import java.io.*; import java.util.Calendar; public class DeSerializeObject { public static void main(String args[]) { DateAndTimeObject dateAndTimeObject = null; FileInputStream fileInputStream = null; ObjectInputStream objectInputStream = null; String serializedFileName = "dateAndTime.ser"; if(args.length > 0) { serializedFileName = args[0]; } try { fileInputStream = new FileInputStream(serializedFileName); objectInputStream = new ObjectInputStream(fileInputStream); dateAndTimeObject = (DateAndTimeObject) objectInputStream.readObject(); objectInputStream.close(); //Date and Time that was serialized System.out.println("Serialize Date and Time: " + dateAndTimeObject.getDateAndTime()); //Current Date and Time System.out.println("Current Date and Time : " + Calendar.getInstance().getTime()); } catch(FileNotFoundException fnfe) { System.out.println("File not found: "+fnfe.getMessage()); //Close all I/O streams //Handle the exception here } catch(IOException ioe) { ioe.printStackTrace(); //Close all I/O streams //Handle the exception here } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); //Close all I/O streams //Handle the exception here } } } Here is the output from the above listing. The readObject(...) method of the ObjectInputStream class facilitates creating the object in the runtime from the serialized object. Page 1 of 2
http://www.developer.com/java/other/article.php/3863686/Java-Serialization-Persist-Your-Objects.htm
CC-MAIN-2014-35
en
refinedweb
09 November 2011 10:27 [Source: ICIS news] TOKYO (ICIS)--?xml:namespace> The companies plan to start producing MMA monomer using biomass as feedstock by 2016, MRC said in a statement. They aim to produce 50% of MRC’s MMA monomer output using biomass, it added. The companies will develop two new sustainable production methods. The first involves technology using biomass as feedstock in the existing production processes, while the second involves completely new technology using the fermentation process of biomass, MRC said. MRC currently produces MMA monomer using two methods: the C4 direct oxidisation process that uses isobutylene as feedstock, and the ACH process that uses acetone and hydrogen cyanide as feedstocks, according to the company’s website.For more information
http://www.icis.com/Articles/2011/11/09/9506593/japans-mrc-lucite-to-develop-bio-based-mma-production-tech.html
CC-MAIN-2014-35
en
refinedweb
Roll-your-own Scala I've always really liked this passage from On the Genealogy of Morals: [T]here is a world of difference between the reason for something coming into existence in the first place and the ultimate use to which it is put, its actual application and integration into a system of goals… anything which exists, once it has come into being, can be reinterpreted in the service of new intentions, repossessed, repeatedly modified to a new use by a power superior to it. A couple of months ago at LambdaConf I had a few conversations with different people about why we like (or at least put up with) Scala when there are so many better languages out there. Most of the answers were the usual ones: the JVM, the ecosystem, the job market, the fact that you don't have to deal with Cabal, etc. For me it's a little more complicated than that. I like Scala in part because it's a mess. It's not a "fully" dependently typed language, but you can get pretty close with singleton types and path dependent types. It provides higher-kinded types, but you have to work around lots of bugs and gaps and underspecified behaviors to do anything very interesting with them. And so on—it's a mix of really good ideas and a few really bad ideas and you can put them together in ways that the language designers didn't anticipate and probably don't care about at all. The rest of this blog post will be a long story about one example of this kind of thing involving Scalaz's UnapplyProduct. Type lambdas🔗 Type lambdas are one example of a Scala "feature" that's both hugely useful (and sometimes necessary) and apparently totally accidental. Suppose we've got a simple functor type class: trait Functor[F[_]] { def map[A, B](fa: F[A])(f: A => B): F[B] } And we want to create an instance for the List type constructor. This is easy: implicit val listFunctor: Functor[List] = new Functor[List] { def map[A, B](fa: List[A])(f: A => B): List[B] = fa.map(f) } Now suppose we want to create an instance for Either[String, ?]. This is a little trickier. Scala doesn't provide a direct way to partially apply a multi-parameter type constructor, but we can define a type alias with the left-hand type filled in and then use that in our instance definition: type StringOr[A] = Either[String, A] implicit val stringOrXFunctor: Functor[StringOr] = new Functor[StringOr] { def map[A, B](fa: StringOr[A])(f: A => B): StringOr[B] = fa.right.map(f) } This trick won't work very well if we want the left-hand type to be generic, though—there's simply no way to fit a type alias between the generic type parameter on our defining method and that method's return type. We could try to put the type alias inside the method and let the return type be inferred: implicit def eitherFunctor[E] = { type EOr[A] = Either[E, A] new Functor[EOr] { def map[A, B](fa: EOr[A])(f: A => B): EOr[B] = fa.right.map(f) } } But that won't actually work: scala> type StringOr[A] = Either[String, A] defined type alias StringOr scala> implicitly[Functor[StringOr]] <console>:14: error: could not find implicit value for parameter e: Functor[StringOr] implicitly[Functor[StringOr]] ^ Things are looking pretty bleak, but there is a way we can define this instance. It's just not the kind of thing you're likely to guess would work if you hadn't seen it before. implicit def eitherFunctor[E]: Functor[({ type L[x] = Either[E, x] })#L] = new Functor[({ type L[x] = Either[E, x] })#L] { def map[A, B](fa: Either[E, A])(f: A => B): Either[E, B] = fa.right.map(f) } This horrible syntax is an abuse of two Scala language features that at first seem completely unrelated to the task at hand: type refinements and type projections. These language features seem completely unrelated to this problem at least in part because they were designed for completely unrelated purposes—see for example this comment by Paul Phillips on a Scala issue I opened in 2012: Type lambdas are cool and all, but not a single line of the compiler was ever written with them in mind. They're just not going to work right: the relevant code is not robust. This is one of the nice things about creating cool stuff by accident—you don't have to support it (even when it becomes an idiomatic part of the language—type lambdas for example have had special support in IntelliJ for years, and kind-projector, a compiler plugin that provides syntactic sugar for type lambdas, is becoming increasingly widely used). SI-2712🔗 Now that we've got a functor instance for any Either[E, ?] we probably want to be able to use it in methods like the following: def incrementInside[F[_]: Functor](fa: F[Int]): F[Int] = implicitly[Functor[F]].map(fa)(_ + 1) Which works like this on lists: scala> val myList = List(1, 2, 3) myList: List[Int] = List(1, 2, 3) scala> val myIncrementedList = incrementInside(myList) myIncrementedList: List[Int] = List(2, 3, 4) And like this on Either: val myEither: Either[String, Int] = Right(1) val myIncrementedEither: Either[String, Int] = incrementInside(myEither) Just kidding, that doesn't actually compile. Scala isn't capable of figuring out that Either[String, Int] can be seen as a F[Int] where F is Either[String, ?] (which of course we have a functor instance for). This limitation is tracked in SI-2712, an issue that will celebrate its sixth birthday this November (it's also one of the five or six Scala issues that I can recognize by number). Fortunately there's (another) workaround, due originally to Miles Sabin and now available in both Scalaz and cats: trait Unapply[TC[_[_]], MA] { type M[_] type A def instance: TC[M] def apply(ma: MA): M[A] } object Unapply { implicit def unapplyMA[TC[_[_]], M0[_], A0](implicit instance0: TC[M0] ): Unapply[TC, M0[A0]] { type M[X] = M0[X] type A = A0 } = new Unapply[TC, M0[A0]] { type M[X] = M0[X] type A = A0 def instance = instance0 def apply(ma: M0[A0]): M[A] = ma } implicit def unapplyMAB[TC[_[_]], M0[_, _], A0, B0](implicit instance0: TC[({ type L[x] = M0[A0, x] })#L] ): Unapply[TC, M0[A0, B0]] { type M[x] = M0[A0, x] type A = B0 } = new Unapply[TC, M0[A0, B0]] { type M[x] = M0[A0, x] type A = B0 def instance = instance0 def apply(ma: M0[A0, B0]): M[A] = ma } } Now we can rewrite our incrementInside method like this: def incrementInside[FA](fa: FA)(implicit U: Unapply[Functor, FA] { type A = Int } ): U.M[Int] = U.instance.map(U(fa))(_ + 1) And then: scala> incrementInside(myList) res4: List[Int] = List(2, 3, 4) scala> incrementInside(myEither) res5: scala.util.Either[String,Int] = Right(2) Fortunately in practice we usually only need to define methods that take an Unapply instance for a small handful of generic operations (a common convention is to add a U to the end of the method name to distinguish these versions—so for example in Scalaz the syntax for Traverse provides both traverse and traverseU methods). So now we've used implicit resolution to work around a limitation involving higher-order unification for a type class instance that we defined using type refinements and type projections to work around a limitation involving partial application of type parameters. Next we'll add even more dead body parts to the monster. Multiple implicit parameter sections🔗 Sometimes we need more complex Unapply machinery than the relatively simple version above. One example is syntax for things that are bitraversable. For example, we might want to take a tuple (or Either) and do some kind of logging in a Writer monad for both sides (or either): import scalaz._, Scalaz._ (1, 'a).bitraverseU(_.set("saw int" :: Nil), _.set("saw sym" :: Nil)) This in effect lets us map two functions returning writers over the two sides of our tuple and then turn the whole thing inside out, giving us a writer that logs to a list of strings and returns a (Int, Symbol). We need the bitraverseU version again because of SI-2712—the Scala compiler isn't able to recognize the pieces it needs in the return types of the functions we're mapping over the two sides. Unfortunately this doesn't actually work in Scalaz at the moment. It relies on an Unapply variant called UnapplyProduct that was added to Scalaz in 2011 by Jason Zaugg, but it's always been necessary to construct these instances by hand (which is extremely inconvenient and boilerplate-y). From Jason's original comments, which are still in the source today: // This seems to motivate multiple implicit parameter sections. Is there another way? And: // Would be nice, but I'm not sure we can conjure UnapplyProduct implicitly, at least without multiple implicit // parameter lists. The issue is that the signature for the implicit method that generates UnapplyProduct instances seems to need to look like the following, since we have to confirm that the M types in our Unapply instances for the left and right sides are the same: implicit def unapply[TC[_[_]], MA0, MB0](implicit U1: Unapply[TC, MA0], U2: Unapply[TC, MB0] )(implicit iso: U1.M <~> U2.M): UnapplyProduct[TC, MA0, MB0] { // ... Scala doesn't allow types to be referred to by other types in the same parameter list, so we can't just stick the <~> in with the other instances. The problem is that Scala also doesn't support multiple implicit parameter lists. This is a more arbitrary limitation, but I've never seen any serious discussion of changing it. So we're out of luck. I should know by now that if Jason Zaugg is asking for help on a problem, I should stay away from it, but over the past three or four years I've burned at least two or three Saturdays trying to find a way to implement this unapply method. More workarounds!🔗 In February Miles Sabin posted a gist demonstrating what he called "a new approach to encoding dependently-typed chained implicits, using singleton types". It's a pretty clever trick, and my first thought when I saw it was that we could use it to fix Scalaz's UnapplyProduct. And it worked, although I didn't get around to submitting a pull request until this week. The implementation looks like this: case class SingletonOf[T, U <: { type A; type M[_] }]( widen: T { type A = U#A; type M[x] = U#M[x] } ) object SingletonOf { implicit def mkSingletonOf[T <: { type A; type M[_] }](implicit t: T ): SingletonOf[T, t.type] = SingletonOf(t) } implicit def unapply[ TC[_[_]], MA0, MB0, U1 <: { type A; type M[_] }, U2 <: { type A; type M[_] } ](implicit sU1: SingletonOf[Unapply[TC, MA0], U1], sU2: SingletonOf[Unapply[TC, MB0], U2], iso: U1#M <~> U2#M ): UnapplyProduct[TC, MA0, MB0] { type M[x] = U1#M[x] type A = U1#A type B = U2#A } = new UnapplyProduct[TC, MA0, MB0] { type M[x] = U1#M[x] type A = U1#A type B = U2#A def TC = sU1.widen.TC def _1(ma: MA0) = sU1.widen(ma) def _2(mb: MB0) = iso.from(sU2.widen(mb)) } The key idea is that the U1 and U2 type parameters will be inferred to be the singleton types for our two Unapply instances, and our SingletonOf type class captures the way that these types line up with our TC, MA0, and MB0. This allows us to refer to the M type parameters for the Unapply instances in the same implicit parameter list that gathers the Unapply instances themselves (or rather their SingletonOf wrappers). Note that SingletonOf here is less generic than Miles's original formulation, which would also work if we were willing to do some (safe) casting. Since this is the only interesting application that I can think of for this trick, I'm not worried about using a less generic formulation. To demonstrate that it works, you can check out my pull request and run something like the following: import scalaz._, Scalaz._ val w = (1, 'a).bitraverseU(_.set("saw int" :: Nil), _.set("saw sym" :: Nil)) And then: scala> w.run res0: (List[String], (Int, Symbol)) = (List(saw int, saw sym),(1,'a)) To recap: we've taken a few basic (but still pretty broken) Scala language features—singleton types, refinement types, type projections, and the implicit resolution system—and we've very painfully built a language for ourselves that at least kind of looks like it supports partial type parameter application, higher-order unification, and multiple implicit parameter sections. I think that's pretty neat, but I can also understand why almost everyone else would find it horrifying.
https://meta.plasm.us/posts/2015/07/11/roll-your-own-scala/
CC-MAIN-2020-40
en
refinedweb
DS18B20 onewire temperature sensor The DS18B20 temperature sensor is a digital temperature sensor using the 1-Wire protocol. In this post I will review the sensor, show how it can be used and give a final judgement on it. What can the DS18B20 temperature sensor do? The DSB18B20 temperature sensor is a digital temperature sensor that works using the 1-Wire Protocol. The sensor takes care of turning the analogue signal detected into a digital value in Celsius. Some temperature sensors work by giving you the current resistance and expect you to work out the temperature based on the specific sensor. However this sensor does this for you and means you don’t need to calibrate the sensor to known temperatures and resistance values. This is a big advantage for basic projects where you want to quickly want to know the temperature. The downside is that you need something that speaks the 1-Wire protocol. However there is an Arduino library to do this and means you don’t need to program it yourself. Wiring it up to an Arduino Using the one wire protocol there are two ways to power the device, parasitic and standard power mode. In parasitic mode, only the data and GND lines need to be connected which removes the need for the VCC voltage input. To power the device the data line is used to charge an internal capacitor in the sensor. This is stored for periods when the data line is used to send data and no power is being sent. Depending on the sensor there will be delays while the device is “charged” during which no communication can take place on the data bus. In standard power mode both data, GND and VCC lines are connected to the sensor. By having a permanent voltage line the need to pause communication is removed since power is always provided. Running in standard power mode means that the device can be polled for data at a much faster rate. For my experiments I am going to power the sensor in standard power mode. This will mean I can poll the sensor for the temperature at a much faster rate, helpful for logging data rapidly. To connect the sensor to the Arduino in standard power mode I am connecting GND to the Arduino GND and VCC to the 5 volt line on the Arduino. The data line has a pullup resistor between the 5 volts and the data line. It is recommended to use a 4.7 k resistor between these lines. The data line is also connected to pin 8 on the Arduino. This can be any digital pin on the Arduino so the 1Wire protocol can be used. Programming the Arduino with the DS18B20 temperature sensor To access the DS18B20 temperature sensor I am going to use the OneWire and DallasTemperature Arduino library. The OneWire library allows me to access the OneWire protocol without having to know the specifics of how it works. In addition to this I am going to use the DallasTemperature library as a wrapper around the OneWire library. This works with the OneWire library to specifically work with temperature sensors. #include <OneWire.h> #include <DallasTemperature.h> #define ONE_WIRE_PIN 8 OneWire oneWire(ONE_WIRE_PIN); DallasTemperature sensors(&oneWire); void setup() { Serial.begin(115200); } void loop() { sensors.requestTemperatures(); Serial.println(sensors.getTempCByIndex(0)); delay(1000); } Above I create the OneWire object and pass it by reference (the ampersand, &) in the constructor of the DallasTemperature object. With this I am able to request the temperate of the sensor at any time. In my loop I call requestTemperatures on the sensors object to get the temperatures of all sensors on the 1-Wire bus. This operation will detect the sensors on the bus and request the data from the sensors. Once this function call returns I use the sensors object again to get the temperature in celsius using getTempCByIndex. Here I am asking for the first sensor on the bus (as there is only one) so giving it the parameter 0 (programmers count from 0). Once I have the data I print it out to the serial so that I may see the data change as it continues. Practical Measurements Using python to collect the data from the Arduino I set the sensor up in an air-conditioned room. In this room the air conditioning was set to 23C. During the period of the experiment, it was cold outside but was slowly warmed during the day by other people in the room. Here you can see that over the period of the day the temperate was slowly increasing. The DS18B20 temperature sensor has a high resolution and does not fluctuate between temperatures. This ensures that the readings while changing, were stable and slowly increasing. Previous temperature sensors I have tested, DHT11, DHT22 has problems where the temperature would fluctuate between two values however this does not seem as apparent for this sensor. The precision of the sensor shows a gradual increase in temperature which is good to see the consistency of the data. In the future, I will look to compare this data against other like for like sensors. Final Review One of the advantages of this sensor over many other temperature sensors is that it returns data in celsius by default. This removes the need for a sometimes complex calibration step before using it. The precision level is similar to the DHT22 tested previously. One of the features that sets this apart is the 1-Wire protocol this operates on. This can reduce the need for many IO ports on the Arduino and may be helpful when running larger projects. Overall this sensor is at a similar price point and feature level as the DHT22 temperature sensor. However the unique addition of the 1-Wire bus protocol means this is certainly a useful sensor to have around. Would buy again!
https://chewett.co.uk/blog/745/ds18b20-onewire-temperature-sensor/
CC-MAIN-2020-40
en
refinedweb
ConfigVariableSearchPath¶ from panda3d.core import ConfigVariableSearchPath - class ConfigVariableSearchPath¶ Bases: ConfigVariableBase This is similar to a ConfigVariableList, but it returns its list as a DSearchPath, as a list of directories. You may locally append directories to the end of the search path with the methods here, or prepend them to the beginning. Use these methods to make adjustments to the path; do not attempt to directly modify the const DSearchPathobject returned by getValue(). Unlike other ConfigVariabletypes, local changes (made by calling appendDirectory()and prependDirectory()) are specific to this particular instance of the ConfigVariableSearchPath. A separate instance of the same variable, created by using the same name to the constructor, will not reflect the local changes. Inheritance diagram __init__(name: str, default_value: DSearchPath, description: str, flags: int)¶ appendPath(path: DSearchPath) → None¶ Adds all of the directories listed in the search path to the end of the search list. appendPath(path: str, separator: str) → None Adds all of the directories listed in the search path to the end of the search list. clear() → None¶ Removes all the directories locally added to the search list, and restores it to its original form. clearLocalValue() → bool¶ Removes all the directories locally added to the search list, and restores it to its original form. - property default_value→ DSearchPath¶ findAllFiles(filename: Filename) → Results¶ This variant of findAllFiles()returns the new Results object, instead of filling on in on the parameter list. This is a little more convenient to call from Python. findAllFiles(filename: Filename, results: Results) → int. findFile(filename: Filename) → Filename¶ Searches all the directories in the search list for the indicated file, in order. Returns the full matching pathname of the first match if found, or the empty string if not found. getDefaultValue() → DSearchPath¶ getValue() → DSearchPath¶ prependPath(path: DSearchPath) → None¶ Adds all of the directories listed in the search path to the beginning of the search list. - property value→ DSearchPath¶
https://docs.panda3d.org/1.10/python/reference/panda3d.core.ConfigVariableSearchPath
CC-MAIN-2020-40
en
refinedweb
For the pipeline we developed in the last slide deck, I want you to replace the last ( $bucket) stage with one such that, given the documents docs collected, we can get the following output: from operator import itemgetter print(max(docs, key=itemgetter("years"))) print(min(docs, key=itemgetter("years"))) {'firstname': 'Rita', 'surname': 'Levi-Montalcini', 'years': 103.0} {'firstname': 'Martin Luther', 'surname': 'King Jr.', 'years': 39.0} You may assume that any earlier $project stage has been replaced by an equivalent $addFields stage.
https://campus.datacamp.com/courses/introduction-to-using-mongodb-for-data-science-with-python/aggregation-pipelines-let-the-server-do-it-for-you?ex=14
CC-MAIN-2020-40
en
refinedweb
With the final release of Python 2.5 we thought it was about time Builder AU gave our readers an overview of the popular programming language. Builder AU's Nick Gibson has stepped up to the plate to write this introductory article for beginners. With the final release of Python 2.5 we thought it was about time Builder AU gave our readers an overview of the popular programming language. Builder AU's Nick Gibson has stepped up to the plate to write this introductory article for beginners. Python is a high level, dynamic, object-oriented programming language similiar in some ways to both Java and Perl, which runs on a variety of platforms including Windows, Linux, Unix and mobile devices. Created over 15 years ago as an application specific scripting language, Python is now a serious choice for scripting and dynamic content frameworks. In fact it is being used by some of the world's dynamic programming shops including NASA and Google, among others. Python is also the language behind Web development frameworks Zope and Django. With a healthy growth rate now could be the perfect time to add Python to your tool belt. This quickstart guide will give you an overview of the basics of Python, from variables and control flow statements to exceptions and file input and output. In subsequent articles I'll build upon this foundation and offer more complex and specific code and advice for using Python in real world development. Why learn Python? - It's versatile: Python can be used as a scripting language, the "glue" that sticks other components together in a software system, much in the same way as Perl. It can be used as an applications development language, just like Java or C#. It can be used as a Web development language, similiarly to how you'd use PHP. Whatever you need to do, chances are you can use Python. - It's free: Python is fully open source, meaning that its free to download and completely free to use, throw in a range of free tools and IDE's and you can get started in Python development on a shoestring. - It's stable: Python has been around for more than fifteen years now, which makes it older than Java, and despite regular development it has only just has reached version 2.5. Any code you write now will work with future versions of Python for a long time. - It plays well with others: It's easy to integrate Python code with C or Java code, through SWIG for C and Jython for Java, which allows Python code to call C or Java functions and vice versa. This means that you can incorporate Python in current projects, or embed C into your Python projects whenever you need a little extra speed. - It's easy to learn and use: Python's syntax closely resembles pseudo code, meaning that writing Python code is straightforward. This also makes Python a great choice for rapid application development and prototyping, due to the decrease in development time. - It's easy to read: It's a simple concept, a language that is easy to write should also be easy to read, which makes it easier for Python developers to work together. Okay, enough already, I'm sold. Where do I get it? Easy, in fact if you're running Mac or Unix, chances you've already got it, just pull up a terminal and type "python" to load up the interpreter. If you don't have it, or you're looking to upgrade to the latest version head on over to the download page. Alternatively you could install ActivePython, a binary python distribution that smooths out many of the hassles. There is a graphical installer under most platforms, all that you need to do is click through the dialogues, setting the install path and components. In Windows, you can then start up the interpreter by browsing to its entry in the start menu, or on any system simply by typing 'python' in a terminal. While ActivePython is generally easier to set up, it tends to lag behind official Python releases, and at the time of writing is only available for Python 2.4. Interactive Mode Now it's time to load up the interpreter in interactive mode, this gives you a prompt, similiar to a command line where you can run Python expressions. This lets you run simple expressions without having to write a Python program every time, let's try this out: Python 2.5 (r25:51908, Oct 6 2006, 15:24:43) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World" Hello World >>> The first two lines are the Python environment information, and are specific to my install, so your mileage may vary. Interactive mode is useful for more than just friendly greetings however, it also makes a handy calculator in a pinch, and being part of a programming language allows you to use intermediate variables for more complicated calculations. >>> 2+2 4 >>> 2.223213 * 653.9232 1453.8105592415998 >>> x,y = 5,20 >>> x + y 25 >>> tax = 52000 * (8.5/100) >>> print tax 4420.0 >>> "hello" + "world" 'helloworld' >>> "ring " * 7 'ring ring ring ring ring ring ring ' Another Python type that is useful to know is the list; a sequence of other types in order. Lists can be added and multiplied like strings, and can also be indexed and cut into sublists, called slices: >>> x = [1,2,3,4,5,6,7,8,9,10] >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> x + [11] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> x + [12] * 2 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12] >>> x[0], x[1], x[9] (1, 2, 10) >>> x[1:3], x[4:], x[2:-2] ([2, 3], [5, 6, 7, 8, 9, 10], [3, 4, 5, 6, 7, 8]) >>> x[:] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The interactive mode is good for quick and dirty calculations, but once you start writing anything longer than a couple lines, or you would like to save your programs to use again later, it's time to let it go and start writing python programs. Thankfully this is easy, just type your commands into a .py file and run it with the same command. Control Flow Just like your favourite programming language, Python has all the usual ways of controlling the execution of programs through if, while and for statements. In Python, an if statement looks like this: if a > b: print a else: print b You'll see that unlike languages such as C or Java, Python does not use braces to group statements together. Instead statements are grouped together by how far they are indented from the margin, the body of a statement extends for as long as there are lines below it with the same or greater indentation. x = 3 y = 4 if x > y: x = x + 1 y = y + 1 For example, in the above code x = 3 and y = 4 at the end of the program. x = 3 y = 4 if x > y: x = x + 1 y = y + 1 In the second example, however, y finishes equal to 5. Python also has loops, both of the while and for variety. While loops are straightforward: while a > b: a = a + 1 For loops work a little differently from what you might be used to from programming in other languages, rather than increasing a counter they iterate over sucessive items in a sequence, similiar to a Perl or PHP foreach. If you do need to have that counter its no problem, you can use the built-in range function to generate a list of numbers like so: for i in range(10): print i If you need it, you can have finer control over your loops in Python by using either break or continue statements. A continue statement jumps execution to the top of the loop, whilst a break statement finishes the loop prematurely. for x in range(10): if x % 2 == 0: continue if x > 6: break; print x This code will produce the following output: 1 3 5 A real program: cat Now we almost have the tools at our disposal to write a complete, albeit small, program, such as the common unix filter cat (or type in Windows). cat takes the names of text files as arguments and prints their contents, or if no filenames are given, repeats user input back into the terminal. Before we can write this program however, we need to introduce a few new things: Opening and reading files. In Python files are objects like any other type, and have methods for reading and writing. Say for example we have a file called lines.txt which contains the following: line1 line2 line3 There are two main ways we can view the contents of this file, by character or by line. The following code demonstrates the difference: >>> lines1 = file("lines.txt") >>> lines1.read() 'line1\nline2\nline3\n' >>> lines2 = file("lines.txt") >>> lines2.readlines() ['line1\n', 'line2\n', 'line3\n'] The read() method of a file object reads the file into a string, whilst the readlines() method returns a list of strings, one per line. It is possible to have finer control over file objects, for example reading less than the entire file into memory at once, for more information see the python library documentation (). Importing modules and querying command line arguments. Python comes with a wide variety of library modules containing functions for commonly used tasks, such as string and text processing, support for common internet protocols, operating system operations and file compression - a complete list of standard library modules can be found here. In order to use these functions you must import their module into your programs namespace, like so: >>> import math >>> math.sin(math.radians(60)) 0.8660254037844386 In this example you can see that we refer to the imported functions by their module name (ie. math.sin). If you are planning to use a module a lot and don't want to go to the trouble of typing it's module name every time you use it then you can import the module like this: >>> from math import * >>> sin(radians(60)) 0.8660254037844386 Access to command line arguments is in another module: sys, which provides access to the python interpreter. Command line arguments are kept in a list in this module called argv, the following example demonstrates a program that simply prints out all the command line arguments one per line. import sys for argument in sys.argv: print argument This produces the following output when run with multiple arguments, the first argument is always the name of the script. % python args.py many command line arguments args.py many command line arguments Input from the console It seems maybe a little archaic in the era of GUIs and Web delivered content, but console input is a necessity for any program that is intended to be used with pipes. Python has a number of methods for dealing with input depending on the amount of control you need over the standard input buffer, however for most purposes a simple call to raw_input() will do. raw_input() works just like a readline in C or Java, capturing each character until a newline and returning a string containing them, like so: name = raw_input() print "Hello ", name Error handling with exceptions When you're a programmer, runtime errors are a fact of life; even the best and most robust code can be susceptible to user error, hardware failures or simply conditions you haven't thought of. For this reason, Python, like most modern languages, provides runtime error handling via exceptions. Exceptions have the advantage that they can be raised at one level of the program and then caught further up the stack, meaning that errors that may be irretrievable at a deep level but can be dealt with elsewhere need not crash the program. Using exceptions in Python is simple: try: filename = raw_input() filehandle = file(filename) print len(filehandle.readlines()) except EOFErrror: print "No filename specified" except IOError: print filename, ": cannot be opened" In this example, a block of code is placed inside a try statement, indicating that exceptions may be raised during the execution of the block. Then two types of exceptions are caught, the first EOFError, is raised when the raw_input() call reaches an end of line character before a newline, the second, IOError is raised when there is a problem opening the file. In either case if an exception is raised then the line that prints the number of lines in the file will not be reached. If any other exceptions are raised other than the two named, then they will be passed up to a higher level of the stack. Exceptions are such a clean way to deal with runtime errors that soon enough you'll be wanting to raise them in your own functions, and you'll be pleased to know that this is easy enough in Python. try: raise ValueError, "Invalid type" except ValueError: print "Exception Caught" The Final Product Now that you've got all the tools at your disposal to write our filter. Let's take a look at the program in full first, before reading on, put your new knowledge to use by working out what each line does: import sys if len(sys.argv) The program is simple, if there are no command line arguments (except for the script name, of course), then the program starts reading lines from the console until an interrupt is given. If there are command line arguments, then they are opened and printed in order. So there you have it, Python in a nutshell. For my next article I'll be walking you through the development of a Python program for finding all of the images used on a web page. If you'd like to suggest a topic for me to cover on Python drop me a line at nick.gibson@builderau.com.au.
https://www.techrepublic.com/article/a-quick-start-to-python/
CC-MAIN-2022-05
en
refinedweb