text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Uncyclopedia talk:Report a problem From Uncyclopedia, the content-free encyclopedia Revision as of 13:21, March 25, 2014 by PuppyOnTheRadio (talk | contribs) edit Wilde Quote I was wondering if there was a Oscar Wilde template, similar to the random stub templates, to generate random Wilde quotes ? It would seem like a natural place for the Report a problem page. 70.88.218.145 21:40, 16 Sep 2005 (UTC) - Template:Wilde Stub is kind of random, not what you had in mind though I suppose. --Splaka 21:44, 16 Sep 2005 (UTC) - You could create a template like the following (edit to see how it works) --The Right Honourable Maj Sir Elvis UmP KUN FIC MDA VFH Bur. CM and bars UGM F@H (Petition) 21:50, 16 Sep 2005 (UTC) - On second thought: A template would seem to be counterproductive for this, as each page has different requirements for the content of the random quote. Better to just insert the randomness on the page itself (using the hacked together random code Algorithm made (see the source of the above template link)), or on the Wilde: namespace page (I edited Wilde:Tomato as an example, see the code there). --Splaka 21:51, 16 Sep 2005 (UTC) Oops, edit conflict with Elvis, heh. - Thanks for the help. I've put some funny and not so funny random quotes in. 134.241.43.254 00:45, 17 Sep 2005 (UTC) edit Template Help:Infoboxes --SockMob 22:32, 21 March 2009 (UTC)Why is it that, I can't just make a custom Infobox, I create a custom one. And it comes out like the last one I had on my page?
http://uncyclopedia.wikia.com/wiki/Uncyclopedia_talk:Report_a_problem?oldid=5785348
CC-MAIN-2015-27
refinedweb
280
64.54
Maintained by Suyeol Jeon. Not yet implemented functions in Swift. This library is tiny but you must be looking for somebody to make this open sourced library Dictionary.map() and Dictionary.flatMap() which returns Dictionary. let dict: [String: Int] = ["a": 1, "b": 2, "c": 3] let result = dict.map { key, value in return (key, value * 2) } print(result) // ["a": 2, "b": 4, "c": 6] filterNil() on Collection and Dictionary. let dict: [String: Any?] = [ "some": 123, "none": nil, ] let result = dict.filterNil() print(result) // ["some": 123] Using CocoaPods: pod 'Yet' Using Carthage: github "devxoul/Yet" ~> 0.2 Using Swift Package Manager: let package = Package( name: "MyAwesomeProject", targets: [], dependencies: [ .Package(url: " majorVersion: 0) ] ) Any discussions and pull requests are welcomed Use $ swift generate-xcodeproj to generate Xcode project for development. Yet is under MIT license. See the LICENSE for more info.
https://cocoapods.org/pods/Yet
CC-MAIN-2022-21
refinedweb
139
62.14
Python Program for Maneuvering a cave (TCS Codevita) | PrepInsta Maneuvering a Cave Problem Maneuvering a Cave Problem is a 2-D array manipulation problem, which was asked in this year TCS CodeVita 2020 Season 9 coding competition, as a sample question. It is a pretty tough problem, but one can solve it if he has good command on data structures and dynamic programming. Here we have provided a Python Solution for this problem. Problem Description The task is to count all the possible paths from top left to bottom right of a m x n matrix with the constraints that from each cell you can either move only to right or down. Input: - First line consists of T test cases. First line of every test case consists of N and M, denoting the number of rows and number of columns respectively. Output: - Single line output i.e count of all the possible paths from top left to bottom right of a m x n matrix.. Constraints: - 1<=T<=100 - 1<=N<=100 - 1<=M<=100 Python Code def calculate(a, b): if a == 1 or b == 1: return 1 else: return calculate(a - 1, b) + calculate(a, b - 1) result = [] test = int(input()) for i in range(test): a, b = map(int,input().split()) result.append(calculate(a, b)) for i in result: print(i,end=" ") Output: 2 3 3 4 4 6 20 Login/Signup to comment 6 comments on “Python Program for Maneuvering a cave (TCS Codevita) | PrepInsta” #Here I’m coded only for Square matrix Test_case = int(input()) matrix_list = [list(map(int, input().split())) for _ in range(Test_case)] Ans = [] for i in range(Test_case): node = ((matrix_list[i][0]) – 1) + ((matrix_list[i][1]) – 1) reduce = (node + (node – 1)) * matrix_list[i][0] Ans.append(abs((2 ** node) – reduce)) for j in range(Test_case): print(Ans[j], end=’ ‘) Thanks for contributing the code Sukesh This code will run for Larger test cases : Dynamic programming Bottom-up approach : a = int(input()) b = int(input()) def op(a,b): dp = [[0 for i in range(b+1)] for j in range(a+1)] for i in range(a+1): for j in range(b+1): if i==1 or j==1: dp[i][j] = 1 else: dp[i][j] = dp[i-1][j]+dp[i][j-1] return dp[a][b] print(op(a,b)) Thanks Mohammad for contributing the code This might show TLE error No Vilo, it won’t. Try executing the code on an online compiler, as sometimes the IDE may have been customized and show errors
https://prepinsta.com/tcs-codevita/python-program-for-maneuvering-a-cave/
CC-MAIN-2020-40
refinedweb
429
52.12
The .NET built-in compression library has a nifty implementation of the Deflate algorithm. This provides simple compression and decompression tools via the use of Streams. These are great if your app is talking to a web-site that uses compression, or if you wish to compress a single file. If you want to compress multiple files into an archive though, you either have to do a lot of work, or utilize a third-party library. I recently hit a situation where I needed to compress a lot of little files into one file - I also could not use a third party library. This left me with one option: Implement my own archive file system entirely within .NET. I needed to be able to search the archive for files and extract them individually. I did not need to open the archive with another system, so I had no dependency on any existing file format, giving me free reign to develop my own. Now I have a little spare time and I thought I would share the results. My first idea was to build a class that would contain a list of ArchiveFile objects. The ArchiveFile objects would contain details of the file, and a byte array filled with the contents of the file. I would store and compress the data by serializing the class through a compression stream. ArchiveFile I even implemented this solution (I left it in the library as the TinyArchive class) - I was going to use it, but realised it had a fatal flaw: the entire object and all the uncompressed data would need to be loaded into memory. That put definite limits on the maximum size of the archive. TinyArchive Back I went to the drawing board. I could not use the compressed binary serialization code I had written to handle the file structure, because it could not selectively load parts of the archive file. I would need to create my own. I wanted to be able to read just the details of the files in the archive, then use those details to be able to selectively read specific portions of the files. I also realised, I could not put all the indexes at the front of the file, because this would make it very difficult to add more files into the archive. I settled for starting with two bytes that contained the length of the next section of the archive. That next section would be details of the compressed file: its name and its length in the archive, followed immediately by the compressed contents of the file. The next file would be added in an identical manner. The code would read in the first two bytes, convert that to a ushort, and use that value to specify the length of the next block of bytes read in from the archive, which are the index details. From the index, it gets the length of the compressed data block, which it uses to skip to the next index. ushort In this fashion, the reader can catalogue the entire archive very quickly. It builds a searchable index that specifies the start byte index number and length of every file compressed into the archive. Extracting a compressed file is just a matter of opening a file-stream on the archive file, seeking to the index location of the file you wish to extract, then reading in the correct number of bytes. The compressed bytes are then expanded to their original size through the DeflateStream class. DeflateStream The next most difficult part was removing files from the archive. It wasn't required for my initial application, but I felt it was required to make the library complete. I had a lot of trouble with this, and I'm still not entirely happy with my solution. The remove method basically creates a copy of the current archive in a temporary file location, skipping those files it was told to remove. It then deletes the original and moves the copy into its place. Supplied in the Visual Studio project attached is a demo archive forms application. It is a quick, basic implementation of the multiple file archive. You can create archives, add files to it, extract them, and remove them. You can navigate the files in the archive with a tree-view control. The main class handling the archive is StreamingArchiveFile. StreamingArchiveFile The below code shows how to create a new archive, and add a folder of files into it: // create a new or access an existing streaming archive file: StreamingArchiveFile arc = new StreamingArchiveFile(@"C:\Temp\streamingArchive.arc"); // now iterate through the files in a specific directory and add them to the archive: foreach (string fileName in Directory.GetFiles(@"C:\Temp\Test\", "*.*")) { // add the file arc.AddFile(new ArchiveFile(fileName)); } Extracting files: this clip shows how to enumerate the files in an archive, extract them to a temp folder, and shell open them. // open the existing archive file: StreamingArchiveFile arc = new StreamingArchiveFile(@"C:\Temp\streamingArchive.arc"); // iterate the files in the archive: foreach (string fileName in arc.FileIndex.IndexedFileNames) { // write the name of the file Debug.Print("File: " + fileName); // extract the file: ArchiveFile file = arc.GetFile(fileName); // save it to disk: String tempFileName = Path.GetTempPath() + "\\" + file.Name; file.SaveAs(tempFileName); // open the file: Process.Start(tempFileName); } There is also a search method that uses Regular Expressions and LINQ to find files in the archive: /// <summary> /// search the index for a file matching the expression. /// </summary> /// <param name="fileNameExpression"></param> /// <returns></returns> public IEnumerable<ArchiveFileIndex> Search(String fileNameExpression) { return (from file in _fileIndex where Regex.IsMatch(file.FileName, fileNameExpression) select file); } To really see how the archive can be used, check out the code in the FrmStreamingArchiveUI form. FrmStreamingArchiveUI .NET provides two compression classes: GZipStream and DeflateStream. They both use the deflate algorithm, the GZipStream class is actually built on the DeflateStream, and adds some additional header information and CRC checks. GZipStream I have used the DeflateStream class because it is quicker and leaves a smaller footprint. The files are stored in the archive as ArchiveFile objects. This object stores properties of the file, like creation date and size, as well as a byte array filled with the actual contents of the file. The ArchiveFile object is serialized into the archive using the class TinySerializer. This was developed to produce the smallest possible serialization of a class. It has an optional custom SerializationBinder that strips out the AssemblyName and TypeName (this means that the object you are serializing must contain only simple objects as fields or properties) and it can serialize or de-serialize through the Deflate stream class to provide quick and easy compression/decompression. TinySerializer SerializationBinder Deflate /// <summary> /// deserialize an object from compressed data. /// </summary> /// <typeparam name="T">the type of object to deserialize</typeparam> /// <param name="compressedInputStream">stream of compressed /// data containing an object to deserialize</param> /// <returns></returns> public static T DeSerializeCompressed<T>(Stream compressedInputStream, bool useCustomBinder = false) { // construct the binary formatter and assign the custom binder: BinaryFormatter formatter = new BinaryFormatter(); if (useCustomBinder) formatter.Binder = new TinySerializer(typeof(T)); // read the stream through a GZip decompression stream. using (DeflateStream decompressionStream = new DeflateStream(compressedInputStream, CompressionMode.Decompress, true)) { // deserialize to an object: object graph = formatter.Deserialize(decompressionStream); // check the type is correct and return. if (graph is T) return (T)graph; else throw new ArgumentException("Invalid.
http://www.codeproject.com/Articles/313790/NET-Native-Multiple-File-Compression?PageFlow=FixedWidth
CC-MAIN-2015-40
refinedweb
1,225
53.61
Every time my co-worker and I create a new project using EF6 ( Even tried EF5), after I save the .edmx diagram and try to compile I get a ton of errors. One thing that has caught my eye is the fact the using directives are being included after the namespace. namespace EntityIsCool{ using System; using System.Collections.Generic; } If I move the directives back to the top, everything is copasetic, otherwise compile error city. I know the C# doesn't care where the using directives are in the code,as I tried to move them around in other classes without issues. It only happens with the POCO generated stuff in EF. I tried changing the code generation to legacy instead of the T4, but that makes it worse as it cannot find the Dbcontext stuff. I was able to start up VS2010, create a EF4 project, import it into VS2013 and had zero issues( with EF4). I have the most recent Entity Toolset installed ( 6.1.3), and have tried both EF5 and EF6 code generation. Any help would be great. by nopcodex90x90 via /r/csharp
https://howtocode.net/2015/09/entity-6-poco-code-generation-failing/
CC-MAIN-2018-09
refinedweb
187
74.39
First, this is more for experimentation and learning at this point and I know that I can just pass the parameter in directly. def eval(xs: List[Int], message: => String) = { xs.foreach{x=> implicit val z = x println(message) } } def test()(implicit x : Int) = { if(x == 1) "1" else "2" } eval(List(1, 2), test)//error: could not find implicit value for parameter x Is this even possible and I am just not using implicits properly for the situation? Or is it not possible at all? Implicit parameters are resolved at compile time. By-name parameter captures the values it accesses at the scope where it is passed in. At runtime, there isn't any implicit concept. eval(List(1, 2), test) This needs to be fully resolved at compile time. The Scala compiler has to figure out all the parameters it needs to call test. It will try to find out a implicit Int variable at the scope where eval is called. In your case, the implicit value defined in eval won't have any effect at runtime. How to get an implicit value is always resolved at compile time. There's no such thing as a Function object with an implicit parameter. To get a callable object from a method with implicit parameters, you need to make them explicit. If you really wanted to, you could then wrap that in another method that uses implicits: def eval(xs: List[Int], message: Int => String) = { def msg(implicit x: Int) = message(x) xs.foreach { x => implicit val z = x println(msg) } } eval(List(1, 2), test()(_)) You probably won't gain anything by doing that. Implicits aren't an alternative to passing in parameters. They're an alternative to explicitly typing in the parameters that you're passing in. The actual passing in, however, works the same way. I assume that you want the implicit parameter x (in test's signature) to be filled by the implicit variable z (in eval). In this case, z is out of the scope within which x can see z. Implicit resolution is done statically by compiler, so runtime data flow never affect it. To learn more about the scope, Where do Implicits Come From? in this answer is helpful. But you can still use implicit for that purpose like this. (I think it is misuse of implicit so only for demonstration.) var z = 0 implicit def zz: Int = z def eval(xs: List[Int], message: => String) = { xs.foreach{ x => z = x println(message) } } def test()(implicit x : Int) = { if(x == 1) "1" else "2" } eval(List(1, 2), test)
http://www.dlxedu.com/askdetail/3/c1f2c8f6b629b7ed32ed6347e48935fb.html
CC-MAIN-2018-51
refinedweb
437
65.42
] Resco (7) John O Donnell(5) Anand Kumar(4) Ravi Shekhar(3) Shail 0(3) Jigar Desai(3) Dipal Choksi(3) Jaydip Trivedi(2) Jean Paul(2) Priti Kumari(2) Ramesh Sengamalai(2) Microsoft Press(2) Divya Saxena(2) Mike Gold(2) Srinivas Sampath(2) Afzaal Ahmad Zeeshan(1) Najuma Mahamuth(1) Prasham Sabadra(1) Raj Kumar(1) Gagan Sharma(1) Vinoth Rajendran(1) Anas Chaudhary(1) Krishna Kumar(1) Vithal Wadje(1) Akash Bhimani(1) Jay Parekh(1) Deepak Sharma(1) Abhimanyu K Vatsa(1) Destin joy(1) Azim Zahir(1) Karthikeyan Anbarasan(1) Dhananjay Kumar (1) Shirsendu Nandi(1) A V Mahesh(1) Manas Patnaik(1) Mohammad Elsheimy(1) Nipun Tomar(1) Dharmendra Gaur(1) Senthilkumar (1) Shivprasad (1) Kalyan Bandarupalli(1) John Charles Olamendy(1) Clint Batman(1) Moustafa Arafa(1) Danish Hameed(1) pinto.philip (1) klaus_salchner (1) Amit Kumar Agrawal(1) Shailaja (1) Resources No resource found How To Select .NET Edition For Your Projects Dec 13, 2016. Here, you will learn about the selection of .NET edition for your projects. Basics Of Azure Active Directory Dec 09, 2016. This article will help you to know about Azure Active Directory, its editions, the process of creating an Azure Active Directory, Users, Groups and adding members to. Linking ASP.NET MVC Website With Facebook, Twitter, C# Corner Using Visual Studio Mar 09, 2016. This article will help beginners to put social links and icons on ASP.NET websites with Model View Controller (MVC) architecture using Visual Studio 2015 Community Edition in easy simple steps. Upgrade Windows 10 Home To Windows 10 Pro Jan 15, 2016. In this article you will learn how to upgrade from Windows 10 Home edition to Windows 10 pro. Start With MVC Architecture In ASP.NET And Visual Studio 2015 Community Edition Jan 01, 2016. In this article you will learn how to start with MVC Architecture in ASP.NET and Visual Studio 2015 Community Edition. SQL Server 2014 Installation Steps Dec 12, 2015. This article provides a step-by-step procedure for installing a new instance of SQL Server 2014 Enterprise Edition by SQL Server setup installation wizard. Visual Studio 2015 Tips Nov 16, 2015. In this article, I have covered VS 2015 editor tips. Some of the tips already available in the older edition and some of the tips are new to VS 2015. Features of Java 8 Jan 13, 2015. This article explains additional features of Java SE 8. How to Create Database in Windows CE (Compact Edition) OS Operated Device Jul 27, 2014. This article will help you to learn how to create a Database (sdf file) in a Windows CE (Compact Edition) operating system device. DML Operation in WindowsCE (Compact Edition) Device Application With sdf Database Jul 27, 2014. This article will help you to do DML operations in a sdf file in a Windows CE device application. Use of SqlConnectionCE in Smart Device Application Jul 22, 2014. This article will tell you the basics of Smart device applications and some information about SQL Server Compact Edition (SQL Server CE). Sync Feature in SharePoint 2013 Jun 07, 2014. In this article we can explore the Sync feature of SharePoint. This feature is available in SharePoint 2013 and in the online edition. Data Analysis and Chart Creation From SQL Server using QlikView Mar 28, 2014. Using the By QlikView personal edition tool you can analyze data in sources such as Excel Spreadsheets, databases, or text files. Editions of Visual Studio 2012 Jan 17, 2014. In this article we will learn about the various editions of Visual Studio 2012. Use Local Database File in C# Windows Application Jan 08, 2014. Here I will explain how to use a SQL Server Compact (SDF) local database file in your Windows application. CURD Operations in SQL Server Compact Database File in C# Windows Application Jan 08, 2014. Here I will explain how to use a SQL Server Compact Database (SDF) file in your C# Windows application. Introduction to Visual Studio Oct 15, 2013. This article is an introduction into C#. Logging Using Log4net in Compact Framework 2.0 in Visual Studio 2008 Jun 08, 2013. This article will show you how you can use log4net.dll to do logging in a Compact Framework 2.0 application. Connecting to Oracle Database From Windows Forms Application Using C# Jan 10, 2013. In this article I will explain how to connect to an Oracle database from a Windows application using C#. Using Map in Pocket PC Application in VB.NET Nov 10, 2012. GPS enabled applications are a good example of using a Pocket PC to locate a Pocket PC user. This attached application is a location based Pocket PC application developed using .NET compact framework... Introduction to Pocket PC with VB.NET Nov 09, 2012. At the time of writing (Oct 2001) Microsoft has shipped Pocket PC 2002 and also has just released the Visual Studio .NET. Entity Framework Console Applications With SQL Server Compact Oct 08, 2012. Microsoft SQL Server Compact Edition is an embedded database system that allows us to integrate it in our Web, Desktop and Mobile applications. Installation Feb 11, 2012. In this article we can proceed with the installation of SharePoint 2010. Depending on your operating system and edition of SharePoint the installation files vary. XML SchemaValidator Dec 01, 2011. This article shows how to validate an XML document against a schema using C#. For demonstration of this, I have created a GUI application using Visual Studio 2005 Express Edition. DataBinding in WPF using Sql Server Compact Aug 18, 2011. This article will help you to create WPF browser application with basic technique of data binding using Sql Server compact 3.5 sp1, so without waiting anymore time let’s start our first WPF browser application.. Different Data Base Editions in SQL Azure Jun 06, 2011. There are two Data Base Editions in SQL Azure. Index in SQL Server 2008 May 27, 2011. In this article I will describe how to make a Cluster Index, Unique Index and Normal Index in SQL Server 2008 Express editions. Resco MobileForms Toolkit, Android Edition May 13, 2011. The article presents Resco MobileForms Toolkit, Android Edition. Besides the brief characteristics of the included components special attention is devoted to the writing of LOB applications using master-detail concept. DataGrid in WPF using Sql Server Compact Apr 23, 2011. In this article I would like to show the simple way of data binding to datagrid in WPF.. An Introduction to SQL Server Compact Edition (SQLCE 4.0) Feb 23, 2011. About SQLCE a embedded database from Microsoft for Desktop based application,Mobile Device and ASP.Net , its latest feature and how to . Configuring ASP.NET with IIS Jan 21, 2011... Add Validation Rule in Visual Studio 2008 Team system test Edition Dec 27, 2010. In this Article we are going to describe how to add validation rules to a Web test. Connection Strings for SQL Server Compact Edition Dec 22, 2010. SQL Server Compact Edition (SQL CE) is a compact relational database produced by Microsoft for applications that run on mobile devices and desktops. Introduction to Microsoft Visual Studio Team System 2008 Test Edition Dec 21, 2010. This article discusses Microsoft Visual Studio Team System 2008 (Test Edition), an integrated development environment provided with Visual Studio and it's comparison and what’s new from Microsoft Visual Studio 2005. Creating, Recording & Running Web Project using Visual Studio 2008 Team System Test Edition Dec 20, 2010. This Article explains how to create a web test using VSTS 2008 test edition. Chapter 1: SQL Server 2008 R2 Editions and Enhancements Nov 22, 2010.. When mobile solutions play a crucial role, bet on well-proved quality Apr 13, 2010. When targeting Windows Mobile platform, use of 3rd party controls is necessary. Let's find out what the most complete set of .NET Compact Framework components from Resco can offer. . Sql Server 2005 features - Part II Sep 29, 2009. In this article i have explained about the features introduced in the sql server 2005 edition. Automating Compilation for VS Web Developer 2008 Express edition Mar 21, 2009. This tutorial will discuss how we can use the aspnet_compiler.exe to generate DLL for web projects developed in VS 2008 web developer express edition.. SQL Server Compact and LINQ Feb 13, 2009. In this article, I will cover how to access data in SQL Server Compact databases (.sdf file) using new development technologies such as LINQ. Flexible KeyBoard Control for Mobile Applications Oct 21, 2008. This article describes you how to create a customizable keyboard control by using Resco mobile forms toolkit. Implementing a Custom Zoom Bar with Map Suite Aug 29, 2008. this article I will show you how to build a custom zoom bar using the prebuilt zoom levels defined within Map Suite Web Edition (with concepts that also apply to Map Suite Desktop Edition). Grid control on .NET Compact Framework Aug 27, 2008. In this article I will show some typical issues one can encounter when developing mobile applications and how to solve them using a grid control that was designed for mobile devices from the scratch. Visualize data on a mobile device using Visual Studio May 09, 2008. This article is about displaying data in mobile applications built on .NET Compact Framework platform. It demonstrates several typical data structures and their visualization on a small display of a mobile device Creating a filtered list of customers on a mobile device Mar 05, 2008. The article demonstrates how to create a sophisticated filtered customer list on a Windows Mobile device using Resco AdvancedList control.. Best Practices of Compact Framework May 17, 2006. This shares a few recommendations for use in our day to day development of Compact Framework applications.. Databinding with Pocket PC Nov 11, 2005. This articles shows how to write data-driven applications for Pocket PC using ADO.NET and .NET Compact Framework. AI: Using the Compact Genetic Algorithm to Compute Square Roots in C# Oct 09, 2005. This article describes the Compact Genetic Algorithm (cGA) and how it can be used to calculate the square root of a floating point number. Mobile Web Application Secret Sep 12, 2005. This article gives you a clear idea how an ASP.NET Web Application rendering works differently on hand held devices than running Web Applications on normal machines. Programming with .NET Compact Framework 1.0 and SQL CE 2.0 : Part II Aug 11, 2005. In this article I am going to talk about garbage collection and JIT process in .NET compact framework and what are the differences between these two model of framework. Programming with .NET Compact Framework 1.0 and SQL CE 2.0 : Part I Jul 26, 2005. This article covers various major components for developing application for PDA .Before developing application targets to PDA device its very important to understand .NET compact framework, supported/unsupported features for smart device development, Difference between .NET compact framework and .NET framework and of course SQL CE if you want to store application data in SQL database. Pocket PC 2003 : Saving the Signature as a Bitmap Feb 15, 2005. The System.Drawing.Graphics namespace is commonly used for almost any forms in the desktop framework, hence it has got lots of facilities to draw any kind of image on to the device context.). Building Applications with .NET Compact Framework Jun 09, 2004. In this article, author explains various components of Microsoft .NET Compact Framework and how to build compact device applications. Using Map in a Pocket PC Application Apr 19, 2004. GPS enabled applications are a good example of using a Pocket PC to locate a Pocket PC user. This attached application is a location based Pocket PC application developed using .NET compact framework. Using the .NET compact Framework Oct 01, 2003. In this article, we will see how to write a simple .NET Compact Framework application and deploy it onto a device. This article provides a step-by-step instruction on how to write the application. Integrating Web Services with SDE Oct 01, 2003. In this article, we will see how to integrate Web services with a smart device application. Developing Pocket PC Applications using .NET Framework Sep 02, 2003. This article presents the rudimentary knowledge that a developer requires for developing Pocket PC Applications using .Net Compact Framework. Invoking Unmanaged DLL Functions from Compact Framework for Pocket PC Jan 04, 2003. In this example we will use the Compact Framework to create a program containing a launch pad for the Pocket PC. Data Access Overview for Smart Device Extensions Dec 23, 2002. In this article we will take a brief look at ata Access for Smart Device Extensions. Scramble for Pocket PC Sep 19, 2002. This article shows you how to write Scramble for Pocket PC. Unit Conversion Tool for Pocket PC with Compact Framework May 22, 2002. I have created a Unit conversion tool to calculate conversion from 16 different types. Getting NASDAQ Quotes with a Pocket PC May 22, 2002. If you have been lucky enough to get the Compact Framework or Smart devices extension beta for April 2002 you may be wondering what you can do with it. Display and Hiding SIP on a Pocket PC May 21, 2002. When you get your hands on a Pocket PC for the first time you have to wonder just how the heck do you enter information? Introduction to Pocket PC Oct 31, 2001. At the time of writing (Oct 2001) Microsoft has shipped Pocket PC 2002 and also has just released the Visual Studio .NET add-on for Pocket PC called the compact framework. About Compact-Edition NA File APIs for .NET Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!
http://www.c-sharpcorner.com/tags/Compact-Edition
CC-MAIN-2017-09
refinedweb
2,314
58.48
OpenCV 2.4.3rc Samples do not run in NDK r8b I am using windows and trying to build OpenCV Tutorial 3 - Add Native OpenCV in OpenCV4Android 2.4.3. I have followed all the instructions in the following two tutorials I am trying to build the tutorial 3 in Eclipse and getting the following in console, 17:45:42 * Auto Build of configuration Default for project OpenCV Tutorial 3 - Add Native OpenCV * "C:\android-ndk-r8b\ndk-build.cmd" "Compile++ thumb : native_sample <= jni_part.cpp In file included from jni/jni_part.cpp:1:0: C:/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/jni.h:592:13: note: the mangling of 'va_list' has changed in GCC 4.4 SharedLibrary : libnative_sample.so Install : libnative_sample.so => libs/armeabi-v7a/libnative_sample.so 17:45:44 Build Finished (took 2s.247ms) The libnative_sample.so file has been correctly produced. Still, I am getting error that "There is error in the project". Then I've gone to jni_part.cpp and it is showing that it is not getting the header "vector". and it is not understanding the namespace "std". It is also not being able to find FastFeatureDetector. How can I compile it and run it? Hello @Chayan, I am also in OpenCV Tutorial 3 and produced lot of errors. I know you can help me about my problem. How did you resolve the error "Cannot run the program ndk-build.cmd: The system cannot find the file specified" in Tutorial 3? Please help. My original post
https://answers.opencv.org/question/3713/opencv-243rc-samples-do-not-run-in-ndk-r8b/
CC-MAIN-2020-29
refinedweb
254
61.43
As we previously suggested in P0063R0, it would be nice to have a real interoperability story for C atomics and C++ atomics. In the interest of time, and since it appeared to be less essential and more controversial than the rest of that proposal, this suggestion was not pursued further in later revisions of that paper. Nonetheless, it remains a gaping hole in the interoperability story between C and C++. The solution proposed here is based on one that has been used by Android for several years. It is desirable to make C language header files directly usable by C++ code. It is increasingly common for such header files to include declarations that rely on atomics. For example, a header may wish to declare a function that provides saturating ("clamped") addition on atomic integers. This can easily be implemented in the common subset of C and C++, except that we have no convenient and portable way to include the definition of names such as atomic_int, that are defined in <atomic> in C++ and in <stdatomic.h> in C. The best we can currently do in portable code is to use an explicit preprocessor test followed by conditional inclusion of either <atomic> or <stdatomic.h>. In the former case, we then have to add using declarations to inject the required types and functions into the global namespace. Thus we end up with something like #ifdef __cplusplus #include <atomic> using std::atomic_int; using std::memory_order; using std::memory_order_acquire; ... #else /* not __cplusplus */ #include <stdatomic.h> #endif /* __cplusplus */ ... int saturated_fetch_add(atomic_int *loc, int value, memory_order order); This approach relies on the currently implicit assumption or wish that the representation of C and C++ atomics are compatible. Although certainly possible, this is very clumsy compared to the level of interoperability we normally provide; for other language features we commonly provide a C header file that can be included from C++, and provides the necessary declarations. Here we propose to do the same for atomics. The story here is somewhat confused by the fact that most of the other .h compatibility headers currently only appear in the deprecated features section under D.5 C standard library headers [depr.c.headers]. A recent paper, P0619 proposes to undeprecate them. We strongly agree with this paper that the current deprecation of these headers does not reflect reality. Many of them are widely used and heavily relied upon. This proposal assumes that at least some of those headers will be preserved. C and C++ atomics were originally designed together. The original design ensured that the non-generic pieces of the C++ atomics library were usable as a C library. This interoperability story became less clear as a result of several later decisions: _Atomictype qualifier, and the _Atomic(T)type specifier. This happened late enough in the C++11 standardization cycle that there wasn't much of an opportunity for C++ adjustments. stdatomic.hin a C++ program. Shortly before finalizing C++11, we briefly discussed making _Atomic usable from C++ by defining a macro _Atomic(T) as std::atomic<T>. An earlier version of this proposal, approved by SG1, did the same. However LEWG did not appear to approve of defining an implementer-namespace name like _Atomic(T) in a C++ header. (See below for details.) Hence this version of the proposal uses a different name, on the assuption that WG14 would be willing to introduce a corresponding name for C. The latter idea was floated on the WG14 reflector, and not immediately shot down. That clearly does not yet amount to approval. But so far we have a weak indication that it may be preferred over the alternative of simply dropping anything like _Atomic from the C and C++ common subset. We propose to add a header stdatomic.h to the C++ standard. This would mirror the identically named C header, and provide comparable functionality. However, instead of defining it in terms of the C header, we propose that it have the following effects: <atomic>header. atomic_generic_type(T)as std::atomic<T>. This assumes that C would correspondingly define atomic_generic_type(T)as _Atomic(T). atomic_... and memory_order... identifiers introduced by the <atomic>header into the global name space. Although this provides functionality very similar to the C header, it is unlikely that it will be exactly the same. As usual, it is the responsibility of the author of a C and C++ shared header to ensure that the code is correct in both languages. This proposal makes no effort to support an equivalent of the C _Atomic type qualifier, as opposed to the type specifier (which is spelled with parentheses). This is intentional; accommodating the qualifier would be a major language change, particularly since it is the only type qualifier that can affect alignment. We believe this is the minimum required to conveniently use atomics in shared headers. Aside from the renaminc of _Atomic, this proposal reflects current practice in Android since the Android Lollipop release in 2014. (See. That uses a single include file shared between C and C++, which may not be the optimal implementation strategy.) In an ideal world, this would be easy to support in various compiler environments. The main requirement is is that C and C++ atomics should be implemented identically and use the same ABI conventions. There is no fundamental reason to do anything differently. Implementing ordering constraints in incompatible ways is already greatly undesirable, in that mixed language programs with memory_order annotations would no longer be sequentially consistent. Using incompatible locking schemes for large atomics would generally double the amount of space required for the lock table, and complicate ABI conventions, with no benefit. Our preliminary experiments with gcc-4.9 found no differences on x86-64, though it did find some seeminly gratuitous alignment differences om ARMv7. Unfortunately later information from Jonathan Wakely and David Goldblatt points out that gcc in fact relies on two separate mechanisms for determining atomics alignment in C and C++, and these differ in some corner cases, since alignment decisions are made by the compiler in one case and the library the other. Although this is nontrivial to change, and requires C++ ABI changes in those corner cases, those changes appear desirable, even independent of this proposal. Some applications already assume compatible C++ and C ABIs for atomics, and those will currently break. And the current approach appears to preclude a consistent ABI between e.g. gcc and clang. There appears to be general agreement that this should be fixed in any case. More discussion can be found at . Thus the implementation effort for meaningful conformance to this proposal will vary between adding a simple header file on one hand, and appreciable changes to the existing atomics alignment logic in either C or C++ on the other. The implementation effort for minimal conformance consists of only the header file, since we can't normatively say anything about C and C++ consistency. <cstdatomic>? We do not believe there is a strong need to introduce a <cstdatomic> that only introduces names into the std:: namespace. The justification for <stdatomic.h> is entirely to support headers shared between C and C++, not to import a C facility into C++. A shared header will not be able to take advantage of names introduced into the std:: namespace. There is an argument that <cstdatomic> should be provided anyway for uniformity. It's not clear that this outweighs the cost of introducing a header that we expect to get essentially no use. There did not appear to be sentiment in SG1 for adding <cstdatomic>. Placement and details of the wording are heavily dependent on the outcome of the P0619 discussion, and whether use of .h headers should remain deprecated. We expect something along the following lines: The above is close to a verbatim reflection of the part of the Android <stdatomic.h> header that is used when compiling C++. R0, with changes that were incorporated into R1, was approved by SG1 in Jacksonville, 6/17/4/10/0. R1 was not discussed in Rapperswil, since LEWG was bandwidth-constrained. R1 was briefly discussed by LEWG in San Diego. LEWG voted mildly against putting "_Atomic(T) ... in the set of tokens that are cross-language compatible" and, in a separate poll, mildly against forwarding to LWG. There was a consensus in favor of "Revise proposal along the lines of `effects equivalent to (the goals of this paper)'". The concerns I heard, both during the meeting, and during a later discussion with Titus Winters were: _Atomicin C++. _Atomic(T)and atomic_intin C++ would yield objects that have member functions, which differs from C. These unfortunately raise some new questions, which we did not have a chance to pursue during the initial discussion: _Atomic. (Since the identifier is in the system namespace, implementations could choose to keep it anyway.) Would this resolve LEWG concerns? Would it reduce SG1 consensus? There is weak evidence that this is unpopular in WG14. _Atomicin C, as proposed in R2. Is this satisfactory for SG1? LEWG? WG14? _Atomicin clang. It is true that clang already assigns a meaning to _Atomic. But it is not clear that this breaks anything, since we would effectively be replacing that with a presumed compatible implementation if stdatomic.his included in C++ code. atomic_intin C++ already contains member functions in C++, which does differ from C. But this seems entirely unavoidable, and was part of the original C/C++ atomics design, which was intended to support the kind of compatibility we're looking for here. Furthermore, we clearly want the standalone C++ atomics functions to be applicable to C-compatible atomics. That requires that C atomics be convertible to atomic<T>, which makes it hard to see how atomic_int, or _Atomic(int), if we keep it, could not have member functions in C++. Changes made to reflect SG1 discussion Jacksonville. SG1 voted 6/17/4/1/0 to advance to to LEWG, but suggested a few changes: usingdeclarations required for the namespace promotion. Note that the SG1 discussion was slightly incorrect in that it overlooked the recent change of memory_oder to an enum class. But in retrospect it's not at all clear that this affects our proposal. It simply adds one more easily avoidable incompatibility between C and C++ usages of the header. Revised the proposal to define atomic_generic_type (placeholder name) instead of _Atomic Added the last section about the LEWG discussion in San Diego.
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0943r2.html
CC-MAIN-2022-33
refinedweb
1,741
55.24
Python is very useful when dealing with mathematical operations. Thanks to its math module which contains so many useful functions. The ceil function is one of the most useful functions of the math module in Python. What is ceil or ceiling function in mathematics? The general example says that ceil of a number is the smallest integer value not less than that number. I know that is confusing. Here is a trick to memorize it and understand better. Ceil stands for the ceiling which means roof (something above). The ceil returns the nearest greater integer value of a number. Here are some examples that explain it. ceil of 3.11 = 4 ceil of 6.89 = 6 ceil of 9.0001 = 10 An interesting example. ceil of -5.99 = -5 because -5 > -5.99 Now you know the usage of ceil, we can create a Python program to calculate ceil value using math module. Ceil function of Math module in Python Here is the general syntax of ceil function in Python. math.ceil(num) The ceil function takes one parameter num. We can pass integer or float as an argument. Here is an example implementation of ceil function. import math #num = int(input("Enter the number to find ceil value: ")) num = 3.11 ceil_value = math.ceil(num) print(ceil_value) 4 The ceil function in Python is part of the math module. Return Type of ceil() function The return of the ceil function is an integer.
https://holycoders.com/python-math-module-ceil-function/
CC-MAIN-2020-34
refinedweb
244
70.6
Notes for Packagers¶ Binary naming¶ Prevent namespace clashes. We suggest renaming all binaries with cyr_ at the front, including renaming the ctl_* to cyr_. The Cyrus team are looking to fix this in the core bundle in upcoming releases so packagers have less to do. Sample configuration files¶ There are several samples of cyrus.conf(5) and imapd.conf(5) located in the doc/examples directory of the distribution tarball. Please install these to your preferred documentation directory (i.e. /usr/share/doc/cyrus-imapd) as a reference for your users. Predefined configurations¶ The configuration file for master: cyrus.conf¶ When installing a predefined cyrus.conf(5) for your users, please pay attention to new features and how these may impact users. For example, for some time now, Cyrus has supported placing several standard DB files in temporary, or ephemeral, storage, such as memory backed filesystems like tmpfs (see below). This both boosts efficiency and ensures DB consistency in event of a crash or other system disruptive events. But, in light of this, actions which depend on the existence of these database files should not be placed in the START section of cyrus.conf(5). Section Purpose¶ A new section, DAEMON, was added to cyrus.conf(5) in version 2.5. Please consult cyrus.conf(5) for details. Please refer to the notes in Section Descriptions pertaining to the distinctions between START, EVENTS and DAEMON sections. In brief, the sorts of things which should go into the different sections are: - START - SERVICES - EVENTS - DAEMON The configuration file for the various programs: imapd.conf¶ The sample imapd.conf(5) files must be adapted for use from site to site. Here, therefore, we'll attempt to point you towards some reasonable settings which take advantage of recent improvements and features, and may help guide you and your users to a better performing Cyrus installation. Ephemeral files and temporary filesystems¶ In addition to Unix domain sockets and lock files, several databases used by Cyrus programs may be located in temporary filesystems, such as those backed by RAM (i.e. tmpfs, md, etc.). Here's a list of such files. In this example, the filesystem /run is on tmpfs: proc_path: /run/cyrus/proc mboxname_lockpath: /run/cyrus/lock duplicate_db_path: /run/cyrus/deliver.db statuscache_db_path: /run/cyrus/statuscache.db ptscache_db_path: /run/cyrus/ptscache.db tls_sessions_db_path: /run/cyrus/tls_sessions.db lmtpsocket: /run/cyrus/socket/lmtp idlesocket: /run/cyrus/socket/idle notifysocket: /run/cyrus/socket/notify Note Any process which depends on these files already existing should not be placed in the START section of cyrus.conf(5), or the server will not start as expected. New default settings¶ A new stable series means the defaults for some settings may have changed. Please consult Upgrading to 3.4 for details. New or improved features¶ A new stable series means new features, and improvements to existing features. Some of these may be features which previously were not considered ripe for packaging, but merit new consideration. Please see Cyrus IMAP 3.2 Releases for details, and consider enabling these features in the imapd.conf(5) you ship in your packages. Services in /etc/services¶ Listing named services through /etc/services aids in cross-system consistency and cross-platform interoperability. Furthermore, it enables administrators and users to refer to the service by name (for example in /etc/cyrus.conf, 'listen=mupdate' can be specified instead of 'listen=3905'). Some of the services Cyrus IMAP would like to see available through /etc/services have not been assigned an IANA port number, and few have configuration options..
https://www.cyrusimap.org/3.4/imap/download/packagers.html
CC-MAIN-2021-21
refinedweb
594
50.84
Understanding the GWT compiler The GWT compiler is the fulcrum of GWT. The entire approach GWT takes, encapsulating browser differences and compiling JavaScript from Java, is made possible by the design and architecture of the compiler. The GWT compiler compiles Java into JavaScript, but it’s important to understand that the compiler doesn’t compile Java the same way javac does. The GWT compiler is really a Java source to JavaScript source translator. The GWT compiler needs hints about the work that it must perform partly because it operates from source. These hints come in the form of the module descriptor, the marker interfaces that denote serializable types, the JavaDoc style annotations used in serializable types for collections, and more. Although these hints may sometimes seem like overkill, they’re needed because the GWT compiler will optimize your application at compile time. This doesn’t just mean compressing the JavaScript naming to the shortest possible form; it also includes pruning unused classes, and even methods and attributes, from your code. The core engineering goal of the GWT compiler is summarized succinctly: you pay for what you use. This optimization offers big advantages over other Ajax/JavaScript libraries, where a large initial download of a library may be needed even if just a few elements are used. In Java, serialization marked by the java.io.Serializable interface is handled at the bytecode level. GWT examines your code and only provides serialization for the classes where you explicitly need it. Like GWTShell, GWTCompiler supports a set of useful command-line options. They’re described in table 1: GWTCompiler [-logLevel level] [-gen dir] [-out dir] [-treeLogger] [-style style] module Table 1 GWTCompiler parameters The -gen and -out command-line options specify where generated files and the final output directory are to be, respectively. And -logLevel, as in the case of GWTShell, is used to indicate the level of logging performed during the compilation. You can even use the -treeLogger option to bring up a window to view the hierarchical logging information you would see in the shell’s console display. The GWT compiler supports several styles of output, each of use in looking at how your code is executing in the browser. JavaScript output style When working with the GWT compiler, you can use several values with the -style command-line option to control what the generated JavaScript looks like. These options are as follows: OBF- Obfuscated mode. This is a non-human-readable, compressed version suitable for production use. PRETTY- Pretty-printed JavaScript with meaningful names. DETAILED- Pretty-printed JavaScript with fully qualified names. To give you an idea of what these options mean, let’s look at examples of java.lang.StringBuffer compiled in the three different modes. First, in listing 1, is the obfuscated mode. Listing 1 StringBuffer in obfuscated compilation function A0(){this.B0();return this.js[0];} function C0(){if(this.js.length > 1) {this.js = [this.js.join('')];this.length = this.js[0].length;}} function D0(E0){this.js = [E0];this.length = E0.length;} function Ez(F0,a1){return F0.yx(yZ(a1));} function yB(b1){c1(b1);return b1;} function c1(d1){d1.e1('');} function zB(){} _ = zB.prototype = new f();_.yx = w0;_.vB = A0;_.B0 = C0;_.e1 = D0; _.i = 'java.lang.StringBuffer';_.j = 75; function f1(){f1 = a;g1 = new iX();h1 = new iX();return window;} Obfuscated mode is just that. This is intended to be the final compiled version of your application, which has names compressed and whitespace cleaned. Next is the pretty mode, shown in listing 2. Listing 2 StringBuffer in pretty compilation function _append2(_toAppend){ var _last = this.js.length - 1; var _lastLength = this.js[_last].length; if (this.length > _lastLength * _lastLength) { this.js[_last] = this.js[_last] + _toAppend; } else { this.js.push(_toAppend); } this.length += _toAppend.length; return this; } function _toString0(){ this._normalize(); return this.js[0]; } // Some stuff omitted. function _$StringBuffer(_this$static){ _$assign(_this$static); return _this$static; } function _$assign(_this$static){ _this$static._assign0(''); } function _StringBuffer(){ } _ = _StringBuffer.prototype = new _Object(); _._append = _append2; _._toString = _toString0; _._normalize = _normalize0; _._assign0 = _assign; _._typeName = 'java.lang.StringBuffer'; _._typeId = 75; append() becomes _append2() to avoid collision> toString() becomes _toString0()> _typeName holds name of original Java class> Pretty mode is useful for debugging as method names are somewhat preserved. However, collisions are resolved with suffixes, as the _toString0() method name shows . Last, we have the detailed mode, as displayed in listing 3. Listing 3 StringBuffer in detailed compilation function java_lang_StringBuffer_append__Ljava_lang _String_2(toAppend){ var last = this.js.length - 1; var lastLength = this.js[last].length; if (this.length > lastLength * lastLength) { this.js[last] = this.js[last] + toAppend; } else { this.js.push(toAppend); } this.length += toAppend.length; return this; } function java_lang_StringBuffer_toString__(){ this.normalize__(); return this.js[0]; } function java_lang_StringBuffer_normalize__(){ if (this.js.length > 1) { this.js = [this.js.join('')]; this.length = this.js[0].length; } } // . . . some stuff omitted function java_lang_StringBuffer(){ } _ = java_lang_StringBuffer.prototype = new java_lang_Object(); _.append__Ljava_lang_String_2 = java_lang_StringBuffer_append__Ljava_lang_String_2; _.toString__ = java_lang_StringBuffer_toString__; _.normalize__ = java_lang_StringBuffer_normalize__; _.assign__Ljava_lang_String_2 = java_lang_StringBuffer_assign__Ljava_lang_String_2; _.java_lang_Object_typeName = 'java.lang.StringBuffer'; _.java_lang_Object_typeId = 75; Detailed mode preserves the full class name, as well as the method name #2. For overloaded methods, the signature of the method is encoded into the name, as in the case of the append() method #1. There are some important concepts to grasp about this compilation structure, especially given the way GWT interacts with native JavaScript, through the JavaScript Native Interface (JSNI), which will be discussed in the section on the compiler lifecycle. The names of your classes and methods in their JavaScript form aren’t guaranteed, even for different compilations of the same application. Use of the special syntax provided with JSNI will let you invoke known JavaScript objects from your Java code and invoke your compiled Java classes from within JavaScript; but you can’t freely invoke your JavaScript when using obfuscated style, predictably. This imposes certain limitations on your development: - If you intend to expose your JavaScript API for external use, you need to create the references for calls into GWT code using JSNI registrations. - You can’t rely on JavaScript naming in an object hash to give you java.lang.reflect.* type functionality, since the naming of methods isn’t reliable. - Although they’re rare, you should consider potential conflicts with other JavaScript libraries you’re including in your page, especially if you’re publishing using the PRETTY setting. In addition to being aware of the available compiler output options and how they affect your application, you should also be familiar with a few other compiler nuances. Additional compiler nuances Currently, the compiler is limited to J2SE 1.4 syntactical structures. This means that exposing generics or annotations in your GWT projects can cause problems. Other options are available for many of the purposes for which you might wish to use annotations. For example, you can often use JavaDoc-style annotations, to which GWT provides its own extensions. Along with the J2SE 1.4 limitations, you also need to keep in mind the limited subset of Java classes that are supported in the GWT Java Runtime Environment (JRE) emulation library. This library is growing, and there are third-party extensions, but you need to be aware of the constructs you can use in client-side GWT code—the complete JRE you’re accustomed to isn’t available. Of course, one of the great advantages of GWT’s approach to compiling JavaScript from plain Java is that you get to leverage your existing toolbox while building your Ajax application. When you execute the hosted mode browser, you’re running regularly compiled Java classes. This, again, means you can use all the standard Java tooling—static analysis tools, debuggers, IDEs, and the like. These tools are useful for writing any code, but they become even more important in the GWT world because cleaning up your code means less transfer time to high-latency clients. Also, because JavaScript is a fairly slow execution environment, such cleanup can have a large impact on ultimate performance. The GWT compiler helps by optimizing the JavaScript it emits to include only classes and methods that are on the execution stack of your module and by using native browser functions where possible, but you should always keep the nature of JavaScript in mind. To that end, we’ll now take a closer look at the lifecycle of a GWT compilation and at how this JavaScript is generated. The compiler lifecycle When the GWT compiler runs, it goes through several stages for building the final compiled project. In these stages, the need for the GWT module definition file becomes clear. First, the compiler identifies which combinations of files need to be built. Then, it generates any client-side code using the generator metaprogramming model. Last, it produces the final output. We’ll look at each of these steps in the compiler lifecycle in more detail.dentifying build combinations One of the great strengths of GWT is that it builds specific versions of the application, each exactly targeted to what the client needs (user agent, locale, so on). This keeps the final download, and the operational overhead at the client level, very lean. A particular build combination is defined in the GWT module definition using a tag. This establishes a base set of values that are used for the build. The first and very obvious property is the user agent that the JavaScript will be built for. Listing 4 shows the core GWT UserAgent module definition. Listing 4 The GWT UserAgent definition <define-property <property-provider<![CDATA[) { var result = /msie ([0-9]+)\.([0-9]+)/.exec(ua); if (result && result.length == 3) { if (makeVersion(result) >= 6000) { return "ie6"; } } } else if (ua.indexOf("gecko") != -1) { var result = /rv:([0-9]+)\.([0-9]+)/.exec(ua); if (result && result.length == 3) { if (makeVersion(result) >= 1008) return "gecko1_8"; } return "gecko"; } return "unknown"; ]]></property-provider> Here the tag establishes a number of different builds that the final compiler will output #1: in this case, ie6, gecko, gecko1_8, safari, and opera. This means each of these will be processed as a build of the final JavaScript that GWT emits. GWT can then switch implementations of classes based on properties using the tag in the module definition. As the GWT application starts up, the JavaScript snippet contained within the tag determines which of these implementations is used #2. This snippet is built into the startup script that determines which compiled artifact is loaded by the client. At the core of the GWT UI classes is the DOM class. This gets replaced based on the user.agent property. Listing 5 shows this definition. Listing 5 Changing the DOM implementation by UserAgent <inherits name="com.google.gwt.user.UserAgent"/> <replace-with <when-type-is <when-property-is </replace-with> <replace-with <when-type-is <when-property-is </replace-with> <replace-with <when-type-is <when-property-is </replace-with> <replace-with <when-type-is <when-property-is </replace-with> <replace-with <when-type-is <when-property-is </replace-with> Now you can see the usefulness of this system. The basic DOM class is implemented with the same interface for each of the browsers, providing a core set of operations on which cross-platform code can easily be written. Classes replaced in this method can’t be instantiated with simple constructors but must be created using the GWT.create() method. In practice, the DOM object is a singleton exposing static methods that are called by applications, so this GWT.create() invocation is still invisible. This is an important point to remember if you want to provide alternative implementations based on compile-time settings in your application. You can also define your own properties and property providers for switching implementations. We have found that doing this for different runtime settings can be useful. For example, we have defined debug, test, and production settings, and replacing some functionality in the application based on this property can help smooth development in certain cases. This technique of identifying build combinations and then spinning off into specific implementations during the compile process is known in GWT terms as deferred binding. The GWT documentation sums this approach up as “the Google Web Toolkit answer to Java reflection.” Dynamic loading of classes (dynamic binding) isn’t truly available in a JavaScript environment, so GWT provides another way. For example, obj.getClass().getName() isn’t available, but GWT.getTypeName(obj) is. The same is true for Class.forName("MyClass"), which has GWT.create(MyClass) as a counterpart. By using deferred binding, the GWT compiler can figure out every possible variation, or axis, for every type and feature needed at compile time. Then, at runtime, the correct permutation for the context in use can be downloaded and run. Remember, though, that each axis you add becomes a combinatory compile. If you use 4 languages and 4 browser versions, you must compile 16 final versions of the application; and if you use several runtime settings, you end up with many more combinations in the mix. This concept is depicted in figure 1. Figure 1 Multiple versions of a GWT application are created by the compiler for each axis or variant application property, such as user agent and locale. Compiling a new monolithic version of your application for each axis doesn’t affect your end users negatively. Rather, this technique allows each user to download only the exact application version they need, without taking any unused portion along for the ride. This is beneficial for users, but it slows compile time considerably, and it can be a painful point for developers. Reducing the compile variants to speed up compile time Even though GWT compile time can be long, keep in mind that the end result for users is well optimized. Also, the GWT module system allows you to tweak the compile time variants for the situation. During day-to-day development, you may want to use the tag in your module definition to confine the compile to a single language, or single browser version, to speed up the compile step. Another important use for module properties is in code generation, which is the next step of the compilation process. Generating code GWT’s compiler includes a code generation or metaprogramming facility that allows you to generate code based on module properties at compile time. Perhaps the best example is the internationalization support. The i18n module defines several no-method interfaces that you extend to define Constants, Messages (which include in-text replacement), or Dictionary classes (which extract values from the HTML host page). The implementations of each of these classes are built at compile time using the code generation facility, producing a lean, custom version of your application in each language. The i18n module does this through the tag, which lets you add additional iterative values to a property in a module. Listing 6 demonstrates the use of this concept to add French and Italian support to a GWT application. Listing 6 Defining French and Italian using extend-property <extend-property <extend-property When an application inherits the i18n module, the GWT compiler searches for interfaces that extend one of the i18n classes and generates an implementation for the class based on a resource bundle matching the language code. This is accomplished via the tag in the i18n module definition. Listing 7 shows this along with the tag, which is used for establishing which language will be needed at runtime. Listing 7 The i18n module’s locale property declarations <define-property <property-provider <![CDATA[ try { var locale; // Look for the locale as a url argument if (locale == null) { var args = location.search; var startLang = args.indexOf("locale"); if (startLang >= 0) { var language = args.substring(startLang); var begin = language.indexOf("=") + 1; var end = language.indexOf("&"); if (end == -1) { end = language.length; } locale = language.substring(begin, end); } } if (locale == null) { // Look for the locale on the web page locale = __gwt_getMetaProperty("locale") } if (locale == null) { return "default"; } while (!__gwt_isKnownPropertyValue("locale", locale)) { var lastIndex = locale.lastIndexOf("_"); if (lastIndex == -1) { locale = "default"; break; } else { locale = locale.substring(0,lastIndex); } } return locale; } catch(e) { alert("Unexpected exception in locale "+ "detection, using default: " + e); return "default"; } ]]> </property-provider> <generate-with <when-type-assignable </generate-with> The module first establishes the locale property. This is the property we extended in listing 6 to include it and fr. Next, the property provider is defined . The value is checked first as a parameter on the request URL in the format locale=xx and then as a tag on the host page in the format ; finally, it defaults to default. The last step is to define a generator class. Here it tells the compiler to generate implementations of all classes that extend or implement Localizable with the LocalizableGenerator . This class writes out Java files that implement the appropriate interfaces for each of the user’s defined Constants, Messages, or Dictionary classes. Notice that, to this point, nowhere have we dealt specifically with JavaScript outside of small snippets in the modules. GWT will produce the JavaScript in the final step. Producing output You can do a great deal from Java with the GWT module system, but you may need to get down to JavaScript-level implementations at some point if you wish to integrate existing JavaScript or extend or add lower-level components. For this, GWT includes JSNI. This is a special syntax that allows you to define method implementations on a Java class using JavaScript. Listing 8 shows a simple JSNI method. Listing 8 A simple JSNI method public class Alert { public Alert() { super(); } public native void alert(String message) /*-{ alert(message); }-*/; } In this listing, we first define the alert() method using the native keyword. Much like the Java Native Interface (JNI) in regular Java, this indicates that we are going to use a native implementation of this method. Unlike JNI, the implementation lives right in the Java file, surrounded by a special /*- -*/ comment syntax. To reference Java code from JavaScript implementations, syntax similar to JNI is provided. Figure 2 shows the structure of calls back into Java from JavaScript. Figure 2 The structure of JSNI call syntax GWT reuses the JNI typing system to reference Java types. The final compiled output will have synthetic names for methods and classes, so the use of this syntax is important to ensure that GWT knows how to direct a call from JavaScript. In the final step of the compilation process, GWT takes all the Java files, whether provided or generated, and the JSNI method implementations, and examines the call tree, pruning unused methods and attributes. Then it transforms all of this into a number of unique JavaScript files, targeted very specifically at each needed axis. This minimizes both code download time and execution time in the client. Although this complex compilation process can be time consuming for the developer, it ensures that the end user’s experience is the best it can possibly be for the application that is being built. This article is excerpted from Chapter 1 of GWT in Practice, by Robert Cooper and Charlie Collins, and published in May 2008 by Manning Publications. (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) Christian Ullenboom replied on Wed, 2008/06/18 - 11:59am It's worth to mention the GWT 1.5 RC 1 with the ability to use Java 5 and annotations as an alternative to JavaDoc for the compiler hints. defines nearly 20 annotations for the metadata. Christian Ricardo Nóbrega replied on Thu, 2009/03/05 - 10:23am Hi folks! Do you know if it is possible to use the GWTCompiler to compile just specific classes of the project? I know is possible to compile specific modules. But I'd like to know for classes! Thanks in advance! Ricardo Grupo eGen
http://css.dzone.com/news/understanding-gwt-compiler
CC-MAIN-2014-15
refinedweb
3,322
56.76
Details - Type: Bug - Status: Resolved - Priority: Major - Resolution: Won't Fix - Affects Version/s: None - Fix Version/s: None - Component/s: None - Labels:None Description There are a lot of deprecated methods in HttpServer. They are not used anymore. They should be removed. Issue Links - is related to HADOOP-10254 HttpServer doesn't load listeners - Resolved HBASE-10336 Remove deprecated usage of Hadoop HttpServer in InfoServer - Closed Activity - All - Work Log - History - Activity - Transitions Suresh Srinivas Thanks for the helpful suggestion. We're letting go of this dependency in our trunk. We can't just do it 'now' in existing releases w/o frustrating our users. Thanks. Is the end effect kind of the same as Suresh Srinivas suggested? Haohui Mai, the patch for HADOOP-10254, is kind of undo part of HDFS-5545, so it is about the same as the original version. Is that not an option? +1 to make a copy of this HttpServer and bring the original HttpServer back. HttpServer is a private API and it should not support any downstream uses. Haohui Mai, given that this class is marked as LimitedPrivate this class cannot be removed or made private. ,The interface is marked as evolving, so incompatible changes should be allowed. However, I suggest just making a copy of this HttpServer (HttpServer2?) for internal use in HDFS and MapReduce, with cleaner code and leave HttpServer class alone. At some point in time when HBase folks are ready, they can copy this to their project and we can delete this from Hadoop, possibly in 3.0. Haohui Mai "...HttpServer is a private API and it should not support any downstream uses." Go easy. The above is all well and good as some sort of general statement only there is the caveat that Andrew Purtell quotes you above (and which was quoted to you a few days ago over in HADOOP-10232). I believe the hope was that those listed in the LimitedPrivate set would get notice if the class was to change radically. Notice noted. We are moving to get off this Interface now – a patch will go in in the next few days and we'll soon enough have a release out with the patch in it – but please do not remove these methods just yet and make it so releases we have in the field now fail when our users would like to go to apache 2.5/2.6, etc. Thanks. This is exactly the situation that we want to avoid – HttpServer is a private API and it should not support any downstream uses. I went and reviewed the code in question, and I don't understand this statement. This is the interface annotation for HttpServer on HEAD of Hadoop common branch-2: @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce", "HBase"}) @InterfaceStability.Evolving public class HttpServer implements FilterContainer { My read of HBASE-10336 is the change there will be committed to HBase trunk, but not to the 0.96 and 0.98 release branches. For those releases, we will need to add a disclaimer they will not work with Hadoop 2.X where X is wherever the backwards compatibility is broken on the Hadoop 2.x release line. This is exactly the situation that we want to avoid – HttpServer is a private API and it should not support any downstream uses. The only downstream user of this class is HBase. Once HBASE-10336 is landed, you should be clear to upgrade. I feel like we can't do this change in a 2.x. For 3.x it's fine, but as all the HBasers are saying, it's clearly backwards incompatible with earlier 2.x releases. The methods will be removed in the next release. If you mean 2.5, then you will have only moved the problem for HBase 0.96.x and HBase 0.98.x to 2.5. Surely other downstreams will be affected also. According to HBASE-10336, the deprecated methods will stay in the 2.4 release. The methods will be removed in the next release. Echoing Andrew Purtell, there are a lot of downstreams using HttpServer. Even if these methods were deprecated in 1.x, it seems kind of nasty to remove them in a 2.x release after 2.2 GA. Have you checked if downstream projects are using them? According to the discussion in HADOOP-10255. HttpServer is reserved for HBase's use. Marking this jira as won't fix.
https://issues.apache.org/jira/browse/HADOOP-10253
CC-MAIN-2016-22
refinedweb
743
74.59
Our Detail component is now executing code to render the text that gets passed to it as props, but it could easily render other valid ES6 code too. To demonstrate this, let's pull in the Chance library, which generates realistic-looking random data. In your terminal window, run this command: npm install --save chance You were probably still running Webpack Dev Server in there, but that's OK - press Ctrl+C to quit that, then run the npm command above. Once that's finished you can restart Webpack Dev Server again by running webpack-dev-server. The Chance library generates realistic-looking random data, which means it can generate random first names, last names, sentences of text, social security numbers and so on – this makes it a good test case for printing out some information. To use it you need to import the library into Detail.js, like this: src/pages/Detail.js import Chance from 'chance'; You can then generate random first names inside the render() method like this: src/pages/Detail.js return <p>Hello, {chance.first()}!</p>; Just to make sure you're following along, here's how your Detail.js file should look once these changes are made: src/pages/Detail.js import React from 'react'; import Chance from 'chance'; class Detail extends React.Component { render() { return <p>Hello, {chance.first()}!</p>; } } export default Detail; If you save that file and look back in your web browser you'll see "Hello, Emma!" or similar appear, and you can hit refresh in your browser to see a different name. So you can see we're literally calling the first() method in the Chance library right there while rendering, and I hope it's clear that putting code into braces like this is very powerful indeed. But there's a catch, and it's a big one. In fact, it's a catch so big that fisherman will tell tall tales about it for years to!
http://www.hackingwithreact.com/read/1/6/generating-random-values-for-our-page
CC-MAIN-2017-22
refinedweb
329
71.75
I am new to python, more familiar with perl. I want to write a basic code that will loop through a function indefinitely every one hour.I tried to write the below code but it doesnt seem to work. Can someone help me? - Code: Select all while var True : def main(): connect("10.1.1.1") return 0 localtime = time.localtime(time.time()) sleeptime = (60 * ((19 - localtime) % 60)); print localtime time.sleep 60 def connect(ip) : #my function to connect Basically I want the function connect() to be called every one hour. its kinda strange with python, am used to braces to begin and end a loop, but here its just a :
http://www.python-forum.org/viewtopic.php?p=7372
CC-MAIN-2016-40
refinedweb
112
76.93
Artifact 7f1438fb2bef8eb1fdd4f09b4e709a39d53e6963: - File src/sqlite.h.in — part of check-in [15110ea0] at 2008-03-19 14:15:34 on branch trunk — Add a new api sqlite3_randomness() for providing access to SQLite's internal PRNG. Add sqlite3_test_control() verbs for controlling the PRNG. (CVS 4882) (user: drh size: 244447) /* **.293 2008/03/19 14:15:35 release number ** and is incremented with ** each release but resets back to 0 when Y is incremented. ** ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. ** ** INVARIANTS: ** ** {F10011} The SQLITE_VERSION #define in the sqlite3.h header file ** evaluates to a string literal that is the SQLite version ** with which the header file is associated. ** ** {F10014} The SQLITE_VERSION_NUMBER #define resolves returns an integer ** equal to [SQLITE_VERSION_NUMBER]. ** ** {F10022} The [sqlite3_version] string constant contains the text of the ** [SQLITE_VERSION] string. ** ** {F10023} The [sqlite3_libversion()] function returns **, ** the mutexes are omitted. Without the mutexes, it is not safe ** to use SQLite from more than one thread. ** ** There is a measurable performance penalty for enabling mutexes. ** So if speed is of utmost importance, it makes sense to disable ** the mutexes. But for maximum safety, mutexes should be enabled. ** The default behavior is for mutexes to be enabled. ** ** This interface can be used by a program to make sure that the ** version of SQLite that it is linking against was compiled with ** the desired setting of the SQLITE_THREADSAFE macro. ** ** INVARIANTS: ** ** {F10101} The [sqlite3_threadsafe()] function returns nonzero if ** SQLite was compiled with its mutexes enabled or zero ** if SQLite was compiled with mutexes disabled. */ int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle {F12000} ** KEYWORDS: {database connection} ** ** {F10200} **. ** ** INVARIANTS: ** ** {F10201} The [sqlite_int64] and [sqlite3_int64] types specify a ** 64-bit signed integer. ** ** {F10202} The [sqlite_uint64] and [sqlite3_uint64] types specify ** a 64-bit unsigned integer. */ {F12010} ** ** This routine is the destructor for the [sqlite3] object. ** ** Applications should [sqlite3_finalize | finalize] all ** [prepared statements] and ** [sqlite3_blob_close | close] all [sqlite3_blob | BLOBs] ** associated with the [sqlite3] object prior ** to attempting to close the [sqlite3] object. ** ** <todo>What happens to pending transactions? Are they ** rolled back, or abandoned?</todo> ** ** INVARIANTS: ** ** {F12011} The [sqlite3_close()] interface destroys an [sqlite3] object ** allocated by a prior call to [sqlite3_open()], ** [sqlite3_open16()], or [sqlite3_open_v2()]. ** ** {F12012} The [sqlite3_close()] function releases all memory used by the ** connection and closes all open files. ** ** {F12013} If the database connection contains ** [prepared statements] that have not been ** finalized by [sqlite3_finalize()], then [sqlite3_close()] ** returns [SQLITE_BUSY] and leaves the connection open. ** ** {F12014} Giving sqlite3_close() a NULL pointer is a harmless no-op. ** ** LIMITATIONS: ** ** {U12015} The parameter to [sqlite3_close()] must be an [sqlite3] object ** pointer previously obtained from [sqlite3_open()] or the ** equivalent, or NULL. ** ** {U12016} The parameter to [sqlite3_close()] must not have been a lot of C code. The ** sqlite3_exec() interface is implemented in terms of ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. ** The sqlite3_exec() routine does nothing that cannot be done ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. ** The sqlite3_exec() is just a convenient wrapper. ** ** INVARIANTS: ** ** {F12101} The [sqlite3_exec()] interface evaluates zero or more UTF-8 ** encoded, semicolon-separated, SQL statements in the ** zero-terminated string of its 2nd parameter within the ** context of the [sqlite3] object given in the 1st parameter. ** ** {F12104} The return value of [sqlite3_exec()] is SQLITE_OK if all ** SQL statements run successfully. ** ** {F12105} The return value of [sqlite3_exec()] is an appropriate ** non-zero error code if any SQL statement fails. ** ** {F12107} If one or more of the SQL statements handed to [sqlite3_exec()] ** return results and the 3rd parameter is not NULL, then ** the callback function specified by the 3rd parameter is ** invoked once for each row of result. ** ** {F12110} If the callback returns a non-zero value then [sqlite3_exec()] ** will aborted the SQL statement it is currently evaluating, ** skip all subsequent SQL statements, and return [SQLITE_ABORT]. ** <todo>What happens to *errmsg here? Does the result code for ** sqlite3_errcode() get set?</todo> ** ** {F12113} The [sqlite3_exec()] routine will pass its 4th parameter through ** as the 1st parameter of the callback. ** ** {F12116} The [sqlite3_exec()] routine sets the 2nd parameter of its ** callback to be the number of columns in the current row of ** result. ** ** {F12119} The [sqlite3_exec()] routine sets the 3rd parameter of its ** callback to be an array of pointers to strings holding the ** values for each column in the current result set row as ** obtained from [sqlite3_column_text()]. ** ** {F12122} The [sqlite3_exec()] routine sets the 4th parameter of its ** callback to be an array of pointers to strings holding the ** names of result columns as obtained from [sqlite3_column_name()]. ** ** {F12125} If the 3rd parameter to [sqlite3_exec()] is NULL then ** [sqlite3_exec()] never invokes a callback. All query ** results are silently discarded. ** ** {F12128} If an error occurs while parsing or evaluating any of the SQL ** statements handed to [sqlite3_exec()] then [sqlite3_exec()] will ** return an [error code] other than [SQLITE_OK]. ** ** {F12131} If an error occurs while parsing or evaluating any of the SQL ** handed to [sqlite3_exec()] and if the 5th parameter (errmsg) ** to [sqlite3_exec()] is not NULL, then an error message is ** allocated using the equivalent of [sqlite3_mprintf()] and ** *errmsg is made to point to that message. ** ** {F12134} The [sqlite3_exec()] routine does not change the value of ** *errmsg if errmsg is NULL or if there are no errors. ** ** {F12137} The [sqlite3_exec()] function sets the error code and message ** accessible via [sqlite3_errcode()], [sqlite3_errmsg()], and ** [sqlite3_errmsg16()]. ** ** LIMITATIONS: ** ** {U12141} The first parameter to [sqlite3_exec()] must be an valid and open ** [database connection]. ** ** {U12142} The database connection must not be closed while ** [sqlite3_exec()] is running. ** ** {U12143} The calling function is should use [sqlite3_free()] to free ** the memory that *errmsg is left pointing at once the error ** message is no longer needed. ** ** {U12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()] ** must remain unchanged while [sqlite3_exec()] is running. */ int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluted */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* ** CAPI3REF: Result Codes {F10210} ** KEYWORDS: SQLITE_OK {error code} {error codes} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicates success or failure. ** ** {F10220} ** KEYWORDS: {extended error code} {extended error codes} ** KEYWORDS: {extended result codes} ** ** In its default configuration, SQLite API routines return one of 26 integer ** [SQLITE_OK | result codes]. However, experience has shown that ** many of these result codes are too course. ** ** INVARIANTS: ** ** {F10223} The symbolic name for an extended result code always contains ** a related primary result code as a prefix. ** ** {F10224} Primary result code names contain a single "_" character. ** ** {F10225} Extended result code names contain two or more "_" characters. ** ** {F10226} The numeric value of an extended result code contains the ** numeric value of its corresponding primary result code in ** its least significant 8 bits. */ )) /* ** CAPI3REF: Flags For File Open Operations {F10230} ** **_TRANSIENT_DB 0x00000400 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* ** CAPI3REF: Device Characteristics {F10240} ** ** {F10250} ** ** {F10260} ** **. The SQLITE_SYNC_NORMAL flag means ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag {F11110} ** ** {F11120} ** ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to ** an instance of this object. This object defines the ** methods used to perform various operations against the open file. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). * The second choice is an ** OS-X style fullsync. The SQLITE_SYNC_DATA. ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the ** */ }; /* ** CAPI3REF: Standard File Control Opcodes {F11310} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and /* ** CAPI3REF: Mutex Handle {F17110} ** ** {F11140} ** **. ** ** {F11141} SQLite will guarantee that the zFilename string passed to ** xOpen() is a full pathname as generated by xFullPathname() and ** that the string will be valid and unchanged until xClose() is ** called. {END} So the [sqlite3_file] can store a pointer to the ** filename if it needs to remember the filename for some reason. ** ** } ** ** The file I/O implementation can use the object type flags to ** changes> ** ** . {END} ** ** } The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existance of a file, ** or [SQLITE_ACCESS_READWRITE] to test to see ** if a file is readable and writable, or [SQLITE_ACCESS_READ] ** to test to see if a file is at least readable. {END} The file can be a ** directory. ** ** {F11150} SQLite will always allocate at least mxPathname+1 bytes for ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact ** size of the output buffer is also passed as a parameter to both ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN ** should be returned. As*, int nOut, char *z. */ }; /* ** to see if the file exists. {F11193} With ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see ** if the file is both readable and writable. {F11194} With ** SQLITE_ACCESS_READ the xAccess method ** checks to see if the file is readable. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 #define SQLITE_ACCESS_READ 2 /* ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} ** ** The sqlite3_extended_result_codes() routine enables or disables the ** [SQLITE_IOERR_READ | extended result codes] feature of SQLite. ** The extended result codes are disabled by default for historical ** compatibility. ** ** INVARIANTS: ** ** {F12201} Each new [database connection] has the ** [extended result codes] feature ** disabled by default. ** ** {F12202} The [sqlite3_extended_result_codes(D,F)] interface will ** shown in the first argument. If no successful. ** ** INVARIANTS: ** ** {F12221} The [sqlite3_last_insert_rowid()] function returns the ** rowid of the most recent successful insert done ** on the same database connection and within the same ** trigger context, or zero if there have ** been no qualifying inserts on that connection. ** ** {F12223} The [sqlite3_last_insert_rowid()] function returns ** same value when called from the same trigger context ** immediately before and after a ROLLBACK. ** ** LIMITATIONS: ** ** {U12232} If a separate thread does3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified {F12240} ** ** This function returns the number of database rows that were changed ** or inserted or deleted by the most recently completed SQL statement ** on the connection specified by the first parameter. Only ** changes that are directly specified by the INSERT, UPDATE, or ** DELETE statement are counted. Auxiliary changes caused by ** triggers are not counted. Use the [sqlite3_total_changes()] function ** to find the total number of changes including changes caused by triggers. ** **. ** ** So in changes ** caused by subtriggers since they have their own context. ** ** SQLite implements the command "DELETE FROM table" without ** a WHERE clause by dropping and recreating the table. (This is much ** faster than going through and deleting individual elements from the ** table.) Because of this optimization, the deletions in ** "DELETE FROM table" are not row changes and will not be counted ** by the sqlite3_changes() or [sqlite3_total_changes()] functions. ** To get an accurate count of the number of rows deleted, use ** "DELETE FROM table WHERE 1" instead. ** ** INVARIANTS: ** ** {F12241} The [sqlite3_changes()] function returns the number of ** row changes caused by the most recent INSERT, UPDATE, ** or DELETE statement on the same database connection and ** within the same trigger context, or zero if there have ** not been any qualifying row changes. ** ** LIMITATIONS: ** ** {U12252} If a separate thread makes changes on the same database connection ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and unmeaningful. */ int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified {F12260} *** ** This function returns the number of row changes caused ** by INSERT, UPDATE or DELETE statements since the database handle ** was opened. The count includes all changes from all trigger ** contexts. But. ** ** LIMITATIONS: ** ** {U12264} If a separate thread makes changes on the same database connection ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and unmeaningful. */: ** ** and ** so will not detect syntactically incorrect SQL. ** **: ** ** {U10512} The input to sqlite3_complete() must be a zero-terminated ** UTF-8 string. ** ** identifies. ** ** There can only be a single busy handler defined for each database ** connection. Setting a new busy handler clears any previous one. ** Note that calling [sqlite3_busy_timeout()] will also set or clear ** the busy handler. ** ** argument which ** are a copy of the pointer supplied by the 3rd parameter to ** [sqlite3_busy_handler()] and a count of the number of prior ** invocations of the busy handler for the same locking event. ** ** LIMITATIONS: ** ** {U12319} A busy handler should not call while when a ** table is locked. The handler will sleep multiple times until ** at least "ms" milliseconds of sleeping have been done. . ** **} ** ** are give a NULL pointer. All other values are in ** their UTF-8 zero-terminated string representation as returned by ** [sqlite3_column_text()]. ** ** A result table might consists-ed.()]. ** **()] write the number of columns in the ** result set of the query into *ncolumn if the query is ** successful (if the function returns SQLITE_OK). ** ** {F12374} If the nrow parameter to [sqlite3_get_table()] is not NULL ** then [sqlite3_get_table()] write writes(). ** **. {F17382} However, if ** SQLite is compiled with the following C preprocessor macro ** ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> ** ** where <i>NNN</i> is an integer, then SQLite create a static ** array of at least <i>NNN</i> bytes in size and use]. ** ** INVARIANTS: ** ** {F17303} The [sqlite3_malloc(N)] interface returns either a pointer ** where K is the lessor: ** ** {U17350} The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] ** must be either NULL or else a pointer obtained from a prior ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that has ** not been released. ** ** ()] ** the memory allocation subsystem included within the SQLite. ** **water mark was last reset. ** ** {F17374}. ** ** {F17375} The memory highwater mark is reset to the current value of ** [sqlite3_memory_used()] if and only if the parameter to ** [sqlite3_memory_highwater()] is true. The value returned ** by [sqlite3_memory_highwater(1)] is the highwater mark ** prior to the reset. */ sqlite3_int64 sqlite3_memory_used(void); sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator {F17390} ** ** ** appliations. ** ** INVARIANTS: ** ** {F17392} The [sqlite3_randomness(N,P)] interface writes N bytes of ** high-quality pseudo-randomness into buffer P. */ void sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks {F12500} ** **. If the authorizer code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the prepared ** statement is constructed to insert a NULL value in place of ** the table column that would have ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. ** **. Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** coded the ** function] ** triggersub8 opertion. <todo>What if N is less than 1?</todo> ** ** {F12913} The progress callback itself is identified by the third ** argument to [sqlite3_progress_handler()]. ** ** {F12914} The fourth argument [sqlite3_progress_handler()] is a *** void pointer passed to the progress callback ** function each time it is invoked. ** ** {F12915} If a call to [sqlite3_step()] results in fewer than ** N opcodes being executed, ** then the progress callback is never invoked. {END} ** ** {F12916} Every call to [sqlite3_progress_handler()] ** overwrites any previously registere by the filename argument. ** The filename argument is interpreted as UTF-8 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 ** in the native byte order for [sqlite3_open16()]. ** An [sqlite3*] handle is usually returned in *ppDb, even ** if an error occurs. The only exception. ** ** The default encoding for the database will be UTF-8 if ** [sqlite3_open()] or [sqlite3_open_v2()] is called and ** UTF-16 in the native byte it acccepts if possible, or reading only if ** if the file is write protected. In either case the database ** must already exist or an error is returned. The third option ** opens the database for reading and writing and creates it if it does ** not already exist. ** The third options is behavior that is always used for [sqlite3_open()] ** and [sqlite3_open16()]. ** ** If the filename is ":memory:", then an private ** in-memory database is created for the connection. This in-memory ** database will vanish when the database connection is closed. Future ** version of SQLite might make use of additional special filenames ** that begin with the ":" character. It is recommended that ** when a database filename really does begin with ** ":" that you prefix the filename with a pathname like "./" to ** avoid ambiguity. ** ** If the filename is an empty string, then a private temporary ** on-disk database will be created. This private database will be ** automatically deleted as soon as the database connection is closed. ** **. ** ** hermer is V is */ ); /* ** CAPI3REF: Error Codes And Messages {F12800} ** **-language ** text that describes the error, as either UTF8 or UTF16 respectively. ** Memory to hold the error message string is managed internally. ** The application does not need to worry with freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions. ** ** INVARIANTS: ** ** {F12801} The [sqlite3_errcode(D)] interface returns the numeric ** [SQLITE_OK | result code] or ** [SQLITE_IOERR_READ | extended result code] ** for the most recently failed interface call associated ** with [database connection] D. ** ** {F12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)] ** interfaces return English-language text that describes ** the error in the mostly recently failed interface call, ** encoded as either UTF8 or UTF represent single SQL statements. This ** object {F13010} ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. ** ** The first argument "db" is an [database connection] ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] **. {END} ** **' or '\u0000' character or ** until the nByte-th byte, whichever comes first. {END} ** ** *pzTail is made to point to the first byte past the end of the ** first SQL statement in zSql. These routines only compiles the first ** statement in zSql, so *pzTail is left pointing to what remains ** uncompiled. ** ** *ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. Or if there is an error, *ppStmt is ** set to NULL. If the input text contains no SQL (if the input ** is and empty string or a comment) then *ppStmt is set to NULL. ** {U13018} The calling procedure is responsible for deleting the ** compiled SQL statement ** using [sqlite3_finalize()] after it has finished with it. ** ** On success, [SQLITE_OK] is returned. Otherwise an ** . {END}. {END} ** </li> ** ** <li> **> ** **, then SQL text is ** read from zSql is read up to the first zero terminator. ** ** {F13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)] ** and its variants is non-negative, then nBytes bytes **]) ** it first sets *ppStmt to NULL. */IREF: Retrieving Statement SQL {F13100} ** ** This intereface can be used to retrieve a saved copy of the original ** SQL text used to create a [prepared statement]. ** ** INVARIANTS: ** ** {F13101} If the [prepared statement] passed as ** the an argument to [sqlite3_sql()] was compiled ** compiled using either [sqlite3_prepare_v2()] or ** [sqlite3_prepare16_v2()], ** then [sqlite3_sql()] function returns a pointer to a ** zero-terminated string containing a UTF-8 rendering ** of the original SQL statement. ** ** {F13102} If the [prepared statement] passed as ** the an argument to [sqlite3_sql()] was compiled ** compiled using either [sqlite3_prepare()] or ** [sqlite3_prepare16()], ** then [sqlite3_sql()] function sqlite3_value} ** ** SQLite uses the sqlite3_value object to represent all values ** that can be stored in a database table. ** SQLite uses dynamic typing for the values it stores. ** Values stored in sqlite3_value objects can.) ** then there is no distinction between ** protected and unprotected sqlite3_value objects and they can be ** used interchangable. However, for maximum code portability it ** is recommended that applications make the distinction between ** between protected and unprotected sqlite3_value objects even if ** they are single threaded. ** **()]. All other ** interfaces that use sqlite3_value require protected sqlite3_value objects. */ typedef struct Mem sqlite3_value; /* ** CAPI3REF: SQL Function Context Object {F16001} ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. A pointer to an sqlite3_context ** object is always first parameter to application-defined SQL functions. */ typedef struct sqlite3_context sqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements {F13500} ** ** In the SQL strings input to [sqlite3_prepare_v2()] and its ** variants, literals may be replace by a parameter in one ** of these forms: ** ** <ul> ** <li> ? ** <li> ?NNN ** <li> :VVV ** <li> @VVV ** <li> $VVV ** </ul> ** ** In the parameter forms shown above NNN is an integer literal, ** VVV alpha-numeric parameter name. ** The values of these parameters (also called "host parameter names" ** or "SQL parameters") **" parameters is the value of NNN. ** The NNN value must be between 1 and the compile-time ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). ** ** The third argument is the value to bind to the parameter. ** ** In those ** routines that have a fourth argument, its value is the number of bytes ** in the parameter. To be clear: the value is the number of <u>bytes</u> ** in the value, ** string after SQLite has finished with it..ite3_prepare | occurances of the same ** parameter, or one more than the largest index over all ** parameters to the left if this is the first occurrance ** of this parameter, or 1 if this is the leftmost parameter. ** ** {F13521} The [sqlite3_prepare | SQL statement compiler] fail with ** an [SQLITE_RANGE] error if the index of an SQL parameter ** is less than 1 or greater than SQLITE_MAX_VARIABLE_NUMBER. ** ** V value ** V value after it has finished using the V value. ** ** -holders for values that are [sqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** This routine actually returns the index of the largest]. ** SQL parameters of the form ":AAA" or "@AAA" or "$AAA" have a name ** which is the string ":AAA" or "@AAA" or "$VVV". ** In other words, the initial ":" or "$" or "@" ** is included as part of the name. ** Parameters of the form "?" or "?NNN" have no name. ** ** The first host()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. ** ** INVARIANTS: ** ** {F13621} The [sqlite3_bind_parameter_name(S,N)] interface returns ** a UTF-8 rendering of the name of the SQL parameter in ** [prepared statement] S having index N, or ** NULL if there is no SQL parameter with index N or if the ** parameter with index N is an anonymous parameter "?" or ** a numbered parameter "?NNN". */|sqlite3_bind()]. A zero ** is returned if no matching parameter is found. The parameter ** name must be given in UTF-8 even if the original statement ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. ** ** INVARIANTS: ** ** {F13641} The [sqlite3_bind_parameter_index(S,N)] interface returns ** the index of SQL parameter} ** ** These routines return the name assigned to a particular column ** in the result set of a SELECT statement. The sqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated ** UTF16 string. The first parameter is the ** [prepared statement] that implements the SELECT statement. ** The second parameter is the column number. The left-most column is ** number 0. ** ** The returned string pointer is valid until either the ** [prepared statement] is destroyed by [sqlite3_finalize()] ** or until the next call. ** ** INVARIANTS: ** ** {F13721} A successful invocation of the [sqlite3_column_name(S,N)] ** interface returns the name ** of the Nth column (where 0 is the left-most column) for the ** result set of [prepared statement] S as a ** zero-terminated UTF-8 string. ** ** {F13723} A successful invocation of the [sqlite3_column_name16(S,N)] ** interface returns the name ** of the Nth column (where 0 is the left-most column) for the ** result set of [prepared statement] S as a ** zero-terminated UTF-16 string in the native byte order. ** ** {F13724} The [sqlite3_column_name()] and [sqlite3_column_name16()] ** interfaces return a NULL pointer if they are unable to ** allocate memory memory to hold there normal return strings. ** ** {F13725} If the N parameter to [sqlite3_column_name(S,N)] or ** [sqlite3_column_name16(S,N)] is out of range, then the ** interfaces returns indentifier **} ** ** [prepared statement] is destroyed using ** [sqlite3_finalize()] or until preprocessor symbol defined. ** ** [prepared statement] S ** is extracted, or NULL if the [prepared statement] S ** is extracted, or NULL if the [prepared statement] S ** is extracted, or NULL if the [prepared statement] S ** is extracted, or NULL if the [prepared statement] S ** is extracted, or NULL if the [prepared statement] S ** is extracted, or NULL if the: ** ** {U13751} If two or more threads call one or more ** [sqlite3_column_database_name|column metadata interfaces] ** the same [prepared statement] and result column ** at the same time then the results are undefined. */ {F13760} ** **. {END} **. ** ** INVARIANTS: ** ** {F13761} A successful call to [sqlite3_column_decltype(S,N)] ** returns a zero-terminated UTF-8 string containing the **} ** ** After an [prepared [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. ** ** INVARIANTS: ** ** {F13202} If [prepared statement] S is ready to be ** run, then [sqlite3_step(S)] advances that prepared statement ** until to completion or until it is ready to return another ** row of the result set or an interrupt appropraite error code that is not one of ** [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE]. ** ** {F15310} If an [sqlite3_interrupt|interrupt]} ** ** Return} ** ** These routines form the "result set query" interface. ** **-most column of the result set ** has an index of 0. ** ** If the SQL statement is not currently point to a valid row, or if the ** the column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call. ** **. ** ** The object returned by [sqlite3_column_value()] is an ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object ** may only be used()], ** then the behavior is undefined. ** **<br>Type <th> Requested<br <b>not</b> pass the pointers returned ** ]. ** ** INVARIANTS: ** ** {F13803} The [sqlite3_column_blob(S,N)] interface converts the ** Nth column in the current row of the result set ** [prepared statement] S into a floating point value and ** returns a copy of that value. ** ** {F13815} The [sqlite3_column_int(S,N)] interface converts the ** Nth column in the current row of the result set for ** [prepared statement] S into a 64-bit signed integer and ** returns the lower 32 bits of that integer. ** ** {F13818} The [sqlite3_column_int64(S,N)] interface converts the ** Nth column in the current row of the result set for ** [prepared statement] S into a 64-bit signed integer and ** returns a copy of that integer. ** ** {F13821} The [sqlite3_column_text(S,N)] interface converts the ** Nth column in the current row of the result set for ** [prepared statement] S into a zero-terminated UTF-8 ** string and returns a pointer to that string. ** ** {F13824} The [sqlite3_column_text16(S,N)] interface converts the ** Nth column in the current row of the result set ** [prepared statement] S. ** ** {F13830} The [sqlite3_column_value(S,N)] interface returns a ** pointer to an [unprotected sqlite3_value] object for the ** Nth column in the current row of the result set for ** [prepared statement] S. */ ** [prepared statement] S indicated an error, then ** [sqlite3_reset(S)] returns an appropriate [error code]. ** ** {F11338} The [sqlite3_reset(S)] interface does not change the values ** of any [sqlite3_bind_blob|bindings] on [prepared statement] S. */ int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions {F16100} ** KEYWORDS: {function creation routines} ** ** These two functions (collectively known as ** "function creation routines") parameter is the [database connection] to which the SQL ** function is to be added. If a single ** program uses more than one [database connection] internally, then SQL ** functions must be added individually to each [database connection]. ** **. ** ** INVARIANTS: ** ** {F16103} The [sqlite3_create_function16()] interface behaves exactly ** like [sqlite3_create_function()] in every way except that it ** interprets the zFunctionName argument as ** zero-terminated UTF-16 native byte order instead of as a ** zero-terminated UTF-8. ** ** {F16106} A successful invocation of ** the [sqlite3_create_function(D,X,N,E,...)] interface registers ** or replaces callback functions in [database connection] D ** used to implement the SQL function named X with N parameters ** and having a perferred finial} ** ** ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** ** These routines work only with [protected sqlite3_value] objects. ** Any attempt to use these routines on an [unprotected sqlite3_value] ** object results in undefined behavior. ** ** These routines work just like the corresponding ** [sqlite3_column_blob | sqlite3_column_* routines] except that ** these routines take a single [protected sqlite3_value] object. ** ** ** ** is called for a particular aggregate, SQLite allocates nBytes of memory ** zeros allocation N bytes of memory, ** zero that memory, and return a pointer to the allocationed **: Function Auxiliary Data {F16270} ** ** by the sqlite3_set_auxdata() function with the Nth argument ** value to the application-defined function. ** If no meta-data has been ever been set for the Nth ** argument of the function, or if the cooresponding function parameter ** has changed since the meta-data was set, then sqlite3_get_auxdata() ** returns a NULL pointer. ** ** The sqlite3_set_auxdata() interface saves the meta-data ** pointed to by its 3rd parameter as the meta-data meta-data when the corresponding function parameter changes ** or when the SQL statement completes, whichever comes first. ** ** SQLite is free to call the destructor and drop meta-data on ** any parameter of any function at any time. The only guarantee ** is that the destructor will be called before the metadata is ** dropped. ** ** In practice, meta-data} ** **() inerfaces set the result of ** the application defined function to be a BLOB containing all zero ** bytes and N bytes in size, where N is the value of the 2nd parameter. ** **8. SQLite ** interprets the string from sqlite3_result_error16() as UTF copy. ** ** The sqlite3_result_toobig() interface causes SQLite ** to throw an error indicating that a string or BLOB is to long ** to represent. The sqlite3_result_nomem() interface ** causes SQLite to throw an exception indicating that sqlite3_result_blob is the special constant SQLITE_STATIC, then ** SQLite assumes that the text or blob result is constant space and ** does not copy the space or call a destructor when it has ** finished using that result. ** If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** ** The sqlite3_result_value() interface sets the result of ** the application-defined function to be a copy the ** [unprotected sqlite3_value] object specified by the 2nd parameter. The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] ** so. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that recieved ** the [sqlite3_context] pointer, the results are undefined. ** **88 string ** V up through the first zero or until N bytes are read if N ** is positive. ** ** {F16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the ** return value of function C to be the UTF16 native byte order ** string V up through the first zero or until N bytes are read if N ** is positive. ** ** {F16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the ** return value of function C to be the UTF16 big-endian ** string V up through the first zero or until N bytes are read if N ** is positive. ** ** {F16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the ** return value of function C to be the UTF16 little-endian ** string V up through the first zero or until N bytes are read if N ** is positive. ** ** {F16448} The [sqlite3_result_value(C,V)] interface changes the ** return value of function C to} ** ** may. The ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that ** the routine expects pointers to 16-bit word aligned strings ** of UTF a copy of the void* passed as ** the fourth argument to sqlite3_create_collation() or ** sqlite3_create_collation16() as its first parameter. ** ** The remaining arguments to the application-supplied routine are two strings, ** each represented by a (length, data) pair and encoded in the encoding ** that was passed as the third argument when the collation sequence was ** registered. {END} The application defined collation()]. ** ** INVARIANTS: ** ** {F16603} A successful call to the ** [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface ** registers function F as the comparison function used to ** implement collation X [database connection] B on text values that ** use the collating sequence name: *** ** [sqlite3*] database handle to which a ** [prepared statement] belongs. ** The database handle returned by sqlite3_db_handle ** is the same database handle that was ** the first argument to the [sqlite3_prepare_v2()] or its variants ** that was used to create the statement in the first place. ** ** INVARIANTS: ** ** {F13123} The [sqlite3_db_handle(S)] interface returns a pointer ** to the [database connection] associated with ** [prepared statement] S. */ sqlite3 *sqlite3_db_handle(sqlite3 cancelled cancelled callback ** function F to be invoked with first parameter P whenever ** a table row is modified, inserted, or deleted} ** ** This routine enables or disables the sharing of the database cache ** and schema data structures between connections to the same database. ** Sharing is enabled if the argument is true and disabled if the argument ** is false. ** ** Cache sharing is enabled and disabled ** for an entire process. {END}. ** ** Virtual tables cannot be used with a shared cache. When shared ** cache is enabled, the [sqlite3_create_module()] API used to register ** virtual tables will always return an error. ** ** This routine returns [SQLITE_OK] if shared cache was ** enabled or disabled successfully. An labrary. labrary. ** ** . ** ** A negative or zero value for N means that there is no soft heap limit and ** [sqlite3_release_memory()] will only be called when memory is exhausted. ** The default value for the soft heap limit is zero. ** ** SQLite makes a best effort to honor the soft heap limit. ** But if the soft heap limit cannot} ** ** */ ); /* ** CAPI3REF: Load An Extension {F12600} ** ** } ** {F12620} ** ** So as not to open security holes in older applications that are ** unprepared to deal with extension loading, and as a means of disabling ** extension loading while evaluating user-entered SQL, the following ** API is provided to turn the [sqlite3_load_extension()] mechanism on and ** off. {F12622} It is off by default. {END} See ticket #1863. ** ** {F12621} Call the sqlite3_enable_load_extension() routine ** with onoff==1 to turn extension loading on ** and call it with onoff==0 to turn it back off again. {END} */ int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} ** ** {F12641} This function ** registers an extension entry point that is automatically invoked ** whenever a new database connection is opened using ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} ** ** This API can be invoked at program startup in order to register ** one or more statically linked extensions that will be available ** to all new database connections. ** ** {F12642} Duplicate extensions are detected so calling this routine multiple ** times with the same extension is harmless. ** ** {F12643} This routine stores a pointer to the extension in an array ** that is obtained from sqlite_malloc(). {END} If you run a memory leak ** checker on your program and it reports a leak because of this ** array, then invoke [sqlite3_reset_auto_extension()] prior ** to shutdown to free the memory. ** ** {F12644} Automatic extensions apply across all threads. {END} ** ** This interface is experimental and is subject to change or ** removal in future releases of SQLite. */ int sqlite3_auto_extension(void *xEntryPoint); /* ** CAPI3REF: Reset Automatic Extension Loading {F12660} ** ** {F12661} This function disables all previously registered ** automatic extensions. {END} This ** routine undoes the effect of all prior [sqlite3_auto_extension()] ** calls. ** ** {F12662} This call disabled automatic extensions in all threads. {END} ** **; /* ** CAPI3REF: Virtual Table Object {F18000} ** KEYWORDS:); }; /* ** CAPI3REF: Virtual Table Indexing Information {F18100} ** KEYWORDS: sqlite3_index_info ** ** /* ** CAPI3REF: Register A Virtual Table Implementation {F18200} ** ** */ ); /* ** CAPI3REF: Register A Virtual Table Implementation {F18210} ** ** */ ); /* ** CAPI3REF: Virtual Table Instance Object {F18010} ** KEYWORDS: sqlite3_vtab ** ** Every module implementation uses a subclass of the following structure ** to describe a particular instance of the module. */ }; /* ** CAPI3REF: Virtual Table Cursor Object {F18020} ** KEYWORDS: sqlite3_vtab_cursor ** ** */ }; /* ** CAPI3REF: Declare The Schema Of A Virtual Table {F18280} ** ** The xCreate and xConnect methods of a module use the following API ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */} ** ** An instance of this object represents an open BLOB on which ** incremental I/O can be preformed. **. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O {F17810} ** ** This interfaces opens a handle to the blob located ** in row iRow,, column zColumn, table zTable in database zDb; ** in other words, the same blob that would be selected by: ** ** <pre> ** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; ** </pre> {END} ** **()]. ** ** INVARIANTS: ** ** {F17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)] ** interface opens an [sqlite3_blob] object P on the blob ** in column C of table T in database B on [database connection] D. ** ** {F17814} A successful invocation of [sqlite3_blob_open(D,...)] starts ** a new transaction on [database connection] D if that connection ** is not already in a transaction. ** ** {F17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface opens the blob ** for read and write access if and only if the F parameter ** is non-zero. ** ** {F17819} The [sqlite3_blob_open()] interface returns )] will return ** information approprate for that error. */ int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); /* ** CAPI3REF: Close A BLOB Handle {F17830} ** ** Close an open [sqlite3_blob | blob handle]. ** ** Closing a BLOB shall cause the current transaction to commit ** if there are no other BLOBs, no pending prepared statements, and the ** database connection is in autocommit mode. ** If any writes were made to the BLOB, they might be held in cache ** until the close operation if they will fit. ** [sqlite3_get_autocommit | autocommit mode]. ** ** {F17839} The [sqlite3_blob_close(P)] interfaces closes the ** [sqlite3_blob] object P unconditionally, even if ** [sqlite3_blob_close(P)] returns something other than [SQLITE_OK]. ** */ int sqlite3_blob_close(sqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB {F17840} ** ** Return the size in bytes of the blob accessible via the open ** [sqlite3_blob] object} ** ** This function is used to read data from an open ** [sqlite3_blob |. ** ** On success, SQLITE_OK is returned. Otherwise, an ** [error code] or an [extended error code] is returned. ** ** INVARIANTS: ** ** {F17853} The [sqlite3_blob_read(P,Z,N,X)] interface reads N bytes ** beginning at offset X from ** the blob that [sqlite3_blob] object P refers to ** and writes those N bytes into buffer Z. ** ** {F17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the blob ** is less than N+X bytes, then the function returns [SQLITE_ERROR] ** and nothing is read from the blob. ** ** {F17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero ** then the function returns [SQLITE_ERROR] ** and nothing is read from the blob. ** ** {F17862} The [sqlite3_blob_read(P,Z,N,X)] interface returns [SQLITE_OK] ** if N bytes where successfully read into buffer Z. ** ** {F17865} If the requested read could not be completed, ** the [sqlite3_blob_read(P,Z,N,X)] interface returns an ** appropriate [error code] or [extended error code]. ** ** {F17868} If an error occurs during evaluation of [sqlite3_blob_read(D,...)] ** then subsequent calls to [sqlite3_errcode(D)], ** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return ** information approprate for that error. */ int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} ** **. If n is ** less than zero [SQLITE_ERROR] is returned and no data is written. ** ** On success, SQLITE_OK is returned. Otherwise, an ** [error code] or an [extended error code] is returned. ** ** INVARIANTS: ** ** {F17873} The [sqlite3_blob_write(P,Z,N,X)] interface writes N bytes ** from buffer Z into ** the blob that [sqlite3_blob] object P refers to ** beginning at an offset of X into the blob. ** ** {F17875} The [sqlite3_blob_write(P,Z,N,X)] interface returns ** [SQLITE_READONLY] if the [sqlite3_blob] object P was ** [sqlite3_blob_open | opened] for reading only. ** ** {F17876} In [sqlite3_blob_write(P,Z,N,X)] if the size of the blob ** is less than N+X bytes, then the function returns [SQLITE_ERROR] ** and nothing is written into the blob. ** ** {F17879} In [sqlite3_blob_write(P,Z,N,X)] if X or N is less than zero ** then the function returns [SQLITE_ERROR] ** and nothing is written into the blob. ** ** {F17882} The [sqlite3_blob_write(P,Z,N,X)] interface returns [SQLITE_OK] ** if N bytes where successfully written into blob. ** ** {F17885} If the requested write could not be completed, ** the [sqlite3_blob_write(P,Z,N,X)] interface returns an ** appropriate [error code] or [extended error code]. ** ** {F17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)] ** then subsequent calls to [sqlite3_errcode(D)], ** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return ** information approprate()]. */ sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); int sqlite3_vfs_unregister(sqlite3_vfs*); /* ** CAPI3REF: Mutexes /2, unix, and windows. ** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. The ** mutex interface routines defined here become external ** references in the SQLite library for which implementations ** must be provided by the application. This facility allows an ** application that links against SQLite to provide its own mutex ** implementation without having to modify the SQLite core. ** ** } The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_MEM2 ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU ** </ul> {END} ** ** . {END} ** ** {F17019} The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in ** use when they are deallocated. . {U17028} If the same thread tries to enter any other ** kind of mutex more than once, the behavior is undefined. ** {F17029} SQLite will never exhibit ** such behavior in its own use of mutexes. {END} ** ** Some systems (ex: windows95) do not the operation implemented by ** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will ** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} ** ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. {U17032} The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. {F17033} SQLite will ** never do either. {END} ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */*); /* ** CAPI3REF: Mutex Verifcation. . {END} ** ** {X17084} The implementation is not required to provided versions of these ** routines that actually work. ** If the implementation does not provide working ** versions of these routines, it should at least provide stubs ** that always return true so that one does not get spurious ** assertion failures. {END} ** ** . {END} */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ #define SQLITE_MUTEX_STATIC_LRU()]. {U11308} The underlying xFileControl method might ** also return SQLITE_ERROR. } ** ** The sqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. The first parameter_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes {F11410} ** ** These constants are the valid operation code parameters used ** as the first argument to [sqlite3_test_control()]. ** ** These parameters and their meansing are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the ** [sqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_FAULT_CONFIG 1 #define SQLITE_TESTCTRL_FAULT_FAILURES 2 #define SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES 3 #define SQLITE_TESTCTRL_FAULT_PENDING 4 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 #define SQLITE_TESTCTRL_PRNG_RESET 7 /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ #ifdef SQLITE_OMIT_FLOATING_POINT # undef double #endif #ifdef __cplusplus } /* End of the 'extern "C"' block */ #endif #endif
https://sqlite.org/src/artifact/7f1438fb2bef8eb1
CC-MAIN-2020-40
refinedweb
6,939
52.39
Chapter 3 Build Your First App in Swift and SwiftUI Learn by doing. Theory is nice but nothing replaces actual experience. – Tony Hsieh By now you should have installed Xcode and some understanding of Swift. If you have skipped the first two chapters, please stop here and go back to read them. You need to have Xcode installed in order to work on all exercises in this book. In the previous chapter, you have tried out to create some UI components with SwiftUI. In this chapter, we will dive a little bit deeper and give you a proper introduction of the SwiftUI framework. On top of that, you will have an opportunity to create your first iOS app. visually design the app UI or write the UI in code.. What that means to you is that the UI code is easier and more natural to write. Compared with the existing UI frameworks like UIKit, you can create the same UI with way less code. 3-2. That's the code you need to implement the heart button. In around 20 lines of code, you create an interactive button with a scale animation. This is the power of the SwiftUI declarative UI framework. Building Your First App Using SwiftUI That's enough for the background information of the SwiftUI framework. As I always said, you have to get your hands dirty to learn programming. Now it's time to fire up Xcode and write your first iOS app in SwiftUI. For the rest of the chapter, you will write code to try out different UI components such as Text, Image, Stack Views. Furthermore, you will learn how to detect tap gesture. By combining all the techniques, you will eventually build your first app. First, fire up Xcode and create a new project using the App template under the iOS category. Choose Next to proceed to the next screen. Next, set the name of the project to HelloWorld. Hello World is a program for the first-time programmer to create. It's a very simple program that outputs "Hello, World" on the screen of a device. While your first app will be more complicated than that, let's follow the programming tradition and name the project "HelloWorld". The organization identifier is a unique identifier of your app. Here I use com.appcoda but you should set it to your own value. If you have a website, set it to your domain in reverse domain name notation. Otherwise, you may use "com. Xcode now supports two ways to build user interace. Since this book is about SwiftUI, please set the Interface option to SwiftUI. For the programming language, you can set it to Swift. For both Use Core Data and Include Tests options, you can leave them unchecked. Click "Next" to continue. Xcode then asks you where to save the "HelloWorld" project. Pick any folder (e.g. Desktop) on your Mac. You may notice there is an option for source control. Just deselect it. Meanwhile, we do not need to use the option. Click "Create" to continue. After you confirm, Xcode automatically creates the "Hello World" project. The screen will look like the screenshot shown in figure 3-5. Familiarize Yourself with Xcode Workspace Before we start to implement the Hello World app, let's take a few minutes to have a quick look at the Xcode workspace environment. In the left pane is the project navigator. You can find all your project files in this area. The center part of the workspace is the editor area. You do all the editing stuff here (such as editing the project setting, source code file, user interface) in this area. Depending on the type of file, Xcode shows you different interfaces in the editor area. For instance, if you select HelloWorldApp.swift in the project navigator, Xcode displays the source code in the center area. Xcode comes with several themes for you to choose from. Say, if you prefer dark themes, you can go up to the menu and choose Xcode > Preferences > Themes to change it. If you select the ContentView.swift file, Xcode automatically resizes the code editor and displays an extra pane right next to it. This extra pane is the preview pane for the ContentView. If you can't see the design canvas, you can go up to the Xcode menu and choose Editor > Canvas to enable it. By default, the instant preview is paused. You can click the Resume button to render the app preview. After you click the button, Xcode renders the preview in a simulator that you choose in the simulator selection (e.g. iPhone 12 Pro). To give yourself more space for writing code, you can hide both the project navigator and the inspector (see figure 3-6). If you want to resize the preview, use the magnifying icons at the bottom-right corner. Run Your App for the First Time Until now, we haven't written a single line of code. The code in ContentView is generated by Xcode. Before we write our own code, let's try to run the app using the built-in simulator. This will give you an idea how to build and test your app in Xcode. In the toolbar, you should see the Run button. The Run button in Xcode is used to build an app and run it in the selected simulator. By default, the Simulator is set to iPod touch. If you click the iPod touch button, you'll see a list of available simulators such as iPhone SE and iPhone 12 Pro. Let's select iPhone 12 Pro as the simulator, and give it a try. Once selected, you can click the Run button to load your app in the simulator. Figure 3-7 shows the simulator of an iPhone 12 Pro. To terminate the app, simply hit the Stop button in the toolbar. Try to select another simulator (e.g. iPhone 12 mini) and run the app. You will see another simulator showing up on screen. The latest version of Xcode allows developers to run multiple simulators simultaneously. The simulator works pretty much like a real iPhone. You can click the home button (or press shift-command-h) to bring up the home screen. It also comes with some built-in apps. Just play around with it to familiarize yourself with Xcode and simulator environment. Working with Text Now that you should be familiar with the Xcode workspace, it's time to check out the SwiftUI code. The sample code generated in ContentView already shows you how to display a single line of text. You initialize a Text object and pass to it the text (e.g. Hello World) to display like this: Text("Hello World") The preview canvas then displays, font, weight) of a control by calling methods that are known as Modifiers. Let's say, you want to bold the text. You can use the modifier fontWeight and specify your preferred font weight (e.g. .bold) like this: Text("Stay Hungry. Stay Foolish.").fontWeight(.bold) a new view that has the bolded text. What is interesting in SwiftUI is that you can further chain this new view with other modifiers. Say, if you want to make the bolded text a little bit bigger, you write the code like this: Text("Stay Hungry. Stay Foolish.").fontWeight(.bold).font(.title) The font modifier lets you change the font properties. In the code above, we specify the title font type in order to enlarge the text. SwiftUI comes with several built-in text styles including title, largeTitle, body, etc. If you want to further increase the font size, replace .title with .largeTitle. The code will be hard to read if we continue to chain more modifiers in the same line of code. Therefore, we usually write the code in the following format by breaking it into multiple lines: Text("Stay Hungry. Stay Foolish.") .fontWeight(.bold) .font(.title) The functionality is the same but I believe you'll find the code above more easy to read. We will continue to use this coding convention for the rest of this book. The font modifier also lets you change the text design. Let's say, you want the font to be rounded. You can write the font modifier like this: .font(.system(.title, design: .rounded)) Here you specify to use the system font with title text style and rounded design. The preview canvas should immediately respond to the change and show you the rounded text. Working with Buttons Button is another common UI components you need to know. It is a very basic UI control which has the ability to handle users' touch, and trigger a certain action. To create a button using SwiftUI, you just need to use the code snippet below to create a button: Button { // What to perform } label: { // How the button looks like } When creating a button, you need to provide two code blocks: - What action to perform - the code to perform after the button is tapped or selected by the user. - How the button looks - the code block that describes the look & feel of the button. For example, if you just want to turn the Hello World label into a button, you can update the code like this: struct ContentView: View { var body: some View { Button { } label: { Text("Hello World") .fontWeight(.bold) .font(.system(.title, design: .rounded)) } } } The Hello World text becomes a tappable button, even though we didn't specify any follow-up actions. The text color is automatically changed to blue because this is the default color for buttons in iOS. You have to run the app before you can try out the button. Click the Play button in the simulator dock (figure 3-12) to switch to the interactive mode. Though the button doesn't perform any actions, you should see a blink effect when tapping the button. Customizing the Button Style Similar to Text, you can customize the color of the button by attaching some modifiers. For example, you can attach the foregroundColor and background modifiers to make a purple button. Button { } label: { Text("Hello World") .fontWeight(.bold) .font(.system(.title, design: .rounded)) } .foregroundColor(.white) .background(Color.purple) After the change, your button should look like the figure below. As you can see, the button doesn't look very good. Wouldn't it be great to add some space around the text? To do that, you can use the padding modifier like this: SwiftUI also makes it very easy to create a button with rounded corners. You just need to attach the cornerRadius modifier to the Button view and specify the corner radius like this: .cornerRadius(20) The value of cornerRadius describes how rounded the corners of the button. A larger value produces a more rounded corner, while a smaller value achieves a shaper corner. You can change the corner radius to other values to see the effect. Adding the Button Action A button is not useful if it doesn't perform any actions. What we are going to implement is to make the button speak. When the button is tapped, it will speak "Hello World!" This doesn't sound easy, right? We have to deal with text-to-speech. That said, Apple has made this very easy even for beginners. As I mentioned before, the iOS SDK has bundled many amazing frameworks for developers to use. We are now using the SwiftUI framework to create user interface. To perform text-to-speech, we can rely on the AVFoundation framework. Before we can use the framework, we have to import it at the beginning of the code. Right below import SwiftUI, insert the following import statement: import AVFoundation Next, update the code of Button like this:) Here, we added 4 lines of code in the action block. That's the code you need to instruct iOS to speak a piece of text for you. The first line of code specifies the text (i.e. "Hello World"), while the second line of code sets the voice to British English. The rest of the lines are to create the speech synthesizer and speak out the text with the chosen voice. To test the app, click the Play button in the simulator dock. Then click the Hello World button to test out text-to-speech. If you can't hear the voice, please check if your speaker is turned on and not muted. Introducing Stack Views Your first app works great, right? With just around 10 lines of code, you already created an app that can translate text into speech. Presently, the button is designed to speak "Hello World". What if you want to create another button, which speaks a different sentence or words, above the Hello World button? How can you arrange the UI layout? SwiftUI provides a special type of views known as Stack Views for you to construct complex user interfaces. More specifically, stack views lets you arrange multiple views (or UI components) in vertical or horizontal direction. For example, if you want to add a new button above the Hello World button, you can embed both buttons in a VStack like this: VStack { // New Button // Hello World Button } VStack is a vertical stack view for laying out views vertically. The order of the views inside a VStack determines how the embedded views are arranged. In the code above, the new button will be placed on the top of the Hello World button. Now let's modify the actual code to see the changes in action. To embed the Hello World button in a VStack, you can hold the command key and click Button. In the context menu, choose Embed in VStack. Xcode then wraps the Hello World button in a VStack view. Once you embedded the Hello World button in the VStack, duplicate the code of the Hello World button to create the new button like this: VStack { Button { let utterance = AVSpeechUtterance(string: "Happy Programming") utterance.voice = AVSpeechSynthesisVoice(language: "en-GB") let synthesizer = AVSpeechSynthesizer() synthesizer.speak(utterance) } label: { Text("Happy Programming") .fontWeight(.bold) .font(.system(.title, design: .rounded)) } .padding() .foregroundColor(.white) .background(Color.yellow) .cornerRadius(20)) } The label of the new button is changed to Happy Programming and its background color is also updated to Color.yellow. On top of these changes, the string parameter of AVSpeechUtterance is changed to "Happy Programming." You can refer to figure 3-18 for the changes. This is how you arrange two buttons vertically. You can run the app for a quick test. The Happy Programming button works exactly the same as the Hello World button, but it speaks "Happy Programming!" Understanding Methods Before we end this chapter, let me introduce another basic programming concept. Take a look at the code of ContentView again. There are quite a lot of similarities and duplicated code for the two buttons. One duplicate is the code in the action block of the buttons. Both block of code are nearly the same except that the text to read is different. One is "Happy Programming", the other is "Hello World." In Swift, you can define a method for this type of repetitive tasks. In this case, we can create a method named speak inside ContentView like this: func speak(text: String) { let utterance = AVSpeechUtterance(string: text) utterance.voice = AVSpeechSynthesisVoice(language: "en-GB") let synthesizer = AVSpeechSynthesizer() synthesizer.speak(utterance) } The func keyword is used to declare a method. Following the func keyword is the name of the method. This name identifies the method and makes it easy for the method to be called elsewhere in your code. Optionally, a method can take in parameters as input. The parameters are defined within the parentheses. Each of the parameters should have a name and a type, separated by a colon ( text parameter which has the type String. :). In this example, the method accepts a In the method, that's the 4 lines of code for converting text into speech. The only change is this line of code: let utterance = AVSpeechUtterance(string: text) We set the string parameter to text, which is the text passed by the method caller. Now that we have created the method, how can we call it? You just need to use the method name and pass it the required parameter like this: speak(text: "Hello World") Let's go back to the ContentView struct to modify the code. First, create the speak(text: String) method as shown in figure 3-20. Next, you can replace the action block of both button by calling the speak method. This new method doesn't change the functionality of the application. Both buttons work exactly the same as before. However, as you can see from the final code, it's easier to read and much cleaner. And, what if you need to introduce another text-to-speech button to the application? You no longer need to duplicate the 4 lines of code but just call the speak method with the text to read. This is why we need to group common operations into methods. Exercise In order to help you fully understand how to work with buttons and methods, here is a simple exercise for you. Your task is to modify the existing code and build a "Guess These Movies" app. The UI and functions are very similar to the Hello World app. Each button displays a set of emoji icons. The player's task is to guess the movie's name from those emojis. By tapping the button, the app will speak out the correct answer. For example, when the player taps the button in blue, the app reads "The answer is Ocean 11!" Summary Congratulations! You've built your first iPhone app. It's a simple app, but I believe you already have a better understanding of Xcode, SwiftUI, and the built-in frameworks provided by the iOS SDK. It's easier than you thought, right? To access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.
https://www.appcoda.com/learnswift/swiftui-basics.html
CC-MAIN-2022-21
refinedweb
3,023
74.29
tag:code.tutsplus.com,2005:/categories/google-chrome Envato Tuts+ Code - Google Chrome 2015-07-06T17:00:48Z tag:code.tutsplus.com,2005:PostPresenter/cms-24205 Debugging Android Apps with Facebook's Stetho <h2>Introduction</h2> <p><a href="">Stetho</a>.</p> <p>In this tutorial, you are going to learn how to add Stetho to an Android project and use both Google Chrome’s developer tools and Stetho’s command line utility, <strong>dumpapp</strong>, to debug it.</p> <h2>1. Adding Gradle Dependencies</h2> <p>To add the Stetho library to your project, add <code class="inline">com.facebook.stetho:stetho</code> as a <code class="inline">compile</code> dependency in the <code class="inline">app</code> module’s <strong>build.gradle</strong> file:</p> <pre class="brush: java noskimlinks noskimwords"> compile 'com.facebook.stetho:stetho:1.1.1' </pre> <p>In this tutorial, you will be using <strong>OkHttp</strong>, a popular networking library from Square, to manage all network connections, because it plays really well with Stetho. Add it as another <code class="inline">compile</code> dependency:</p> <pre class="brush: java noskimlinks noskimwords"> compile 'com.facebook.stetho:stetho-okhttp:1.1.1' </pre> <h2>2. Initializing Stetho</h2> <h3>Step 1: Creating a Custom <code class="inline">Application</code> Class</h3> <p>The best time to initialize Stetho is when your application is starting. Therefore, you have to create a new class that extends <code class="inline">Application</code> and initialize Stetho inside its <code class="inline">onCreate</code> method.</p> <p>Create a new class called <strong>MyApplication</strong> and override its <code class="inline">onCreate</code> method:</p> <pre class="brush: java noskimlinks noskimwords"> public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); } } </pre> <p>To initialize Stetho, you must first create an instance of <code class="inline">Stetho.InitializerBuilder</code>, using the <code class="inline">Stetho.newInitializerBuilder</code> method. Next, to allow Stetho to work with Chrome’s developer tools, you must call <code class="inline">enableWebKitInspector</code>. If you also want to enable dumpapp, you must call <code class="inline">enableDumpapp</code>. Once <code class="inline">Stetho.InitializerBuilder</code> is ready, you can call its <code class="inline">build</code> method to generate an <code class="inline">Initializer</code> object and pass it to the <code class="inline">Stetho.initialize</code> method.</p> <p>For now, let’s enable the default functionality by using the default <code class="inline">InspectorModulesProvider</code> and <code class="inline">DumperPluginsProvider</code>. Add the following code to the <code class="inline">onCreate</code> method:</p> <pre class="brush: java noskimlinks noskimwords"> //); </pre> <h3>Step 2: Editing the Manifest</h3> <p>To let the Android operating system know that you have a custom <code class="inline">Application</code> class, add an attribute called <code class="inline">android:name</code> to the manifest’s <code class="inline">application</code> tag and set the value to the name of your custom <code class="inline">Application</code> class.</p> <pre class="brush: xml noskimlinks noskimwords"> <application android: ... </application> </pre> <h2>3. Using Chrome’s DevTools</h2> <p>After compiling and installing your app on an Android device (or the emulator), start Google Chrome and type in <strong>chrome://inspect</strong> in the address bar. You will see a screen that looks like this:</p> <figure class="post_image"> <img data- </figure> <p>Click the <strong>inspect</strong> link to open the <strong>Developer Tools</strong>.</p> <figure class="post_image"> <img data- </figure> <h3>Step 1: Inspecting Network Connections</h3> <p>Stetho allows you to inspect, in real time, the network connections that your app makes. However, in Stetho version 1.1.1, this only works with the OkHttp network library. When using OkHttp with Stetho, you should remember to add a <code class="inline">StethoInterceptor</code> to the <code class="inline">OkHttpClient</code> object’s <code class="inline">List</code> of network interceptors.</p> <p>Here’s some sample code that connects to <a href="">HttpBin</a> and retrieves a JSON document:</p> <pre class="brush: java noskimlinks noskimwords"> //()); } </pre> <p>When the code runs, you will see the following in the <strong>Network</strong> tab of the <strong>Developer Tools</strong> window:</p> <figure class="post_image"> <img data- </figure> <p>If you click the URL in the first column, you will be taken to a screen that displays more information about the response:</p> <figure class="post_image"> <img data- </figure> <h3>Step 2: Querying SQLite Databases</h3> <p>With Stetho, you can perform a lot of operations on your app’s SQLite databases. Click the <strong>Resources</strong> tab and select <strong>Web SQL</strong>. If your app has any SQLite databases, they will be listed here. Selecting a database shows a list of the tables in the database. Finally, clicking a table displays the records of the table:</p> <figure class="post_image"> <img data- </figure> <p>You can also execute SQL queries after selecting a SQLite database:</p> <figure class="post_image"> <img data- </figure> <h3>Step 3: Manipulating Your App’s Preferences</h3> <p>To view your app’s <code class="inline">SharedPreferences</code>, open the <strong>Resources</strong> tab of the <strong>Developer Tools</strong> window and select <strong>LocalStorage</strong>. You will see the names of the files your app uses to store the preferences. Clicking a file displays the key-value pairs stored in that file:</p> <figure class="post_image"> <img data- </figure> <p>You can even edit the values stored in a file:</p> <figure class="post_image"> <img data- </figure> <p>Note that any changes you make to the values are permanent.</p> <h2>4. Using dumpapp</h2> <h3>Step 1: Downloading dumpapp</h3> <p>dumpapp is a powerful utility that allows you to manipulate your Android app from the command line. You can get it by cloning <a href="">Stetho’s repository</a>:</p> <pre class="brush: bash noskimlinks noskimwords"> git clone </pre> <p>Because dumpapp is a Python script, you should have the latest version of Python installed on your computer to use it.</p> <h3>Step 2: Using Plugins</h3> <p>To view a list of available plugins, enter the <strong>stetho/scripts</strong> directory and execute the following command:</p> <pre class="brush: bash noskimlinks noskimwords"> ./dumpapp -l </pre> <p>The output looks something like this:</p> <figure class="post_image"> <img data- </figure> <p>Let’s use the plugin called <strong>prefs</strong>. This plugin is used to view and edit the values stored in your app’s <code class="inline">SharedPreferences</code>. For example, the following command lists all the key-value pairs stored in your app’s <code class="inline">SharedPreferences</code>:</p> <pre class="brush: bash noskimlinks noskimwords"> ./dumpapp prefs print </pre> <p>The output looks something like this:</p> <figure class="post_image"> <img data- </figure> <h3>Step 3: Creating a Custom Plugin</h3> <p>Custom dumpapp plugins are simply Java classes that implement the <code class="inline">DumperPlugin</code> interface. Let’s create a simple plugin that prints the package name of the app being tested.</p> <p>Create a new class inside the <code class="inline">MyApplication</code> class called <strong>MyDumperPlugin</strong>. After overriding the methods of the <code class="inline">DumperPlugin</code> interface, your class should look like this:</p> <pre class="brush: java noskimlinks noskimwords"> class MyDumperPlugin implements DumperPlugin { @Override public String getName() { } @Override public void dump(DumperContext dumpContext) throws DumpException { } } </pre> <p>The <code class="inline">getName</code> method should return the name of the plugin. To return the value <strong>my_plugin</strong>, add the following code to the <code class="inline">getName</code> method:</p> <pre class="brush: java noskimlinks noskimwords"> return "my_plugin"; </pre> <p>The <code class="inline">dump</code> method is the method that is called when you run the plugin from the command line. The <code class="inline">DumperContext</code> provides various I/O streams, which allow you to read from the command line or write to it. For now, we will just be using the standard output. Add the following code to the <code class="inline">dump</code> method to get a reference to the standard output stream:</p> <pre class="brush: java noskimlinks noskimwords"> PrintStream out = dumpContext.getStdout(); </pre> <p>Because this plugin is part of the <code class="inline">MyApplication</code> class, to get the package name of the app, you can directly call the <code class="inline">getPackageName</code> method. Once you have the package name, print it using the <code class="inline">PrintStream</code> object’s <code class="inline">println</code> method:</p> <pre class="brush: java noskimlinks noskimwords"> out.println(MyApplication.this.getPackageName()); </pre> <p>Your custom plugin is now ready to use.</p> <h3>Step 4: Creating a Custom Plugins Provider</h3> <p>The plugin you created in the previous step will not be available to Stetho unless you create a custom plugins provider and use it while initializing Stetho. A custom plugins provider is a class that implements the <code class="inline">DumperPluginsProvider</code> interface.</p> <p>Let’s create a custom plugins provider called <strong>MyDumperPluginsProvider</strong>. Create this class inside the <code class="inline">MyApplication</code> class. After overriding the only method of the <code class="inline">DumperPluginsProvider</code> interface, your class should look like this:</p> <pre class="brush: java noskimlinks noskimwords"> class MyDumperPluginsProvider implements DumperPluginsProvider { @Override public Iterable<DumperPlugin> get() { } } </pre> <p>Because the <code class="inline">get</code> method returns an <code class="inline">Iterable</code>, all you have to do is create a list, add your custom plugin to the list, and return the list. The code for doing that would look like this:</p> <pre class="brush: java noskimlinks noskimwords"> // Create a list ArrayList<DumperPlugin> plugins = new ArrayList<>(); // Add one or more custom plugins plugins.add(new MyDumperPlugin()); // Return the list return plugins; </pre> <p>However, because your custom plugins provider’s <code class="inline">Iterable</code> does not include the default plugins, you won’t be able to use them while running dumpapp. If you want to use both the custom and the default plugins together, you should add the default plugins to your <code class="inline">ArrayList</code>. To get the list of default plugins, you have to call the <code class="inline">get</code> method of the plugins provider returned by the <code class="inline">defaultDumperPluginsProvider</code> method.</p> <pre class="brush: java noskimlinks noskimwords"> // Add default plugins to retain original functionality for(DumperPlugin plugin:Stetho.defaultDumperPluginsProvider(MyApplication.this).get()){ plugins.add(plugin); } </pre> <p>Your custom plugins provider is now ready. To use it, go to the <code class="inline">onCreate</code> method and pass an instance of it to the <code class="inline">enableDumpapp</code> call:</p> <pre class="brush: java noskimlinks noskimwords"> initializerBuilder.enableDumpapp(new MyDumperPluginProvider()); </pre> <h3>Step 5: Using the Custom Plugin</h3> <p>List all the available plugins again using the <code class="inline">dumpapp -l</code> call. You will see the name of your custom plugin in the list:</p> <figure class="post_image"> <img data- </figure> <p>To run it, execute the following command:</p> <pre class="brush: bash noskimlinks noskimwords"> ./dumpapp my_plugin </pre> <p>It should print the package name of your app:</p> <figure class="post_image"> <img data- </figure> <h2>Conclusion</h2> <p.</p> <p>To learn more about Stetho, refer to the code and documentation that’s available on <a href="">GitHub repository</a>.</p> 2015-07-06T17:00:48.000Z 2015-07-06T17:00:48.000Z Ashraff Hathibelagal tag:code.tutsplus.com,2005:PostPresenter/cms-21549 Google I/O 2014 Aftermath .</p><h2>Android L </h2><p>Android is getting a major overhaul with its next version, which is currently being referred to as<b> </b><b>Android L</b>. The new version will tout more than 5,000 new APIs, multiple new features, a new runtime engine, and a major user interface makeover.</p><p.</p><h3>Material Design</h3><p>Android L will be sporting a brand, new user interface that Google refers to as <b>Material Design</b>. It's sleek, fresh, and it has a modern look to it. It's everything you'd expect from a user interface update. However, Material Design has lot more <b>depth</b> to it, which literally is one of the key concepts of Material design. You can specify a view's elevation, allowing you to raise user interface elements and cast dynamic shadows.</p><figure class="post_image"><img alt="" data-</figure><p.</p><h3>Widgets</h3><p>Android L also includes two new user interface widgets. <code class="inline">RecyclerView</code> is a more advanced and flexible version of the <code class="inline">ListView</code> class and is ideal for listing elements that change dynamically. The <code class="inline">RecyclerView</code> class provides a layout manager for item positioning and default animations.</p><p>The <code class="inline">CardView</code> class extends <code class="inline">FrameLayout</code>, which you may already be familiar with. <code class="inline">CardView</code> will let you place information inside cards that can be easily modified. The background color, corner radius, and elevation of a card can all be changed.</p><h3>Animations</h3><p>Animations are an important element of Material Design. The material theme includes default animations, which can be easily modified. A new set of APIs also let you create custom animations. The new animation APIs let you:</p><ul> <li>respond to touch events with touch feedback animations</li> <li>hide and show views with reveal effect animations</li> <li>switch between activities with custom <b>activity transition </b>animations</li> <li>create more natural animations with <b>curved motion</b> </li> <li>animate changes in one or more view properties with <b>view state change</b> animations</li> <li>show animations in <b>state list drawables</b> between view state changes</li> </ul><h3>Notifications</h3><p>Notifications have been further improved and will now show up on the lock screen. In addition to this, there's a <b>heads-up notification</b> that can appear at the top of a full-screen application and is dismissible with a simple swipe.</p><figure class="post_image"><img alt="" data-</figure><h3>Runtime</h3><p>The <b>Dalvik</b> runtime will be replaced with <b>ART</b>, which has plenty of new features to justify a changing of the guard.</p><ul> <li>Ahead-of-Time (AOT) compilation</li> <li>improved garbage collection (GC)</li> <li>improved debugging support</li> </ul><p>You can find more information at the <a href="" rel="external" target="_blank">Android Developer website</a>.</p><h3>Project Volta</h3><p>Project Volta is a part of Android L and is dedicated to improving battery performance. It is comprised of three parts:</p><ul> <li> <b>Battery Historian</b> is a new tool designed to measure battery discharge by visualizing an application's power consumption.</li> <li>The goal of the <b>Android Job Scheduler</b> is to improve an application's power consumption. One of the tasks of the Android Job Scheduler API is scheduling maintenance tasks while the device charging.</li> <li> <b>Battery Saver mode</b> can be used to clock down the CPU, decrease the screen's refresh, or turn off background data. Battery Saver mode can be triggered manually or set to start automatically when the battery reaches a certain level.</li> </ul><h3>Recent Apps Screen</h3><p>Android's <b>Recent Apps</b> interface was previously limited to a single instance of an app. In Android L, developers will be able to mark an activity within your app and have it treated as a new task by the Recent Apps screen.</p><p>Android L will include many of other improvements, including graphical improvements and updates to <code class="inline">WebView</code>. More information can be found at the <a href="" rel="external" target="_blank">Android Developer website</a>.</p><h2>Integration</h2><p>The coming together of Android and Chrome has been talked about for some time. Google I/O showed off a number of ways in which this will start to happen.</p><h3>Polymer</h3><p><b><a href="" rel="external" target="_blank">Polymer</a></b> allows for web components to be built and placed in HTML. It takes an object approach to web development and allows for extremely complex and flexible objects to be easily imported to any web application. Objects can be placed at the DOM level with a simple element tag.</p><figure class="post_image"><img alt="" data-</figure> <a href="" rel="external" target="_blank">Google Design website</a>.</p><h3>Mobile Web Experience</h3><p.</p><p>App indexing has been improved. Information from Google search results can now be opened by an appropriate app, given the right scenario. For example, a search for restaurants will return results in the browser, but you will also have the option to view the results in, for example, <a href="" rel="external" target="_blank">OpenTable</a> for Android.</p><h3>Chromebooks</h3><p>Any remaining doubts or questions about Chromebooks have been put to rest during this year's Google I/O. It's clear Chromebooks are a hit, with the top ten rated laptops on Amazon all being Chromebooks.</p><p>Further improvements have been made to Chromebooks to integrate them more with Android. These include incoming calls and alerts from your phone appearing on your Chromebook and unlocking your Chromebook by having your phone in proximity.</p><p>The most significant announcement, however, is that Android apps will be able to run on Chromebooks. During the keynote, <a href="" rel="external" target="_blank">Evernote</a> for Android was showcased running on a Chromebook. The popular <a href="" rel="external" target="_blank">Vine</a> for Android application was able to use the Chromebook's camera to create a video. This is very exciting and looks promising for the future.</p><h2>Android everywhere</h2><p>Android is set to be coming to a screen near you, any screen.</p><h3>Android Wear </h3><p><b><a href="" rel="external" target="_blank">Android Wear</a></b> was officially released. Android Wear continues the Android experience onto your wrist and into a smaller form factor. It pairs with any smartphone running <b>4.3 or higher</b>, and can receive and show notifications from your Android apps.</p><p>Applications can also show content on the Wear device. <b><a href="" rel="external" target="_blank">Google Now</a></b> cards are a great example, showing you information as and when it becomes relevant.</p><figure class="post_image"><img alt="" data-</figure><p>Much like the Recent Apps screen on phones and tablets, content can be navigated by swiping up or down, and dismissed by swiping left or right. Android Wear also takes advantage of Google voice search and allows you to perform searches or issue commands.</p><p>Two devices went on pre-order after the event. The <b><a href="" rel="external" target="_blank">LG G Watch</a></b> will ship on July 2 and will cost $229. The <b><a href="" rel="external" target="_blank">Samsung Gear Live</a></b> will ship on July 7 and will cost $199.</p><figure class="post_image"><img alt="" data-</figure><p>Both devices have a similar form factor and comparable specifications. They run on a 1.2GHz CPU, have 4GB of storage, and sport 512MB of RAM.<br></p><p>Motorola will also be releasing a Wear device later in this year, the <a href="" rel="external" target="_blank">Moto 360</a>, which will be the first smartwatch to feature a circular watch face.</p><figure class="post_image"><img alt="" data-</figure><p>Android Wear seems to be a solid platform, or an extension to Android, and will drastically reduce the number of times you need to take your phone out of your pocket.</p><h3>Android Auto</h3><p><b><a href="" rel="external" target="_blank">Android Auto</a></b> will bring some of Google's best features to your car. It strips down the Android experience and takes the most relevant aspects to driving, optimizing them for a dashboard user experience.</p><p><a href="" rel="external" target="_blank">Google Voice Search</a> is an important part of this experience. It can be initiated from the push of a button located near the steering wheel, allowing for commands to be issued hands-free. This should create a more familiar, intelligent, and safer drive.</p><h3>Android TV</h3><p><b><a href="" rel="external" target="_blank">Android TV</a></b>.</p><p>It will also include Google Voice Search, which lends itself well to sitting back on the sofa. Google TV will come with full <b><a href="" rel="external" target="_blank">Chromecast</a></b> support.</p><p>Gaming is also getting a big push for Android TV, with many games already announced as being compatible on launch and the ability for multiplayer games to be played across devices.</p><p>Android TV is available for manufactures to embed into their television sets and also as set-top boxes. Google Play will be opening its doors to Android TV in the fall.</p><h3>Chromecast </h3><p>Chromecast continued to add new features. You can now use Chromecast when the casting and receiving devices are not on the same Wi-Fi network. The content will be sent via the cloud and a pin authentication system will be used for security.</p><p>You will soon be able to cast the entire screen of your Android device, enabling you to show anything, regardless of the app you're running. This will initially be limited to a selection of devices.</p><h2>Google at Work</h2><p.</p><p.</p><h2>Cloud Services</h2><p>Google Cloud Services saw new features with new debugging, tracing, and monitoring tools.</p><p>Google also announced <b><a href="" rel="external" target="_blank">Cloud Save</a></b>, <a href="" rel="external" target="_blank">Google BigQuery</a>.</p><h2>Google Fit</h2><p>With the trending of health and fitness, technology and apps, it was no surprise to hear that Google had something in store related to fitness.</p><figure class="post_image"><img alt="" data-</figure><p>The new <b><a href="" rel="external" target="_blank">Google Fit</a></b> platform will allow developers to track fitness data, synchronize it across devices, and store it in a central location. A few major brands, such as Nike and Adidas, have already confirmed that they'll be using the service.</p><h2>Conclusion</h2><p.</p><p>With all that was announced, I did notice the omission of anything relating to a smart home and Google Glass. It is odd that Google made no mention of last year's biggest announcement.</p> 2014-07-01T15:45:49.000Z 2014-07-01T15:45:49.000Z Leif Johnson tag:code.tutsplus.com,2005:PostPresenter/cms-21565 Deb.js: the Tiniest Debugger in the World <p <a href="">Deb.js</a>, a small JavaScript library that helps you to debug from within the browser.<br></p> <h2>The Example</h2> <p>Let's start by creating a simple page with some JavaScript interaction. We will create a form with two fields and a button. Once the user clicks on the button, we will collect the data and will output a message in the console. Here is the page's markup:</p> <pre class="brush: html noskimlinks noskimwords"><form> <label>Name:</label> <input type="text" name="name" /> <label>Address:</label> <input type="text" name="address" /> <input type="button" value="register" /> </form> <div data-</div> </pre> <p>In order to simplify the example, we will use jQuery for the DOM selection and events. We will wrap the functionality in the following module:</p> <pre class="brush: javascript noskimlinks noskimwords">var Module = { collectData: function(cb) { var name = $('[$('[<img alt="" data-</figure><p>When there is no data, our script works as expected. There is <code>Missing data</code> text displayed below the form. However, if we add something into the fields and press the button, we get an: <code>Uncaught TypeError: Cannot read property 'msg' of null</code>, message. Now, let's hunt down the bug and remove it.<br></p> <h2>The Traditional Approach</h2> <p>Google Chrome has wonderful instruments for solving such problems. We may click on the thrown error and see its stack trace. We could even go to the exact place where the error was produced.</p><figure class="post_image"><img alt="" data-</figure> <p>It looks like the <code>error</code> method of our module receives something that is <code>null</code>. And of course, <code>null</code> doesn't have a property called <code>msg</code>. That's why the browser throws the error. There is only one place where the <code>error</code> function is invoked. Let's put a breakpoint in and see what happens:</p><figure class="post_image"><img alt="" data-</figure> <p>It looks like we received the right <code>data</code> object and <code>error</code> is equal to <code>null</code>, which is the correct behavior. So, the problem should be somewhere in the <code>if</code> clause. Let's add a <code>console.log</code> and see if we are going in the right direction:</p> <pre class="brush: javascript noskimlinks noskimwords">Module.collectData(function(err, data) { console.log(typeof err); if(typeof err === 'object') { Module.error(err); } else { Module.success(data); } }); </pre> <p>And indeed, the <code>typeof err</code> returns <code>object</code>. That's why we are always showing an error.</p><figure class="post_image"><img alt="" data-</figure> <p>And voila, we found the problem. We just have to change the <code>if</code> statement to <code>if (err)</code> and our little experiment will work as expected. </p> <p>However, this approach can be difficult sometimes so consider the following pointers:</p> <ul> <li>As we saw, we ended with logging a variable. So, setting the breakpoint is not always enough. We have to jump to the console too. At the same time, we have to look at our code editor and the Chrome's debugging panel. These are several different places to work in, both of which could be annoying.</li> <li>It is also a problem if we have a lot of data logged into the console. Sometimes it is difficult to find out the needed information.</li> <li>This approach doesn't help if we have a performance issue. More often than not, we will need to know the execution time.</li> </ul> <p>Stopping the program at runtime and checking its state is priceless but there is no way for Chrome to know what we want to see. As it just so happened in our case, we have to double check the <code>if</code> clause. Wouldn't it be better if we had a tool directly accessible from within our code? A library that brings similar information like the debugger, but lives inside the console? Well, <a href="">Deb.js</a> could be the answer to this question.</p> <h2>Using Deb.js</h2> <p><a href="">Deb.js</a> is a tiny piece of JavaScript code, 1.5 kilobytes minified, that sends information to the console. It could be attached to every function and prints out:</p> <ul> <li>The function's execution place and time</li> <li>Stack trace</li> <li>Formatted and grouped output</li> </ul> <p>Let's see what our example looks like, when we use Deb.js:</p><figure class="post_image"><img alt="" data-</figure> <p>We again see the exact passed arguments and the stack trace. However, notice the change in the console. We work on our code, find out where the problem may be and add <code>.deb()</code> after the function's definition. Notice that the type of the <code>err</code> is placed nicely inside the function. So, we don't have to search for it. The output is also grouped and painted. Every function that we want to debug will be printed with a different color. Let's now fix our bug and place another <code>deb()</code> to see how it looks.</p><figure class="post_image"><img alt="" data-</figure> <p>Now we have two functions. We could easily distinguish between them because they are in different colors. We see their input, output and execution time. If there are any <code>console.log</code> statements, we will see them inside the functions where they occur. There is even an option to leave a description for better function recognition.</p> <p>Notice that we used <code>debc</code> and not <code>deb</code>. It's the same function, but the output collapses. If you start using <a href="">Deb.js</a>, you will very soon find out that you don't always want to see everything.</p> <h2>How Deb.js Was Made</h2> <p>The initial idea came from <a href="">Remy Sharp</a>'s blog post about finding where the <code>console.log</code> occurs. He suggested that we can create a new error and get the stack trace from there:</p> <pre class="brush: javascript noskimlinks noskimwords">[); }; }) </pre> <p>The original post can be found <a href="">on Remy's blog</a>. This is especially helpful if we develop in a Node.js environment. </p> <p>So, with the stack trace in hand, I somehow needed to inject code into the beginning and at the end of the function. This is when the pattern used in <a href="">Ember's computed properties</a> popped into my head. It's a nice way to patch the original <code>Function.prototype</code>. For example:</p> <pre class="brush: javascript noskimlinks noskimwords">Function.prototype.awesome = function() { var original = this; return function() { console.log('before'); var args = Array.prototype.slice.call(arguments, 0); var res = original.apply(this, args); console.log('after'); return res; } } var doSomething = function(value) { return value * 2; }.awesome(); console.log(doSomething(42)); </pre> <p>The <code>this</code> keyword in our patch, points to the original function. We may run it later which is exactly what we needed, because we could track the time before and after the execution. At the same time, we are returning our own function that acts as a proxy. We used <code>.apply(this, args)</code> in order to keep the context and the passed arguments. And thankfully to Remy's tip, we may get a stack trace too. </p> <p>The rest of the <a href="">Deb.js</a> implementation is just decoration. Some browsers support <code>console.group</code> and <code>console.groupEnd</code> which helps a lot for the visual look of the logging. Chrome even gives us the ability to paint the printed information in different colors.</p> <h2>Summary</h2> <p>I believe in using great instruments and tools. The browsers are smart instruments developed by smart people, but sometimes we need something more. <a href="">Deb.js</a> came as a tiny utility and successfully helped to boost my debugging workflow. It's, of course, open source. Feel free to <a href="">report issues or make pull requests</a>.</p> <p>Thanks for reading.</p> 2014-06-30T17:59:21.000Z 2014-06-30T17:59:21.000Z Krasimir Tsonev tag:code.tutsplus.com,2005:PostPresenter/cms-21478 Google Chrome Hegemony <p><a href="">Google Chrome</a>.</p> <h2>Developing Responsive Web Applications</h2> <p:</p> <pre class="brush: html noskimlinks noskimwords">> </pre> <p>There is some basic styling on the page. The CSS rules, float the navigation's links and makes the two sections positioned next to each other. The result looks like this:</p><figure class="post_image"><img alt="" data-</figure> .</p><h3>Setting the Viewport</h3> <p>Our content breaks and we want to see the exact size of the viewport. So we have to resize the browser's window. Under Chrome, we are able to open the <b>developer tools panel</b> and increase its size in there.</p> <p>Notice that while we are changing the viewport's size, we see its size in the <b>upper right corner</b>. This little tooltip eliminates the need of a manual size check. In our case, both sections below the navigation became too squashed, around 500px. So, that's the place for our first media query:</p> <pre class="brush: css noskimlinks noskimwords">section { float: left; width: 50%; } @media all and (max-width: 550px) { section { float: none; width: 100%; } } </pre> <p>If we go a little bit below 550px, we will see that the navigation causes a horizontal scroll around 540px. A new media query definition solves that problem.</p> <pre class="brush: css noskimlinks noskimwords">.nav { list-style: none; margin: 10px auto; padding: 0; width: 510px; } .nav li { float: left; margin: 0 20px 0 0; } @media all and (max-width: 540px) { .nav { width: auto; } .nav li { float: none; margin: 0; padding: 0; text-align: center; } } </pre> <p>The result is a web page that works on a wide range of screens. Yes, our page is a simple one and has only two breakpoints, but the process of choosing them will be the same, even if we have a giant website. </p><h3>Device Simulation</h3> <p.</p> <p>Let's say that we need to simulate an iPhone5 device. There is a small button that opens the <b>drawer</b> panel and then there is an <b>Emulation</b> tab.</p> <p>We choose the device and Chrome applies all the settings in <b>Screen</b>, <b>User agent</b> and <b>Sensors</b> sections. The browser even emulates touch events.</p><h3>Making Modifications With the Elements Panel</h3> <p.</p> <p>The <b>Elements</b>.</p><h3>Developers Tools Panel</h3> <p>And then lastly, sometimes we need to search for certain CSS styles, but it is difficult to find them because there are a lot of definitions. In the <b>developers tools</b> panel, we have a nice filter field. Let's say that we want to access the rules for our <code><section></code> tag that has the <code>concept</code> class applied, here's how we could do that:</p><figure class="post_image"><img alt="" data-</figure> <h2>Debugging JavaScript</h2> <p>Google Chrome is a universal tool. It has instruments for supporting designers like we did in the last section of this tutorial. But it can do the same for the developers, as we will see now. </p><h3>Integrated JS Debugging</h3><p>There is a nice JavaScript debugger, integrated within Chrome. There's also a wonderful console and source viewer. To illustrate how everything works, we will add a little logic to our example. We want to change the label <b>Examples</b> in the main menu to <b>Awesome examples</b> when we <b>click</b> on the link. We will use jQuery as a helper, so we can focus on the example better:</p> <pre class="brush: javascript noskimlinks noskimwords">$('.nav').on('click', function(e) { var clicked = e.currentTarget; if(clicked.innerHTML === 'Examples') { clicked.innerHTML = 'Awesome examples'; } else { console.log('do nothing ...'); } }); </pre> <p>You probably already know the problem, but let's see how the above code works.</p><figure class="post_image"><img alt="" data-</figure> <p>No matter what we <b>click</b> we get <code>do nothing ...</code> in the console. So, it looks like our <code>if</code> clause is always false. Let's set a breakpoint to see what's going on.</p> <p>The debugger stops at our breakpoint and shows us the local defined variables. The variable <code>clicked</code>, points to the navigation element and not to the <code><a></code> element. So, its <code>innerHTML</code> property is definitely not <code>Examples</code>. That's why we got <code>do nothing ...</code> every time. To fix the bug, we could simply use <code>.nav a</code> instead of just <code>.nav</code>.</p><figure class="post_image"><img alt="" data-</figure> <p>Above is the traditional approach that works if we know where exactly to set the breakpoint. But if we work with a large code base and especially if we have to debug the concatenated file, it gets a little bit problematic. We start placing <code>console.log</code> <code>%c</code> in front of the text, passed to the <code>.log</code> method. After that, attach a second parameter containing our styles. For example:</p><figure class="post_image"><img alt="" data-</figure> <p>There is something else that we could add. The <code>console</code> object has two, not so popular methods - <code>group</code> and <code>groupEnd</code>. They give us the ability to group our logs. </p><h3>Using Deb.js</h3> <p>There is also a library that combines both the styling and grouping of the output, Deb.js. The only thing that we have to do, is to include it in our page before the other scripts and attach <code>.deb()</code> at the end of the function that we want to inspect. There is also <code>.debc()</code> version that sends collapsed groups to the console.<br></p> <p>With this library, we can get the arguments passed to the function, its stack trace return value and execution time. As we mentioned above, the messages are nicely grouped and nested into each other, so it is much easier to follow the application's flow.</p> <h2>Terminal in the Browser</h2> <p>One of the killer features of Google's browser, is the extension's ecosystem. There's a way for us to write installable programs that run in the browser and there are dozens of <a href="">helpful APIs</a> that we can use. The most important thing though, is that we don't have to learn a new language. The technologies that we'll use, are the usual HTML, CSS and JavaScript. Checkout the following <a href="" target="_self">introduction to Chrome's extension development</a>. </p><h3>Yez!</h3> <p>There's even a separate section in the Chrome's web store called <a href=""><em>Web development</em></a>. It contains useful instruments made specifically for us - developers. There is one called <a href="">Yez!</a>. It brings terminal like functionalities into the Developer Tools panel. We are able to execute shell commands and get their output in real time.</p> <p <code>npm install -g yez</code>. </p> <h3>Yez! Git Integration</h3><p>Yez! also has nice Git integration and it shows us the branch in the current directory. We are able to execute terminal commands and get their output immediately. </p> <p>The extension was originally developed as a task runner. So it has an interface for task definitions. In fact, that's just a series of shell commands run after each other. We are achieving the same results by creating shell scripts.</p> <p>We can also see the terminal's output in real time. So the extension is suitable for developing Node.js applications. Normally we have to restart the Node.js process, but now, everything is visible inside Chrome.</p> <h2>Performing HTTP Requests</h2> <p>As web developers, it often happens that we have to perform HTTP request to our applications. Maybe we developed a REST API, or we have a PHP script that accepts POST parameters. There is a command line tool available called <a href="">cURL</a>. It's probably the most widely used instrument for querying the web.</p><p>With cURL, we don't have to jump to the terminal. There is <a href="">DHC (REST HTTP API Client)</a> available. It's an extension that gives us full control of the HTTP request. We could change the request method, the headers, or the GET and POST parameters. It also displays the result of the request, with its headers. A very useful instrument.</p> <h2>Testing With Chrome's Web Driver</h2> <p>We all know the importance of <a href="">testing</a>. <a href="">DalekJS</a>. It's easily installable by running:</p> <pre class="brush: bash noskimlinks noskimwords">npm install -g dalek-cli </pre> <p>Let's make a short experiment and see how everything works. In a newly created directory, we need a <code>package.json</code> file with the following content:</p> <pre class="brush: javascript noskimlinks noskimwords">{ "name": "project", "description": "description", "version": "0.0.1", "devDependencies": { "dalekjs": "0.0.8", "dalek-browser-chrome": "0.0.10" } } </pre> <p>After running <code>npm install</code> in the same directory, we will get <code>dalekjs</code> and <code>dalek-browser-chrome</code> installed into a <code>node_modules</code> folder. We will place our test inside a file called <code>test.js</code>. Let's save it in the same folder. Here is a short script that tests the search functionality of GitHub:</p> <pre class="brush: javascript noskimlinks noskimwords"() } }; </pre> <p>To run the test, we have to fire <code>dalek ./test.js -b chrome</code> in our console. The result is that DalekJS launches an instance of the Google Chrome browser. It then opens GitHub's site, at which point you can type <code>dalek</code> in the search field and it goes to the correct repository. In the end, Node.js simply closes the opened window. The output in the console looks like this:</p><figure class="post_image"><img alt="" data-</figure> <p>DalekJS supports PhantomJS, Firefox, InternetExplorer and Safari. It's a useful tool, and it works on Windows, Linux and Mac. The documentation is available at the official page <a href="">dalekjs.com</a></p> <h2>Summary</h2> <p>When we are in front of our computer, we spend most of that time in the browser. It's good to know that Google Chrome is not only a program for browsing the Web, but it's also a powerful instrument for web development. </p><p>Now, there are tons of useful extensions and a constantly growing community, so I urge you to try Google Chrome, if you aren't already using it for your next web app.</p> 2014-06-20T19:59:21.000Z 2014-06-20T19:59:21.000Z Krasimir Tsonev tag:code.tutsplus.com,2005:PostPresenter/net-21286 How I Made the Domai.nr Chrome Extension <figure class="final-product final-product--image"><img data-< data-< data-< data-<"> <></pre> <p ">;}</pre> <div class="tutorial_image"><img data-<"> $ ...</pre> <p>In the chunk above, we do a number of things:</p> <ul> <li>First, we focus the input box by default</li> <li>Next, we set some variables (as per the Domai.nr API)</li> <li>Then, on the form submit, we do the following: <ul> <li>Check to make sure the query is not blank</li> <li>Assuming that passes, we then set the body width, and show an AJAX loader icon</li> <li>We then clear out the previous (if there is one) list of domains, and remove the previous search query from the view</li> <li>Finally, we remove some information that we'll get to more below</li> </ul> </li> </ul> <p>So, it's a good start. Some of the code above won't make sense because it's not in our HTML yet. It will be shortly, just go with it for now.</p> <pre class="brush: js noskimlinks noskimwords"> // ... data-</div> <p!</p> <p.</p> <pre class="brush: css noskimlinks noskimwords">;}</pre> <div class="tutorial_image"> <img data- <> <pre class="brush: html noskimlinks noskimwords"> ><"> $("&gt;...<"> // });</pre> <div class="tutorial_image"><img data-<"> ;}</pre> <div class="tutorial_image"><img data-</div> <hr> <h2>All Done!</h2> <p!</p> 2011-08-09T20:59:36.000Z 2011-08-09T20:59:36.000Z Connor Montgomery tag:code.tutsplus.com,2005:PostPresenter/net-18879 Quick Tip: 2 Chrome Extensions you Must Install <p> In this video quick tip, rather than focusing on some specific coding technique, we're going to review two excellent Chrome extensions that I highly recommend you install: <a href="">StyleBot</a> and <a href="">Vimium</a>.</p> <p><!--more--></p> <div class="tutorial_image"> <object width="600" height="338"><param name="movie" value=""> <param name="allowFullScreen" value="true"> <param name="allowscriptaccess" value="always"> <embed src="" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="600" height="338"></embed></object><br> <span><a href="">Subscribe to our YouTube page to watch all of the video tutorials!</a></span> </div> 2011-03-14T23:06:55.000Z 2011-03-14T23:06:55.000Z Jeffrey Way tag:code.tutsplus.com,2005:PostPresenter/net-11735 Switching to Chrome? Download these Extensions <p. </p> <p><!--more--></p> <p!</p> <hr> <h2> <span>1.</span> <a href="">Web Developer</a> </h2> <div class="tutorial_image"><img data-</div> <p>Some of you might be familiar with this plug-in from Firefox. Although the Chrome version can't disable JavaScript, due to some restrictions from the browser's side, WDT remains one of the most powerful additions to a web developer's arsenal.</p> <p>You can easily outline different elements of a site, and test it in various environments (for instance, without CSS and images) through the extension. It also offers quick access to important code validation services and some other interesting options.</p> <hr> <h2> <span>2.</span> <a href="">Pendule</a> </h2> <div class="tutorial_image"><img data-</div> <p>Though it isn't filled with features like <a href="">Chris Pederick's Web developer toolbar</a>, Pendule proves itself to be worthy of comparison against the famous Firefox add-on.</p> <p>Other than the basics (source, images, validators), it contains a couple of very cool tools, like the ruler and the color picker, which will be highly valued by web developers and aren't a part of WDT.</p> <hr> <h2> <span>3.</span> <a href="">Chrome Sniffer</a> </h2> <div class="tutorial_image"><img data-</div> <p>No, Chrome sniffer can't produce smells equivalent to your screen picture. Sorry. However, if you'd like to find out which frameworks and libraries a particular site uses, that's an area sniffer can help you with.</p> .</p> <hr> <h2> <span>4.</span> <a href="">Chrome SEO</a> </h2> <div class="tutorial_image"><img data-</div> <p>Although still in Beta, Chrome SEO is one of the best search engine optimization analyzers you can find as a browser extension these days.</p> <p>It provides easy access to various tools that can help you out with Competitive Analysis, Keyword Research, Backlink Checks, PageRank Checks and other daily SEO tasks.</p> <hr> <h2> <span>5.</span> <a href="">Speed Tracer</a> </h2> <div class="tutorial_image"><img data-</div> <p>Speed tracer is an official Chrome extension, developed by Google. It tracks your site performance in real-time, generating reports on various problems that might have occurred while communicating with the server. You can then use these metrics to optimize your code for better site performance.</p> <p><b>Note:</b> You should read the <a href="">getting started guide</a> before using Speed tracer.</p> <hr> <h2> <span>6.</span> <a href="">Frame Two Pages</a> </h2> <div class="tutorial_image"><img data-</div> <p>"Frame Two Pages" does exactly what it sounds like; it splits your two tabs into resizable frames. In other words, your physical screen will be split into independent areas.</p> <p>Once you click the extension's icon, the current tab will be merged with the previous (left) one into a frameset with two rows or columns (frames). Unlike the other similar extensions, "Frame Two Pages" can open links in the same frame they were clicked in. </p> <hr> <h2> <span>7.</span> <a href="">Snippy</a> </h2> <div class="tutorial_image"><img data-</div> <p>Snippy allows you to grab snippets from web pages and save them for future use or upload to Google Docs. The extension is very useful when copying a lot of information from various sites, since it shortens the cpoy/paste process to only one simple click.</p> <hr> <h2> <span>8.</span> <a href="">IE Tab</a> </h2> <div class="tutorial_image"><img data-</div> <p>No matter how much we hate it, the fact remains that some sites need Internet Explorer to work properly. IE tab acts as if you had the Internet Explorer engine running inside your Chrome browser.</p> <p>Although most developers will use IE tab to test their work in Internet Explorer, the extension can also be used to access local (file://) URLs (not possible through Chrome itself).</p> <hr> <h2> <span>9.</span> <a href="">Color Picker</a> </h2> <div class="tutorial_image"><img data-</div> <p>Color picker can provide you with both hexadecimal and RGB values of a currently selected color. It does a pretty good job most of the time, but the desired site must be fully loaded at 100% zoom level for best results.</p> <hr> <h2> <span>10.</span> <a href="">BuiltWith</a> </h2> <div class="tutorial_image"><img data-</div> <p>Similar to Chrome sniffer, BuiltWith does a great job of understanding which technologies and frameworks a particular site is using. In addition to their names and short descriptions, you'll be provided with usage statistics and a list of other websites using the same technologies.</p> <hr> <h2> <span>11.</span> <a href="">Lightshot</a> </h2> <div class="tutorial_image"><img data-</div> <p. </p> <p>You can also copy or edit your screenshots (add text, draw lines and more other functions) using an on line tool much reminding of Photoshop.</p> <hr> <h2> <span>12.</span> <a href="">Xmarks bookmark sync</a> </h2> <div class="tutorial_image"><img data-</div> <p. </p> <p>And you don't have to, because Xmarks will do that for you. It can synchronize across multiple computers and web browsers, and is available as a free extension for Chrome, Firefox, Safari and Internet Explorer.</p> <hr> <h2> <span>13.</span> <a href="">Web of Trust</a> </h2> <div class="tutorial_image"><img data-</div> <p." </p> <p.</p> <hr> <h2> <span>14.</span> <a href="">Last Pass</a> </h2> <div class="tutorial_image"><img data-</div> <p>LastPass is a free online password manager and form filler that easily remembers your on line passwords and auto-fills them for you. The only password you'll need to remember from now on is the one of your Last pass account!</p> <hr> <h2> <span>15.</span> <a href="">Chromeshark</a> </h2> <div class="tutorial_image"><img data-</div> <p>ChromeShark is a Chrome extension containing basic playback controls for your <a href="">Grooveshark</a> account. You can pause a song, skip it, or stop the playback entirely.</p> <p><b>Note:</b> The extension has problems when multiple Grooveshark tabs are opened.</p> <h2> <span>16.</span> <a href="">Recent History</a> </h2> <div class="tutorial_image"><img data-</div> <p.</p> <hr> <h2> <span>17.</span> <a href="">L(ink)y URL Shortener</a> </h2> <div class="tutorial_image"><img data-</div> <p>Twitter users will absolutely adore this extension. It automatically shortens your URLs using the popular Bit.ly URL shortening service. It also remembers the most recent shortened URLs so you don't have to retype them.</p> <hr> <h2> <span>18.</span> <a href="">Tab Menu</a> </h2> <div class="tutorial_image"><img data-</div> <p>For those who like to get carried away opening new tabs in Google Chrome, this tool will be of great assistance. Instead of looking at tiny horizontal tab icons, it gives you a vertical overview of all your current tabs opened and enables searching as well!</p> <hr> <h2> <span>19.</span> <a href="">Note Anywhere</a> </h2> <div class="tutorial_image"><img data-</div> <p>With "Note Anywhere," you can post a sticky note on any page you are viewing, customize it, and then review the note on a later date.</p> <p>It can be quite useful when doing on line research, since the sites you posted the stickers on will be remembered in the extension's options page. They remain posted until you delete them.</p> <hr> <h2> <span>20.</span> <a href="">Auto Translate</a> </h2> <div class="tutorial_image"><img data-</div> <p>This translator can be customized according to your preferences, so you can choose when will the translate pop-up appear.</p> <p>For instance, you could set it to translate from English when Control double clicked, but to try to detect the language automatically when you Shift select a word.</p> <hr> <p>Thanks so much for reading. Which ones are your favorites? Any I missed?</p> 2010-05-13T15:01:11.000Z 2010-05-13T15:01:11.000Z Toni Kukurin
https://code.tutsplus.com/categories/google-chrome.atom
CC-MAIN-2020-45
refinedweb
8,830
56.35
example/animation_blit.py works fine on my laptop, but > for some reason not obvious to me it is not working on my > desktop. Here is the error: > Traceback (most recent call last): File > "animation_blit.py", line 30, in update_line > ax.draw_artist(line) File > "/usr/local/lib/python2.4/site-packages/matplotlib/axes.py", > line 1336, in draw_artist assert self._cachedRenderer is > not None AssertionError > Both machines are up-to-date with cvs. Any clues? The only way to get this error is if you call draw_artist before draw. It could have something to do with the order of the calls in the gtk idle machinery. Try the following which connects to the new "draw_event" to block animation until after draw and background storage # For detailed comments on animation and the techniqes used here, see # the wiki entry # = None def snap_background(self): global background background = canvas.copy_from_bbox(ax.bbox) p.connect('draw_event', snap_background) def update_line(*args): if background is None: return True #:' , 200/(time.time()-tstart) sys.exit() update_line.cnt += 1 return True update_line.cnt = 0 gobject.idle_add(update_line) p.show()
https://discourse.matplotlib.org/t/animation/3211
CC-MAIN-2019-51
refinedweb
180
50.53
sysmgr_runstate_burst() Ask the system to turn on dynamically offlined CPUs Synopsis: #include <sys/sysmgr.h> int sysmgr_runstate_burst( const unsigned ms_length ); Since: BlackBerry 10.0.0 Arguments: - ms_length - The length of time, in milliseconds, that the user expects the system to be busy, or 0 to cancel the burst-mode request. The time can be up to 65535 ms. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: Most of the time, the dynamic CPU-onlining algorithm works fine, but it can take up to 64 ms to decide that there's enough system load to turn on a dynamically offlined CPU, and sometimes we just don't want to wait that long. The sysmgr_runstate_burst() function tells the kernel that the system is about to get busy, and it should be turning on CPUs much sooner than it would normally. Multiple threads can call the function, and burst mode remains in effect until the last time period expires. A thread can cancel its burst-mode request by calling sysmgr_runstate_burst() again with an argument of 0; any other thread requests remain in force. In order to successfully call this function, your process must have the PROCMGR_AID_RUNSTATE_BURST ability enabled. For more information, see procmgr_ability(). Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/s/sysmgr_runstate_burst.html
CC-MAIN-2015-18
refinedweb
235
56.35
Filter definition. More... #include <avfilter.h> Filter definition. This defines the pads a filter contains, and all the callback functions used to interact with the filter. Definition at line 165 of file avfilter.h. Filter name. Must be non-NULL and unique among filters. Definition at line 169 of file avfilter.h. Referenced by convert_from_tensorflow.Operand::__str__(), avfilter_graph_parse(), avgblur_opencl_filter_frame(), config_output(), convolution_opencl_filter_frame(), convolution_opencl_init(), init_filter(), lavfi_read_header(), link_filter(), link_filter_inouts(), neighbor_opencl_init(), print_digraph(), and program_opencl_init(). A description of the filter. May be NULL. You should use the NULL_IF_CONFIG_SMALL() macro to define it. Definition at line 176 of file avfilter.h. List of static inputs. NULL if there are no (static) inputs. Instances of filters with AVFILTER_FLAG_DYNAMIC_INPUTS set may have more inputs than present in this list. Definition at line 185 of file avfilter.h. List of static outputs. NULL if there are no (static) outputs. Instances of filters with AVFILTER_FLAG_DYNAMIC_OUTPUTS set may have more outputs than present in this list. Definition at line 194 of file avfilter.h. 204 of file avfilter.h. A combination of AVFILTER_FLAG_*. Definition at line 209 of file avfilter.h. Referenced by ff_filter_frame_framed(). The number of entries in the list of inputs. Definition at line 222 of file avfilter.h. The number of entries in the list of outputs. Definition at line 227 of file avfilter.h. This field determines the state of the formats union. It is an enum FilterFormatsState value. Definition at line 233 of file avfilter.h. Filter pre-initialization function. This callback will be called immediately after the filter context is allocated, to allow allocating and initing sub-objects. If this callback is not NULL, the uninit callback will be called on allocation failure. Definition at line 248 of file avfilter.h. 271 of file avfilter.h. 284 of file avfilter.h. 296 of file avfilter.h. Query formats supported by the filter on its inputs and outputs. This callback is called after the filter is initialized (so the inputs and outputs are fixed), shortly before the format negotiation. This callback may be called more than once. This callback must set AVFilterLink.outcfg.formats on every input link and AVFilterLink.incfg.formats on every output link to a list of pixel/sample formats that the filter supports on that link. For audio links, this filter must also set in_samplerates / out_samplerates and in_channel_layouts / out_channel_layouts analogously. This callback must never be NULL if the union is in this state. Definition at line 323 of file avfilter.h. A pointer to an array of admissible pixel formats delimited by AV_PIX_FMT_NONE. The generic code will use this list to indicate that this filter supports each of these pixel formats, provided that all inputs and outputs use the same pixel format. This list must never be NULL if the union is in this state. The type of all inputs and outputs of filters using this must be AVMEDIA_TYPE_VIDEO. Definition at line 334 of file avfilter.h. Analogous to pixels, but delimited by AV_SAMPLE_FMT_NONE and restricted to filters that only have AVMEDIA_TYPE_AUDIO inputs and outputs. In addition to that the generic code will mark all inputs and all outputs as supporting all sample rates and every channel count and channel layout, as long as all inputs and outputs use the same sample rate and channel count/layout. Definition at line 345 of file avfilter.h. Equivalent to { pix_fmt, AV_PIX_FMT_NONE } as pixels_list. Definition at line 349 of file avfilter.h. Equivalent to { sample_fmt, AV_SAMPLE_FMT_NONE } as samples_list. Definition at line 353 of file avfilter.h. The state of the following union is determined by formats_state. See the documentation of enum FilterFormatsState in internal.h. size of private data to allocate for the filter Definition at line 356 of file avfilter.h. Additional flags for avfilter internal use only. Definition at line 358 of file avfilter.h. Make the filter instance process a command. Definition at line 372 of file avfilter.h. 386 of file avfilter.h. Referenced by avfilter_graph_request_oldest().
https://www.ffmpeg.org/doxygen/trunk/structAVFilter.html
CC-MAIN-2022-05
refinedweb
655
53.68
An electronic scoreboard is one of the most important gadgets anybody can have during any sports tournament. Old manual scoreboard using conventional methods are very time consuming and Error-prone, hence a computerized scoreboard becomes necessary where the display unit needs to be changed in real-time. This is why in this project, we will be building a Bluetooth controlled wireless scoreboard in which we can change the score on the board just by using an android application. The brain of this project is an Arduino Nano, and for the display part, we will be using a P10 LED matrix to show the score remotely in real-time. The P10 LED Display Matrix A P10 LED Matrix Display is the best way available to make a LED advertisement board for outdoor or indoor use. This panel has a total of 512 high brightness LEDs mounted on a plastic housing designed for best display results. It also comes with an IP65 rating for waterproofing making it perfect for outdoor use. With this, you can make a big LED signboard by combining any number of such panels in any row and column structure. Our module has a size of 32*16, which means that there are 32 LEDs in each row and 16 LEDs in each column. So, there is a total of 512 LEDs present in each led signboard. Other than that, it has an IP65 rating for waterproofing, it can be powered by a single 5V power source, it has a very wide viewing angle, and the brightness can go up to 4500 nits. So, you will be able to see it clearly in brought daylight. Previously we have also used this P10 Display with Arduino to build a simple LED Board. Pin Description of P10 LED Matrix: This LED display board uses a 10-pin mail header for input and output connection, in this section, we have described all the necessary pins of this module. Also, you can see there is an external 5V connector in the middle of the module which is used to connect the external power to the board. - Enable: This pin is used to control the brightness of the LED panel, by giving a PWM pulse to it. - A, B: These are called multiplex select pins. They take digital input to select any multiplex rows. - Shift clock (CLK), Store clock (SCLK), and Data: These are the normal shift register control pins. Here a shift register 74HC595 is used. Interfacing P10 LED Display Module to Arduino: Connecting the P10 matrix display module to Arduino is a very simple process, in our circuit, we configured pin 9 of the Arduino as Enable pin, Pin 6 as Pin A, Pin 7 as pin B, Pin 13 is the CLK, Pin 8 is the SCLK, Pin 11 is the DATA, and finally Pin GND is the GND pin for the module and Arduino, a complete table below explain the pin configuration clearly. Note: Connect the power terminal of the P10 module to an external 5V power source, because 512 LEDs will consume a lot of power. It is recommended to connect a 5V, 3 Amp DC power supply to a single unit of P10 LED module. If you are planning to connect more numbers module, then increase your SMPS capacity accordingly. Components Required for Arduino Scoreboard As this is a very simple project, the components requirements are very generic, a list of required components are shown below, you should be able to find all of the listed material in your local hobby store. - Arduino Nano - P10 LED matrix display - Breadboard - 5V, 3 AMP SMPS - HC-05 Bluetooth Module - Connecting Wires Circuit Diagram for Arduino Scoreboard The Schematic for the Arduino LED Scoreboard is shown below as this project is very simple, I have used the popular software fritzing to develop the schematic. The working of the circuit is very simple, we have an Android application and a Bluetooth module, to successfully communicate with the Bluetooth module, you have to pair the HC-05 module with the android application. Once we are connected, we can send the string that we want to display, once the string is sent, Arduino will process the string and convert it to a signal that the internal 74HC595 shift resistor can understand, after the data is sent to the shift resistor, its ready to display. Arduino Scoreboard Code Explanation After the successful completion of the hardware setup, now it’s time for the programming of Arduino Nano. The stepwise description of the code is given below. Also, you can get the complete Arduino Scoreboard code at the bottom of this Tutorial. First of all, we need to include all the libraries. We have used the DMD.h Library in order to control the P10 led display. You can download and include it from the given GitHub link. After that, you need to include the TimerOne.h Library, which will be used for interrupt programming in our code. There are many fronts available in this library, we have used “Arial_black_16” for this project. #include <SPI.h> #include <DMD.h> #include <TimerOne.h> #include "SystemFont5x7.h" #include "Arial_black_16.h" In the next step, the number of rows and columns are defined for our LED matrix board. We have used only one module in this project, so both ROW value and COLUMN value can be defined as 1. #define ROW 1 #define COLUMN 1 #define FONT Arial_Black_16 DMD led_module (ROW, COLUMN); After that, all the variables used in the code are defined. A character variable is used to receive serial data from Android App, two integer values are used to store scores, and an array is defined which stores the final data to be displayed on the Matrix. char input; int a = 0, b = 0; int flag = 0; char cstr1[50]; A Function scan_module() is defined, which continuously checks for any incoming data from Arduino Nano through the SPI. If yes, then it will trigger an interrupt for doing certain events as defined by the user in the program. void scan_module() { led_module.scanDisplayBySPI(); } Inside setup(), the timer is initialized, and the interrupt is attached to the function scan_module, which was discussed earlier. Initially, the screen was cleared using the function clear screen(true), which means all the pixels are defined as OFF. In the setup, serial communication was also enabled using function Serial.begin(9600) where 9600 is the baud rate for Bluetooth communication. void setup() { Serial.begin(9600); Timer1.initialize(2000); Timer1.attachInterrupt(scan_module); led_module.clearScreen( true ); } Here, the serial data availability is checked, if there is valid data is coming from Arduino or not. The received data from the App is stored in a variable. if(Serial.available() > 0) { flag = 0; input = Serial.read(); Then, the received value was compared with the predefined variable. Here, in the Android application, two buttons are taken to select the scores for both teams. When button 1 is pressed, Character ‘a’ is transmitted to Arduino and when button2 is pressed, Character ‘b’ is transmitted to Arduino. Hence, in this section, this data is matched, and if matched, then the respective score values are incremented as shown in the code. if (input == 'a' && flag == 0) { flag = 1; a++; } else if (input == 'b' && flag == 0) { flag = 1; b++; } else; Then, the received data is converted into a character Array, as the P10 matrix function is only capable of displaying character data type. This is why all variables are converted and concatenated into a character array. (String("HOME:")+String(a) + String(" - ") + String("AWAY:")+String(b)).toCharArray(cstr1, 50); Then, to display information in the module, the font is selected using the selection() function. Then drawMarquee() function is used to display the desired information on the P10 board. led_module.selectFont(FONT); led_module.drawMarquee(cstr1,50, (32 * ROW), 0); Finally, as we need a scrolling message display, I have written a code to shift our whole message from Right to Left directions using a certain period. long start = millis(); long timming = start; boolean flag = false; while (!flag) { if ((timming + 30) < millis()) { flag = led_module.stepMarquee(-1, 0); timming = millis(); } } This marks the end of our coding process. And now it’s ready for uploading. Smartphone Controlled Scoreboard - Testing After uploading code to Arduino, it’s time to test the project. Before that, the android application needs to be installed on our smartphone. You can download the P10 Score Board application from the given link. Once installed, open the app and the home screen should look like the below image. Click on the SCAN button to add the Bluetooth module with App. This will show the list of paired Bluetooth devices of the phone. If you haven’t paired the HC-05 Bluetooth module before, pair the module using your phone’s Bluetooth setting and then do this step. The screen will look like shown: Then, from the list, click on “HC-05” as this is the name of our Bluetooth module used here. After clicking on it, it will show connected on the screen. Then we can proceed with the scoreboard. Click on any button between “Home” & “Away” as shown in the App. If the Home button is selected, the score of Home will be incremented in the P10 display. Similarly, if the Away button is selected, the score of Away will be incremented. The below image shows how the final screen looks. I hope you liked the project and learned something new, if you have any other questions regarding the project, feel free to comment down below or you can ask your question in our forum. #include <SPI.h> #include <DMD.h> #include <TimerOne.h> #include "SystemFont5x7.h" #include "Arial_black_16.h" #define ROW 1 #define COLUMN 1 #define FONT Arial_Black_16 char input; int a = 0, b = 0; int flag = 0; char cstr1[50]; DMD led_module(ROW, COLUMN); void scan_module() { led_module.scanDisplayBySPI(); } void setup() { Serial.begin(9600); Timer1.initialize(2000); Timer1.attachInterrupt(scan_module); led_module.clearScreen( true ); } void loop() { if(Serial.available() > 0) { flag = 0; input = Serial.read(); if (input == 'a' && flag == 0) { flag = 1; a++; } else if (input == 'b' && flag == 0) { flag = 1; b++; } else; } (String("HOME:")+String(a) + String(" - ") + String("AWAY:")+String(b)).toCharArray(cstr1, 50); led_module.selectFont(FONT); led_module.drawMarquee(cstr1,50, (32 * ROW), 0); long start = millis(); long timming = start; boolean flag = false; while (!flag) { if ((timming + 30) < millis()) { flag = led_module.stepMarquee(-1, 0); timming = millis(); } } }
https://circuitdigest.com/microcontroller-projects/bluetooth-controlled-arduino-scoreboard-using-p10-led-matrix-display
CC-MAIN-2020-50
refinedweb
1,733
62.98
Q 1 : Which of the following are keywords in Java programming language - code which of the following define local variables: - a) i, j only. - b) sum only. - c) i, j and sum. - d) There are no local variables. Q 3 : Which of the following are correct regarding Java variables - a) The default value for boolean variable is: true. - b) A literal and a variable are the same. - c) This is a valid variable declaration: int _52 = 52; - d) This is a valid instance variable declaration: int i, j = 10; Q 4 : Consider the code: // This program prints text and an integer number. public class YearPrinter { public static void main(String [] args) { int year= 2013; System.out.println("This year is: " + year); } } Which of the following are correct of the above code: - a) “year” is a numeric variable. - b) ‘System.out.println(“This year is: ” + year);’ is a statement. - c) “YearPrinter” is the name of a class. - d) “main” is the name of a method. - e) “//” is used to write a comment within a class. Q 5 : Which of the following code snippets correctly show statement “blocks” a. public int calculate(int a, int b) { int c = a + b; System.out.println("a+b = " + c); return c; } b. String a = "Java"; String b = "programming"; String c = "Java programming"; if (c.equals(a + b)) { System.out.println("Java programming"); // prints Java programming } c. { Object object = null; } d. Integer i = null; try { i = new Integer("56"); } catch(NumberFormatException nfe) { nfe.printStackTrace(); } Q 6 : To create a Java application which of the following are required - a) A source code file. - b) Java programming language compiler. - c) A text editor or an IDE. - d) The Java application launcer. Q 7 : Consider the code public class YearPrinter { public static void main(String [] args) { new YearPrinter().printIt(); } private void printIt() { int year= 2013; System.out.println("This year is: " + year); } } Which one of the following is correct after the above is compiled and run: - a) There is a compile time error. - b) The program prints “The year is: 2013”. - c) There is a runtime error. Q 8 : Consider the code package mypackage; public class ClassA { public static void main(String [] args) { new ClassA().doThis(); } public void doThis() { System.out.println("Running the ClassA class."); } } Assume that the ClassA.java is in the current directory. And, all the Java commands are run from the current directory. Which of the following are correct: - a) The command “javac -d . ClassA.java” at command prompt creates a directory called mypackage, and ClassA.class file within that directory. - b) The above class can be run at the command prompt using the command “java mypackage.ClassA”. - c) The above class can be run at the command prompt using the command “java ClassA”. - d) The above class can be run at the command prompt using the command “java ClassA.class”. Q 9 : The package and import statements must be specified before a class definition within a class file True or false: Q 10 : Consider the following two Java classes ProgramA.java: import java.util.ArrayList; public class ProgramA { public static void main (String [] rrr) { ArrayList<String> list1 = new ArrayList<String>(); list1.add("element 1"); System.out.println("An element is added to the array list."); } } ProgramB.java: public class ProgramB { public static void main (String [] args) { java.util.ArrayList<String> list = new java.util.ArrayList<String>(); list.add("element 1"); System.out.println("An element is added to the array list."); } } Which of the following are correct of the above two classes: - a) Both ProgramA and ProgramB compile, run and print “An element is added to the arraylist .”. - b) Only ProgramA compiles, runs and prints “An element is added to the arraylist .”. - c) Only ProgramB compiles, runs and print “An element is added to the arraylist .”. - d) Both ProgramA and ProgramB fail to compile and run. OCAJP Mock Exam Answers The following are the answers for the above questions. these questions are created based on the real questions on the exam. If you find any incorrect or clarifications on the answers, please write it in the comments section. If you are interested in receiving 300 mock questions for OCAJP 7 from JavaBeat, please call +91 9740134466 1. a, b and c are correct. d and e are incorrect. d: main is the name of a method. This is the method a Java program is launched from. e: scope is not a keyword. 2. c is correct. a, b and d are incorrect. c: The variables defined within a method are local variables. This includes the method parameters i and j in the above code. 3. c and d are correct. a and b are incorrect. a: The default value for boolean variable is “false”. b: Literals and variables are not the same. A literal is a value assigned to a variable. There are two types of literals; String and primitive type. An example of a String literal is “This is a String literal”. And, an example of a primitive literal is 52. d: The variable i is initialized to 0, and j is initialized to 10. 4. a, b, c, d and e are all correct. 5. a, b, c and d are correct. A block is a group of statements of code defined within curly braces (“{ }”). 6. a, b, c and d are correct. All are required. “Javac” is the Java compiler, and “java” is the application launcher required to compile the source code and run the application, respectively. A text editor may be used to create a Java application (for example, MyApp) in a source code file with the name like “MyApp.java”. 7. b is correct. a and c are incorrect. 8. a and b are correct. c and d are incorrect. a: “-d” option used with “javac” specifies the destination of the class file. “.” is used to specify the current directory. The class file is created as mypackage/ClassA.class in the current directory. b: The program runs and prints “Running the ClassA class.”. c: Throws runtime exception. The class name is wrong. d: Prints Error: Could not find or load main class ClassA.class. The extension “.class” is not to be specified when a Java class is run. 9. True. The package statement must be the first statement in a class file, followed by import statements. Both package and import statements are optional. There can be only one package statement, and zero or more import statements. There can be comments specified before a package statement. 10. a is correct. b, c and d are incorrect. a: ArrayList class is defined in the java.util package of Java programming language API. In ProgramA, the import statement makes the ArrayList class available within the class. In ProgramB the ArrayList class is used with a fully qualified name, java.util.ArrayList.
https://javabeat.net/ocajp-mock-exam-questions-java-basics/
CC-MAIN-2021-39
refinedweb
1,139
69.79
Bias, Variance, and Regularization I really like the way Andrew Ng describes bias and variance in Week 1 of Improving Deep Neural Networks. %pylab inline from IPython.display import Image Image('images/bias_variance.PNG') Populating the interactive namespace from numpy and matplotlib A model with high bias often looks linear and takes broad stroke approach to classification. Whereas a model with high variance has complicated fitting behavior to its training set, and thus predicts poorly on new data. Train vs Test Set Error Or described using a simple example– say you were trying to build a classifier to automate something you could manually do with an extremely-low error rate So there are things that we can do to help stabilize these errors. If you have a model with high bias, you might consider a more robust network or training longer. The meat of this notebook is in addressing high variance. Correction Schemes for High Variance You have a model that has learned too niche/nuacned of features. And so you want to figure out some sort of penalizing scheme to keep your model from getting too excited about any one feature. L2 Normalization L2 Normalization gives us a concept of distance or magnitude. The idea being that if any one feature is too “big” then you proportionally penalize your model. In the same manner that the distance between two points can be expressed as $\sqrt{(y_2 - y_1)^2 + (x_2 - x_1)^2}$ We can extend that same idea to a matrix via the following $ \sqrt{\sum_{i=1}^{n} w_i^{2}}$ Which is available to us via a call to the convenient numpy.linalg.norm() x = numpy.random.rand(5, 5) numpy.linalg.norm(x) 3.0366626116644495 In the context of a Neural Network, this means that our new cost function becomes $J(W^{[1]}, b^{[1]}, …, W^{[l]}, b^{[l]}) = \frac{1}{m} \sum \mathcal{L}\big(\hat{y}^{i}, y^i\big) + \frac{\lambda}{2m} \sum_{l}\sum_j\sum_k||W_j^{l}||_k^{2}$ However, you should place great care in what value you put for this lambda parameter. Too large, and you will penalize everything and make all of your networks basically linear– defeating the purpose of using non-linear activation functions. On the other hand, too low and you’re just adding more computation for little error correction. Dropout Regularization Dropout regularization achieves a similar result, but through different means. Instead of adjusting each weight via a constant, in dropout, we just deactivate nodes (with some random probability) during the forward and back propagation step of one cycle. Then we reactivate them and deactivate other nodes with the same random probability. This ensures that we don’t ever over-rely on any one node to learn features, thus don’t overfit. Image('images/dropout.PNG') Couple notes on this, though: - We don’t do any sort of dropout when using the model to predict - This completely muddies the monotonically-decreasing performance of Gradient Descent, so you lose that as a debugging tool
https://napsterinblue.github.io/notes/machine_learning/neural_nets/regularization/
CC-MAIN-2021-04
refinedweb
505
51.68
15 May 2007 10:19 [Source: ICIS news] SINGAPORE (ICIS news)--India's largest polyvinyl chloride (PVC) producer Reliance Industries has turned to imports to meet the country’s growing demand, a company source said on Tuesday, joining fellow producer Finolex Industries Ltd. ?xml:namespace> Supply has been tight in the past few months due to unplanned and planned shutdowns at Finolex and earlier outages at Reliance plants. “We have sold imported Asian cargoes in the Indian domestic market for the first time ever as our capacity was not adequate to meet the growing requirements of our customers,” he said. The source would not specify the volumes being imported but said it could become a regular trend if the current robust demand and tight supply continued. Finolex doubled its monthly imports of PVC in April to 5,000-6,000 tonnes to meet the growth in domestic consumption during the ongoing peak demand season, a company source said. “Demand for PVC pipes has been extremely strong in the construction, water supply and irrigation segments,” he added. Limited availability coupled with strong demand has resulted in a surge in import prices. Prices of imported PVC rose to $930-950/tonne CFR (cost and freight) ?xml:namespace> However, a stronger Indian rupee had capped domestic prices, producers said. Indian producers have rolled over their local PVC offers from April to May at rupees (Rs) 45.50/kg EXW (ex-works), despite strong demand and tight supply, to offset the additional costs their customers face due to a stronger local currency, domestic producers said. The value of the Indian rupee has risen as high as Rs40.59 to the dollar, up 8.4% from Rs44 a month earlier. Currently Indian producers are able to achieve relatively good margins on their sales of imported PVC as domestic prices convert to $950-960/tonne EXW. “However, if the value of the Indian rupee declines, the viability of our imports will be under threat,” the Reliance source said. ($1 = Rs40
http://www.icis.com/Articles/2007/05/15/9028666/focus-indias-reliance-turns-to-pvc-imports.html
CC-MAIN-2014-41
refinedweb
334
51.38
Tutorial: Integrate Amazon Web Services (AWS) with Azure Active Directory In this tutorial, you'll learn how to integrate Amazon Web Services (AWS) with Azure Active Directory (Azure AD). When you integrate AWS with Azure AD, you can: - Control in Azure AD who has access to AWS. - Enable your users to be automatically signed-in to AWS with their Azure AD accounts. - Manage your accounts in one central location, the Azure portal. To learn more about SaaS app integration with Azure AD, see What is application access and single sign-on with Azure Active Directory. >. Scenario description In this tutorial, you configure and test Azure AD SSO in a test environment. AWS supports SP and IDP initiated SSO. Add AWS from the gallery To configure the integration of AWS into Azure AD, you need to add AWS from the gallery to your list of managed SaaS apps. - Sign in to the Azure portal by using either a work or school account, or a personal Microsoft account. - In the left pane, select the Azure Active Directory service. - Go to Enterprise Applications, and then select All Applications. - To add new application, select New application. - In the Add from the gallery section, type Amazon Web Services (AWS) in the search box. - Select Amazon Web Services (AWS) from the results panel, and then add the app. Wait a few seconds while the app is added to your tenant. Configure and test Azure AD single sign-on Configure and test Azure AD SSO with AWS by using a test user called B.Simon. For SSO to work, you need to establish a linked relationship between an Azure AD user and the related user in AWS. To configure and test Azure AD SSO with AWS, complete the following building blocks: - Configure Azure AD SSO to enable your users to use this feature. - Configure AWS to configure the SSO settings on the application side. - Create an Azure AD test user to test Azure AD SSO with B.Simon. - Assign the Azure AD test user to enable B.Simon to use Azure AD SSO. - Create an AWS test user to have a counterpart of B.Simon in AWS who is linked to the Azure AD representation of the user. - Test SSO to verify whether the configuration works. Configure Azure AD SSO Follow these steps to enable Azure AD SSO in the Azure portal. In the Azure portal, on the Amazon Web Services (AWS) application integration page, find the Manage section, and select Single sign-on. On the Select a Single sign-on method page, select SAML. On the Set up Single Sign-On with SAML page, select the pen icon for Basic SAML Configuration to edit the settings. On the Basic SAML Configuration section, the application is pre-configured, and the necessary URLs are already pre-populated with Azure. The user needs to save the configuration by selecting Save. When you are configuring more than one instance, provide an identifier value. From second instance onwards, use the following format, including a # sign to specify a unique SPN value. The AWS application expects the SAML assertions in a specific format, which requires you to add custom attribute mappings to your SAML token attributes configuration. The following screenshot shows the list of default attributes. Select the pen icon to open the User Attributes dialog box. In addition to the preceding attributes, the AWS application expects few more attributes to be passed back in the SAML response. In the User Claims section on the User Attributes dialog box, perform the following steps to add the SAML token attribute. a. Select Add new claim to open the Manage user claims dialog box. b. In Name, type the attribute name shown for that row. c. In Namespace, type the namespace value shown for that row. d. In Source, select Attribute. e. From the Source attribute list, type the attribute value shown for that row. f. Select Ok. g. Select Save. On the Set up Single Sign-On with SAML page, in the SAML Signing Certificate section, find Federation Metadata XML. Select Download to download the certificate and save it on your computer. In the Set up Amazon Web Services (AWS) section, copy the appropriate URLs, based on your requirement. Configure AWS. Create an Azure AD test user In this section, you create a test user, B.Simon, in the Azure portal. From the left pane in the Azure portal, select Azure Active Directory > Users > All users. Select New user at the top of the screen. In the User properties, follow these steps: a. In the Name field, enter B.Simon. b. In the User name field, enter the username@companydomain.extension. For example, B.Simon@contoso.com. c. Select Show password, and write it down. Then, select Create. Assign the Azure AD test user In this section, you enable B.Simon to use Azure SSO by granting access to AWS. In the Azure portal, select Enterprise Applications, and then select All applications. In the applications list, select Amazon Web Services (AWS). In the app's overview page, find the Manage section, and select Users and groups. Select Add user. In the Add Assignment dialog box, select Users and groups. In the Users and groups dialog box, select B.Simon. Then choose Select. If you're expecting any role value in the SAML assertion, in the Select Role dialog box, select the appropriate role for the user from the list. Then choose Select. In the Add Assignment dialog box, select Assign. Test single sign-on When you select the AWS tile in the Access Panel, you should be automatically signed in to the AWS for which you set up SSO. For more information about the Access Panel, see Introduction to the Access Panel. Known issues role ARN and the saml-provider ARN for a role being imported must be 119 characters or less Additional resources Feedback
https://docs.microsoft.com/en-us/azure/active-directory/saas-apps/amazon-web-service-tutorial
CC-MAIN-2019-39
refinedweb
982
66.23
Basic Servlet Structure By: aathishankaran Viewed: 396 times Printer Friendly Format Listing outlines of a basic servlet that handles GET requests.. Servlets can also very easily handle POST requests, which are generated when someone submits an HTML form that specifies METHOD="POST". For details on using HTML forms. To be a servlet, a class should extend HttpServlet and override doGet or doPost, depending on whether the data is being sent by GET or by POST. If you want the same servlet to handle both GET and POST and to take the same action for each, you can simply have doGet call doPost, or vice versa. Both of these methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods by which you can find out about incoming information such as form data, HTTP request headers, and the client’s hostname. The HttpServletResponse lets you specify outgoing information such as HTTP status codes (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send the document content back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page. Form data, HTTP request headers, HTTP responses, and cookies will all be discussed in detail in the following chapters. Since doGet and doPost throw two exceptions, you are required to include them in the declaration. Finally, you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServlet- Response). Strictly speaking, HttpServlet is not the only starting point for servlets, since servlets could, in principle, extend mail, FTP, or other types of servers. Servlets for these environments would extend a custom class derived from Generic- Servlet, the parent class of HttpServlet. In practice, however, servlets are used almost exclusively for servers that communicate via HTTP (i.e., Web and application servers), and the discussion in this article will be limited to this usage. ServletTemplate.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate status // code and headers (e.g. the content type, cookies). PrintWriter out = response.getWriter(); // Use "out" to send content to. fantastic make something like this View Tutorial By: jyoti maheshwari at 2009-03-27 22:15:35 2. fantastic make something like this View Tutorial By: jyoti maheshwari at 2009-03-27 22:15:36
http://www.java-samples.com/showtutorial.php?tutorialid=91
CC-MAIN-2018-09
refinedweb
404
66.13
Pkg Pkg is Julia's builtin package manager, and handles operations such as installing, updating and removing packages. What follows is a very brief introduction to Pkg. For more information on Project.toml files, Manifest.toml files, package version compatibility ( [compat]), environments, registries, etc., it is highly recommended to read the full manual, which is available here:. What follows is a quick overview of Pkg, Julia's package manager. It should help new users become familiar with basic Pkg features. Pkg comes with a REPL. Enter the Pkg REPL by pressing ] from the Julia REPL. To get back to the Julia REPL, press backspace or ^C. This guide relies on the Pkg REPL to execute Pkg commands. For non-interactive use, we recommend the Pkg API. The Pkg API is fully documented in the API Reference section of the Pkg documentation. Upon entering the Pkg REPL, you should see a similar prompt: (v1.1) pkg> To add a package, use add: (v1.1) pkg> add Example Some Pkg output has been omitted in order to keep this guide focused. This will help maintain a good pace and not get bogged down in details. If you require more details, refer to subsequent sections of the Pkg manual. We can also specify multiple packages at once: (v1.1) pkg> add JSON StaticArrays To remove packages, use rm: (v1.1) pkg> rm JSON StaticArrays So far, we have referred only to registered packages. Pkg also supports working with unregistered packages. To add an unregistered package, specify a URL: (v1.1) pkg> add Use rm to remove this package by name: (v1.1) pkg> rm Example Use update to update an installed package: (v1.1) pkg> update Example To update all installed packages, use update without any arguments: (v1.1) pkg> update Up to this point, we have covered basic package management: adding, updating and removing packages. This will be familiar if you have used other package managers. Pkg offers significant advantages over traditional package managers by organizing dependencies into environments. You may have noticed the (v1.1) in the REPL prompt. This lets us know v1.1 is the active environment. The active environment is the environment that will be modified by Pkg commands such as add, rm and update. Let's set up a new environment so we may experiment. To set the active environment, use activate: (v1.1) pkg> activate tutorial [ Info: activating new environment at `/tmp/tutorial/Project.toml`. Pkg lets us know we are creating a new environment and that this environment will be stored in the /tmp/tutorial directory. Pkg has also updated the REPL prompt in order to reflect the new active environment: (tutorial) pkg> We can ask for information about the active environment by using status: (tutorial) pkg> status Status `/tmp/tutorial/Project.toml` (empty environment) /tmp/tutorial/Project.toml is the location of the active environment's project file. A project file is where Pkg stores metadata for an environment. Notice this new environment is empty. Let us add a package and observe: (tutorial) pkg> add Example ... (tutorial) pkg> status Status `/tmp/tutorial/Project.toml` [7876af07] Example v0.5.1 We can see tutorial now contains Example as a dependency. Say we are working on Example and feel it needs new functionality. How can we modify the source code? We can use develop to set up a git clone of the Example package. (tutorial) pkg> develop --local Example ... (tutorial) pkg> status Status `/tmp/tutorial/Project.toml` [7876af07] Example v0.5.1+ [`dev/Example`] Notice the feedback has changed. dev/Example refers to the location of the newly created clone. If we look inside the /tmp/tutorial directory, we will notice the following files: tutorial ├── dev │ └── Example ├── Manifest.toml └── Project.toml Instead of loading a registered version of Example, Julia will load the source code contained in tutorial/dev/Example. Let's try it out. First we modify the file at tutorial/dev/Example/src/Example.jl and add a simple function: plusone(x::Int) = x + 1 Now we can go back to the Julia REPL and load the package: julia> import Example A package can only be loaded once per Julia session. If you have run import Example in the current Julia session, you will have to restart Julia and rerun activate tutorial in the Pkg REPL. Revise.jl can make this process significantly more pleasant, but setting it up is beyond the scope of this guide. Julia should load our new code. Let's test it: julia> Example.plusone(1) 2 Say we have a change of heart and decide the world is not ready for such elegant code. We can tell Pkg to stop using the local clone and use a registered version instead. We do this with free: (tutorial) pkg> free Example When you are done experimenting with tutorial, you can return to the default environment by running activate with no arguments: (tutorial) pkg> activate (v1.1) pkg> If you are ever stuck, you can ask Pkg for help: (v1.1) pkg> ? You should see a list of available commands along with short descriptions. You can ask for more detailed help by specifying a command: (v1.1) pkg> ?develop This guide should help you get started with Pkg. Pkg has much more to offer in terms of powerful package management, read the full manual to learn more!
https://docs.julialang.org/en/v1.5/stdlib/Pkg/
CC-MAIN-2021-39
refinedweb
895
51.44
In this lab, you will gain experience using C#, the Azure Cloud Shell/PowerShell/CLI, and Visual Studio to connect to and use Azure Service Bus queues. You will use the Azure Cloud Shell to create a Service Bus namespace and queue. Then, you’ll RDP into a Windows VM and update a pre-built Visual Studio solution with the appropriate C# code to connect to the queue, send messages to the queue, and subscribe to the queue to read messages. When you’re finished, you will run the console application to see everything working. Finally, you will verify messages were sent and received from the queue using the Azure portal. Upon completion of the lab, you will have gained the experience required to work with Azure Service Bus queues using C#. Learning Objectives Successfully complete this lab by achieving the following learning objectives: - Set up Cloud Shell and use PS/CLI to create a Service Bus namespace and queue. PowerShell script to create namespace and queue: # ------------------------ # az servicebus namespace create # az group list # az servicebus queue create # ------------------------ # create a Service Bus namespace and queue $resourceGroup = _______________ --query '[0].name' --output json $namespaceName = "LALab" + (Get-Date).ticks _______________ --resource-group $resourceGroup --name $namespaceName --location southcentralus _______________ --resource-group $resourceGroup --namespace-name $namespaceName --name myQueue # - RDP into the VM, open the VS solution, and set up Cloud Shell. RDP login: UserName : "azureuser" Password : "LA!2018!Lab" PowerShell to run: Add-Type -Path "C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.5System.IO.Compression.FileSystem.dll" $url = "" $zipfile = "C:UsersazureuserDesktopazure-service-bus-queues Service Bus queues. When we’re finished, we’ll run our completed console app to send messages to the queue and subscribe to the queue to read messages. We’ll also verify the messages were saved through the Azure portal.
https://acloudguru.com/hands-on-labs/using-azure-service-bus-queues-with-c-cloud-shell-powershell-and-cli
CC-MAIN-2021-10
refinedweb
300
53.21
A linked list is a recursive data structure. A recursive data structure is a data structure that has the same form regardless of the size of the data. You can easily write recursive programs for such data structures. # include <stdio.h> # include <stdlib.h> struct node { int data; struct node *link; };); } void printlist(struct node *p) { printf("The data values in the list are\n"); while (p != NULL) { printf("%d\t", p->data); p = p->link; } } 1. This recursive version also uses a strategy of inserting a node in an existing list to create the list. 2. An insert function is used to create the list. The insert function takes a pointer to an existing list as the first parameter, and a data value with which the new node is to be created as the second parameter. It creates the new node by using the data value, then appends it to the end of the list. It then returns a pointer to the first node of the list. 3. Initially, the list is empty, so the pointer to the starting node is NULL. Therefore, when insert is called the first time, the new node created by the insert function becomes the start node. 4. Subsequently, the insert function traverses the list by recursively calling itself. 5. The recursion terminates when it creates a new node with the supplied data value and appends it to the end of the list. Points to Remember 1. A linked list has a recursive data structure. 2. Writing recursive programs for such structures is programmatically convenient.
http://www.loopandbreak.com/inserting-a-node-by-using-recursive-programs/
CC-MAIN-2021-17
refinedweb
261
65.73
A few corrections: Step 4: Enter the project name (AddCalc in this case) and click "OK" Step 6: Instead of "OK" it should be "Finish" Step 8: Instead of "change the name to" it should be "enter the name" Posted 26 January 2010 - 10:52 PM Posted 02 February 2010 - 11:34 AM Posted 19 March 2010 - 08:05 AM Posted 14 April 2010 - 08:16 AM Posted 01 May 2010 - 10:01 AM #include <iostream> using namespace std; int main() { int a; cout<<"hi..enter any integer."<<endl; cin>>a; cout<<"thankyou."; return 1; } Posted 15 May 2010 - 12:53 AM Posted 15 May 2010 - 09:00 AM Posted 01 June 2010 - 07:41 AM AcroneShadow, on 23 July 2009 - 01:30 AM, said: return 0; cout << result << endl; Posted 01 June 2010 - 08:31 AM Kerem Karatas, on 01 June 2010 - 08:41 AM, said: AcroneShadow, on 23 July 2009 - 01:30 AM, said: return 0; cout << result << endl; Posted 19 June 2010 - 03:17 PM Posted 14 July 2010 - 02:01 PM Posted 15 July 2010 - 05:43 AM Posted 15 July 2010 - 12:10 PM Posted 21 July 2010 - 12:16 AM Posted 13 August 2010 - 10:20 PM
http://www.dreamincode.net/forums/topic/49569-getting-started-in-microsoft-visual-studio-2008/page__st__15__p__1018349
CC-MAIN-2016-44
refinedweb
203
51.18
I. First, some background on the ClientWindow feature. In the name of clean design, this feature is disabled by default. Because the Faces Flows feature entirely depends on ClientWindow, the usage of Faces Flows will automatically enable ClientWindow if it is not enabled already. To explicitly enable ClientWindow, you can set a <context-param> with a <param-name> of javax.faces.CLIENT_WINDOW_MODE and a <param-value> of url in your web.xml. For example <context-param> <param-name>javax.faces.CLIENT_WINDOW_MODE</param-name> <param-value>url</param-value> </context-param> The JSF specification allows other values for this parameter, but other values would be implementation specific. If ClientWindow is enabled, it will add an extra name=value pair onto every navigation component rendered by JSF. This extra name=value pair is the rendered representation of an instance of the javax.faces.lifecycle.ClientWindowclass. The JavaDoc for that class states: This class represents a client window, which may be a browser tab, browser window, browser pop-up, portlet, or anything else that can display a UIComponent hierarchy rooted at a UIViewRoot. The specification provides for additional logic that will cause an instance of ClientWindow to be automatically created if one is not already present for the currently rendered view. Now that we’ve defined the feature, let’s explain how to trip it up, and how to fix it. “Open in new tab” or “Open in new window” If a JSF 2.2 app has the ClientWindow feature enabled, every view that can be reached from the landing page for that app will have the extra name=value pair appended. In Oracle Mojarra, this parameter looks like this: jfwid=518a78c52da3c025ab7a31cf4d50:6. Components that render as hyperlinks offer the user a browser context menu that usually includes two options: “Open in new tab” and “Open in new window”. Selecting either of these two options would effectively cause two tabs to share the same ClientWindow. This is a violation of the concept and any data that is client window specific (such as flow scoped data) would now be shared across the two tabs (or windows). The easiest way to work around this is to simply prevent the context menu on any link components. This can simply be accomplished using an HTML5 Friendly Markup feature in JSF 2.2: passthrough attributes. Declare a an XML namespace on your facelet page with the following namespace URI:. Once declared, any attribute from that namespace will automatically be rendered straight to the markup without any server side interpretation. This can be used with the handy oncontextmenu javascript attribute to disable the context menu. For example: <html xmlns="" xmlns:h="" xmlns: <h:form <p><h:link value="callB via GET" outcome="callB" my:</p> </h:form> </html> Granted, this is a pretty brute force approach, but it can be targeted at individual components. I’ve opened JAVASERVERFACES_SPEC_PUBLIC-1227to create a more nuanced approach. Please vote for it if you’re interested and maybe we’ll get to it for JSF 2.3.
https://community.oracle.com/blogs/edburns/2013/10
CC-MAIN-2018-51
refinedweb
504
54.22
memmove() prototype void* memmove( void* dest, const void* src,size_t count ); The memmove() function takes three arguments: dest, src and count. When the memmove() function is called, it copies count bytes from the memory location pointed to by src to the memory location pointed to by dest. Copying is performed even if the src and dest pointer overlaps. This is because copying takes place as if an intermediate buffer is created where the data are first copied to from src and then finally copied to dest. It is defined in <cstring> header file. memmove() Parameters dest: Pointer to the memory location where the contents are copied to src: Pointer to the memory location where the contents are copied from. count: Number of bytes to copy from src to dest. memmove() Return value The memmove() function returns dest, the pointer to the destination memory location. Example: How memmove() function works #include <cstring> #include <iostream> using namespace std; int main() { int arr[10] = {8,3,11,61,-22,7,-6,2,13,47}; int *new_arr = &arr[5]; memmove(new_arr,arr,sizeof(int)*5); cout << "After copying" << endl; for (int i=0; i<10; i++) cout << arr[i] << endl; return 0; } When you run the program, the output will be: After copying 8 3 11 61 -22 8 3 11 61 -22
https://www.programiz.com/cpp-programming/library-function/cstring/memmove
CC-MAIN-2020-16
refinedweb
219
57.5
You can click on the Google or Yahoo buttons to sign-in with these identity providers, or you just type your identity uri and click on the little login button. Corrected by Test case: #!/usr/bin/env python import subprocess a, b = subprocess.Popen('true', stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print a.strip() E1103: 4: Instance of 'list' has no 'strip' member (but some types could not be inferred) I have this issue to +1 I have this issue as well. for those to which this matters: this is a good opportunity to contribute to the pylint-brain :) more info here: This bug is corrected by a functionnality implemented in pylint-brain Since the bug fix we now get: #!/usr/bin/env python import subprocess a = subprocess.Popen('true').wait() E1101: 3,4: Instance of 'Popen' has no 'wait' member I have the same problem with Popen - wait, returncode and stdin yield E1101 Me 2. The bugfix didn't completely fix the issues, I'm still getting : Instance of 'Popen' has no 'wait' member Instance of 'Popen' has no 'returncode' member
http://www.logilab.org/ticket/46273
CC-MAIN-2014-52
refinedweb
183
61.67
Certification Exams for Symfony and Twig are now Online! We are extremely pleased to announce that the Symfony and Twig certification exams are available online! It means that you can now take the exam from home or from your office! You need your computer, a web cam and a stable Internet connection! Fabien Potencier introduced the Symfony certification program during his keynote at SymfonyLive Paris 2012 and the first certification session was organized during the conference. At that time, the certification was only organized during official Symfony events. The exam was hold in the conference venue and proctored by the SymfonyLive team. Then different exam sessions were organized during the year at SensioLabs’ offices. The first certification was dedicated to the 2.3 version of the framework. In October 2013, the Symfony certification was launched worldwide and available in 4,000 physical exam centers to enable much more people to take it. At the same time we introduced the « Advanced level » as an intermediary step before the « Expert level ». Since then, the certification exam was only available in one of the 4,000 worldwide exam centers available. The Symfony 3 certification was launched in December 2015 and the Twig certification was introduced in June 2016. Lately this year, on March 30th, we introduced the Symfony 4 certification. We are now moving forward with the certification! We wanted to enable everyone to take any exam no matter where you are in the world 1: as long as you have a computer, a web cam and a stable Internet connection, you can take it. As of today, the certification exam is only available online for any Symfony versions and Twig. You don’t have to go to any exam center, schedule an appointment and physically go there to take the exam. Now it’s faster and easier to take the exam, you can take it from your own home or office.. Your online certification exam will be proctored during the entire test, the proctor will ask you to test your camera and show the room where you take the exam before starting the test. Don't forget to test and check your camera and network connection before starting! To book your online certification exam, follow these steps: 1- Buy your certification voucher for Symfony 3 or 4 version or for Twig 2- Create your candidate account or log in to your existing account 3- Activate your voucher to schedule an exam appointment 4- Take the exam online in your own home or office and get your result immediately! When you buy your certification voucher and activate your voucher, you have to wait for 24 hours before scheduling your exam. You can buy your certification voucher today and become a Symfony or a Twig certified developer tomorrow! We are proud to count about 400 certified Symfony and Twig developers in our community and we’d like to congratulate again all the certified Symfony and Twig developers! You want to become a Symfony or a Twig certified developer? Book your certification voucher at the unique price of 250 € for Symfony and 149€ for Twig. If you have any questions regarding the Symfony and Twig certification exams, please read our FAQ section where you’ll find more detailed information. Good luck! 1Exceptions of Cuba, Iran, North Korea, Sudan and Syria due to US Foreign policies. As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities. Certification Exams for Symfony and Twig are now Online! symfony.com/index.php/blog/certification-exams-for-symfony-and-twig-are-now-onlineTweet this __CERTIFICATION_MESSAGE__ Become a certified developer! Exams are online and available in all countries.Register Now The new provider for the online certification is a company from USA, and the USA government doesn't allow its companies to do business in certain countries. In addition to Cuba, the online certification is not available in Iran, North Korea, Sudan and Syria. Also, because the online certification requires continuous monitoring of the person taking the exam, is restricted to people of 18 years of older, also because of some USA legal requirements. I already failed once and I know some of the questions I failed. For example; I didn't know correct syntax for forwarding request because PHPStorm does it for me (and I only used it once). There are few more I did wrong like mistaking DOMCrawler for CssSelector component. Thanks. you mentioned "Buy your certification voucher for Symfony 3 or 4 version or for Twig" this is not available for symfony 2.3 voucher ? No, I don't believe so, like any other exam you are expected to know these things. The same goes for doctors, and any other profession, you are expected to know these things when you are certified. Sure, you might need to look something up when you don't use it daily, that's normal, but you know the majority of things. Relying on tools like autocomplete, syntax highlighting or xdebug is great to help you with your daily work, but being a professional means you can proof you know these things other rather then relying on only your tools, Assembly coders that worked with a PDP didn't have debugging or syntax highlighting (there wasn't even screen, only a typewriter that printed what you typed 🤪 ). I got started with PHP using notepad and no internet connection! You know how hard it is to use notepad? More then often it failed, but I still managed to make it work (after hours of cussing...). If PHPStorm (or Zend Studio at the time) fails to work or is not available I can still use Atom or notepad++, there is no autocomplete, no error highlighting or even code generator. But still I can make it work resorting to only my knowledge (and tests). That is what being a professional is about, knowledge is power! PHPStorm is a tool. Tools make our lives easier but they can fail, and when that happens you need knowledge to make it working again. If an exam allowed these kinds of things to make it easier, the exam would loose its added value, anyone could pass it by Googling the answer or using suggestions, the certification becomes nothing more then a tittle for anyone who can pay for it. What if your brain surgeon winged himself through college (hello Dr. Nick), "what that's that thing in your skull?" Can you trust him with your life? I have seen people (in Holland) wing themselves through a drivers exam by cheating the rules! And guess what, they drive terrible and might even kill (or have killed) someone because they don't know the freaking rules!! They cared more about getting their license rather then assuring themselves with the rules, which exist for a reason, to ensure safety of themselves and those involved in traffic. This is what happens when exams (in general) become to easy or when cheating is not prevented, it looses its value and security, we compromise until we no longer care. And people become more obsessed with getting certified (or getting their license) rather then remembering why these rules and requirements were set-up in the first place. In this case to assure knowledge and skills. If you didn't make it first time, you try again, yes it's painful to fail, but not the end of world. If you believe in yourself you can make it, maybe not the next time, maybe not then, but when you do make it, it will be ever more rewording because you achieved something that is hard, you worked for it, and deserve that honoring title, and that makes you special, it makes you a professional! You don't compromise but you show you care, and do it right. Some closing tips. If you really want to learn how do things properly you might want to stop using PHPStorm for a while or stop using the auto suggest, you learn best by doing things yourself rather then letting someone (or something) do it for you. Tools help us, they don't replace us. ---- Hopefully I wasn't to harsh, I am trying show why caring about these things matters to be a professional. I am not suggesting that you cheat by using auto suggest. I will try to explain my thoughts a little better below. Uncle Bob Martin had a good talk on this, if we stop caring about quality as programmers, and compromise (endlessly) just to make it work, we loose control of our code, we start to compromise until we no longer care. And that's dangerous, we will loose respect and value for our craft, our industry will become regulated by law to ensure all software we produce is of a good quality and secure! Being certified will become mandatory rather then an added value. We are responsible for what we produce, if we allow ourselves to knowingly allow code of a lesser quality to be released, we are responsible for the outcome of that broken code. People have died because of faulty code! I am in the process of building a hosting system (open-source) and carry with this a major responsibility, think what will happen if this system will ever get hacked?! I will be responsible for that (not lawfully btw), but ethically, if I can't proof I took proper steps to prevent this from happening. Compromise it not an option here. To me the first step in being a professional is to show you care to do things right, not because they are easy but because they matter. Or as and old saying goes: Soft healers make for stinky wounds. Sometimes you need to be harsh or touch, to do whats right. For example; I built tons of compiler passes, form extensions, custom route annotations (even undocumented usage of Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface) but I find it hard to remember their namespaces. Sometimes even class names; guess I am getting old. So I don't think autocomplete is cheating nor it in any ways influence code quality. I have phpstan for that, max-level. It is a tool just like doctors have tools for heart surgery; the time of doing it manually is long gone. --- Anyway, this is not a forum. Thanks Javier for answering; I will try again. I really want that badge :) Also, if you wanted to enable everyone to take an exam no matter where they are in the world, You should choose a provider that has no limitation from the USA government. If you can't, please remove that bolded sentence from your blog. - for US companies to work with companies originated from banned countries - and for US companies to work with any other company that trades with companies originated from banned countries. This means every company in the world has to choose between working with US companies or with Cuban/Iran/... companies. I don't think it's fair to blame Symfony on this, it concerns everyone and it's something Symfony can't do anything about. Plus, there is a list of the exceptions at the end of the blog post, so the limitation is transparent. To ensure that comments stay relevant, they are closed for old posts. Yonel Ceruto said on Oct 31, 2018 at 12:19 #1
https://symfony.com/index.php/blog/certification-exams-for-symfony-and-twig-are-now-online
CC-MAIN-2021-10
refinedweb
1,910
60.75
I'm reading through Classic Computer Science Problems in Python (affiliate link) by David Kopec, and I'm working on his Genetic Algorithm examples. He got to the point where he describes the roulette-style selection process. Some background: this isn't a post about Genetic Algorithms, but imagine this. Assume you've got a group of candidates in a breeding process. The roulette-style selection process means that you create a giant roulette wheel with all of the candidates on it, and the size of each candidate's wedge depends on their "fitness" score: how much of the desired result they have in them. Then, you spin the wheel to randomly select based on these weights. OK, so back to me. I read through that description and I was mentally gearing up to implement this. We need to get each candidate's fitness, figure out how they stack up, normalize to a scale from 0 to 1, and then figure out how to randomize that selection. Not impossible to implement, but it would take several lines or more of code to do it. Cool beans. Then I get to the author's solution. And I just sat there. Staring at it. You know that feeling when you see something and it just makes you mad and because of how hard you worked on yours and then somebody comes in and does it the easy way? But at the same time, you're also very impressed because it's awesome? Something like that. Here. Just look at it. I tweaked it a little to show more context here: from random import choices def pick_parent_candidates(population): fitnesses = [candidate.fitness() for candidate in population] return tuple(choices(population, weights=fitnesses, k=2)) It just... It just does the thing. Anyways, random.choices is pretty cool. In fact, the whole random module has a lot of underrated functions that can save you oodles of time and code. Discussion (2) Found this post searching specifically for GA selection techniques, just wanted to say that the choices() is great, but it's really not a roulette selection, it's just selecting 2 candidates with probability being equal to the fitness. In order to make a roulette wheel selection, you have to be a little more complex than that, mainly: Very simple code: This is a very simple algorithm, and there are other implementations (way faster and better), but it shows the point ;). 100%! I have found random.choice is very useful for generating test data.
https://dev.to/rpalo/python-s-random-choices-is-awesome-46ii
CC-MAIN-2021-21
refinedweb
420
64.41
Hello, I am using OS X. Where do I save my scripts so that I can import them? I get an error when I try to import: "ImportError: no module named <sample>" Where do I save my scripts so that I can import them? I get an error when I try to import: "ImportError: no module named <sample>" import <module> import time It says to begin the Python shell in the same directory as where the file is saved. I am not sure what this means. from <module> import * from tryme3 import * File "<stdin>", line 1, in <module> ImportError: No module named function My task was just to import a script that the book suggested I write. I saved it on my Desktop and I also tried saving it in My Documents, but the result is the same, the error. I do not know how to save my script in the same directory as the Python shell, so that I can import it like the example in the book. And thanks for clearing up how to post well. metulburr@ubuntu:~$ mkdir temp metulburr@ubuntu:~$ cd temp metulburr@ubuntu:~/temp$ ls metulburr@ubuntu:~/temp$ sudo vim test_module.py [sudo] password for metulburr: metulburr@ubuntu:~/temp$ cat test_module.py def adder(x,y): return x + y metulburr@ubuntu:~/temp$ python test_module.py metulburr@ubuntu:~/temp$ sudo vim test.py metulburr@ubuntu:~/temp$ cat test.py import test_module total = test_module.adder(1,3) print(total) metulburr@ubuntu:~/temp$ python test.py 4 metulburr@ubuntu:~/temp$ ls test_module.py test_module.pyc test.py metulburr@ubuntu:~/temp$ python Python 2.7.4 (default, Apr 19 2013, 18:28:01) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.listdir('.') ['test.py', 'test_module.pyc', 'test_module.py'] >>> ok here is an example of creating/using a module. This is all done via terminal in linux. vim is the text editor i used to write the files, and the cat displays the file (for you to see what I wrote). All of these files are in the directory "temp" that i created. The ls command given displays the 3 files in the directory, the 2 i wrote and the .pyc that python wrote when the module was imported. All these files are in the same directory. The last command given starts up the python interpreter. the directory i am in when i start it is the directory the interpreter is in, (shown via os.listdir) import os import tryme3 and neither the python shell nor the built in terminal displays what I quoted above. When I did this, my file "tryme3.py" was converted into "tryme3.pyc". I don't know the difference. Should I be saving files ending in .pyc from now on? Also, please explain to me why "import os" allowed me to import other scripts? bash-3.2$ bash-3.2$ python >>> bash-3.2$ pwd bash-3.2$ ls bash-3.2$ ls tryme3.py from tryme3 import * bash-3.2$ cd bash-3.2$ mkdir thinkpython bash-3.2$ cd thinkpython/ bash-3.2$ mv ~/Desktop/*.py ./ Return to General Discussions Users browsing this forum: Google Feedfetcher and 1 guest
http://www.python-forum.org/viewtopic.php?f=10&t=4713
CC-MAIN-2013-48
refinedweb
536
78.35
Microcontroller Monday - Wemos W600 Pico < Film trailer voice >From the team that brought you the Wemos D1 comes the W600 Pico...< / Film trailer voice > Before we get too deep into this blog post I would like to thank Volodymyr Shymanskyy for his help in solving a few issues with this board. So please go and check out his projects! A new tiny board that connects to the Internet! Another one? Yeah! The Wemos W600 Pico is a rather fun piece of kit, especially when we factor in the cost, around $3 for the board! Measuring only 33mm x 20mm this board is just smaller than the venerable Wemos D1 Mini (which has powered a few of my projects!) What do we get for the money? - Arm Cortex M3 running at 80MHz - WIFI (2.4GHz) - 1MB Flash - 15x IO - 1x I2C - 1x SPI - 1x UART - RTC (Real Time Clock) - Hardware Cryptography - CH340 USB to TTL (Serial) connector - MicroPython Where can I buy one? I picked up a couple from Aliexpress for $2.10 each and they took around 2 weeks to reach me. At the time of writing, the seller is out of stock. This is likely due to it being Chinese New Year and the awful virus outbreak means that whole areas are isolated from each other, preventing them from working and being with loved ones so that everyone can be safe. Pinout Image from [] The GPIO runs at 3.3V so when using any components at 5V, take all the necessary steps to protect the W600 Pico. >>IMAGE! Getting access to the repl To access the repl for the w600 Pico, and from there we can test that our board works, we need to plug in the board to our computer and for my Ubuntu machine I opened a terminal and ran the following command to detect which port it was connected to. udevadm monitor --udev Which was /dev/ttyUSB0 for me. Windows users can detect the correct port using the Device Manager application, and then checking their COM ports. Connecting to the repl I used tio, a recent Tuesday Tooling discovery to create a connection to the W600 Pico via the USB to Serial interface. But you can use tools such as puTTY to make a connection on Windows. So this is MicroPython? Yup, the included version (as of January 2020) is MicroPython v1.10-282-g6a9b3cb-dirty on 2019-09-17; WinnerMicro module with W600 and it comes with a standard set of modules for us to use. What modules come as standard? _boot hashlib select uos _onewire heapq socket urandom _thread io struct ure array json sys uselect binascii machine time usocket builtins math ubinascii ustruct cmath micropython ucollections utime collections network uctypes utimeq ds18x20 ntptime uerrno uzlib easyw600 onewire uhashlib w600 errno os uheapq zlib framebuf random uio Two modules which caught my eye were easyw600 and w600 as these are board specific. But what do they do? easyw600 >>> import easyw600 >>> easyw600. __class__ __name__ binascii connect disconnect network oneshot scan utime w600 createap closeap ftpserver Immediately I can see connect and disconnect which provide a simple means to connect to a know WiFi AP / SSID. Connect to WiFi import easyw600 easyw600.connect("NAME OF ACCESS POINT","PASSWORD") Create a quick FTP Server and upload your files All I needed to do was first connect the board to the WiFi and then run the ftpserver. It opened port 21, and told me the username/ password. import easyw600 easyw600.ftpserver() Then using an FTP client, in my case the file manager in Ubuntu, go to the IP address of the board, like this. And login as username: root password: root We can then upload files to the board, for example I uploaded a custom boot.py using this method, and now my W600 Pico connects to WiFi on boot. This is far from ideal, but it at least gives me access from any device. Change the FTP password In the easyw600.pyfile, line 55 we see the username and password for the FTP server. These can be changed to suit your requirements. def ftpserver(): w600.run_ftpserver(port=21,username="root",password="root") print("ftp server port is 21, username is root, password is root") Create an Access Point If you need to create an access point from which we can connect locally, we can tell the W600 Pico to broadcast its own Access Point. import easyw600 easyw600.createap() Then we can connect via FTP to upload files. w600 The w600 module looks to be a collection of tools to work with the flash memory of the device. Use with caution! >>> w600. __class__ __name__ flash_erase flash_id flash_read flash_size flash_user_start flash_write run_ftpserver version Can I make an LED blink? The "Hello World" of physical computing! Ok lets do it! I connected the anode (long leg) of an LED to PB6, and the short leg (cathode) was connected to GND via a 220 Ohm resistor. from machine import Pin import time led = Pin(Pin.PB_06, Pin.OUT, Pin.PULL_FLOATING) while True: led.value(1) time.sleep(0.2) led.value(0) time.sleep(0.2) Why Pin.PULL_FLOATING? For some reason if we do not include that argument, then the pin will not activate. My best guess is that there is a pull up/down resistor for the pin. The only issue with doing this test is that the repl will become unresponsive, and we have to reset the board to carry on working. w600tool January 31 2020 - Update - Please note that this section has been completely revised so that we only use the original version of this tool, and not the Wemos version which has a few issues with correctly flashing code to the W600. So what is it? The original and well maintained tool to upload firmware to a W600 Pico board. Created by Volodymyr Shymanskyy, w600tool is designed for W600 and W601 boards and is a general maintenance tool for uploading firmware and for getting and setting the devices MAC address. So how do I install it? Clone the repository from Github. git clone You can also download the ZIP file containing the project. Then install a few dependencies via pip3. sudo pip3 install pyserial PyPrind xmodem So how do I use it? Lets take a typical use case. Flashing new firmware to the W600 Pico I've got my W600 Pico, and a new firmware is released. So I download it and copy the image file img or fls to the same location as w600tool.py and then I use this command to upload it to the board. python3 w600tool.py -p /dev/ttyUSB0 -u wm_w600.fls --upload-baud 115200 Lets breakdown that command I call python3 to run the Python code inside w600tool.py. The -p switch tells w600tool that I am using port /dev/ttyUSB0 to upload the file. The -u switch is the name of the firmware file I aam uploading. Finally --upload-baud 115200 tells w600tool that the baud rate (connection speed) should be 115200bps. Can I make w600tool.py an executable application? Sure, to make w600tool.py executable in a terminal, in the same directory as the file type chmod +x w600tool.pyand you will not have to call the command with python3at the start. You can also copy w600tool.py to your /usr/bin/directory by typing sudo cp w600tool/w600tool.py /usr/bin/w600toolso now all we have to do is type w600toolto use the command. So why should I use this over the Wemos version? This is the original version which does not have any issues. The Wemos fork of this project has a few issues with line ending characters and this causes Python3 to error unless we remove these characters using a tool such as dos2unix. How can I upload my code to the board? I mentioned earlier that we can set the W600 Pico to run an FTP server, but sometimes we just want to send a file to the board without messing around with servers etc. The ideal tool for this is Adafruit's ampy, which I've written about in a Tuesday Tooling blog post. But here is a condensed version of that post. To install ampy Linux sudo pip3 install adafruit-ampy Windows pip.exe install adafruit-ampy For my project I wanted to upload a custom boot.py file to connect my W600 Pico to my home WiFi on boot. So in a text editor I did just that. import easyw600 easyw600.connect("EVIL LAIR AP","TRUSTNO1") Then using ampy I upload the file to the W600 Pico...or so I thought :( ampy --port /dev/ttyUSB0 put boot.py I got an error stating that ampy could not enter a raw repl and this caused the application to exit But luckily Volodymyr Shymanskyy was on hand to help and offered a workaround by replacing a file in the ampy install with a modified version. I've copied the file to my Google Drive, from where you can download it. I then saved the original pyboard.py file in the ampy directory sudo mv /usr/local/lib/python3.6/dist-packages/ampy/pyboard.py /usr/local/lib/python3.6/dist-packages/ampy/pyboard.py.old And then copied the new pyboard.py file from my Downloads directory to the ampy directory. sudo cp /home/les/Downloads/pyboard.py /usr/local/lib/python3.6/dist-packages/ampy/pyboard.py Then I ran the ampy command to copy my custom boot.py file to the W600 Pico. ampy --port /dev/ttyUSB0 put boot.py The code in my custom boot.py file, and no that is not my WiFi details Successfully copied a file to the W600 Pico Proof that it worked So is ampy at fault? No! FYI, there's really no problem with ampy, I believe the problem is in the pre-built uPython image for W600 (it uses different line ending marks for some reason)— Volodymyr Shymanskyy (@vshymanskyy) January 29, 2020 As Volodymyr says "I believe the problem is in the pre-built uPython image for W600 (it uses different line ending marks for some reason)" and I believe that the issue with line ending marks we encountered and had to mitigate using dos2unix confirms this. MicroPython Specifics! MicroPython has two files that are important to us and these are the main files that we will interact with, unless we add our own libraries of MicroPython code. boot.py This is the file which contains the code that will run when the W600 Pico is powered up. So in my use case I added two lines of code to automatically connect the board to my WiFi. This can also be used to set any specific requirements for the board, WiFi, FTP server, blinking lights to confirm successful startup. main.py In this file is the main application / project that you are using the board for, such as your cool weather station or Neopixel lamp.
https://bigl.es/microcontroller-monday-wemos-w600-pico/
CC-MAIN-2020-16
refinedweb
1,832
72.97
The example in this section demonstrates how to implement html2shtml, a custom SAF that instructs the server to treat a .html file as a .shtml file if a .shtml version of the requested file exists. A well-behaved ObjectType function checks if the content type is already set, and if so, does nothing except return REQ_NOACTION. The primary task an ObjectType directive needs to perform is to set the content type (if it is not already set). This example sets it to magnus-internal/parsed-html in the following lines: The html2shtml function looks at the requested file name. If it ends with .html, the function looks for a file with the same base name, but with the extension .shtml instead. If it finds one, it uses that path and informs the server that the file is parsed HTML instead of regular HTML. Note that this requires an extra stat call for every HTML file accessed. To load the shared object containing your function, add the following line in the Init section of the magnus.conf file: Init fn=load-modules shlib=yourlibrary funcs=html2shtml To execute the custom SAF during the request-response process for some object, add the following line to that object in the obj.conf file: ObjectType fn=html2shtml The source code for this example is in otype.c in the nsapi/examples/ or plugins/nsapi/examples subdirectory within the server root directory. #include "nsapi.h" #include <string.h> /* strncpy */ #include "base/util.h" #ifdef __cplusplus extern "C" #endif NSAPI_PUBLIC int html2shtml(pblock *pb, Session *sn, Request *rq) { /* No parameters */ /* Work variables */ pb_param *path = pblock_find("path", rq->vars); struct stat finfo; char *npath; int baselen; /* If the type has already been set, don't do anything */ if(pblock_findval("content-type", rq->srvhdrs)) return REQ_NOACTION; /* If path does not end in .html, let normal object types do * their job */ baselen = strlen(path->value) - 5; if(strcasecmp(&path->value[baselen], ".html") != 0) return REQ_NOACTION; /* 1 = Room to convert html to shtml */ npath = (char *) MALLOC((baselen + 5) + 1 + 1); strncpy(npath, path->value, baselen); strcpy(&npath[baselen], ".shtml"); /* If it's not there, don't do anything */ if(stat(npath, &finfo) == -1) { FREE(npath); return REQ_NOACTION; } /* Got it, do the switch */ FREE(path->value); path->value = npath; /* The server caches the stat() of the current path. Update it. */ (void) request_stat_path(NULL, rq); pblock_nvinsert("content-type", "magnus-internal/parsed-html", rq->srvhdrs); return REQ_PROCEED; }
http://docs.oracle.com/cd/E19857-01/819-6515/abvfr/index.html
CC-MAIN-2015-35
refinedweb
404
55.34
The QSqlIndex class provides functions to manipulate and describe QSqlCursor and QSqlDatabase indexes. More... #include <qsqlindex.h> Inherits QSqlRecord. List of all member functions. This class is used to describe and manipulate QSqlCursor and QSqlDatabase indexes. An index refers to a single table or view in a database. Information about the fields that comprise the index can be used to generate SQL statements, or to affect the behavior of a QSqlCursor object. Normally, QSqlIndex objects are created by QSqlDatabase or QSqlCursor. See also Database Classes. Reimplemented from QSqlRecord. Appends the field field to the list of indexed fields. The field is appended with an ascending sort order, unless desc is TRUE. Returns the name of the cursor which the index is associated with. See also toStringList(). Returns the name of the index. This file is part of the Qt toolkit. Copyright © 1995-2005 Trolltech. All Rights Reserved.
https://doc.qt.io/archives/3.3/qsqlindex.html
CC-MAIN-2019-18
refinedweb
147
62.85
About a year ago WordPress decided to update the required minimum PHP version, from 5.2 (used since 2010) to something more up-to-date. In fact, Today the minimum version of PHP recommended by WordPress is one of the most recent: PHP 7.3. If you are a simple WordPress user, this probably will not impact you too much (beyond the fact that these new versions give better performance). But if you are a developer, these new PHP versions have some awesome features you can use in your plugins and themes. And today, specifically, I would like to talk to you about one that has been with us for a long time but: namespaces. WordPress and code prefixes One of the first rules you learn as a WordPress developer is to “use prefixes in everything we do” to avoid “name collisions.” As we can read in WordPress best practices : A naming collision happens when your plugin is using the same name for a variable, function or a class as another plugin. [To avoid name collisions], all variables, functions and classes should be prefixed with a unique identifier. Prefixes prevent other plugins from overwriting your variables and accidentally calling your functions and classes. It will also prevent you from doing the same.Best practices for developing WordPress plugins Thus, for example, instead of creating a function like get_site_id, it’s better to name it nelio_content_get_site_id. This way, we are able to quickly identify the plugin ( nelio_content) or theme to which a certain function ( get_site_id) belongs and avoid fatal errors if several plugins try to define the same function. Using prefixes is a rudimentary way of creating a “namespace”; a workaround we had to implement when we didn’t have a better alternative. All those elements that use the same prefix are part of the same set or namespace. But this results in unnecessarily more complex code: names are longer because of prefixes that serve no purpose other than emulating namespaces. PHP Namespaces PHP version 5.3 introduced the concept of namespace. The definition they give of it in the documentation seems excellent to me, so I reproduce it here: the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: 1. Name collisions between code you create, and internal PHP code or third-party code. 2. Ability to alias (or shorten) Extra_Long_Names, improving readability of source code.PHP docs How to create a namespace Creating a namespace in PHP is extremely easy. At the beginning of the PHP file you create, add a namespace directive with the name you want to use and “everything” you define in that file will belong to that namespace: <?php namespace Nelio_Content; Yes, it’s that simple! Now “everything” we create there will be in the Nelio_Content namespace. For example, if I define a function like the one I mentioned at the beginning: <?php namespace Nelio_Content; function get_site_id() { // ... } we now know that get_site_id is inside the Nelio_Content namespace. In this way, we no longer have to use the nelio_content_ prefix when defining the function. Great! Exceptions To Namespaces If you look closely at what I have told you so far, you will see that I have been writing “everything” in quotes: “‘everything’ we add there will belong to the specified namespace.” Why did I do that? Because namespaces don’t apply to absolutely all code we write… there are some exceptions. PHP namespaces only cover the following PHP elements: - Classes - Interfaces - Traits - Functions - Constants declared with constbut not with define In addition, there are some additional things in WordPress that also need their own namespaces and, unfortunately, PHP namespaces do not cover: your script handles, database options, or custom content types and their metadata, etc. In all these cases, you must continue using prefixes. How to Import Elements From One Namespace To Another If you need to use an element that is in your own namespace, you don’t have to do anything special: just call it by its name. For example, in the following code snippet: <?php namespace Nelio_Content; function get_site_id() { // ... } function get_auth_token() { $site_id = get_site_id(); // ... } You can see that we have defined two functions: get_site_id and get_auth_token, both within the Nelio_Content namespace. When get_auth_token needs to use get_site_id, it simply calls it as usual. If, on the other hand, you need to use get_site_id in a different namespace, you must call the function using its full identifier: <?php namespace Something_Else; function do_some_action() { $site_id = Nelio_Content\get_site_id(); // ... } or you must import the function with the keyword use: <?php namespace Something_Else; use Nelio_Content\get_site_id; function do_some_action() { $site_id = get_site_id(); // ... } I personally like the second option a lot: using the keyword use to import functions from other namespaces, you can take a quick look at the header of your file and identify its dependencies. WordPress Filters And Actions With PHP Namespaces There is an important detail that you should keep in mind when using namespaces next to WordPress filters and actions. When you specify filter and action callbacks, usually you do so by giving the callback name as an string: <?php // ... add_action( 'init', 'do_some_action' ); The problem is that if this function is within a namespace, the previous hook will not work as expected; you must tell WordPress the full name of the function. In other words, you have to include its namespace (if it has one). Are you adding the hook in the file where you define the namespace itself? It doesn’t matter, use the full name: <?php namespace Nelio_Content; function do_some_action() { // ... } add_action( 'init', 'Nelio_Content\do_some_action' ); Are you in another namespace but you imported the function with use? It doesn’t matter either, use the full name: <?php namespace Something_Else; use Nelio_Content\do_some_action; // ... add_action( 'init', 'Nelio_Content\do_some_action' ); Using Aliases With Our Namespaces Another very interesting functionality of namespaces is aliasing. Imagine the following scenario: <?php namespace Nelio_Content; function get_site_id() { // ... } If I want to use this function in another namespace, we have already seen that I can do it with use. But how would I use this function if the module I want to use it in already has a function called get_site_id? Well, luckily for me, we can alias our imports into new names: <?php namespace Something_Else; use Nelio_Content\get_site_id as get_nc_site_id(); function get_site_id() { // ... } function do_some_action() { $nc_site_idd = get_nc_site_id(); // ... } Start Using Namespaces Today! Namespaces are a fantastic tool to avoid name collisions and to organize our code. In fact, and although I have not commented on this post, there are standards such as PSR-4 that allow PHP to auto-load classes based on the structure of namespaces you use and how you organize the code into directories and files. If you are not yet using namespaces in your projects yet, we recommend you start doing so from now on. Tell us about your experience in the comments! Featured image by Chaitanya Tvs on Unsplash.
https://neliosoftware.com/blog/namespaces-in-php/
CC-MAIN-2020-29
refinedweb
1,153
63.29
Defining new control structures using C macros While procrastinating today, I stumbled upon a blog post describing how to start some background work from C code in a convenient way. The solution the author came in with allows a developer to write code such as: int baz(void) { do_something(); start_deferred_work(); do_something_else(); end_deferred_work(); do_something_different(); return some_value; } The implementation uses two macros, start_deferred_work to fork the current process and end_deferred_work to terminate the child process using exit(0). I do not intend to discuss the validity or the efficiency of this method. I am more interested in how the author could have introduced a new control structure instead of those two macros. The main reason I do not like them is that they have a risk of letting you with an open scope if you forget the end_deferred_work macro, and they do not play nicely with automatic indentation, as the implicitly created scope does not visually appear. Many languages allow you to introduce new control structure through delayed evaluation blocks (e.g., Scala, Factor, Smalltalk, Ruby) or some macro expansion (e.g., Lisp-like languages). This is not directly possible in C as the C preprocessor only allows basic manipulations. However, those text manipulations can sometimes be sufficient to mimic new control structures. Let us rewrite those two macros as a pseudo control-structure named detach. To acknowledge the fact that after forking we need to perform two actions (execute the user-supplied code, the exit the child process) we will use a for loop as a way to invert two actions A() and B(): if B() evaluates to false or makes the current thread terminate, then A(); B(); may be written as for (;; B()) A();. Since exit(0); makes the current process quit, we can use this for construct to insert a call to exit(0); after the user-supplied code: #include <stdlib.h> #include <unistd.h> #define detach if (fork()); else for (;; exit(0)) After this definition, we can use detach as if it were a built-in C control structure comparable to for or while: /* Example 1 */ detach do_something(); /* Example 2 */ detach { do_something(); do_something_else(); } /* Example 3 */ detach for (int i = 0; i < 2; i++) do_something(i); /* Example 4 */ if (execute_in_background) detach do_something(); /* Execute on background */ else do_something(); /* Execute on foreground */ The astute reader will wonder why, in the macro definition snippet, we used a surprising if (fork()); else instead of if (!fork()) which might first appear to be equivalent. The reason to do so is that both constructs may sometimes have different effects: in C, an else is paired with the closest same-scope if without a else clause. This allows the compiler to parse code such as if (condition) if (other_condition) do_something(); else do_something_else(); without ambiguity. Here, we want users of our macro to be able to use it with a similar if clause as is the case in example 4. If we used the incorrect if (!fork()) code, we would end up with the following macro expansion (indented to show how the compiler understands it): if (execute_in_background) if (!fork()) for (;; exit(0)) do_something(); else do_something_else(); According to the rule we described earlier, the else do_something_else(); part would be matched with the if (!fork()) in line 2 instead of the if (execute_in_background) in line 1. If execute_in_background is true, do_something() and do_something_else() will both be executed (the former in the child process, the latter in the parent process), and if execute_in_background is false, none of the functions will be called. Using our proposed macro, the expansion will give (once again indented as the compiler understands it) if (execute_in_background) if (fork()); else for (;; exit(0)) do_something(); else do_something_else(); which correctly matches the latest else with the right if. For the same reason, we can properly nest calls to our macro: #include <stdio.h> int main(void) { printf("In parent (pid = %d)\n", getpid()); detach { printf("In child (pid = %d, ppid = %d)\n", getpid(), getppid()); detach printf("In grand child (pid = %d, ppid = %d)\n", getpid(), getppid()); printf("Still in child here (pid = %d)\n", getpid()); } printf("Still in parent (pid = %d)\n", getpid()); } gives on my system In parent (pid = 31402) Still in parent (pid = 31402) In child (pid = 31403, ppid = 31402) Still in child here (pid = 31403) In grand child (pid = 31404, ppid = 31403) So the C macro system, although very limited, lets you define new control structures to use in your code. In C++, the Boost library makes an heavy use of them to define, for example, new iterators. Note that, once again, I am not discussing here the appropriateness of spawning a child process to execute background code, but only a better way of implementing the original proposal. Aren’t C macros cool? Edit: the initial version of this article used a more complicated macro which required the compiler to respect the C99 standard. A commenter pointed out a simpler form, which is the form now used here.
http://www.rfc1149.net/blog/2012/03/17/control-structures-with-c-macros/
CC-MAIN-2013-48
refinedweb
822
54.05
Provides access to the children of one of the following: an XElement object, an XDocument object, a collection of XElement objects, or a collection of XDocument objects. object.<child> Required. An XElement object, an XDocument object, a collection of XElement objects, or a collection of XDocument objects. Required. Denotes the start of a child axis property. Required. Name of the child nodes to access, of the form [prefix:]name. Part Description prefix Optional. XML namespace prefix for the child node. Must be a global XML namespace defined with an Imports statement. name Required. Local child node name. See Names of Declared XML Elements and Attributes. Required. Denotes the end of a child axis property. A collection of XElement objects. You can use an XML child axis property to access child nodes by name from an XElement or XDocument object, or from a collection of XElement or XDocument objects. Use the XML Value property to access the value of the first child node in the returned collection. For more information, see XML Value Property. The Visual Basic compiler converts child axis properties to calls to the Elements method. The name in a child axis property can use only XML namespace prefixes declared globally with the Imports statement. It cannot use XML namespace prefixes declared locally within XML element literals. For more information, see Imports Statement (XML Namespace). The following example shows how to access the child nodes named phone from the contact object. Dim contact As XElement = _ <name>Patrick Hines</name> <phone type="home">206-555-0144</phone> <phone type="work">425-555-0145</phone> Dim homePhone = From hp In contact.<phone> _ Where contact.<phone>.@type = "home" _ Select hp Console.WriteLine("Home Phone = {0}", homePhone(0).Value) This code displays the following text: Home Phone = 206-555-0144 The following example shows how to access the child nodes named phone from the collection returned by the contact child axis property of the contacts object. Dim contacts As XElement = _ <contacts> <name>Patrick Hines</name> <phone type="home">206-555-0144</phone> <name>Lance Tucker</name> <phone type="work">425-555-0145</phone> </contacts> Dim homePhone = From contact In contacts.<contact> _ Where contact.<phone>.@type = "home" _ Select contact.<phone> Console.WriteLine("Home Phone = {0}", homePhone(0).Value) The following example declares ns as an XML namespace prefix. It then uses the prefix of the namespace to create an XML literal and access the first child node with the qualified name ns:name. Imports <xmlns: Class TestClass4 Shared Sub TestPrefix() Dim contact = <ns:contact> <ns:name>Patrick Hines</ns:name> </ns:contact> Console.WriteLine(contact.<ns:name>.Value) End Sub End Class Patrick Hines
http://msdn.microsoft.com/en-us/library/bb384806.aspx
crawl-002
refinedweb
446
59.09
In the third part of this article series (see links to previous articles below), we will look at how Strimzi exposes Apache Kafka using Red Hat OpenShift routes. This article will explain how routes work and how they can be used with Apache Kafka. Routes are available only on OpenShift, but if you are a Kubernetes user, don't be sad; a forthcoming article in this series will discuss using Kubernetes Ingress, which is similar to OpenShift routes. Note: Productized and supported versions of the Strimzi and Apache Kafka projects are available as part of the Red Hat AMQ product. Red Hat OpenShift routes Routes are an OpenShift concept for exposing services to the outside of the Red Hat OpenShift platform. Routes handle both data routing as well as DNS resolution. DNS resolution is usually handled using wildcard DNS entries, which allows OpenShift to assign each route its own DNS name based on the wildcard entry. Users don't have to do anything special to handle the DNS records. If you don't own any domains where you can set up the wildcard entries, OpenShift can use services such as nip.io for the wildcard DNS routing. Data routing is done using the HAProxy load balancer, which serves as the router behind the domain names. The main use case of the router is HTTP(S) routing. The routes are able to do path-based routing of HTTP and HTTPS (with TLS termination) traffic. In this mode, the HTTP requests will be routed to different services based on the request path. However, because the Apache Kafka protocol is not based on HTTP, the HTTP features are not very useful for Strimzi and Kafka brokers. Luckily, the routes can be also used for TLS passthrough. In this mode, it uses TLS Server Name Indication (SNI) to determine the service to which the traffic should be routed and passes the TLS connection to the service (and eventually to the pod backing the service) without decoding it. This mode is what Strimzi uses to expose Kafka. If you want to learn more about OpenShift routes, check the OpenShift documentation. Exposing Kafka using OpenShift routes Exposing Kafka using OpenShift routes is probably the easiest of all the available listener types. All you need to do is to configure it in the Kafka custom resource. apiVersion: kafka.strimzi.io/v1beta1 kind: Kafka metadata: name: my-cluster spec: kafka: # ... listeners: # ... external: type: route # ... The Strimzi Kafka Operator and OpenShift will take care of the rest. To provide access to the individual brokers, we use the same tricks we used with node ports and which were described in the previous article. We create a dedicated service for each of the brokers, which will be used to address the individual brokers directly. Apart from that, we will also use one service for the bootstrapping of the clients. This service would round-robin between all available Kafka brokers. Unlike when using node ports, these services will be only regular Kubernetes services of the clusterIP type. The Strimzi Kafka operator will also create a Route resource for each of these services, which will expose them using the HAProxy router. The DNS addresses assigned to these routes will be used by Strimzi to configure the advertised addresses in the different Kafka brokers. Kafka clients will connect to the bootstrap route, which will route them through the bootstrap service to one of the brokers. From this broker, clients will get the metadata that will contain the DNS names of the per-broker routes. The Kafka clients will use these addresses to connect to the routes dedicated to the specific broker, and the router will again route it through the corresponding service to the right pod. As explained in the previous section, the routers main use case is routing of HTTP(S) traffic. Therefore, it is always listening on ports 80 and 443. Because Strimzi is using the TLS passthrough functionality, the following will be true: - The port will always be 443 as the port used for HTTPS. - The traffic will always use TLS encryption. Getting the address to connect to with your client is easy. As mentioned previously, the port will always be 443. This can cause problems when users try to connect to port 9094 instead of 443. But, 443 is always the correct port number with OpenShift routes. You can find the host in the status of the Route resource (replace my-clusterwith the name of your cluster): oc get routes my-cluster-kafka-bootstrap -o=jsonpath='{.status.ingress[0].host}{"\n"}' By default, the DNS name of the route will be based on the name of the service it points to and on the name of the OpenShift project. For example, for my Kafka cluster named my-cluster running in project named myproject, the default DNS name will be my-cluster-kafka-bootstrap-myproject.<router-domain>. Because the traffic will always use TLS, you must always configure TLS in your Kafka clients. This includes getting the TLS certificate from the broker and configuring it in the client. You can use following commands to get the CA certificate used by the Kafka brokers and import it into Java keystore file, which can be used with Java applications (replace my-cluster with the name of your cluster): oc extract secret/my-cluster-cluster-ca-cert --keys=ca.crt --to=- > ca.crt keytool -import -trustcacerts -alias root -file ca.crt -keystore truststore.jks -storepass password -noprompt With the certificate and address, you can connect to the Kafka cluster. The following example uses the kafka-console-producer.sh utility, which is part of Apache Kafka: bin/kafka-console-producer.sh --broker-list :443 --producer-property security.protocol=SSL --producer-property ssl.truststore.password=password --producer-property ssl.truststore.location=./truststore.jks --topic For more details, see the Strimzi documentation. Customizations As explained in the previous section, by default, the routes get automatically assigned DNS names based on the name of your cluster and namespace. However, you can customize this and specify your own DNS names: # ... listeners: external: type: route authentication: type: tls overrides: bootstrap: host: bootstrap.myrouter.com brokers: - broker: 0 host: broker-0.myrouter.com - broker: 1 host: broker-1.myrouter.com - broker: 2 host: broker-2.myrouter.com # ... The customized names still need to match the DNS configuration of the OpenShift router, but you can give them a friendlier name. The custom DNS names (as well as the names automatically assigned to the routes) will, of course, be added to the TLS certificates and your Kafka clients can use TLS hostname verification. Pros and cons Routes are only available on Red Hat OpenShift. So, if you are using Kubernetes, this is clearly a deal-breaking disadvantage. Another potential disadvantage is that routes always use TLS encryption. You will always have to deal with the TLS certificates and encryption in your Kafka clients and applications. You will also need to carefully consider performance. The OpenShift HAProxy router will act as a middleman between your Kafka clients and brokers. This approach can add latency and can also become a performance bottleneck. Applications using Kafka often generate a lot of traffic—hundreds or even thousands of megabytes per second. Keep this in mind and make sure that the Kafka traffic will still leave some capacity for other applications using the router. Luckily, the OpenShift router is scalable and highly configurable so you can fine-tune its performance and, if needed, even set up a separate instance of the router for the Kafka routes. The main advantage of using Red Hat OpenShift routes is that they are so easy to get working. Unlike the node ports discussed in the previous article, which are often tricky to configure and require a deeper knowledge of Kubernetes and the infrastructure, OpenShift routes work very reliably out of the box on any OpenShift installation.
https://developers.redhat.com/blog/2019/06/10/accessing-apache-kafka-in-strimzi-part-3-red-hat-openshift-routes?p=601277
CC-MAIN-2021-39
refinedweb
1,314
63.8
Contents tagged with WP7 Broken Windows Phone Marketplace! Farseer tutorial for the absolute beginners This post is inspired (and somewhat a direct copy) of a couple of posts Emanuele Feronato wrote back in 2009 about Box2D (his tutorial was ActionScript 3 based for Box2D, this is C# XNA for the Farseer Physics Engine). Here’s what we’re building: What is Farseer The Farseer Physics Engine is a collision detection system with realistic physics responses to help you easily create simple hobby games or complex simulation systems. Farseer was built as a .NET version of Box2D (based on the Box2D.XNA port of Box2D). While the constructs and syntax has changed over the years, the principles remain the same. This tutorial will walk you through exactly what Emanuele create for Flash but we’ll be doing it using C#, XNA and the Windows Phone platform. The first step is to download the library from its home on CodePlex. If you have NuGet installed, you can install the library itself using the NuGet package that but we’ll also be using some code from the Samples source that can only be obtained by downloading the library. Once you download and unpacked the zip file into a folder and open the solution, this is what you will get: The Samples XNA WP7 project (and content) have all the demos for Farseer. There’s a wealth of info here and great examples to look at to learn. The Farseer Physics XNA WP7 project contains the core libraries that do all the work. DebugView XNA contains an XNA-ready class to let you view debug data and information in the game draw loop (which you can copy into your project or build the source and reference the assembly). The downloaded version has to be compiled as it’s only available in source format so you can do that now if you want (open the solution file and rebuild everything). If you’re using the NuGet package you can just install that. We only need the core library and we’ll be copying in some code from the samples later. Your first Farseer experiment Start Visual Studio and create a new project using the Windows Phone template can call it whatever you want. It’s time to edit Game1.cs1. The Big Dummies Guide for Windows Phone Developer Resources Windows Phone apps are growing in popularity as does the 50,00060! Prairie Dev Con West - Sessions Announced and Registration Open! I’m thrilled to announce that the Prairie Dev Con West folks have posted sessions and speakers on their! MediaWiki, WP7 and JSON Together Again For The First Time In another project that I’m working on (like I don’t have enough of them) I stumbled across the MediaWiki API. MediaWiki is the workhorse wiki software that powers such sites as Wikipedia. What you may (or may not) know is that the MediaWiki API is pretty slick, offering access to any content on a MediaWiki powered site. In this post we’ll walk through building a Windows Phone 7 app to browse the content on Wikipedia using JSON and the MediaWiki API. First create a new Windows Phone 7 app. Any app template will do but I find the Windows Phone Databound Application template to be useful as it creates a few useful things out of the box for you like a ViewModel class and adds it to the app. It’s nothing special that you can’t do yourself, but does save a little time. Next you’ll want to be able to read the data coming from Wikipedia. We’ll be using the MediaWiki API (no download required) which can serve data up in XML format but we’ll opt for using JSON. Rather than using the native JSON methods in .NET let’s use the Json.NET library, a wicked cool library by James Newton-King that makes serializing and deserializing JSON into .NET objects a breeze. Unfortunately at the time of this writing, the Nuget package for Json.NET doesn’t install properly on Windows Phone 7 projects so you have to download the file, unzip it, and add the references manually. Hopefully someone updates the Nuget package so this 5 minute task can be avoided in the future. The default app has a listbox with items to display that links to a detail page. For this sample, we’ll fill the list with categories and drill into the category to display the pages associated with it. The first task is to retrieve the categories from Wikipedia. The full documentation for the API is online here. To get the categories it’s a straight forward API call that looks like this: The first part is where the API page is located on Wikipedia (it may not be in this location on other WikiMedia sites so check with the site owner). Then we specify an action, in this case a query. We ask for a list of items specifying “allcategories” and we want it in JSON format. Here’s the output: { query: { allcategories: [ { *: "!" } { *: "!!! EPs" } { *: "!!! albumns" } { *: "!!! albums" } { *: "!!! songs" } { *: "!!AFRICA!!" } { *: "!910s science fiction novels" } { *: "!928 births" } { *: "!936 births" } { *: "!946 poems" } ] } query-continue: { allcategories: { acfrom: "!949 births" } } } MediaWiki queries come back in two groups. First is the query results and then a section titled “query-continue” that contains the next value that you can use to start from on a subsequent query. You may need to do several queries if you want to get everything. MediaWiki supports up to 500 items per call but very often (especially with the size of Wikipedia) that number can be in the thousands. It’s up to you how to do the queries (all at once or as you go) but think of it as picking up where you left off. The default size is 10 which is fine for now. However the results are not very pretty and somewhat bizarre list of categories. First we’ll add some more data to the category with information about it. This is done by adding more parameters to the API call: All we’ve done is add “&acprop=size&acprefix=A” to the call. This brings in number pages, files, sub categories into the mix (the size property is the sum of all those). We’ll also get categories that start with the letter “A” to avoid the categories named “!”. Here’s the results: { query: { allcategories: [ { *: "A" size: 0 pages: 0 files: 0 subcats: 0 } { *: "A&E Network shows" size: 0 pages: 0 files: 0 subcats: 0 } { *: "A&E Shows" size: 0 pages: 0 files: 0 subcats: 0 } { *: "A&E Television Network shows" size: 0 pages: 0 files: 0 subcats: 0 } { *: "A&E Television Networks" size: 17 pages: 14 files: 0 subcats: 3 } { *: "A&E Television network shows" size: 0 pages: 0 files: 0 subcats: 0 } { *: "A&E network shows" size: 0 pages: 0 files: 0 subcats: 0 } { *: "A&E shows" size: 66 pages: 66 files: 0 subcats: 0 } { *: "A&E television network shows" size: 0 pages: 0 files: 0 subcats: 0 } { *: "A&M Records" size: 0 pages: 0 files: 0 subcats: 0 } ] } query-continue: { allcategories: { acfrom: "A&M Records EPs" } } } That looks better. Unfortunately there’s no way to include additional filters like “don’t include items with size = 0” so you’re going to have to make multiple calls and the filtering in your app (LINQ is great for this) but this is good enough to get started. Json.NET can deserialize these results into an object graph but you need to create the classes for it. One way to do this is to use the JSON C# Class Generator which is a pretty handy tool if you’re starting with JSON as your format and don’t have anything. It doesn’t know anything about the Json.NET library so it uses native C# calls for the structure and helpers and but will give you something to start from. We’ll just build our classes manually as there are only a few we need. Here’s the first cut (based on the JSON data above): public class MediaWiki { public Query Query { get; set; } public QueryContinue QueryContinue { get; set; } } public class Query { public Allcategory[] Allcategories { get; set; } } public class Allcategory { public int Size { get; set; } public int Pages { get; set; } public int Files { get; set; } public int Subcats { get; set; } } public class QueryContinue { public Allcategories Allcategories { get; set; } } public class Allcategories { public string Acfrom { get; set; } } The class and property names here are not the most intuitive but we’ll fix that. First let’s make the call to the API to get our JSON then deserialize it into this object graph. Replace the LoadData method in the MainViewModel with this code: public void LoadData() { var address = @""; var webclient = new WebClient(); webclient.DownloadStringCompleted += OnDownloadStringCompleted; webclient.DownloadStringAsync(new Uri(address)); } This kicks off the download and sets up the callback to invoke when the download is complete (I also added “&aclimit=500” to the end of the query to get more than the default 10 results). When the string is downloaded we call this: foreach (var category in json.Query.Allcategories.Where(category => category.Size > 0)) { Items.Add( new ItemViewModel { LineOne = "Pages: " + category.Pages, LineTwo = "Subcats: " + category.Size, }); } This takes the result of the download and calls the JsonConvert method DeserializeObject. This is a generic method that we pass our MediaWiki class from above to. Then just loop over the Allcategories array to pluck out each category and create our ItemViewModel items manually. We use LINQ in the loop to filter out any categories with a size of 0. Here's the result on our phone: This isn’t too exciting because frankly we don’t know what the name of each category is. Remember the JSON? { *: "A&E Television Network shows" size: 0 pages: 0 files: 0 subcats: 0 } Hmmm.. how are we going to get that name into a property in our class? The Json.NET library matches up names of attributes in the markup with the name of a property in your class. We can’t create a property called “*” as that’s not valid in C#. The answer is to use the JsonPropertyAttribute on our class and introduce a new property called Title. Here’s our updated Allcategory class with the markup: public class Allcategory { [JsonProperty("*")] public string Title { get; set; } public int Size { get; set; } public int Pages { get; set; } public int Files { get; set; } public int Subcats { get; set; } } This tells Json.NET that when it comes across a value with the markup “*” to deserialize it into the Title property. Now we can update our LoadData method to use the title instead: private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { var json = JsonConvert.DeserializeObject<MediaWiki>(e.Result); foreach (var category in json.Query.Allcategories.Where(category => category.Size > 0)) { Items.Add( new ItemViewModel { LineOne = category.Title, LineTwo = string.Format("Pages: {0} Subcats: {1}", category.Pages, category.Subcats), }); } IsDataLoaded = true; } Which now looks like this on the phone: That’s a little better. With the [JsonProperty] attribute we can also specify the name of the property in the JSON markup so that we’re not tied to that name when specifying the name in our C# class. This allows us to make our C# class a little more readable. Here’s an couple of examples: public class Query { [JsonProperty("allcategories")] public Allcategory[] Categories { get; set; } } public class Allcategory { [JsonProperty("*")] public string Title { get; set; } public int Size { get; set; } public int Pages { get; set; } public int Files { get; set; } [JsonProperty("subcats")] public int Categories { get; set; } } The JsonProperty will match whatever markup MediaWiki (or whomever is providing your JSON feed) and we can use a more friendlier name in our code (P.S. the class names can be whatever you want, it’s the properties that are important). The default app already has the function to display the DetailsPage when you tap on an item in the list. It passes the index of the array of ItemViewModel items to the page which retrieves it from the Items property of the ViewModel stored in the App class and sets up the title of the DetailsPage to the LineOne property of the ViewModel. This property is really the title of the category and the value we can use to get more information from the MediaWiki API. We’ll use the “categorymembers” action to get all pages in a given category. Here’s the url we’re going to use: We’re going after all pages in the “Zombies” category and want to include the type of page, the id, and the title. Here’s the JSON from this call: { query: { categorymembers: [ { pageid: 8375 ns: 0 title: "Draugr" type: "page" } { pageid: 27279250 ns: 0 title: "Felicia Felix-Mentor" type: "page" } { pageid: 143895 ns: 0 title: "Jiang Shi" type: "page" } { pageid: 1776116 ns: 0 title: "Clairvius Narcisse" type: "page" } { pageid: 781891 ns: 0 title: "Philosophical zombie" type: "page" } { pageid: 7568400 ns: 0 title: "Zombie Squad" type: "page" } { pageid: 5048737 ns: 0 title: "Zombie walk" type: "page" } { pageid: 22328159 ns: 0 title: "Zombeatles" type: "page" } { pageid: 34509 ns: 0 title: "Zombie" type: "page" } { pageid: 6569013 ns: 14 title: "Category:Hoodoo" type: "subcat" } ] } query-continue: { categorymembers: { cmcontinue: "subcat|31450932|ZOMBIES AND REVENANTS IN POPULAR CULTURE" } } } Note that we have a new attribute called “categorymembers” instead of “allcatgories” (but the top level attribute is still “query”). We’ll definitely need a class to handle the categorymembers array returned by the call but should it go into the existing Query class? Technically you could do it. Json will deserialize it for you and if it can match up the attribute with the C# property name (or find the property decorated with the JsonProperty attribute) it will and the other items will just be null. It’s up to you if you want to build a special query class for each type of query. I suggest you do (you can even create a generic MediaWikiQuery<T> class that takes in things like a CategoryMember class or AllCategory class) to keep things clean. Otherwise you’re violating a few SOLID principles and laying the foundation for a God class. For demo purposes I’ll just add the CategoryMember class to our Query class but like I said, it’s a demo only. Here’s the new CategoryMember class and the modified Query class: public class CategoryMember { public int PageId { get; set; } public string Title { get; set; } public string Type { get; set; } } public class Query { [JsonProperty("allcategories")] public Allcategory[] Categories { get; set; } [JsonProperty("categorymembers")] public CategoryMember[] Pages { get; set; } } Now when the DetailsPage loads we’ll figure out the index of the item based on the parameter passed in and call a new method on our MainViewModel to load the pages. protected override void OnNavigatedTo(NavigationEventArgs e) { string selectedIndex = ""; if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex)) { int index = int.Parse(selectedIndex); App.ViewModel.LoadPages(index); DataContext = App.ViewModel.SelectedCategory; } } Note that the LoadPages method is another call to the service so we’ll probably want to create a handler in our view to handle displaying a “Loading” indicator and respond to something like a property changed event on our ViewModel to remove it. Here we’ll just the binding in the ViewModel and the page will update (eventually) with the list of pages. It’s not the UX you want to build but this post is already getting long and I’m sure you’re pretty tired reading it. We also set the DataContext of our DetailsPage to a new property we added in the ViewModel call SelectedCategory. This way MainViewModel hangs onto whatever category the user selected so we can reference it (and it’s properties) later. To load the pages first we’ll call out to Wikipedia to fetch them based on our category. We could pass in the title we want but here we’ll pass the index to the title and fetch it in the method: public void LoadPages(int index) { SelectedCategory = Items[index]; var address = string.Format( ":{0}&cmprop=type|ids|title", SelectedCategory.LineOne); var webclient = new WebClient(); webclient.DownloadStringCompleted += OnDownloadPagesCompleted; webclient.DownloadStringAsync(new Uri(address)); } This sets up SelectedCategory based on the index we passed in and crafts the url to the MediaWiki API to fetch all pages for whatever the category is (based on the title). Now we need to process the JSON when the download of the page list completes. For this we’re going to need a new ViewModel. Here’s a quick and dirty one that just uses the title and pageid property: public class PageViewModel : INotifyPropertyChanged { private int _pageid; private string _title; public int PageId { get { return _pageid; } set { if (value == _pageid) return; _pageid = value; NotifyPropertyChanged("PageId"); } } public string Title { get { return _title; } set { if (value == _title) return; _title = value; NotifyPropertyChanged("Title"); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { var handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } We’ll display the Title to the user but the pageid needs to be stored because later we’ll want to retrieve all the details about a single page. In the ItemViewModel (our category) we have an ObservableCollection of PageViewModel objects called Pages. This mimics the Items property in the MainViewModel. Here’s the declaration: public ObservableCollection<PageViewModel> Pages { get; private set; } And here’s the constructor creating them: public ItemViewModel() { Pages = new ObservableCollection<PageViewModel>(); } Back in the MainViewModel we deserialize the JSON and add the PageViewModel objects to our selected category: private void OnDownloadPagesCompleted(object sender, DownloadStringCompletedEventArgs e) { var json = JsonConvert.DeserializeObject<MediaWiki>(e.Result); foreach (var page in json.Query.Pages.Where(page => page.Type.Equals("page"))) { SelectedCategory.Pages.Add( new PageViewModel { PageId = page.PageId, Title = page.Title }); } } Just like when we loaded the categories here we only select items where the page.Type is a “page”. In our Zombie example, one of the items is a “subcat”. In a real app, we would have something to handle constructing that and creating some kind of link to another category (since everything is a category, we could reuse a lot of this code for that). The last part is changing the DetailsPage.xaml to display a list of pages. Here’s the LayoutRoot grid updated: <Grid x: <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title--> <StackPanel x: <TextBlock x: <TextBlock x: </StackPanel> <!--ContentPanel contains details text. Place additional content here--> <Grid x: <TextBlock x: <ListBox x: <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="0,0,0,17" Width="432"> <TextBlock Text="{Binding Title}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Grid> The result is a details page that shows our category as the title and a listbox full of pages. At this point you can add an additional handler to the listbox to drill down into the page itself. From there you can pluck out a list of images, links to other pages, and even the wiki content and sections. Check the MediaWiki API for more info on getting down into all of this stuff. It’s very cool being able to poke into MediaWiki and beats the hell out of screen scraping! A Call to Action! This just gives you an intro to accessing a resource like Wikipedia using the public API and deserializing results via JSON into a set of classes you can use to bind to a Windows Phone 7 app. I’m going to leave the rest up to you. A few ideas to think about if you were to build on this example: - Calling directly from the ViewModel isn’t a production practice, it was a demo only. You’ll probably want to create a MediaWikiService and inject it into your ViewModel - The call can take a few seconds so you’lll need to handle this in your service and update the UI accordingly - Drill down into a single page, pluck out the images and create a visual MediaWilki browser experience or something. - You can even post content *to* a MediaWiki wiki (after you login with a username/pass that has rights to) so not only can it be a browser experience but it can be an editing experience too. - This is just one example to use the MediaWiki API by fetching categories and page content but there are a lot of other type of queries you can make like getting a list of recent changes, comment history, or even random pages. Use your imagination and above all, have fun. If you get stuck feel free to leave questions in the comments section and I’ll do my best to answer them.. WP7 Mobile Friendly WordPress Site If you're running a WordPress site you owe it to yourself to check out WPTouch. WPTouch is a fabulous plug-in for WordPress that instantly transforms your site into a navigatable mobile friendly one. Browse to a WordPress site and it's pretty clean. Here's my site using the default Twenty Ten theme in my Windows Phone 7 IE browser: That's pretty good. In fact, comparing it to the site in the browser it's identical. However navigating tiny links on the site or menus can be tedius with fat fingers. Sure, mobile devices offer pinch zoom and features like that but do you really want to be constantly zooming in, panning around, and zooming back out to read content? Andrew Woodward over at 21apps turned me onto a WordPress plugin called WPTouch this weekend so I thought I would give it a go. I have a few sites I run on WordPress and I wanted to see what it could do. Wow. What a transformation. Once you install and activate the WPTouch plugin (all from the comfort of your WordPress dashboard) your site will magically be transformed into this: My WordPress site looks like an iPhone app! No software to install on the client, this is all magically done behind the scenes by detecting the browser and serving up an alternate theme via the plug-in. To get it working for WP7 I had to add a quick modification to the settings. Once you're installed WPTouch and activated it (just add it through the built-in search in the WordPress dashboard, it's the first one to come up) then go to Settings > WPTouch. Scroll down to Advanced Options. There you'll see a list of currently enabled user-agents so the list is pretty full; Android, BlackBerry, iPhone, etc. What's missing is the user agent to detect the Windows Phone 7. Just add "iemobile" which is the lowest common denominator to the Custom user-agents box and save the settings. Visit your site with your WP7 phone and voila, everything will be right as rain. Don't worry about navigation as it's covered by a clever menu that's created by the plugin so you'll have access to tags, categories and any part of the site: The rest of the site looks awesome and your browser users will still continue to see the site with whatever theme you have applied. It's not perfect on WP7 as the theme is designed for iPhones but IMHO it's a far better experience than trying to tap on tiny links in a browser. Everything is big and bold, the way it should be on a mobile device. Finally, if you do decide to add the plugin (it's free, although there is a Pro version too) then show your WPTouch pride to your desktop browser users with a decal. The guys ask you link back to the site if you do. You grab whatever size and format image you want from here. Hope that helps and here's to a better mobile experience from your WordPress site! P.S. The "boys" and I were discussing something like this for SharePoint. Yeah, it would be totally awesome if we had something like this which would serve up say a Metro view for WP7 phones. Not sure if it'll become a reality but food for thought.
http://weblogs.asp.net/bsimser/Tags/WP7
CC-MAIN-2015-35
refinedweb
4,035
59.84
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. Count Rows of one2many field - numbering positions I try to implement numbering positions in invoices. I got a field "position" in the one2many field and it looks like this <field name="invoice_line" widget="one2many_list" context="{'type': type,'order_id':active_id}"> <field name="position"/> (..) My class class account_invoice_line(osv.osv): _inherit = 'account.invoice.line' _columns = { 'position': fields.char('Position'), } def position_number(self, cr, uid, context=None): return ACTUAL ROW NUMBER _defaults = { 'position': lambda obj, cr, uid, context: obj.position_number(cr, uid, context), } account_invoice_line() I have no Idea how to get the actual row number or how to count the rows. I found this, but it's not working :-/ def _default_sequence(self, cr, uid, context=None): if context is None: context = {} max_sequence = 0 if context.get('order_id'): sale_order_line_ids = self.search(cr, uid, [('order_id', '=', context['order_id'])]) if sale_order_line_ids: max_sequence = max([line['position'] for line in self.read(cr, uid, sale_order_line_ids, ['position'])]) return max_sequence + 1 _defaults = { 'sequence': lambda obj, cr, uid, context: obj._default_sequence(cr, uid, context), } Can anybody help me? I have do it using on_change attribute of order_line. I have made changes in xml like this. <field name="order_line" on_change="update_seq(order_line)"> and the python side in sale.order added following method. def update_seq(self, cr, uid, ids, order_line, context=None): new_order_line = [] counter = 1 for line in order_line: if line[0] in [1,4]: line[0] = 1 if type(line[2]) == type({}): line[2].update({'seq':counter}) else: line[2] = {'seq':counter} counter = counter + 1 new_order_line.append(line) return {'value': {'order_line': new_order_line} } Just try it. and post here if any problem occurs. Okay, I tried it, but I have the problem, that the onchange function won't be executed. So I have a field: <field name="position" on_change="position_number(cr, uid, context)"/> and a function "def position_number(self, cr, uid, context=None): print("bla")" but the function will not be executed. Why? Because, from the XML part you can not pass cr, uid and context. These are the default parameter that OpenERP core will be pass automatically. That's is the only reason the method is not going to!
https://www.odoo.com/forum/help-1/question/count-rows-of-one2many-field-numbering-positions-50603
CC-MAIN-2016-44
refinedweb
378
59.4
Packages….!!!Packages are those class which contains methods without the main method in them.Packages are mainly used to reuse the classes which are already created/used in other program.We can define many number of classes in the same package.Packages are mainly divided into two types.They are 1.Built in packages 2.User defined Packages. The main use of Packages is: - Classses contain in packages of other programme can easily be used. - In packages,classes can be unique,compare with classes in other packages. - Packages provide the way to hide classes thus preventing other program(or) packages from accessing classes that are meant for internal use only. Built in Packages:Built Packages are provided for the programme in-order to reduce the burden.Some of the frequently used built in packages are: - lang - util - io - awt - net - applet These built in packages are placed in the package “java”.In order to use these packages/classes present in the package we need to import them in the current program.The syntax for importing packages is: import java.util.* The above statement tells the compiler that you need to import all the classes present in the “util” package,which in turn present in the “java” package.The asterisk symbol tells the compiler to import all the classes in present in the util package.If you want to import specific class then we need to mention the name of the class instead of the asterisk.For eg: import java.util.Scanner Built in packages: 1.java.lang:language supports classes.These are classes that java compiler itself uses and therefore automatically imported.They include classes for primitive types,stirngs,maths,threads and exceptions. 2.java.util:language utility classes such as vecotrs,hash tables,random numbers,date etc. 3.java.io:input/output support classes.They provide the facility for input/output of data. 4.java.awt:set of classes for implementing graphical user interface.They include classes for windows,buttons,lists 5.java.net:Classes for networking.They include classes for communicating with local computers as well as with internal servers. Today we shall create a user defined package.For this we need to create a folder with your desired name. package name_of_folder_given public class A { public void display() { System.ou.println("Hello world"); } } Now we have created a package.We shall now reuse the above defined class in other program. import name_of_the_folder_given.*; class packagedemo { public static void main(String arg[]) { A ob = new A(); ob.display(); } } There fore we have reused the a class defined in other program.Before executing the second program we need to compile the package i.e. javac a.java Output: you can download the code: 1.download package 2.download program Pingback: Programming with Packages…!!! | letusprogram....!!!
https://letusprogram.com/2013/10/10/packages-in-java-with-examples/
CC-MAIN-2021-17
refinedweb
463
52.97
Runtime Arguments In Eclipse Java A variable which is to be substituted in the configuration value is surrounded by '$' characters. Information such as user scoped preferences and login information may be found in the user location. Specifying the Java virtual machine Here is a typical Eclipse command line: eclipse -vm c:\jdk7u45\jre\bin\javaw Tip: It's generally a good idea to explicitly specify which Java VM to use when running The default value is "true". navigate here The optional classpath entries (a comma separated list) are added to the runtime classpath of each plug-in. Georges This the best explanation i've found on the web. If you need to launch Eclipse from the command line, you can use the symbolic link "eclipse" in the top-level eclipse folder. About Press Copyright Creators Advertise Developers +YouTube Terms Privacy Policy & Safety Send feedback Test new features Loading... How To Pass Command Line Arguments In Java With Example eclipse.exe looks for eclipse.ini, product.exe looks for product.ini) --launcher.suppressErrors (Executable) If specified the executable will not display any error or message dialogs. Configuration (-configuration) {osgi.configuration.area} [@none, @noDefault, @user.home, @user.dir, filepath, url] Configuration locations contain files which identify and manage the (sub)set of an install to run. The configuration determines what plug-ins will run as well as various other system settings. A default application is identified by the eclipse.product or the eclipse.application options. All runtime related data structures and caches are refreshed. See bug 191254 for details. How To Take Command Line Arguments In Java boot - the boot classloader. I can run this file from command prompt by : javac filename.java java filename -30 But, it takes more steps, and I must cd to this folder. (to long for each Eclipse Command Line Arguments Txt File osgi.bundlefile.limit specifies a limit on the number of jar files the framework will keep open. Install (-install) {osgi.install.area} [@user.home, @user.dir, filepath, url] An install location is where Eclipse itself is installed. This option can be used to work around certain VM bugs which can cause deadlock. WARNING - enables logging of ERROR and WARNING messages. Run Eclipse From Command Line Ubuntu Valid arguments are "on=[y|n];textDir=[ltr|rtl|auto]",. Dinesh Varyani 1,669 views 2:38 Java w/ Eclipse 03 - Hello World using Java command line - Duration: 14:15. In all cases, the string "@user.home" is simply replaced with the value of the Java "user.home" System property. Eclipse Command Line Arguments Txt File HowTo 884 views 4:42 How to execute java program using Command prompt - Duration: 7:09. Durga Software Solutions 23,048 views 11:31 how to pass command line parameter in eclipse - Duration: 4:13. How To Pass Command Line Arguments In Java With Example don't know what you're doing wrong, maybe you're not re-running it, running a different configuration from the one you're editing or something weird? Eclipse Run Configuration Vm Arguments Working... Locations The Eclipse runtime defines a number of locations which give plug-in developers context for reading/storing data and Eclipse users a control over the scope of data sharing and visibility. check over here This argument is typically not needed. In all cases, the string "@user.dir" is simply replaced with the value of the Java "user.dir" System property. By default the framework properties are backed by the System properties (e.g. Eclipse Command Line Workspace The default value is false. The valid types are the following: app - the application classloader. asked 4 years ago viewed 39785 times active 1 year ago Blog Developers, webmasters, and ninjas: what's in a job title? his comment is here The configuration file determines the location of the Eclipse platform, the set of available plug-ins, and the primary feature. Advertisement Autoplay When autoplay is enabled, a suggested video will automatically play next. Java Command Line Arguments Parser osgi.instance.area {-data} the instance data location for this session. The reason for this behavior is that every UI application on Mac can open multiple documents, so typically there is no need to open a program twice. A new method Bundle.start(options) has been added to allow lazy activated bundles to be activated according to their lazy activation policy. - If this property is not set then all available TrustEngine services are used at runtime. - eclipse.trace.backup.max NEW the max number of backup trace files to allow. - The system property "org.osgi.framework.bootdelegation" will be used to determine which packages should be delegated to boot. - Rating is available when the video has been rented. - If set to "false" only the default application will have an application descriptor service registered. - The value given here overrides any application defined by the product (see eclipse.product) being run eclipse.application.launchDefault Controls launching the default application automatically once the platform is running. - Add to Want to watch this again later? Any user/plug-in defined configuration data is not purged. osgi.checkConfiguration if set to "true" then timestamps are check in the configuration cache to ensure that the cache is up to date with respect to the contents of the installed bundles. This mode is very fast but may result in unresolved bundles because of class space inconsistencies. How To Pass Arguments To Main Method In Java eclipse.exitOnError if set to "true" then the platform will exit if an unhandled error occurs. McProgramming 8,462 views 6:48 what is the purpose of command line arguments in java - Duration: 11:31. Thanks all. sed or awk: remove string which starts with number and ends with rpm Frozen Jack: Actor or Prop? weblink This includes bundles which specify a lazy activation policy. In 3.2, an optional workspace name argument was added that displays the provided name in the window title bar instead of the location of the workspace. 2.0 -vm vmPath The location Linked -3 how could I pass an argument to my java program when I run it in eclipse 3 java.lang.ArrayIndexOutOfBoundsException: 0 0 Client/Socket in java - error on client side 0 Typically the user location is based on the value of the Java user.home system property but this can be overridden. eclipse.security specifies that a security policy and manager should be configured when the framework is launched. The default value is "false". MargretPosch 12,340 views 8:22 current affairs telugu may 2016 mcqs part 1 - Duration: 6:37. See osgi.framework.activeThreadType. The workspace is the directory where your work will be stored. JAVA62 64,410 views 15:37 Learn Programming in Java - Lesson 17: File Input/Output - Duration: 28:42. The default is 30000 ms (30 seconds). How can I discover the Python version in QGIS? osgi.filepermissions.command specifies an optional OS specific command to set file permissions on extracted native code. This is helpful for disabling hook configurators that are specified in hook configurator properties files. According to the OSGi R4.1 specification, if a bundle with a lazy activation policy fails to start then class loads must still succeed. eclipse.product {-product} the identifier of the product being run. package commandline; public class AdditionOfTwoNumbers { public static void main(String[] args) { int a, b; a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); int sum = a + b; System.out.println("The Sum is: " osgi.user.area.default the default location of the user area. That's excellent. –Duncan Aug 31 '12 at 20:42 add a comment| up vote 14 down vote Right click the class. For example, the Resources plug-in uses this as the default location for projects (aka the workspace). osgi.arch {-arch} the processor architecture value. This security manager is required to fully support the OSGi Conditional Permission Admin specification. A zero value indicates no max trace size. Are the Player's Basic Rules the same as the Player's Handbook when it comes to combat?
http://dailyerp.net/command-line/runtime-arguments-in-eclipse-java.html
CC-MAIN-2017-39
refinedweb
1,339
50.33
On-demand Media tag:typepad.com,2003:weblog-139070 2011-06-30T02:47:16+01:00 Nothing personal TypePad This is an XML content feed. It is intended to be viewed in a newsreader or syndicated to another site, subject to copyright and fair use. Studying the link economy tag:typepad.com,2003:post-6a00d8341d599853ef0154335bf235970c 2011-06-30T02:47:16+01:00 2011-07-01T16:49:50+01:00 Jeff Jarvis is launching "an ambitious research project" to study what he has elsewhere called the link economy. He has penned an opening set of questions and hypotheses and issued a call for feedback. I think this is spot-on. The... Nico Flores <div xmlns=""><p>Jeff Jarvis is launching "an ambitious research project" to study what he has elsewhere called the link economy. He has <a href="">penned</a> an opening set of questions and hypotheses and issued a <a href="">call</a> for feedback.</p> <p>I think this is spot-on. The issues Jeff is exploring have interested me for a long time (see e.g. <a href="">this</a> and <a href="">this</a> and <a href="">this</a>), and I think understanding them will be increasingly important for media strategy. So here are some contributing thoughts.</p> <p style="text-align: justify;">Jeff posits:</p> <p style="margin-left: 36pt;">. […] </em></p> <p style="margin-left: 36pt;"><em>What is that value? Well, of course, that is impossible to calculate precisely; there are too many variables. </em></p> <p.</p> <p. </p> <p>With that, the beneficiaries of our click-through are:</p> <ul> <li>The reader, who gets value from being sent to the right content in the right context. The value is the amount that the reader would be willing to pay if there were no alternatives. </li> <li>The publisher, who gets to advertise to the reader. </li> <li>The aggregator, who also gets to advertise. </li> </ul> <p>Sum up the three things up and you have the value of this user experience – probably in the order of a cent or two.</p> <p>New business models can use three strategies:</p> <ul> <li><strong>Growing the pie </strong>by making the<strong> </strong>link-following experience more valuable to one or more of its three beneficiaries <strong> </strong></li> <li><strong>Re-slicing the pie</strong> so that the split in the value received by the parties changes </li> <li><strong>Capturing</strong> some of the value that today readers get to enjoy, by making them pay (strictly this is a case of re-slicing) </li> </ul> <p>The focus of Jeff's research is new business models involving collaboration between publishers and aggregators. In this, we can expect pure re-slicing strategies to play only a minor part, for two reasons:</p> <ul> <li>Leaving aside some edge cases like Reuters paying Breitbart for traffic (as has been <a href="">rumoured</a>), it's culturally hard to imagine a newspaper paying the Huffington Post or Google News, at least without added incentives. </li> <li>Quality publishers have more page-views than they can monetize at decent CPMs. </li> <li>As to the converse, as I've <a href="">argued</a> elsewhere, most publishers have next to no negotiating power vis-à-vis aggregators. This is because, for a given click-through, aggregators have many publishers to choose from while publishers are in a take-it-or-leave-it situation (economists <a href="" target="_self">call</a> this kind of predicament a "competitive bottleneck", but the theory is dense). </li> </ul> <p>Pie-growing looks more promising. Jeff himself once <a href="">proposed</a> one such strategy: aggregators would give publishers some data about the audience they are sending their way, so that publishers can sell better-paying advertising targeted at them. Publishers would pay aggregators a kick-back and thus the upside would be split between the two.</p> <p.</p> <p.</p> <p>I have a lot of other things to throw in Jeff's soup. Time allowing I may add more in the coming weeks.</p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> Towards the publisher's solution tag:typepad.com,2003:post-6a00d8341d599853ef014e86766e3f970d 2011-03-03T18:21:00+00:00 2011-03-07T13:33:22+00:00 In a widely noted Monday Note post, Frédéric Filloux wonders if the solution to print publishers' new-media woes may be to stop delaying the inevitable and just jump into the abyss: [...] very few publishers of money-losing dailies can elude... Nico Flores <div xmlns=""><p>In a widely noted <em>Monday Note</em> <a href="" target="_self">post</a>, Frédéric Filloux wonders if the solution to print publishers' new-media woes may be to stop delaying the inevitable and just jump into the abyss:</p> <p style="padding-left: 30px;"><em>[...].</em></p> <p>The title of Frédéric's post, "The Publisher's Dilemma", is a reference to <em><a href="" target="_self">The Innovator's Dilemma</a></em>, Clayton Christensen's seminal study of how firms that fail to embrace disruptive change risk being killed by new players who are nimbler and leaner. Frédéric offers some high-level thoughts on what a radical solution might look like here: relying less on advertising, moving towards smaller newsrooms, and abandoning the daily news cycle. But bold as these steps may be, I feel they fall short of the self-cannibalizing poison pill that Christensen might prescribe.</p> <p>For Christensen, old firms that try to "incrementally" change their ways while fundamentally staying the same are almost always doomed to fail. The reasons are many, but two key ones are that:</p> <ul> <li>The new businesses lines usually have lower margins ("digital dimes vs print dollars") which, when push comes to shove, forces old-firm executives to prioritize the old products and clients when assigning resources.</li> <li>Their culture, values, professional networks, salaries, customer and supplier relationships are all undermined by (and thus bound to reject) a new set-up in which their work and products would be "cheapened". Think of some journalists' contempt for aggregators and "content farms", or some publishers' views of "value-destroying" ad networks.</li> </ul> <p>Even if firms adopt all the right technologies and processes, their organizational fabric is strained to the limit. And, if the technology in question (here, the internet) is truly disruptive, the new industries will slowly but surely improve their products until one day they can compete with the old ones - at lower costs and prices. All the money then quickly flows to the new guys, who get even better, and suddenly the old industry is relegated to a high-end niche.</p> <p>So what is to be done? The solution, says Christensen, is to set up your own disruptive start-up - i.e. a new business unit with its own P&L - and let it run with it. Let it undercut the older units' products and cannibalize their income. Let it kill them if need be. "A business unit isn’t designed to evolve. But a company can evolve if it has many business units within it" (<a href="" target="_self">via</a> Lostremote). What remains may be smaller than what you once had, but then the alternative might be nothing at all.</p> <p>Of course, media companies have been experimenting with variants of this since the web's beginnings (Christensen's book was first published in 1997, and it drew on older, less well-known work by others). Many magazines' websites have their own journalists and content and carry only part of their print output. Newspapers used to do something similar (although the trend is now towards integration of newsrooms). And of course <em>The Daily</em> is a bold experiment, without an umbrella brand or subsidised content from a print mothership. </p> <p>But I think there's room for far more radical experimentation along Christensen's lines. If the prescription is to act like a real startup, then some of the current attitudes feel misplaced. For example:</p> <ul> <li><strong>Advertising:</strong> Many publishers refuse to sell remnant inventory to "value-destroying" ad networks, hoping that their rivals will do the same and keep prices from eroding. But such gentlemanly, almost cartel-like conduct would be unthinkable for a starving startup alone in the world.</li> <li><strong>Multi-platform:</strong> Almost all publishers and many TV companies have tried to re-invent themselves as platform-agnostic content (or "journalism") operations. But this means treating the internet as just a change in <em>how</em> you do (or distribute) what you do, and not as demanding a deeper transformation. From Christensen's point of view this might be an ostrich-and-sand situation.</li> <li><strong>Aggregation:</strong> Print publishers' websites almost never promote their rivals' content alongside their own. Of course this is sensibly motivated by profit - you want your own content to generate ad impressions. Yet link-based aggregation is central to many of today's successful web-only journalistic startups. Could the old players be missing a trick here?</li> </ul> <p>The aggregation point may be key. Sending traffic to your rivals' content when your print colleagues have already written articles on the same subjects sounds absurd (the content costs are already sunk). Yet if you are serious about acting like a startup, perhaps you should be less loyal top your print colleagues and care less about their sunk costs. This is not to say that you should be completely separate; surely there should be an advantage from shared ownership. The questions is what is the right level of alignment, and how to implement it.</p> <p>On that, just a few tentative thoughts. The idea that a web editor should always link to his print colleagues' content is reminiscent of (or a case of?) problems in corporate strategy where a division is getting its inputs from an internal supplier at sub-market prices, which encourages inefficiency. A common solution there is to set up an internal market with prices dictated by external conditions and adjust incentives accordingly. Could something similar work here? Who should be selling what to whom? Should the print people sell content to the web people, or should the web people sell click-throughs to the content people?</p> <p>I will have a go at discussing this in another post. In the meantime, if you've read this far you might also want to read two old posts by your humble blogger: "<a href="" target="_self">The publisher's dilemma</a>" and "<a href="">Publishing, aggregation and 'The Innovator’s Dilemma'</a>".</p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> Apple power tag:typepad.com,2003:post-6a00d8341d599853ef014e864330b6970d 2011-02-23T12:10:52+00:00 2011-03-01T12:55:26+00:00 I've been struck by some of the reactions to Apple's ipad rev-share announcement. Take this from Frédéric Filloux: A 30% rate could be acceptable for managing complex applications such as games that requires sophisticated development tools and technical approval; but... Nico Flores <div xmlns=""><p>I've been struck by some of the reactions to Apple's ipad rev-share <a href="">announcement</a>. Take this from <a href="">Frédéric Filloux</a>:</p> <blockquote> <p>A 30% rate could be acceptable for managing complex applications such as games that requires sophisticated development tools and technical approval; but not for contents-based apps such as newspapers. No one says Apple should have left a backdoor for digital subscriptions open, but the Cupertino guys should probably consider a more flexible approach based on real costs.</p> </blockquote> <p>Or <a href="">this</a> from the Nieman Lab's Joshua Benton:</p> <blockquote> <p>Frankly, I'm a little surprised Google's even taking 10 percent. The transaction costs themselves shouldn't be any higher than what Google Checkout regularly charges, which is 2.9 percent plus 30 cents a transaction (plus volume discounts). Sure, building and maintaining the record-keeping system for subscribers and the tools for distinguishing free/paid content will cost something.</p> </blockquote> <p>Debates about content monetization tend to focus far too much on questions of entitlement and fairness (it's symptomatic that this is a 'debate' at all). But this is business not ethics, and I'm hard pressed to see why Apple would volunteer to apply <a href="">cost-plus pricing</a> to something that is far from being a commodity. Presumably, 30% is the price-point that Apple thinks will maximize its profits today. Barring legal or regulatory challenges, the main reason this could change is competitive pressure.</p> <p>For more on that, consider <a href="">this bit</a> by Forrester's James McQuivey:</p> <blockquote> <p.</p> </blockquote> <p>This is slightly confusing. It may be rational for Apple's competitors to push prices down towards marginal costs (thus making things more 'efficient'). But it is less rational for Apple to do so without a competitor forcing it to. The whole point of creating innovative, differentiated products is to avoid getting into this 'efficiency' trap by making the competition irrelevant. You do that by making consumers see you as unique and irreplaceable. Apple has excelled at this.</p> <p>But this misses the point. The key to Apple's strategy here is <em>not</em> that the iPad is a better product. It is that Apple can avoid competing for publishers' business (and the resulting drop in the rev-share) <em>even</em> if Android is successful and competition for consumers becomes intense..</p> <p>This is a case of what economists call the "competitive bottlenecks" of "two-sided markets". The abstract to <a href="">this paper</a> on the subject makes it clear just why newspapers' position is so dire here (my emphasis and adaptation):</p> <blockquote> <p>When platforms are viewed as [undifferentiated] by [publishers] but [differentiated] by [consumers], we show that "competitive bottlenecks" arise endogenously. In equilibrium, platforms do not compete directly for [publishers], instead choosing to compete indirectly by subsidizing [consumers] to join. <strong>[Publishers] are left with none of the gains from trade</strong>.</p> </blockquote> <p>In other words: a platform owner won't go out of its way to be nice to publishers. What it cares about is <em>consumer </em>market share. Vis-à-vis publishers, it is a monopoly gateway to its consumers and can set prices accordingly – no matter how large or small its market share may be.</p> <p>At least that's the theory. In practice things are more nuanced, but broadly Apple seems to think the theory is right. We'll have to wait and see. Meanwhile, James' McQuivey's <a href="">words</a> may serve as consolation:</p> <blockquote> <p>Perhaps it's healthy that the content industries were able to so quickly see that Apple isn't really a savior for their businesses after all. At least now they can make decisions based on market facts rather than market hopes.</p> </blockquote></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> A small breakthrough tag:typepad.com,2003:post-6a00d8341d599853ef014e8629864d970d 2011-02-18T21:37:21+00:00 2011-02-18T21:41:04+00:00 From Paidcontent: Commercial public TV broadcasters are about to get a big boost to their web-based VOD services from the BBC. Nine months after it first announced it, the BBC has finally started including in BBC iPlayer linked VOD listings... Nico Flores <div xmlns=""><p><a href="">From Paidcontent</a>: </p><p style="margin-left: 36pt"><em>Commercial public TV broadcasters are about to get a big boost to their web-based VOD services from the BBC. </em></p><p style="margin-left: 36pt"><em>Nine months after it first announced it, the BBC has finally started including in BBC iPlayer linked VOD listings for counterpart sites. </em></p><p style="margin-left: 36pt"><em>As expected, partners are channels from ITV (LSE: ITV), Channel Four, Channel Five, S4C and SeeSaw - but a surprise edition is MSN Video Player, the aggregator spearheaded by former iPlayer chief Ashley Highfield at Microsoft. </em></p><p style="margin-left: 36pt"><em>This is a big deal because iPlayer is the most popular TV catch-up site in the UK, and has virtually become a byword for the whole VOD phenomenon it has helped popularise. </em></p><p>As I <a href="">wrote</a> when this was first announced, I had something to do with the early thinking behind this a few years ago. So here goes a cheer and a toast to everybody involved. </p><p>It wouldn't feel right for me to go into that early work here – and it may not be that relevant today. But what I find much more interesting is <a href="">this snippet</a> from my mate Chris who was involved in the later stages of the project: </p><p style="margin-left: 36pt"><em>We encourage you to reconsider the role of aggregation. In fact, we've been doing this for a couple of years now in several confidential consulting projects, as well as publicly. We've seen it deliver up to 40% more views to the aggregating party's content. </em></p><p>Take a minute to digest this. </p><p>Imagine you are a content owner who publishes (i.e. hosts) and aggregates (i.e. curates) his own content online – say, a typical newspaper's website. Suppose that one day you start adding links to your competitors, promoting their content alongside your own and sending people to their sites (where your competitors get the advertising money, not you). Your site becomes more useful, and more people start visiting you. So far, nothing surprising. But then you check how much traffic <em>your own</em> content is getting (your articles, not just your site), and find that it is 40% more popular than before. <em>That</em> is surprising. You give traffic away and are rewarded (by your visitors, not your competitors) with more traffic to your content. </p><p>If this can be shown to hold more generally (and not just in the cases that Chris studied), the implications for media companies everywhere could be significant. It would challenge fundamental assumptions about the role of media brands, the relationship between aggregators and publishers, and more. </p><p>For years this blog has been harping on about how the changing nature of aggregation is changing the media value chain. I'll try to put together a summary of that in the coming weeks. </p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> Trading on net neutrality tag:typepad.com,2003:post-6a00d8341d599853ef0147e07d4691970b 2010-12-08T19:58:18+00:00 2010-12-08T20:02:18+00:00 "Net neutrality" is often portrayed as a matter of consumer rights, cyber rights or free speech. But while it may be all that, it is it also "in good part a business negotiation being conducted in a policy arena" (NY... Nico Flores <div xmlns=""><p> "Net neutrality" is often portrayed as a matter of consumer rights, cyber rights or free speech. But while it may be all that, it is it also "in good part a business negotiation being conducted in a policy arena" (<a href="">NY Times</a>). Some <a href="">recent</a> <a href="">developments</a> on the subject on both sides of the Atlantic prompted me to undust some old work I did in my MBA days. </p><p>First, a very condensed introduction to equity market theory: </p><p>According to the <a href="">efficient market hypothesis</a>, <a href="">beta</a>, as distinct from its <a href="">alpha</a>). This makes it possible to separate a stock's performance into its "normal" return (which reflects the market's performance) and its "abnormal" return (which is "idiosyncratic" to it). </p> <a href="">market-neutral</a>. </p><p>Enough theory. You don't need to buy the EMH (I'm not sure that I do), but for the argument's sake please do. </p>? </p><p>That is the multibillion-dollar question. Whatever the answer may be (and nobody knows), it will depend on: </p><ul><li>The infrastructure being there. Among other things, this means that everybody should have at least a 2mbps broadband connection (for a single standard-definition stream) </li><li>The technology, products and business models developing and achieving enough take-up </li><li>Cable operators being unable to prevent this, either because of competitive pressures or regulation – specifically, net neutrality regulation </li></ul><p: </p><ul><li>The stocks of cable operators and (to a lesser extent) telcos should go down </li><li>The stocks of over-the-top companies like Apple, Google, Netflix etc should go up </li></ul>. </p><p>If you had done this a year ago, this is how your portfolio should have performed: </p><p><img src="" alt=""></img> </p><p>This chart is normalized so that today's value = 100. What it says is that your market-neutral long "over-the-top" portfolio would have gained a 28% return over a year, while your M/N short telecom portfolio would have been essentially unchanged. </p><p. </p><p>The fluctuations are also interesting. </p><ul><li>The over-the-top portfolio suffered losses between June and August: this may be a reaction to Comcast's court <a href="">victory</a> in April and the FCC's subsequent announcement that it would consider Title II reclassification of broadband (which was politically <a href="">troubled</a>) </li><li>The turnaround in August may have been a reaction to the <a href="">breakdown</a> in FCC-sponsored industry talks aimed at finding a compromise solution, which some observers interpreted as a preamble to the FCC taking a harder line </li></ul><p>But of course, these are just interpretations – there are lots of other possible ones, and mine is good as the next. </p><p> </p><p><em>Disclosure and disclaimer: in the past I have held small derivative positions designed to profit from variants of this trade. Although I currently no not, I may do so again in the future. This post is not intended as a recommendation for this or any other investment strategy. </em></p><p><em>A postscript for financial types: the chart above reflects cumulative abnormal returns against a full Fama-French regression, using synthetic SML/SMB portfolios based on combinations of Russell indices as per <a href="">this paper</a>..</em></p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> About that net neutrality thing tag:typepad.com,2003:post-6a00d8341d599853ef0134897da853970c 2010-11-24T21:13:30+00:00 2010-11-24T21:39:44+00:00 If all that net neutrality anxiety is messing with your head and you need the low-down from a business perspective… you might want to check out my old primer on the thing. It's a bit old but still relevant. Nico Flores <p>If <a href="">all</a> <a href="">that</a> <a href="">net</a> <a href="">neutrality</a> <a href="">anxiety</a> is messing with your head and you need the low-down from a business perspective… you might want to check out <a href="">my old primer on the thing</a>. It's a bit old but still relevant.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> Yet another post about the Times’ paywall tag:typepad.com,2003:post-6a00d8341d599853ef013488b04726970c 2010-11-03T20:55:50+00:00 2010-11-04T11:19:29+00:00 Yesterday the Times of London released some numbers about its first few months with a pay-wall, prompting a frenzy of coverage in the media and the blogsphere. If you are reading this you've probably already read some of that, so... Nico Flores <div xmlns=""><p>Yesterday.</p> <p>Most pundits are focusing on what the pay-wall meant in terms of audience – which is largely irrelevant here. The key number, the drop in page views, was not released by News Int. Using two different third-party sources, both <a href="">Seeking Alpha</a> and <a href="">Tech Crunch</a> reckon a drop of 90%. So, a 90% loss in ad revenues you might say? Not quite as bad, for two reasons:</p> <ul> <li>First, the remaining readers probably command a premium in advertising, because their demographics are known. Assume a 10% premium.</li> </ul> <ul> <li.</li> </ul> <p>Mix the two effects and you have that ad revenues today should be 20% of before, or a loss of 80%.</p> <p>How much is that worth? Very hard to tell without public numbers. Assume a CPM of £20; 4m impressions per month post-paywall (<a href="">Comscore via Techcrunch</a> – likely overestimated); and 2 ads per page. That means that ad revenues today would be £160,000 per month. If that's 20% of the original, the loss would be £640,000 per month.</p> <p>What's the gain? News Int claim 52,250 monthly digital-only subscribers (including digital editions), at monthly rates of around £8.7. This means around £454,000 per month.</p> <p>Net result: a loss of around £185,000 per month, or around one-quarter of original digital revenues.</p> <p>But:</p> <ul> <li>It is early days, and presumably more people will sign up. With the assumptions above, break-even would happen at around 75,000 subscriptions.</li> </ul> <ul> <li>If you assume their initial sell-through was only 30% instead of 50%, ad revenues lost would be only £378,000, for a net <strong>gain</strong> of £76,000 per month.</li> </ul> <ul> <li>If you assume their average CPM is £14 and not £20 as above (and keep the 50% sell-through) then you almost have break-even at a £7,000 gain per month.</li> </ul> <ul> <li>The value of retaining print subscribers may be considerable.</li> </ul> <p>All in all an inconclusive picture, but quite possibly financially neutral or even positive.</p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> Findability and public-service broadcasting (wonkish) tag:typepad.com,2003:post-6a00d8341d599853ef01348836b401970c 2010-10-15T12:52:00+01:00 2010-11-25T09:03:50+00:00 Buried at the end of a recent speech by UK culture minister Jeremy Hunt there was something that grabbed my attention. At some point I would like to write something proper about this, but right now I only have time... Nico Flores <div xmlns=""><p><span style="font-family:Times New Roman; font-size:12pt">Buried. </span></p><p><span style="font-family:Times New Roman; font-size:12pt">In his <a href="">speech</a>, Hunt said (my emphasis): </span></p><p style="margin-left: 36pt"><span style="font-family:Times New Roman; font-size:12pt">I intend to bring forward new legislation to clarify which [Public Service Broadcasters'] channels should get guaranteed positioning on page one of the Electronic Programme Guide <em>and its future online equivalents</em>. </span></p><p style="margin-left: 36pt"><span style="font-family:Times New Roman; font-size:12pt">As we move into a multi-channel, multi-platform era, this is likely to become <em>the principal intervention </em>through which we repay broadcasters who invest in content with a social or cultural benefit. I want to make sure we have absolute clarity on how that will work. </span></p><p><span style="font-family:Times New Roman; font-size:12pt">This may be a significant statement. To see why, a bit of context is needed. </span></p><p><span style="font-family:Times New Roman; font-size:12pt"><strong>The Public Service Publisher (PSP) </strong> </span></p><p><span style="font-family:Times New Roman; font-size:12pt">Until now, European governments and regulators have had three main tools to ensure that quality, "worthy" public-service content reaches TV audiences: </span></p><ul><li>Directly funding broadcasters from taxation or licence fees – e.g. the BBC </li><li>Assigning spectrum to advertising-funded broadcasters (public and private) who commit to certain public-service obligations </li><li>Requiring pay-TV operators (mainly satellite and cable) to carry PSBs' channels and to feature them prominently in their Electronic Programme Guides (EPG) </li></ul><p><span style="font-family:Times New Roman; font-size:12pt". </span></p><p><span style="font-family:Times New Roman; font-size:12pt" <em>Content</em> (PSC) and not in how it is delivered (Public Service <em>Broadcasting</em>). Therefore, the key is to identify areas of potential "market failure" where not enough content is being produced (e.g. autochthonous childrens' programmes), and to use public funds to ensure that it is produced and made <em>available</em> to audiences (i.e. "published"). </span></p><p><span style="font-family:Times New Roman; font-size:12pt">Although the PSP idea was eventually <a href="">shelved</a>, the thinking that it generated remains relevant. Indeed, when it announced the shelving, Ofcom said that generating the discussion had been the main reason to float the idea in the first place. </span></p><p><span style="font-family:Times New Roman; font-size:12pt"><strong>Pushing broccoli </strong> </span></p><p><span style="font-family:Times New Roman; font-size:12pt". </span></p><p><span style="font-family:Times New Roman; font-size:12pt">To be fair, Ofcom was not blind to this. In a key document it <a href="">said</a> (my emphasis): </span></p><p style="margin-left: 36pt"><span style="font-family:Times New Roman; font-size:12pt">…this abundance of provision, and extreme fragmentation, also leads to an important new barrier to public service content achieving reach and impact: how will people become aware of, or discover, interactive public service content which meets their needs as citizens? […] <em>In future, ensuring that people know about, and can find, a wide range of high-quality interactive public service content seems likely to be a greater challenge than ensuring its availability</em> […] One question is therefore whether intervention might be possible to enhance the reach and impact of existing public service content, and ensure it is easy for audiences to find and access. </span></p><p><span style="font-family:Times New Roman; font-size:12pt">This went in the right direction but, in my opinion, not far enough. To suggest that it's enough for public service content to be <em>easy to find</em> is like saying that it's enough for supermarkets not to make vegetables too hard to find. From a public health perspective you would like supermarkets to "push" vegetables aggressively, and you might also use public money to promote their consumption ("<a href="">social marketing</a>"). </span></p><p><span style="font-family:Times New Roman; font-size:12pt" <a href="">hammocking</a>, or even advertising) have been central. </span></p><p><span style="font-family:Times New Roman; font-size:12pt">Without a push, <a href="">broccoli content</a> just won't get eaten very much, no matter how "high-quality" it may be. If society is prepared to live with that then fine, but if it isn't (and I don't think that it is, at least in Europe) then you have a problem. </span></p><p><span style="font-family:Times New Roman; font-size:12pt"><strong>Pushing pull</strong> </span></p><p><span style="font-family:Times New Roman; font-size:12pt">Even if you agree with all this, you might still object. "The internet is a 'pull' medium" you might say, "and all the 'push' that broadcasters used to do simply won't work here, however high-minded." But here I disagree. Consider two things: </span></p><ul><li>The web's "economy of ideas" is often a black economy and the "wisdom of crowds" is often the herding of sheep. Read <a href="">this fascinating post</a> by internet investor Mark Suster on his shock as he realized that many of the main social aggregators are "systematically rigged by powerful trading networks of people who are paid to help propagate (and kill) stories". </li><li>What keeps the web turning is advertising, which is nothing but a way of pushing content to people who are not looking for it. Without "push" the web would go broke </li></ul><p><span style="font-family:Times New Roman; font-size:12pt". </span></p><p><span style="font-family:Times New Roman; font-size:12pt" <a href="">right</a> <a href="">track</a> here. But I digress. </span></p><p><span style="font-family:Times New Roman; font-size:12pt"><strong>EPGs after EPGs </strong> </span></p><p><span style="font-family:Times New Roman; font-size:12pt">So, back to Hunt's speech. His emphasis on the "future online equivalents" of Electronic Programme Guides is spot on. Of course a key reference here is <a href="">Youview</a> , <em>advertising-led</em>" (Houellebecq). Given this, the key space for intervention will be where things get promoted – where we decide to watch this rather than that. In television, today that means EPGs. Their future online equivalents are anyone's guess.</span></p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> One reason why paid content may be the only way forward tag:typepad.com,2003:post-6a00d8341d599853ef0133f49c26db970b 2010-09-27T01:42:10+01:00 2010-10-15T12:56:27+01:00 A few days ago I wrote a post about the economics of online advertising. To summarize, the argument went like this: Increasingly, publishers' ability to differentiate themselves in the advertising market is being undermined by the web This is mainly... Nico Flores <div xmlns=""><p>A few days ago I wrote <a href="">a post</a> about the economics of online advertising. To summarize, the argument went like this:</p> <ul> <li>Increasingly, publishers' ability to differentiate themselves in the advertising market is being undermined by the web </li> <li>This is mainly because of (i) audiences' promiscuity thanks to the hyperlink, and (ii) ad networks </li> <li>This drives advertising costs down towards publishers' marginal costs of inventory </li> </ul> <p>Granted, this picture may not be the full story; among other things it doesn't apply to all advertising categories. But to the extent that it does describe the future, it has an interesting strategic implication, at least for general news:</p> <p.</p> <p>Sorry for the abbreviated nature of this post. If there are reactions I might write a more expanded version.</p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/> Ruminations on the concept of value tag:typepad.com,2003:post-6a00d8341d599853ef013487bc48fd970c 2010-09-26T23:53:27+01:00 2010-09-27T14:06:47+01:00 Value is a concept that keeps coming up in debates about the future of news. In the eyes of many publishers, their industry made a mistake by letting audiences get used to reading news online without paying. But, channelling Marx,... Nico Flores <div xmlns=""><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><br>Value is a concept that keeps coming up in debates about the future of news. In the eyes of many publishers, their industry made a mistake by letting audiences get used to reading news online without paying. But, <a href="">channelling Marx</a>, they insist that their content 'has value' if only because creating it is not free. They hope that if enough publishers start charging then readers will pay. <br><br>In this blog I have tried to challenge some of the thinking involved here. I have argued that it is not news <em>content </em>itself that is valuable to audiences, but rather the everyday experience of reading the news - what I have <a href="">called</a> <em>coverage</em>. And while content is important in this, it is only part of the story. For example, reading a (print) Sunday paper is as much about having a nice breakfast - perhaps while discussing some of the news with your partner, as s/he reads another section - as it is about the writing. Yes, you do make an active choice to read this paper rather than that one because you like its writers and you identify with their views. But that is secondary; just think of the times when you've bought a newspaper in a foreign country, even if you barely understand the language. To paraphrase marketing guru Patrick Barwise, the category comes first, the brand second. To exaggerate a bit, I've quipped that <a href="" title="newspapers are in the breakfast business"><span style="color:blue; text-decoration:underline">newspapers are in the breakfast business</span></a>. </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">My objections to the value of content are not only related to the 'physical' aspects of reading, but also to the 'mental' aspects (these words are not ideal but will do for now). In the web, how valuable a piece of content is to a given reader is closely related to how that person came across the content. If I receive an email from a colleague with a link to an article that I really must read, then I have a clear interest in reading the article itself. But if I go to a newspaper's website as part of my morning routine and then follow a link to an article, my interest is not so much in the article itself as in being able to get on with my reading routine. And if I find a link to the same article in my Facebook group I may want to click on it so as to know what my friends are talking about, but I won't be very upset if I can't do so. As marketing practitioners will recognize, distinctions like these have implications for whether, how, when and how much online newspapers can charge their readers. </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">Over the last year I've been doing lots of practical work around turning this thinking into value for publishers, but this post is not about that. What I want to explore here is some of my own emerging ideas <em>behind</em> this line of thinking. Please be warned, this is a rather philosophical post, with a bit of marketing theory thrown in. If that's not your kind of thing, look away now. </span></p><p style="background: white"> </p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><strong>Heidegger</strong> </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><br>In his main opus <em>Being and Time</em>, Martin Heidegger said we have various ways of relating to things. Here I'll focus on two of these: </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">In the first way, things can appear to us as <em>available or unavailable</em> for something we are <em>doing</em>. To use an example given by Heidegger, consider a hammer that a man uses to build his house. For him, the hammer is not something to be contemplated but rather to be used in connection to something else: the house and the life he will live in it. The idea is not so much that the hammer is a means to an end, but rather that for a builder a hammer only comes into the picture when it is <em>relevant</em> to a meaningful activity (similarly, a violin is relevant to the meaningful activity of playing music, even if this is not a 'utilitarian' means to an end). Note two important things here: first, what has value is the activity (building the house and living in it) and not the thing (the hammer or the house). Second, the activity links the hammer with many other objects - e.g. nails, slabs of wood - in a network that only makes sense in terms of the activity and what drives it.<br><br>A second way in which things exist is <em>occurrentness</em>. Suppose that in the process of building his house our man breaks his hammer and, giving up on it, leaves it on the floor. When he looks at it again it is no longer a tool for him - it is neither available nor unavailable - but is just a piece of metal that lies there, <em>occurrent</em>, as an object of a certain shape, weight, color etc but essentially <em>worthless</em> because it is irrelevant<em>. </em>He may then wish to buy a new hammer, which until then is unavailable and valuable, but these words do not apply to the broken hammer. Or imagine that on his way home our man drops his hammer, in perfect condition, and someone else who has no plan to build anything finds it on the floor. For this person the hammer does not appear as a tool (even if he knows that it is a tool) but rather as an irrelevance. Again the hammer is worthless (unless we know of a place where we can sell it, in which case the hammer is an <em>asset</em> - but I'll ignore that here). </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><strong>Marketing</strong> </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">Now connect this to the world of marketing - i.e. to the tasks of designing and selling products at a price and at a place. People don't pay for occurrent objects but do for available things - or rather, to make unavailable things available. For us, these things are always part of a network of other things, a network that makes sense in terms of our activities, our lives and our social world. I don't buy a washing machine because it is a good piece of engineering. I buy it because it lets me wash my clothes so I can live and work in a society where wearing clean clothes is the norm; and I choose a white model so that it fits in my kitchen with its white furniture, which in turn reflects my style; and I care about this because I like to express myself through my style. </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">Marketing's role here is twofold. First, it aims to understand my world so as to design a machine that fits in it well. Second, it aims to <em>place</em> it in my world. It shows me that this brand and design is approved by my social milieu (if necessary, through advertising and 'positioning'), by selling it near my work or home, by offering to take care of the installation, and by helping me chose by asking me intelligent questions about the rest of my kitchen. </span></p><p style="background: white"> </p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><strong>Content and value</strong> </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">Heidegger says that nothing 'is' anything on its own, without a 'referential whole' that is meaningful to someone - e.g. the washing machine vs the rest of the kitchen and my life. In the specific realm of content (text, video, etc), these references have always been explicit: if an admired author references an unknown author repeatedly - whether positively or negatively - the second author and his work becomes relevant to all those who care about the first. </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><br>Note, importantly, that this account of referencing has nothing to do with 'filtering', 'recommending' or helping people 'discover' new content that they might 'like'. I may find it worthwhile to read the referenced content even if it I don't expect it to be 'good'. For example, <em>Mein Kampf</em> may be a repulsive and uninspired piece of writing, but reading it as part of a course in modern history which refers to it is a valuable enterprise (yes, value). Conversely, an otherwise brilliant piece of writing may be relatively worthless to me, even if I stumble on it, read it and 'enjoy' it, if it is outside my network of relevance. And an otherwise boring statement can become funny in the light of something else that reveals its pretentiousness. </span></p><p style="background: white"> </p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">Note how this contradicts traditional thinking about content according to which products have certain attributes, consumers have certain needs (real or perceived, 'hedonic' or 'utilitarian'), and the challenge is to facilitate the 'search' so that the right people can be paired with the right content with minimal pain. The better the match, the higher the value delivered. By contrast, I am saying that the value also depends on the <em>path</em> taken to get to content, because the path is part of what the content <em>is</em>. </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><br><strong>The web</strong> </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">Now back to the web. Above I noted how different contexts - checking the news in the morning vs following a link in an email from your boss - lead to different valuations of a given piece of content, for the same person. At a technological level, the web embodies this through the hyperlink. But at a deeper level, what the hyperlink allows is an unprecedented richness in the art of <em>reference</em>. Of course referencing is not a new art; footnotes and library cards have existed for centuries. But with the hypelink the space between referring and referenced text has been brought to zero. </span></p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt"><br>It matters that something was linked off the Drudge Report precisely because it was Matt Drudge who placed that link. This is not because the Drudge links to good content, but because (for certain people) something is a must-read <em>by virtue of</em> being mentioned in the Drudge. If micropayments ever become easy and widespread, it may make sense to increase an article's price when it is linked from the Drudge report - but only for people following that link - and it may make sense to give Matt Drudge a cut. By contrast, a link found by accident on Google is relatively worthless, even if the content it leads to is exceptional. This suggests that the Wall Street Journal's decision to allow Google readers to by-pass its pay-wall may be sensible. </span></p><p style="background: white"> </p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">Note the role that Matt Drudge as a curator plays in this example. I give value to following his links because what he says (through his linking) <em>matters</em> to me, and this is only possible if he is already part of my world. Of course, Matt Drudge could just as well be the BBC, Reuters, Fox News, my friends or whoever it is that I have somehow allowed to decide what should matter to me (decide, not judge - but the distinction is a subject for another post). </span></p><p style="background: white"> </p><p style="background: white"><span style="color:black; font-family:Verdana; font-size:10pt">This says at least two things about the role of brands online, and specifically about the role of curator brands. First, editorially they are as powerful than any old-media editor may have been before the hyperlink was invented – if not more. Second, commercially curators and aggregators are the kingmakers, not only because they drive traffic but also, and crucially, because they 'charge' that traffic with a layer of value. One day they may find a way to turn that to their financial advantage more aggressively than they do today.</span></p></div><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1" alt=""/>
http://feeds.feedburner.com/OnDemandMedia
CC-MAIN-2017-13
refinedweb
8,335
50.16
. 5.5.1. NDArray¶ In its simplest form, we can directly use the save and load functions to store and read NDArrays separately. This works just as expected. from mxnet import nd from mxnet.gluon import nn x = nd.arange(4) nd.save('x-file', x) Then, we read the data from the stored file back into memory. x2 = nd.load('x-file') x2 [ [0. 1. 2. 3.] <NDArray 4 @cpu(0)>] We can also store a list of NDArrays and read them back into memory. y = nd.zeros(4) nd.save('x-files', [x, y]) x2, y2 = nd.load('x-files') (x2, y2) ( . mydict = {'x': x, 'y': y} nd.save('mydict', mydict) mydict2 = nd.load('mydict') mydict2 {'x': [0. 1. 2. 3.] <NDArray 4 @cpu(0)>, 'y': [0. 0. 0. 0.] <NDArray 4 @cpu(0)>} (Section 5.3) is quite advantageous here since we can simply define a model without the need to put actual values in place. Let’s start with our favorite MLP.’. net.save_parameters('mlp.params') To check whether we are able to recover the model we instantiate a clone of the original MLP model. Unlike the random initialization of model parameters, here we read the parameters stored in the file directly. clone = MLP() clone.load_parameters('mlp.params') Since both instances have the same model parameters, the computation result of the same input x should be the same. Let’s verify this. yclone = clone(x) yclone == y [[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]] <NDArray 2x10 @cpu(0)> 5.5.3. Summary¶ The saveand loadfunctions can be used to perform File I/O for NDArray objects. The load_parametersand save_parametersfunctions allow us to save entire sets of parameters for a network in Gluon. Saving the architecture has to be done in code rather than in parameters. 5.5.4. Exercises?
http://classic.d2l.ai/chapter_deep-learning-computation/read-write.html
CC-MAIN-2020-16
refinedweb
316
69.28
class Test { public static void main( String [] args ) { System.out.println("Hello world!"); } }Things to note: System.out.println( ... ) System.out.print( ... )The former prints the given expression followed by a newline, while the latter just prints the given expression. Like the C++ << operator, these functions can be used to print values of any type. For example, all of the following are fine: System.out.print("hello"); // print a String System.out.print(16); // print an integer System.out.print(5.5 * .2); // print a floating-point number The + operator can be useful when printing. It is overloaded to work on Strings as follows: If either operand is a String, it Example int x = 20, y = 10; System.out.println("x: " + x + "\ny: " + y);The output is: x: 20 y: 10This is because the argument to println is an expression of the form: The only operator is +, so the expression is evaluated left-to-right (if there were another operator with higher precedence, the sub-expression involving that operator would be evaluated first). The leftmost sub-expression is: Evaluation of the argument to println continues, producing as the final value the String shown above (note that \n means the newline character): x: 20 y: 10 Assume the following declarations have been made: int x = 20, y = 10;What is printed when each of the following statements is executed? System.out.println(x + y); System.out.println(x + y + "!"); System.out.println("printing: " + x + y); System.out.println("printing: " + x * y); solution A C++ programmer deals with source files, object files, and executable files: Source Files: .h and .cc (or .cpp or .C) created by: you (the programmer) contain : C++ source code two kinds : .h (header files) contain class definitions and function specifications (just headers - no bodies) must be included by every file that uses the class / calls the functions .cc contain implementations of class member functions and "free" functions, including the main function Object Files: .o created by: the compiler, when called w/ -c flag; for example: g++ -c main.cc compiles main.cc creating main.o contain : object code (not executable) source code is compiled, but not linked/loaded Executable Files created by: the compiler (no -c flag) contain : executable code Code is compiled if necessary, then linked and loaded. These are the files that you can actually run, just by typing the name of the file. name : default = a.out any other name is possible via the -o flag; for example: g++ main.o -o test creates an executable named "test" A Java programmer deals with source files and bytecode files (no executable files): Source Files: .java created by : you (the programmer) contain : Java source code (one or more classes per file) restrictions : (1) each source file can contain at most one public class (2) if there is a public class, then the class name and file name must match Examples If a source file contains the following: public class Test { ... } class Foo { ... } class Bar {... } then it must be in a file named Test.java If a source file contains the following: class Test { ... } class Foo { ... } class Bar {... } then it can be in any ".java" fileSmall digression: Bytecode Files: .class created by: the Java compiler contain : Java bytecodes, ready to be "executed" -- really interpreted -- by the Java interpreter names : for each class in a source file (both public and non-public classes), the compiler creates one ".class" file, where the file name is the same as the class name Example If a source file contains the following: public class Test { ... } class Foo { ... } class Bar {... } then after compiling you will have three files: Test.class Foo.class Bar.class Here's how to compile and run the example "hello world" program given above, assuming that it is in a file named "tst.java": Remember, when compiling a program, you type the full file name, including the ".java" extension; when running a program, you just type the name of the class whose main function you want to run. Write a complete Java program that uses a loop to sum the numbers from 1 to 10 and prints the result like this: The sum is: xxxNote: Use variable declarations, and a for or while loop with the same syntax as in C++. Make sure that you are able to compile and execute your program! solution In Java, there are two "categories" of types: primitive types and reference types: Notes: C++ Arrays vs Java Arrays int [] A = {1, 222, 0}; // A points to an array of length 3 // containing the values 1, 222, and 0 int [] A = new int[10]; ... A.length ... // this expression evaluates to 10 A = new int[20]; ... A.length ... // now it evaluates to 20 Write a Java function called NonZeros, using the header given below. NonZeros should create and return an array of integers containing all of the non-zero values in its parameter A, in the same order that they occur in A. public static int[] NonZeros( int [] A ) Write a complete Java program that includes a main function as well as the NonZeros function. The main function should test NonZeros by creating several arrays, and calling NonZeros with each array. It should print the array it passes to NonZeros as well as the returned array. So for example, when you run your program, your output might look like this (if your NonZeros function is implemented correctly): passing [0,1,2,3,2] got back [1,2,3,2] passing [0,0] got back [] passing [22,0,-5,0,126] got back [22,-5,126] passing [1,0] got back [1] solution int [] A, B; A = new int[10]; -- code to put values into A -- B = new int[5]; System.arraycopy(A, 0, B, 0, 5) // copies first 5 values from A to B System.arraycopy(A, 9, B, 4, 1) // copies last value from A into // last element of B The arraycopy function also works when the source and destination arrays are the same array; so for example, you can use it to "shift" the values in an array: int [] A = {0, 1, 2, 3, 4}; System.arraycopy(A, 0, A, 1, 4);After executing this code, A has the values: [0, 0, 1, 2, 3]. int [][] A; // A is a two-dimensional array A = new int[5][]; // A now has 5 rows, but no columns yet A[0] = new int [1]; // A's first row has 1 column A[1] = new int [2]; // A's second row has 2 columns A[2] = new int [3]; // A's third row has 3 columns A[3] = new int [5]; // A's fourth row has 5 columns A[4] = new int [5]; // A's fifth row also has 5 columns For each of the following code fragments, fill in the number of the picture that best illustrates the value of A after the code executes, or fill in "error" to indicate that executing the code causes a runtime error. (In the pictures, a diagonal line indicates a null pointer.) solution C++ Classes vs Java Classes class List { public void AddToEnd(...) { ...} ... } C++ List L; // L is a List; the List constructor function is called to // initialize L. List *p; // p is a pointer to a List; // no list object exists yet, no constructor function has // been called p = new List; // now storage for a List has been allocated // and the constructor function has been called L.AddToEnd(...) // call L's AddToEnd function p->AddToEnd(...) // call the AddToEnd function of the List pointed to by p JAVA List L; // L is a pointer to a List; no List object exists yet L = new List(); // now storage for a List has been allocated // and the constructor function has been called; // note that you must use parentheses even when you are not // passing any arguments to the constructor function L.AddToEnd(...) // no -> operator in Java -- just use . The fact that arrays and classes are really pointers in Java can lead to some problems: Problem 1: Simple assignment causes aliasing: Java code conceptual picture (all empty boxes contain zeros) +--+ +---+---+---+ int [] A = new int[3], A: | -|-----> | | | | +--+ +---+---+---+ B = new int[2]; +--+ +---+---+ B: | -|-----> | | | +--+ +---+---+ +--+ +---+---+---+ A[0] = 5; A: | -|-----> | 5 | | | +--+ +---+---+---+ +--+ +---+---+---+ B = A; A: | -|-----> | 5 | | | +--+ +---+---+---+ ^ +--+ | B: | -|-------+ +--+ +--+ +---+---+---+ *** NOTE ** B[0] = 2; A: | -|-----> | 2 | | | the value of A[0] +--+ +---+---+---+ changed, too! ^ +--+ | B: | -|-------+ +--+ Problem 2: In Java, all parameters are passed by value, but for arrays and classes the actual parameter is really a pointer, so changing void f( int [] A ) { A[0] = 10; // change an element of parameter A A = null; // change A itself } void g() { int [] B = new int [3]; B[0] = 5; f(B); *** B is not null here, because B itself was passed by value *** however, B[0] is now 10, because function f changed the first element *** of the array }In C++, similar problems can arise when a class that has pointer data members is passed by value. This problem is addressed by the use of For each of the following Java code fragments, say whether it causes a compile-time error, a run-time error, or no error. If there is an error, explain why. 1. int A[5]; 2. int [] A, B; B = 0; 3. int [] A = {1,2,3}; int [] B; B = A; 4. int [] A; A[0] = 0; 5. int [] A = new int[20]; int [] B = new int[10]; A = B; A[15] = 0; solution Java is much more limited than C++ in the type conversions that are allowed. Here we discuss conversions among primitive types. Conversions among class objects will be discussed later. Booleans cannot be converted to other types. For the other primitive types (char, byte, short, int, long, float, and double), there are two kinds of conversion: implicit and explicit. Implicit conversions: An implicit conversion means that a value of one type is changed to a value of another type without any special directive from the programmer. A char can be implicitly converted to an int, a long, a float, or a double. For example, the following will compile without error: char c = 'a'; int k = c; long x = c; float y = c; double d = c;For the other (numeric) primitive types, the basic rule is that implicit conversions can be done from one type to another if the range of values of the first type is a subset of the range of values of the second type. For example, a byte can be converted to a short, int, long or float; a short can be converted to an int, long, float, or double, etc. Explicit conversions: Explicit conversions are done via casting: the name of the type to which you want a value converted is given, in parentheses, in front of the value. For example, the following code uses casts to convert a value of type double to a value of type int, and to convert a value of type double to a value of type short: double d = 5.6; int k = (int)d; short s = (short)(d * 2.0);Casting can be used to convert among any of the primitive types except boolean. Note, however, that casting can lose information; for example, floating-point values are truncated when they are cast to integers (e.g., the value of k in the code fragment given above is 5), and casting among integer types can produce wildly different values (because upper bits, possibly including the sign bit, are lost). So use explicit casting carefully! Fill in the table below as follows: solution Solutions to Self-Study Questions Test Yourself #1 System.out.println(x + y); ==> 30 System.out.println(x + y+ "!"); ==> 30! System.out.println("printing: " + x + y); ==> printing: 2010 System.out.println("printing: " + x * y); ==> printing: 200 Test Yourself #2 class Test { public static void main( String[] args ) { int sum = 0; for (int k=1; k<=10; k++) sum += k; System.out.println("The sum is: " + sum); } } Test Yourself #3 class Test { public static int[] NonZeros( int[] A ) { // count # nonzero values int nonz = 0; for (int k=0; k<A.length; k++) if (A[k] != 0) nonz++; // allocate and fill new array int[] result = new int[nonz]; int j = 0; // index of next element of new array to fill in for (int k=0; k<A.length; k++) { if (A[k] != 0) { result[j] = A[k]; j++; } } return result; } public static void PrintArray( int[] A ) { System.out.print("["); for (int k=0; k<A.length; k++) { System.out.print(A[k]); if (k < (A.length - 1)) System.out.print(" "); } System.out.print("]"); } public static void main(String[] args) { int[] A = {0,1,2,3,2}; System.out.print("passing "); PrintArray(A); A = NonZeros(A); System.out.print(" got back "); PrintArray(A); System.out.println(); int[] B = {0,0}; System.out.print("passing "); PrintArray(B); A = NonZeros(B); System.out.print(" got back "); PrintArray(A); System.out.println(); int[] C = {1,0}; System.out.print("passing "); PrintArray(C); A = NonZeros(C); System.out.print(" got back "); PrintArray(A); System.out.println(); } } Test Yourself #4 CODE CORRESPONDING PICTURE ---- --------------------- int [] A; 9 int [] A = new int[4]; 6 int [][] A = new int[4][3]; 3 int [][] A = new int[4][]; A[1] = new int[4]; A[3] = new int[2]; 1 int [] A = new int[4]; int [] B = {0,1,2,3,4,5,6,7,8,9}; System.arraycopy(B,2,A,0,4); 14 int [] A = new int[4]; int [] B = {2,3,4}; System.arraycopy(B,0,A,0,4); error int [] A = new int[4]; int [] B = {0,1,2,3,4,5,6,7,8,9}; System.arraycopy(B,8,A,0,4); error int [] A = {1,1,1,1}; int [] B = {2,2,2}; System.arraycopy(A,0,B,1,2); System.arraycopy(B,0,A,0,3); 12 int [] A = new int[4]; int [] B = {0,1,2,3,4,5,6,7,8,9}; System.arraycopy(B,0,A,0,10); error int [][] A = new int[4][3]; int [] B = {1,2,3,4,5,6,7,8,9,10}; System.arraycopy(B,0,A[0],0,3); System.arraycopy(B,1,A[1],0,3); System.arraycopy(B,2,A[2],0,3); System.arraycopy(B,3,A[3],0,3); 10 Test Yourself #5 int A[5]; Compile-time error: Can't specify array dimension in a declaration. This is C/C++ syntax. int [] A, B; B = 0; Compile-time error: Incompatible type for =. Can't convert int to int[]. B is an array reference, not an int, and 0 is not equiv to null as in C/C++. int [] A = {1,2,3}; int [] B; B = A; No errors. int [] A; A[0] = 0; Compile-time error: Variable A may not have been initialized. The array was never allocated. int [] A = new int[20]; int [] B = new int[10]; A = B; A[15] = 0; Runtime error: ArrayIndexOutOfBoundsException: 15 A now references the same array as B, which only has length 10 Test Yourself #6 Declaration Correct Rewrite with cast Never correct Variable's value ------------------------------------------------------------------------------ double d = 5; X 5.0 int k = 5.6; int k = (int) 5.6 5 long x = 5.4; long x = (long) 5.4 5 short n = 99999; short n = (short) 99999 -31073 int b = true; X char c = 97; X 'a' short s = -10.0; short s = (short) -10.0 -10
http://pages.cs.wisc.edu/~hasti/cs368/JavaTutorial/NOTES/Java_vs.html
crawl-002
refinedweb
2,557
61.87
Where Are the Hashes, Haskell? How to Model a Hash Data Structure in Haskell It's true, Haskell doesn’t have hashes. In terms of data types with multiple values, Haskell offers only two: Lists and Tuples. Lists offer an ordered array of elements (all of the same type) and Tuples have a fixed number of elements that are immutable but can be of varying types. Neither of these offers the key-value pair data type that a hash or dictionary does. Coming from a Javascript background, this was rather strange. After all, Javascript uses the “object” or hash data structure for almost everything… even an array in JavaScript is just a hash with the indices as the keys. Below are two ways you can use model a key-value pair data structure and look up the values. Using Tuples and Lists The first way involves using Haskell’s Tuples and Lists. We can model a key-value pair as a Tuple: ('key', 'value') And we can store multiple pairs in a List of these Tuples. This will essentially be our hash: [('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')] Now to look up a value from a key. You can create a search function to find the matching values for a key: search :: [(String, String)] -> String -> Maybe Answer search [] key = Nothing search ((k,v):xs) key = if key == k then Just v else search xs key Actually, Haskell already has a built-in lookup function. It takes in a list of tuples and will return the values that match or nothing if there are no matches. See the example below: lookup 'key3' [('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]Output: Just 'value3' Using Data.Map Another way to model a hash in Haskell is to use the Data.Map module. The Data.Map module is an implementation of map from keys to values using size-balanced binary trees under the hood. It's just a fancier (more optimized) version of what we were doing with the lists of tuples. import Data.Map First, we want to create a map. This will allow us to store key-value pairs and search in them. So a map from Data.Map is essentially a hash in that it stores key-value pairs. However, it's not like a JavaScript hash since it uses a binary tree and not hashing. To create your map you can either convert a list of tuples like the one above using the fromList function or you can manually add each key-value pair using the insert function: hash = [(1, "one"), (2, "two"), (3, "three")] mapFromList = Data.Map.fromList hash mapManual = Data.Map.insert 2 "two" . Data.Map.insert 1 "one" . Data.Map.insert 3 "three" $ Map.empty Now we have our map (or essentially hash but really a tree…). To search for values we can simply use the lookup function again with the key we are interested in. lookup 2 mapFromListOutput: Just 'two' Runtime Analysis One thing to note is that the runtime of both these hash implementations. One of the benefits of using a hash/ dictionary structure is that they provide constant-time O(1) lookup, regardless of the size or number of key-value pairs. In the first Haskell implementation the runtime will be linear O(n) since you need to traverse the entire list and in the second implementation the lookup runtime will be logarithmic O(logn) since it uses a binary tree. Therefore, both these implementations are still less optimized than a standard hash in JavaScript.
https://sarakhandaker.medium.com/where-are-the-hashes-haskell-718bf401c220?readmore=1&source=user_profile---------0----------------------------
CC-MAIN-2021-43
refinedweb
590
71.34
Type: Posts; User: mayooresan Im trying to call a XML webservice via JQuery. but there is no responce?? What could be the reason. I searched online and couldnt' figure out the issue as I'm new to both JQuery and web dev. var... thank you verymuch :D my bad :rolleyes: I have been following a tutorial on net abt JQuery. I'm a newbie to this framework. I've tried the following fading code but itz not working. can some one help me out??? Thankz in advance ... thanks myitdiary above code was added and config file was saved.. still the problem continues.. :( I have configured Apache, php, MySQL in my local machine. Later I installed phpbb3 in a folder "forum" When I point the browser to , the browser shows directory listing... recently I moved my data to new server!@ later I changed the namespace also in godaddy (my domain registrar). Later I found that my browser always points to the old server not to the new server...... I think you guys didnt get my point!! can you remember in wordpress, when you delete posts it'll show an command box asking 'are you sure you want to delete this post?' then we can click either... :) anyway it's working..! anyway you got it work..huh? thats the spirit!! good luck! while($row = mysql_fetch_array($r)) { ?> <?php ... you need to check which text boxes are selected and then you can continue your process... Remember that checkboxes with the same name work in a group, and the form will pass their value as an... I'm not a expert in usablity issure.. but I think for a good tech related blog like yours.. you need to have good theme, a UNIQUE them!!! <?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email { //send email $subject = $_REQUEST['subject'] ; Thanks alot.. this is wat i'm talking abt!!! When I click a link, javascript should generate a command box asking "Are you sure you want to visit the link". this command box should also have yes and no button.!!! Some one please help me.... Seems ok, It should work now... check and tell me! I replied there... wot is your problem there? reply in dat page... I"m waiting to help! or else you can use a comment form to generate emails to your inbox!! :) Enjoy da PHP! I want to display the latest last entrd message as the first result, so I used the tag ORDER BY mesgID DESC It's working perfectly all rite in query window.. when I intergrate it to PHP it... select mesgID, title, content from mesgboard ORDER BY mesgID DESC; thanks it worked with this code!! :) Wow.. it's working... thanks alot shank!! I'm using a table with mesg_id, Mesg mesg_id is a auto increment field. I want to get the last message entered should come first. for ex: if I have three rows then it may look like this.. ... thanks alot slaughters :) can anyone point me a resource where I can find the following detail. when user click the button in a form a script should check the form for empty fields and it should make a error mesg. if all...
http://www.webdeveloper.com/forum/search.php?s=c7c30a27051b0fbf36f9b5b44e16e13e&searchid=6223587
CC-MAIN-2014-35
refinedweb
536
86.1
You can subscribe to this list here. Showing 7 results of 7 I ended up with a Javanese solution: browser = r'c:\program files\mozilla firefox\firefox.exe' from java.lang import Runtime Runtime.getRuntime().exec((browser, url)) Question is, would this work on non-Windows platforms? I am looking into it now but it would be great is we could get the ' subprocess.py' module working under Jython 2.2. It works under CPython 2.2and higher... so it shouldn't be that bad to get working under the current Jython. I browsed in the source and it does a lot of condition checking / setting based on OS platform (currently Win32 and UNIX) so some Jython specific code would be in order I am sure. I use subprocess.py all the time for launching external processes.. and its awesome. > ------------------------------ > > From: adam_goucher@... > To: astigmatik@... > Subject: RE: [Jython-users] Jython2.2b2 determining OS/platform and > executing external programs > Date: Sat, 30 Jun 2007 12:23:19 -0400 > > Heres an excerpt from my homebrew Selenium framework which answers the > first part of your question. > > # jython doesnt really have a sys.platform > if java.lang.System.getProperty("os.name").lower().startswith("windows"): > else: > print "Ummm, don't have to do any other platforms right now" > sys.exit(1) > > As for the second, look at the popen2 module. > > -adam > > > > ------------------------------ > > > > Date: Sat, 30 Jun 2007 23:19:07 +0800 > > From: astigmatik@... > > To: jython-users@... > > Subject: [Jython-users] Jython2.2b2 determining OS/platform and > executing external programs > > > > >>>. > > > > _______________________________________________ > > Jython-users mailing list > > Jython-users@... > > > > > > ------------------------------ > > Discover the new Windows Vista Learn more!<> > > ------------------------------ > Get news, entertainment and everything you care about at Live.com. Check > it out! <> > > ------------------------------------------------------------------------- > This SF.net email is sponsored by DB2 Express > Download DB2 Express C - the FREE version of DB2 express and take > control of your XML. No limits. Just data. Click to get it now. > > _______________________________________________ > Jython-users mailing list > Jython-users@... > > > Dear all, I've written 2 wiki pages dedicated to the new socket and select modules. The primary purpose of these pages is to contain supplemental information about using the modules, beyond what you find from reading the cpython socket and select documentation. Specifically, we are now finding that there are a couple of fundamental differences in behaviour between cpython and jython that are unavoidable, because java implements a different model to c/python. The pages are at Each page has a section to document the differences between cpython and jython, and the socket page has a section on known issues and workarounds. Regards, Alan. [Arye] > The little program below behaves differently when run by jython and Python: > I am trying to encode in utf-8 a unicode string with 3 characters in it: > u"(r)™°" The "Registered", "Trade Mark", and "Degrees" characters. The fundamental problem here is that jython does not support PEP 263, which permits you to declare the encoding of your source module. Because you have embedded your funny characters directly in your source, jython does not interpret them correctly. Cpython will only interpret them correctly if you have an encoding declaration at the top of your source file, like so # -*- coding: utf-8 -*- (Change the encoding to whatever your text editor produces) Defining Python Source Code Encodings There are two solutions to your problem 1. Do not embed the raw characters directly in your source file. Instead, declare them with unicode escapes, like so myfunnychars = u"\u00b0\u00ae\u2122" 2. Keep all unicode strings in separate files to your source, and read them with codecs.open. Try running this code in both cpython and jython; you should get identical results from both # -=-=-=-=-=-=-=-=-= import sys print "sys.getdefaultencoding()=", sys.getdefaultencoding() myfunnychars = u"\u00b0\u00ae\u2122" my_utf8 = myfunnychars.encode("utf-8") print "len(my_utf8)=",len(my_utf8) print "my_utf8=",my_utf8 for c in my_utf8: print ord(c) # -=-=-=-=-=-=-=-=-= Regards, Alan. Meant to send this to the full list for archive purposes. =20 -adam =20 From: adam_goucher@...: astigmatik@...: RE: [Jython-= users] Jython2.2b2 determining OS/platform and executing external programsD= ate: Sat, 30 Jun 2007 12:23:19 -0400 Heres an excerpt from my homebrew Selenium framework which answers the firs= t part of your question.# jython doesnt really have a sys.platformif java.l= ang.System.getProperty("os.name").lower().startswith("windows"): platfor= m =3D "win32"else: print "Ummm, don't have to do any other platforms rig= ht now" sys.exit(1) As for the second, look at the popen2 module. -ad= am > Date: Sat, 30 Jun 2007 23:19:07 +0800> From: astigmatik@...> To: jy= thon-users@...> Subject: [Jython-users] Jython2.2b2 deter= mining OS/platform and executing external programs> > >>> import sys, os> >= >> sys.platform> 'java1.6.0_01'> >>> os.name> 'java'> > How do I actually k= now if the OS is Windows or UNIX or whatever?> > Second question, how do I = run an external program? One that will work> for ANY platform (Windows, *ni= x,.> /db2/> _______________________________________________> Jython-users mailin= g list> Jython-users@...> ists/listinfo/jython-users Discover the new Windows Vista Learn more!=20 _________________________________________________________________ News, entertainment and everything you care about at Live.com. Get it now! [Jason] > I’ve spent way too much time on this problem, but I’d like to find a > resolution. I asked about this problem months ago, but I’m still > struggling for a solution. I ask a question at the end, but first, > here’s a detailed description of the problem. I’ve tried to create base > scenario that replicates the problem, but it’s difficult because I don’t > understand the core issue. > To do this, I have to add quite a few libraries to the classpath. I do > this dynamically after loading the JVM by adding the libraries to > sys.path (lots of sys.path.append statements). > The problem is that the core libraries that I’m loading don’t run > correctly because they do not have an adequately-initialized classpath. I'm not certain if this is the cause of your problem, but have you added the java packages to the jython SystemState, like so import sys sys.add_package('com.my.third.party.lib') I can't find much information about it, so here's an email I wrote about it to web-sig a few years back. I suppose this really be an FAQ. Alan. >>>
http://sourceforge.net/p/jython/mailman/jython-users/?viewmonth=200706&viewday=30&style=flat
CC-MAIN-2014-49
refinedweb
1,051
66.84
text_type can give IndexError: string index out of range in zope 2.11 & 2.12 Bug Description Reporting for Justin Dunsworth: <sm> The fix for https:/ <sm> http:// <sm> to reproduce, have a dtml document return whitespace greater than 14 chars in length What is the buggy behavior which returning more than 14 characters of whitespace triggers? See the last two lines I commented ? Lines 39 and 40 in the paste. i grows too big, causing the IndexError. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Simon Michael wrote: > See the last two lines I commented ? Lines 39 and 40 in the paste. i > grows too big, causing the IndexError. What IndexError? The attached patch adds two calls to the test case for that function which prepend 15 spaces to text: they pass without errors. This patch is made against a trunk checkout, after cleaning up some typical "old Zope" ugly testing cruft. Tres. - -- ======= Tres Seaver +1 540-429-0999 <email address hidden> Palladion Software "Excellence by Design" http:// -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - http:// iEYEARECAAYFAks imkAoJ9TdzRDz8S =lacZ -----END PGP SIGNATURE----- Importance of this error should be bumped up to "Critical" because it affects DTML Document and DTML Method. This renders Zope 2.12.3 unusable. I don't know whether this is exactly the same bug but it is most likely highly related. For example, I am getting the following traceback: Traceback (innermost last): Module ZPublisher.Publish, line 127, in publish Module ZPublisher.mapply, line 77, in mapply Module ZPublisher.Publish, line 47, in call_object Module OFS.DTMLDocument, line 150, in __call__ - <DTMLDocument at /production/test2> - URL: http:// - Physical Path: /production/test2 Module zope.contenttype, line 76, in guess_content_type Module zope.contenttype, line 39, in text_type IndexError: string index out of range --------- DTML Document content in test2 <dtml-call "REQUEST. <dtml-call "REQUEST. <dtml-call "REQUEST. <dtml-call "REQUEST. -------- Zope Version (2.12.3, python 2.6.4, linux2) Python Version 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] Here is a solution applied to lib/python2. *** Please incorporate into next Zope 2 release *** -------- # at least the maximum length of any tags we look for iMAXLEN=14 if len(s) < iMAXLEN: return 'text/plain' i = 0 # here is the fix starting line 39 try: while s[i] in string.whitespace: i += 1 except IndexError: i=i-1 zope.contenttype 3.5.1 released with a test and fix: http:// In case the gist disappears: def text_type(s): """Given an unnamed piece of text, try to guess its content type. Detects HTML, XML, and plain text. Returns a MIME type string such as 'text/html'. """ # at least the maximum length of any tags we look for iMAXLEN=14 if len(s) < iMAXLEN: return 'text/plain' i = 0 while s[i] in string.whitespace: # <- bug i += 1 # <-
https://bugs.launchpad.net/zope2/+bug/487998
CC-MAIN-2021-21
refinedweb
481
66.74
- Fund Type: Open-End Fund - Objective: General (Non-US) - Asset Class: Money Market - Geographic Focus: Australia BT Wrap Essentials - UBS Cash+ Add to Watchlist BTUBSCS:AU0.9850 AUD Price Method: Price As of 00:59:30 ET on 10/17/2014. Snapshot for BT Wrap Essentials - UBS Cash (BTUBSCS) Fund Chart for BTUBSCS - BTUBSCS:AU 0.9850 … Previous Close - 1W - 1M - YTD - 1Y - 3Y - 5Y Open: High: Low:Volume: Recently Viewed Symbols Save as Watchlist Saving as watchlist... Fund Profile & Information for BTUBSCS BT Wrap Essentials - UBS Cash is an open-end fund incorporated in Australia. The Fund aims to provide a return (before fees and taxes) equivalent to its benchmark when measured over rolling 12 month periods. The Fund is an actively managed $A portfolio of high quality short-term call deposits and cash equivalent securities. Fees & Expenses for BTUBSCS Quotes delayed, except where indicated otherwise. Mutual fund NAVs include dividends. All prices in local currency. Time is ET. Sponsored Link Recommended Symbols: Advertisement - 1 - 2 - 3 - 4 - 5 Sponsored Links Advertisements
http://www.bloomberg.com/quote/BTUBSCS:AU
CC-MAIN-2014-42
refinedweb
173
57.98
SCDJWS Study Guide: SOAP Printer-friendly version | Mail this to a friend Using SOAP in HTTP SOAP defines a binding to the HTTP protocol. Binding SOAP to HTTP provides the advantage of being able to use the formalism and decentralized flexibility of SOAP with the rich feature set of HTPP. when including SOAP entity bodies in HTTP messages. This binding describes the relationship between parts of the SOAP request message and various HTTP headers. All SOAP requests use the HTTP POST method and specify at least three HTTP headers: Content-Type, Content-Length, and a custom header SOAPAction. The actual SOAP message is passed as the body of the request or response. An example SOAPAction header in an HTTP request. The string preceding the # is the namespace name of the first child of the Body element whereas the string following the # is the local name of that element. POST /endpoint.pl HTTP/1.1 Content-Type: text/xml; charset=UTF-16 Content-Length: 167 SOAPAction: urn:example-org:demos#Method <s:Envelope xmlns: <s:Body> <m:Method xmlns: </s:Body> </s:Envelope> SOAP 1.1 defines a single protocol binding, for HTTP. The WS-I Basic Profile 1.0 mandates the use of that binding, and places the following constraints on it use: - HTTP Versions Several versions of HTTP are defined. HTTP/1.1 has performance advantages, and is more clearly specified than HTTP/1.0. Note that support for HTTP/1.0 is implied in HTTP/1.1, and that intermediaries may change the version of a message; for more information about HTTP versioning, see RFC2145, "Use and Interpretation of HTTP Version Numbers." - Identifying SOAP Fault Some consumer implementations use only the HTTP status code to determine the presence of a SOAP Fault. Because there are situations where the Web infrastructure changes the HTTP status code, and for general reliability, the Profile requires that they examine the envelope. - HTTP Methods and Extensions. The HTTP Extension Framework is an experimental mechanism for extending HTTP in a modular fashion. Because it is not deployed widely and also because its benefits to the use of SOAP are questionable, the Profile does not allow its use. - SOAPAction Header Syntax. For example, and TCP Ports). There has been considerable debate within the W3C and IETF regarding the propriety of the use of port 80 for SOAP messages bound to HTTP. It has been concluded that this is an acceptable practice. - HTTP Success Status Codes. - HTTP Redirect Status CodesFC2616 notes that user-agents should not automatically redirect requests; however, this requirement was aimed at browsers, not automated processes (which many Web services will be). Therefore, the Profile allows, but does not require, consumers to automatically follow redirections. - HTTP Client Error Status Codes. Note that these requirements do not force an instance to respond to requests. In some cases, such as Denial of Service attacks, an instance may choose to ignore requests. - HTTP Server Error Status Codes HTTP uses the 5xx series of status codes to indicate failure due to a server error. - HTTP Cookies).
http://xyzws.com/scdjws/SGS22/7
CC-MAIN-2018-39
refinedweb
509
56.35
Clojure: Functions function expression: 「fn」 fn defines a function. It returns a expression that represents a function. (“fn” is similar to traditional lisp's “lambda”) ;; this is a function. aka lambda, anonymous function (fn [x y] (+ x y)) ;; define a function and apply it to 3 4 ((fn [x y] (+ x y)) 3 4) ; 7 ;; anonymous function can be given a name, if you want to call it in body for recursion ( (fn hh [n] (if (< n 5) (hh (inc n)) 6 )) 3 ) ; ⇒ 6 ;; this is shown as example. Better is to replace hh inside by “recur” you can use def and fn together to define a named function. (def yy (fn [x y] (+ x y))) (yy 3 4) ; 7 Defining a function and assign it to a variable is often used. So, there's a syntax shortcut “defn”. (defn name …) is equivalent to (def name (fn …)) define and name function: 「defn」 ;; define a function (defn ff "Add 2 numbers" [x y] (+ x y)) (ff 3 4) ; 7 Note: doc string comes after the function name, BEFORE the parameters. Note: square brackets [] is used for parameters. Unspecified Number of Parameters To define a function with unspecified number of parameters, add & rest to the end of parameter vector. This is usually called “rest parameters”. clojure.core/& In the function body, the rest arg rest is a list. ;; function with 0 or more parameters (defn cc [& xx] (count xx)) (cc) ; ⇒ 0 (cc 4 5 6) ; ⇒ 3 (count returns the number of items in the collection.) clojure.core/count ;; function with 1 or more parameters (defn dd [x & xx] xx) (dd) ; ArityException Wrong number of args (0) passed to: core/dd clojure.lang.AFn.throwArity (AFn.java:429) (dd 4) ; nil. When arg not received, it's nil (dd 4 5) ; (5) Polymorphism A function can be defined with different behavior depending on number of arguments or argument's type. (this is called “polymorphism”) Normally, function has this form: (defn name […] body) To define a function that depends on number of args, use this form: (defn name ([…] body1) ([…] body2) …) ;; function with different behavior depending on arity (defn gg ([] 0) ; no argument, return 0 ([x] x) ; 1 arg, return itself ([a b] (+ a b) ; 2 args, add them )) (println (gg)) ; 0 (println (gg 3)) ; 3 (println (gg 3 4)) ; 7 syntax shortcut for fn (fn [x] (body)) is equivalent to #(body) and in body, % stand for 1st argument, %1 is the 1st argument. %2 is 2nd argument, etc. ;; syntax shortcut for function “fn” #(+ % %) ;; same as (fn [x] (+ x x)) the % is the argument. ;; syntax shortcut for function “fn” #(+ %1 %2) ;; same as (fn [x y] (+ x y)) %1 is the 1st argument. %2 is 2nd argument. pre-condition and post-condition function can have pre-condition (sometimes called “guards”). If the condition isn't met, the function won't run. ;; function can have pre-condition ;; make sure the arg is greater than 1 (defn ff [xx] {:pre [(> xx 1)]} xx) (ff 2) ; ⇒ 2 (ff 1) ; AssertionError Assert failed: (> xx 1) user/ff (form-init5996506143908541499.clj:1) Here's a example of post-condition. ;; function can have post-condition ;; make sure the result is less than 10 (defn gg [yy] {:post [(< % 10)]} (Math/pow yy 2)) (gg 2) ; ⇒ 4 (gg 5) ; AssertionError Assert failed: (< % 10) user/gg (form-init5996506143908541499.clj:1) Function Binding Forms when defining a function, the parameter spec […] can be a nested structure, used to do “Destructure Binding”. See: Clojure: Binding Forms, Destructuring. Function Chaining Clojure: Function Chaining partial function generator (currying) see Clojure: Partial Function (Currying)
http://xahlee.info/clojure/clojure_functions.html
CC-MAIN-2017-39
refinedweb
595
60.24
For our current developer contest, we’ve challenged you to integrate Twilio into a Metro-styled Windows 8 application. To help you get started, we’ve put together a simple example that shows how to use the new HttpClient in .NET 4.5 to send a text message from within your app. What about twilio-csharp? WinRT uses a subset of .NET Framework 4.5 that doesn’t include some of the dependencies our current twilio-csharp library requires. Because of this you are not able to use it within a Metro-style Windows 8 app. We’re working on adding support for Metro-style apps in a future release but for now, we’ll use the new System.Net.Http namespace and classes to make our requests to the Twilio REST API. Getting Started The heart of our request revolves around System.Net.Http.HttpClient, a new and improved replacement for HttpWebRequest with a simple API and full async support. In the example below we’ll use HttpClient to make our POST requests needed to send a message. If you haven’t yet, download and install the Windows 8 developer preview. Once installed, open Visual Studio and create a new Visual C# Windows Metro Style Application project. Open up the MainPage.xaml.cs and create a method with parameters for the number to send from, the number to send the message to and the contents of the message. Lastly, create a new instance of an HttpClient so we can configure it to make the request. Here’s what we have so far: Next, because Twilio uses HTTP Basic authentication on calls to our API, you need to add authentication headers to the HttpClient. The new System.Net.Http.Headers.AuthorizationHeaderValue class gives you a clean way to represent the different HTTP authentication headers and exposes a simple constructor that accepts the authorization scheme authorization value. Create a separate method to encapsulate the creation of the AuthenticationHeaderValue class and return the instance. Once the AuthenticationHeaderValue instance is returned from the CreateBasicAuthenticationHeader method, assign it to the HttpClient instance. The client exposes a property called DefaultRequestHeaders which represents the default set of headers included with the request, including the Authorization header. Next, create the actual content to POST to the API. Sending an SMS requires three parameters: a From number, a To number and the Body. To send the content the HttpContent requires you to encapsulate content into a type derived from the HttpContent object, so for simple string content, you can create a instance of the StringContent class and pass it the assembled POST request body. Note that by default the StringContent object will send its content with a Content-Type of text/plain, but you need to let Twilio know that is actually form data. To do that you need to set the StringContent object’s ContentType property. Once the StringContent object is created and its Content-Type set, you’re ready to make the POST request to the API which is done by calling the Post method of the HttpClient with the URL to post to and the content to include. The fully assembled method is shown below: The Post method returns a HttpResponseMessage object which contains a number of useful properties, including the IsSuccessStatusCode property, which will tell you if the request succeeded (a status code from 200-299 was returned) or failed (any other status code was returned). The HttpResponseMessage.Content property contains the data the REST API sends back, which for successful requests will be the XML representation of the message we just created. You can easily parse this response with LINQ to XML. To use the method in an app, you simply call the SendMessage method from somewhere in your app: Going Async One of the major aspects of the experience of Metro style apps in Windows 8 is the requirement that they remain responsive to the end user. To help you create apps that don’t lock the UI, Microsoft has added new asynchronous programming features to .NET. To leverage these new features in the SendMessage method, you need to make a few simple modifications. First decorate the method with the new async keyword and change the method to return a Task<HttpMessageResult>. Next change the Post method call to use the PostAsync method and decorate that call with the await keyword. Now when the app is run the request will be made asynchronously, keeping the UI nice and responsive. The remaining code in the method will continue to run once the asynchronous Post method call completes. Build Your Own App Sending SMS is just the start of what you can do with the Twilio REST API. Now that you’re armed with the skills to integrate Twilio into your application, enter our developer contest for a chance to win a Samsung Windows 8 Developer Preview tablet. Hurry, the contest ends this Sunday October 1st at 11:59pm PT! What do you think?
http://www.twilio.com/blog/2011/09/using-the-twilio-rest-api-in-windows-8-metro-style-applications.html
CC-MAIN-2014-42
refinedweb
830
61.67
Changing text color in Table View Cell Is there any way to change the text color in Table View Cell? A TableViewCell's text_labelis a regular Labeland can thus have its text_colorchanged: class MyDataSource(object): def tableview_cell_for_row(self, tv, section, row): cell = ui.TableViewCell() cell.text_label.text_color = (1.0, 0.0, 0.0, 0.0) cell.text_label.text = "I am red" return cell This creates a new cell, I want to modify an existing one. - polymerchm Here's a snippet of code in my flashcard program. highlight is a global that corresponds to the row needing highlighting in the items for the tableview. def tableview_cell_for_row(self, tableview, section, row): # Create and return a cell for the given section/row cell = ui.TableViewCell() cell.text_label.text = self.items[row]['title'] if row == highlight: cell.text_label.text_color = 'red' cell.accessory_type = self.items[row]['accessory_type'] return cell I also set a checkmark on this cell. Remember, this is called every time cell appears on the screen. As when it scrolls into view. Is there a tutorial on how to create custom TableViewCells (with multiple subviews like labels, images, etc.) and then populate them with data? Ah - - seems to be a good starting point!
https://forum.omz-software.com/topic/1244/changing-text-color-in-table-view-cell
CC-MAIN-2022-27
refinedweb
200
50.43
December 6, 2011 Councilmember James S. Oddo City Council of New York 250 Broadway Suite 1553 New York, NY 10007 Dear Councilmember Oddo: Thank you for your letter of October 6, 2011 in which you asked IBO to provide data on the distribution of New York City residents incomes, tax liabilities and tax credits. Weve estimated the distributions of income and city personal income tax (PIT) liabilities in 2009 using a sample of New York personal income tax returns compiled by the New York State Department of Taxation and Finance. Your letter asked specifically about the share of income and tax liability attributable to high income households in the city. Both income and tax liabilities are highly concentrated among the most affluent New Yorkers. Filers with incomes above $105,400one tenth of all who filed 2009 tax returnsreceived 58.2 percent of total personal income and paid 71.2 percent of the city PIT. Within this most affluent ten percent, or decile, of the income distribution, the top one percent received most of the income and incurred most of the tax liability. At the other end of the distribution, a third of all tax filers who had incomes did not have any PIT liability because their incomes were too low and/or they received tax credits which offset their initial (pre-credit) liabilities. Data and Scope These estimates are derived from the annual sample of New York State personal income tax returns compiled by the states Department of Taxation and Finance Office of Tax Policy Analysis (OTPA). That office shares the sample, with appropriate protection of taxpayer identification, with tax policy and revenue forecasting organizations in the state, including IBO. The most recent sample consists of returns for tax year 2009. OTPA includes in the sample every high-income return (those with incomes of $1 million or more) actually filed in that year, so the incomes and taxes of these filers are not subject to sampling error. For other returns in the sample, OTPA uses known details about all returns actually filed in 2009the populationto compute weights indicating how representative of the population is each sampled return. Because the weights provided by OTPA are estimated, the income and tax totals reported here are subject to sampling errors and should therefore be regarded as estimates. The size of the sample is large enough to produce fairly reliable estimates of the number of filers, reported incomes, and PIT liabilities of various income groups. Among the sample of returns filed by city residents, weve excluded a small number of returns filed by part-year city residents and by those who can be claimed as a dependent by others (e.g., children claimed as dependents on their parents tax return). With these exclusions, the sample includes roughly 410,000 returns representing an estimated 3,462,000 tax returns filed. IBO used New York adjusted gross income (AGI) as the measure of income to define decile and percentile groups of tax filers and to report income amounts. AGI is the broadest measure of income used on tax returns and includes most types of income, although there are some exclusions such as some social security and retirement income, and interest on tax-exempt bonds. To avoid negative shares of income in any group, we set income to equal $0 for returns showing negative AGI, usually the result of reported business and investment losses. Because income amounts are obtained from tax returns, average and median income levels and taxes, as well as the income levels defining the decile and percentile groups, are per filer. Incomes per return are not necessarily the same as incomes per household or incomes per capita because filers may be single, married couples filing jointly, heads of household (single parents), couples filing singly, or widowed. Income Distribution Income is highly skewed toward filers in the top income group, the 10th decile, which includes all filers with incomes above $105,400. This groupabout 346,200, a tenth of all filersaccounts for 58.2 percent of the income reported on all returns. The average (mean) income for all filers is $66,600, but this too is skewed upward by the very high incomes of some New Yorkers. Half of all filers have incomes below $28,200 (the median income). Minimum Income Total Income In Group Dollars in millions $0 $342.1 $3,794 $9,072 $14,229 $20,555 $28,213 $37,672 $49,509 $68,146 $105,368 2,279.1 3,995.9 5,978.8 8,431.3 11,351.0 15,020.0 20,034.5 28,997.0 134,038.4 Average (Mean) Income Per Filer $988 6,587 11,543 17,270 24,353 32,804 43,377 57,881 83,790 387,259 $66,580 Median = $28,213 10th Decile Details 91st-95th Percentiles 96th-99th Percentiles 100th Percentile Taxation and Finance NOTES: The number of filers in each decile is approximately 346,200. Income measure is NY adjusted gross income. Data are for full-year city residents who cannot be claimed as dependents on others tax returns. Income Group 1st Decile 2nd Decile 3rd Decile 4th Decile 5th Decile 6th Decile 7th Decile 8th Decile 9th Decile 10th Decile All Filers: 0.1% 1.0% 1.7% 2.6% 3.7% 4.9% 6.5% 8.7% 12.6% 58.2% $230,468.1 100.0% SOURCES: IBO, based on 2009 PIT Sample, Office of Tax Policy Analysis, New York State Department of Within the top decile itself income is concentrated among those with the very highest incomes. Most of the income of filers in the decile is received by filers in the top income percentilethose -2- with AGIs of $493,400 or more. This most affluent one percent of filers received over a third (33.8 percent) of all income, compared with almost a quarter (24.4) of all income received by the rest of the top decile (91st through 99th percentiles). In contrast, the income share of the bottom percentile is only 0.1 percent of all income. Almost all filers in the lowest decile have little income in any form. However, a small minority of them1.3 percentreceived at least $50,000 from any single source of income but had little or no AGI because the income was offset by business or capital gains losses. (See accompanying table.) Though all types of income are concentrated at the top of the distribution, the concentration of non-wage income is especially large. Overall, the estimated $165.2 billion of wages and salaries accounts for 71.7 percent of all income received. The average wage and salary income per filer $47,700is substantially greater than the median of $24,700, indicating a skewed distribution of wages and salaries toward the highest earners, but the shares of wage income received by the top decile and top percentile48.0 percent and 18.9 percentare not as great as those for all income. Almost the entire non-wage portion of AGI consists of dividends and interest, net business income (gains minus losses), or net realized capital gains (gains minus losses). Most filers have none of these non-wage types of income, and the top one percent of all filers received more than half of each: 58.3 percent of dividends and interest, 84.6 percent of business income, and 84.7 percent of capital gains. Note that while we set negative AGIs to equal $0 in order to avoid computing negative overall income shares, we did not do so for negative amounts of business income and capital gains realizations (i.e., losses). A small number of filers in the lowest decile reported a total of $4.8 billion business lossesan amount equivalent to 16.7 percent of the net income of all filers. Though filers in all other deciles had positive amounts of net business income, combined business income in all deciles but the top was still negative. As a result business income received by the top decile$28.9 billionexceeded the total net business income of all filers. The returns of filers with business and investment losses explain why contrary to expectations for low-income New Yorkers, the first decile accounted for 6.6 percent of dividends and interest income and 11.3 percent of realized capital gains. This suggests that some of filers with the lowest AGIs had substantial amounts of business losses that more than offset large amounts of capital gains and/or dividends and interest. Distribution of Income Tax Liability Most city PIT liability is incurred by the most affluent New Yorkers, as would be expected given the concentration of income. Over two-thirds (71.2 percent) of 2009 tax liability is born by the top decile of filers, including 43.2 percent by the top percentile. Filers with incomes below $49,500those in the first seven AGI decilesaccounted for only 8.0 percent of PIT liability. -3- Total NYC PIT Liability Income Group 1st Decile 2nd Decile 3rd Decile 4th Decile 5th Decile 6th Decile 7th Decile 8th Decile 9th Decile 10th Decile All Filers: 10th Decile Details 91st-95th Percentiles 96th-99th Percentiles 100th Percentile of Taxation and Finance Dollars in millions Number of Taxpayers -0.4% -0.6% -0.7% 0.0% 1.3% 3.2% 5.3% 8.0% 12.8% 71.2% 9 214 104,979 175,647 286,107 338,188 342,856 344,058 344,774 345,169 0.0% 0.0% 4.6% 7.7% 12.5% 14.8% 15.0% 15.1% 15.1% 15.1% Average PIT Liability Per Taxpayer $280 54 63 186 316 571 935 1,401 2,236 12,475 $2,718 Median = $999 $3,618 7,759 75,447 $(26.9) (37.0) (39.6) (2.1) 78.4 192.6 320.4 481.7 770.7 4,306.0 SOURCES: IBO, based on 2009 PIT Sample, Office of Tax Policy Analysis, New York State Department NOTES: The number of filers in each decile is approximately 346,200. Income measure is NY adjusted gross income. Data are for full-year city residents who cannot be claimed as dependents on others tax returns. The average city tax of all filers was $1,746 and the median was $391. Included in the calculation of these numbers, however, are the large numbers of New Yorkersover a third of all filerswho incur no PIT liability because their incomes are too low or whose initial liability was entirely offset by tax credits. The estimated 1,180,000 filers who pay no city PIT are in addition to those low-income persons and households who do not file tax returns at all. When only filers who incur positive city PIT liabilitytaxpayersare considered, average and median taxes in 2009 were each higher: $2,718 and $999, respectively. The majority of the filers in each of the first three deciles did not pay city income taxes, and most received refund payments from the city to the extent the combined value of any earned income tax credits (EITC), child and dependent care credit, and STAR credits exceeded pre-credit liabilities. In each of the first four deciles, more tax revenue was refunded to filers than was paid to the city. The citys EITC and child care credit are determined as percentages of the federal versions of these credits. With several enhancements over the last two decades at the federal and state levels, combined with the introduction in the last decade of city versions of these credits, the incentives for low- and moderate-income families to file tax returns has increased, and the numbers claiming credits has increased over time. -4- Total EITC Income Group 1st Decile 2nd Decile 3rd Decile 4th Decile 5th Decile 6th Decile 7th Decile 8th-10th Deciles TOTAL Dollars in millions Number of EITC Recipients 1.5% 12.3% 28.9% 28.5% 20.0% 8.0% 0.8% 0.0% 58,511 198,405 216,446 147,528 135,940 105,057 22,975 6.6% 22.4% 24.5% 16.7% 15.4% 11.9% 2.6% 0.0% Average EITC Per Recipient $25 59 127 183 139 72 34 n .a. $107 $94.8 100.0% 884,862 100.0% SOURCE: IBO, based on 2009 PIT Sample, Office of Tax Policy Analysis, New York State Department of Taxation and Finance NOTES: The number of filers in each decile is approximately 346,200. Income measure is NY adjusted gross income. Data are for full-year city residents who cannot be claimed as dependents on others tax returns. An estimated 884,900 tax filers received $94.8 million in EITCs in 2009; over a quarter of them (28.9 percent) were taxpayers, meaning the credit reduced rather than eliminated their tax liability. Filers with incomes from $9,100 to $28,200 (the third through fifth decile) received the bulk of EITC credits77.4 percent of the valueand accounted for 56.5 percent of EITC recipients. The combined average EITC of recipients in these three deciles was $147, compared with a $107 average credit for all recipients. Sensitivity of Income Distribution to Economic Conditions Because the citys economy contracted and financial markets took a beating in 2009, estimates of the percentages of income received and tax liability borne by the most affluent city residents are likely to be lower than comparable estimates obtained from data of other recent years. Non-wage income, which is very highly concentrated in the top percentile of the income distribution, was particularly low in 2009. Taken together, dividends and interest received by city residents was 40.9 percent lower than in 2007 and capital gains realizations were down 75.4 percent. With much more non-wage income in 2007 than in 2009, the top decile received over two-thirds of all income reported in 2007 tax returns, compared with 58.2 percent in 2009. This group also incurred 82.0 percent of the tax liability in 2007, compared with 71.2 percent in 2009. The decrease from 2007 to 2009 in the share of income going to the 100th percentile was particularly sharpfrom 45.3 percent of total AGI in 2007 to 33.8 percent in 2009. The top one percent of the income distribution also was responsible for 57.8 percent of PIT liability in 2007, compared with 43.2 percent in 2009. Using 2007 and 2009 as the two years to compare income distribution results in the sharpest contrast because they were, respectively, the peak and the trough of the local business cycle. As a result, the comparison does not provide information about long-term trends in the distribution of income. To this end, a better comparison would use data from two comparable years in the business cycle, such as the most recent peak to 2000, the peak of the previous business cycle. Assembling that data would take additional time. -5- I hope the information weve provided is of interest to you. Please contact Michael Jacobs, Supervising Analyst of IBOs Economics and Taxes Unit, or myself if you have any questions or would like further information. Best wishes. Sincerely, -6- Income and Personal Income Tax (PIT), 2009, by Income Deciles and Selected Percentiles $105,368 159,216 493,439 Wages and Salaries Income Group 1st Decile 2nd Decile 3rd Decile 4th Decile 5th Decile 6th Decile 7th Decile 8th Decile 9th Decile 10th Decile TOTAL Average Wages, All Filers: Dollars in millions Minimum Income In Group $0 3,794 9,072 14,229 20,555 28,213 37,672 49,509 68,146 105,368 Number of Filers 346,320 346,026 346,159 346,193 346,213 346,021 346,268 346,132 346,068 346,121 3,461,521 10.0% 10.0% 10.0% 10.0% 10.0% 10.0% 10.0% 10.0% 10.0% 10.0% 100.0% Total Income Dollars in millions $342.1 2,279.1 3,995.9 5,978.8 8,431.3 11,351.0 15,020.0 20,034.5 28,997.0 134,038.4 $230,468.1 0.1% 1.0% 1.7% 2.6% 3.7% 4.9% 6.5% 8.7% 12.6% 58.2% 100.0% Average Income Per Filer $988 6,587 11,543 17,270 24,353 32,804 43,377 57,881 83,790 387,259 $66,580 Median income, all filers: 28213 173,061 138,448 34,612 Dividends and Interest Dollars in millions $830.7 1,202.6 2,511.8 4,483.1 7,220.8 10,364.3 13,983.3 18,542.3 26,846.7 79,252.4 $47,736 0.5% 0.7% 1.5% 2.7% 4.4% 6.3% 8.5% 11.2% 16.2% 48.0% $918.9 233.4 237.8 237.1 244.6 340.5 376.3 529.7 698.1 10,137.5 $13,953.9 6.6% 1.7% 1.7% 1.7% 1.8% 2.4% 2.7% 3.8% 5.0% 72.6% 100.0% $(4,832) 731.3 1,011.4 722.6 506.2 367.4 225.9 493.0 747.4 28,920.5 $28,893.4 -16.7% 2.5% 3.5% 2.5% 1.8% 1.3% 0.8% 1.7% 2.6% 100.1% 100.0% $1,751.4 (33.9) (26.5) (13.2) (16.6) (31.7) (33.8) 45.4 9.1 13,847.6 $15,498.0 11.3% -0.2% -0.2% -0.1% -0.1% -0.2% -0.2% 0.3% 0.1% 89.4% 100.0% $165,237.9 100.0% Income and Personal Income Tax (PIT), 2009, by Income Deciles and Selected Percentiles Median Wages, All Filers: 10th Declile Details 91st -95th Percentile 96th - 99th Percentile 100th Percentile $19,891.5 28,076.2 31,284.7 Total NYC PIT Liability $623.8 1,071.9 2,610.3 Percent of Filers Who are Taxpayers 0.0% 0.1% 30.3% 50.7% 82.6% 97.7% 10.3% 17.7% 43.2% $3,604 7,742 75,416 EITC Dollars in millions Dollars in millions $24,749 12.0% 17.0% 18.9% $635.0 1,371.7 8,130.8 Average PIT Liability Per Filer -0.4% -0.6% -0.7% 0.0% 1.3% 3.2% 5.3% 8.0% 12.8% 71.2% $(78) (107) (114) (6) 226 557 925 1,392 2,227 12,441 $1,746 Median PIT, All Filers: $391 172,413 138,158 34,598 Number of EITC Recipients 1.5% 12.3% 28.9% 28.5% 20.0% 8.0% 58,511 198,405 216,446 147,528 135,940 105,057 6.6% 22.4% 24.5% 16.7% 15.4% 11.9% 4.6% 9.8% 58.3% $924.3 3,556.3 24,439.8 3.2% 12.3% 84.6% $88.8 636.0 13,122.8 Average PIT Liability Per Taxpayer 0.0% 0.0% 4.6% 7.7% 12.5% 14.8% 15.0% 15.1% 15.1% 15.1% 100.0% $280 54 63 186 316 571 935 1,401 2,236 12,475 $2,718 0.6% 4.1% 84.7% Number of Taxpayers 9 214 104,979 175,647 286,107 338,188 342,856 344,058 344,774 345,169 2,282,001 $(27) (37.0) (39.6) (2.1) 78.4 192.6 320.4 481.7 770.7 4,306.0 $6,044.3 100.0% Median PIT, Taxpayers: $999 7.6% 6.1% 1.5% $3,618 7,759 75,447 Average EITC Per Recipient $25 59 127 183 139 72 Income Group 1st Decile 2nd Decile 3rd Decile 4th Decile 5th Decile 6th Decile Income and Personal Income Tax (PIT), 2009, by Income Deciles and Selected Percentiles 7th Decile 8th Decile 9th Decile 10th Decile TOTAL 10th Decile Details 91st -95th Percentile 96th-99th Percentile 100th Percentile 99.6% 99.8% 100.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% n .a. n .a. n .a. 99.0% 99.4% 99.6% 99.7% 65.9% 0.8 0.0 0.0 0.0 $94.8 0.8% 0.0% 0.0% 0.0% 100.0% 22,975 $884,862 2.6% 0.0% 0.0% 0.0% 100.0% 34 n .a. n .a. n .a. $107 SOURCES: IBO, based on 2009 PIT Sample File, Office of Tax Policy Analysis, NYS Department of Taxation and Finance NOTES: The measure of income used is NY adjusted gross income (AGI). Sample includes only full-year NYC residents and excludes filers claimed as dependents by others. The number of filers in each decile are not exactly even because of sampling. Taxpayers are filers who incurr positive NYC PIT liabilities.
https://ru.scribd.com/document/75579290/Scan-ibo-Income-Distribution-Response-Letter-dec-2011
CC-MAIN-2019-30
refinedweb
3,485
59.84
#include <sys/types.h> #include <sys/stream.h> #include <sys/stropts.h> #include <sys/ddi.h> #include <sys/sunddi.h> int qassociate(queue_t *q, int instance Solaris DDI specific (Solaris DDI). Pointer to a queue(9S) structure. Either the read or write queue can be used. Driver instance number or -1. The qassociate() function must be used by DLPI style 2 device drivers to manage the association between STREAMS queues and device instances. The gld(7D) does this automatically on behalf of drivers based on it. It is recommended that the gld(7D) be used for network device drivers whenever possible.. The qassociate() function can be called from the stream's put(9E) entry point. Success. Failure. DLPI style 2 network driver DL_ATTACH_REQ code specifies:. dlpi(7P), gld(7D), open(9E), put(9E), ddi_no_info(9F), queue(9S)
http://docs.oracle.com/cd/E36784_01/html/E36886/qassociate-9f.html
CC-MAIN-2016-22
refinedweb
137
63.15
[ ] ASF GitHub Bot commented on CXF-6392: ------------------------------------- Github user asfgit closed the pull request at: > Schema imports are not handled correctly in generated WSDL and XSD files > ------------------------------------------------------------------------ > > Key: CXF-6392 > URL: > Project: CXF > Issue Type: Bug > Components: JAX-WS Runtime > Affects Versions: 3.1.0, 2.7.16 > Reporter: Tomas Hofman > > 1) XSD files cannot be accessed by URLs that should be enabled by XML catalog rules. > 2) Under some circumstances, schema location attributes in <include> elements are not rewritten to "?xsd=location" form > *Situation:* > - We have following rule in jax-ws-catalog.xml: > {code} > <rewriteSystem systemIdStartString="" rewritePrefix="/wsdl/schemata/"/> > {code} > - We have WSDL file importing an XSD file, which in turn is including another XSD file, all located in /wsdl/ directory on classpath: > {code} > /wsdl/service.wsdl > /wsdl/schemata/schema.xsd > /wsdl/schemata/included_schema.xsd > {code} > - WSDL file contains import like this, with *relative path*: > {code} > <import namespace="" > > {code} > - schema.xsd file contains following include, again with relative path: > {code} > <xsd:include > {code} > *Problem 1:* > XSD file cannot be accessed by URL, which is supposed to be working due to rewriteSystem rule. > It can only be accessed with relative path URL: "?xsd=schemata/schema.xsd". > This (meaning the first URL) starts working when import in WSDL file is modified to use full URL instead of relative path: > {code} > <import namespace="" > > {code} > *Problem 2:* > When schema.xsd is accessed by request using full url like "?xsd=", instead of relative url, schemaLocation attribute in <import> and <include> elements in that file are not rewritten into "?xsd=..." form, so those schemaLocations cannot be followed by client. > I'm attaching also a PR with a test case demonstrating described behaviour, and proposed fix. -- This message was sent by Atlassian JIRA (v6.3.4#6332)
http://mail-archives.apache.org/mod_mbox/cxf-issues/201505.mbox/%3CJIRA.12827677.1430923417000.12218.1432318518033@Atlassian.JIRA%3E
CC-MAIN-2017-43
refinedweb
291
52.6
Prior to .NET Framework 4, the development of in-process shell extensions using managed code is not supported at all because of the CLR limitation allowing only one .NET runtime per process. Jesse Kaplan, one of the CLR program managers, explains it in this MSDN forum thread:. In .NET 4, with the ability to have multiple runtimes in process with any other runtime. However, writing managed shell extensions is still not supported. Microsoft recommends against writing them. We built a whole namespace extension in .net and works fine including being able to provide callbacks to a file filter driver to manage Office File Open/Save dialogs. It is possible and works great. Hi Jialiang, I've read through all your articles regarding Windows Shell Extension. They are really great ones. I am just curious whether it is officially supported now? Does Windows Shell team has a plan to get it supported in the near future?
http://blogs.msdn.com/b/codefx/archive/2011/01/04/is-it-officially-supported-to-write-windows-shell-extension-using-net-4-today.aspx?Redirected=true&t=Is%20it%20supported%20to%20write%20Windows%20Shell%20Extension%20using%20.NET%204%20today
CC-MAIN-2013-48
refinedweb
155
68.06
add_wordsvocabulary list be a dictionary that has spoken and written forms. I don't know how that works,I think Natlink has a way. Caspark mentioned this (pseudo-?)code on the Talents slack. Not sure does the spoken forms: import natlink def add_words(words): for word in words: known_word = natlink.getWordInfo(word) if known_word is None: natlink.addWord(word) np, if you need more flexibility for commands then dragonfly is not at all hard to learn see e.g. @mrob95 I'm hoping maybe you've seen this error message before and can point me in the right direction. Here's the sequence of events: Any advice? @alexboche pretty much what @esc123 said. In scientific notebook you can go into a permanent math mode where everything you type is assumed to be math, regardless of new lines et cetera, whereas LyX requires you to constantly reset the mode and it is easy to accidentally jump out by going to the end of the line or w/e. Also in SN you can select and manipulate blocks of math easily. Since I mostly used it for bashing out homework assignments or completing exams the ease of getting stuff down in SN easily outweighed its lack of complex formatting options. I think the main use case for LyX is as an alternative to raw LaTeX for technical writing, but since I know LaTeX pretty well and am comfortable in a text editor I don't really have a need for it. btw if you are considering trying SN, then I would definitely recommend version 5.5 over version 6 if you can get it. Version 6 is much closer to the behaviour of LyX and I really think they have made it worse. $\Omega _{k}$in source are nonstandard from a style standpoint. In case it's not clear, $\Omega _{k}$and $\Omega_{k}$compile to the same typeset result, since LaTeX ignores most whitespace characters in math mode. I've looked into it but didn't really fancy spending that much for something which I'm not sure I have a use for. The same commands should work though if scientific workplace were added as another context for the scientific notebook commands. I downloaded a 30 day trial of version 6 and managed to get most of the commands working so if you wanted to give it a try I could make a pull request? I suspect that if you prefer SN to LyX then you will prefer the old version though. It's a shame because I really liked 5.5 and it is pretty much impossible for anyone to get hold of now without buying MathTalk. I think putting some math vocabulary in with dictation is very useful so we don't have to pause or use "say <dictation>" all the time. Here's what I tried so far (including some of Mike's old code). Capturing dictation and then replacing some words with a dictionary (would be in a separate grammar that would be disabled unless you are doing math). math_replacement_dictionary = {"math gamma": r"$\gamma$", "math gamma below beta": r"$\gamma_\beta$"} def math_replace(dictation, dictionary): input_list = str(dictation).split(" ") output_list = [] for i in range(len(input_list)): if input_list[i] == "cap": input_list[i+1] = input_list[i+1].title() else: output_list.append(input_list[i]) pre_math_string = " ".join(output_list) output_string = copy.copy(pre_math_string) for k, v in sorted(dictionary.items(), key=lambda pair: len(pair[0]), reverse=True): output_string = output_string.replace(k, v) Text(output_string).execute() "<dictation>": Function(math_replace, dictionary=math_replacement_dictionary), The first part of the function is just to getcapitalization for regular dictation. The reason I did the sorting stuff is because I want to make sure I am replacing the largestthing first. e.g. replacing "math gamma below beta" before "math gamma" since otherwise that would cause problems. We can generate a dictionary for the math replacement dictionary. Let me know what people think. David zurow said he had some thoughts about a better way to do this sort of thing am hoping he will share. I still need to get it to put in spaces at the beginning of each utterance unless there already is aspace which I guess is something that Dragon does automatically but is not done by this. A variety of things seem kind of clunky when all of your dictation is passed through this. e.g. scratch that doesn't work. @annakirkpatrick you can have backslashes in the Dragon vocabulary word if you put them in the printed form which is in preferences under a word in the Vocabulary Editor. However, if you are using the approach above if you pass everything through that command, the printed form will be lost it will just write out the written form; in other words you can't do both approaches at the same time. I'm not sure it's worth it really. Losing dragon's built-in editing features is annoying and this would be vulnerable to slight misrecognitions of the command words. I don't think pausing before starting to dictate latex wastes too much time in the scheme of things. Probably an easier way of accomplishing something similar would be to just dictate as normal until you have a document with numerous instances of "math gamma" and then just do a find and replace for all of them. By "Dragon 's built-in editing features" do you mean the commands like "insert before <dictation>" ? That still works with this but those don't usually work in math -based apps anyways. There are a few small issues regarding spacing that need to be worked out. for now I think I'm just going to have a space at the end of the text action. but spacing with things like "open paren" works though the spacing does not seem to work properly for custom Dragon vocabulary words or for "slash". I don't think the find and replace approach would be suitable if you have a lot of different symbols going around. The issue of misrecognitions is important; ideally this grammar would be given lower priority than the other grammars so that it would have the low priority that dictation usually has. Rather than just replacing words it might be more flexible to have a restricted set of commands available, especially for Lyx / scientific notebook where you need keystrokes not just text. I just posted David's suggestion on how to do this at the end of this issue dictation-toolbox/Caster#623 . In general, this sort of thing would not be so much for a situation where you are doing heavy duty calculations but more for a situation with like 70-30 English-math symbols ratio or higher. I will be trying out this sort of thing in the wild myself so I will see how it goes. I think it will at least be good to have as an option which the user can easily enable/disable, but I will have a better sense after using for a while.
https://gitter.im/mathfly-dictation/community?at=5d2784beeab6cd77634fa622
CC-MAIN-2022-21
refinedweb
1,178
61.97
Pre-Intermediate BUSINESS G & PRACTICE Nick Brieger & Simon Sweeney vk. com/ engl ishl ibr ary^ ,cG% CEF(eve(-^ ^ IV 0 R ^ V = P O W E R E D BY C O B U I L D vk.com/bastau Contents Introduction v G ram m atical Terms vi G ram m ar Language Form Unit 1 Be (1) am /is/are 2 U nit 2 Be (2) was/were/have been 4 Verbs - Voice Unit 39 Active I make. 78 Unit 40 Passive It is made. 80 Unit 41 Active vs. Passive I m ake/lt is made. 82 Verbs - Other Unit 42 It Is/They Are vs. There Is/There Are 84 Unit 43 Have and Have Got 86 vk.com/bastau Unit 44 Get and Have Got 88 U nit 45 Say vs. Tell 90 Unit 46 Make vs. Do 92 U nit 47 Used To 94 Unit 48 Rise vs. Raise 96 Unit 49 Verb + Preposition 98 Unit 50 Verb + Adverb (P hrasal Verb) 100 Nouns Unit 61 S in gu la r and P lu ra l Nouns machine, machines 122 Unit 62 Countable and Uncountable Nouns machine, m achinery 124 Unit 63 Noun Com pounds company personnel 126 Unit 64 Genitive Form s the company's, o f the company 128 Determ iners Unit 71 A rticle s the company, a company 142 Unit 72 Personal Pronouns I, me, you, he, him, etc. 144 Unit 73 Possessive and Reflexive Pronouns m y/your/his/our company 146 Unit 74 D em onstratives this/that company 148 Unit 75 Some and Any some/any products 150 Unit 76 Some, Any and Related Words someone, somewhere, etc. 152 Unit 77 Q uantifiers (1) all/several/a lot o f products 154 Unit 78 Q uantifiers (2) many/[aj few details, m uch/lal little inform ation 156 Unit 79 Q uantifiers (3) each/every company 158 Unit 80 N u m e ra ls 160 Prepositions Unit 81 Tim e in at on 162 Unit 82 Place (1) at, to, from, in, into, out of, on 164 Unit 83 Place (2) above, below, etc. 166 Unit 84 Like, As, The Same As and D ifferent From 168 Business Files 1 Industries and Jobs 170 2 C ountries and C urrencies 171 3 Business A bbreviations and Short Form s 172 4 B ritish English vs. A m erican English 173 5 N um bers, Dates and Tim es 174 6 Irre g u la r Verb Table 175 vk.com/bastau Introduction Targets and objectives Business Grammar & Practice: Pre-Intermediate is for pre-interm ediate to intermediate speakers of English who need to m aster the type of English used in professional situations. Whether you are studying to enter the workplace or already using English at work, accurate use of English grammar w ill make you a more effective communicator. If you feel you already know the core gram m ar for business English, the Intermediate book in this series w ill take you through more complex grammar. To ensure that the language you learn is relevant for the workplace, the book uses example sentences from the Collins corpus. This is a constantly updated database of English language from a range of print and spoken sources. You can therefore be sure that any example used is an authentic use of English in a business context. Business Grammar & Practice: Pre-Intermediate can be used together with any business English course book to provide more detailed explanations and supplementary exercises in the gram m ar of business English. It is suitable fo r both classroom and self-study use. Organisation of material There are 84- units and 6 Business Files. Each unit consists of: 1. Language presentation through: sample sentences to show the language form s in use; an explanation of the language forms; a description of the uses of these forms. 2. Practice through: controlled exercises to develop recognition of the language form s (Exercise 1); controlled exercises to practise combining language form and language use (Exercise 2); controlled or guided exercises focusing on language form and meaning (Exercise 3); transfer activities to practise transferring the language presented in the unit to the students own personal and professional experience. 3. Answers to the controlled and guided exercises. P re -In te rm e d ia te Business G ra m m a r vk.com/bastau Modals are followed by an infinitive, e.g. You must Regular verb (see also Irreg u lar verb) attend the meeting. A verb that forms the past tense and past participle Neednt and darent are also used in this way. by adding -ed, e.g. start - started - started. Noun Relative clause A word that names persons, places or things, A clause beginning with a relative pronoun such as e.g. manager, factory, computer. who, whose, which, that or a relative adverb such as A countable noun is a noun with a singular and when, where, why. plural form, e.g. a machine, 20 machines. Sentence An uncountable noun is a noun that does not A group of words with a subject and a verb between have a plural and you cannot put a or an before it, two full stops, e.g. My name is Paul. I come from e.g. information, equipment. London. A noun compound is a group of words with two or more nouns, e.g. sates director. Short form A noun phrase is phrase with a noun as the main A short form of a verb that is written with an word, e.g. a very good manager. apostrophe to show that some letters are missing, e.g. it s, were, cant. Object A noun or noun phrase that is used after a transitive Simple verb, e.g. We played golf. A verb construction in either the present simple or past simple tense. Ordinal num ber The numbers 1st, 2nd, 3rd, 4th, 5th, 6th etc. Simple sentence A sentence which is only one main clause, e.g. Sales Passive (see also Active and Voice) have increased. A passive construction contains a verb or verb phrase in the form be + past participle, where the Singular (see also Plural) doer of the action is expressed as the agent rather A form of a noun, pronoun or verb which shows that than the subject, e.g. Taxes were increased by the there is only one, e.g. company, I, she lives in York. last government (passive] versus The last government Subordinate clause (see also Main clause) increased taxes (active). A group of words with a subject and verb which is Perfect (aspect) not a sentence because it needs a main clause to be A verb construction in the form has/have + past complete, e.g. He worked for ITCorp before he joined participle which puts the action or event in a MeoaTech. different time from the time of speaking or writing. Subordinating conjunction The present perfect shows that the action has been A word which introduces a subordinate clause, e.g. completed by the time of speaking or writing, e.g. We because, although, if, who. have already seen the report. The past perfect shows that an action has been Superlative (see Comparison of adjectives) completed by an earlier point of time, e.g. We had Tense already seen the report. The grammatical form of a verb which shows Phrasal verb the time of the action, e.g. present or past. A verb phrase that consists of a verb + adverb, e.g. Tim e m arker to look up a word (in a dictionary). A phrase which shows when something happens, Phrase e.g. last year, at the moment, next week. A group of words, but less than a clause, i.e. not Transitive verb (see also Intransitive verb) containing a subject and verb. A main verb which takes a direct object, e.g. We Plural (see also Singular) played golf last week. A form of a noun, pronoun or verb which shows that Uncountable noun (see Noun) there are more than one, e.g. companies, they, profits Verb .. .ing are increasing. The verb form infinitive + ing, e.g. helping. Preposition Voice A word that is used before a noun and shows us The grammatical category of either active or passive something about time, e.g. in the morning, at 7 oclock, verb form. place, e.g. on the desk, or manner, e.g. by_ car. Vowel Pronoun One of the letters a, e, i, o, u. A word that takes the place of a noun or noun phrase, e.g. she, my, this, who. Wh-question A question beginning with who, what, why etc or Quantifier with how. A word which describes quantity, e.g. all, many, some, few, no. Yes/no question A question to which the answer must be yes or no, Question tag e.g. Is your name Mary? A short question which makes statement into a question, e.g. We sent the goods last week, didnt we? Zero article (see Article) vk.com/bastau UNIT Be(1) See also Unit 2 Be 12] A Sample sentences A: W here are you from? B: 1 am from Asciano. And my colleagues are from Pisa. A: Im sorry. W here is Asciano? B: It is in Tuscany. Its near Siena. B Form The present tense of to be has three form s: the positive, the negative and the question. Positive form 1 am I'm you are youre he/she/it is he's/she's/its the manager is the manager's the company is the companys we are we're they are they're the managers are the managers're the companies are the companies're Note The firs t seven sh o rt fo rm s are used in spoken or in fo rm a l w ritte n English; the last two (the m a n ag e rs're etc.) are used in spoken language only. 1 am not am 1? you/we/they are not are you/we/they? he/she/it is not is he/she/it? the manager/the company is not is the manager/the company? the managers/the companies are not are the managers/the companies? C Uses Look at these sentences w ith the verb to be in different form s: Exercise 1 In the dialogue betow, Peter Hay is talking to Jane Field and A rnold Weiss at a trade fair. Put the verb form s in sentences 1-14 into the correct box. The firs t one is done for you. PH: Hello, Im Peter Hay. (1) Where are you from ? (2) JF: Were from Seattle in the USA. (3) PH: Oh, are you A m erican? (4) JF: I am. (5) But A rnold is n t. (6) aw ^ r m from A ustria. (7) But w e re from the same company, Inte r Corp. (8) PH: Oh, yes, Inte r Corp. What are your nam es? (9) JF: My nam e's Jane Field. (10) This is A rnold Weiss. (11) PH: Pleased to meet you. Are you in banking? (12) AW: No, w e re not. (13) W ere in insurance. (14) Exercise 2 Complete the spaces. Use sh ort form s where possible. Exercise 3 Complete the following text about Axdal Electronics. Use a form o f be. Axdal Electronics is a w orld leader in control systems. W e_________ suppliers to the car industry. Car m a n u fa ctu re rs_________ our only customers. We__________ also suppliers to o ther industries. A E _________ an international company. Our cu sto m e rs__________in the USA, Japan and Europe. Our Chief Executive_________ Paul Axdal. We__________ a fam ily company and business_________ very good, says Paul. Transfer Write short sentences about yo urself and some friends. Use different present tense form s o f be. vk.com/bastau ! 3 i UNIT Be (2) See also Unit 1 B e lli A Sample sentences A: Hello Raj. W here w ere you yesterday? A: I haven't seen you a ll w eek! B: I wasn't in my office. I was at a meeting. B: I know. I have been very busy. B Form The verb to be has three main tenses: the present (see Unit 1), the past and the present perfect. Look at the positive fo rm s in the past and the present perfect. the managers were the managers have been the managers've been (spoken only] the companies were the companies have been the companiesve been (spoken only) C Uses Look at these sentences w ith the verb to be in different tenses and d iffe re n t form s: A: W here w ere you yesterday? You w eren 't in your office, (past question and negative) B: 1was in Bolton, (past positive) A: Why w ere you in Bolton? (past question) B: 1was with a client, (past positive) Ct I'm sorry. Bolton? W here is Bolton? (present positive and question) A: It is in the north of England, near Manchester. In the past it was a famous textile centre. (present positive and past positive) C; 1haven't been to Manchester. But I've been to Liverpool. (present perfect negative and positive) B: 1was in Liverpool last w eek. When w ere you there? (past positive and question) C; 1was there in January, (past positive) P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 In the dialogue below, Henry Leer and Joe Fisher are in a hotel b a r in Amsterdam. Put the verb form s in sentences 1-10 into the correct box. Exercise Delco Ltd. Complete the le tte r below with words 16-20 East Mount Road, Lincoln LN3 5RT 6 November.... from the box. Dear Mary, Last week Tom and Paula__________ here for a meeting. I t __________ very useful. T h e y___________ here for two days. W e __________ to Oslo in the last few days. W e __________ there for a meeting with our Norwegian colleagues. Arne Sillessen__________ very interested in our ideas. Until now, I __________ happy with the project. Now I am very optimistic. Exercise 3 Complete the spaces in the em ail below. Use sh ort form s where possible. From: ipcs3@cc.uat.es Sent: Mon 28 November 15:40 Subject: Short Bros Dear Frances, I am sorry I _____ (not) at the meeting yesterday. I _____ (not) in the office this week. Tom and I ______ in London. W e _______at a Sales Conference. I ___ very busy recently.______ Short Brothers happy with the contract?_______they ______ in contact today? Juanito __ ..................... Transfer Write a sh ort paragraph about yo urself and a local industry o r institution. Use past tense and present perfect form s of be. vk.com/bastau 5 UNIT The Present Continuous Positive Be The present continuous negative The present continuous question The present continuous vs. the present simple A Sample sentences At the m oment 70% of consumers are using the Internet to buy things. Prasad is currently preparing a business plan. At present I am eating my lunch. B Form The present continuous positive has tw o parts: the present tense of to be + infinitive .. .ing C Uses We use the present continuous to ta lk about: Note W ith C1 and 2, we can use the follow ing expressions: but not actually vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Look at the email below. Underline five present continuous forms. Exercise 2 Here is p a rt o f a telephone conversation. Complete the spaces with the correct form o f the word in brackets. Use sh ort forms, where possible. DL:Hello, Peter. Listen, I m reading Ire a d lyo u r report. Theres a problem on page 50. PT: Okay, I _[look] at it rig h t now. Whats the problem ? DL: It says w e __________ (invest] $250,000 in research. That's wrong. I t s $25,000, not $250,000. PT: Okay I ll change that. DL: Right. Remember, y o u __________ (meet] M r Lally and his colleagues today. PT: Yes, I know. They__________ (come] here at 2.30. DL: Fine. Good luck. See you tomorrow, then. Exercise 3 Look at the graph below. It shows total company sales and sales for two products, A and B. Write fou r sentences. Use the prom pts below. 2. Product A (increase). 3. Product B (fall). Transfer Write fou r sentences about you, yo ur friends o ra local business o r institution. Include phrases from the box. now at the m oment currently at present vk.com/bastau 7 UNIT The Present Continuous Negative See also Units 1,2 Be Unit 3 The present continuous positive Unit 5 The present continuous question Unit 9 The present continuous vs. the present simple A Sample sentences I am not working at the moment; I am looking for a job. The company is not growing quickly enough. M anagers are not dealing w ith the issue at the moment. B Form The present continuous negative has three parts: the present tense of to be + not + infinitive .. .ing C Uses We use the present continuous to ta lk about: vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Look at the text below. Underline four present continuous negatives. We are not increasing our prices th is year. The m arket is not strong enough. We are launching new products f o r th e domestic market. M ost o f our products are selling well at home. A t present, we are not planning any new products fo r export. Sales are not increasing in our e xpo rt markets. The company is not expecting improved sales th is year. Exercise 2 Write sentences with a present continuous negative. Use short form s, where possible. Exercise 3 Make negative o r positive sentences fo r pictures 1-4 below. Use the words in brackets. (this year/the com pany/do w e ll in the USA) (at p re sent/w e/present a good image Transfer Write six sentences about yo u r current activities. Use the present continuous tense, with some positive and some negative sentences. vk.com/bastau UNIT The Present Continuous Question Be The present continuous positive The present continuous negative The present continuous vs. the present simple Questions A Sample sentences Yoshie: Henry, what are you doing? Henry: I'm checking the figures. There is a mistake here. W hat is Janet doing Yoshie: She is calling a taxi for you. Are you leaving now? Henry: Yes, but Janet is staying. B Form The present continuous question has two parts: the present tense of to be + infinitive .. .ing ( i g i Subject am i presenting? are you making? is he/she/it calling? is the computer (= it) analysing? is the consultant (= he/she) reading? are we meeting? are you looking? are they visiting? are the specialists (= they) doing? are the machines (= they) preparing? C Uses We use the present continuous question to ask about: vk.com/bastau P re -In te rm e d ia te B usiness G ra m m a r TASKS Exercise 1 Underline the mistakes in the following sentences. Then correct them. Exercise 2 Make questions to complete the dialogue below. Use the words in brackets. Exercise 3 Make questions fo r the pictures 1-4. Use the words in brackets. 4. (w hy/oil/leak) Transfer Write five questions about yo u r colleagues using the present continuous form. vk.com/bastau I 11 UNIT The Present Simple Positive 6 See also Unit 7 The present simple negative Unit 8 The present simple question Unit 9 The present continuous vs. the present simple A Sample sentences We always investigate a job applicant's background. The m anager norm ally has total responsibility for this process. Many people say they never eat breakfast. I often go to France. B Form The present sim ple positive has one part: infinitive(s) ect I make you present he/she/it calls the company/the department (= it) prepares the manager/the boss (= he/she) reads we meet you look they visit the companies/the departments (= they) do the managers/the workers (= they) discuss C Uses We use the present sim ple to ta lk about: vk.com/bastau 12 ! P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Make sentences with the following words. See the example. I live in a city. Exercise 2 Match the sentences below to the correct picture a-e. Exercise 3 Complete the following text. Use the words in brackets. Put the verbs in the present simple. Transfer Write a sh ort paragraph like the one in Exercise 3 about someone you know. Include some o f the following words. vk.com/bastau 13 UNIT The Present Simple Negative 7 See also Unit 6 The present simple positive Unit 8 The present simple question Unit 9 The present continuous vs. the present simple Unit 31 Do A Sample sentences We dont use complicated equipm ent or technology; we use very sim ple processes. He doesnt w ork w ith me anymore; he w orks in Beijing now. The company provides nurses and healthcare staff, but it doesn't provide managers. B Form The present sim ple negative has two parts: don't/doesn't + infinitive C Uses We use the present sim ple to ta lk about: vk.com/bastau 14 I P re -In te rm e d ia te B usiness G ra m m a r TASKS Exercise 1 Make negative sentences with the following words. See the example. I don't w ork in the oil industry. Exercise 2 Make negative sentences with the following prompts. 2 . w e/advertise/on television 3. the co m p an y/sponsor/sport 4. l/lik e /fis h 8 . you/live/in an a p a rtm e n t Exercise 3 A local newspaper attacked Teal Ltd fo r damaging the environment. The owner, Peter Teal, wrote a reply. Give the negative form s o f the words in the brackets. D ear S ir, I w a n t to te ll y o u r re a d e rs so m e fa c ts a b o u t Teal L td . T he c o m p a n y (u s e ) c h e m ic a l d y e s in its p ro d u c ts o r b le a c h to m ake o u r m a te ria ls w h ite . T he m a n a g e m e n t (e n c o u ra g e ) th e use o f c o m p a n y c a rs . We (a llo w ) s ta ff to p a rk p riv a te c a rs on c o m p a n y p re m is e s . W e (b u rn ) o u r ru b b is h and we (th ro w a w a y ) g la s s or p a p e r. Y o u rs fa ith f u lly , f 3 TtM PJ T eal M a n a g in g D ir e c to r (T e a l L td ) Transfer Write six present sim ple negative sentences about the place where you live and/or work. vk.com/bastau 15 UNIT The Present Simple Question 8 See also Unit 6 The present simple positive Unit 7 The present simple negative Unit 9 The present continuous vs. the present simple Unit 31 Do Units 53-55 Questions Sample sentences Eduardo: W hat do you do? Yu Yin: I w o rk as a tran slato r for a company in London. Eduardo: And w hat does the company make? Yu Yin: It doesnt m ake anything, It offers legal advice. B Form The present sim ple question has two parts: do/does + infinitive lieigipan do I present? do you make? does he/she/it solve? does the computer (= it] analyse? does the consultant (= he/she) reach? do we compete? do you look? do they visit? do the specialists (= they) fix? do the machines (= they) prepare? C Uses We use the present sim ple question to ask about: vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Undertine do o r does and the main verb (infinitive) in the foltowing questions. Then answer them. 2. Do the largest com panies in your area export products to m any different countries? 4. Do you know any in te rn a tio n a lly fam ous products fro m your country? Exercise 2 M artin and Javier m eet in a hotel bar in Paris. Match the questions to the correct picture a-h. Exercise 3 Write questions for the answers on the right. 1. W here/from ? W here do you come from? I come fro m Santiago, in Chile. Transfer Prepare five o r six questions to ask a friend about h is/her work o r studies. Use the present sim ple tense. vk.com/bastau 17 UNIT The Present Continuous vs. The Present Simple Be The present continuous The present simple The present tenses and the past tenses A Sample sentences Luc: Brigitta, w hat do you do? Brigitta: I w ork as a m arketing director in Heidelberg, but at the m om ent I'm working in Osnabriick. Luc: So, w here do you live? Brigitta: My fam ily lives near Heidelberg, butat present I'm staying in a hotel in Osnabriick. B Form R em em ber these differences between the present continuous and the present sim ple: C Uses We use the present continuous to ta lk about: vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Read the dialogue below. A jo u rn a list is talking to a representative o f Chemco Ltd. Put the verb form s in sentences 1-7 into the correct box. The firs t has been done for you. Question Present continuous Present simple Exercise 2 Complete the dialogue below between a consultant and a m arketing manager. Exercise 3 Complete the spaces in the short dialogue below about a bank, Credit Bank International. Use the correct form o f a verb from the box. A: W hat________________________ ? B: We___________ 10 new branches in Argentina and Chile. A: ___________ the bank c u rre n tly ____________ branches only in Buenos Aires and Santiago? B: Yes. A: B ut not Brasilia? B: No, w e ___________ in Brazil yet. A: ___________ Pablo Hernandez_____ ______ here this week? B: Yes, h e ___________ these meetings. Transfer Write five sentences about yo u r own current activities. Use both the present sim ple and the present continuous. vk.com/bastau 19 UNIT Positive and Negative Imperatives See also Unit 56 Commands - positive and negative B Form The positive im perative has one part: The negative im perative has two parts: infinitive don't + infinitive go dont go m ake don t m ake do don t do discuss don t discuss be don t be C Uses We use the positive im perative to te ll one o r m ore people w hat they m u st do o r they can do We use the negative im perative to te ll one or m ore people w hat they m u st not do: Note We can use please w ith im peratives to make them m ore polite. 20 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Underline positive im peratives and(^ircle)negative imperatives in the following instructions to visitors to a factory. Please arrive at 10 o clock prom pt. Present your identity papers to the se curity o ffice r at the gate. Do not park your car in the staff ca r park. Please go where the se curity officer te lls you. He w ill give you an o fficial pass. W alk to the reception. Present your o fficia l pass to the receptionist. Do not e nte r the office block. A guide w ill come to m eet you. Please w ait in reception. Do not sm oke. Do not take photographs. Exercise 2 Give an imperative [positive o r negativeI for each o f the following. Use the verb in brackets. 1. (wear) 2. (put in] 3. 6. 9. 'l I oo <g>o o OOO (M ) & OOO o o ooo X o o o ----- FREEPHONE Exercise 3 Put the verbs in the box into the correct positive o r negative imperative form. Transfer What imperatives, positive and negative, have you seen recently in yo ur home town o r in the place where you live and work? vk.com/bastau UNIT The Past Simple Positive See also Unit 12 The past simple negative Unit 13 The past simple question A Sample sentences Last year we opened an office in Berkeley. The company released its report a few w eeks ago. Sales increased by 40% in the first half of last year. B Form The past sim ple positive has one part: past tense S ubject I made you presented h e /sh e /it called th e com pany/the d ep artm en t (= it) prepared th e m a n ag er/th e boss (= he/she) read we m et you looked they visited the com panies/the d ep artm en ts (= they) did the m an ag ers/th e w o rke rs (= they) w rote C Uses We use the past sim ple to ta lk about an activity at a definite tim e in the past: We started the business about a yea r ago. He bought the company in 2001 for $ 5 billion. Last year he joined the company as m arketing manager. Note We use the past sim ple w ith these expressions: 22 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Give the past sim ple form o f the following verbs. Exercise 2 Below is p a rt o f a report from Baxmer, a pharm aceutical company. Underline six mistakes and correct them. stopped On 25 A pril this year we stop production o f Arpol, a treatm ent fo r migraine. Arpol production begin in 2004 and early sates was very impressive. However, Belpharm Ltd did launch the Calpem range three years ago. This product was taking a 30% m arket share in the firs t two years. A t firs t we agree to continue with Arpol. Now the situation is different. Exercise 3 Look at the time line below showing events over ten years for Metfan S.A., a Swedish furniture maker. Make sentences with the verbs given. Example: Metfan started business 11 years ago. years -11 -1 0 -9 -8 -7 -6 -5 -4 -3 -2 -1 Transfer Make five sentences about a business you know well or businesses in your country. vk.com/bastau 23 UNIT The Past Simple Negative 1 J Unit 11 The past simple positive 1 mgm Unit 13 The past simple question Unit 31 Do A Sample sentences Last year we didn't s ell as many products. I was disappointed because I didn't reach the target. In 2002 the company didn't have the skills it needed to do this. B Form The past sim ple negative has two parts: didnt + infinitive I didn't live you didn't work he/she/it didn't produce the organisation (= it) didnt employ the director (= he/she) didn't discuss we didn't meet you didn't know they didnt like the teams (= they) didnt . __ prefer the employees (= they) didn't make C Uses We use the past sim ple to ta lk about an activity at a definite tim e in the past: The business didn't grow much last year. This product didn't exist two years ago. I didnt go to w ork yesterday because I w asn't w ell. Note We use the past sim ple w ith these expressions: 24 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Underline the past sim ple negatives in the following. I joined th is com pany five years ago. It was a d iffic u lt tim e. The com pany was not in a very good state. We d id n t have a cle a r m anagem ent stru ctu re . Our local m a rkets were not very good. Our m a rke tin g d id n t include A m erica or the Pacific regions. We d id n't have any cle a r m a rketing strategy. Now, thing s are very different. Exercise 2 Read the text below. Change the past sim ple positives to negative. Then make the negatives positive. New products were cheap to develop. We spent a lot of m oney on research. Our m arket share increased in the early 2000s. The com pany made m any good products. Chemco d id n t buy the company. There w a sn t a big change in the organisation. The new m anagem ent d id n t w ant to change everything. Most of the old m anagem ent d id n t leave. Things did n t improve. Now, we are very o ptim istic. Exercise 3 Look at the delivery schedule for an order with Interfood nv, a Dutch frozen foods company. Unfortunately the order went wrong: on January 15, Interfood did not prepare the order. Complete the sentences below. Write what did not happen. 3. On January 17 th e y_______________________ 6. So E spofrigo_______________________ Transfer List things that you did not do ... yesterday/the day before yesterday/last Saturday/last week/last m onth/three years ago/in 2005/when you were young. vk.com/bastau 25 UNIT The Past Simple Question A Sample sentences Did you see that promotion for the new product? W here did you buy your new computer? Why did you leave the company? B Form The past sim ple question has two parts: did + infinitive We put the subject between part 1 and part 2: did I present? did you m ake? did h e/sh e/it solve? did the co m p u te r (= it) analyse? did the co nsu ltan t (= he/she) reach? did we com pete? did you look? did they visit? did the sp ecialists (= they) fix? did the m achines (= they) prepare? C Uses We use the past sim ple question to ask about an activity at a definite tim e in the past: When did you arrive in England? Did you m eet the managing director when she was in New York? How long did you w ork for the company? W hat did you say to her? IS5351I Match the question on the le ft with the appropriate answ er on the right. 1. When did you arrive here? a. Yes, it was very com fortable. 2. How long did the jo u rne y take? b. No, unfo rtu na tely I did n t. Exercise 2 B ill Klemens went to Malaysia on a business trip. He is discussing the trip with a colleague, Joelle Kee. Complete the spaces in the dialogue. Exercise 3 A manager returns from a trip and asks her assistant about yesterday. Write questions for the items below. Use the words in brackets. 1. x 1, k 4. M r Fish phoning about order. 7 1N (the m aintenance eng in e er/ (M r Fish/phone?) re p air/th e copier?) 5. VISA APPLICATION URGENT - Caracas Report John: please read im m ediately. 6. Write to Kongo Club. Larish Ltd to collect order. Pay on collection. (you/w rite/to the Kongo Club?) (Larish L td /co lle ct th e ir order?) (they/pay?) Transfer Prepare six questions to ask a colleague. Use the past sim ple tense. vk.com/bastau UNIT The Past Continuous See also u Units 1,2 Unit 20 Be The present tenses and the past tenses B Form The past continuous positive and question have two main parts: the past tense of to be + infinitive .. .ing .......De ..to . .... Subject infinitive.. Jng l/he/she/it was making was l/he/she/it making? you/we/they were presenting were you/we/they presenting? the company (= it) was preparing was the company (= it) preparing? the manager (= he/she) was reading was the manager (= he/she) reading? the departments (= they) were doing were the departments (= they) doing? the workers (= they) were discussing were the workers (= they) discussing? gative form C Uses We use the past continuous as a tim e fra m e fo r a n o th e r activity: ------------------------------ x -----------------------------. this time last week 28 P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Read the extract from a D irecto rs speech at the Annual General Meeting o f Pace PLC. Underline all form s o f the past continuous. Label them positive IP), negative (N), o r question [Q). W hat was happening a few years ago? Well, the com pany w a sn t doing very w ell. During the 1990s we w ere com peting w ith many suppliers. We had a s m a ll turnover. Then everyone was thin kin g about m ergers and takeovers. In the early 2000s we were operating in a very d iffe re n t m arket. There w ere only fo u r large com panies. A ll fo u r were m aking big profits. We were a ll doing w ell. Exercise 2 A Safety Officer is talking to a technician about a fire at a factory Complete the dialogue. Use the words in brackets. Exercise 3 Look at the table below which describes Sally K lin e s day Write where she was and what she was doing. place action At 10.30 Sally was at the 1. 10.30 a irp o rt check in airport. She was checking in. Transfer Make sentences about yo urself o r a company o r institution you know. Begin with phrases like This time Last y e a r ... and In the s u m m e r__ Use the past continuous where possible. vk.com/bastau 29 UNIT The Present Perfect Simple A Sample sentences M artina: How long have you w orked here? Andrea: I have been here for five years now and Erica has been here since 2001. B Form The present perfect sim ple positive and question have two parts: has/have + the past participle Negative form ------ -~ Subject has/have not past participle l/you/w e/they have not prepared h e /sh e /it has not helped th e d ire c to r (= he/she) has not arrived th e em ployees (= they) have not discussed C Uses We see the present perfect sim ple as a tense w hich lin ks the past and the present. So we use the present perfect sim p le to ta lk about: 2 . an activity w hich happened at a tim e in the past - but we dont know exactly when - w ith a result in the present: I have visited the US several tim es. (Present result, I know many places.) P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Make sentences from the words betow. See the exampte. M r Flaherty has studied economics. Exercise 2 Look at the graph betow. It shows the p ro fit perform ance fo r fo u r products. Write how long each product has been profitable. Use the verbs in the box. profit P ro du ct A Exercise 3 Answ er the following questions. Give long and sh ort answers. 3. Has your com pany/school/university made any lin ks w ith foreign companies? Transfer Ask a friend questions about travel/w ork/studies/etc. like the ones above. Write down the answers. H e /s h e ... vk.com/bastau 31 UNIT The Present Perfect Continuous 16 See also Unit 15 The present perfect simple Unit 17 The present perfect with for, since, ever and never Unit 18 The past simple vs. the present perfect simple A Sample sentences Production has been declining since 2000. The company has been working on this project for several years. Profits are falling; so we have been looking at ways of cutting costs. B Form The present perfect continuous positive and question have three parts: has/have + been + infinitive .. .ing (has/have been is the present perfect of to be) H m m u m l/you/w e/they have been living have l/you/w e/they been producing? h e /sh e /it has been w o rkin g has h e/sh e/it been studying? discussing . Negative form Subject has/have not been Infinitive .. .ing l/you/w e/they have not been doing h e /sh e /it has not been helping C Uses We use the present perfect continuous to ta lk about: 2. an activity w hich happened at a tim e in the past - but we dont know exactly when it happened: The company has been doing extra tests on the systems. In many cases, the m eaning of the two present perfect tenses is the same. He has w orked for the airline for 25 years = He has been working for the airline for 25 years. Exercise 1 Match the phrase on the le ft to a phrase on the rig h t to make six sentences. Exercise 2 Write one sentence fo r each o f the five projects mentioned in the notes below. The firs t one has been done fo r you. Exercise 3 Comptete the following le tte r from an Executive of Euro TV, a Paris-based television channel. He is w riting to a colleague in Japan. Dear Hisashi, Thank you for your letter. EuroTV________(develop) links with companies in other countries. In particular w e__________ (discuss) programme making with networks in Belgium and Germany. We_________ (talk to) small, private companies. So far we have not tried to set up links with companies outside Europe. Many American TV stations_________ (examine) ways to work in Europe. Transfer Write sentences about four things that you started in the past and which are s till continuing. vk.com/bastau 33 UNIT The Present Perfect with For, Since, Ever and Never 17 See also Unit 15 The present perfect simple Unit 16 The present perfect continuous Unit 18 The past simple vs. the present perfect simple Business File 6 Irregular verb table We use the present perfect sim ple and the present perfect continuous w ith for and since: I have w orked for ABC for many years. I have w orked for ABC since 1990. I have been working for ABC for six years. I have been working fo r ABC since 1st January. We use the present perfect sim ple w ith ever and never: Have you ever visited the trade fa ir in Hannover? No, I have never been there. 1. W ith the present perfect both for and since show the duration of an activity. In both cases it started in the past and continues to the present: past present 5 years We have been working on this technology for five years, (period of tim e w ith for) We have been working on this technology since 2005. (point of tim e w ith since) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Match the questions on the Left with appropriate answers on the right. 1. How long has she w orked Yes, we made heavy losses in the 1970s. fo r S m ith C allm an Ltd? 2. How long have you Yes, but I've never visited the USA. known P eter Lomax? 3. Have you ever lived c. She's been w ith the com pany since 1994. in a d iffe re n t country? Exercise 2 A shampoo, Shine Plus, is not selling well. The Product Manager is talking to a marketing consultant. F ill the spaces. Use words from the box. for since [21 ever never long have [21 has [21 been Exercise 3 Kate and M att m eet in an a irp ort departure lounge. They are waiting for the ir flights. Complete the dialogue below. Use for, since, ever, never. Transfer Ask someone six questions with ever or how Long. Get answers with never, for and since. vk.com/bastau 35 UNIT The Past Simple vs. The Present Perfect Simple 18 I See also Units 11, 12, 13, 14 The past Units 15,16, 17 The present perfect Business File 4- British English vs. American English Business File 6 Irregular verb table A Sample sentences I dont think we have met. My name is D ieter S tallkam p. I've only recently arrived from Stuttgart. So, when did you join the company? I started at the beginning of the year. B Form When we ta lk about or ask about an activity at a definite tim e in the past, we use: + - past tense didn't + infinitive did + subject + infinitive past simple positive past simple negative past simple question When we ta lk about o r ask about an activity in the past w ith a lin k to the present, we use: + - ? have/has + past participle havent/h as n t + past participle have/has + subject + past participle present perfect present perfect present perfect simple positive simple negative simple question C Uses Look at th is m in i-dialo g ue in the past sim ple: A: So when did you start the company? B: W ell, we opened the first sales office five years ago. At first, demand for our products was slow. Then we placed an advertisem ent in Eurow eekly. A: And did that help? B: Yes we started to receive enquiries from w holesalers. They didnt w ant to buy from larg e r companies because th e ir deliveries w ere very slow.So, they came to us. 36 | P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Look at the sentences betow. Underline examples of the sim ple past and(^frcle)examples o f the present perfect. 1. The com pany has sold its London offices. 2. The Managing D irecto r resigned three years ago. 3. I have not read the new spaper today. U. A rival m a n u fa ctu re r has bought the company. 5. The to p -s e llin g product made over 3m last year 6. Many shareholders have sold th e ir shares. 7. M arket analysts have estim ated com pany tu rn o ve r at over 40m. 8. Axam Ltd did not im prove its sales. Exercise 2 The graphs below show the turnover, R&D costs and share value for Lander Ltd. Complete the text with the correct form o f the words in brackets. This shows the turnover fo r Lander. It _ This shows that the value o f Lander shares Ideclinel between 2004 and 2006 but it _____ _ Iincrease1 between 2004 and 2005. [risej since 2006. The com pany______ [spendl I t _______ [m aintain] the same level since 2005. more on R&D. Com petitors share values_______ Iincrease}. The in cre ase _______ (not/be) very large. Exercise 3 Complete the em ail below with the correct form o f verbs in the box. | Date: ' 20 May 2 0 ... 1 To: | mike.jones@abcplanninq.com From: | t.robson@tkdengineering.com 1 Seta plant closure 1 Dear Mike We to close down the Beta plant for three weeks. On Tuesday maintenance inspectors__________ _____ problems w ith the machines. I __________ the inspectors' report. ________a detailed study. A few weeks ago w e __________ the pump. It is Yesterday w e ________ possible that the pump ______ again. W e__________ production to our other plant. Fortunately, w e ______ much production. I w ill telephone you next week w ith more information. Best regards Transfer Write a few sentences describing your recent activities. Use the past simple and the present perfect. vk.com/bastau 37 UNIT The Past Perfect See also Units 11-13 The past simple Business File 6 Irregular verb table A Sample sentences He had w orked as a m arketing assistant for many years. Then he changed jobs. Had you used this technology before you came here? The club had not made a profit during the five years before the m erg er took place. B Form The past perfect positive and question have two main parts: had + past participle Negative form had not past participle l/h e /s h e /it had not made you/w e/they had not presented the com pany (= it) had not prepared the m anager (= he/she) had not read the w o rk e rs (= they) had not discussed C Uses We use the past perfect to ta lk about an activity at a tim e before the past: -J___________ I___________ u be head o f com pany sale o f com pany A fter he had been head of the company for three and a half years, he sold it. past perfect past present !< r ------------ Note We can often use the past sim ple instead of the past perfect: I called him a fte r I had arrived in the office = I called him a fte r I arrived in the office, P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Underline examples o f the past perfect in the sentences below. 4. Mrs Maw had not finished opening her post when John cam e in. 5. The w o rk had not been com pleted before the Vice President arrived. Exercise 2 Use the words below to make sentences. Include a past perfect tense contrasted with a simple past tense. Use positive (+), negative (-) and question form s (?]. 1. The com pany/test/new produ cts/be fore/la u nch /on the m a rke t The company had tested the new products before it launched them on the m arket. (+) The company hadn't tested the new products before it launched them on the m arket. (-) Had the company tested the new products before it launched them on the m arket? (?) Exercise 3 Fred has problem s with a photocopier. Complete the dialogue. Tom: What happened? Fred: Before the machine broke down, I ________ Imadel 100 copies. Tom: Then what? Fred: When I _____________________ (done) 100, the paper jam m ed. Tom: What did you do? Fred: When I __________(clearj the paper, I pressed the s ta rt button. Tom: Then? Fred: I thought I /solveI the problem. But I __________________ (not/notice] another problem. _ Transfer Write sentences contrasting events affecting your work o r studies. Example: When I arrived in Tanzania I had already learnt Swahili. vk.com/bastau 39 UNIT The Present Tenses and The Past Tenses A Sample sentences John: W here do you come from , Diane? Sonia: I was born in Scotland, but I live in Finland now. John: Thats interesting. My brother has lived in Finland for five years. How long have you lived there? Sonia: I moved there three years ago. John: And do you like it? Sonia: Yes. But unfortunately, I dont live in the capital. I commute to the office every day. It takes about an hour. So, we are looking for a flat near the centre. Have you ever been to Finland? John: Yes, many tim es. In fact I prepared a big construction project there two years ago. But w hile I was working on it, the client w ent bankrupt. Fortunately, we had not invested too much money. B Form R em em ber these d iffe re n t fo rm s fo r the present tenses and the past tenses: Present fo rm s of to be = am /is/are Past fo rm s of to be = w as/w ere Present perfect form s of to be = have been/has been C Uses Look at the differences in m eanings between the follow ing sentences: I usually w ork w ith clients in the catering industry, but at present I am w orking w ith a music company. [present sim ple vs. present continuous) How long have you lived in Jerusalem , Joel? I moved here three years ago. (present perfect vs. past sim ple) Exercise 1 Look at the following extract from a newspaper report. Label the tenses as follows: present sim ple iPresSj, present continuous [PresCl, past sim ple (PastSl, past continuous (PastCl, present perfect sim ple IPPS], present perfect continuous IPPCJ, past perfect [PastPl. Exercise 2 Use the prom pts below to make a dialogue. A B 1. P eter/w here/w ork? Peter, w h e re __________ ? I __________ Frobo Ltd. 2. how long/there? How lo n g __________ ? I __________ two years. 3. w here/before/Frobo? W here__________ before Frobo? Allen Brothers. A. why/change? Why__________ ? Because the m a rk e ts __________ falling and the com pany__________ going bankrupt. 5. why/choose/Frobo? Why__________ Frobo? I __________ [w ork] there before I joined Allen Bros. Exercise 3 Maria is showing a visitor round h er distribution company, Largo S.p.A. Make sentences using the prom pts below. 1. M a ria :_______________________________ 4. M a ria :________________________________ (from January u n til June last ye a r/b u ild / (in D ecem ber/buy/new lorries) new office block) Transfer Prepare some questions to ask a friend about h is/her work o r studies. Together, discuss what you have both done and are doing now. vk.com/bastau 41 UNIT The Future with W ill and Shall 21 See also Unit 22 The future with going to vs. present continuous Unit 23 The future with w ill vs. going to vs. present continuous B Form The fu tu re w ith w ill has two parts: the m odal w ill + infinitive We often use the sh ort fo rm s in spoken language; we som etim es use the m in in fo rm a l w ritte n language: I'U check the figures this afternoon. Sales w on't recover before next year. C Uses 1. We use the fu tu re w ith w ill to ta lk about futu re facts: Prices w ill rise by 3.3% next month, [not: will to rise} When w ill the product be available in stores? The company said it w on't perform tests on animals. Exercise 2 Below is p a rt o f a presentation by Tom Kip, from LM F Ltd, a food manufacturer. Tom is describing the days program m e to a group o f visitors from France. Put the sentences in the correct order. Underline any uses o f w ill o r sh all. The firs t has been m arked 11) fo r you. a. Well have lunch in a local re stau ra n t at about 1 o'clock. b. Well finish at about U oclock. c. A fte r th is introduction, w e ll have a sh ort to u r of the plant. d. So, s h a ll we begin the tou r? e. Then before coffee w e ll show you a film about o u r d istrib u tio n system. f. Well have coffee at 11, then w e ll have a m eeting w ith Ken Levins, o u r Product Manager. g. Right, now Ill explain the program m e fo r the day. (1) h. A fte r lunch w e ll discuss fu tu re plans. Exercise 3 Complete the exchanges below. Use a form o f w ill o r shall in yo ur answer. Transfer A nsw er the following questions about yo ur work. Use a form o f w ill o r shall. W hat do you plan to do tom orro w ? W hat about getting a big pay rise next year? Where are you going on Saturday? W hatll you ta lk about tom orro w ? Who w o n t you see this evening? If the com pany has problem s, w ill you lose your job? vk.com/bastau 43 UNIT The Future with Going To vs. Present Continuous 22 See also Unit 21 The future with will and shall Unit 23The future with will vs. going to vs. present continuous A Sample sentences When are you going to give us a decision? We are going to discuss m arketing strategy. I am leaving for Europe at the end of the w eek. We are not selling as much to Asia. B Form The fu tu re w ith going to has three parts in the positive and question: to be + going to + infinitive Negative form Sub f j j ; e not g to I am not going to you/w e/they are not going to come h e /sh e /it is not going to For the fo rm s of the present continuous (positive, negative and question), see Units 3-5. C Uses 1. We use the fu tu re w ith going to to ta lk about intentions: I am going to do $2000 in sales today. (It is my intention.) The company is going to build 1000 cars a year. (It is o u r com panys intention.) 2. We use the fu tu re w ith the present continuous to ta lk about personal fixed plans or schedules: Next month we are launching a new online service. (It is o u r fixed plan.) When are you flying to Jakobsberg? (When have you fixed to fly there?) Note It is im p o rta n t to specify a fu tu re tim e, when you use the present continuous w ith a fu tu re meaning. When are you flying to Jakobsberg? I'm flying there tom orrow m orning. Exercise 1 Read the text below. Underline once any uses o f going to + infinitive Iintention1 and underline twice any examples o f the present continuous tense Ifixed plans]. A: Were setting up a new d istrib u tio n netw ork in Asia. Were not using our own staff. Were going to use local agents. Were going to re c ru it top quality experts. Were exam ining som e possible applicants next week. Were going to run psychom etric tests as p art of the re c ru itm e n t procedure. Im m eeting colleagues la te r today to fin alise plans. Exercise 2 A custom er is telephoning a mobile phone rental company. Complete the conversation. C aller: Well, we re having lhavel a conference in three months. I need some phones. PhoneCo: Fine. How many p eo p le_________Icomel? Caller: Well, __________ Isend out150 invitations this week. PhoneCo: That's fine__________(hire) phones fo r everyone? Caller: No, ju s t about half', I think. PhoneCo: A n d __________I need I anything else, faxes or modems? C aller: N o ,______________Inot/plan] anything complicated. Exercise 3 Look at the project plan fo ra jo in t venture between two companies, KJE Ltd and Weisskopf GmbH. Complete the memo below. Use the correct form o f the words in the box. Put them into the present continuous or the going to form. Memo To: HJ From: KP Re: KJE/W eisskopf Joint Venture As you know, w e __________ a new engine w ith W eisskopf GmbH. W e _______ D epartm ent m eeting next week and I __________ to Brem en on the 16th. We contract th e n ___________ to the m eeting? T h ats all. Good luck. Transfer Write sentences on [al your intentions, and Ibj yo ur fixed plans. vk.com/bastau UNIT The Future with Will vs. Going To vs. Present Continuous See also Unit 21 The future with will and shall Unit 22 The future with going to vs. present continuous A Sample sentences A: W hen are you going to launch the new product? B: It wont be ready before June. A: W hen are you going to fix the price? B: For the rest of this year we are offering them at a special price. This w ill increase demand. A: Are you going to appoint a m arketing director? B: Yes, we are interview ing the candidates in two weeks. B Form Remember 2. You need the verb to be before going to and the present continuous form s. For m ore in form ation on the form s, see Units 21 and 22. C Uses Look at the differences in m eanings between the follow ing pairs of sentences: W hat are you going to do tom orrow? (What do you intend to do?) (future w ith going to) W hat are you doing tom orrow? (What are your fixed plans?) (future w ith present continuous) We are going to launch a new cable channel at the end of this year. (We intend to la u n c h ...) (future w ith going to) The official launch w ill take place in New York on Friday. (The launch date is a fact.) (future w ith will) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Read the dialogue below. N um ber the future form s 1-6. Then write the num bers in the box. tiorts/going to Facts/s Exercise 2 4 jo u rn a lis t is interviewing a director o f a paints m anufacturer, Byant Ltd. The company is in trouble because last week chemicals polluted a local river. Complete the dialogue with appropriate future form s o f the words in brackets. Exercise 3 Complete the email below. Use the verbs in the box in appropriate future forms. To: ricardo.benato@eurosales.com From: | jeanclaude.isias@papin.com Dear Ricardo, Representatives of Harkes Ltd next week. They the plant and then we a meeting at 2 o'clock. We_________ our plans for the next five years.They know __ our Sales Division to Brussels. They don't know that this__________ in December this year. I them before the meeting. Best Regards Jean Claude Isias (Papin S.A.) (1)4577 3371 Transfer Discuss future plans, intentions and events with a colleague. Ask h im /h e r questions. vk.com/bastau UNIT Conditional I ik A Sam ple sentences See also Unit 25 Conditional fl B Form A cond itio n al sentence has two parts: the if clause + the m ain clause In cond itio n al I sentences, we use: C Uses A co nditional I sentence shows a real possibility: If Ahmed leaves now, he will be back in Glenvale before lunch. (We d o n 't know if Ahm ed w ill leave now; but if he leaves now, there is a real possibility tha t he w ill be in Glenvale before lunch.) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Label the main clauses IMCI and underline them with a continuous line I_____I Label the if clauses 11Cl and underline them with a dotted line (........1. The firs t one has been done for you. 5. We can take our tim e, unless Chemco m akes a sudden o ffe r fo r Axam. Exercise 2 Make conditional sentences based on these prompts. Moda PLC is a fashion clothes manufacturer. Here is an email on plans for next year. Complete the spaces with appropriate clauses from the box. unless the economy recovers our products w on't sell we w ill do better we w ill produce If we have Date: | 29/03/11 To: I jay.taylor@modaplc.com From: [ g.sartori@modaplc.com Subject: | Next season's forecast_________ Dear Jay, Transfer Make four conditional sentences about your work o r yo ur studies. Use if and unless. vk.com/bastau UNIT Conditional II See also Unit 24 Conditional I A Sample sentences If ITCorp accepted our offer, both companies would benefit. The results would improve, if we spent more time on planning. What would you do if you lost your job? Unless you left now, you would not arrive in time. B Form A cond itio n al sentence has two parts: the if clause + the m ain clause In cond itio n al II sentences, we use: If we sent the mailshot this week, it would arrive next week. (= cond itio n al II) If we didn't send the mailshot this week it wouldn't arrive in time. (= cond itio n al II negative; here we ca n't use unless) C Uses A cond itio n al II sentence shows a rem ote possibility: If Ahmed left now, he would be back in Glenvale before lunch. (We dont know A hm eds plans, but there is only a remote [sm all] possibility th a t he w ill leave now.) P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Underline three conditional II sentences in the extract o f a report below. Label the if clauses [1C] and the main clauses [MC] in the three conditional II sentences. I f we sell Mago in Asia i t will help to establish our brand name. But i f we se t up our own d istribu tio n network it would cost too much. Unless we spent millions, we wouldn't make any money. I f we use local people i t will be much cheaper. I f Mago does well in Asia, then we'll Exercise 2 Make conditional II sentences with these prompts. 5. M ary/be/happy//Fred/resign 6. w e /in crea se /th e R&D budget to $50 0 m //w e/b e /th e m a rke t leader Exercise 3 Two colleagues are on a business trip. They are discussing travelling for work. Complete each sentence by adding a clause from the box. Transfer Think o f some remote possibility events in yo u r work o r personal life. Write five conditional II sentences. vk.com/bastau 51 UNIT Tense Review 1 See also Units 1 to 25 All tense forms FUTURE I am going to finish the project next month, i am leaving Germany at the end of the year. But I will be back. P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Match the question on the le ft to the correct answ er on the right. Then p ut brackets round the part o f any answ er that could be le ft out in a sh ort answer. The firs t one has been done fo r you. 6. How long have you been doing that? / f. Im preparing a cu sto m e r survey. 7. What are you doing th is evening? \ -g - (I live) near Liverpool. 8. What are you going to do next sum m er? h. Ive been doing it fo r about two weeks. 9. If you had a com pletely free choice, i. Im m eeting a friend in a bar. w here w ould you w ork? j- I began in January this year. 10. If you learn English perfectly, how w ill it help you most? Exercise 2 Imagine you are interviewing someone fo ra job. You have to complete the following personal details form. What questions would you ask? Begin with the given word on the right. Transfer Write a paragraph about yo urself with s im ila r inform ation to the personal details above. Include answers to the following questions. vk.com/bastau UNIT Tense Review 2 See also Units 1 to 25 A ll tense forms P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Read the following dialogue between a jo u rn a list and Sydney J. Clement, Vice-President ofA xoil Inc, an American oil company Write the sentence num bers in the correct box below. . . . Question p re s e n t past __ _____________ _.. fu tu re Exercise 2 Use the inform ation below to complete sentences about Ardanza Pascual, a Spanish foods manufacturer. Use the given prompts. Transfer Write one o r two paragraphs about the history and the present and future activities o f a company you know well. vk.com/bastau UNIT Infinitive + To 28 See also Unit 30 Infinitive + to or verb ...ing A Sample sentences I would like to have a career in hotel m anagem ent. The company agreed to lease the building for 20 years. It is im portant to listen to employees. B Form The infinitive + to is a form of the verb. It is two words: to + infinitive, e.g. to help, to produce, to negotiate, etc. C Uses We use th is infinitive fo rm : a fte r som e verbs a fte r som e adjectives. 1. W ith verbs: They w ant to reduce costs. The firm plans to spend 600 m illion on a new processing plant. We hope to advance in the m arket by providing a b e tte r service than our rivals. Note We usually lin k two verbs in th is way, but see also Unit 29. We use an infinitive + to a fte r these verbs: Note We often lin k an adjective and a verb in th is way, but see also Unit 29. We use an infinitive + to a fte r these adjectives: P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Underline the infinitives + to in the following extract from a letter. coming. T ell him, o f course, we'd like to m eet him a n o th e r tim e... Exercise 2 Match the phrases on the le ft with a suitable infinitive + to on the right. Exercise 3 Here is p a rt o f a speech to the Annual General Meeting o f the B ram w ell Group, by the Chairman, William Foss. He is leaving the company a fte r 20 years. F ill the spaces with the infinitive + to. Use the verbs in the box. Transfer What do you think? Complete the following with an infinitive + to. vk.com/bastau 57 UNIT V erb...ing See also Unit 30 Infinitive + to o r verb .. .ing A Sample sentences The company will start producing the screens next year. Please stop sending me unwanted emails. 60% of employees say they are interested in receiving more information and training. The firm interviews several candidates before making a decision. B Form Verb .. .ing is a form of the verb w ith one part: infinitive + ing, e.g. living, working, helping, producing, etc. C Uses We use the verb .. .ing form : a fte r som e verbs a fte r prepositions. 1. W ith verbs: They enjoyed working with each other. The company announced that it will stop selling the drug next year. He suggests advertising in a local newspaper. Note We so m e tim e s lin k two verbs in th is way, but see also Unit 28. We usually use a verb .. .ing a fte r these verbs: 2. A fte r prepositions: He is interested in negotiating a deal, [not: in negotiate) I look forward to meeting you. [not: to m eet, because to here is a preposition) Before hiring any specialist, a check on background and experience is necessary. [not: before to produce) Note We always use verb .. .ing a fte r a preposition. P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 In the emait betow , underline fou r examples o f the verb ... ing used a fte r a verb o r a preposition. Date: 112.1.2010_________________________ To: | george.macdonald@advertiseme.com From: I sophie.allen@advertiseme.com Subject: Shello sales campaign Dear George We are planning a meeting next week. We are interested in hearing colleagues' views on the sales campaign for the Shello range. Before attending the meeting, please read the interim report, Shello Advertising SA/JD 3421JD. I suggest inviting the marketing group to attend the meeting, but we should avoid having long discussions about individual markets. Regards Sophie Allen Exercise 2 Look at these sentences from five different tetters. Complete the spaces with appropriate verb . . . ing forms. Exercise 3 Ben Massey is asking fo r advice from a colleague. Complete the spaces with the verb ... ing form. Choose from the verbs in the box. Transfer Write sentences about yo urself o r yo ur work with verb . ..ing form s a fte r the following words: interested in, before, after, regret, suggest, avoid, stop. vk.com/bastau 59 UNIT Infinitive + To or Verb .. .ing 30 See also Unit 28 Unit 29 Infinitive + to V e rb ...ing A Sample sentences Do you like working at the hotel? Do you like to w o rk on new projects? We w ill continue to introduce new products. We w ill continue introducing new products. B Form A fte r som e verbs we can use: Verb .. .ing o r infinitive + to e.g.: I have started writing my report. I have started to w rite m y report. C Uses S om etim es the m eaning is the sam e; so m e tim e s it is different. 2. A d iffe re n t m eaning We can use both fo rm s a fte r these verbs, but w ith a d iffe re n t meaning: Note We would like to launch our new range in the autum n, [not: we would like launchi P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Choose the correct alternative to complete the sentences below. In two cases, both are possible. Exercise 2 Read the sentences given here. Then choose which meaning is the correct one. Exercise 3 H arry Cox is a purchaser fo ra B ritish manufacturer. Here is p a rt o f an em ail he wrote to a friend while sitting in a bar near the Colosseum in Rome. Complete the spaces with the correct form o f a verb from the box. @ 0@ ............... .......... ............ ........................- ......................... .......................... * ' O [X Transfer Make sentences about a colleague or about yo urself using the following verbs: start, Love, intend, hate, try, remember. vk.com/bastau UNIT Do 31 See also Units 7,8 Present simple negative and question Unit 10 Positive and negative imperatives Units 12,13 Past simple negative and question Unit 46 Make vs. do Unit 52 Negative statements A Sample sentences A: Does M r Zim m erm an w ork for your company? B: No, M r Zim m erm an doesn't w ork here any longer. A: W hy did he leave? B: He didnt fit into our corporate culture. B Form The a uxilia ry do has two m ain tenses: the present and the past. (See also Unit 46 fo r the fu ll verb do.) We use the auxilia ry to form questions and negatives in the present sim ple and past sim ple: W here do you work? W hen did you join the company? He doesn't w o rk here. He didn't like the atm osphere. The fo rm s of the auxiliary do are: Past simple uestion form ive form C Uses We use the auxilia ry do in: 1 - present sim ple questions: W here do you live? 2. present sim ple negatives: The company doesn't announce products until they're actually at the dealers. 3. past sim ple questions: W hen did you join the fam ily business? 4. past sim ple negatives: We didn't get financial help. 5. negative im peratives: Please don't mention this to Fred. P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Choose the correct alternative in the sentences below. Exercise 2 1. Make the following sentences negative. a. He likes his job. b. We s e ll co m p u te r softw are. c. He w o rks fo r RYG. Exercise 3 Write appropriate questions and answers for the prom pts below. N o ___________a Yes, Transfer Ask a friend three questions using do or did. Write four sentences about yourself using don't or didn't. Tell a friend not to do something. vk.com/bastau UNIT W ill and Would 32 See also Unit 21 The future with will and shall Unit 23 The future with will vs. going to vs. present continuous Units 24, 25 Conditionals I and II A Sample sentences A: Would you help me, please? B: Yes, certainly. A: W ill you fill in this form and return it to us as soon as possible? B: Of course. B Form W ill and would are m odal verbs. Would is the past tense form of w ill. A fte r w ill and would, we use the infinitive w ith o u t to: We w ill send the goods im m ediately, [not: we w ill to send) Would you sit down, please, {not: would you to sit down) The negative sh o rt fo rm s are: wont (= w ill not) and wouldnt (= would not) The o rder w ont be ready before Friday. C Uses We use w ill and would: 2. to express conditions: If the plan wins approval, we w ill begin building next year. If high unem ployment occurred, wages would fall. (See Units 24-25 on the conditionals.) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Read the following sentences. Say if they are examples o f the future IF], conditions [C], offers or willingness 10] o r requests IR]. Exercise 2 Complete the following negotiation between a buyer and a supplier. Use appropriate positive or negative form s o f w ill or would. Use short forms, where possible. Exercise 3 A custom er phones the A fte r Sales Departm ent ofAXK Ltd with a problem. Choose the correct line from the box to complete the dialogue. a. I'm not sure if tha t w ill be possible. W ill you hold on please? b. Okay. Well so rt it out. c. Right, Ill ask an e ngineer to visit you. d. Okay. If you use the em ergency sw itch on the back, the lig h t w ill come on. e. Hello again. Som eonell be there at 2 p.m. tom orrow . f. W ill you give me your address, please? Transfer Write sentences which include a form of w ill o r w o u ld and which are: an offer to help, a request, a conditional, a reference to the future. vk.com/bastau UNIT May and Might 33 See also Unit 34 Can and could Unit 36 Mustnt, neednt, don't have to and haven't got to B Form May and might are m odal verbs. Might is the past tense form of may. A fte r may and might, we use the infinitive w ith o u t to: We may send the goods im m ediately, [not: we may to send) When might you be in Paris? [not: m ight you to be) C Uses We use may and might to ta lk about: May/might I ask a question? You may smoke here. You may not smoke here. Yes, of course you may. (See also cant in Unit 34 and mustn't in Unit 36.) Notes P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Correct any mistakes in the following dialogue. Exercise 2 Read the sentences below. Write may (not), m ight (not) o r m ay/m ight (not) on the right, depending on the meaning o f each sentence. Exercise 3 A nsw er the following questions with the prom pts below. The firs t is done fo r you. 1. How w ill you go to New York? 3. When are you going to finish the research? Ill probably fly, but I m ig h t go by tra in . Ill probably fin ish it by Friday but i t __________ ready by Thursday. Transfer Write sentences about probability that affect you, Example: I m ig h t go to London n e xt year. vk.com/bastau I 67 I UNIT Can and Could See also Unit 33 May and might 3 4 Unit 36Mustn't, needn't, dont have to and haven't got to A Sample sentences A: Can I help you? B: My name is Nancy Farm er. Could I speak to M r Kumar, please. A: I'm sorry, but hes not available at the m oment. Can he call you tom orrow? B: No, he cant reach me tom orrow , but he could call me on Friday. B Form Can and could are m odal verbs. Could is the past tense form of can. A fte r can and could, we use the infinitive w ith o u t to: We can send the goods im m ediately, [not: we can to send) Could you repeat your name, please? [not: could you to repeat) C Uses We use can and could: 4. in requests fo r action: A: Can/could you give the name and phone num ber of your sales m anager, please? B: Of course. It's Fintan Mullane, and his num ber is 0576 345980. Notes In C1, could is a w eaker ability than can; in C2, can is a stro n g e r possibility than could. Norm ally, we dont use could fo r present perm ission. Exercise 1 Use phrases with can, can't, could and couldn't to replace the underlined words. Exercise 2 Look at the pictures below. Choose the sentence from a -c which matches each picture. 1. a. We cant have a pay rise. 3. a. We can see a big increase in sales here. b. We could have a pay rise. b. C ouldnt we increase o u r advertising a little ? c. We can d efinitely have a pay rise. c. I cant see any im provem ent here. Exercise 3 Complete the sentences below using can, can't, could and couldn't. 1. help you? Yes, I need som e advice. 2. come in? 'Of co urse. 3. Sorry; ------ _____ u nd e rstan d . U. The plane _________ take off. It was too foggy. 5. My c a r has broken down. I __________ be very la te . Transfer Make sentences which express ability/inability, possibility/im possibility, perm ission/prohibition, and requests for action. Use form s o f can and could. vk.com/bastau 69 UNIT Must, Have To and Have Got To 35 See also Unit 36 Mustn't, neednt, dont have to and havent got to Unit 37 Should and ought to A Sample sentences We must receive your comments on or before May 4th. In many European countries, men have to com plete a period of m ilitary service; theyve got to do at least a year. Last year China had to increase wheat imports because of a sharp drop in domestic production. B Form Must is a m odal verb; a fte r must we use the infinitive w ith o u t to: We must raise extra capital. (not: we m ust to raise) Have to is a present tense fo rm ; have got to is a present perfect tense form . Had to is the past tense form of have to; we also use it as the past tense of must and have got to: Last y ea r a ll drivers first had to report to reception; now we have (got) to d eliver the goods straight to the w arehouse. We use must a fte r a ll subjects; it does not change. There is no sh o rt form of must. Here are the fo rm s of have (got) to: Positive Question Subject Verb Verb Subject Verb i/you/we they have (got) to do l/you/we/they have to? he/she/it has (got) to does he/she/it have to? the company has (got) to does the company have to? the directors have (got) to do the directors have to? Past Positive Question Subject Ver b Verb H I ect Verb l/you/we they had to did l/you/we/they have to? he/she/it had to did he/she/it have to? the company had to did the company have to? the directors had to did the directors have to? The question fo rm s of have got to are: have l/you/w e/they got to . . has h e /sh e /it got to. There is no sh o rt form of have to. The s h o rt fo rm s of have got to are: I've/you ve /w e've/they've got to, h e's/shes /it's got to. C Uses We use must and have (got) to: 1. to ta lk about obligations - w hat you m ust do: A: We must do something. The situation is critical. B: I know. There has to be a sim ple solution. A: W hat did we do last time? B: We had to go to the bank and explain the situation. A: And then we had to pay back the money? B: Then w e ve got to do the same now. A: And how soon did we have to repay the loan? B: We had to repay it w ithin six months. 2. to express certainty: The new governm ent w ants to introduce reform . So change must soon be on its way. (= It is certain that there w ill soon be change.) P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Read the following dialogue. Then m ark the sentences 1-6 below true (Tj o r false IF}. Sue: Ive got to go to a m eeting. I m ust telephone John before I go. You have to stay here. Bill: Okay. Wait! Youve got to take the report w ith you. Sue: Why? Have I got to present it in the m eeting? Bill: No, but Fred w ants it today. He said he m ust have it. Exercise 2 Correct the mistakes in the following sentences. Exercise 3 Complete the sentences fo r the following pictures. Use must, have to or have got to. Transfer Make sentences about obligations fo r yourself, yo ur friends, o ra company you know. vk.com/bastau 71 UNIT Mustn't, Needn't, Don't Have To and Haven't Got To See also Unit 35 Must, have to and have got to Unit 37 Should and ought to A Sample sentences You m ustnt remove anything from the property. Thanks to mp3 players you neednt be at home to listen to your favourite music. It was Saturday and I didnt have to go to w ork. The museum is free. You havent got to pay to get in. B Form Mustn't is the negative of the m odal verb must; a fte r mustn't we use the infinitive w ith o u t to: You m ustn't touch these chemicals, [not: you m u s tn t to touch) Needn't is also a negative m odal verb. A fte r needn't, we also use the infinitive w ith o u t to: You needn't pay this bill before the end of next month. Don't have to is a present tense fo rm ; havent got to is a present perfect tense form . R em em ber to use: doesn't have to a fte r he/she/it or a s in g u la r noun hasn't got to a fte r he/she/it o r a sin g u la r noun. We don't have to w o rk harder; we just have to w o rk sm arter. The company hasn't got to grow; it's just got to become more profitable. C Uses We use these verbs in ta lk about w hat is prohibited and w hat is not necessary. 1. Prohibited: You mustnt enter this building. You mustnt park your car here. (See also may not in U nit 33 and cant in U nit 34.) 2. Not necessary: You needn't do anything at all. (It is not necessary tha t you do anything.) P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Make the sentences betow negative. Exercise 2 Change the underlined words in the sentences below. Use the correct form o f the words in brackets. Do not change the meaning. Exercise 3 Nordic Business, a newspaper, wrote a report on a successful Danish company, Larssen S.A. Here the Chairman o f the company, Bo Johannessen, writes a le tte r to the newspaper. Complete the spaces with appropriate form s of have to, need, must. Dear Sir, You reported last w eek that Larssen S.A. had a strong m arket position. Then you said that the com pany __________ think about its com petitors. This is not true. W e __________ believe that our m arket share is perm anent. We __________ w orry about our job s today, but we c e rta in ly cannot fo rg e t about our com petitors. A year is a short tim e in business. Yours faithfully, Bo Johannessen Chairman Larssen S.A. Transfer Write three sentences about yo urself and three about where you work. Include mustn't, neednt, don't have to and haven't got to. vk.com/bastau UNIT Should and Ought To See also Unit 35 Must, have to and have got to A Sample sentences You should m eet him. He's a very interesting person. The company ought to spend some tim e and money doing m arket research. Inflation should slow fu rth e r next year. You shouldn't buy w hat you don't need. B Form Should is a m odal verb; a fte r should we use the infinitive w ith o u t to: You should recycle a ll paper and glass, [not: you should to recycle a ll paper and glass) C Uses 1. We use should I/w e to m ake suggestions: A: Everybody is here now. So, should w e start the meeting? (I suggest th a t we start.) B: And should I take the minutes? (I suggest tha t I take the m inutes.) Note They must be home by now. (It is certain.) They should be home by now. (It is probable.) Exercise 1 Choose the correct alternative from the words in italics below. Two colleagues are discussing high bank charges. Label each sentence as a suggestion (SI, advice [Al or a probability IP]. Exercise 3 Use the prom pts below to make sentences using s h o u ld o r o u g h t to. LOW PRICES!! All VX and VXA range Transfer Write sentences about yourself, your friends o ra company you know. Include some examples of talking about probability, some suggestions and some advice. Examples: The com pany sh o u ld m ake a p ro fit again th is year. The boss o u g h t to have a pay ris e . vk.com/bastau ' 75 UNIT Question Tags 38 See also Units 1,2 Be Unit 31 Do Units 32,33, 34, 35, 36, 37 Modal verbs B Form A question tag has two parts: m odal or auxilia ry + subject We n o rm a lly form question tags w ith opposite polarity: can could will would shall must might is are has have cant couldnt wont wouldnt shant mustnt mightn't isnt arent hasnt havent If the verb doesnt have an auxiliary or m odal, we use a form of the auxiliary do: C Uses A tag tu rn s a statem ent into a question. We use tags when we w ant co nfirm ation o r agreem ent from the o th e r person P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Match the statem ent on the le ft with the correct tag on the right. Exercise 2 Passman pic is trying to buy a competitor, BKD Ltd. A D irector o f Passman pic is leaving a meeting. Journalists want to talk to him. Write tags and short answers for the text below. 1. The com pany has agreed to buy BKD Ltd, h a s n 't it? No, it h a sn 't. Exercise 3 Complete this conversation in a hotel bar. Transfer Write a conversation with a friend. Use ten different tags. vk.com/bastau 77 UNIT Active 39 See also Unit 40 Passive Business File 6 Irregular verb table A Sample sentences We are discussing the term s of the agreem ent. M r Uno accepted the job. They compete a ll over the w orld. Profits have steadily increased. B Form Every active sentence has at least two parts: a subject + an active verb form We n o rm a lly put the subject in fro n t of the verb: The Finance Director travels to Am erica every year. subject + verb A fte r an in transitive verb we cant put a d irect object. But we can put a phrase w ith an adverb or preposition. We use the active verb form in speech and w ritin g to describe actions and events. In general, the active fo rm is m ore personal than the passive. (See Unit 40.) Look at the follow ing sentences w ith active tra nsitive verbs: Now look at the follow ing sentences w ith active intransitive verbs: P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Make sentences out o f the words below. Exercise 2 Match a transitive verb in the firs t box with a typical direct object from the box below. Exercise 3 Complete the following sentences with a verb from the box. 4. Mobile Phone of the Year Awards 20 08 Poor performance I r Transfer Write sim ple sentences about a local employer. Use the verbs in the box. Example: A fa c to ry in m y to w n m a ke s s p o rts e q u ip m e n t. vk.com/bastau 79 UNIT Passive 40 See also Units 1, 2 Be Unit 39 Active Business File 6 irregular verb table A Sample sentences Any rem aining money is distributed to shareholders. Kwan's w ork has been accepted for publication. This issue was discussed in Chapter 6. The contract w ill be signed at the end of the year. B Form The passive verb fo rm has two parts: to be + past participle to be + past participle We can only make passive verb fo rm s fro m tra nsitive verbs. (See Unit 39.) Look at the follow ing passive verb form s: Simple Continuous Present the design is chosen the design is being chosen the designs are chosen the designs are being chosen to be (present) + past participle to be (present) + being + past participle Past the design was chosen the design was being chosen the designs w ere chosen the designs w ere being chosen to be (past) + past participle to be (past) + being + past participle Present perfect the design has been chosen the designs have been chosen to be (present perfect) + past participle Past perfect the design had been chosen the designs had been chosen to be (past perfect) + past participle Infinitive (to) be chosen (to) be being chosen (to) be + past participle (to) be + being + past participle C Uses Look at the use of passive verbs and the preposition by in the follow ing m in i-dialo g ue : P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Make passive sentences from these words. Write sentences in the present simple, the past simple and the future with w ill. S ta ff are o rg an ise d in p ro je c t team s. S ta ff w e re o rg an ise d in p ro je c t tea m s. S ta ff w ill be o rg an ise d in p ro je c t tea m s. Exercise 2 Use the passive to describe the process shown here. Use the prom pts given. Exercise 3 Tim Hall, an airline manager, is talking about what happens before a plane takes o ff Complete the spaces with passives. There are many im p o rta n t activities before take-off. The fu e l ta n k s __________ (fill) and the a irc ra ft s y s te m s __________ (check). F o o d ___________ (bring) on board. A ll the baggage (load) in the hold. The captain and the c o -p ilo t _ _________ (inform ) of runw ay conditions and o th e r details about take-off. When everything is alm o st ready p a s s e n g e rs__________ (invite) to board the plane. Transfer Describe any process you know. How is bread made? How is tea made? How is a car made? vk.com/bastau 81 UNIT Active vs. Passive 41 See also Unit 39 Active Unit 40 Passive Business File 6 Irregular verb table A Sample sentences A: How often do you upgrade your com puter system? B: Our system is upgraded every year. A: And when are you going to do the next upgrade? B: The next upgrade w ill be carried out by our IT consultant in October. B Form For the active verb form , see Unit 39; fo r the passive verb form , see Unit 40. Now look at the relationship between the active and the passive sentences below: C Uses We use the active verb form in speech and w ritin g to describe actions and events: They are launching a budget range of softw are disks next month. First they w ill take part in an IT exhibition in Birm ingham. 2. In process descriptions: First the door is prim ed, then rubbed down using sandpaper. This is the typical style fo r the d escription of the steps in a process. Again, we are not interested in the doer. The corresponding active sentence w ould be: First you prim e the door, then you rub it down using sandpaper. 3. In im p e rso n a l language: The building site is dangerous; hard hats must be worn at a ll tim es. This is the typical style of a w ritte n o rd e r o r in stru ction . The corresponding active sentence w ould be: The building site is dangerous; w ear hard hats. Exercise 1 Read the text betow about security o f inform ation in Chemco PLC. There are six verb form s in the text. Mark them A IactiveI o r P [passive]. Exercise 2 Complete the sentences fo r each situation below. Use the given verb in the active or passive. 2. switch off/lights Exercise 3 Below are notes fo r a welcome presentation fo r visitors to Eastern Water by Sam Weal, the Public Relations Manager. Write the beginning o f his presentation. Use the seven verbs given here. Put each verb into an appropriate active or passive form. Transfer Describe some actions in your norm al day. Then describe a process you know. vk.com/bastau 83 UNIT It Is/They Are vs. There Is/There Are See also Units 1,2 Be A Sample sentences A: It is not possible to approve these figures. They w ere wrong last year and they are s till wrong. B: But there was a m istake in the program then. A: There are s till many mistakes in the program . It isn't right yet. B: It is a very complex program . B Form We can use it or there w ith the verb be in the follow ing main tenses: Note The m ost com m on sh o rt fo rm s are shown in brackets. C Uses Look at the follow ing m in i-dialogues: In the firs t exchange, it refers to in form a tion th a t has already been identified, i.e. the new house. In the second exchange, there introduces new in form a tion , i.e. the kitchen and the lounges. In the th ird exchange, we use the em pty it before the adjective (im possible} and the noun [a mistake}. The it has no m eaning; but in th is way we can postpone the im p o rta n t in form ation to the end of the sentence. It is difficult to develop a m arketing plan has m ore im pact than To develop a m arketing plan is difficult. Note We can put e ith e r a sin g u la r o r a p lu ra l verb a fte r there. The fo rm depends on the subject. There is one im portant reason for our decision. There are three main points in my presentation. 84 I P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Make eight questions o r sentences from the words below. Examples: Are there a lot of museums here? It isn't cheap. It is French. There are a good restaurant here. They it good quality. Are they expensive. Is aren't cheap. isn't many tourists here. there a lot of museums. Exercise 2 Choose the correct alternative to complete the dialogue below. A: There is/There a re /lt is many good hotels in Tokyo. I like the Tokyo Hilton. There is /lt is in the centre of the city. B: Is there/Are there/ls it many s m a ll fam ily hotels? A: No, there a re n 't/it is n t. B: I im agine they is/they are/there are very expensive. A: In Tokyo? Yes, there is/is it/it is an expensive city. Exercise 3 Maria is at Dusseldorf railw ay station. She wants to go to Munster. Look at the notes from the timetable. Complete the spaces in the dialogue below. Use the phrases in the box. there is [21 DEPARTURES [Tils is it are there Maria: Is there a tra in to M unster? Clerk: Yes,________ m any trains. Now 11.25. a tra in at 11.20. The next one is at 11.41. Maria: ________ direct? Clerk: N o ,________ It goes via Essen. _ a train to M unster via Essen every 20 minutes. Maria: direct tra in s to M unster? Clerk: Yes, ___ a direct tra in at 11.50. ____ d irect to Munster. Transfer Make a dialogue using is there/are there/there is/there a re /it is/they are about yo ur town. vk.com/bastau 85 UNIT Have and Have Got 43 See also Units 15,16, 17 Present perfect Units 35, 36 Have to, have got to, and havent got to Unit 44 Get and have got A Sample sentences A: Do you have an office in Tokyo? B: No, we've only got a representative office there. We dont have enough sales there. Has your company got an agent in Japan? A: Yes. In fact until last year we had two, but one didnt have reg u lar contact w ith us. So we had to cancel our agency agreem ent. B Form Have is both a fu ll verb and an auxiliary. 1. For the auxiliary have, see Unit 15 [present perfect) and Unit 19 (past perfect). 2. Below are the fo rm s of the fu ll verb have: EB9HHI Present statem ent Present question Subject Positive verb Verb Verb l/yo u/w e /th ey have got havent got have l/you/w e/they got h e /sh e /it has got hasnt got has h e /sh e /it got the com pany has got hasn't got has the com pany got the d irectors have got havent got have the d irectors got The past fo rm s of have got are had got (positive verb), hadnt got (negative verb) and had .. . got (question). The s h o rt fo rm s of have got are I've/youve /w e've/th eyve got, hes /s h e 's /its got C Uses 1. S om etim es have and have got have (got) the same m eaning: Sixty insurance companies have (got) th e ir headquarters in the city. 2. S om etim es we use have in fixed phrases: On fine evenings, we usually have a barbecue. Come and have a coffee w hile we discuss w hat you should do. P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 1 Label have in the following text as auxiliary [AUX], fu ll verb (VI o r p a rt o f have got (HGj. I did n t have a very good job last year. Now Ive got a new position in the company. Ive taken co n tro l of export sales. Weve m any new clie n ts in A m erica and Asia. Have you seen o ur product brochure? Weve had a new one printed th is week. Mary, have you got a copy? Exercise 2 Match the following to the correct picture a-f. Exercise 3 Fumi Wang is talking to Mike Winters, o f Trans World Systems, a software company Complete the following conversation. Use form s o f have or have got. Transfer Write a short dialogue about a company you know well. Use sentences with have and have got. Include the following words. vk.com/bastau UNIT Get and Have Got See also Unit 43 Have and have got u u Business File 4 British English vs. American English A Sample sentences A: How often do you get financial updates? B: I get new inform ation every w eek. A: And when did you get the latest inform ation? B: I got a report yesterday. I've got it here. Have you got tim e to look at it? B Form Get is a fu ll verb (see Business File 6: Irre g u la r verb table.) The form have got is the present perfect of get (see Unit 4-3 fo r the fo rm s of have got). C Uses 1. We use get in the present and past to mean receive : A: Did you get the message? B: Yes, I got it yesterday. Note We have got the keys. (We have them now.) We got the keys last w eek. (We received them last week.) P re -In te rm e d ia te B usiness G ra m m a r vk.com/bastau TASKS Exercise 1 Underline and [abet six form s o f get (Gj and have got IHGJ in the following text. Exercise 2 Match the following to the correct picture a-f. Exercise 3 Complete the following exchanges. Choose a form of get o r have got from the box. Use the correct tense. get (21 get easier get better have got [2] not/get Transfer , Write sentences about yourself with get or have got Include positive negative and question forms. vk.com/bastau 85 UNIT Say vs. Tell 4 5 A Sample sentences A: W hat did head office say about the branch manager? B: They didn't say a lot. They told us that he hadn't been very helpful. A: And w hat did they say about the appraisals? B: They always te ll us that the appraisals are outside th e ir responsibility. A: Next tim e, please te ll them that we are w orried. Say Many people say that the city is safer now than it was ten years ago. {not: Many people say us tha t the city is sa fe r now than it was ten years ago.) A: W hat did he say to you? [not: W hat did he say you?) B: He said to me that he w ill m ake a very im portant speech at the conference. [not: He said me th a t he w ill make a very im p o rta n t speech at the conference.) T ell Please te ll Jane that I w ill call her later. [not: Please te ll to Jane ...) I w ill te ll my friends to stay at your hotels. [not: I w ill te ll to my frie n ds ...) He told us the history of the city, [not: He told the history of the city.) Exercise 1 Two colleagues are in a restaurant. Match a sentence on the left to an appropriate reply on the right. 5. Tell the w a ite r you w ant a no the r knife. e. I said I w ould like fish. Exercise 2 A purchaser from Delta Hospital Services wants to buy some equipment from a supplier, Langer. There are fou r mistakes in the conversation. Identify them and correct them. Exercise 3 Complete the email below with say, said, te ll or told. Transfer What have you said today? Who did you te ll something? What has someone told you? vk.com/bastau 91 UNIT Make vs. Do 46 See also Unit 31 Do A Sample sentences A: W hat do you do? B: I w ork as a receptionist for Arnison and Naylors. A: And w hat do Arnison and Naylors make? B: They dont make anything; they sell houses. B Form Make and do are fu ll verbs. (See B usiness File 6: Irre g u la r verb table.) Do is also an auxiliary verb. We use it in the negative and question fo rm s of the present and past sim ple tenses. (See Unit 31.) C Uses Make and do often have s im ila r m eanings. S om etim es we use make and som etim es we use do. There are no fixed rules. So you should learn som e of these phrases. make an appointment an arrangement a budget a choice a complaint a decision a loss a mistake money an offer a profit progress a report sure a trip Now look at the follow ing dialogue w ith make and do: A: So, how did your company do last year? B: We did very w e ll. We made a profit of $ 1.2 billion. A: How did you make so much money? B: We did a lot of w o rk on our forecasts. A: So you didn't make any m istakes in your budgets? B: No, w e didn't. vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS U. Pablo did/m ade a plan fo r the South A m erican m a rke t last week. Exercise 2 Two colleagues are discussing a meeting. Their company has produced a new product, BIGGO. F ill the spaces in the dialogue with an appropriate form o f do o r make. Exercise 3 Complete the sentences below. Replace the underlined words with a new verb phrase using m ake o r do in the correct tense. 4. The meeting was very long but it has been useful. We____________________ progress. 5. They suggested a price but it was too low. They__________ an offer, but it was too low. Transfer What did you do yesterday? What are you doing today? Have you made anything recently? vk.com/bastau UNIT Used To 4 7 A Sample sentences A: Do you travel a lot in your job? B: I used to go abroad twice a month. A: I'm sure that was very tiring. B: Not really. At that tim e I was used to travelling, but now I'm used to working in the office. B Form There are two different verb phrases w ith the form used to: 1. used to + infinitive I used to w ork for ITCorp. (I w orked fo r ITCorp in the past, but I dont w o rk there now. We use used to to ta lk about a past habit. C Uses These two verb phrases have d iffe re n t m eanings. 1. used to + infinitive We use th is phrase to ta lk about a past activity or habit tha t is not a present activity o r habit. We used to stock 36 different kinds of steel pipes. (In the past we re g ula rly stocked 36 types of stee l pipes, but now we dont.) In the past we used to design everything by hand; today w e use computers. We use this phrase to ta lk about a general habit - n orm a lly in the present, but possibly in the past or future. Is it s till strange, or are you used to it now? He was used to the journey as he had done it several tim es. I'm sure Peter w ill soon be used to the new com puter system. Note The follow ing sentences have d iffe re n t fo rm s but s im ila r m eanings: We w ere used to working until 7 or 8 pm. (= past general habit) We used to w ork until 7 or 8 pm. (= past habit) vk.com/bastau 94 | P re -In te rm e d ia te Business G ra m m a r TASKS faHSfffSfl Underline six examples o f used to in the dialogue. Label them as PH [past habit] o r GH Igeneral habit]. Exercise 2 Write sentences, based on the prom pts below, about Michael Ross, Chairman o f Kelfield PLC. Use used to and the words in brackets. H e __________ (make/presentations]. H e __________ [work/late]. Exercise 3 Complete the following sentences using appropriate form s o f used to. Transfer Write five sentences about yo urself and yo ur work or studies in the past and now. Use used to. vk.com/bastau 95 UNIT Rise vs. Raise See also Unit 85 Describing trends 4 8 A Sample sentences A: The governm ent is going to raise taxes next year. B: So, taxes w ill rise again. They raised taxes last year. A: And the level of unem ploym ent rose. B Form Rise and raise are different verbs, but they have s im ila r m eanings. So rise is an irre g u la r verb and raise is a re g u la r verb. The o th e r difference is tha t rise is intra nsitive and raise is transitive. (See Unit 39.) Prices rose last year, (intransitive) We raised prices last year, (transitive) C Uses We use both verbs to indicate an upward movem ent: vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Underline examples of ris e and raise. Mark them as intransitive [ll o r transitive iTj. I In the first half of the year prices rose by 10%. Wages rose at the same time. The government raised taxes and the banks raised interest rates. Inflation continued to rise. Exercise 2 Choose the correct sentence from the atternatives given. Exercise 3 Write sentences 1-5 fo r the pictures a-e. Use the given prompts. Transfer Write fou r sentences about yo u r work o r studies. Use appropriate form s o f rise o r raise. vk.com/bastau 97 UNIT Verb + Preposition 49 See also Unit 29 Verb.. .ing Business File 6 Irregular verb table A Sample sentences They are preparing for a conference in London next week. Do you approve of spending so much? Our success depends on reg u lar orders from big companies. The company has succeeded in reducing costs. B Form A verb + preposition phrase has two fo rm s: verb + preposition + noun phrase I've heard about the vacancy in the M arketing Departm ent. about at fo r in of on to w ith Note We always use verb .. .ing a fte r a preposition: Excuse me for interrupting, [not: excuse me fo r in terru pt) C Uses Now look at these sentences w ith verb + preposition phrases: I look forw ard to seeing you soon, [not: I look forw ard to see you soon.) Here to is a preposition. Dealers are waiting for prices to fall. He apologised for being late. The departm ent asked for a 13% increase in its budget. vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 1 Match a verb on the Ieft with a preposition on the right. succeed to ask on hear fo r depend w ith consist in look forw ard about agree of Exercise 2 Complete the le tte r below with an appropriate tense of the correct verb and preposition from the box. Exercise 3 Two colleagues, Sam and Paula, go out for an evening a fte r a successful negotiation with a supplier. Complete the dialogue with an appropriate verb and preposition combination. Choose a verb from the box. Put it in the correct tense. Transfer Write a paragraph about yo urself and/or yo ur company o r studies. Include examples o f verb and preposition combinations. vk.com/bastau 99 UNIT Verb + Adverb (Phrasal Verb) See also Business File 6 Irregular verb table A Sample sentences Always switch off the light when you leave the room. The office didnt make its sales targets, and the company eventually shut it down. You must fill out a form if you want to claim expenses. Why did you give up marathon running? B Form A verb + adverb phrase is also called a phrasal verb. If the phrasal verb takes an object, then we can put the object a fte r the adverb (sentence 1) or between the verb and the adverb (sentence 2). But if the object is a pronoun, then we m ust put the pronoun between the verb and the adverb (sentence 3). Sentence 4 shows a phrasal verb w ith o u t an object. C Uses S om etim es a phrasal verb keeps the m eaning of its parts: A: Let's bring forward the date of the meeting. B: No. I think we should put the date back. S om etim es a phrasal verb has a d iffe re n t m eaning from its parts: A: We have a lot to discuss. We're getting behind schedule. B: We can make up some time, if we call the meeting off. (make up = gain; call off = cancel) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Match the verb on the le ft with a phrasal verb on the rig h t with the same meaning. Exercise 2 Match the pictures a -d with the correct sentences 1-4 below. Underline the phrasal verb in each sentence. a. b. d. Exercise 3 Replace the underlined words in the conversation below with a phrasal verb from the box. Transfer Have you given up anything? Do you want to set up anything? Have you put back any plans ? Have you taken away anything? Do you Look back on things? Have you taken out anything? What would you like to cut down or call off? vk.com/bastau 101 UNIT Positive Statements 51 See also Unit 3 The present continuous positive Unit 6 The present simple positive Unit 11 The past simple positive Unit 52 Negative statements A Sample sentences He reports to the group vice president. Capacity at European plants is expanding. Last year the company opened ten new retail stores. I have just returned from a visit to the training centre. B Form A positive statem ent has at Least two parts: subject + positive verb form The market is booming. will improve, has increased. In positive statem ents, we usually put the subject before the verb: The caretaker lives on the top floor. subject + positive verb On the top floor lives the caretaker is possible but not com m on. We can put the verb into one of the follow ing tenses: C Uses We use positive state m e n ts to give positive inform ation. Here are some positive state m e n ts w ith d iffe re n t verb phrases: The seminar will start at 2pm. We have five points on the agenda. In the meeting they discussed the future of the company. Shareholders must vote on this offer. Both issues should be decided soon. Read the text betow. Underline and label the subject o f each sentence [S] and the verb phrase [VPj. Sales (S) have been very disappointing (VP) this year. Our costs are rising every day. Clearly, our marketing team need to market our products better. But our R&D Department are confident. They are developing a brilliant new product. It will need support from the bank. A new business plan is being prepared at the moment. Exercise 2 The text below gives the history o f Keele Brothers Ltd. Put the sentences into the correct order. The firs t two have been done for you. d. Between 1980 and 2000 the m ain products w ere pum ps and s m a ll engines. e. The name of the com pany was changed to United E lectric (UK) Ltd. Exercise 3 Complete the sentences below taken from the annual report o f Hebden pic, a m anufacturing company. Put the verbs in the correct form. 3. Our p ro d u cts __________ all over the w orld fo r many years, [export] Transfer Write six positive statem ents about yo urself o r a company you know. Use different verb phrases. vk.com/bastau UNIT Negative Statements 52 See also Unit 4 The present continuous negative Unit 7 The present simple negative Unit 12 The past simple negative Unit 31 Do A Sample sentences We arent increasing our advertising budget this year. The company doesnt have any South African operations. They havent sold the stock yet. We can't wait until next year. B Form A negative statem ent has at least two parts: subject + negative verb form Quality isn't improving. The negative verb fo rm has a m odal o r auxiliary + not + verb. In negative statem ents, we usually put the subject before the verb: The members didn't agree on this point. subject + auxilia ry + not + verb On this point the members didn't agree is possible but not com m on. We can put the verb into one of the follow ing tenses: If the verb is in the present sim ple o r past sim ple, we use a fo rm of do to make the negative. (See Unit 31.) We don't produce the A5687 in England; we produce it in the Far East. negative verb form positive verb form C Uses Look at the negative statem ents in th is m ini-dialogue: A: The situation doesnt look good. B: i dont agree. We didn't make a loss last month. A: Yes, but we havent made a profit for six months. B: But we mustnt always focus on the past. P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS Underline negative statem ents in the text betow. Label subjects [Si and negative verbs [NVj. To: 1nick_fox@jdloughman.com From: | maria_aubert@jdloughman.com Subject: | Ibros S.A. negotiation Dear Nick We did not have a meeting with Ibros S.A. because we rejected their offer.The offer did not come by email. We received a fax on Thursday. We understand that the Managing Director of Ibros, Mr Kalkis, will not sign the contract. We have not accepted the present proposals. At the moment we are not planning to continue production of the Alisia range. Last year we didn't reach agreement immediately. I Now, I think it will not be easy to find a solution. a Exercise 2 Make the following statem ents negative. Use sh ort forms, where possible. Exercise 3 Write negative statem ents fo r the pictures a - f below. Use an appropriate modal o r auxiliary + not. d. 1. we/not/increase/R+D spending We have not increased our R+D spending. 2. inflation/not/rise/in the near future 3. S ols m arket share/not/increase in ten years 2003 2004 2005 2006 2007 Definitely no takeover of Hammond 2010 Transfer Write six negative statem ents about yourself, yo u r work o r your studies, o r about an institution or company you know. vk.com/bastau 105 UNIT Questions: Yes/No 53 See also Unit 5 The present continuous question Unit 8 The present simple question Unit 13 The past simple question Unit 31 Do Units 54, 55 Questions A Sample sentences Do you still play golf? Didn't we discuss this yesterday? Has Marija finished the calculations yet? Can't we do this another time? B Form A yes/no question has at least two parts: question verb form + subject We can put the verb into one of the follow ing tenses: If the verb is in the present sim ple o r past sim ple, we use a form of do to make the question. (See Unit 31.) Did we meet our production targets? fo rm of do + verb p art 2 C Uses Look at these yes/no questions: P re -In te rm e d ia te Business G ra m m a r vk.com/bastau TASKS 1335331 Undertine the ye s/n o questions in the following dialogue. Exercise 2 Paulo Introini wrote an em ail to his company's Marketing Department. He received the email message printed on the right. Match the correct answers [a -f] on the rig h t to the questions [1-61 on the left. Here are six questions. a Yes, we are going to send you a full report. ; 1 Has all the research been completed? b No, we do not recommend any major 2 Was the rate of response good? changes in our selling techniques, 3 Was the feedback satisfactory? c No. We will repeat the survey in two years, 4 Are we planning to repeat the survey? d Yes, we received good feedback on our 5 Will you send me a report? products. 6 Are changes recommended in our selling technique? e Yes, the research has been completed, f Yes, the response rate was good. Kind regards Paulo Exercise 3 Look at the prom pts below. Write a ye s/n o question fo r each one. 1. you/call/Fred/yesterday? Did you call Fred yesterday? 2. M andy/m eet/Joanne/next weekend? 3. Alex/be b ack/from Nairobi tom orrow ? 4. T o m /usu a lly/re n t/a ca r fo r trip s abroad? 5. be/you/prepared/for y o u r presentation/next week? 6. R olf/go/N ew York/in June last year? Transfer Prepare eight yes/no questions to ask a friend about h is/he r work. vk.com/bastau UNIT Questions: Wh- 54 See also Units 5, 8, 13 Questions in present and past Unit 31 Do Units 53, 55 Questions B Form A w h -q ue stio n has at least three parts: w h -q ue stio n w ord + verb + subject The verb may be e ith e r a positive verb form o r a question verb form : Who(m) did you m eet at the airport? (question verb form ) Who m et you at the airport? (positive verb form ) The difference depends on the g ra m m a tic a l function of who. In the firs t sentence who(m) is the object; in the second, the subject. Only who, what and which can be e ith e r a subject o r object. For m ore in form ation on question verb form s, see Unit 53. C Uses Look at these w h -q ue stio ns: Who built this tow er? (who is the subject of the verb) Who(m) did he choose for the role? (who(m) is the object of the verb) Which candidates came to the interview ? (which candidates is the subject of the verb) Which candidate w ill you appoint? (which candidate is the object of the verb) Note Jn spoken language we usually use who fo r the object; in fo rm a l w ritte n language we use who(m). 108 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r y g fffg s n Underline the wh-question words in the sentences below. Match the questions on the le ft to the correct answ er on the right. 1. When did you get here? a. For a m eeting w ith our partners. 2. Where are you staying? b. Roland K. Saxman. 3. Do you plan to stay long? c. No, th is is my firs t visit. -4. W hat kind of business are you in? d. I came on Monday. 5. Which bank? e. At the Crescent hotel. 6. Why are you in New York? f. I w o rk fo r a bank as a fin a n cia l adviser. 7. Who is the se nior V ice-P resident of CBI? g. Credit Bank International. 8. Have you been here before? h. Just two days. Exercise 2 Complete the questions below with wh-question words. A: To Greece. Q : ____ ______are they carrying? A: Kalkos S.A. A: In Saloniki. Exercise 3 A t Compo Ltd the Marketing Departm ent have a meeting to talk about a new idea. Write questions about the underlined words in the sentences below. Transfer , , Ask a colleague questions using who, whom what which, where when why. , , vk.com/bastau UNIT Questions: How 55 See also Units 5, 8, 13 Questions in present and past Unit 31 Do Units 53, 54 Questions Units 77, 78, 79 Quantifiers A Sample sentences How did they become such big brands? How many people w ill lose th e ir jobs? How long has the company been in business? During the past month, how often have you spent tim e alone w ith your husband or wife? B Form We form a question w ith how in the sam e way as a w h -q ue stio n. It has at least three parts: how + verb + subject The main how -question w ords are: how? how m uch/m any? how long? how far? how often? how big/sm all? C Uses Look at these how -questions: 6. asking about the dim ensions - how big, how sm all, etc. How big is your office? How sm all does the digital cam era have to be? 7. asking about the extent of a qua lity - how busy, how hot, etc. How busy are you a fte r lunch? How hot does it get in sum m er? vk.com/bastau P re -In te rm e d ia te B usiness G ra m m a r TASKS p w jfiw s n Exercise 2 Complete the email below by asking the question fo r the given answers. Use a question phrase with how. Date: 18/10/2010 To: | k.r.nijran@amtel.com From: marketing@amtel.com Subject: [ RE: AMTEL MARKET SURVEY Dear Kevin, ______are we going to spend? US $450,000 ----------people will get questionnaires? 3,000 ----------will the research take? two months ----------do we need to repeat this survey? every two years will the survey extend? all over Japan is the consultancy which is carrying out the research? the 4th biggest in Japan will they analyse the result? by computer and personal interview ::. 3 Ben Kamal is Managing D irector ofA ranco Ltd. He is talking about insurance with a friend, Willy Hoos. Complete the dialogue with appropriate questions. W illy : How do vou decide (decide) w hich insurance com pany to use? Ben: We choose an insurance com pany on the basis of cost and service. W illy : (employee insurance/cost)? Ben: Employee insurance costs about 10% of the salaries. W illy : (employees/have)? Ben: Around 850. W illy : (they/stay/w ith Arancol? Ben: N o rm a lly if they stay, they stay fo r a long tim e. W illy : (make/a detailed study of em ployee insurance)? Ben: We make a detailed study very often. Every year. Its very im portant. W illy : Ibe/A rancos turnover)? Ben: Our tu rn o ve r is 30m. This is increasing by between 3% and 6% every year. Transfer I How many people live in yo u r town? How big is the largest company? How often do you travel abroad? How fa r is the local airport? How long does it take to get to the nearest seaport? vk.com/bastau 1111 UNIT Commands - Positive and Negative 56 See also Unit 10 Positive and negative imperatives Unit 38 Question tags A Sample sentences Make sure that your w ork is presented neatly. Dont place anything w et on a wooden table. Please send your order to this address. Sit downpw ill you! B Form We form a positive com m and using an infinitive (the positive im perative form ): Call this num ber right now. infinitive We form a negative com m and w ith dont + infinitive (the negative im perative form ): Don't w ait until tom orrow, don't + infinitive For m ore in form ation on im perative verb form s, see Unit 10. We can put please before or a fte r the com m and to make it m ore polite. C all me before 10 o'clock, please, (w ritten w ith a comma) Please don't phone me a fte r 10 o'clock at night, (w ritten w ith o u t a com m a) We can put the tag w ill you a fte r a com m and to make it m ore em phatic, but this is not very polite. Correct these figures, w ill you? C Uses Look at these com m ands: 112 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Undertine positive commands once and negative commands twice in the following extract. Please arrive at about 8.30. R egister w ith reception. You w ill be given a key. You may relax u n til 9.30. At 9.30, please m eet at the Main Entrance. Dont go directly to the S em inar Room. Wait fo r your group leader. He/she w ill give you in stru ction s. Please dont telephone the office except in an emergency. F u rth e r in form a tion can be obtained by em a il o r letter. Exercise 2 Match the commands betow to the correct picture a-h. c. e. b. d. Exercise 3 Jane Callow has a new Personal Assistant. Jane is in London on business. She leaves instructions fo r h e r Personal Assistant. Complete h er instructions with positive commands for the tasks m arked { / ) and negative commands fo r the tasks m arked (XL Use verbs in the box. Transfer Write three positive commands fo r a regular visitor to your home o r company. Write three negative commands fo r the same person. vk.com/bastau 113 UNIT Sentence Types: Simple vs. Complex 57 A Sample sentences Prices have gone up. House prices w ill increase but w ages w on't rise. Expenses are high because he has to travel a lot. Organizations which need to save money often cut jobs. B Form A sim ple sentence has only one clause, i.e. contains one verb phrase. We c a ll th is a main clause. m ain clause A com plex sentence has m ore than one clause, i.e. contains m ore than one verb phrase: We can borrow from the bank or raise capital from the shareholders. verb phrase 1 verb phrase 2 We are moving to a new office because the present building is too sm all. verb phrase 1 verb phrase 2 C Uses 1. A sim ple sentence can be a statem ent, a question, o r a com m and: W hen are you going to see him? (question) The com mittee's next meeting is scheduled for August 22. (statem ent) Dont forget to send a copy of the report to everyone, (command) 2. C o-ordination is often m ore vague than subordination. Look at the follow ing sentences: Finally, we appointed Susanne Schneider and we think that she'll be a good Research Director. Finally, we appointed Susanne Schneider, who we think w ill be a good Research Director. Finally, we appointed Susanne Schneider because we think that she w ill be a good Research Director. They have s im ila r m eanings, but the fin a l sentence is the m ost inform ative. 3. S ubordination shows the re lationship between the m ain clause and the subordinate clause: A: OK, the green light, w h ich you can see here, is the first indicator. (relative clause m akes specific) Don't press the button u n til the green light goes on. (indicates tim e) B: But w hat do we do i f the green light doesn't go on? (indicates condition) A: This shows th a t the machine is not ready, (subordinate clause a fte r the verb to explain show ) 1U vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS E E E & l Label the main clauses [MCI and the subordinate clauses [SCI in the following. Underline the co-ordinating conjunctions and(circle)the subordinating conjunctions. The Am co 75 w ent into production in the Spring. Sales were very good and we quickly established a sig n ifican t m a rke t share. We have begun exporting the Am co 75, though early sales are weak. We w ill have a satisfactory year if our exports improve. P rofit has gone up th is year because o u r dom estic sales have increased. Our research has been very productive but costs have risen. Now we have many co m p etito rs who are seen as im p o rta n t dangers in som e key m arkets. Exercise 2 Add appropriate conjunctions in the following dialogue. Choose from the box. A: We need m ore office space and _ o u r staff want m ore co m p ute r equipm ent. B: Yes, we have agreed to re cru it a no the r se cre ta ry,__________ we have not decided when. A: But we need one now. There w ill be problem s we dont get one soon. B: I th in k there w ill be resignations _____ everyone is w o rkin g too hard. A: I agree. People w ill re s ig n _____ they w ill sim ply be less effective at work. B: Im going to speak to P a tric k ,__ __ w ill accept tha t the situation is critica l. Exercise 3 Look at the paragraph below. Hans Koeppel talks about his company. Count the sentences. Are they sim ple or complex? Below it is the same paragraph, rew ritten with few er sentences. Make them into complex sentences by putting one word in each space. I w o rk fo r Arkop GmbH. Arkop m akes car com ponents. The com pany is based in K irchheim . K irchheim is in S outhern Germany. This is a good location. Many of our cu stom ers are very close. We s e ll o u r products a ll over Germany. We also export a lot. Our dom estic m a rke t is the m ost im p o rta n t part of o u r business. I work for Arkop GmbH _________ makes car components. The company is based in Kirchheim, _________is in Southern Germany This is a good lo ca tion _________ many of our customers are very close. We sell our products a ll over G erm any_________ we also export a lot, our domestic m arket is the m ost im portant p a rt o f our business. Transfer Write six sim ple sentences about a company o r institution you know well. Then reduce the num ber o f sentences by rew riting them as complex sentences. vk.com/bastau 115 UNIT Subordinate Clauses See also Unit 57 Sentence types: simple vs. complex A Sample sentences We w orked quickly because w e had to m eet the deadline. A fter the MD presents the figures, you can ask your questions. I am going to buy a laptop so that I can w ork on the train. Although the mobile phone m arket has increased, growth has slowed. We have appointed a new Chief Executive, who used to w ork for ITCorp. B Form A subordinate clause depends on a main clause. It cannot stand by itse lf as a sentence. 1. that: The MD said that the company was making good profits. 2 . a subordinating conjunction: If sales improve, the company w ill soon be profitable again. 3. a w h -w o rd or how -w ord: We don't know when the new product w ill be launched. C Uses Look at the follow ing sentences. Each sentence has a subordinate clause; and each subordinate clause has a different meaning. 1. because - cause o r reason: The business w ill succeed because we have recruited good staff. 2. if - condition: We w ill reduce the fee i f you pay in advance. 3. although - contrast: A lth o u g h we have reduced costs, profits have not increased. Notes We can use though o r although. 4. so that - purpose: We are changing the way we do business so th a t w e can compete more effectively. 5. so (that) - result: There was enough room so (th a t) w e could invite tw enty guests. 6. after - tim e: A fte ry o u finish high school, you can go to university. 7. w h -w o rd - reported question and relative clause: I would like to know w h y you are here, (reported question) They jointly own the company w h ich w ill operate the pipeline, (relative clause) 116 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS E G E M 1 Identify nine subordinating conjunctions or wh-words in the wordsquare betow. There are five horizontal, three vertical and one diagonal. B E C A U S E T S B L 0 L R H E M I I F F 0 M W T H A W U K W C H I H G T H R D P E H S 0 0 X L N Exercise 2 Match the main clause on the le ft with an appropriate subordinate clause on the right. Exercise 3 Valbor Metal is trading in a d ifficult market. In an internal meeting, a m em ber o f the Board is talking about the problems. Complete the following text with words from the box. We need to increase our p ric e s __________ our costs are rising. Many companies are in a sim ila r p o s itio n ,__________ our costs are especially high. We have a strong export m arket __________ o ur sales are s till good. We have identified some key p ro b le m s_______ make the home m arket very d ifficult at present. We w ill have continued p ro b le m s _______ __we do not take some d ifficult decisions. There is no time to lose, we have to do something quickly. ' Transfer Write five sentences with subordinate clauses about the m ajor em ployer in your home town, o r about your company vk.com/bastau 117 UNIT Relative Clauses with Who and Which See also Unit 58 Subordinate clauses A Sample sentences You need to speak to Chris Brown, who is in charge of m arketing. The person who interview s you w ilt supervise your w ork too. Most buyers are looking for a business which can grow. He applied for the post of sales director, which has been vacant since last month. B Form A relative clause is a type of subordinate clause. Relative clauses begin w ith a relative pronoun. Who and which are typical relative pronouns. C Uses 1. Defining relative clauses give in form a tion w hich is e ssential to understand the sentence: You are the only person who can answ er this question. The clause who can answ er this question identifies the person; w ith o u t this inform ation, the sentence has a d iffe re n t meaning. This is the machine which can print 25 pages a minute. The clause which can print 25 pages a m inute identifies the m achine; w ith o u t th is inform ation, the sentence has a different m eaning. 2. N on-defining relative clauses give additional, non -e sse ntia l in form a tion : Norbert, who(m ) we m et in New York, is visiting London next month. The clause who(m ) we met in New York gives a dditional in fo rm a tio n ; we can s till identify the person w ith o u t th is in form a tion . I've read a ll of your papers, which I found very interesting. The clause which I found very interesting gives a dditional in fo rm a tio n ; we can s till identify the papers w ith o u t this in form a tion . vk.com/bastau P re -In te rm e d ia te B usiness G ra m m a r TASKS E S E & i Undertine five relative clauses in the text below. Label them defining clauses [Dj o r non-defining clauses [NDj. Salisbury Tel: 01722 368359 ANTIBIOTICS TODAY The conference, w hich w ill discuss the action of a n tib io tics on diseases, w ill be held at U niversity College, w hich is one of the oldest colleges in the city. People w ho w ish to attend should send an application fo rm to the P resident of the Society, who is in charge of bookings. Anyone who is presenting a paper at the conference w ill a u to m a tica lly receive fu ll details. Combine the sentences below into single sentences with a relative clause. 1. Our clothes are very fashionable. They are p opular w ith young people. Our clothes, which are very fashionable, are popular w ith young people. 2. The w om an said o u r collection was w o n de rfu l. She is the e d ito r of Style. 3. We use the best agencies to show o u r collection. They charge a lot of money. 4. We depend on m agazine publicity. This increases our in te rn a tio n a l reputation. 5. Many im p o rta n t m agazine editors attend the fairs. They have massive influence. 6. The design team is very experienced. They plan o u r participation. S335ESB Write sentences with the prom pts below. Include relative clauses using the words in brackets. 1. Our com pany (m akes floors) grow /by 10% per year. Our company, which makes floors, is growing by 10% per year. 2. The D irecto r (came here yesterday) be/Italian. 3. Our m ain clie n ts (in Europe) b e/sports clubs. 4. In 2008 (record year) w e /s u p p ly /flo o rs /fo r the Olympic Games. 5. Our R and D in stitute (based at Newtown University) develop/new flo o r m aterials. 6. The flo o rs (w e/send/to F in la nd /la st year) are specially fo r o utd oo r use. Transfer Write four sentences, including relative clauses, about the town where you live. vk.com/bastau 119 UNIT Clauses of Cause or Reason with Because See also Unit 58 Subordinate clauses A Sample sentences I am going to do the training because I w ill learn something from it. We spent the money because w e needed new equipment. I am calling because I would like your help. B Form A clause of cause/reason is a type of subordinate clause. Clauses of cause/reason begin w ith a subordinating conjunction. (See Unit 58.) Because is a subordinating conjunction of cause o r reason. C Uses Clauses of cause or reason answ er the question 'why?'; they present the cause or the reason. A: Why are you leaving early? B: Im leaving because I want to catch my train. A: And why are you joining ITCorp? B: I am joining ITCorp because they have offered me an interesting job. And why are you moving to SoftSys? A: Because I've worked at ITCorp for 15 years and I need a new challenge. Our fin an cia l position changes during the year because o u r sales are seasonal. They are seasonal because we have always been sp ecialists in w in te r clothing. This creates problem s because in s u m m e r we have a shortage of money. We are planning to e nter new m a rke ts because, if we do not, we w ill not survive. Exercise 2 Complete the following by w riting clauses o f cause or reason based on the prom pts below. Exercise 3 Use the prom pts below to w rite a paragraph with clauses o f cause or reason with because. Example: John resigned because he was not happy. He was not happy because his salary was too low. His salary was too low because he had few responsibilities. He had few responsibilities because the company had too many m anagers. Write a paragraph about yo ur recent activities. Include examples o f clauses o f cause or reason with because. vk.com/bastau 121 UNIT Singular and Plural Nouns # a Unit 62 Countable and uncountable nouns A Sample sentences The company has its main office in Hershey, Pennsylvania. The company has branches in 172 countries. The Japanese subsidiary is in Nagoya. The organisation employs 180,000 people w orldw ide. B Form A noun is a g ra m m a tica l unit. If we can put a or an in fro n t of the sin g u la r form of the noun, we c a ll it a countable noun. (See U nit 62 fo r uncountable nouns.) a company an account an agent a branch a firm an em ployer a meeting a magazine We use a if the noun begins w ith a consonant; we use an if the noun begins w ith a vowel, a job a factory a plant an agency an employee an industry an organisation an update (but a union} A fte r a sin g u la r noun we use a sin g u la r verb; a fte r a p lu ra l noun we use a p lu ra l verb. Notes 1. Some countable nouns only have a p lu ra l form . The m ost com m on is people: There w ere 20 people at the m eeting, [not: there was 20 people) 2. Some nouns only have a p lu ra l fo rm , but are not countable. Some com m on ones are: assets 1financial1 contents funds Imoneyl headquarters prem ises Ibuildingsj savings C Uses Look at the follow ing sentences. Each sentence has at least one countable noun in the s in g u la r o r the plural. singular export exports fish accountants capital figure sales Exercise 2 Complete the following text by choosing the correct alternative fo r each noun. Every year/years the com pany publishes its a nnual account/accounts in a report fo r the shareholder/shareholders. The m ain detail/details concern the fin a n cia l report. This contains inform ation/inform ations about sale/sales, turnover/turnovers, cost/costs and profit/profits. It also re p orts the asset/assets th a t are held by the company, and the liability/liabilities. These are any debt/debts or cash/cashes th a t the com pany owes. A ll this data/datas is presented in the pro fit and loss/profits and losses account and the balance sheet. Exercise 3 Complete the dialogue by referring to the pictures a A: Where is your _ (a )? B: It's near O rleans but o u r __________ (b) is in Paris. A: How m a n y __________ (c) do you have? B: About 2,000 including o u r ______ >___ (d). A: W hats the a n n u a l_________ (e)? B: This year it ll be about 85m. A: And w hat w ill be t h e _______ e) on that? B: Around 5m. G-Com Estimate 4 (Year ending) Turnover: 85m Profit: 5m Transfer Write a short paragraph including the following nouns used either in the singular or in the p lu ral as necessary vk.com/bastau 123 UNIT Countable and Uncountable Nouns 62 See also Unit 61 Singular and plural nouns A Sample sentences We buy a ll our computers from one supplier. We believe that they m ake the best equipment. Airlines make big profits on transatlantic flights but they lose money locally. B Form A noun is a g ra m m a tica l unit. If we can put a or an in fro n t of the noun, we ca ll it a countable noun. (See Unit 61 fo r sin g u la r and p lu ra l nouns.) If we can't put a o r an in fro n t of the noun, we ca ll it an uncountable noun. A countable noun has a sin g u la r and p lu ra l fo rm ; an uncountable noun has only one form . We would like to buy a machine. s in g u la r countable We would like to buy 20 machines. p lu ra l countable We would like to buy some machinery. [not: m achineries) uncountable The inform ation is in our brochure, [not: the in form a tion s are! uncountable noun + s in g u la rv e rb C Uses Look at the follow ing sentences. They show the use of countable and uncountable nouns. A: Could you give me some inform ation about your training programm es? [not: some inform ations) B: Of course, I'll send you some details. vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Read the following extract from a newspaper report. M ark a ll the nouns countable singular ICl, countable p lu ra l (CPl, uncountable singular (U) o r uncountable p lu ra l (UPl. CHANGES IN RETAILING The rationalisation of retailing has been a major characteristic of recent years and many small shops have disappeared. Large chains j and supermarkets now dominate the sector In the UK, 70% of food is I sold by just four retailers. Many people have criticised this trend. They say it leaves the consumer with less choice. Exercise 2 Underline the m istakes in the following sentences. Correct them. 2. How m any w o rks have you had since you left school? 4. Please can I change this money? I need som e coin for the telephone. W ith pleasure. Exercise 3 Complete the following. 1. We dont have enough in form a tion . Ring them and ask fo r m ore d ___________ 2. John w o rks fo r a com pany that m akes a g ric u ltu ra l m ___________ 3. We are a financial services company. We give a ________ __on insurance, pensions and o th e r aspects of m oney m anagem ent. 4. I asked him fo r a __________ _ He made two s ___________First, do more advertising and secondly, find a new sales assistant. 5. Please can you help me w ith these c __________ ? They are very heavy. 6. John has changed his j _________ _. He now w o rks fo r a bank. 7. Many p __ _______ w o rk in insurance o r banking, but m ost w o rk in com m erce. Transfer Write sentences using fou r countable and four uncountable nouns. vk.com/bastau 125 UNIT Noun Compounds 63 See also Unit 61 Singular and plural nouns Unit 62 Countable and uncountable nouns A Sample sentences The cost of making a telephone call has fallen. The advertising campaign was a big success. I went for a job interview today. He handed me his business card. B Form A noun com pound is a phrase w ith two or m ore nouns together, e.g. computer software noun + noun 1. The firs t noun is like an adjective; it gives m ore in form a tion about the second noun: A: I need some inform ation. B: W hat type of inform ation? A: I need some product inform ation. C Uses We use noun com pounds because: A: This approach to m anagem ent development requires a serious com m itm ent by the organization, [rather than the developm ent of m anagem ent) B: I agree. We need more training sem inars. (ra th e r than se m in a rs fo r training) Notes Some noun com pounds are w ritte n as one word: chequebook taxpayer newspaper flow chart notebook vk.com/bastau P re -In te rm e d ia te Business G ra m m a r Make nine noun compounds from the following words. Exercise 2 Read the le tte r below. Rewrite it as a fax, replacing the underlined words with noun compounds. EJ Metal Co Ltd, Unit 48, Ciough Rd Industrial Estate, Hull, HU6 4PY Tel. 01482 662841 Fax 01482 662800 above number to the above number ASAP. Yours sincerely Thanks f i j . O R o u rk e P.J. ORourke Exercise 3 Complete the noun compounds in the following. 1. When do you eat in the m iddle o f the day? I eat a t about lu n c h tim e . 2. If you apply for a job, you complete and send a j __________ a __________ 3. The result o f the test is a t ___________ r __________ U. When you need to change money to another currency, you ask fo r the e _ r __________ _ 5. If a company wants to spend money on advertising, it prepares an a_____ 6. Before getting on a plane, you have to wait in the d 7. People who travel a lot on business make many b _ 8. We use a lot o f computers. We live in an age o f i __ Transfer Look in an English language newspaper o r magazine. Find ten examples of noun compounds. vk.com/bastau UNIT Genitive Forms See also Units 61, 62, 63 Nouns A Sample sentences I disagree w ith M r Bajajs statem ent. The article appeared in todays edition of the Times. The companys sales fe ll by 3.8% . She looked around for the ladies toilet. B Form We form the genitive of a noun w ith an apostrophe () or w ith the preposition of: this year's results (= the re su lts of this year) the Directors' decisions (= the decisions of the directors) the launch of the product the cost of m aterials Note W here we form the genitive w ith an apostrophe, we w rite : 's if the noun is singular, e.g. the companys results (= the re su lts of the company) s' if the noun is plural, e.g. the companies results (= the re su lts of the companies) C Uses 1. We typically use the genitive w it h 's o r s' w ith the follow ing nouns: a. hum an nouns.- Dr M ortons job b. a n im a l nouns: the dogs head c. tim e nouns, todays newspaper d. location nouns: A m ericas economy e. organisation nouns: the Boards decision {but the C hairm an of the Board) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Underline genitive form s in the following extract from a speech by Alex Conrad, Chief Executive o f Tambo Inc., a food manufacturer. 'Tambo's re su lts are very good. Last year's fig u re s were also pleasing, but now our tu rn o ve r has improved by 15%, Our co m p e tito rs re su lts are not as good. The w o rk of a ll o u r staff has been excellent. Our products have answered the needs of o u r custom ers. The com pany's dedication to quality has been total. The decision of the Board to e n te r new m a rke ts was also very im p o rta nt. The fo rm e r Chief Executive, B ill Machin, made a very big co ntribu tio n - B ills ideas m ade Tambo the success it is today. Exercise 2 Choose the correct genitive form fo r each o f the following. 1. a. the ca r of Fred b. Freds car c. Freds car 5. a. the w o rk e rs canteen b. the canteen of the w o rke rs c. the w o rke r's canteen Exercise 3 Complete the text below about the future for Frodo, an engineering company. Write appropriate genitive form s to combine the words in brackets. The results of the tests (results/testsj were very good. The__________ [report/Research Director! was very positive. We hope that a l l __________ [custom ers/Frodol w ill like the new product. We think it w ill m e e t__________ Ineeds/our customers!. I agree w ith ___________ [opinion/John Tudor]. He th in k s __________ [m arket share/Frodo) w ill increase. With this new p ro d u ct,__________ [perform ance/next year] w ill be very good. As always, we m ust focus on the __________ Iquality/our products and services]. The____________ Ispeech/Chairman] at the AGM w ill say that quality and new products are m ost important. Transfer Look in an English language newspaper or magazine. Identify ten genitive forms. vk.com/bastau UNIT Adjectives vs. Adverbs 65 See also Unit 66 Comparison of adjectives B Form Adjectives and adverbs are g ra m m a tic a l units. C Uses We use an adjective: 1. to give m ore in form a tion about a noun: We need skilfu l m anagers. adjective + noun W hat type of managers? S kilful m anagers. 2 . a fte r the verb be: She is fluent in English, [not: fluently) We use an adverb: 1 . to give m ore in form a tion about a verb: She speaks English fluently. verb + adverb SISSIOSSSSDI Label eight adjectives ladjl and seven adverbs (advj in the following extract from a report on MODO, a clothing company. Excellent re su lts have helped MODO. In an unusually w et sum m er, the com pany did really w ell. The fashionable clothes were p opular w ith young consum ers. Now the com pany w ill definitely increase its production. Staff are busily planning an equally successful range fo r next year, but the m a rke t w ill be very com petitive. Exercise 2 Complete the crossword with adjectives and adverbs using the clues below. A cross 1 competes w ell (11) 5 one left over; n o t even (3) 7 n ot right (5) 10 the same (9) 11 in telligent (6) 12 n ot late (5) 15 o fte n (10) 16 d iffic u lt or n o t so ft (4) Down 2 n ot young (3) 3 new fo r the m arket (10) 4 more or less (13) 6 n o t going fast (6) 8 fundam ental (7) 9 every three m onths (9) 13 obvious (5) 14 arriving w hen the plane has le ft (4) Exercise 3 Complete the following dialogue. Two managers are discussing plans. Choose the correct alternative. A la n : The changes in the m a rke t are going to affect the com pany quite serious/seriously. Helga: We need to m ake som e quick/quickly decisions. A la n : We urgent/urgently need a new m a rketing strategy. Helga: Fortunately/fortunate, the products are excellent/excellently. A la n : I agree absolute/absolutely, but we have to get people interesting/interested. Helga: I m confidently/confident tha t we w ill do that. A la n : Good, because o u r sales have fallen dram atic/dram atically. Transfer Describe a business you know well. Describe its activities and trading performance. Use words like good, big, usually, modern, quickly, absolutely, etc. vk.com/bastau 131 UNIT Comparison of Adjectives 66 See also Unit 65 Adjectives vs. adverbs B Form Many adjectives have three fo rm s: positive, com parative and superlative: Last year Manson had h ig h profits, (positive adjective) Last year Burton had h ig h e r profits than Manson. (com parative adjective) Checkout had th e h ig h e s t profits, (superlative adjective) 1. If the positive adjective has one syllable, we fo rm the com parative by adding -e r and the superlative by adding -est: Positive long longer longest high higher highest cheap cheaper cheapest Positive easy easier easiest narrow narrower narrowest simple simpler simplest 3. For o th e r adjectives w ith two syllables o r more, we fo rm the com parative w ith more and the superlative w ith most: Positive Comparative modern more modern most modern expensive more expensive most expensive competitive more competitive most competitive 4. There is a s m a ll group of adjectives w ith irre g u la r com parative and superlative form s: C Uses 1. If we com pare two objects, we use than in the com parative: Burton's products are more expensive than Manson's, but th e ir profits are higher. 2. If we com pare m ore than two objects, we use the in the superlative: Checkout has th e most expensive prices and the highest profits. 132 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 2 Look at the graph. Mark the sentences true IT] o r false IF]. A unit price unit 8.20 1. Product B :he m ost successful. sales *.B unit price 9.00 2. Product A Write sentences comparing the three banks. Use form s o f sm alt, big, m uch 12], strong. Gold Bank has the fe w e s t branches. It has a __________ m arket share than Rotobank Ltd. Gold Bank h a s __________ capital reserves. It i s ___________ bank. In term s o f branches, Credit Bank International is __________ than the other two banks. It has m a n y______ ___ branches. It also h a s __________ capital reserves than Rotobank Ltd. Transfer Compare your country with another country you know. Write six sentences. vk.com/bastau 133 UNIT Adverbs 67 See also Unit 65 Adjectives vs. adverbs A Sample sentences Firstly, we offer inform ation and advice. The com puter w ill be delivered soon. Please check your order carefully. Government spending is slightly higher than forecast. B Form 1. Most adverbs are form ed by adding -ly to the adjective, e.g. quick - quickly. (See Unit 65.] 2. Some adjectives have the same fo rm as adverbs, e.g. hard, late. (See Unit 65.) 3. Some adverbs have no adjective fo rm , e.g. very, soon, outside. 4. The adverb of good is well. C Uses 1. There are three types of adverbs: b. Adverbs of tim e answ er the question when?, how long? or how often?: Can we ta lk about this tom orrow ? (When can we ta lk about this? Tomorrow.) I have always lived in Boston. (How long have you lived in Boston? Always.) We never sell any of our m ailing lists. (How often do you s e ll you m ailing lists? Never.) (See Unit 67.) 2. Position of adverbs We can often put adverbs in d iffe re n t positions in a sentence. The three main positions are: vk.com/bastau P re -In te rm e d ia te B usiness G ra m m a r TASKS Label the adverbs below place (P], time IT] o r m anner (Ml. Exercise 2 M r Roach had to go to a business meeting at 2 o clock. Look at the pictures below. Complete the sentences using words from the box. Exercise 3 Complete the following sh ort dialogue. Use the words in the box. A: Is M rs King there? B: No, sorry. She is out. A: When w ill she b e ___________ ? B: Perhaps s h e 'll be b a c k __________ today. A: OK. Ill p h o n e ___________ B: Can I take a message? A: Well, yes please. Tell h er the meeting w ith Blanchard w ent v e ry ___________We have to prepare a c o n tra c t__________ , but it m ust be d o n e ___________ The details are very im portant. B: OK. Thanks. Goodbye. Transfer How long have you lived in your town? When do you norm ally have a holiday? How w ell do you speak English ? Where do you go a fte r work? vk.com/bastau 135 UNIT Expressions of Frequency 68 See also Unit 67 Adverbs A Sample sentences How often do you see her? We always keep cash for em ergencies. He rarely goes out to dinner. The industry holds a trade exhibition twice a year. B Form We can divide expressions of frequency into indefinite frequency and definite frequency. 1. Indefinite frequency most often usually/norm ally often som etimes rarely/setdom never least often 2. D efinite frequency These phrases te ll us m ore precisely how often som ething happens in a period of tim e: C Uses 1. Q uestions about frequency: How often do you go to head office? Make frequency adverbs from the following ju m b le d letters. Then num ber them 1-7, in order of frequency. always Exercise 2 Complete the following phrases with an expression o f frequency, based on the w ordlsj in brackets. _______ [December]. 6. Our Sales Report is p u b lish e d _______ Exercise 3 Two people are in an a irp o rt departm ent lounge in Amsterdam. They are waiting fo ra flight to New York. Complete p art o f the conversation with frequency expressions from the box. Transfer Write sentences about what you do and do not do. Use frequency adverbs to say how often. vk.com/bastau UNIT Degree with Very, Too and Enough See also Unit 67 Adverbs A Sample sentences It is very difficult to estim ate the size of the m arket. There is too much w ork for one person. The building is not big enough fo r our needs. B Form Very, too and enough are adverbs. (See Unit 67.) We put very and too before an adjective o r adverb: Rotaronga is a very industrial region. adjective In fact, industry has grown too quickly. adverb We put enough a fte r an adjective or adverb: Social services have not increased fast enough. adverb Note We put enough before a noun: The area already has enough factories. noun C Uses 1. Very m akes the m eaning of an adjective or adverb stronger: A: A ll his staff are intelligent. B: Yes, and some of them are very intelligent. A: They answered our questions quickly. B: Yes, but they didn't answ er them very accurately. 2. Too m eans m ore (or less) than necessary; enough m eans acceptable: A: Our m anufacturing tim e is too slow. B: I agree, it is not fast enough. But our w orkers are w e ll paid. A: Yes, but they think th e ir w ages are not high enough. They think they are paid too little. 138 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS faSBfBBSn Add very, too or enough to the following phrases. __________ time __________ dangerous difficult not big strong im portant beautiful profitable many people Exercise 2 Complete the comments on these dishes in a restaurant. Z e C 04 d O r fjl0 Exercise 3 Complete the following exchanges with appropriate words. A: T heres a lot of tra ffic on the roads. B: Yes, I agree. T heres __________ m uch. A: The Chien Andalou re stau ra n t is one of the best in town, B: Yes, and n o t__________ expensive. Everything is _______ fresh. Transfer Write six sentences about yo u rse lf and your work o r studies. Include very, too and enough. vk.com/bastau UNIT Already, Yet, Again and Still See also Unit 67 Adverbs A Sample sentences Have you got your m edical insurance yet? We have already sold more than 300 units. When w ill you play it again? The company can s till afford to advertise. B Form Already, yet, again and still are adverbs of tim e. (See Unit 68.) C Uses 1. Already m eans 'by th is /th a t tim e '; we use it in positive statem ents: This year we have already hired 50 people, (by th is tim e, i.e. by now) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Read the following text. Underline examples o f already, yet, again and still. Then m ark the statem ents that follow as true [Tj o r false IF}. John is s till w aiting fo r a new contract. The com pany have not agreed the te rm s yet. John may leave. In fact he's already had an interview w ith a no the r company. Anyway, to m o rro w he's going to ta lk to his boss again about the contract. Exercise 2 Choose already, yet, again or still to complete the dialogue below. Exercise 3 Complete the text below with a word in each space. Last year o ur sales overseas were down. This year exports a re ___________ poor. We expect low export p ro fits __________ , but the good news is that in o ur domestic m arket we have________ reached o ur targets. Overall, things are not s e rio u s __________ The situation w ill be clearer at the end o f the year. Transfer Write six sentences about yo u r actions or yo ur plans. Include already, yet, again and still. vk.com/bastau UNIT Articles 71 See also Units 61, 62 Nouns A Sample sentences They signed a contract to purchase two planes. He's an agent for an insurance company. The address of the company is on the policy. At present sales are increasing. B Form There are three fo rm s of the a rticle : C Uses 1. A(n) - the indefinite a rticle We use a(n) w ith sin g u la r countable nouns (see Unit 61) when we use a word fo r the firs t tim e: A com puter usually has a keyboard. vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS A travel agent telephones Henry Fish with details o f his trip to M unster in Germany Underline all definite and indefinite articles. Indicate zero articles before uncountable nouns and before p lu ral countable nouns with a zero 101. 'Mr Fish? I have, got details for your trip to Munster today. First, the flight. There's a British Airways flight from London Heathrow to Dusseldorf at 16.05 from Terminal 1. It arrives at 17.35. Then you can take a train to Munster from the central station at 18.45. The train arrives in Munster at 20.15. Coming back there's a flight to Manchester at 16.30, arriving at Manchester Airport at 17.50. There are trains every hour from Manchester to Leeds. You also asked about money and the ticket. You can change money at Heathrow and pick up the flight ticket from the B.A. desk in Terminal 1.' Exercise 2 Read the dialogue about a problem in a chem ical plant. Put in articles where necessary. Exercise 3 Below is an advertisem ent flye r from Beelo 0E Ltd, office furniture designers. Complete the text with definite o r indefinite articles in the spaces if necessary. Transfer Look at any sh ort text from an advertisement, a newspaper or a magazine in English. Circle the use o fte n definite, indefinite, o r zero articles. vk.com/bastau 143 UNIT Personal Pronouns 72 See also Unit 73 Possessive and reflexive pronouns A Sample sentences We are going to m eet them tom orrow. Ill send them fu ll details. B Form We use a pronoun in place of a noun: The company is based in Bolton. It employs 200 people. (= the company) This is the Marketing Director. She joined the organisation three years ago. (= the female Marketing Director) Notes 1. We use he/him fo r men and boys; we use s he/her fo r w om en and g irls; we use it fo r a ll n on -p e rso na l form s. C Uses A: Id like to introduce you to Karen Pusey. B: I m et her last w eek. She is the new publisher. A: Yes, you are right. I forgot you w ere with us here last week, Note I am sending you our latest catalogue. (I = the person) We are sending you our latest catalogue. (We = the company) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS Exercise 2 Wim van d e rJ o n k visits Educo, an Irish producer o f educational materials. Here is p a rt o f a conversation with Joe Keeley, a Sales Manager. Write personal pronouns in the spaces. Exercise 3 Rewrite the em ail below. Replace the words in brackets with personal pronouns. Best regards J Sam * Transfer Write one o r two paragraphs about some o f your colleagues. Include as many personal pronouns as you can. Underline the personal pronouns. Example: Two colleagues w o rk w ith m e. They are . . . vk.com/bastau 145 UNIT Possessive and Reflexive Pronouns See also Unit 72 Personal pronouns B Form We use a pronoun in place of a noun. 2. We use a reflexive pronoun when the object is the sam e as the subject: I would like to introduce myself. subject = object I lljlS -* iilSEBSiil 1st person singular my mine myself plural our ours ourselves 2nd person singular your yours yourself plural your yours yourselves 3rd person singular masculine his his himself feminine her hers herself non-personal its its itself plural their theirs themselves Notes 1. We use the possessive d e te rm in e r in fro n t of a noun: We would like to reduce our overheads. possessive d e te rm in e r + noun C Uses 1. Possessive pronouns: A: My company develops softw are products. (I am the ow ner of the company.) B: Are you the owner? A: Yes, the company is m ine, (m ine = my company) 2. Reflexive pronouns: Welcome to our first meeting. First, Id like to introduce myself. I'm Janet Aspinall. Now could you say a few words about yourselves? vk.com/bastau 146 I P re -In te rm e d ia te Business G ra m m a r TASKS pBTHHUI Underline examples o f possessive and reflexive pronouns in the extract below. Label them RIreflexive], PDIpossessive determ iners] o r PPIpossessive pronouns]. Exercise 2 Correct the following sentences. Exercise 3 Complete the sentences below each picture. Include a possessive or reflexive pronoun. Transfer Write five sentences about you and your family, or about colleagues at work. Use possessive and reflexive pronouns. vk.com/bastau I U7 UNIT Demonstratives 1 U A Sample sentences A: Hello, is that the M arketing Departm ent? B: No, this is Customer Services. B Form D em onstratives point to som ething near or som ething fa r away: I don't understand this analysis, (the analysis here) I didn't attend that presentation, (the presentation there o r then) iS IS iffl SbmI Near reference this these Far reference that those C Uses 1. N ear reference can be: a. near in space: His secretary left these documents for you to look at. (the docum ents here) b. near in tim e: Can I come and stay w ith you this week? (the week now) c. near in the text: Payment should reach us by 1st July. This guarantees your rights, (payment by 1st July) vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS igggsii Cathy is showing a visitor around h er company Look at the demonstratives in the sentences below. Label them near [N j o r far [F j + singular ISI or p lu ra l IP}. The firs t has been done fo r you. Exercise 2 Carla and Petra are spending an evening together in a hotel. Complete the following exchanges with appropriate demonstratives. Exercise 3 Alex works f or a drinks manufacturer. He is m aking a presentation. Complete the spaces with a demonstrative. 1 . ________ picture shows our best seller, ZIGGO___________ is very popular with children. A few m inutes ago I mentioned PIPPO________ __ is also m ainly fo r children. 2. Last year we agreed new prices. Now we k n o w __________ prices were too low. 3. In term s o f m arket share, there are five very sm all players. A t least two o f ___________ w ill disappear, e ith e r__________ year o r next. Transfer Look around you. Write fou r sentences about things you can see using this, these, that and those. vk.com/bastau 149 UNIT Some and Any 75 See also Units 61, 62 Nouns Unit 76 Some, any and related words A Sample sentences We are waiting for the delivery of some new equipment. I didn't buy any tickets. Have you received any inform ation about the event? If you have any fu rth e r questions, please call me. B Form Some and any can be pronouns (see Unit 72) and d ete rm ine rs. D eterm iner I need some information. I dont need any information. Do you need any information? Pronoun Id like some, please. I dont need any. Do you need any? C Uses We use some and any w ith p lu ra l nouns, e.g. managers, and w ith uncountable nouns, e.g. information. 1. Some a. in positive statem ents: b. in polite offers: 2. Any a. in questions: 150 vk.com/bastau P re -In te rm e d ia te Business G ra m m a r TASKS P 39H H H M Steve M arshall and Ben Long work fo r an engineering company. Steve has ju s t returned from a week in Kuala Lum pur, at a trade fair. Underline examples o f some and any. Label the sentence with some o r any as positive statem ent IPS], negative statem ent iNSj o r question [Q]. Exercise 2 Identify six mistakes in the following. Correct them. Paula: We havent launched any new products th is year. Last year we had any. Four, in fact. We need som e fo r next year. Mohammad: I w ould like to show you designs. Exercise 3 Two colleagues are talking about a printing job. Put some or any in the spaces. Transfer Write a sh ort dialogue about buying something in a shop o r from a company Sales Office. Include some and any vk.com/bastau 151 UNIT Some, Any and Related Words See also Unit 75 Some and any A Sample sentences Someone must install the equipm ent before it can be used. Do you want to add anything to w hat I've said? Nobody in the company received an appraisal last month. Our pricing strategy is sim ilar to any other business. B Form Below are the m ain fo rm s of some, any and no words: C Uses 1. Some words We use these in positive statem ents: I spoke to someone from the m arketing departm ent. He told me something about the charitys w ork. I m et him som ewhere near Rennes. 2. Any words We use these in negative state m e n ts and questions: A: Does anyone have any questions? [not-, any question] B: You didnt say anything about the location of the new equipm ent. A: You can install it near the main area. B: But can we place it anywhere? 3. No words We use these in negative state m e n ts and questions: No-one has accepted the offer. Is there nothing else that we can do? The car is now produced in Mexico and nowhere else. vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r TASKS E E 33M 1 Underline examples o f some, a ny and related words in the text below. Label them positive statem ent IPS], negative statem ent INS] or question IQ]. A: Is anything wrong? B: Yes, there's som ething wrong w ith one of o u r production m achines. No-one knows what the problem is. We've looked in the U se rs M anual but we cant find the solution anywhere. A: Have you contacted the m anufacturers? B: Yes, they th in k it s nothing very com plicated. Theyre sending som eone to visit us. Hell be here soon. He was already som ew here near here. Exercise 2 Choose the best meaning a, b, or c fo r the sentences 1-5. Exercise 3 Ella and Pat are staying in a hotel. They are talking about problems. Complete the spaces in the conversation. Use words from the box. Transfer Is there anyone working with you who speaks French ? Have you been anywhere interesting recently? Does no-one help you with y o u r work? Say something about yo u r job. Describe somewhere you have been recently. vk.com/bastau I 153 UNIT Quantifiers (1) 77 See also Units 61, 62 Nouns Unit 75 Some and any Units 78, 79 Quantifiers A Sample sentences Our website lists a ll the products that are available. We have upgraded most of our hotels. Do you have a lot of im portant m eetings to attend? They had some problems with th e ir suppliers. The hotel is fu ll. There are no rooms available. B Form C Uses A: Do you know a ll the people here? B: I know most of them , [not: the m ost of them ) A: W here did you m eet them? B: I m et some of them at the last sales conference. A: I see. So, let's start the m eeting. We have a lot of points to cover. There is no tim e to lose. |3 !H W S B 1 Exercise 2 The table gives the results o f a quality test on electrical components atAPKAL Ltd. ioo% 0% 0% KBIBIIEL- fe | 88% 10% 2% Exercise 3 Replace the underlined words with a word o r phrase from the box. Change the verb if necessary. Transfer Write sentences about a company you know. Use quantifiers. vk.com/bastau UNIT Quantifiers (2) 78 See also Units 61, 62 Nouns Unit 75 Some and any Unit 77 Quantifiers (1] Unit 79 Quantifiers (31 A Sample sentences They d id n 't spend m uch m oney. How m any em p loye e s do th e y have? H ere are a fe w o f m y su g g e stio n s. L et m e give you a lit t le advice. B Form We use countable qua n tifiers w ith p lu ra l countable nouns; we use uncountable q uantifiers w ith uncountable nouns. (See Unit 62.) They o n ly m ade a fe w re co m m e n d a tio n s. q u a n tifie r + countable noun They o n ly gave us a lit t le advice. q u a n tifie r + uncountable noun C Uses 1. Much, m any and a lo t of a. in statem ents: T here a re n 't m any to u ris ts a ro u n d in th e w in te r, (m any + countable noun) People d id n 't e a rn m uch m oney in th e 1940s. (much + uncountable noun) We n orm a lly use m uch and m any in negative statem ents; in positive statem ents, we often use a lo t of w ith both countable.and uncountable nouns: We w e re given a lo t o f e q u ip m e n t. b. in questions: How m uch do I owe you? (how m uch money) How m any com panies in cre a se d th e ir e a rn in g s la s t y e a r? (m any + countable noun) How m uch w o rk are you p re p a re d to do? (m uch + uncountable noun) E G 33M 1 Am y wants to hire a car. Identify seven quantifiers in the following dialogue. M ark them countable (Cl o r uncountable (U l Exercise 2 Boris runs a m obile phone rental company Here he talks about his business. Choose the correct quantifiers from the alternatives. We hire m obile phones. We have m u ch/all types of phones. We keep a lot of/no phones in stock. Most/a lot o f are hired fo r ju s t one day. A little /a few o f o u r cu stom ers keep them for a m onth o r two. Not all/few /m any people hire phones fo r longer than many/a few w eeks. CITY M O B I L Exercise 3 Replace the underlined phrases with quantifiers. Do not change the meaning. 1. Not many and not enough people understand how to program com puters. 2. There is not m uch and not enough dem and fo r o u r products. 3. We made not many but enough contacts at the Singapore Trade Fair. 4. There was some, but not m uch c ritic is m in the report. 5. A large n um be r of people answered o u r advertisem ent. 6. Not even one applicant w as good enough fo r the job. Transfer Write five sentences about jo b s, job advertisements, applications and people looking for work in your home town. Use quantifiers. vk.com/bastau 157 UNIT Quantifiers (3) See also .............................. .......... ,.11 Units 61, 62 Nouns Units 77, 78 Quantifiers A Sample sentences Hotel staff check each room before guests arrive. They meet every morning at 7.15. All employees must be given a written contract. B Form During their visit we show them all the machinery in the factory. q u a n tifie r + uncountable noun C Uses Each and every have very s im ila r m eanings. 1. Each Police were checking each car. (many cars, one by one) The fee for each session is 50. (each individual session) (n o t: each sessions) 2. Every Every department faces cuts, (a ll departm ents, w ith o u t exception) There is a staff meeting every Monday morning, (each Monday m orning, w ith o u t exception) 3. All We send all our clients a weekly update on airfares, (every/each client) They paid all the money last week. Note every + sin g u la r noun = all + p lu ra l noun: Every manager/all managers must plan, lead, organise and control. 158 vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r TASKS Exercise 2 How many combinations with every, each and all can you make with these words o r phrases? Try to write fu ll sentences. person money custom er products inform ation o f us week departm ent Examples: In a team, each person has an important role to play. Every person in this room is wearing shoes. All the money in the world wouldn't change me. Exercise 3 Complete the sentences below using each, every or all + a word o r phrase from the box. The firs t has been done for you. Transfer Write five sentences about yo u r home town. Include each, all, every vk.com/bastau UNIT Numerals 80 See also Business File 5 Numbers, dates and times A Sample sentences Ten new plants will be built in the next five years. This is the third time the company has been sold. Department managers must spend half their time on the sales floor. The committee meets once a month. B Form 1. C ardinal num bers 4. Frequency expressions once twice three times fou r times etc. C Uses A: How many people does ITCorp employ? B: We have about 5000 people at 28 plants worldwide. A: And how long have you worked for the company? B: I joined them in 2008. A: And where were you before that? B: Before ITCorp I worked for GloboSys for 5 years. A: So is ITCorp your second job? B: Yes. And how often do you come here? A: I visit the country three times a year. At present we are thinking of building a second factory here. B: Yes. The economic situation is very healthy at the moment. A: Inflation is only 2.5%. So its an attractive place to invest. P re -Inte rm e d ia te Business G ra m m a r vk.com/bastau TASKS Exercise 2 Read the following details about Abacus pic, a UK-based m anufacturing company. Write a ll the num bers as you would say them. Exercise 3 Use the table to give inform ation to a colleague. Write exactly what you say in the spaces. Transfer Find a newspaper or another document with a lot o f num bers in it. Practise reading them aloud. vk.com/bastau UNIT Time Unit 17 The present perfect with for, since, ever and never A Sample sentences We agreed a deal in 2005. The meeting w ill start at 8.30 and finish at 10.30. The course w ill be held for six w eeks from Novem ber 6th. I expect to be back in Britain on Decem ber 18th. B Form A preposition is a g ra m m a tic a l unit. It comes in fro n t of a noun, e.g. in the morning. preposition + noun The m ost im p o rta n t prepositions of tim e are: C Uses 1. At, in, on and by at + clock tim e at 6 oclock in + parts of the day in the m orning/afternoon/evening [but: at night) on + days of the week on Monday on Thursday afternoon on + dates on 3rd May (spoken: on the third of May) in + m onths and years in May in 1997 (spoken: in nineteen ninety-seven) by + a deadline You must finish the report by U o'clock, (at the latest) 2. By and u n til/till 3. No preposition P re -Inte rm e d ia te Business G ra m m a r vk.com/bastau TASKS A: W hens he conning? B: In the m orning. A: Before 10 oclock? B: Probably. Well show him the factory fo r an h ou r o r two, then when Ju lie arrives at 12 oclock w e ll have o u r m eeting. A: So, during lunchtim e? B: Yes, from about 12 t ill around 2.30. A: We m ust be finished by 3 because w e ve an appointm ent w ith Axis in the afternoon. B: That' s no problem . Exercise 2 The time tine below shows the product development o f the XR20, a m in i television made by Camicam. Complete the text with prepositions from the box. sales growth ~T~ r 08 09 10 11 12 13 14 We researched the XR20 12 months, then ___ 2009 it went into production. _________ 15th January 2010 the product was launched. _______ then we have had good sales and we w ill break even_______ March 2011. We expect increasing s a le s __________about two y e a rs ,__________sales p e a k __________ the year 2013 that, the sales w ill decline. Exercise 3 Complete the sentences fo r the time lines below. vk.com/bastau 163 UNIT P lac e d ) 82 See also Unit 83 Place (2} A Sample sentences I paid in some money at the bank. Glover came into the office at 8am . He left his car in the car park. There's someone from People magazine on the phone. B Form A preposition is a g ra m m a tica l unit. It comes in fro n t of a noun, e.g. in the factory. preposition + noun The m ost im p o rta n t prepositions of place are: W alk into the main building; the reception desk is on the left. We im port our components from Rotaronga. C Uses 1. at We use at to describe a place w ith o u t any specific dim ensions: I'll see Lloyd tom orrow at the m eeting. A problem had arisen at w ork. 2. to We use to to describe m ovem ent to a place w ith o u t any specific dim ensions: He drove to w ork every day. We deliver the goods to our customers w ithin 72 hours. 3. from We use from to describe m ovem ent away from a place w ith o u t any specific dim ensions: He drove from the shipyard to Antwerp. R etailers buy goods from the manufacturer. U. in and into We use in to describe a place: I'll m eet you in the restaurant. We use into to describe m ovem ent to a place: They packed the goods into the lorry. A: We deliver the m aterials in cases. B: And w here do you deliver them? A: We take them into the warehouse. 6. on We use on w ith objects w hich have a surface: He looked at the notebook on his desk. There are some lovely salads on the menu. 164 vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r TASKS Exercise 1 La bet the following with prepositions o f place. X X X- Exercise 2 Correct the following, where necessary. Two sentences are correct. Exercise 3 Complete the description o f the process shown in the diagram. Use words from the box. The finished tablets are s e n t__________ the production area ______ this machine which puts th e m __________ sm a ll bottles. Labels are p u t__ ____ the bottles which are then p acked__________ boxes. The boxes are tra n sfe rre d _______ the warehouse. They are ta ke n __________ the w arehouse___________ the shops. Transfer Write seven sentences about yo urself o r about a place you know well. Include place prepositions at, to, from, in, into, out of, on. vk.com/bastau UNIT Place (2) 83 See also Unit 82 Place{1} A Sample sentences We w alked through the building to the main entrance. Graham pushed the report across the desk to me. The club is located above a restaurant. The w a te r is stored in a tank below ground level. B Form We use prepositions to describe: place (see also Unit 82) position m ovem ent (see also Unit 82). S om etim es, the same preposition can have different uses. C Uses 1- Describing position: The com puter room is above the reception area. We are planning to have a dem onstration room next to the reception area. vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r TASKS Underline the prepositions in the following. Mark them position [Pi o r movement [M l. When you arrive, go out of the a irp o rt and along the road to the taxis jl w aiting outside. Ask to go to Jasons, on High Street. Our offices are : between the Post Office and the Magnus foodstore. Were opposite Credit Bank International. Go through the main entrance and into the - lift. Go up to the fou rth floor. Were ju s t next to the fire exit. Exercise 2 Replace each preposition in the following sentences with another one which means the same. Match each sentence 1-5 with the correct diagram a-f. There is one more diagram than you need. Exercise 3 Look at this picture of a factory. production factory warehouse main office block offices A nsw er the questions. Choose words o r phrases from the box. You may use a word or phrase more than once. T ra n s fe r vk.com/bastau UNIT Like, As, The Same As and Different From 8Z A Sam ple sentences Superm arkets now s ell things like clothes and hom eware as w e ll as food. I w ork as a w a ite r in a hotel. Prices this year are the same as last year. The Japanese m arket is different from the US m arket. B Form Like, as and fro m are prepositions. We put a noun phrase a fte r a preposition: His briefcase is like a mobile office. preposition + noun phrase She w orks as a financial adviser. preposition + noun phrase C Uses 1. Both lik e and as mean the same as o r s im ila r to': a. like Even in countries like Germany and Sw itzerland, banks have been running into trouble. (s im ila r to) We make personal computers, like ITCorp. (the sam e as) b. as She w orks as a custom er service manager, (it is h er job) As you can see, the published accounts show little detail, [not: like you can see) c. the same as Flexitim e is the same as flexible working hours, (not: the sam e like) The airline faces the same problems as other airlines. vk.com/bastau 168 I P re -Inte rm e d ia te Business G ra m m a r TASKS E S 2 S 3 I Tick IS ] sentences 1-8 if you agree with them. If you do not agree, write a cross I/]. 2. German cars have an im age w hich is very different from the image of Japanese cars. 6. One fast food store is often the same as any o th e r fast food store. Exercise 2 Taruba is a car manufacturer. Here are details of two Taruba cars. Complete the advertisement below. The GX40 lo o k s ______________ the GX50. But the engine of the GX50 i s _____ ______________ the engine in the GX4-0. It is b ig g e r._____________ a ll Taruba cars, the GX m odels have a seven-year w a rra n ty_______________ you can see, we build fo r quality. ______________ you, we d on t w ant any trouble. Exercise 3 Here is p a rt o f the Chairman's annual address to the shareholders o f BBL pic. Five sentences have been ju m bled up. Rewrite them, beginning with the wordls] given. Transfer Write five sentences about yourself, o r about a company you know. Include Like, as, the sam e as and different from. vk.com/bastau 169 BUSINESS FILE Industries and Jobs INDU STRIES 1 Manufacturing Aerospace E lectrical P lastics A gricu lture & food Energy P ower generation production Engineering Pulp & paper A pparel & fashion Food & d rin k Rail Autom otive Furniture Road C hem ical Gas R ubber C onstruction M etal Telecom m unications Cosm etics & person onal M ining Textiles care Petroleum W ater Dyes & pigm ents P harm aceutical Services A ccounting In te rn a tio n a l relations Real estate A dvertising In te rn a tio n a l trade Retail A rch itectu re IT (Inform ation Technology) & S ecurity & protection Banking & fin an cia l telecom s Tax services Jo u rn a lism Tourism C harities Law Training (incl. education) Civil service Media T ransportation (incl. shippi C onsultancy M ilita ry Travel E nvironm ent Music U tilitie s Health & healthcare P olitics & governm ent Volunteering H otel & hospitality P rinting Insurance P ublic relations JO BS Departments/Divisions A dm in istra tio n Legal Purchasing Design Logistics (incl. d istribution) Q uality assurance E ngineering M arketing & PR (Public R ecruitm ent E nvironm ent relations) Research & developm ent Finance & accounting M a terials m anagem ent Sales G eneral m anagem ent HR (Hum an Resources) & S ecurity Health & safety tra in in g Training Inform ation technology Production J o u rn a lism Project m anagem ent vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r BUSINESS FILE Countries and Currencies 2 Country Currency Currency 1 Country Currency Algeria Algerian Dinar Italy Euro Peru Sol Argentina Peso Jamaica Jamaican Dollar Philippines Philippine Peso Australia Australian Dollar Japan Yen Poland Zloty Austria Euro Jordan Jordanian Dinar Portugal Euro Belgium Euro Kenya Kenyan Shilling Romania Leu Bolivia Peso Boliviano Kuwait Kuwait Dinar Russia Rouble Brazil Real Laos Kip Rwanda Rwanda Franc Bulgaria Lev Lebanon Lebanese Pound Saudi Arabia Riyal Czech Republic Czech Koruna Mexico Peso Sri Lanka Sri Lankan Rupee Denmark Krone Monaco Euro Sudan Sudanese Pound Ecuador US Dollar Mongolia Tugrik Sweden Krona vk.com/bastau BUSINESS FILE Business Abbreviations and ^ Short Forms vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r BUSINESS FILE British English vs / American English You can find difference between B ritish English (BrE) and A m erican English (AmE) at fo u r main levels: g ra m m a r pronunciation vocabulary spelling 1. G ram m ar Present perfect and past sim ple Have you done it yet? (BrE) Did you do it yet? (AmE) I have already done it. (BrE) I already did it. (AmE) I haven't done it yet. (BrE) I didn't do it yet. (AmE) Verb Phrases to m eet someone (BrE) to m eet with someone (AmE) to agree to a proposal (BrE) to agree a proposal (AmE) to appeal against a decision (BrE) to appeal a decision (AmE) 2. Vocabulary BrE AmE BrE AmE C o rp orate Language Chairman President Sales Manager Sales Director Managing Director Chief Executive Officer/ Board of Directors Executive Board Senior Vice-President G e n e ra l L a n g u a g e flat apartment fortnight two weeks autumn fa ll holiday vacation biscuit cookie motorway freeway/highway b ill (for payment] check petrol gas boot (car) trunk post mail centre (of town/city] downtown queue line chem ists shop/chemist pharmacy/drugstore rubbish garbage/trash chips (French] fries solicitor lawyer/attorney crisps (potato] chips tap faucet 3. Pronunciation BrE AmE detail detail interested in te re s te d research research hostile /ta il/ hostile / 1(a) 1/ vk.com/bastau BUSINESS FILE Numbers, Dates and Times A Num bers 5 We can divide num bers into: cardinals ordinals fra ctio n s and decim als frequency expressions 1. Cardinals 0 - nought, zero [especially fo r m a the m a tics and fo r tem peratures), oh (in B ritish English fo r telephone num bers), n il (in sports) 100 - a/one hundred. We offer a/one hundred different products. 101 - a/one hundred and one 1,000 - a/one thousand. At present we employ a/one thousand employees, [not: one thousand of) 1,000,000 - a/one m illio n 2. Ordinals 1st - first. The first of A pril (spoken) 2nd - second. This is the second tim e we have visited the Paris fashion show. 3rd - third. Our third attem pt to find an agent w as successful. 4th - fou rth . This is the fourth job I have applied for. 21st - tw e n ty-first. W e're living in the tw en ty-first century. 100th - (one) hundredth. This is our (one) hundredth trade fair. 101st - one hundred and firs t 1000th - (one) thousandth 3. Fractions and decimals 1/2 - (a) half. Over (a) half (of) our products are made in France. B Dates Notice the difference between the w ritte n and spoken fo rm s and between B ritish and A m erican English: We opened our new office on 5 A pril 2010. BrE (written) We opened our new office on the fifth of April, two thousand and te n *. BrE (spoken) o r We opened our new office on A p ril the fifth, two thousand and te n *. BrE (spoken) We opened our new office on A p ril 5th 2010. AmE (written) We opened our new office on A p ril fifth, two thousand te n *. AmE (spoken) *W e also say twenty ten BrE/Am E (spoken) 5 /4 /2 0 1 0 - BrE (w ritten) fo r 5 A p ril 2010, i.e. d ate /m o nth /ye a r 4 /5 /2 0 1 0 - AmE (w ritten) fo r 5 A p ril 2010, i.e. m o n th /d ate /ye a r C Times Notice the w ritte n and spoken form s: The meeting w ill start at 9 .0 0 /9 .0 0 a m /9 o'clock, (written) The meeting w ill start at nine a.m ./n in e o'clock, (spoken) The meeting w ill finish at 4.30 p .m ./16.30. (written) The meeting w ill finish at four th irty p.m ./(a) half past four/sixteen thirty, (spoken) vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r BUSINESS FILE Irregular Verb Table 6 be was/were been lie lay lain beat beat beaten lose lost lost become became become make made made begin began begun mean meant meant break broke broken meet met met bring brought brought pay paid paid build built built put put put buy bought bought read read read catch caught caught ride rode ridden choose chose chosen rise rose risen come came come run ran run cost cost cost say said said cut cut cut see saw seen do did done sell sold sold draw drew drawn send sent sent drink drank drunk set set set drive drove driven shine shone shone eat ate eaten shoot shot shot fall fell fallen show showed shown feel felt felt shut shut shut fight fought fought sing sang sung find found found sink sank sunk fly flew flown sit sat sat forget forgot forgotten sleep slept slept get got got (BrEj speak spoke spoken get got gotten (AmE) spend spent spent give gave given split split split go went gone stand stood stood grow grew grown steal stole stolen have had had strike struck struck hear heard heard swim swam swum hide hid hidden take took taken hit hit hit teach taught taught hold held held tell told told keep kept kept think thought thought know knew known throw threw thrown lay laid laid understand understood understood lead led led wake woke woken leave left left wear wore worn lend lent lent win won won let let let write wrote written vk.com/bastau Answer Key (M) = Model/suggested answers Exercise 3 TASKS 1 From: ipcs3@cc.uat.es B E (1 ) Sent: Mon 28 November 15:40 Subject: Short Bros E x ercis e 1 Dear Frances, Present negative Prese n t q I am sorry I was not at the meeting yesterday. I have not been in the 1 3 5 7 8 6 13 2 4- 9 12 office this week. Tom and I have been in London. We were at a Sales Conference. I have been very busy recently. 10 11 U Were Short Brothers happy with the contract? Have they been in contact today? E x e rc is e 2 Please contact me by email tomorrow. 2. My nam es Pierre Lapin. Im a Sales Manager. Thanks 3. M ary and Hans are from my d e p artm en t. Juanito They're co m p ute r pro gram m ers. ..:...... a U. This is Naom i Cox. She's a research scien tist. 5. Hello. My nam e's Franz Johann and th is is Tomas D oll. W e're from Salzburg. TASKS 3 6. Ah, Franz and Tomas! You're very w elcom e! 7. This is o u r office. It isnt very big. The Present Continuous Positive E x ercis e 3 E x ercis e 1 Axdal Electronics is a w orld leader in control systems. We are suppliers to the car industry. Car m anufacturers Date: 12 march 20.. are not o ur only customers. We are also suppliers to To: all staff TASKS 2 Room 40. Janet is planning a leaving party fo r John. At present, John is recovering in hospital after an accident. He is hoping to return to w ork next m onth, b u t only un til th e summer. E x e rc is e 1 E x ercis e 2 Last week Tom and Paula were here for a meeting. It w as very 1. Total sales are going up. useful. They were here for two days. We have been to Oslo in 2. Sales fo r P roduct A are increasing. the last few days. We were there for a meeting with our 3. Sales fo r P roduct B are fa llin g . Norwegian colleagues. Arne Sillessen w as very interested in U. The com pany is stopping production of P roduct B. our ideas. Until now, I have not been happy with the project. Now I am very optimistic. See you next week. Best wishes Sand3 f t t l Sandy Peel P re -Inte rm e d ia te Business G ra m m a r vk.com/bastau TASKS 4 TASKS 6 The Present Continuous Negative The Present Simple Positive E x ercis e 1 E x ercis e 1 We are not increasing our prices this year. The You work for a multinational company. market is not strong enough. We are launching He/She studies foreign languages. new products for the domestic market. Most of our We/You/They travel a lot for work. products are selling well at home. At present, we are The company makes better products. not planning any new products for export. Sales are Our Research Department develops new solutions. not increasing in our export markets. The company is not expecting improved sales this year. E x ercis e 2 1. d 2. e 3. c U. a 5. b E x ercis e 2 vk.com/bastau 177 Yes. TASKS 8 But not Brasilia? No, we don't operate in Brazil yet. The Present Simple Question Is Pablo Hernandez coming here this week? Yes, he likes these meetings. E x e rc is e 1 TASKS 11 E x e rc is e 2 The Past Simple Positive M: We deal mainly with Germany, France and Sweden. C: And are you negotiating with Japanese E x ercis e 1 customers at the moment? increased gave helped ran supplied received M: No, not at the moment. delivered met ordered lost broke climbed C: Are you planning to enter any new markets? came read wrote spoke M: Yes, Italy. We are launching a range of products there later this year. E x ercis e 2 C: And Sweden? Do you sell much there? M: Yes, we often get big orders from Swedish manufacturers. On 25 April this year we stop (stopped/ production ofArpol, a treatment for migraine. Arpol production E x e rc is e 3 begin /began/ in 2004 and early sales was (were/ very impressive. However, Belpharm Ltd did launch A: What's happening? /launched/ the Calpem range three years ago. This B: Were opening ten new branches in Argentina product was taking /took / a 30% market share in and Chile. the first two years. At first we agree /agreed/ to A: Does the bank currently have branches only in continue with Arpol. Now the situation is different. Buenos Aires and Santiago? vk.com/bastau 178 I P re -Inte rm e d ia te Business G ra m m a r Joelle: Dont you like w ork? Bill: Of course I do. I love w ork! Two years la te r Metfan launched the Stella range. Seven years ago Stella reached a 15% m a rke t share. E x ercis e 3 In 20.. M etfan tu rn o ve r rose 20% and two years la te r Metfan bought Lanco S.A. Last year M etfan had a 1. Did the m aintenance engineer rep air the copier? 23% m a rke t share. 2. Did John read th e Caracas report? 3. Did you w rite to the Kongo Club? U. Did M r Fish phone? TASKS 12 5. Did you send the VISA application? 6. Did Larish Ltd co lle ct th e ir order? The Past Simple Negative Did they pay? E x ercis e 1 TASKS U I joined th is com pany five years ago. It was a d ifficu lt tim e. The com pany was not in a very good state. The Past Continuous We d id n 't have a cle a r m anagem ent stru ctu re . Our local m arkets were not very good. O ur m arketin g E xercise 1 d id n t include A m erica o r the Pacific regions. We d id n 't have any cle a r m arketin g strategy. W hat was happening (Q) a few years ago? Well, Now, th ing s are very different. the com pany w a s n 't doing (N) very w ell. D uring the 1990s we w ere com peting (P) w ith m any suppliers. We had (P) a s m a ll turnover. Then everyone was E x ercis e 2 th in kin g about (P) m erge rs and takeovers. In the New products were not cheap to develop. We didnt early 2000s we w ere operating IP) in a very different spend a lot of m oney on research. O ur m arket share m arket. There w ere only fo u r large com panies. A ll didnt increase in the early 2000s. The com pany fo u r w ere m aking (P) big profits. We were a ll doing didn't make m any good products. w e ll (P) . . . Chemco bought the company. There was a big change in the organisation. The new m anagem ent E x ercis e 2 wanted to change everything. Most of the old m anagem ent left. T hings improved. Now, we are T: From 8 oclock u n til 9 o'clock I was checking very optim istic. the production system . From 9 oclock u n til 10 oclock I was repairing a com puter. Then w hen the fire started I wasnt working. I E x ercis e 3 was having coffee. 2. On the next day they didn't send the goods to S.F: Were your colleagues drinking coffee too? Rotterdam by train . T: No, they w ere installing a new printer. 3. On January 17 they didn't load the goods onto a S.F: Was the factory working normally? ship in Bilbao. T: Yes, everything was running perfectly. U. On the next day the goods didnt arrive in Bilbao. S.F: Okay. T hanks fo r your help. 5. C arretera T rasportes didn't take the goods to Vitoria. E x ercis e 3 6. So Espofrigo didnt confirm the arrival. 2. At 11.00 Sally w as in the duty free shop. She was buying clothes. 3. At 11.30 Sally w as at the Gate. She w as w aiting to TASKS 13 get on the plane. 4. At 12.00 she w as on the plane. She was reading. The Past Simple Question 5. At 2.00 she was (still) on the plane. She was having lunch. E x ercis e 1 6. At 5.00 she was at a m eeting. She w as giving a 1. c 2. d 3. e U. b 5. a presentation. E x ercis e 2 TASKS 15 Joelle: Did you have an interesting visit? Bill: Yes, I made som e u sefu l contacts. The Present Perfect Simple Joelle: Did you see M r Keitel? Bill: No, he w as in New York. E x ercis e 1 (M) Joelle: And did you visit o u r colleagues in Sabah? I have been to B elgium . Bill: No, I telephoned, but I didnt have tim e to visit. Joelle: Did you have tim e fo r any to u rism ? You havent visited Saudi Arabia. Bill: T ourism ! No ... only w o rk and m ore w ork! H e's/Shes studied econom ics. vk.com/bastau Shes/H e s produced a report. O ur d ep a rtm e n t has made a profit. TASKS 17 The com pany has developed new products. The governm ent has increased taxes. The Present Perfect with For, Since, Ever and Never E x ercis e 2 E x ercis e 1 Product B has been profitable since 2008. P roduct C has done w e ll since 2006. 1. c 2. d 3. b 4. a Product D has made a p ro fit since 2007. E x ercis e 2 E x ercis e 3 (M) MC Have you ever had a big fa ll in sales before? 2. Ive known h im /h e r since I was 16. Since I was 16. PM No, sales have never fallen so suddenly. 3. No, it hasn t made any links. No, it h asnt. MC How long have you been m arketing this product? 4. Yes, it has owned a p rintin g business since 1965. PM Since the beginning of last year. Yes, it has. MC So, it s been on th e m arket for less than 5. Ive lived in my present house fo r five years. two years? For five years. PM: Yes, it has. 6. No, I havent w orked fo r an A m erican company. MC: Have you com pared Shine Plus w ith No, I havent. c o m p e tito rs sales results? 7. Yes, I have (Ive) studied fo r an MBA. Yes, I have. PM: Yes, o u r drop in sales has happened since January. The m a rk e t has improved. The graph shows how o u r th re e m ain co m p etito rs have TASKS 16 a ll benefited: th e yve a ll been se llin g better. E x ercis e 2 TASKS 18 Since 2006 w e ve been using autom ated production. Since 2008 w e ve been running tra in in g courses. The Past Simple Since January w e ve been processing o rd ers w ith vs. The Present Perfect Simple ele ctron ic system s. We've been building a new w arehouse since E x ercis e 1 February. 1. The com pany has sold its London offices. E x e rc is e 3 2. The M anaging D ire c to r resigned three years ago. 3. I^have not read the new spaper to day. EuroTV, 170-174 Rue des Capucins, 2270 Lesigny, FRANCE 4. A rival m an ufa ctu re r^has bought the company. 5. The to p -s e llin g pro duct made over 3m last year. Dear Hisashi, 6. Many sh a re h o ld e r^ have sold th e ir shares. Thank you for your letter. EuroTV has been developing links with companies in other countries. In particular we have been discussing programme 7. M arket analysts^have estim ated|com pany tu rn ove r making with networks in Belgium and Germany. We have been talking to a to v e r 4 0 m . small, private companies. So fa r we have not tried to set up links with 8. Axam Ltd did not im prove its sales. companies outside Europe. Many American TV stations have been examining ways to work in Europe. E x ercis e 2 I look forward to meeting you in Paris. We can discuss these developments. This shows the tu rn o ve r fo r Lander. It declined between 2004 and 2006 but it has risen since 2006. Yours sincerely, The com pany has spent m ore on R&D. Tor* K tftch. Tom Kitsch E x ercis e 3 E x ercis e 2 Tom: What happened? g. So, now Ill explain the programme for the day. Fred: Before the machine broke down, I had made c. After this introduction, w e'll have a short tour of 100 copies. the plant. Tom: Then what? e. Then before coffee w e'll show you a film about our Fred: When I had done 100, the paper jammed. distribution system. vk.com/bastau f. WeLl have coffee at 11 then well have a meeting with Ken Levins, our Product Manager. TASKS 23 a. We'll have lunch in a local restaurant at about 1 o'clock. The Future with W ill vs. Going h. After lunch we'll discuss future plans. To vs. Present Continuous b. We'll finish at about 4- oclock, E x ercis e 1 d. So, shall we begin the tour? A: What are we going to do (1) about the E x e rc is e 3 promotional material for the exhibition? 2. John: Ill be in my office tomorrow. B: Im taking (2) it to the printers this afternoon. M arie: Ill call you. They told me itll be done (3) by Monday. 3. Jacob: I need to see the report. A: Okay. Tell them Ill pick it up (4) at 10 oclock. Hisashi: Ill get it. B: Its not necessary. Theyre coming (5) here about A. P ierre: Wholl tell us the answer? something else. Imogen: Erik won't A: Okay. Im going to find out (6) who can do some 5. Juan: What about lunch? translations for us ... Amy: Shall we go to Gigi's Restaurant? Fixed plans/ Intentions/ 3 Facts/specific present continuous going to j tim e s /w iU TASKS 22 2, 5 1,6 3,4 PhoneCo: And are you going to need anything else From: j jeanclaude.isias@papin.com C aller: No, w e re not planning anything Dear Ricardo, complicated. R epresentatives o f Harkes Ltd are coming next w eek.They are disaster. Present 3 ,8 ,9 12 1 3. If sales collapsed, people w ould lose th e ir jobs. Past 5 7 4, 6 U. If the plane crashed, we w ould m iss the m eeting. Future 2, 10 13 11 5. M ary w ould be happy if Fred resigned. 6. If we increased the R&D budget to $500m we w ould be the m a rke t leader. E x ercis e 2 (M) E x ercis e 3 The two com panies had been com petitors. 2. If we spent less on hotels the com pany w ould In 1965 Ardanza Pascual had 45 shops in Spain. pay m ore tax. Between 1965 and 1980 the com pany was growing 3. Travelling w ould be h arde r w o rk if we didn't by 5% every year. go first class. Since 1980 the com pany has been exporting all U. I would like travelling if I d id n t have to w ait fo r over Europe. hours in airpo rts. Now the com pany is planning 20 new products. 5. If I d id n 't like the tra ve llin g I would get a The com pany is going to buy into the US m arket. different job. In 2020 it is opening a new factory in Poland. 6. My company w ouldnt use this hotel unless it was really good. vk.com/bastau E x ercis e 3 TASKS 28 Ben: Claude, listen. Before taking a decision on Infinitive + To the Combo advertising, I would appreciate knowing your views on the agency we are E x ercis e 1 working with, Kinetics. I was pleased to talk to you on the telephone last Claude: Well, avoid signing the contract this week. night. We w ill be glad to see you in Washington Tell them were interested in learning next month, but I am sorry to hear that Sam is more about their plans. not coming. Tell him, of course, wed like to meet Ben: Good. Thanks. ILl tell them were looking him another tim e ... forward to meeting them again soon to discuss things in more detail. Claude: Yes. And ask them to stop talking about E x ercis e 2 television advertising. We said it was too 1. I was sorry to hear that John was not well. expensive. 2. It w ill be good to see you again. 3. We plan to spend more on advertising next year. TASKS 30 U. We always want to give a good service. 5. We expect to do well next year. Infinitive + To or Verb . . . ing E x e rc is e 3 E x ercis e 1 "Friends, I am pleased to have the opportunity to speak again at our Annual General Meeting. I am 1. We continue to promote the use of recycled glad to see so many old friends. It is difficult to know materials in our factory. what to say after 20 years as Chairman of the Group. 2. Would you like to see our latest products? I w ill be sad to leave the company after so long. 3. I tried to phone/phoning you yesterday. The good news is that I plan to play more golf next 4. Our Overseas Director intends to visit/visiting all year! But also, I hope to come to the AGM next year. I our subsidiaries this year. expect it w ill be difficult not to follow the news about 5. I remember meeting you in Madrid last year. the company. Now, of course, I would like to thank E x ercis e 2 the many people who have helped me in 20 years ... 1. I like drinking coffee TASKS 29 b. Coffee is what I like to drink. 2. I forgot to telephone Mr James, Verb ...ing b. I did not call him. 3. Try calling him in the evening. E x ercis e 1 a. If you call in the evening, it is possible that you w ill reach him. Dear George We are planning a meeting next week. We are interested E xercise 3 in hearing colleagues' views on the sales campaign for the Shello range. Before attending the meeting, please Im on a tour of our European suppliers as Im read the interim report, Shello Advertising SA/JD responsible for checking quality control. I had 3421JD. I suggest inviting the marketing group to intended to see/seeing all our suppliers but its attend the meeting, but we should avoid having long impossible to do that in only one week. I'm in Rome discussions about individual markets. at the moment. I remember arriving in Rome last year. I had forgotten to bring the address of our Regards supplier. I found the number in the telephone book. Sophie Allen I love coming here. I enjoy hearing the language. Tomorrow Im in Spain. I like going there too. We E x e rc is e 2 have an excellent supplier in Tarragona. vk.com/bastau Exercise 2 Exercise 2 1. We have got to pay more tax this year. Jim : Should we discuss the problem with the 2. We must not spend too much on special bank? (S) promotions. Alice: I dont know. You ought to talk to Jeremy 3. Last year we had to advertise a lot on television. first. (A) 4. Our competitors are in trouble. They have got to Jim: Well, the bank charges ought to come down reduce their prices. next year. (P) 5. We must to plan our marketing carefully. Alice: Maybe we should close the account. (S) Jim : First, I think I ought to write to the bank. (S) E x ercis e 3 E x ercis e 3 1. 'We must buy some more trucks. 2. Ive no money. Ill have to borrow some from 1. You ought to/should see a doctor. the bank. 2. The truck ought to/should arrive tomorrow. 3. You have to present a business plan. 3. We ought to/should cut our prices. 4. Theres only one problem. Weve got to /w ill have U. Inflation ought to/should fall soon. t o /11 have to pay the money back. TASKS 38 TASKS 36 Question Tags Mustn't, Neednt, Dont Have To E x ercis e 1 and Havent Got To 1. Business is important, isn't it? E x ercis e 1 2. Businesses have to make a profit, don't they? 2. Companies do not have to pay a minimum wage. 3. Profit creates jobs, doesn't it? 3. We do not need to meet health and safety U. People w ill always have new ideas, wont they? regulations. 5. Most companies have improved working 4. Our competitors did not have to reduce their prices. conditions, havent they? 5. We havent got to advertise in national newspapers 6. Companies havent always spent much on training, have they? E x ercis e 2 7. Businesses cannot forget their customers, can they? 2. You do not need a visa to go to Poland from 8. Government must help businesses, mustnt it? Germany. E x ercis e 2 3. You haven't got to pay by cash. 4. We didnt need to increase production. 2. You cant tell us the price of BKD, can you? 5. He doesn't have to learn a new software program. No, I cant. 3. Youre going to London now, aren t you? Yes, I am. 4. There w ill be another meeting in the morning, Dear Sir, wont there? Yes, there w ill. 5. So discussions are still continuing, aren t they? You reported last week that Larssen S.A. had a strong market position. Then you said that the Yes, they are. company does not have to think about its 6. But you havent agreed a price, have you? competitors. This is not true. We must not believe Not yet. Goodbye. that our market share is permanent. We do not need to worry about our jobs today, but we E x ercis e 3 certainly cannot forget about our competitors. A year is a short time in business. A: This is a good hotel, isnt it? B: Yes, its fine. You havent stayed here before, Yours faithfully, have you? A: No, this is my first time. Bo Johannessen B: Its 8 oclock. We should have dinner, shouldn't we? Chairman Larssen S.A. A: Yes, Im hungry. Oh dear! I didnt book a table. B: We don't need to, do we? A: I dont know. Well find out, wont we? TASKS 37 TASKS 39 Should and Ought To Active E x e rc is e 1 E x ercis e 1 A: Ought we to have a meeting? 2. He flew to Miami last night. B: We shouldnt have one today. 3. He took his laptop with him. We ought to wait a few days. U. He wanted to finish writing the report on the plane. A: Should we? 5. He w ill give it to Head Office in Miami. vk.com/bastau 186 I P re -Inte rm e d ia te Business G ra m m a r Exercise 2 Exercise 2 rent a car 1. Paper should be recycled. accept an offer 2. Please switch off the lights. appoint a secretary 3. Visitors should leave coats and bags, etc. here. design a new product 4. Eye protection must be worn. investigate a problem write a letter E x ercis e 3 borrow money pay an invoice First, well see a film about Eastern Water. Then quote a price the Managing Director w ill give a talk on the history and future for EW. Then w e'll go on a tour E x ercis e 3 of the factory. Well see demonstrations of how 1. Our prices have risen this year. water is distributed and how water is treated, 2. Last year our sales fell. Finally, well have dinner. 3. We reduced our prices. 4. We have also improved our products. 5. Our sales have recovered. TASKS 42 TASKS 40 It Is/They Are vs. There Is/ There Are Passive E x ercis e 1 (M) E xercise 1 Are they French? New products (are/were/will be) tested in our There are many tourists here. laboratories. They arent French. Customers (are/were/will be) sent a company Are there a lot of museums? newsletter. Are they expensive? Company policy (is/was/will be) based on quality. There is a good restaurant here. Profits (are/were/will be) invested in new projects. Is it French? E x ercis e 2 It is expensive. 1. Orders are taken by telephone. E x ercis e 2 2. The information is sent to the warehouse. 3. The goods are loaded into vans. A: There are many good hotels in Tokyo. I like the 4. They are delivered to the shops. Tokyo Hilton. It is in the centre of the city. B: Are there many small family hotels? A: No, there aren t. B: I imagine they are very expensive. There are many important activities before A: In Tokyo? Yes, it is an expensive city. take off. The fuel tanks are filled and the aircraft systems are checked. Food is brought E x ercis e 3 on board. All the baggage is loaded in the hold. The captain and the co-pilot are informed of Clerk: Yes, there are many trains. Now it's 11.25. runway conditions and other details about There was a train at 11.21. The next one is take off. When everything is almost ready, at 11.41. passengers are invited to board the plane. M aria: Is it direct? Clerk: No, it isn't. It goes via Essen. There is a train to Munster via Essen every 20 minutes. M aria: Are there direct trains to Munster? TASKS 41 Clerk: Yes, there is a direct train at 11.50. Its direct to Munster. Active vs. Passive E x ercis e 1 TASKS 43 Users should change [A] their password every Have and Have Got week. All confidential information should be stored (P) on computer hard disk. Users should copy (A) E x ercis e 1 confidential information on to floppy disks. Disks I didnt have (V) a very good job last year. Now Ive should be placed (P) in the safe in the Finance got (HG) a new position in the company. Ive (AUX) Office. Confidential information should not be taken control of export sales. Weve (V) many new removed (pi from Chemco PLC without the clients in America and Asia. Have (AUX) you seen permission of a Department Manager. Report (A) all our product brochure? Weve (AUX) had a new one security incidents to an appropriate manager. printed this week. Mary, have you got (HG) a copy? vk.com/bastau 187 Exercise 2 Exercise 2 1. d 4. c Delta: Tell te me again, how much do you want? 2. e 5. f Langer: I said $20,000. 3. a 6. b Delta: But tell me a lower price. Langer: I am telling you our lowest price. E x e rc is e 3 Delta: What did you say roe last week about Fumi: How many employees do you have?/have terms of payment? you got? Langer: I told you 60 days payment. Mike: W eve/w eve got about 2,000. Fumi: Do you have/have you got/have you many E x ercis e 3 sales reps? Mike: About 300. WeveAA/eve got 30 in the Far East. To: | k.brand@abcsolutions.com Fumi: Have you worked in Malaysia? From: I r.patel@abcsolutions.com Mike: Yes, I have. And w eve got/we have three big Subject: | Your meeting w ith Dennie Flowers (Axis Ltd) Tuesday 20 March customers there. Dear Karen, Fumi: What about Indonesia? Mike: No, we haven't/haven't got any customers What did Ms Flowers say about the delivery last week? there. I saw her on Monday. She didn 't say anything about it. Did she tell you anything about the invoice? On the telephone I told her we would give a 10% TASKS U discount. In fact I forgot. Please phone her.Tell h e r! made a mistake. Say we can send a new invoice. Get and Have Got Note: I have told all our sales reps to offer a 10% discount. E x ercis e 1 Best Regards A: Did you get (G) my letter yesterday? Rajiv B: I didn't get (G) it yesterday. It came today. Ive got (HG) it here on my desk. The problem is getting (G) serious, but I haven't got (HG) time to discuss it now. Ill call later. TASKS 46 B: Well, Ive got (HG) a meeting this afternoon. A: Okay. Ill call you before lunch. Make vs Do E x e rc is e 2 E x ercis e 1 1. f 4. b 1. made 5. did 2. d 5. c 2. do 6. making 3. a 6. e 3. making 7. make 4. made 8. Do E x ercis e 3 1. Beth: Getting better. E x ercis e 2 2. M ike: What have you got? Amy: Was it a good meeting? 3. Peter: We didnt get the contract. Leo: Yes, we made a decision. We are going to 4. Amy: Did you get the money? increase production of BIGG0. 5. Syd: Yes. I got it yesterday. Thank you very much. Amy: What about the costs? 6. Alice: Ive got a new job and its really difficult. Leo: We made a new budget. We think we w ill do 7. Billy: Itll get easier, Im sure. more business next year. Well make a profit of 200,000. TASKS 45 Amy: Good. Do you know that Rospa Ltd. have made a complaint about our BIGG0 promotion? Say vs Tell Leo: Yes, they are making a big mistake. We have done nothing wrong. We have done our E x ercis e 1 research. Rospa know that BIGGO is going 1. What did you say? to make money. With good marketing we e. I said I would like fish. will make sure that we do better than Rospa 2. Tell me which you prefer. next year. f.I prefer white wine with fish. 3. Tell me about the work in India, E x ercis e 3 d. Have I told you about Mr Singh? 1. We do business in France. 4. Say anything you like, 2. You are making a mistake. c. What sh a lll say? 3. They did a good job. 5. Tell the waiter you want another knife. 4. We have made progress. a. Ive told him already. 5. They made an offer, but it was too low. 6. Let me pay. 6. We had to make a choice. b. No, I said I would this time. 7. They have done the research. E x ercis e 2 D ear Jam es, 1. He has lived abroad. He used to live in Italy. 2. He is used to making presentations. T h a n k y o u fo r ag reeing to a tte n d o u r m e e tin g o n 28 O c to b e r .W e w ill talk ab o u t o u r m a r k e tin g s tr a te g y f o r next a g e n d a w ill co n sist of ju s t th r e e p o in ts : 3. He likes going for walks. When he was young he y e a r. T h e used to go for walks with his father. re c r u itm e n t, t r a in in g , a d v e r tis in g a n d p r o m o tio n . I th in k w e motorbike. Y o u rs s in c e r e ly E x ercis e 3 Ann: I dont mind. I'm used to it. Peter: Have you always driven to work? E x ercis e 3 Ann: No, I used to go by train. Peter: Is this your first job? Sam: The meeting was really good. We got almost Ann: No, I used to work for RYG. You ask so many all we were asking for. questions! Paula: Yes, in fact, I was surprised we managed to Peter: I'm used to it. Im a journalist! obtain a very low price. Sam: Also, we got good terms. We dont have to pay for the goods until January. TASKS 48 Paula: Thats true. I think they have lost some business recently. They were relying on Rise vs. Raise getting the contract from us. We got a good E x ercis e 1 deal because they knew we have other suppliers. We were not depending on them. In the first half of the year prices rose (I) by 10%. Also, we werent in a hurry. We can wait for Wages rose (I) at the same time. The government smaller companies to supply us. raised (T) taxes and the banks raised (T) interest Sam: But obviously, we were hoping for a quick deal. rates. Inflation continued to rise (I). E x ercis e 2 1. c. Sales rose by 10%. TASKS 50 2. b. The advertising budget has risen. Verb + Adverb (Phrasal Verb) 3. c. Costs w ill probably rise. U. a. The number of unemployed workers rose E x e rc is e 1 this year. 5. b. Electricity companies have raised their charges. return (goods) = send back 6. c. Bank charges w ill rise next year. reduce (production) = cut back abandon (plans) = call off E x ercis e 3 buy (a company) = take over 1. The National Telephone Company has raised the go out of business = close down price of making a call. start (a machine) = switch on vk.com/bastau E xercise 2 TASKS 52 1. The meeting has been put back two months, d 2. AD Industries closed the plant down ten years Negative Statements ago. a 3. Weve called in the suppliers to fix the machine, c 4. AGCO has turned down an offer of $800,000 for To: | nickl_fox@jdloughman.com .. . I j the company, b From: | m aria_aubert@ jdloughman.com Subject: | Ibros S.A. negotiation I E x e rc is e 3 Dear Nick, Boris: If we cannot sell all the goods we have, we We (S) did n o t have (NV) a m eeting w ith Ibros S.A. because we rejected must cut back production. th e ir offer.The offer (S) did n o t com e (NV) by email. We received a fax on Thursday. We understand th a t th e Managing D irector o f Ibros. Mr Susan: Yes. Our agents want to send back goods Kalkos. (S) w ill n o t sign (NV) th e contract. We (S) have n o t accepted they cannot sell. But I also think we should (NV) th e present proposals. A t th e m om ent we (S) are n o t planning to continue (NV) production o f th e Alisia range. Last year w e (S) d id n 't set up an agency network in Asia. reach (NV) agreem ent im m ediately. Now, I th in k it (S) w ill n o t be easy Boris: But we turned down that idea last year. (NV) to fin d a solution. Susan: I think the Board should find ways to build up our reputation for quality service. E x ercis e 2 Boris: Certainly. That would be better than putting up prices again. 1. We wont finish our business tomorrow afternoon. 2. The meeting w asnt planned to last three days. 3. We cant go home tomorrow. TASKS 51 U. We shouldnt go to the Castle restaurant tonight. 5. It doesn't open every night. Positive Statements 6. Friday isn't a good night to go. 7. They dont cook fish on Fridays. E x ercis e 1 8. I haven't eaten a lot of fish recently. 9. The Castle restaurant hasn't been Sales (S) have been ven/ disappointing (VP) this year. recommended to us. Our costs (S) are rising (VP) every day. Clearly, our 10. We didn't go there last time. marketing team (S) need to market (VP) our products better. But our R & D Department (S) are confident E x ercis e 3 (VP). They (S) are developing (VP) a brilliant new 2. Inflation wont rise in the near future. product. ]t (S) will need (VP) support from the bank. 3. Sols market share has not increased in ten years. A new business plan (S) is being prepared (VP) at the 4. The sales volume did not improve between 2004 moment. and 2006. 5. Actual sales did not reach forecast sales in 2009. E x ercis e 2 6. Hammond Ltd w ill not be taken over next year. a. Now United Electric exports all over the world. 7 b. In 2000 Keele Brothers was taken over by United TASKS 53 Electric Inc. U c. In those days Keele Brothers made bicycles. 2 Questions: Yes/No d. Between 1980 and 2000 the main products were E x ercis e 1 pumps and small engines. 3 e. The name of the company was changed to United A: Do you live near your company? Electric (UK) Ltd. 5 B: No, its about 25 km to the office. f. Keele Brothers Ltd was started in 1970. 1 A: So how do you travel to work? g. Since then the company has developed an B: I go by train or sometimes by car. international market. 6 A: Is it quicker by train? B: Yes - and I can work on the train. E x ercis e 3 A: Isnt it crowded? B: No, not usually. Its okay. 1. In 2009 Hebden joined an international consortium to develop a new aircraft. E x ercis e 2 2. Since 2004 the company has realised continual 1. e 3. d 5. a growth. 2. f U. c 6. b 3. Our products have been exported all over the world for many years. E x ercis e 3 U. Our production uses highly automated systems. 2. Will Mandy meet/ls Mandy going to meet Joanne 5. Our market share in our home market is now next weekend? 12%. 3. Will Alex be back from Nairobi tomorrow? 6. 7,000 people are employed by the Hebden group. U. Does Tom usually rent a car for trips abroad? 7. The annual report contains details for our 21 5. Are you prepared for your presentation next week? different product areas. 6. Did Rolf go to New York in June last year? vk.com/bastau Pre -Inte rm e d ia te Business G ra m m a r E x ercis e 2 TASKS 54 Questions: Wh- Date: i 18/10/2010 ......... I To: | k.r.nijran@amtel.com E x ercis e 3 vk.com/bastau E x ercis e 2 TASKS 57 We w ill know if there are any problems after the first Sentence Types: Simple vs. six months' sales. Complex The product w ill be launched next week though at first only in the home market. E x ercis e 1 Its a new concept so it w ill need a lot of promotion. We are going to promote it heavily because we need The Amco 75 went into production in the Spring. a major new success. Sales were very good (MC) and we quickly We w ill target young people who have always been established a significant market share (MC). We our key market. have begun exporting the Amco 75 (MC),[thought early sales are weak (SC). We w ill have a satisfactory E x ercis e 3 year (MC)(lf]our exports improve (SC). Profit has gone up this year (MC)jbecause our domestic sales We need to increase our prices because our costs have increased (SC). Our research has been very are rising. Many companies are in a similar position, productive (MC) but costs have risen (MC). Now though our costs are especially high. We have a we have many competitors (MC)[whojare seen as strong export market where our sales are still good. important dangers in some key markets (SC). We have identified some key problems which make the home market very difficult at present. We will E x ercis e 2 have continued problems if we do not take some difficult decisions. There is no time to lose, so we B: Yes, we have agreed to recruit another secretary, have to do something quickly. though we have not decided when. A: But we need one now. There w ill be problems if we dont get one soon. TASKS 59 B: I think there w ill be resignations because everyone is working too hard. Relative Clauses A: I agree. People w ill resign or they w ill simply be less effective at work. with Who and Which B: Im going to speak to Patrick, who w ill accept E x ercis e 1 that the situation is critical. 9 sentences, all S (simple) The conference, which w ill discuss the action of antibiotics I work for Arkop GmbH which makes car on diseases IND). w ill be held at University College, which is one of the oldest colleges in the city (ND). People who wish components. The company is based in Kirchheim, to attend (D) should send an application form to the which is in Southern Germany. This is a good location President of the Society, who is in charge of bookings (ND). because many of our customers are very close. We Anyone who is presenting a paper at the conference (D) w ill automatically receive fu ll details. sell our products all over Germany and/though/but we also export a lot, but/though our domestic market is the most important part of our business. E x ercis e 2 w (s loj 0 X L (nJ 6. The floors which we sent to Finland last year are specially for outdoor use. E x ercis e 3 research X record records 1. We dont have enough information. Ring them and ask for more details. accountant accountants capital X 2. John works for a company that makes figure figures sale sales agricultural machinery. 3. We are a financial services company. We give advice on insurance, pensions and other aspects E x ercis e 2 of money management. Every year the company publishes its annual U. I asked him for advice. He made two suggestions. accounts in a report for the shareholders. The First, do more advertising and secondly, find a main details concern the financial report. This new Sales Assistant. contains information about sales, turnover, costs 5. Please can you help me with these cases? They and profit. It also reports the assets that are held are very heavy. by the company, and the liabilities. These are any 6. John has changed his job. He now works for debts or cash that the company owes. All this data a bank. is presented in the profit and loss account and the 7. Many people work in insurance or banking, but balance sheet. most work in commerce. vk.com/bastau Exercise 2 TASKS 63 1. b. Freds car Noun Compounds 2. b. the Chief Executives car 3. b. KLPs market share is 12% E x ercis e 1 4. b. yesterdays paper weather forecast market forces 5. a. the workers canteen credit card satellite dish 6. a. the design of the computer hotel room container ship alarm clock E x ercis e 3 identity card The Research Director's report was very positive. E x ercis e 2 We hope that all Frodo's customers w ill like the new product. We think it w ill meet our customers' needs. I agree with John Tudors opinion. He thinks Please send ^product information Frodo's m arket share w ill increase. With this new *price list product, next year's perform ance will be very good. and details of *customer services As always, we must focus on the quality of our and ^payment terms products and services. The Chairman's speech at I would like a product demonstration and I want to the AGM w ill say that quality and new products are arrange a meeting with a sales representative. Also, most important. do you have any special sales promotions at present? Please send a fa x message to the above number ASAP TASKS 65 Adjectives vs. Adverbs E x ercis e 3 E x ercis e 1 2. If you apply for a job, you complete and send a job application. Excellent (adj) results have helped MODO. In an 3. The result of the test is a test result. unusually (adv) wet (adj) summer, the company did 4. When you need to change money to another really (adv) well. The fashionable (adj) clothes were currency, you ask for the exchange rate. popular (adj) with young (adj) consumers. Now the 5. If a company wants to spend money on company w ill definitely (adv) increase its production, advertising, it prepares an advertising budget. Staff are busily (adv) planning an equally (adv) 6. Before getting on a plane, you have to wait in the successful (adj) range for next (adj) year, but the departure lounge. market w ill be very (adv) competitive (adj). 7. People who travel a lot on business make many business trips. E x ercis e 2 8. We use a lot of computers. We live in an age of information technology. TASKS 64 Genitive Forms E x ercis e 1 Alan: The changes in the market are going to 1. Yesterday Mr Roach got up early. affect the company quite seriously. 2. He had a coffee, then calmly began to read the paper. Helga: We need to make some quick decisions. 3. Suddenly he noticed the time. Alan: We urgently need a new marketing strategy. U. Im m ediately he ran out of the house. Helga: Fortunately, the products are excellent. 5. He looked urgently for a taxi. Alan: I agree absolutely, but we have to get 6. The taxi went very fast to the airport. people interested. 7. He was just in tim e for the plane. Helga: Im confident that we w ill do that. 8. Fortunately, he was not too late for the meeting. Alan: Good, because our sales have fallen dramatically. E x ercis e 3 E x ercis e 2 E x ercis e 2 vk.com/bastau 195 Lee: I thought you planned to stop making it. TASKS 69 Klaus: Last year we planned to stop, but we changed our mind. This year we also Degree with Very, Too and Enough planned to stop, but again we have continued. The 26 is still very popular. E x ercis e 1 Lee: Are you still selling the Arco 26? OFFICE COMFORT'- Klaus: Yes, it is still doing well. For rapid service telephone FREEPHONE OFFICE S T ftfl 800800 now!! Lee: Have you made a replacement yet? Klaus: Yes, the Arco 28 is already available. Lee: Are you going to stop making the 26? Klaus: Yes, but not yet. vk.com/bastau Ben: I hope so. Weve had some good news this Exercise 3 week. (PS) Pat: I hear you lost something yesterday. Steve: What was that? Ella: Yes, my mobile phone. I wanted to phone Ben: Our American agent wants some more someone but I couldnt find the phone PXIOOs. (PS) anywhere. Steve: Good. Have they sold any more PX50s? (Q) Pat: You must have put it down somewhere. Ben: Some, but not many. (PS) Ella: Yes, I asked at reception. They knew nothing E x ercis e 2 about it. Pat: So no-one found it? Paula: We havent launched any new products Ella: No. I asked reception to call me if anyone this year. Last year we had some. Four, found anything. in fact. We need some for next year. Mohammad: I would like to show you some designs. TASKS 77 Paula: Have you any pictures of the new designs? Quantifiers (1) Mohammad: No, we haven't any yet, but some w ill be ready next week. E x ercis e 1 TASKS 76 E x ercis e 3 1. A little training helps all managers. Some, Any and Related Words 2. No customers w ere unhappy. 3. A ll of our products are guaranteed. E x ercis e 1 U. Many people came to the exhibition. A: Is anything wrong? [Q] 5. Few exhibitors liked the exhibition space. B: Yes, theres something wrong with one of our 6. The organisers offered little help. production machines. (PS) No-one knows what the problem is. (NS) Weve looked in the Users Manual but we cant find the solution anywhere. (NS) TASKS 78 A: Have you contacted the manufacturers? Quantifiers (2) B: Yes, they think its nothing very complicated. (NS) Theyre sending someone to visit us. (PS) Hell E x ercis e 1 be here soon. He was already somewhere near A: Hello. Id like some (U) help please. here. (PS) B: Certainly. A: How much (U) does this car cost to hire? E x ercis e 2 B: That one is 120 a day. 1. Some people prefer small hotels. A: Thats quite a lot of (U) money. c. A number of people prefer small hotels. B: Well, we have a lot of (C) other cars that cost a little 2. I knew no-one at the meeting. (U) less. How many (C) days do you need a car? b. There was not one person I knew at the meeting. A: Only a few (Cl. Three or four. 3. We sell anything you want. a. We have everything you want. E x ercis e 2 4. We can send orders anywhere. 'We hire mobile phones. We have a ll types of phones. c. We can deliver to any place you choose. We keep a lot of phones in stock. Most are hired for 5. Theres something wrong with the figures. just one day. A few of our customers keep them for b. The figures are partly wrong. a month or two. Not many people hire phones for longer than a few weeks. 1. Few people understand howto program computers. I have some figures for sales in two thousand and 2. There is little demand for our products. ten. In the first quarter we sold three hundred 3. We made a few contacts at the Singapore Trade Fair. and thirty-six units and had a turnover of seven 4. There was little criticism in the report. thousand three hundred and two pounds fifty-two 5. Many people answered our advertisement. pence. This produced a profit of three thousand four 6. No applicant was good enough for the job. hundred and fifty pounds. The second and third quarter performance was better with profit between three thousand eight hundred and ninety-one TASKS 79 pounds fifteen, and three thousand seven hundred pounds fifty. In the fourth quarter, the number of Quantifiers (3) units sold was two hundred and fifteen, or about half the previous two quarters. Profit was also down, E x ercis e 1 to one thousand nine hundred and forty-three 'Each day we process hundreds of orders. Every pounds twenty one pence. order comes by email. All orders are entered into our database. Each request is checked with our current TASKS 81 stock. Every order is immediately transferred to the warehouse. M orders are despatched within one hour. Time E x ercis e 2 E x ercis e 1 vk.com/bastau 199 5. Theres nothing about the company in the newspaper. TASKS 84 6. We decided to take some money out of our emergency bank account. W) Like, As, The Same As and 7. They put a lot of money into research. Different From 8. They have taken business from us. 9. The computer is on the desk. E x ercis e 1 (M) E x ercis e 3 (M) vk.com/bastau outside, 166 present habit, 94 S too, 138 over, 166 present perfect, 40 same, 168 transitive, 78, 102 present perfect say, 90 P continuous, 32, 34 schedule, 44 U passive, 80, 82 present perfect seldom, 136 uncountable noun, 122, past continuous, 28, 40 continuous negative, sentence, 114 124, 154, 156, 158 past continuous 32 shall, 42 under, 166 negative, 28 present perfect shant, 42 unless, 48, 50 past continuous continuous question, should, 74 until, 162 question, 28 32 shouldnt, 74 up, 166 past habit, 94 present perfect simple, simple sentence, 114 up to, 162 past participle, 30, 36, 30, 34, 36 since, 34, 162 used to, 94 38, 40, BF6 present perfect simple singular noun, 122, usually, 136 past perfect, 38, 40 negative, 30, 36 124 past perfect negative, 38 present perfect simple so, 116 V past perfect question, 38 question, 30, 36 so that, 116 verb + adverb, 100 past simple, 22, 24, 26, present simple, 12, 14, some, 150, 152, 154, 156 verb + preposition, 98 36,40 16, 18, 22,40 somebody, 152 verb phrase, 114 past simple negative, 24, present simple negative, someone, 152 very, 138 36, 62 14,62 something, 152 past simple question, present simple question, sometimes, 136 W 26, 36, 62 16, 62 somewhere, 152 was, 4, 28 past tense, 22, 36, 40, present tenses, 40 sorry, 178 weekly, 136 BF6 present time markers, 6 statement, 114 were, 4, 28 past tenses, 40 probability, 74 still, 140 what, 108, 116 permission, 66, 68 process description, 82 subordinate clause, 116, when, 108, 114, 116 personal pronoun, 144 prohibition, 66, 68, 72 118, 120 where, 108, 116 phrasal verb, 100 pronoun, 144, 146, 148, subordinating which, 108, 114, 116, 118 plan, 44, 46 150 conjunction, 114, 116, while, 116 plural noun, 122, 124 120 who, 108, 114, 116, 118 position, 166 Q suggesting, 42, 74 who(m), 108 positive (statements), 6, quantifier, 154, 156, superlative adjective, 132 wh-question, 108 12 , 22 158 wh-word, 116 positive adjective, 132 quarterly, 136 T why, 108, 116 positive imperative, 20 question, 10, 16, 26, 28, tell, 90 will, 42, 64 positive statement, 102 30,32,36,38, 106, tense review, 52, 54 willingness, 64 possessive determiner, 108, 114 that, 114, 116, 148 wont, 42, 64 146 question tag, 76 the, 142 would, 64 possessive pronoun, 146 the same as, 168 wouldnt, 64 possibility, 66, 68 R there is/are, 84 preposition, 162, 164, raise, 96 these, 148 Y 166, 168 rarely, 136 they are, 84 yearly, 136 present continuous, 6, 8, reason, 120 this, 148 yes/no question, 106 10, 18,40,44, 46 reflexive pronoun, 146 those, 148 yesterday, 22 present continuous relative clause, 118 though, 114, 116 yet, 140 negative, 8 relative pronoun, 118 till, 162 present continuous request, 64, 68 time, BF5 Z question, 10 rise, 96 to, 164 zero article, 142 vk.com/bastau P re -Inte rm e d ia te Business G ra m m a r Collins English for Business Choose the topics of most interest to you or work through the whole book for a comprehensive course in pre-interm ediate grammar.
https://de.scribd.com/document/342186458/BGP-pre-pdf
CC-MAIN-2019-30
refinedweb
46,152
84.07
class Solution(object): def simplifyPath(self, path): places = [p for p in path.split("/") if p!="." and p!=""] stack = [] for p in places: if p == "..": if len(stack) > 0: stack.pop() else: stack.append(p) return "/" + "/".join(stack) you use str built-in function like join and split, which is not appropriate in the interview case... said in 9 lines of Python code: if len(stack) > 0: more pythonic would be if stack: You solution is good. I just change a little to make it a little neater. def simplifyPath(self, path): stack = [] for p in path.split("/"): if p == "..": if stack: stack.pop() elif p and p != '.': stack.append(p) return "/" + "/".join(stack) Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/28240/9-lines-of-python-code
CC-MAIN-2017-34
refinedweb
130
79.46
How to: Return Items from a List This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. To return items from a list, you can instantiate an SPWeb object and drill down through the object model to the SPListItemCollection object for the list. After you return the collection of all items for a list, you can iterate through the collection and use indexers to return specific field values. The following example returns all the items for a specified Events list. It assumes the existence of a text box that can be used to type the name of an Events list. Dim mySite As SPWeb = SPContext.Current.Web Dim listItems As SPListItemCollection = mySite.Lists(TextBox1.Text).Items Dim i As Integer For i = 0 To listItems.Count - 1 Dim item As SPListItem = listItems(i) Response.Write(SPEncode.HtmlEncode(item("Title").ToString()) & " :: " _ & SPEncode.HtmlEncode(item("Location").ToString()) & " :: " _ & SPEncode.HtmlEncode(item("Begin").ToString()) & " :: " _ & SPEncode.HtmlEncode(item("End").ToString()) & "<BR>") Next i In the example, indexers are used both to return the list that is typed by the user and to return specific items from the list. To return the items, the indexers must specify the name of each column whose value is returned. In this case, all the field names pertain to a common Events list. This example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces. Use one of the GetItem* methods of the SPList class to return an item or subset of items from a list. The following table lists the methods provided by SPList that you can use to return list items. Dim mySite As SPWeb = SPContext.Current.Web Dim list As SPList = mySite.Lists("Books") Dim query As New SPQuery() query.Query = "<Where><Gt><FieldRef Name='Stock'/><Value Type='Number'>100</Value></Gt></Where>" Dim myItems As SPListItemCollection = list.GetItems(query) Dim item As SPListItem For Each item In myItems Response.Write(SPEncode.HtmlEncode(item("Title").ToString()) & "<BR>") Next item The previous example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces. The example assumes the existence of a Books list that has a Stock column containing number values. The previous example uses a constructor to instantiate an SPQuery object, and then assigns to the Query property of the query object a string in Collaborative Application Markup Language Core Schemas that specifies the inner XML for the query (in other words, the Where element). After the GetItems property is set, the query object is passed through the GetItems method to return and display items. You can perform cross-list queries to query more efficiently for data across multiple Web sites. The following example uses the SPSiteDataQuery class to define a query, and then uses the GetSiteData method to return items where the Status column equals "Completed". Dim webSite As SPWeb = SPContext.Current.Web Dim query As New SPSiteDataQuery() query." query." + "<Value Type=""Text"">Completed</Value></Eq></Where>" Dim items As System.Data.DataTable = webSite.GetSiteData(query) Dim item As System.Data.DataRow For Each item In items Response.Write((SPEncode.HtmlEncode(item("Title").ToString()) + "<BR>")) Next item This example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.
https://msdn.microsoft.com/en-us/library/ms456030(v=office.12).aspx?cs-save-lang=1&cs-lang=vb
CC-MAIN-2017-13
refinedweb
582
50.23
STRSEP(3) BSD Programmer's Manual STRSEP(3) strsep - separate strings #include <string.h> char * strsep(char **stringp, const char *delim); The., one caused by two adjacent delimiter characters, can be detected by comparing the location referenced by the pointer re- turned by strsep() to '\0'. If *stringp is initially NULL, strsep() returns NULL. The following uses strsep() to parse a string, containing tokens delimit- ed by whitespace, into an argument vector: char **ap, *argv[10], *inputstring; for (ap = argv; ap < &argv[9] && (*ap = strsep(&inputstring, " \t")) != NULL;) { if (**ap != '\0') ap++; } *ap = NULL; The strsep() function is intended as a replacement for the strtok() func- tion. While the strtok() function should be preferred for portability reasons (it conforms to ANSI X3.159-1989 ("ANSI C")) it is unable to han- dle empty fields, i.e., detect fields delimited by two adjacent delimiter characters, or to be used for more than a single string at a time. The strsep().
http://mirbsd.mirsolutions.de/htman/sparc/man3/strsep.htm
crawl-003
refinedweb
159
64.91
I'm a complete novice with REACT, especially to extract information from the server. I don't have any API inside my backend, so... Can I generate react code as follow? Example of my component: var Test= React.createClass({ render: function () { return ( <div> <p> This is my test: {this.props.name} </p> </div> ); } }); <script type="text/babel"> <?php foreach($tests as $test){ ?> ReactDOM.render( <div className="text-center"> <Test name="Test 1" /> <Test name="laralala" /> </div> ,document.getElementById("test") ); <?php} ?> </script> Accessing data from PHP One possible solution would be to put your data (generated by PHP) into the generated HTML page as global/static JS variables, like var data = <?php echo json_encode($data); ?>;. As long as you only need the data initially this will work fine. The issue you will run into is that you have to reload your page every time $data was updated (by a form for example). This kinda goes agains all this "single page application" logic. But I guess if you do not have an API, you're stuck with this solution. @SPA React currently is all the rage. But if you do not need all its power (beeing a SPA with routing, client-side state, ...) I would suggest just using something simple, yet powerful, like jQuery. Using it is fine, even in 2016. You also could look into Polymer or Web Components. If you do not already know React and only need it to render some HTML, I don't think you should have to learn it. There are other good alternatives to render dynamic HTML (isn't that what PHP was mode for initially?!).
https://codedump.io/share/PSLn8uxD3jOP/1/generate-reactjs-inside-php-loop
CC-MAIN-2017-39
refinedweb
271
67.86
: /* * Contrast compiling with: * gcc -UBAD -o mmap-rw mmap-rwx.c * gcc -DBAD -o mmap-rwx mmap-rwx.c */ #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <errno.h> #include <string.h> int main() { size_t *m; #ifdef BAD m = mmap( NULL, 1024, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); #else m = mmap( NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); #endif if( m == MAP_FAILED ) printf("mmap failed: %s\n", strerror(errno)); else printf("mmap succeeded: %p\n", m); return 0; } Similarly, try running the following with EMULTRAMP both enabled and disabled. This convoluted code forces gcc to set up a trampoline for the nested function f2(). The trampoline is executable code which lives on the stack and could allow the user to inject their own code via the variable i. /* * Contrast compiling with: * gcc -DTRAMPOLINE -o trampoline trampoline.c * gcc -UTRAMPOLINE -o trampoline trampoline.c * */ #include <stdio.h> typedef void (*fptr)(void) ; void f0(fptr f) { (*f)(); } void f1() { int i ; printf("Enter an interger: "); scanf("%d", &i); void f2() { printf("%d: Bouncey bouncey bounce!\n", i); } #ifdef TRAMPOLINE f0(f2); #endif } int main () { f1() ; return 0; } 2. The second is Address Space Layout Randomization (ASLR). This provides a randomization of the memory map of a process (as reported, for example, by pmap) and thus makes it harder for an attacker to find the exploitable code within that space. Each time a process is spawned from a particular ELF executable, its memory map is different. Thus exploitable code which may live at 0x00007fff5f281000 for one running instance of an executable may find itself at 0x00007f4246b5b000 for another. While the vanilla kernel does provide some ASLR, a PaX patched kernel increases that. Furthermore, when an application is built as a Position Independent Executable ( /* * Contrast compiling with: * gcc -o aslr-test-withpie -fPIC -pie aslr-test.c * gcc -o aslr-test-without -fno-PIC -nopie aslr-test.c * */ #include <stdio.h> void doit() { ; return ; } int main() { printf("main @ %p\n", main); printf("doit @ %p\n", doit); return 0; } For more information on PIE, see our documentation on the relax certain PaX restrictions on a per ELF object basis. This is done by tweaking the PaX flags which are read by the kernel when the ELF is loaded into memory and execution begins. This seconds step is usually straight forward except when the ELF object that requires the relaxation is a library. In that case, the library's flags have to be back ported to the executable that links against: As stated above, some PaX features can be enforced (in the case of SOFTMODE) or relaxed (in the case of non-SOFTMODE) on a "per ELF object" basis. These are PAGEEXEC, EMULTRAP, MPROTECT, RANDMMAP and SEGMEXEC and these are respectively controlled by the following flags: P, E, M, R, S and p, e, m, r, s. The upper case. Currently the PaX patches support three ways of doing PaX markings: EI_PAX, PT_PAX and XATTR_PAX. EI_PAX places the PaX flags in bytes 14 and 15 of the e_ident field of an ELF objects's header. But this is broken in recent versions of glibc and is no longer supported. (See While PT_PAX is still support, the preferred approach is to use XATTR_PAX which places the PaX flags in a file system's extended attributes. This has the advantage that it does not modify the ELF object in any way, but the disadvantage that the filesystems which house these objects, and the utilities used to copy, move and archive, them, must support xattrs. In the case of Gentoo and portage, this means that tmpfs must support the user.pax.* xattr namespace in which the PaX flags are placed, not just the security.* and trusted.* namespaces. (Note: user.pax.* is the subspace of user.* which will be used for PaX related xattr information. We do not enable the entire user.* namespace in tmpfs to reduce the risk of attack vectors via that path.) One final caveat about the two supported methods of doing PaX markings: the PaX kernel [*] Enable various PaX features PaX Control -> [ ] Support soft mode [ ] Use legacy ELF header marking [*] Use ELF program header marking [ ] Use filesystem extended attributes marking MAC system integration (none) ---> Non-executable page -> [*] Enforce non-executable pages [*] Paging based non-executable pages [*] Segmentation based non-executable pages <--- Not available on amd64 [*] Emulate trampolines [*] Here As we mentioned above, there are five PaX protections that can be enforced (in SOFTMODE) or relaxed (in non-SOFTMODE) on a per ELF object basis: PAGEEXEC, EMULTRAP, MPROTECT, RANDMMAP and SEGMEXEC. The later, SEGMEXEC, is only available on x86 CPUs which support segmentation, unlike paging which is supported on all CPUs, even x86. Since some programs break for one reason or another under full PaX enforcement, we are faced with the choice of either fixing the code to work with PaX or relaxing one or more of these protections. In practice, "fixing the code" may be very difficult and we resort to the latter. The general approach should be to try full enforcement, and if something breaks, use dmesg to obtain a report from the kernel regarding why and then relax that particular protection. Even this is not generally needed on a Gentoo system because the ebuilds should set the correct flags for you via the pax-util.eclass. If you find that you have to set your own flags, we would ask that you file a bug report. Generally setting the PaX flags is straightforward, but the user should keep a few things in mind: 1) One can set either PT_PAX and/or XATTR_PAX flags on the ELF object independently of one another. Similarly, the kernel can be configured to read either, both or neither fields. It is up to you to make sure that you set the flags in the field being used by the kernel to get the desired results. For example, if you have PT_PAX="Pe---" while XATTR_PAX missing on the object, but the kernel is configured only to use XATTR_PAX, you may not get the desired result! 2) The recommended approach is to mark both PT_PAX and XATTR_PAX fields identically on the objects whenever possible, and set the kernel to read only XATTR_PAX. The "whenever possible" is where things get complicated and the two fields may not wind up containing the same flags. If the ELF does not contain a PAX_FLAGS program header, PT_PAX marking will fail. However, the absence of this program header will not affect XATTR_PAX markings. If the ELF is busy (ie. there is a running process making use of the ELF's text), then one can read the PT_PAX flags but not set them. Again, this does not affect setting or getting XATTR_PAX flags. On the other hand, if you are using any file systems which do not support extended attributes, then XATTR_PAX marking will fail on those file systems while PT_PAX marking is uneffected, except as already stated. This can be fairly subtle because copying a file from a file system with xattrs to one without, and then back again will drop the XATTR_PAX flags. Or tarring with an older version of tar which does not preserve xattrs will again drop our flags. 3) The PaX flags are only enforced when a process is loaded from an ELF executable. This executable in turn usually links dynamically against shared objects in memory. Using `cat /proc/<pid>/status | grep PaX` gives you the resulting PaX enforcement on the running process with PID=<pid>. But since the the executable and shared objects can have different flags, the question arises, which ones are used to determine the final running PaX enforcements? The answer is the executable for reasons of control and security. If the libraries were to set the runtime PaX enforcement, then which of the libraries would "win" if an executable linked against many? And one overly relaxed library could relax the privileges on many executables that link against it. Eg. Relaxing all PaX protection on glibc would effectively turn PaX off on one's system. Nonetheless, it may be the code in the library itself that needs the relaxation of some PaX enforcement. In that case, one has to "back port" the flags from the library to the executable that uses it. Below we describe the utilities provided on a Gentoo system for working PaX markings. There are several since as PaX evolved, new features were needed. Each one emphasizes a different need with respect to the above caveats. 1. paxctl This it the traditional upstream package for setting PaX flags. It is limited only in that it sets PT_PAX only, not XATTR_PAX. It is provided by emerging sys-apps/paxctl. It does have one functionality that no other utility has: it can either create a PAX_FLAGS program header or convert a GNU_STACK to PAX_FLAGS. Both of these are not recommended since they can break the ELF under certain circumstances. However, in the extreme case that you cannot use XATTR_PAX (eg. you can't use file systems that support extended attributes) and you are dealing with an ELF object that wasn't build with a PAX_FLAGS program header, then these options are available to you via this utility. Here is a synopsis of its usage:!) Note that paxctl also reports on an older PaX protection called RANDEXEC. This is now deprecated --- the randomization of the base address of a processes now simply part of ASLR on all executables build ET_DYN rather than EX_EXEC. Here is paxctl in action: # paxctl -v /usr/bin/python3.2 PaX control v0.7 Copyright 2004,2005,2006,2007,2009,2010,2011,2012 PaX Team <pageexec@freemail.hu> - PaX flags: -----m-x-e-- [/usr/bin/python3.2] MPROTECT is disabled RANDEXEC is disabled EMUTRAMP is disabled # paxctl -P /usr/bin/python3.2 # paxctl -v /usr/bin/python3.2 PaX control v0.7 Copyright 2004,2005,2006,2007,2009,2010,2011,2012 PaX Team <pageexec@freemail.hu> - PaX flags: P----m-x-e-- [/usr/bin/python3.2] PAGEEXEC is enabled <--- Note: this added to the earlier flags, it didn't overwrite them. MPROTECT is disabled RANDEXEC is disabled EMUTRAMP is disabled 2. getfattr setfattr These are not PaX specific utilities but are general utilities to set a file's extended attributes. On Gentoo, they are provided by emerging sys-apps/attr. Since XATTR_PAX uses the user.* namespace, specifically it uses "user.pax.flags", you can use set/getfattr to work with this field. However, keep in mind that setfattr and getfattr know nothing about PaX, so they will not perform any sanity checking of what you are putting into that field. Only if you set user.pax.flags to some meaningful combination of the chars PpEeMmRr # getfattr -n user.pax.flags /usr/bin/python3.2 getfattr: Removing leading '/' from absolute path names # file: usr/bin/python3.2 user.pax.flags="Hi Mom, wish you were here." <--- Mom appreciates it, but PaX does not. There is no sanity checking. 3. paxctl-ng paxctl-ng is the new swiss army knife of working with PT_PAX an XATTR_PAX markings. It can be built with support for just one or the other or both types of markings. When built with support for both, it can copy PT_PAX to XATTRP_PAX fields or vice versa, to make sure you have consistency. In sum, it can do everything paxctl and set/getfattr can do, except it will not try to create or convert a PAX_FLAGS program header. This is discouraged and should only be use in the corner case mentioned above. Here is a synopsis of its usage: Package Name : elfix 0.7.1 Bug Reports : Program Name : paxctl-ng Description : Get or set pax flags on an ELF object Usage : paxctl-ng -PpEeMmRrSsv ELF | -Zv ELF | -zv ELF : paxctl-ng -Cv ELF | -cv ELF | -dv ELF : paxctl-ng -Fv ELF | -fv ELF : paxctl-ng -Lv ELF | -lv ELF : paxctl-ng -v ELF | -h Options : -P enable PAGEEXEC -p disable PAGEEXEC : -E enable EMUTRAMP -e disable EMUTRAMP : -M enable MPROTECT -m disable MPROTECT : -R enable RANDMMAP -r disable RANDMMAP : -S enable SEGMEXEC -s disable SEGMEXEC : -Z all secure settings -z all default settings : : -C create XATTR_PAX with most secure setting : -c create XATTR_PAX all default settings : -F copy PT_PAX to XATTR_PAX : -f copy XATTR_PAX to PT_PAX : -L set only PT_PAX flags : -l set only XATTR_PAX flags : : -v view the flags, along with any accompanying operation : -h print out this help Note : If both enabling and disabling flags are set, the default - is used The following is an example of paxctl-ng in action: #. We also provide bindings to python via a module, pax.so, which is installed by emerging dev-python/pypax. This package is a dependency of sys-apps/elfix since the both revdep-pax and migrate-pax import it. It can be compiled with either PT_PAX and/or XATTR_PAX support, like paxctl-ng, but it is not as featureful since its scope is limited to just the needs of revdep-pax and migrate-pax. This may change in the future if there is a need to better integrate PaX marking with portage which is written in python. Currently pax.so publicly exports the following: pypaxctl is a simple front end to pax.so which just gets and sets the PaX flags using the same logic. When getting the flags, if both PT_PAX and XATTR_PAX are present, the latter will override the former. When setting, it will set both fields whenever possible. Here it is in action: #: -em-- If the logic of XATTR_PAX taking precedence over PT_PAX is not what you want, it can be compile with just PT_PAX xor XATTR_PAX support. In this case, the other field is not ever touched, as demonstrated below: #. revdep-pax This utility is used to map out the linkings between all the ELF objects on your system and their shared objects in both directions. It can then search for PaX flag markings that are mismatched between the shared objects than the executables; and optionally, allows the user to migrate the markings forwards or backwards on a per ELF object basis. Here's a synopsis of its usage: Package Name : elfix Bug Reports : Program Name : revdep-pax Description : Get or set pax flags on an ELF object Usage : revdep-pax -f [-v] print out all forward mappings for all system binaries : revdep-pax -r [-ve] print out all reverse mappings for all system sonames : revdep-pax -b OBJECT [-myv] print all forward mappings only for OBJECT : revdep-pax -s SONAME [-myve] print all reverse mappings only for SONAME : revdep-pax -l LIBRARY [-myve] print all reverse mappings only for LIBRARY file : revdep-pax [-h] print out this help : -v verbose, otherwise just print mismatching objects : -e only print out executables in shell $PATH : -m don't just report, but mark the mismatching objects : -y assume "yes" to all prompts for marking (USE CAREFULLY!) Here's revdep-pax in action. Since the out is long, we've replaced some of it with ellipses: # revdep-pax -f < --- Report all mismatching forward link--- ) ..... # revdep-pax -m -b /usr/bin/python3.2 < --- Forward port PaX flags for python3.2--- ) Will mark libraries with --m-- Set flags for /usr/lib64/libpython3.2.so.1.0 (y/n): n < --- You will be prompted unless you give -y Set flags for /lib64/libpthread-2.16.so (y/n): n < --- We'll say 'n' to each for this demo Set flags for /lib64/libc-2.16.so (y/n): n Set flags for /lib64/libdl-2.16.so (y/n): n Set flags for /lib64/libutil-2.16.so (y/n): n Set flags for /lib64/libm-2.16.so (y/n):-- One final note about revdep-pax's internals. It currently uses a "mixed" approach to finding all the ELF objects on a system and their shared objects. To get the list of objects it uses Gentoo's portage database at /var/db/pkg, but to get the linkings, it uses /usr/bin/ldd which is a bash script wrapper to `LD_TRACE_LOADED_OBJECTS=1 /lib/ld-linux.so.2` on glibc, and its own program on uclibc. We are working towards two separate approaches: 1) The future revdep-pax will use /var/db/pkg for both the list of ELF objects and their linkings to shared objects. This will be a lot faster than the current utility. 2) There will be a revdep-pax-ng which will not assume a Gentoo system, but rather construct a list ELF objects collected from a combined $PATH for the executables and /etc/ld.so.conf for the shared objects. This utility will work on non-Gentoo systems and be more exhaustive than revdep-pax, but much slower. Here -ng stands for Not Gentoo. 6. migrate-pax At this point you're probably fed up with dealing with both PT_PAX and XATTR_PAX fields and their relationship to the kernel's configuration, and you just want to drop the older PT_PAX and get on with life! migrate-pax does only that ... it will go through all ELF objects on your system and migrate the PT_PAX field to XATTR_PAX. That's it. Package Name : elfix Bug Reports : Program Name : migrate Description : Migrate PT_PAX to XATTR_PAX Flags on all system ELF objects Usage : migrate -v print out all system ELF objects : migrate -m [-v] migrate flags on all system ELF objects : migrate -d [-v] delete XATTR_PAX on all system ELF objects : migrate [-h] print out this help : -v be verbose when migrating
https://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo/xml/htdocs/proj/en/hardened/pax-quickstart.xml?revision=1.14
CC-MAIN-2018-39
refinedweb
2,916
61.97
How to get acknowledgement when sending message? Hi, I have registered my SiPy in backedn.sigfox.com and tried to send some messages using REPL and this code:) s.send(bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])) REPL response was 12 and I see no messages in my backend. So how can I ensure that message is successfully sended? Something like ACK. Thanks in advance. similar problem.. avgSnr=20.74 rssi=-52.00 Used HW: FiPy on '1.17.5.b6' No problem @josua! I'm glad you got it up and running! :) I had an interesting discovery about using the 22 dBm SiPy in RCZ1 along the way so we all learnt something today! Best of luck with your project! :) @bucknall Yes, it works now. I just tried to use it (to send msg) out of the building and it works.. Fill my self silly as I didn't try to do it earlier.. I really appreciate your help. Your team is great! Thank you! @josua Ok! Quick question, I know it sounds a little bit silly but which connector do you have the antenna plugged into? @bucknall According to the sigfox coverage map there are 3 base stations and more. @josua Hmm ok possibly not what I thought! Do you know that you definitely have Sigfox Coverage where you are located? Hi @josua I think I know what your problem might be! What country are you trying to use your device in and also which version of the SiPy do you have? The 14dBm or the 22dBm? @josua we're currently working to push all of our source code up to GitHub and this includes the Sigfox classes. This should be coming in the next couple of weeks. Daniel will make an announcement when this takes places! I'm just testing it now! @bucknall By sources I mean source code. For example source code of the socket or sigfox classes. Maybe I don't have the clear understanding of how it all works. But I think there are somewhere definition of those classes with their methods? Am I right? Looking forward to hear the results of your investigation. Thank you! @josua What do you mean by sources? This is the link to the Sigfox Class if that helps? Also, I tried it with two of my SiPys... oddly one of them worked and the other failed so I'm trying to pinpoint what is going on! Should have an answer for you this afternoon! @bucknall Looking forward to your response. By the way, where I could find the sources of the API? Tried to find sources for sigfox and socket classes, but unsuccessfuly. Thanks! @josua No worries! If you press "spacebar" 4 times from the margin, you'll start a code block :) Hmm I've just tried it with two of my devices... one of them works, the other is generating the same error that you are seeing. I will follow this up and work out the cause. Thanks! ok it means: pc/network software – operational errors Network is down. but what can be the reason? Bad covering of the sigfox network? Or something else... thank you for your response. I tried to execute your snippet but the error occurs: s.send("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 100] ENETDOWN What do You think it could be? P.S. I don't see something like "code block button" in the message editor, how you do it? :) Sigfox does not send an ACK message by default as messages are primarily uplink only. You can, however, request a downlink message which can be used as a method to check if your message was received. To enable a downlink message to be sent to your device you could use the following snippet of code: from network import Sigfox import socket sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1) s = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW) s.setblocking(True) # the True argument is what sets the SiPy to expect a downlink message s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, True) s.send("hello") s.recv(32)
https://forum.pycom.io/topic/844/how-to-get-acknowledgement-when-sending-message/
CC-MAIN-2019-18
refinedweb
697
77.33
Getting Started: Using the GCP Console or Getting Started: Using the gsutil Tool. Naming The bucket namespace is global and publicly visible. Every bucket name must be unique across the entire Cloud Storage namespace. For more information, see Bucket and Object Naming Guidelines.. Multi-Regional Storage or Regional Storage class. These classes provide the best availability with the trade-off of a higher price. Data that will be infrequently accessed and can tolerate slightly lower availability can be stored using the Nearline Storage or Coldline. The boto plugin includes code that validates server certificates by default. to Cloud Storage to initiate a resumable upload, then you should use Compute Engine instances in the same locations as your Cloud Storage buckets. You can then use a geo IP service to pick the Compute Engine region to which you route customer requests, which will help.
https://cloud.google.com/storage/docs/best-practices?hl=da
CC-MAIN-2019-30
refinedweb
143
57.16
Management, monitoring, automation, and instrumentation topics for the IT-Pro. PsInfo is great for gathering asset information from Windows computers, both locally and remotely. PowerShell is great for automation and cleaning up output (among other things) as well as working with database driven data. The following examples show how to gather an itemized list of the installed software on remote machines, process the data, then either display it to the screen or store it in a database. It's worth noting that PsInfo can also work on multiple remote computers from its native command line, or even read a list of computers from a file (check out the PsInfo site for more info). Since the final example seeks to show PsInfo in a database driven envoriment, PowerShell comes in very handy. Note: In order for this example to work the necessary network connectivity and credentials will need to be in place. Consider the following examples: 1 - The output is merely displayed on the screen. With this method the output can be redirected to a file and imported into an application like Excel for further analysis or record keeping. 2 - A database is used to drive the computers polled as well as store the output. The database table is very flat (one table) with 2 fields: 'Computer' and 'Software'. For large amounts of data, this will need to be normalized. With the following output (imported into Excel): Example 1: Standard Screen Output The following PowerShell script gathers a software inventory from 3 remote computers ('happyhour', 'shaken', and 'extradry'). Presumably, your computer names will be different. After gathering and parsing the data, it's then displayed on the screen for all machines successfully queried. Before running this script, test your connectivity and credentials with a single PsInfo command: PsInfo -s Applications \\somecomputer PsInfo -s Applications \\somecomputer Example PowerShell script: $computersToQuery = ("happyhour","shaken","extradry")] = @{} } }}foreach ($computer in $softwareInventory.Keys) { foreach ($softwareItem in $softwareInventory[$computer].Keys) { $computer + ":" + $softwareItem }} Your output should look something like: Example 2: Save Output to a Database This example is additive to the first in that it adds the following 3 items: The following is the database schema for this example: #) { "Loading-" + $computer + ":" + $softwareItem # Try an Insert than an Update() For more information: If you would like to receive an email when updates are made to this post, please register here RSS Hi, nice thing. But what about removed software? That should be marked as deleted. I did myself something similar but not with Powershell. I remebered the last output from psinfo -s and diff´ed this with the actual output, so i get all those software which has been deleted from the last run..... Regards, Bernd. Hey Bernd, That's a good point. I looked that the above database enabled script to see what modifications would need to be made to allow removed applications to be trackable and realized that it will work as is (although I admit, that was not my intention). Every time the script is run, it will add/overwrite entries for the applications with a new time stamp, but it won't delete previous entries for a computer. Therefore one can query for specific computer and see the application audit history. Thanks for your feedback, Otto Sweet! Check out this post from Otto Helweg on using PsInfo and PowerShell (I <3 you, PowerShell, I could not run the sample scripts: error: PS C:\temp\Pstoolsv2.43> c:\temp\pstoolsv2.43softwareinventory.ps1 File C:\temp\pstoolsv2.43\softwareinventory.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details. At line:1 char:42 + c:\temp\pstoolsv2.43\softwareinventory.ps1 <<<< PS C:\temp\Pstoolsv2.43> Hello Ramon, The default PowerShell execution policy is to only run "signed" scripts (makes it less likely to be a vehicle for worms). In order to change this, run the following command in PowerShell: set-executionpolicy remotesigned This is great! Thanks for this post! I found this info helpful but will show my ignorance on one point. You reference a database in part 2. What did you use to create this database? We are at a small, private college and have SQL Server Express installed there, as well as SQL Server itself. Would the express edition be sufficient for databases of information that would be from or used with Powershell applications? Also, I am assuming that the database was created beforehand. If the script creates it, which it does not look like it does, how does it do this? If the script does not create the tables or database, but merely updates an existing database, then please ignore this second question. Thank you in advance. Hello Ray, No, the script does not create the database. It was created beforehand. Since I'm using SQL 2005, I use 'SQL Server Management Studio' to create my database(s) and table(s). This should install with the Client Tools (but might not be available for the 'express' version - never tried that one). Hope that helps, Tonight I stumbled across this blog and thought it was interesting. [link] I like it so much I think Last Friday Quest software made GA the RC of the ActiveRoles ADcmdlets. This, to me, is another significant I have tried the script on a group of 100 servers, but what i find is that while on the powershell screen it loads many applications, i find only a handful actually appear in the database. Could the strip duplicates actually strip duplicates from other servers? This can be done natively without pstools. It's all available in wmi. get-wmiobject -class "win32_Product" -namespace "root\cimv2" -computername sirvine | sort Name | select-object Name,Vendor,Version,Caption | export-csv sirvineaudit.csv The script does not work for me. It does not recognize the psinfo call made be the script. Below is the error output. The term './psinfo.exe' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again. At line 5, position 35 $psinfoOutput = ./psinfo.exe -s Applications \\$computer Besides creating a custom WMI report, you could use PSInfo to do something similar I believe. Combine
http://blogs.technet.com/otto/archive/2007/03/04/quick-and-dirty-software-inventory-with-psinfo-and-powershell.aspx
crawl-002
refinedweb
1,032
55.64
Hi, I am able to build OpenEV on FreeBSD 6.0 using the following installed FreeBSD ports (packages): py-gtk-0.6.11_1 A set of Python bindings for GTK gtk-1.2.10_12 Gimp Toolkit for X11 GUI (previous stable version) gtkglarea-1.2.3 An OpenGL widget for the GTK+ GUI toolkit py-gtk-0.6.11_1 A set of Python bindings for GTK gdal-1.2.1_2 A translator library for raster geospatial data formats xorg-libraries-6.8.2 X11 libraries and headers from X.Org (w/ OpenGL) But I get this error when I try to run the openev.py script: %pymod/openev.py Traceback (most recent call last): File "pymod/openev.py", line 80, in ? import gviewapp File "/home/sam/openev/openev/pymod/gviewapp.py", line 136, in ? import gtkmissing File "/home/sam/openev/openev/pymod/gtkmissing.py", line 2, in ? import _gtkmissing ImportError: dynamic module does not define init function (init_gtkmissing) % I do see an init function defined in gtkmissing.c and I tried fiddling with the PYTHONPATH env variable but with no success. Any help would be greatly appreciated. The FreeBSD ports/package stuff (binaries,docs,includes,lib...) gets installed into /usr/local/... and this is where all the gtk, pygtk, gdal, ... stuff is on my FreeBSD system. If I can get this program working, I'll make at crack at creating a FreeBSD "port" () of OpenEV myself (it would be my first attempt at doing so, though). Has anyone got OpenEV working on FreeBSD? I'm trying to decide betweeen Ubuntu () and FreeBSD () for my ultimate GIS desktop workstation. Ubuntu has the lead so far, since I got OpenEV to build and work on it. I think I've decided on FreeBSD for my GIS server OS platform but I haven't used Ubuntu for server duties yet. Sam A. Many thanks!
http://sourceforge.net/p/openev/mailman/openev-discuss/thread/20060104044428.20211.qmail@web80503.mail.yahoo.com/
CC-MAIN-2014-23
refinedweb
311
78.96
Introduction This is a tutorial for function passing and returning object in java. The program is given below that adds two complex numbers. The program is extendable. Go enjoy the program. Let begin………… Before you begin.Do this - Create a separate java file for other class. - Create a java file for main class. - Import the created java class in main class file. Program for addition of two complex numbers using class in java. 1. Create a class. //declare the package name if the class file is //created in other package. package Myclasses; //import scanner import java.util.Scanner; //declare class public class ComplexNo { //declare variables. private int a,b; //functions should be public if needed to access from other class public void getdata() { //print message to enter numbers System.out.println("Enter a and b of a+ib:"); //Take input Scanner input = new Scanner(System.in); a = input.nextInt(); b = input.nextInt(); } public ComplexNo addit(ComplexNo x) { ComplexNo tmp = new ComplexNo(); tmp.a = a+x.a; tmp.b = b+x.b; return tmp; } public void print() { System.out.println("The Sum of Complex Numbers = "+a+"+i"+b); } } 2. Create ClassFunct.java file. //import our class import Myclasses.ComplexNo; // the name of our class its public public class ClassFunct { //void main public static void main (String[] args) { //declare class ComplexNo no1 = new ComplexNo(); ComplexNo no2 = new ComplexNo(); ComplexNo sum = new ComplexNo(); //call functions no1.getdata(); no2.getdata(); sum = no1.addit(no2); sum.print(); } } Output Enter a and b of a+ib: 1 2 Enter a and b of a+ib: 1 3 The Sum of Complex Numbers = 2+i5 How it Works - Objects of class are created. - The getdata function is called from main class. - functions. Main class - Create other class - Import your class. - Declare the class as public. - Add the void main function. - Declare class. - Declare objects. - Call functions. At the end. You learnt creating the Java program for Function passing and returning object . So now enjoy the program. Please comment on the post and share it.
https://techtopz.com/java-programming-function-passing-and-returning-object/
CC-MAIN-2019-43
refinedweb
337
61.83
I am datalogging a lot of data to a file on an SD card using the Ethernet shield and a RTC. i collect alot of datapoints overtime and this makes for some long files. I would like some input on if it is possible to do a variable filename in this comand. If possible i would like to change the file name on a monthly or even yearly basis. After you have 700 or so lines of data it becomes unmanageable. I have tried using a string but it seems it will not accept a string in place of using the DataLogFile or “DATA.CSV”. Idealy, i would like to end up with multiple files on the SD card with data from a set period of time. #include <Wire.h> #include <Time.h> #include <SdFat.h> #include <SdFatUtil.h> #include <SPI.h> #include <Ethernet.h> #define DataLogFile “DATA.CSV” … if (!myFile.open(DataLogFile, O_RDWR | O_CREAT | O_AT_END)) { error(“open file failed”); I had tried building a string I found the string was fine and worked as expected. DataFile = “”"; DataFile += “DAT”; DataFile += String(year()); DataFile += “.CSV”"; End resut = “DAT2012.CSV” However, when i replace DataLogFile with the string DataFile, as expected it errors. no matching function for call to SdFile::open(string&,int) If anyone has any suggestions, i would be greatful.
https://forum.arduino.cc/t/datalog-to-sd-card-filename-solved/86158
CC-MAIN-2021-39
refinedweb
220
76.93
Firstly, I'm going to explain the main features I've just added to my python back-testing package pysystemtrade; namely the ability to estimate parameters that were fixed before: forecast and instrument weights; plus forecast and instrument diversification multipliers. (See here for a full list of what's in version 0.2.1) Secondly I'll be illustrating how we'd go about calibrating a trading system (such as the one in chapter 15 of my book); actually estimating some forecast weights and instrument weights in practice. I know that some readers have struggled with understanding this (which is of course entirely my fault). Thirdly there are some useful bits of general advice that will interest everyone who cares about practical portfolio optimisation (including both non users of pysystemtrade, and non readers of the book alike). In particular I'll talk about how to deal with missing markets, the best way to estimate portfolio statistics, pooling information across markets, and generally continue my discussion about using different methods for optimising (see here, and also here). If you want to, you can follow along with the code, here. Key This is python: system.forecastScaleCap.get_scaled_forecast("EDOLLAR", "carry").plot() This is python output: hello world This is an extract from a pysystemtrade YAML configuration file: forecast_weight_estimate: date_method: expanding ## other options: in_sample, rolling rollyears: 20 frequency: "W" ## other options: D, M, Y Forecast weights A quick recap The story so far; we have some trading rules (three variations of the EWMAC trend following rule, and a carry rule); which we're running over six instruments (Eurodollar, US 10 year bond futures, Eurostoxx, MXP USD fx, Corn, and European equity vol; V2X). We've scaled these (as discussed in my previous post) so they have the correct scaling. So both these things are on the same scale: system.forecastScaleCap.get_scaled_forecast("EDOLLAR", "carry").plot() system.forecastScaleCap.get_scaled_forecast("V2X", "ewmac64_256").plot() Notice the massive difference in available data - I'll come back to this problem later. However having multiple forecasts isn't much good; we need to combine them (chapter 8). So we need some forecast weights. This is a portfolio optimisation problem. To be precise we want the best portfolio built out of things like these: There are some issues here then which we need to address. An alternative which has been suggested to me is to optimise the moving average rules seperately; and then as a second stage optimise the moving average group and the carry rule. This is similar in spirit to the handcrafted method I cover in my book. Whilst it's a valid approach it's not one I cover here, nor is it implemented in my code. In or out of sample? Personally I'm a big fan of expanding windows (see chapter 3, and also here) nevertheless feel free to try different options by changing the configuration file elements shown here. forecast_weight_estimate: date_method: expanding ## other options: in_sample, rolling rollyears: 20 frequency: "W" ## other options: D, M, Y Also the default is to use weekly returns for optimisation. This has two advantages; firstly it's faster. Secondly correlations of daily returns tend to be unrealistically low (because for example of different market closes when working across instruments). Choose your weapon: Shrinkage, bootstrapping or one-shot? In my last couple of posts on this subject I discussed which methods one should for optimisation (see here, and also here, and also chapter four). I won't reiterate the discussion here in detail, but I'll explain how to configure each option. BoostrappingThis is my favourite weapon, but it's a little ..... slow. forecast_weight_estimate: method: bootstrap monte_runs: 100 bootstrap_length: 50 equalise_means: True equalise_vols: True We expect our trading rule p&l to have the same standard deviation of returns, so we shouldn't need to equalise vols; it's a moot point whether we do or not. Equalising means will generally make things more robust. With more bootstrap runs, and perhaps a longer length, you'll get more stable weights. Shrinkage I'm not massively keen on shrinkage (see here, and also here) but it is much quicker than bootstrapping. So a good work flow might be to play around with a model using shrinkage estimation, and then for your final run use bootstrapping. It's for this reason that the pre-baked system defaults to using shrinkage. As the defaults below show I recommend shrinking the mean much more than the correlation. forecast_weight_estimate: method: shrinkage shrinkage_SR: 0.90 shrinkage_corr: 0.50 equalise_vols: True Single period Don't do it. If you must do it then I suggest equalising the means, so the result isn't completely crazy. forecast_weight_estimate: method: one_period equalise_means: True equalise_vols: True To pool or not to pool... that is a very good question One question we should address is, do we need different forecast weights for different instruments, or can we pool our data and estimate them together? Or to put it another way does Corn behave sufficiently like Eurodollar to justify giving them the same blend of trading rules, and hence the same forecast weights? forecast_weight_estimate: pool_instruments: True ## One very significant factor in making this decision is actually costs. However I haven't yet included the code to calculate the effect of these. For the time being then we'll ignore this; though it does have a significant effect. Because of the choice of three slower EWMAC rule variations this omission isn't as serious as it would be with faster trading rules. If you use a stupid method like one-shot then you probably will get quite different weights. However more sensible methods will account better for the noise in each instruments' estimate. With only six instruments, and without costs, there isn't really enough information to determine whether pooling is a good thing or not. My strong prior is to assume that it is. Just for fun here are some estimates without pooling. system.config.forecast_weight_estimate["pool_instruments"]=False system.config.instrument_weight_estimate["method"]="bootstrap" system.config.instrument_weight_estimate["equalise_means"]=False system.config.instrument_weight_estimate["monte_runs"]=200 system.config.instrument_weight_estimate["bootstrap_length"]=104 system=futures_system(config=system.config) system.combForecast.get_forecast_weights("CORN").plot() title("CORN") show() system.combForecast.get_forecast_weights("EDOLLAR").plot() title("EDOLLAR") show() Note: Only instruments that share the same set of trading rule variations will see their results pooled. Estimating statistics There are also configuration options for the statistical estimates used in the optimisation; so for example should we use exponential weighted estimates? (this makes no sense for bootstrapping, but for other methods is a reasonable thing to do). Is there a minimum number of data points before we're happy with our estimate? Should we floor correlations at zero (short answer - yes). forecast_weight_estimate: correlation_estimate: func: syscore.correlations.correlation_single_period using_exponent: False ew_lookback: 500 min_periods: 20 floor_at_zero: True mean_estimate: func: syscore.algos.mean_estimator using_exponent: False ew_lookback: 500 min_periods: 20 vol_estimate: func: syscore.algos.vol_estimator using_exponent: False ew_lookback: 500 min_periods: 20 Checking my intuition Here's what we get when we actually run everything with some sensible parameters:() Although I've plotted these for corn, they will be the same across all instruments. Almost half the weight goes in carry; makes sense since this is relatively uncorrelated (half is what my simple optimisation method - handcrafting - would put in). Hardly any (about 10%) goes into the medium speed trend following rule; it is highly correlated with the other two rules. Out of the remaining variations the faster one gets a higher weight; this is the law of active management at play I guess. Smooth operator - how not to incur costs changing weights Notice how jagged the lines above are. That's because I'm estimating weights annually. This is kind of silly; I don't really have tons more information after 12 months; the forecast weights are estimates - which is a posh way of saying they are guesses. There's no point incurring trading costs when we update these with another year of data. The solution is to apply a smooth: forecast_weight_estimate: ewma_span: 125 cleaning: True Now if we plot forecast_weights, rather than the raw version, we get this: system.combForecast.get_forecast_weights("CORN").plot() title("CORN") show() There's still some movement; but any turnover from changing these parameters will be swamped by the trading the rest of the system is doing. Forecast diversification multiplier Now we have some weights we need to estimate the forecast diversification multiplier; so that our portfolio of forecasts has the right scale (an average absolute value of 10 is my own preference). Correlations First we need to get some correlations. The more correlated the forecasts are, the lower the multiplier will be. As you can see from the config options we again have the option of pooling our correlation estimates. forecast_correlation_estimate: pool_instruments: True func: syscore.correlations.CorrelationEstimator ## function to use for estimation. This handles both pooled and non pooled data frequency: "W" # frequency to downsample to before estimating correlations date_method: "expanding" # what kind of window to use in backtest using_exponent: True # use an exponentially weighted correlation, or all the values equally ew_lookback: 250 ## lookback when using exponential weighting min_periods: 20 # min_periods, used for both exponential, and non exponential weighting Smoothing, again We estimate correlations, and weights, annually. Thus as with weightings it's prudent to apply a smooth to the multiplier. I also floor negative correlations to avoid getting very large values for the multiplier. forecast_div_mult_estimate: ewma_span: 125 ## smooth to apply floor_at_zero: True ## floor negative correlations system.combForecast.get_forecast_diversification_multiplier("EDOLLAR").plot() show() system.combForecast.get_forecast_diversification_multiplier("V2X").plot() show() From subsystem to system We've now got a combined forecast for each instrument - the weighted sum of trading rule forecasts, multiplied by the FDM. It will look very much like this: system.combForecast.get_combined_forecast("EUROSTX").plot() show() Using chapters 9 and 10 we can now scale this into a subsystem position. A subsystem is my terminology for a system that trades just one instrument. Essentially we pretend we're using our entire capital for just this one thing. Going pretty quickly through the calculations (since you're eithier familar with them, or you just don't care): system.positionSize.get_price_volatility("EUROSTX").plot() show() system.positionSize.get_block_value("EUROSTX").plot() show() system.positionSize.get_instrument_currency_vol("EUROSTX").plot() show() system.positionSize.get_instrument_value_vol("EUROSTX").plot() show() system.positionSize.get_volatility_scalar("EUROSTX").plot() show() system.positionSize.get_subsystem_position("EUROSTX").plot() show() Instrument weights We're not actually trading subsystems; instead we're trading a portfolio of them. So we need to split our capital - for this we need instrument weights. Oh yes, it's another optimisation problem, with the assets in our portfolio being subsystems, one per instrument. import pandas as pd instrument_codes=system.get_instrument_list() pandl_subsystems=[system.accounts.pandl_for_subsystem(code, percentage=True) for code in instrument_codes] pandl=pd.concat(pandl_subsystems, axis=1) pandl.columns=instrument_codes pandl=pandl.cumsum().plot() show() Most of the issues we face are similar to those for forecast weights (except pooling. You don't have to worry about that anymore). But there are a couple more annoying wrinkles we need to consider. Missing in action: dealing with incomplete data As the previous plot illustrates we have a mismatch in available history for different instruments - loads for Eurodollar, Corn, US10; quite a lot for MXP, barely any for Eurostoxx and V2X. This could also be a problem for forecasts, at least in theory, and the code will deal with it in the same way. Remember when testing out of sample I usually recalculate weights annually. Thus on the first day of each new 12 month period I face having one or more of these beasts in my portfolio: - Assets which weren't in my fitting period, and aren't used this year - Assets which weren't in my fitting period, but are used this year - Assets which are in some of my fitting period, and are used this year - Assets which are in all of the fitting period, and are used this year Option 4 is also easy; we use the data in the fitting period to estimate the relevant statistics. Option 2 is relatively easy - we give them an "downweighted average" weight. Let me explain. Let's say we have two assets already, each with 50% weight. If we were to add a further asset we'd allocate it an average weight of 33.3%, and split the rest between the existing assets. In practice I want to penalise new assets; so I only give them half their average weight. In this simple example I'd give the new asset half of 33.3%, or 16.66%. We can turn off this behaviour, which I call cleaning. If we do we'd get zero weights for assets without enough data. instrument_weight_estimate: cleaning: False Option 3 depends on the method we're using. If we're using shrinkage or one period, then as long as there's enough data to exceed minimum periods (default 20 weeks) then we'll have an estimate. If we haven't got enough data, then it will be treated as a missing weight; and we'd use downweighted average weights (if cleaning is on), or give the absent instruments a zero weight (with cleaning off) For bootstrapping we check to see if the minimum period threshold is met on each bootstrap run. If it isn't then we use average weights when cleaning is on. The less data we have, the closer the weight will be to average. This has a nice Bayesian feel about it, don't you think? With cleaning off, less data will mean weights will be closer to zero. This is like an ultra conservative Bayesian. Let's plot them We're now in a position to optimise, and plot the weights: (By the way because of all the code we need to deal properly with missing weights on each run, this is kind of slow. But you shouldn't be refitting your system that often...) system.config.instrument_weight_estimate["method"]="bootstrap" ## speed things up system.config.instrument_weight_estimate["equalise_means"]=False system.config.instrument_weight_estimate["monte_runs"]=200 system.config.instrument_weight_estimate["bootstrap_length"]=104 system.portfolio.get_instrument_weights().plot() show() These weights are a bit different from equal weights, in particular the better performance of US 10 year and Eurodollar is being rewarded somewhat. If you were uncomfortable with this you could turn equalise means on. Instrument diversification multiplier Missing in action, take two Missing instruments also affects estimates of correlations. You know, the correlations we need to estimate the diversification multiplier. So there's cleaning again: instrument_correlation_estimate: cleaning: True I replace missing correlation estimates* with the average correlation, but I don't downweight it. If I downweighted the average correlation the diversification multiplier would be biased upwards - i.e. I'd have too much risk on. Bad thing. I could of course use an upweighted average; but I'm already penalising instruments without enough data by giving them lower weights. * where I need to, i.e. options two and three Let's plot it system.portfolio.get_instrument_diversification_multiplier().plot() show() And finally... We can now work out the notional positions - allowing for subsystem positions, weighted by instrument weight, and multiplied by instrument diversification multiplier. system.portfolio.get_notional_position().plot("EUROSTX") show() End of post No quant post would be complete without an account curve and a Sharpe Ratio. And an equation. Bugger, I forgot to put an equation in.... but you got a Bayesian cartoon - surely that's enough? print(system.accounts.portfolio().stats()) system.accounts.portfolio().cumsum().plot() show() Stats: [[('min', '-0.3685'), ('max', '0.1475'), ('median', '0.0004598'), ('mean', '0.0005741'), ('std', '0.01732'), ('skew', '-1.564'), ('ann_daily_mean', '0.147'), ('ann_daily_std', '0.2771'), ('sharpe', '0.5304'), ('sortino', '0.6241'), ('avg_drawdown', '-0.2445'), ('time_in_drawdown', '0.9626'), ('calmar', '0.2417'), ('avg_return_to_drawdown', '0.6011'), ('avg_loss', '-0.011'), ('avg_gain', '0.01102'), ('gaintolossratio', '1.002'), ('profitfactor', '1.111'), ('hitrate', '0.5258')] This is a better output than the version with fixed weights and diversification multiplier that I've posted before; mainly because a variable multiplier leads to a more stable volatility profile over time, and thus a higher Sharpe Ratio. Rob, again thank you for the article. I am curious, is there a easy way to feed your system directly from Quandl instead of legacyCSV files? Getting data from quandl python api is very easy. The hard thing is to produce the two kinds of data - stitched prices (although quandl do have this) and aligned individual contracts for carry. So the hard bit at least for futures trading is writing the piece that takes raw individual contracts and produces these two things. This is on my list to do... I had a few Q's on above: OPTIMISATION When you optimise to assign weights to rules, what do you do in your OWN system: 1. i) do you optimise the weights for each trading rule based on each instrument individually, so each trading rule has a different weight depending on the instrument, or ii) do you optimise the weights for trading rules based on pooled data across all instruments?? FORECAST SCALARS When we calculate average forecast scalars, what do you personally do: 1. do you calculate the median or arithmetic average? 2. in order to calculate the average, do you personally pool all the instruments, or do you take the average forecast from each instrument individually? Apologies for the caps, could not find any other way to add emphasis. "1. i) do you optimise the weights for each trading rule based on each instrument individually, so each trading rule has a different weight depending on the instrument, or ii) do you optimise the weights for trading rules based on pooled data across all instruments?" Number (ii) but in the presence of different cost levels (code not yet written). ?" No, if you look at the code it is just stacking all the returns from different instruments. This means they are equally weighted, but actually implicitally higher weights are given to instruments with more data history. "FORECAST SCALARS When we calculate average forecast scalars, what do you personally do: 1. do you calculate the median or arithmetic average?" median "2. in order to calculate the average, do you personally pool all the instruments, or do you take the average forecast from each instrument individually?" Pool. Rob Hi Rob, Thanks for your answer above. I am unclear as to i) when in the process the instrument weights are calculated and ii) how these are calculated. Are you able to explain this? The instrument weights are calculated when they're needed; after combining forecasts (chapter 8) and position scaling (chapters 9 and 10). As to how, it's just portfolio optimisation (of whatever specific kind you prefer; though I use bootstrapping on an expanding out of sample window). The assets in the portfolio are the returns of the trading subsystems, one for each instrument. Rob Sorry Rob, I am still trying to wrap my head around this. So to confirm, the instrument weights are determined in a SEPARATE optimisation that is INDEPENDENT from the optimisation of the weights assigned to trading rules? So two separate optimisations? Yes. The forecast weights optimisation has to be done first; then subsequent to that you do one for the instrument weights. (of course it's feasible to do it differently if you like.... but I find it easier to do this way and that's what in the book and the code) OK, this is clear in my mind now. Thank you! Hi Rob, Can you perhaps write a blog post about how the Semi Automated trader could develop scaled forecasts? In the book, the examples of CFD bets (not available to those of us in the US) is very helpful, but what if we like the way in which your signals fluctuate from moderately strong to stronger? The instrument you're trading is irrelevant. It's just a matter of translating your gut feel into a number between -20 (strong sell) and +20 (strong buy). I'm not sure that's something I can blog about. Or have I misunderstood the question? Right, that makes sense. Perhaps i'm just not fully understanding. Based on the walk-through examples in the book for the Semi-automatic trader using CFD's, the signals aren't combined or anything fancy like that. Like you said, its just a matter of translating gut feel into an integer. I just wanted to know if it were possible for the discretionary trader to develop a weighted combined forecast, similar to the staunch systems trader. One of the most attractive features of your system is the fact that the signal generation is done for you on a routine basis. Based on my limited understanding, it seemed like the semi-automatic trader is limited to explicit stop losses and arbitrary binary trading. Oh sure you can combine discretionary forecasts. If you post your email I'll tell you how (not a secret but a bit long for a comment). I moderate posts so I won't publish the one with your email in it. Hi Robert, I've a question about forecast weights. At first, more theoretical... I want to use bootstrapping to determine the forecast weights. I think it's best to calculate separate forecast weights for each element because the cost/instrument can vary substantially per instrument. Also in my opinion it's important to take into account the trading costs for the calculation of the forecast weights, because a fast trading system will generate a lot of trading costs (I work with CFD's) and I think a lower participation in the combined forecast for the faster system will be better. Do you agree with this ideas ? Now more practical... My idea is to calculate a performance curve for each trading rule variation for each instrument and use this performance curves for bootstrapping. Is the following method correct : 1. Daily calculation per instrument en per trading rule variation - calculate scaled forecast - calculate volatility scaler - calculate number of contracts - calculate profitloss (including trading costs) - create accountcurve 2. use bootstrapping method per instrument using all the account curves for all used trading rule variations. The result should be the forecast weights per instrument (subsystem) Is this the correct way ? Thank you Kris Yes definitely use trading costs to calculate weights and if costs vary a lot between instruments then do them seperately. The method you outline is correct. pysystemtrade will of course do all this; set forecast_correlation_estimate["pool_instruments"] to false Hi Robert, Thank you for the confirmation. Kris I was listening to Perry Kaufman podcast on Better System trader, and he said that true volatility adjustment doesn't work for stocks. The argument is that because stock has low leverage and if you trading a stock with low volatility you will need to invest a lot of money to bring that volatility to mach other stock and you may not have enough money to do that. Another option is to reduce to position of the other stocks but then you not using all the money. What he suggested is to dividing equal investment by stock price. I wonder that your thoughts on this? Generally speaking I think volatility adjustment works for any asset that has reasonably predictable / continously adjusting volatility. Theres nothing bad about stocks, except maybe illiquid penny rubbish, that makes them bad for vol sizing. BUT really low volatility is bad in any asset class. I discuss the problems of trading anything with really low volatility in my book. Essentially you should avoid doing it. If you haven't got leverage then as Perry says it will consume too much capital. If you have got leverage then you'll open yourself up to a fat tailed event. It also leads to higher costs. I have two questions: 1.) I may have missed somewhere if you mentioned it, but how do you manage hedging currencies? It seems like your trading in pounds, so for instance how do you hedge contracts denominated in AUD? 2.) What is your margin to equity? This is something I keep hearing about. For instance backtesting a few different strategies and running the margins in CME database shows a margin to equity of about 35% when I am targeting 15% vol. This seems high compared to other managed futures strategies that say about 15% margin to equity and have higher volatility(even while trading more markets than I). Any thoughts would be more than appreciated!! You don't need to hedge futures exposure, just the margin and p&l. My policy is straightforward - to avoid building up excessive balances in any currency. My margin:equity is also around 35%, but on 25% volatility. I agree that your margin sounds rather high. Thank you!! Would you mind providing just a simple example of how the currency hedging works? Also, I'm trading markets similar to yours and I can't see my margin to equity being correct, would you agree? I buy an S&P future@2000. The notional value of the contract is 200x50 = $100K. I need to post $6K margin. I convert say £4K GBP to do this. Scenario a) Suppose that GBPUSD changes such that the rate goes from 1.5 to 2.0. I've lost £1K since my margin is worth only £3K. But I'm not exposed to losses on the full 100K. Scenario b) Suppose the future goes to 2200 with the fx rate unchanged. I've made $50 x 200 points = $10,000. I sweep this back home to GBP leaving just the initial margin. I now have $10K in GBP; i.e. £6,666 plus $6K margin. Scenario c) Suppose the future goes to 2200. I've made $10,000. I don't sweep and GBPUSD goes to 2.0. I've now got the equivalent of £5,000 in profits and £3,000 in margin. I've lost £1,666 plus the losses on my margin as in scenario (a). I agree your margin does sound very high. Ahh I see. Thank you very much, very helpful to me! Your response is greatly appreciated. Thank you for your work and love the book! I hope you don't mind questions! You say you have a 10% buffer around the current position(i.e if the weight at rebalance is 50% and the target is 45%, you keep it at 50% because it is within 10%). However, what if you have a situation where the position changes from, say, +5% to -4%? This is within the 10% buffer but the signs have changed, what do you do with your position? I wouldn't trade. Gotcha. So you'd leave it at 5%? Yes This is an interesting question. What is the reasoning for a 10% buffer(like why not 5% or 15%)?. Two scenarios pop into my head. a.) Lets say you have 10 commodities and each are 9% above their optimal weights. That would leave you 90% more exposed to commodities than your model would call for. Obviously your willing to accept this risk(unless you have some other limits in place). Or say all the 10 commodities have optimal weights of -5% and your current position in all commodities is 4%. You should be -50% short commodities but instead your 40% long commodities. b.) With the 10% buffer there is room for path dependency. Taking the example above, if you establish positions in 10 commodities in January and the signals give them 4% weights each and say commodities dont move around much for, say 3-months, you end up being long 40% commodities for those three months. On the other hand, say you establish positions in February and the signals for all commodities is -5% and don't move around a lot for 3 months. You are now -50% short for a few months(2 overlapping with the January scenario). Certainly you can say well they didn't move much so overall the difference might not be that important. But in real time, say in March, we obviously don't know the next few months will be less volatile we just know we're either 40% long commodities or -50% short commodities. These are just a few thoughts. Obviously you can mitigate some of the problem by setting exposure limits and such. But the path dependency scenario would still be there(especially with larger buffers). Obviously I'm biased towards a smaller buffer. By how much I'm not sure that's why I'd love to get your thoughts on the matter! Or say you have 11 strategies equally weighted trading one market. Presumably each strategy is profitable after some conservative measure of costs without any buffering. If 10 of the strategies show now changes in weights and 1 strategy is now 100% long(9% increase in position) you'd be ignoring that valuable signal. Would love your thoughts! Theoretically the optimal buffer size depends only on costs. Higher costs means a larger buffer. Lower costs means a smaller buffer. I use a constant buffer size purely to make life simpler. Did you estimate the buffer purely on a backtest? eg tried a bunch of different buffers for a give set of costs and settled on 10%? Also I apologize I should have referenced your book first. I wasn't fully aware that you calculate the buffer using actual contracts, not percents as I thought. The example in your book is: the upper buffer is 133.52 * 1.1 = 147 contracts.? Also, in the example I just gave, isnt the impact different for contracts of varying values. So 1 more contract in JGB is $1m vs 1 more contract in TYA being $125k? I find this aspect interesting, greatly appreciate your thoughts. ESHKD "Did you estimate the buffer purely on a backtest? eg tried a bunch of different buffers for a give set of costs and settled on 10%?" In fact there are well known analytical methods for deriving the optimal buffer size (we should always avoid fitting when we can), and 10% is a pretty conservative value which I chose to avoid the complexity of including yet another table in my book (it's what I use in my own system, regardless of cost, so this is a simplification I'm personally fine with). ?" Correct. "Also, in the example I just gave, isnt the impact different for contracts of varying values. So 1 more contract in JGB is $1m vs 1 more contract in TYA being $125k?" Yes, but (a) it's contract risk that is important not notional size, and (b) there clearly isn't anything we can do about this! Gotcha. It still appears more right to me to set the buffer around % allocations(as opposed to contracts). So obviously I'm missing something. I don't want to exhaust you so thank you for your response! Any resources you may have or know of on the subject would be greatly appreciated though!! Hi Rob, If you don't mind me asking, are your log-scale equity curve charts in base 'e' or base 10? Thanks Neither. They are cumulated % curves. So "5" implies I've made 500% return on capital if I hadn't done any compounding. A log curve of compounded returns would look the same but have some different scale. Also, from what I have read, it seems your instrument and rule weights are only updated each time a new instrument enters your system, so you hardcode these weights in your own config; however, these weights do incrementally change each day as you apply a smooth to them. How can one set this up in pysystemtrade? I understand how you hardcode the weights in the config, but how do I apply a smooth to them in pysystemtrade? Or is this done automatically if I included e.g., 'instrument_weight_estimate: ewma_span: 125' in the config? At the moment the code doesn't support this. However I think it makes sense to smooth "fixed" weights as instruments drift in and out, so I'll include it in the next release. Now added to the latest release. Parameter is renamed instrument_weight_ewma_span: 125 (and same for forecasts). Will apply to both fixed and estimated weights. Set to 1 to turn off. Hi Rob, Can you provide some further details on how to use fixed weights (that I have estimated), yet apply a smooth to them? I've been unable to use 'instrument_weight_ewma_span' to filfill this purpose... Thanks! Hi Rob, I’ve not been clear. I understand how EWMA works and the process of smoothing. The problem I am having is that I am using weekly bootstrapping to estimate instrument weights. However, each day when I run pysystemtrade the calculated instrument weights can vary significantly day to day due to the nature of bootstrapping. This leads to situations where e.g., pysystemtrade would have generated a trade yesterday when I was running it (which I would have executed), but when I run it today the instrument weight estimates may have changed enough due to the bootstrapping so that the trade that was generated and executed yesterday does not show up as a trade that was generated yesterday today. This makes me less trusting of the backtested performance, as the majority of trades that were historically generated but excluded after resampling are losing trades. I only sample the market once a day generally (so that repeated sampling of the market overwriting the current day’s mark is not an issue). I would like to use the bootstrapping to estimate the weights ANNUALLY and apply the smooth to adjust between last year’s calculated weight, and today’s. But if I am using fixed weights (after having estimated via bootstrapping) by setting them as fixed in the config, there are no longer two data points to smooth between as I have only one fixed estimate in the config. How can I insert an historical weight for last year and a new fixed weight this year (by fixing it in the config) and smooth between them? "I am using weekly bootstrapping to estimate instrument weights...." I think this is a little... well if I'm being honest I think its insane. Okay so to answer the question for backtesting I use one config, and then for my live trading system I use another config which has fixed weights. Personally I run these seperately for different reasons, the backtest to get an idea of historical performance, the 'as live' backtest with fixed weights to compare against what I'm currently doing and for actual trading. There is no configurable way of mixing these, so you'd need to write some code that takes the estimate bootstrapped weights and then replaces them with fixed weights after a certain date. Thanks for the reply. I had applied the same method for the instrument weights as for the forecast weights. You'd mentioned above: "Also the default is to use weekly returns for optimisation. This has two advantages; firstly it's faster. Secondly correlations of daily returns tend to be unrealistically low (because for example of different market closes when working across instruments)." Why would the default for forecast weights be weekly but not for instrument weights? Thanks! Oh sorry I misunderstood. You are using WEEKLY RETURNS to estimate instrument weights: that's fine. I thought you were actually redoing the bootstrapping every week. Hi Rob, If I wanted to apply a trading rule to one instrument, say ewmac8_32 just to Corn, and another trading rule to another instrument, say ewmac32_128 just to US10, and combine them into a portfolio so that I could get the account statistics, how could I do that? The typical method of creating systems obviously applies each trading rule to each market. I suspect that this would have to be done at the TradingRule stage such that a TradingRule (consisting of the rule, data, and other_args) would be constructed for the 2 cases above. However, I'm having trouble passing the correct "list" of data to the TradingRule object. And, if that is possible, what would need to be passed in for the "data" at the System level i.e. my_system=System([my_rules], data)? I suspect that if all this is possible, it could also be done with a YAML file correct? Thank you so much for any advice and pointing me in the right direction! Easy. The trading rule object should contain all rules you plan to use. If using fixed weights: YAML: forecast_weights: CORN: ewmac8_32: 1.00 US10: ewmac32_128: 1.00 Python: config.forecast_weights=dict(CORN=dict(ewmac8_32=1.0), US10=dict(ewmac32_128=1.0)) If using estimated weights: YAML: rule_variations: CORN: - "ewmac8_32" US10: - "ewmac32_128" Python: config.forecast_weights=dict(CORN=["ewmac8_32"=1.0], US10=["ewmac32_128"=1.0]) (In this trivial example you wouldn't need to estimate, but you could specify multiple rules of different kinds to do so) Thank you, will test this out! Hi Rob, Thank you for an excellent book. I am trying to rewrite some parts of your system in a different language (broker doesn't support python) and add live trading. However I got a bit stuck while I was trying to reproduce the calculations of volatility scalar. For some reason when I request system.positionSize.get_volatility_scalar("CORN") I receive just a series of NaNs, but the subsystem position is somehow calculated. Don't really understand why is that happening Can you please raise this is an issue on github and include all your code so I can reproduce the problem Rob, I guess I solved the problem. The issue was the DEFAULT_DATES was set up to December 2015, while data in legacycsv was up to May 2016. So the fx_rate USD-USD wasn't defined after December 2015 causing all the problems. Thank you for the fast response, I'm still getting familiar with GitHub. fixed in the code Hi Rob, I tried to reproduce forecast weight estimation with pooling, and bootstrap, using this code from matplotlib.pyplot import show, title from systems.provided.futures_chapter15.estimatedsystem import futures_system() The output came out different than your results, Did I have to configure somethings through YAML as well as Python code? It seemed like the code above was enough. Thanks, Maybe you have changed the config, because when I ran the lines you suggested I got the right answer (subtly different perhaps because of randomised bootstrapping, and because I've introduced costs). Try refreshing to the latest version and make sure there are no conflicts. One coding question for the correlation matrix - Chapter 15 example system. With this code, I get 0.89 for E$-US10 correlation, Table 46 in Systematic Trading says 0.35. I understand ST table combines existing numbers for that number, but the difference seems too big. Maybe I did something wrong in the code? I take PNL results for each instrument, and feed it all to CorrelationEstimator. Thanks, Another code snippet, this one is more by the book, goo.gl/txN63u I only left two instruments, EDOLLAR and US10, included two EWMACs and one carry, with equal weights on each instrument. I get 0.87 for correlation. Yes 0.35 is for an average across all asset classes. It's arguable wehter STIR and bonds are different asset classes; which is why I grouped them together in the handcrafted example in chapter 15. Clearly you'd expect the US 10 year rate and Eurodollar futures to be closely correlated. Thanks! Yes I had the feeling hese two instruments were closely correlated, just was not sure if my calculation was off somehow. Great. And since, according to ST, E$ and US10 are from different geographies that is a form of diversification, and the Ch 15 portfolio has positive SR, so we're fine. Dear Rob, where can I find information on how to calculate account curves for trading rule variations from raw forecasts? Do I assume I use my whole trading capital for my cash volatility target to calculate position size and then return, or should i pick certin % volatility target assuming ("guessing") in advanve a certain sharp ratio i'm planing to achieve on my portfolio? Thanks, Peter The code assumes we use some abstract notional capital and volatility target (you can change these defaults). Or if you use weighted curves it will give you the p&l as a proportion of your total capital. Hi Rob, I am getting tangled up in how the weighted curve groups work, specifically accounts.pandl_for_all_trading_rules. Been over the user guide several times and still don't get it, so some questions:- - when I look at accounts.portfolio().to_frame and get the individual instrument component curves, they all sum up nicely to accounts.portfolio().curve() - when I look at accounts.pandl_for_all_trading_rules().to_frame() the individual rule curves look like they are giving a percentage (in the chart 15 config, curve rises from 0 -> 400 ish - I am guessing this is a percentage of notional capital, so I am dividing this by 100 and multiplying by notional - however I cannot get even close to accounts.portfolio.curve() - the shape looks very similar, the numbers differ from the portfolio curve by a suspiciously stable factor of 1.38 - you point out in your user guide that "it will look close to but not exactly like a portfolio account curve because of the non linear effects of combined forecast capping, and position buffering or inertia, and rounding" - however I still cannot get them close even when I configure buffering to 0 and capping to high (1000) - clarifying questions:- - is the output of pandl_for_all_trading_rules().curve() in fact the percentage of notional capital or do I have that wrong? - when you say (user guide, panel_for_trading_rule) "The total account curve will have the same target risk as the entire system. The individual curves within it are for each instrument, weighted by their contribution to risk." what exactly do you mean by contribution to risk? Are we now talking about a percentage of the systems target volatility? (20% or 50K in this configuration) I appreciate any insights you can give here. Can you send me a private mail? Hi Rob, I'm searching for the historical data on the websites you mentioned in the book. I'm looking to the six instruments you also use in this post. On Quandl I can find continuous contracts but this use rollover method at contract expiry and there is no price adjustment. I'm wondering if this is good enough to backtesting because the effective rolling is total different then the (free) data from Quandl. Also with the premium subscription there are a limited methods for rolling. For example : if we roll corn futures in the summer and working only on december contracts, I think this is not possible with quandl (and I think also other data providers like CSIData.com). I'm thinking to write my own rolling methods myself. Is this a good idea and is it necessary to do this (=time consuming). How do you handle this problem ? Kris I wrote my own rollover code. Soon I'll publish it on pysystemtrade. In the meantime you can also get my adjusted data: Thank you so much for the link Rob! Very usefull for me. I can use this data to do my own calculations with my own program (written in VB.NET) What do you do with the gaps: fill it by the previous day values to have a value for each day so all dataseries are in sync ? Or skip the line with the result that the dataseries are not in sync ? If I'm calculating rolldown which is PRICE - CARRY I first work it out for each day, so I'll have occasional Nans. I then forward fill the values, although not too early as I use the value of the forecast to work out standard deviations for scaling purposes, and premature forward filling will reduce the standard deviation. OK, that's also the way I do. Calculate the forecasts on the raw data (so with gaps). Afterwards fill it to bring all instruments in sync so it's much easier to calculate PL. An other question about the legacycsv files from github : when I look for example V2X, I see the latest prices not exactly match with the individual contracts from Quandl. Am I missing something ? For example : file V2X_price.csv at 2016-07-01 : 25,4 file V2X_carrydata.csv at 2016-07-01 : 25,4 and contract expiry is 201608 (this 2 files matches so that's OK and I know you get the values from the august contract) If I go to the Quandl website and take this particular contract () then I see the settlement for 2016-07-01 value 25.7 Also checked this for Corn and this has also a small deviation. I suppose you use backwards panama ? What's the reason for this small deviations ? The data from about 2.5 years ago isn't from quandl, but from interactive brokers. This comment has been removed by the author. Hi, Rob! I'm struggling with forecast correlation estimates used for fdm calculation, could you plz explain what is ew_lookback parameter and how exactly you calculate ewma correlations? E.g. With pooled weekly returns i use first ew_lookback = 250 data points to calculate ewma correlations, then expand my window to 500 data points and calculate correlations on this new set using 500 ewma e.t.c? Why use 250 and not t 52 if use weekly returns? Thank you! These are the defaults: frequency: "W" date_method: "expanding" ew_lookback: 500 An expanding window means all data will be used. Yes the ew_lookback of 500 implies a half life of ~10 years on the exponential weighting. If you think that is too long then of course reduce it. Personally I don't see why correlations should change that much and I'd rather have a longer estimate. So ew_lookback just specifies my decay factor which i then use for all the data points? How do i go about pooling? e.g. I have asset1 with history from 2010 to 2016 (10 trading rules and variations returns) and asset2 from 2008 to 2016 (10 trading rules and variations returns), do i just stack forecast returns to get total of 14 years of data and calculate correlations 10 x 10 on all of the data or what? I'm confused Yes pooled returns are stacked returns df_from_list is the critical function. Hello, after looking through the python code, I wonder how you came up with the adj_factor for costs when estimating forecast weights? via simulation? THANKS! Please tell me which file you are looking at and the line number please. syscore/optimisation line 322 # factors .First element of tuple is SR difference, second is adjustment adj_factors = ([-.5, -.4, -.3, -25, -.2, -.15, -.1, -0.05, 0.0, .05, .1, .15, .2, .25, .3, .4, .5], [.32, .42, .55, .6, .66, .77, .85, .94, 1.0, 1.11, 1.19, 1.3, 1.37, 1.48, 1.56, 1.72, 1.83]) def apply_cost_weighting(raw_weight_df, ann_SR_costs): """ Apply cost weighting to the raw optimisation results """ # Work out average costs, in annualised sharpe ratio terms # In sample for vol estimation, but shouldn't matter much since target vol # should be the same avg_cost = np.mean(ann_SR_costs) relative_SR_costs = [cost - avg_cost for cost in ann_SR_costs] # Find adjustment factors weight_adj = list( np.interp( relative_SR_costs, adj_factors[0], adj_factors[1])) weight_adj = np.array([list(weight_adj)] * len(raw_weight_df.index)) weight_adj = pd.DataFrame( weight_adj, index=raw_weight_df.index, columns=raw_weight_df.columns) return raw_weight_df * weight_adj Chapter 4 of my book. Hello Rob, Would you consider making the ewma_span period for smoothing your forecast weights a variable instead of fixed value, perhaps by some additional logic to detect different volatility 'regimes' that are seen in the market? Or maybe such a notion is fair, but this is the wrong place to apply it, and should be applied at the individual instrument level or in strategy scripts? No this smacks of overfitting. Put such evil thoughts out of your head. The point of the smooth is to reduce turnover on the first of january each year, not to make money. (goes to the blackboard to write "I will not overfit" 50 times)...sorry, I've read your statements on overfitting more than once, but had a lapse in memory when this question popped into my thick skull. Thanks for your response. Hi Robert, For the diversification multiplier you mention to use exponential weighting. Where or how you implement this? On the returns or on the deviations of the returns from the expected returns (so just before the calculation of the covariances)? Or maybe at an other place ? Can you give me some direction? Thanks Kris No, on the actual multiplier. It's calculated from correlations, updated annually. Without a smooth it would be jumpy on the 1st January each year. OK,but in this article I found 2 different parameters refering to exponantional weighting : - under 'Forecast Diversification Multiplier' --> 'correlation' : I found "using_exponent: True # use an exponentially weighted correlation, or all the values equally" - under 'Forecast Diversification Multiplier' --> 'Smoothing again' : I found "ewma_span: 125 ## smooth to apply" I am a little bit confused about the 2 parameters. I understand that the second parameter (smoothing again) is to smooth the jump on the 1st January each year. But what about the first parameter (correlation) ? I thought that you use some kind of exponantial weighting for calculating the correlations, but maybe I'm wrong ? Sorry, but it is not so clear for me. Kris Sorry, yes I use exponential weighting a lot. With respect to the first, yes I calculate correlations using an exponential estimator: Thanks for this tip! I always try to write my own code (don't like dependency of others code) and also I don't see how I can use the pandas libraries into vb.net. But I've found the functions here : --> EWMCOV and here : --> corr So I can analyse how they to the stuff and can write it in VB.NET Kris I see that the ewm.corr-function return a list of correlations for each date and not a correlation matrix. For the classic corr-function the result a matrix of correlation coëfficients. In your code () I see you only takes the latest value for each year of the ewm.corr function. I should expect that we must take a kind of average of all correlation values from a pair to calculate the correlation coëfficient for each pair. Can you clarify this, thanks. Kris ewm.corr returns rolling correlations; each element in the list is already an exponentially weighted average of correlations. Since I'm doing the rolling through time process myself I only need the last of these elements. OK, but in your simulations you work with an expanding window and do calculations yearly based on weekly data. If we use EWM-span of 125 it means the rolling correlations go back roughly about 3 years (125*5 days). So if for example the total period is from 1990-2016, is the last element of last calculation (1990-2016) then a correct estimate of the correlation of the whole period, because data before 2012 is 'ignored' ? Maybe it's then faster to work with a rolling out-of-sample frame to do this calculations ? Or is my idea on this not correct ? Kris Well 92% of the weight on the correlations will be coming from the last 3 years. So yes you could speed this up by using a rolling out of sample although the results will be slightly different. 5 years would be better as this gets you up to 99%. Rob, in your legacy.csv modules, some specific futures have the "price contract" as the "front month"(closest contract) like Bund, US20 & US10, etc. meanwhile, others such as Wheat, , gas, crude, etc have the "carry contract" as the front month. is this by design? Yes. You should use a nearer month for carry if you can, and trade further out, but this isn't possible in bonds, equities or FX. See appendix B. Hi Rob, Thank you so much for your book. It it very educative. I was trying to understand more about trading rules correlations in "Chapter 8: Combined Forecasts". You mentioned that back-testing the performance of trading rules to get correlation. Could you share a bit more insights on how you get the performance of trading rules, please? (1) Do you set buy/sell threshold at +/- 10? meaning that no position held when signal is [-10,10], only 1 position held when signal is [10,20] and [-20,-10] and 2 positions held when signal is at -20/+20? (2) Trading cost is considered? (I think the answer is yes.) (3) You entry a buy trade, say at signal=10. When do you signal to exit the trade? when signal<10 or signal=0? or you use dynamic positions, meaning the position varies with signal all the time. Another question regarding optimisation: In the formula: f*w - lemada*w*sigma*w' to estimate weights (1) f is rules' sharpe ratio calculated using the rules' historical performance pooled from all instruments or just the sharpe of the rule from the instrument we look at? (2) how do you define lemada? =0.0001? if so, is it always 0.0001? Sorry if those two questions had been asked before. Thanks, Deano To get the performance of a trading rule you run through the position sizing method in the book allocating 100% to a given trading rule. 1) No, that isn't how the system works at all. Read the rest of the book before asking any more questions. 2) yes - again this in discussed later in the book 3) No, I use continous positions. You need to read chapter 7 again as you don't seem to have quite got the gist. f*w - lemada*w*sigma*w I don't think I've ever used this formula in my book, or on my blog, so I can't really explain it. Rob, Is one way to estimate correlations with nonsynchronous trading to run correlations on rolling 3-day returns over a lookback of 60-days?(which I know is much shorter than yours) If you're using daily closing prices to calculate returns across different markets then nonsynchrous is clearly an issue. BUT NEVER, EVER, EVERY USE ROLLING RETURNS!!!!! They will result in your volatility estimate being understated. Instead use non overlapping 3 day returns eg P_3 - P_0, P_6 - P_3, P_9 - P_6 where P_t is the price on day t. As for wether 3 days is enough, well even 2 days would help a bit with nonsynchrous data, although 3 days is better, and 5 days (which is what I use, eg weekly returns if you're in business day space) is better still. On a system trading at the kind of speed I trade at using 60 days worth of correlations probably is too short a period, since it isn't long enough to give you a stable estimate. It's also only 20 observations if you're using 3 day non overlapping returns (it's even worse for weekly returns of course, only 12 observations). Your estimate will be very noisy. Thank you! The idea actually came from the Betting Against Beta paper by the guys at AQR. They say they use overlapping(or rolling) 3-day log returns to calculate correlations to control for non-synchronous trading over 120 trading days. I think it is safe to say your disagreeing with their approach? The guys at AQR know what they are doing and almost without exception are smarter than me. So it would be surprising if they'd done something crazy. Using overlapping returns is generally frowned upon (eg in OLS regression, essentially this is a bias versus variance problem). Using overlapping returns artifically increases the data you have (you only really have completely new observations every 3 days) and that benefit must come at a cost. For correlations it *might* be okay; I rarely work overlapping returns so I don't know their properties well enough to say whether they are fine or not. My intuition and a few minutes of playing with excel suggests they will be fine with zero autocorrelation, but maybe not if autocorrelation comes in. But I don't see the point in using two types of returns - one to calculate vol, one to calculate correlation (in most software you work out a single covariance matrix which embodies both things). Yes, I agree. That was also my initial intuition as well. I compared the weekly non-overlapping approach with the overlapping 3-day approach over the same time-frame and the markets that are synchronous the correlation estimates are very similar. More importantly, for example when I ran it on the Hang Seng the rolling 3-day approach was quite close to the weekly approach. So obviously some slight differences but, as you say, the approach doesn't seem like something crazy. Your response is much appreciated. Hi Rob, what is your view on using returns (weekly in your case) to compute correlations vs log returns (as per this AQR paper). Why do you suppose some choose log returns, do you view any significant difference between the two? I found this on the topic, but still not seeing the fundamental reason to use one vs the other. Appreciate your thoughts as always. To be honest I haven't given this much thought. I can see why it will affect the calculation of volatility, but it's not obvious to me how it affects correlation. Good morning, Rob. When I run your ch_15 system along with default configs, trading rules, etc. unmodified, the stages run fine. If I substitute the legacyCSV files of several instruments with *intraday* 1-minute bars in the same 2-column format, both for the '_price' file and '_carrydata' (expiration months spaced from current date like you showed in legacy versions), spanning 5 days each, and re-running the system but changing nothing except reduction of the instrument_list entries, I get the error from line 530 (get_notional_position) of /systems/portfolio.py "No rules are cheap enough for CRUDE_W with threshold of 1.300 SR units! Raise threshold (...), add rules, or drop instrument." I raised it from the original 0.13 to 1.3, and in other tests as high as 100 (ridiculous value of course, just testing...), same result. Seems I'm overlooking a simple principle of the system, but I can't figure why, given the trading rules were left same. Can you offer a pointer? The answer to your question(s) is that I have not tested the system with non daily data so there is no guarantee it will work. I am pretty sure there are several places where I assume the data is daily (and you have unearthed one of them); some data is always resampled daily whilst others are not, so there could be some issues with mismatching and what. In summary I would need to do a lot of testing before I was confident the code would work with non daily data, so I really wouldn't trust it for those purposes yet. Also, since many of the instruments in the legacy data have a lot of days near the final years of the records with more than one recorded value per day, it seems that using new CSVs with intraday data would be feasible in short order, but making sure to change the period of several calculations in other stages to recognize the periodicity on a minute scale, instead of days, no? Sorry in advance for my hasty monologue... P.S. for example, does the diversification multiplier need to be modified for interpreting 1-minute periods instead of sampling at end-of-day? What about volatility scaling floors currently set with daily period? Just briefly looking at the intra-day posts in this thread, I can say I spent a considerable amount of time last year making the program intra-day compatible (I was using tradestation data). It's been some time since I looked at this project, but I can refer you to where I left off (I believe it works, but I haven't had anybody review my work): Hope this helps Thank you, Gainz! I see that you have an additional folder in 'sysdata' and the 'price' CSVs are 15-minute entries. Can you comment on the adaptation scheme in the stages of the workflow? For example, looking at the /systems/rawdata.py script, only daily prices are mentioned. Did you go that far with changing the code to recognizing intraday, but left the names as 'daily', or is the actual adaptation still needed? Dear Mr. Carver, Most of all I always appreciate you for sharing detailed & practical knowledge of quantitative trading. I have a few questions while reading your book & blog posts. I am trying to develop a trend following trading system with ETFs using the framework in your book. The trading system is long-only and constrained by leverage limit(100%). Under the constraints, what is the best way to use your framework properly? Is there any changes in calculating forecast scalars, forecast weights, FDM, IDM, etc? My thought is... Solution 1. - Maintain all the procedures in your framework as if I could long/short and have no leverage limit. (Suppose that I have 15% target vol) - When I calculate positions for trading, I just assign zero position for negative forecasts. And if sum of long positions exceeds my capital I scale down the positions so that the portfolio could not be leveraged. Solution 2. - Forecast scalar: No change. I calculate forecasts and scale them(-20 ~ + 20). - Forecast weights, Correlation: For each trading rules, + Calculate portfolio returns of pooled instruments according to the forecasts. + Returns for negative forecasts replace to zeros. (Zero position instead of short) + And I scale down the returns for positive forecasts when sum of long positions exceeds my capital. + Returns of trading rules are used when bootstrapping or calculating correlations. + Forecast weights are optimized using these returns. - FDM: + Calculate FDM based on forecast weights and correlations among the forecasts as your framework. + Calculate the historical participations(= sum(long position)/myCapital) using new rescaled forecasts and forecast weights. + Check the Median(participations) for back-tested period. + If it exceeds 100% I scaled down FDM in order to get my portfolio not take too much risk. Frankly speaking I don't know what the right ways are. Both ways does not seem proper. Maybe it is because of my lack of understading. Would you give any advice? I am really looking forward to your 2nd book. Thanks for reading. Best regards, Michael Kim Solution 1 is correct. Chapter 14 actually discusses exactly this problem so it might be worth (re) reading it. I have read chapter 14 again and it was helpful. I should have checked the book before I asked. Thanks for reply. This comment has been removed by a blog administrator. Hi Rob, I have a question with regard to setting up data prior to optimising weights using bootstrapping. If we follow your advice, forecast returns are already standardised across instruments through dividing by say 36-day EWMA vol. However, I understand from the above example, it makes sense also to equalise vols and means. I assume the vol_equaliser fn does this by rescaling the time series of returns so that all the forecast distributions are virtually the same over the entire series (i.e. have identical Sharpes). The weights you derive would presumably be that of a min variance portfolio and therefore relies on a solution based entirely on the correlations between the returns. Is the above correct? I assume you recommend the same procedure for bootstrapping subsystem weights (i.e. equalise means and vol). Now when using pooled data for forecasts, my thinking is fuzzier: is it advisable not to equalise means or vol? You're correct that the solution relies entirely on correlations in this case (in fact it's the optimal Sharpe, maximum return and the minimum variance solution). "Now when using pooled data for forecasts, my thinking is fuzzier: is it advisable not to equalise means or vol?" No, you should still equalise them. Basically the logic in all cases is this. Vol targeting equalises expected vol, but not realised vol which will still be different. If realised vol goes into the optimiser then it will have an effect on the weights, which we don't. Hi Rob thanks for this. Just so I can get my head around your answer a bit better, a question on terminology: are 'estimated' vol and 'realised' vol the same thing and equal to the vol used for standardisation (i.e. rolling historic 36d EWM vol)? As I understand it the two inputs into the the optimisation you do are correlation and mean returns. So are you saying that if we relied merely on vol standardisation (using recent realised vol) then a period of high vol for an instrument with a short data history but high forecasts would lower the forecasts and their corresponding weights? I am failing to make the connection between high forecasts and high price vol which is used for standardisation. I am sorry if I have completely missed the point. On a related point, and I should have asked this earlier: on page 289 of your book you recommend that prior to optimisation we should ensure 'returns have been vol normalised' I assume this is the same as 'equalisation' that you refer to in this post and not the same as standardisation (btw the term volatility normalised is in bold so perhaps your publishers might consider putting a reference in the glossary for future editions before your book becomes compulsory reading for our grandkids). There is rolling historical 36d EWMA vol used for position sizing. Realised vol is what actually happens in the future. When doing optimisation we use a different estimated vol - the vol of returns over a given period (the entire backtest if using an expanding window). The vol used for vol standardisation is the estimated vol of the p&l of the instrument subsystem returns. If all forecasts were identical, and we could predict vol perfectly, then this would automatically be the same for all instruments (because when we scale positions for instrument subsystems we target the same volatility per unit forecast). The fact that estimated vol isn't a perfect forecast adds some randomness to this; a randomness that will be problematic for very short data histories. More problematic again is that for instruments with short histories they will have different forecasts. An instrument with an average forecast of 10 over a year compared to another with an average of 5 will have twice the estimated volatility over that backtest period. But that is an artifact of the different forecast level - it doesn't mean we should actively downweight the higher forecast instrument. I agree I could have been stricter with the terminology I use about equalisation, normalisation and standardisation. There. Hi Rob, it's possible I worded my original question poorly, I will try to be more systematic, so please bear with me. To recap on my understanding: 1.'vol normalisation' is what you do when standardising forecasts. This is typically done by dividing by rolling 36 day EWMA * current price 2. 'vol standardisation' is what you do when standardising subsystems. I would again use rolling 36 day EWM vol (times block value, etc) for this 3. 'vol equalisation' is what you do prior to optimisation to scale the returns over the entire (expanding) window so over this window they have the same volatility 4. Assuming the above is correct, a subsystem position for carry and EWMAC variation is proportional to exp return/vol^2 (which co-incidentally seems to be proportional to optimal kelly scale - although not for the breakout rule). 5. When I said originally 'Now when using pooled data for forecasts, my thinking is fuzzier: is it advisable not to equalise means or vol?', to be clearer I was trying to ask whether it makes sense to equalise vols prior to optimising forecast weights when pooling (not whether to equalise vols when optimising subsystem weights, if we had pooled forecasts previously). In a previous post ('a little demonstration of portfolio optmisation') you do an asset vol 'normalisation' which I believe is the same as 'equalisation' discussed here (scale the whole window, although not done on an expanding window) but I got the impression for forecasts that the normalisation is handled as above and this took care of the need for further equalisation (for forecasts at least). I must admit, I had always thought that if you want to use only correlations and means to optimise then intuitively you should equalise vols in the window being sampled (because to quote you this reduces the covar matrix to a correlation matrix). However I had somehow accepted the fact that normalising forecasts by recent vol ended up doing something similar (also from reading some comments by you about not strictly needing to equalise vols for forecasts, etc). But I guess a different issue arises when pooling short histories? In summary, assuming you deciphered my original question correctly, are you saying it is still important to equalise vols of forecast as the 'realised' variance of forecast returns are proportional to the the level of the forecast (so a forecast of 10 would have twice the variance of a forecast of 5), causing the optimiser to downweight elevated forecasts, which is a problem when pooling short data histories? By equalising vols over the entire window being used for optimisation, we end up removing this effect? If that is what you are saying then I promise to go away and think about this much more deeply. Thanks again for taking the time. OK I think get it. Really had to have a think and run some simulations but as far as I can tell there seem to be two effects in play here. The arithmetic returns from applying a rule on an instrument is the product of two rvs: instrument returns and forecasts. Assuming independence between these rvs, the variance can be shown to be function of their first two moments. Over sufficiently long periods, these moments across different instruments are equal (asymptotically converge). However over shorter periods there may be divergence (i.e. different averages, different vols) which will violate the assumption of equal vols required to be able to run the optimiser using correlations only. As far as I can tell there also is a more subtle effect, and that arises from the fact that forecasts and instrument returns are not independent (EWMAC 2,8 and daily returns when using random gaussian data have a correlation of 45%). This inconveniently introduces covariance terms in the calc for vol. However, in the cross section of a single rule applied across different instruments over sufficiently long periods of time, the covar terms should have an equal effect across all instruments. Again over short periods there may be divergence. This divergence in small samples from the assumed distribution of the population is presumably why it is sensible to equalise vols before optimising. Am I on the right track? BTW please feel free to delete my earlier comment. You've got it. Couple of interesting points from what you've said though: - the fact that a forecast for carry comes out as mu/sigma is a nice property, but in general we only require that raw forecasts are PROPORTIONAL to mu/sigma. So some further correcting factor may be necessary (the forecast scalar) - in terms of multiple rules; obviously if weights added up to 1 and rules were 100% correlated you'd end up with a joint forecast with exactly the same properties as the individual forecasts. In theory the forecast diversification multiplier deals with this problem; with the caveat that it's backward looking and based on historic correlations so it only works in expectation. Many thanks Rob. The more I dig into your system, the more I appreciate the serious thought which has gone into engineering it. A couple of follow-up observations. From my comparatively low vantage point, I also see that from a practical point of view certain simplifications are desirable (at very little cost to robustness). Would you say that is the case with the FDM? Strictly, if it made a big difference, should we be adjusting for reduced portfolio volatility of forecast returns rather than forecasts themselves? Also, wrt FDMs would you pool all instrument data whether or not they share the same rule variations after costs? Patrick. Essentially the question is what is the difference between the correlation of forecast RETURNS rather than forecast VALUES. If returns are more correlated than values, the FDM will be too high (producing a trading rule forecast that has too much volatility). And vice versa. In fact the answer isn't obvious and depends very much on the properties of the signal and the underlying market. At the end of the day I think it's more intuitive to state the FDM in terms that it's ensuring the final combined forecast VALUE has the correct scaling properties. FDM would have to be way off for me to drop this point of view. And it usually is pretty close - in fact any effect is dominated by the problem that volatility and correlations aren't stable enough, which means that trying to hit a volatility target is an imprecise science at best. "Would I pool all instrument data if they didn't share the same rule variations" - ideally yes, but it's very complicated to do this - essentially the problem being to average a series of correlation matrices with some overlapping and non overlapping elements, and produce a well defined matrix at the end. There are techniques to do this, but it strikes me as overkill to bother... Hi Rob, Do you have the breakdown of subsystem signals for the Eurostoxx? You never get short in 2015, only less long? It looks like the market heads down quite a bit. Is this because of the carry signal dwarfing the trend signal? Optically, I can't line up the forecast weights with the chart. Thanks! from systems.provided.futures_chapter15.basesystem import futures_system from matplotlib.pyplot import show system = futures_system(log_level="on") a=system.combForecast.get_all_forecasts("EUROSTX") b=system.combForecast.get_forecast_weights("EUROSTX") c=a*b c.plot() Understood. And thank you again, Rob.
https://qoppac.blogspot.com/2016/01/correlations-weights-multipliers.html
CC-MAIN-2018-09
refinedweb
12,461
63.7
Agenda -> Accepted -> Accepted. Norm: Skip it, we'll take it to email Alex gives regrets Norm: Any comments on my draft of two weeks ago? Mohamed: I made some small comments that don't seem to be addressed. Norm: I thought I did them all, but I'll investigate. Alex: I'm looking at p:file ... p:file is an awful name Norm: Yeah. Ok, what's better? Alex: I think p:resource is better Norm: Ok. Alex: If you point to a resource and it returns an XML media type. ... Does it get escaped? Norm: Yes, it does. But maybe that should be made more clear. Mohamed: How about p:unparsed-text? Alex: But binaries do get parsed Mohamed: How about p:data? Norm: Anyone who can't live with data? ... Ok, let's float that one for the next draft and see what happens. Mohamed: You didn't put the content-type attribute in the examples Norm: Oops. Alex: We also need to change the name of the wrapper. ... If we return a default, then it's content-type without a namespace. If it's in your namespace then we can put content-type in the c: namespace Norm: I'm happy with that. <scribe> ACTION: Norm to change p:/c:file to p:/c:data and make the content-type attribute appear in the c: namespace if a non-c:* wrapper is used. Norm: Let's not. Alex: Not in V1 works for me. Mohamed: Me too. Vojtech: I agree. Norm: I propose to take it out of the next draft. Alex: What are we losing? Norm: You won't be able to write XPath expressions in your pipeline that refer to schema datatypes other than the builtin/predefined ones. ... You won't be able to refer to "x:hatsize". Alex: I don't think it will hurt us to wait until V.next ... If we do it now, we could paint ourselves into a corner. <scribe> ACTION: Norm to remove p:schema-import. Norm expresses his misgivings. Alex: Nope, I don't think it's unreasonable to expect implementors to be able to change the dynamic context. Norm: Ok, I'm content. Alex: But shouldn't they be consistent? Mohamed: I think for label-elements we used $p:index instead of position() because we didn't need last() at all. ... For split-sequence, we do need last sometimes. Norm: Right, so we'd need $p:last. Mohamed: I think the way it is is consistent. Norm: I don't hear any motivation to make this change. <scribe> ACTION: Norm to clarify that position() and last() are expected to work in p:split-sequence Norm: I think the current situation is a bit odd, shouldn't we make it an error to specify both a prefix and a namespace? Alex: yes Mohamed: Can we give an exception if the namespace binding for the prefix is the same as the URI? Norm: I'm ok with that. Mohamed: I thought the point of using a prefix and a URI was to *request* that binding. Scribe struggles to keep track of the thread Vojtech: If you're reading parameters from a file, then you might use QNames, but if you're generating them then you can use the namespace attribute and use NCNames in names. Mohamed: The attribute namespace appears only on c:param. Norm: Right. So this is only about c:param. Mohamed: So I thought that this was for establishing that binding. Norm: I don't think the prefix is *ever* relevant on parameter names, they're only used by the implementation. Alex: The bug is the namespace consistency problem; the answer is just to say they have to match. Norm: We're running out of time, is anyone uncomfortable with adopting at least a temporary resolution that says they have to be consistent. Accepted. Mohamed: Could Vojtech provide an example where it's troubling to not use @namespace. Vojtech: If you want to generate a c:param in XProc, then you'd have to be able to create an xmlns: declaration. Mohamed: Could you send it in email? Vojtech: Sure. Face to face? Norm: We're planning to meet at the technical plenary ... Who's going? Mohamed: I'm going. Alex: I'll try to. Norm: I'm going. ... With luck, we'll be able to go to Last Call next week. <scribe> ACTION: Norm to send mail to the WG about the plenary (including dates of our meeting) No other business heard
http://www.w3.org/XML/XProc/2008/07/31-minutes.html
CC-MAIN-2016-18
refinedweb
757
85.59
Red Hat Bugzilla – Bug 643227 CVE-2011-0002 libuser creates LDAP users with a default password Last modified: 2015-07-31 08:25:18 EDT +++ This bug was initially created as a clone of Bug #643022 +++ <snip> Also when I do not specify the password when creating the user (with -p), some kind of "default" string appears in password: # luseradd tst ldap search listing (see the user pass): # tst, omoris, free, gold.testday dn: uid=tst,ou=omoris,ou=free,dc=gold,dc=testday uidNumber: 503 uid: tst shadowMin: 0 shadowMax: 99999 shadowWarning: 7 shadowExpire: -1 homeDirectory: /home/tst loginShell: /bin/bash shadowInactive: -1 userPassword:: ISE= [snip] --- Additional comment from mitr@redhat.com on 2010-10-14 11:58:39 EDT --- <snip> The "userPassword:: ISE=" value decodes to '!!', which should [not] let the user to log in, per RFC 2307. The comment above is correct WRT RFC 2307 - i.e. using only nss_ldap and using NSS to read the shadow entry and authenticate against it: in that case the RFC 2307 prohibition of unprefixed values means the shadow password returned is always "*". This is, unfortunately, not general enough - when using pam_ldap on a client (or when connecting to the LDAP server using the LDAP protocol, and perhaps in other cases), the generic definition of "userPassword" (RFC 4519) applies, and the "!!" values is considered a plaintext password that can be used to succesfully log in, at least when the server is openldap (I haven't checked against 389). Impact: (luseradd) without specifying a password creates an user account that can, under some circumstances, be used to log in using a default password. In usual cases, the password would be set either in the initial luseradd invocation, or in a following lpasswd invocation, leaving at most a short window when the "!!" value can be used. It is possible, however, to enter "system" accounts into LDAP for which the password is never set; in such cases the default password could persist for indefinite time. This would argue for a rather high vulnerability severity rating. AFAICS the bug has been in libuser for a very long time, since RHEL 3 at least. I have Cc:ed LDAP server maintainers to this bug - could you please verify my understanding of the situation? Adding Nalin as the pam_ldap maintainer as he might have some good ideas about where the fault lies. pam_ldap is not at fault. There are three basic ways to authenticate an user defined in LDAP: - Load the encrypted password from the LDAP server to the client, verify password locally. This is what nss_ldap without pam_ldap does, an it seems to be fine. - Try to authenticate to the LDAP server using the provided password. This is what pam_ldap does (by definition), and "!!" may work. This depends on server capabilities and configuration, but we already know that at least openssl can treat the password as unencrypted. Note that pam_ldap can not filter out "!!" - it really may be a legitimate password. All policy is in the LDAP server in this scenario. - Use an independent authentication mechanism, e.g. Kerberos. In this case the userPassword value is irrelevant. I wasn't able to figure out from sssd-ldap(5) what pam_sss uses. Usually, Kerberos is preferred to pam_ldap with TLS, which is preferred to nss_ldap without pam_ldap. But any of these configurations is "valid" and may be used by our users in production setups. Also note that regardless of the authentication mechanism used to log in users to client computers, "!!" may remain a valid password for the user to log in to the LDAP server directly. The server administrator needs to set up ACLs to restrict what users can change, regardless of the libuser problem - but there are some unauthorized access scenarios, for example an attacker might connect to the LDAP server using the "!!" password and change the user's password to something else. AFAICS the only place where this can be fixed is libuser. Changing userdefaults/lU_USERPASSWORD to "{crypt}!!" is an acceptable workaround if the "ldap" module is used - otherwise this value is not defined, although it would work in practice. A correct fix would be to use the "{crypt}!!" value internally in the LDAP module. There is a theoretical case where libuser is used to create the user record both locally and in LDAP - in that case there is no 100% correct solution in the libuser model because it cannot use a different value for different modules. Please disregard lpasswd - it is attempting to authenticate using the local PAM configuration as the target user; this does not make much sense, but it is also not really relevant to the primary issue. (In reply to comment #4) > Adding Nalin as the pam_ldap maintainer as he might have some good ideas about > where the fault lies. The pam_ldap password check is done by attempting an LDAP bind, so the comparison with the user-supplied value is performed at the server. The check for '!!' is done in pam_unix during the auth phase, so other modules aren't going to heed it. If the server supports checking {CRYPT} passwords, then I agree that always using {CRYPT} is the best route. I'm just not certain that all servers do support it. If we can just omit a default 'userPassword' value without breaking anything, that might be an alternative. If we have libuser set _no_ password by default, what will happen? Will that allow a LDAP-based user to authenticate without a password? What about a local user? If libuser is using shadow/passwd, and we set the default to {crypt}!!, will the local system treat that the same as !! and prevent logins? (In reply to comment #10) > If we have libuser set _no_ password by default, what will happen? OpenLDAP disallows unauthenticated binds by default. Therefore pam_ldap should fail. ldap_bind: Server is unwilling to perform (53) additional info: unauthenticated bind (DN with no password) disallowed But it can be enabled with 'olcAllows: bind_anon_dn' in cn=config. If somebody needs this configuration, {crypt}!! as a default password will be safe way. Setting no userPassword attribute seems to be the cleanest LDAP solution, and reading the code, the rest of the system would probably handle it fine (nss_ldap uses "*" if userPassword is not present, nss_sss uses "*" regardless of userPassword value). Internally in libuser, I'm rather worried that removing the default value could break applications - dereferencing an unexpected NULL value. As for LDAP servers that do not support {crypt}, libuser uses {crypt} everywhere, so if using libuser makes any sense at all, {crypt} is supported. The case of libuser modifying both LDAP and passwd/shadow at once is a semantic mess... if the value of pw_passwd from /etc/passwd and userPassword from LDAP are different (as they almost always are), the LU_USERPASSWORD value returned by libuser is always wrong. This is the mirror image of our problem, that there is no single correct default value of the LU_USERPASSWORD attribute. In addition to the above-discussed "!!" value, the shadow module can set userPassword to "x". The value actually set by libuser depends on module ordering in libuser.conf. In general, libuser is at various internal stages of user creation (user_default, user_add) not able to distinguish between "!!"/"x" specified by the user (intended to be a raw userPassword value) and "!!"/"x" set up by default (intended to be a crypt(2) hash matching no input). Considering that both "!!" and "x" are rather ridiculous values for a plaintext password, I think it would make most sense to do an ugly hack inside the LDAP module, and replace both "!!" and "x" by "{crypt}!!", _only_ when _adding_ an user. Any other value would be passed through unchanged: - The default value of LDAP userPassword would not allow logins - Applications that use libuser and set an explicit, LDAP-formatted, userPassword value would continue to work (except for unencrypted "x" and "!!") - All LDAP-formatted userPassword modifications done using the libuser "*_modify" operation would continue to work unchanged - libuser password change operations (*_setpass *) would continue to work. (This - i.e. lu_user_add() + lu_user_setpass() - is the recommended method, and is used by luseradd(8).) In particular, this would continue to work even in the combined LDAP + /etc/passwd + /etc/shadow scenario. - The "{crypt}!!" value won't appear in /etc/passwd and /etc/shadow (and in particular, /etc/passwd will contain the correct "x" marker for shadow passwords). What do you all think? This sounds like it would work and solve the problem, yes. At this point I suspect we will be calling this a security vulnerability and will need to assign a CVE name to it. Is the fix for this going to be fairly intrusive, or something we can easily backport? We'll need to fix libuser across the board for this. I do think this is a fairly low impact issue as it requires using LDAP with libuser and creating a user without an initial password provided. A preliminary CVSSv2 score for this would be 2.6/AV:L/AC:H/Au:N/C:P/I:P/A:N (based on the creation of the account with '!!' as the password as opposed to being able to log into an account with that password set since the vulnerability is in the creation of such accounts). As such, I think we could safely defer this for some older products, but it might be wise to get this fix into Fedora and RHEL6 where new installations would lead to more creation of user accounts than older/more-established installations where adding new users would not be as common an occurrence. Thoughts? For the record, since I don't think it was answered clearly above: When 'ldap' is selected as the authentication provider in SSSD, it performs an LDAP bind the same way that pam_ldap.so does. Therefore, if the server would validate that as an acceptable password, SSSD would too.? (In reply to comment #17) > ? It could be. Was SSSD configured to use Kerberos for authentication, or LDAP? If it was configured for Kerberos, and that user didn't exist on the KDC, then that might explain it. Though it should still be returning denied rather than error. This is now public via 0.57 release: Created libuser tracking bugs for this issue Affects: fedora-all [bug 668534] A script similar to the following could be used to see if any passwords do not start with {CRYPT} and would need to be updated/changed: #!/usr/bin/python import ldap l = ldap.initialize("ldap://server") #l.simple_bind_s("cn=Manager,dc=server", "password") results = l.search_s("dc=server", ldap.SCOPE_SUBTREE, "(userPassword=*)", ["userPassword"]) for dn, attributes in results: if not attributes["userPassword"][0].startswith("{CRYPT}"): print dn #l.unbind_s() (In reply to comment #42) > l = ldap.initialize("ldap://server") > #l.simple_bind_s("cn=Manager,dc=server", "password") Just to clarify, it's not uncommon to restrict access to userPassword attribute, so the connection is likely to need to bind using a sufficiently privileged user account. Directory Manager account is such example. Details depend on the ACL settings of each LDAP instance. > if not attributes["userPassword"][0].startswith("{CRYPT}"): > print dn This should also report accounts with userPassword using different hash. {SSHA} is commonly used and default for RHDS, for example. Depending on the goal, this can be modified to search for all accounts with plain text passwords, or only compare to the default password '!!' created by libuser. This issue has been addressed in following products: Red Hat Enterprise Linux 6 Red Hat Enterprise Linux 5 Red Hat Enterprise Linux 4 Via RHSA-2011:0170
https://bugzilla.redhat.com/show_bug.cgi?id=643227
CC-MAIN-2017-17
refinedweb
1,927
55.34
I have an (a subclass to) AbstractTableModel which contains an ArrayList of type Item (a home-made class) and some basic methods such as add, remove,getColumnCount, getRowCount and getValueAt. This extension of AbstractTableModel has been put in a JTable, which has been put in a JScrollPane and in a JFrame for viewing. What I am trying to create now in the GUI is a function for the user to add Items to the ArrayList so that they will appear shortly after in the JTable. In overly simplified pseudocode, this function would look something like: 1.User presses button1 which is labeled "create new.." 2.Dialog box with text fields pops up 3.the input is used to create a new instance 4.the add-method is called with that instance. How do I make this happened? I have created a class for handling events.(in param: ActionEvent event). So far that class does nothing. I guess I need some kind of conditional statement like: if(button1 == event.getSource()) and then something that makes a dialog pop up. I've read tons of info on Jdialog and JOptionPane, the classes suggested to use for the dialog. However, I am unable to make anything happened. Please dont just post links to some page at sun microsystems (it feels like I've read them all.) For example, how would a dialog box even be able to appear in the first place? Shouldn't the method that makes it pop up be in the main method that actually starts the program? What I would like as a response to this is some code that easily just could be put in after my if statement and makes a simple dialog box appear. Some clarifying advice would also be nice. PHP Code: public class EventHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ if (event.getSource()== button1){ } } }
http://www.javaprogrammingforums.com/%20awt-java-swing/3053-program-gui-printingthethread.html
CC-MAIN-2014-15
refinedweb
311
74.69
Productive Enterprise Web Development with Ext JS and Clear Data Builder Guest Blog Post It’s not likely that you’ll start developing an enterprise HTML5 application without using one of the JavaScript frameworks. One of the most feature complete frameworks is Sencha Ext JS. Farata Systems has developed an open source software tool called Clear Toolkit for Ext JS. Clear Toolkit includes an Eclipse plugin called Clear Data Builder. This is a productivity tool — a code generator — that can create a CRUD application for you in no time. This application has an HTML/JavaScript/Ext JS client and Java-based server. In this article, you will learn how to jumpstart development of enterprise web applications. Learn the latest about Ext JS and HTML5/JavaScript for three intensive days with 60+ sessions, 3+ parties and more at SenchaCon 2013. Register today!ChangeObject — a universal way to trace the state changes between old and new versions of the same item in a store. - Clear Runtime — Java components that implement the server side of ChangeObject, DirectOptions, etc. directory structure, which is recommended by Sencha for MVC applications. Also, you’ll get the HTML wrapper — index.html — for this application, which contains the link to the entry point of our application. CDB generates an empty project with one sample controller and one view — Viewport.js. To run this application, you need to add the newly generated Dynamic Web Project to Tomcat and start the server (right-click on the Tomcat in the Servers view of Eclipse). package dto; import com.farata.dto2extjs.annotations.JSClass; import com.farata.dto2extjs.annotations.JSGeneratedId; @JSClass public class Person { @JSGeneratedId private Integer id; private String firstName; private String lastName; private String phone; private String ssn; public Person(Integer id, String firstName, String lastName, String phone, String ssn) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.phone = phone; this.ssn = ssn; } // Getters and Setter are omitted }, we will identify our main read method (remember the “R” from CRUD). Also, it would be nice to have some sort of UI to test the service — the annotation @JSGenerateSample will help here. CDB will examine the interface PersonService, and based on these annotations will generate all Ext You can see the SampleController and SampleGridPanel inside the samples folder. CDB also generates the JavaScript application entry point — sampleApp.js. To test this application, just copy the file SampleController.js into the controller folder, SampleGridPanel.js into the view folder, and the sample application in the root of our> result = new ArrayList<>(); Integer id= 0;")); return). Click on the Load menu, and you’ll get 4 persons from our server. To demonstrate the rest of the CRUD methods, we’ll ask the user to insert one new row, modify three existing ones and remove two rows using the generated Web client. The Clear.data.DirectStore object will automatically create a collection of six ChangeObject’s — one to represent a new row, three to represent the modified ones and two for the removed rows. When the user clicks on the Sync menu, the changes will be sent to the corresponding do… remote method. When you sync(), a standard Ext.data.DirectStoreExt do whatever has to be done to persist it in the appropriate storage. In our example, we just print the new person information on the server side Java console. This is why we said earlier, that it may be a good idea to provide a pretty printing feature on the class Person by overriding method toString(). Similarly, when you need to do a delete, the changeObject.getPrevVersion() would give you a person to be deleted. Part Three: Data Pagination The pagination feature is needed in almost every enterprise web application. Often, you don’t want to bring all the data to the client at once — a page by page + Java application: - Add the Ext.toolbar.Paging component - Bind both grid and pagingtoolbar to the same store - Use DirectOptions class to read the pagination parameters We are going to extend our CRUD application by adding the paging toolbar component bound to the same store as the grid. The class DirectOptions will handle pagination parameters on the server side. In public class PersonServiceImpl extends _PersonServiceImpl { @Override public List<Person> getPersons() { List<Person> result = new ArrayList<>(); for (int i=0; i<1000; i++){ result.add(new Person(i, "Joe", "Doe", "555-55-55", "1111-11-1111")); } return result; } } The Google Chrome Console shows that PersonStore was populated with one thousand records. Let’s add the pagination component using the Ext toolbarpaging } ], columns : [ {header : 'firstName', dataIndex : 'firstName', editor : {xtype : 'textfield'}, flex : 1 }, {header : 'id', dataIndex : 'id', flex : 1 }, {header : 'lastName', dataIndex : 'lastName', editor : {xtype : 'textfield'}, flex : 1 }, {header : 'phone', dataIndex : 'phone', editor : {xtype : 'textfield'}, flex : 1 }, {header : 'ssn', dataIndex : 'ssn', editor : {xtype : 'textfield'}, flex : 1 }], tbar : [ {text : 'Load', action : 'load'}, {text : 'Add', action : 'add'}, {text : 'Remove', action : 'remove'}, {text : 'Sync', action : 'sync'} ] }); // Launch the application Ext.application({ name : 'episode_3_pagination', requires : ['Clear.override.ExtJSOverrider'], controllers : ['SampleController'], launch : function() { Ext.create('Ext.container.Viewport', { items : [{ xtype : 'samplegridpanel' }] }); } }); - 9 can be extracted on the server side to get the information about the page’s boundaries. Let’s return to the code of PersonServiceImpl and add some extra code there. Right now, the pagination doesn’t work. The server sends the entire thousand records, because the server is not aware that the data has to be paginated. We’ll fix it in There are 5 responses. Add yours. firefoxSafari2 years ago Thanks for sharing - many intriguing ideas. Some comments / questions: A few of your generated .js files are a little loose with the extra commas. For example, the Ext.container.Viewport subclass I got in a simple test project had a trailing command after align: ‘center’. The HelloController had a trailing comma… there were others. The tool puts A LOT of stuff in WEB-INF lib, some of which I don’t want and I think could contribute to longer build times. I wouldn’t want the jta jars or jotm or the apache commons connection pool stuff. Might be ok for tomcat depending on what you’re used to, but if you’re deploying to WebSphere or something I’m not really comfortable with these or with the framework choosing a transaction strategy for me. At least get rid of the gson source jars! An example doing real database access with a persistence provider like hibernate would be useful. This might be more of an Ext Direct question, but I’m not at all sure from the examples how you’d get data back to the client after a create. Case in point, the example where you create a Person sort of just stops after you see that the server got the request and you’re left staring at a screen where the new Person row still doesn’t have an id. This example would be a lot better if you took it one step further and at least returned a ‘fake’ id so you could see it on the client. I like the idea of scaffolding, or at least the idea of generating .js from annotated java classes. It seems like there’s much room for innovation here. For example, no reason the paging toolbars had to be added by hand - there could have been some extra annotations that indicated the need for paging. It would also be nice if the framework provided at least a simple means of paging among items already in memory. Interested to see where this project goes. Viktor Gamov2 years ago Hello firefoxSafari, Thanks for your feedback. // Trailing commas Thanks for pointing out. We will revise default templates for typos and unnecessary trailing commas. //Transaction libraries By default, Clear Data Builder creates project that could be run on Tomcat without any other dependencies. This is starting point for developer. Tomcat is widely adopted Java WebServer. But Tomcat itself is not full Java EE application server. Which means, some of the important APIs are missing. CDB runtime rely on standard Java Transaction API to translate client side Batch request into server side transactions. For that purpose, CDB ships with JOTM transaction manager library that enables JTA programming model in Tomcat. If you want to run application of WebSphere you need to manually remove jotm libraries. But you need to make sure that your JTA implementation registers java:comp/UserTransaction JNDI resource. Clear Toolkit not choosing a transaction strategy for you, as per Convention over Configuration, only provides a default implementation which works out of the box. //Direct and CRUD You can Java Example Project (New -> ClearDataBuilder for ExtJs Project in Eclipse). This project has extensive example of the CRUD methods. This example has answer to your question. Long story short, as I demonstrated in this article and screencasts, generated store has all required methods backed by server-side service implementation. There is nothing Direct or CDB specific. You can use store.load, store.add and etc //Scaffolding We have something in out minds to add in future releases of CDB. Keep you eye on project page on Github! I hope this will help! Cheers, Viktor firefoxSafari2 years ago Hi Viktor, Thanks for the info. //Direct and CRUD You’re quite right - the Java Example Project did answer my question about id’s. For the benefit of others reading this, the key for me was that I had to invoke changeObject.setNewVersion(dto) in my _doCreate methods after I had assigned the id I wanted to the dto. It might be nice to add just this last bit to the screencast, too. FYI, the Java Example Project gave me several JavaScript errors using Ext 4.2. The controller methods were looking for a method called getExampleCompanyStore, but the actual method Ext generated was getExampleCompanyStoreStore. Brings back nightmares from jax-ws where wsgen always wanted to call my endpoints ServiceService! After changing this, the examples worked as expected. //Transaction libraries I understand that I could remove the tx libraries for WebSphere and that it’s desirable for it to run on Tomcat out of the box. However, it still does sound like CDB is choosing a tx strategy for me in that I have to use JTA and I have to bind things to JNDI. Starting a project from sratch is one thing, but I’ve seen many apps use resource local tx and not mess with JTA at all. Debatable whether this is good, but it’s the reality for many older JavaEE apps I’ve seen. I think it would bring more value if the tx strategy was completely pluggable. Maybe it is - haven’t spent enough time on CDB to give a judgement on it. //Scaffolding Excited for future scaffolding options. Would love to eventually see the templates that actually generate the scaffolding opened up to give users more control. Something like grails or spring roo. Our reality is that we might not be able to use all pieces of CDB on all apps, especially existing ones. IMO to reach the most people and have the most impact, it would good to decouple the Ext Direct and server side parts, the tx strategy, and the client side code generation. For example, maybe because of constraints on a legacy app, someone can’t use Ext Direct but they still get value from annotating Java classes to generate Ext model and sample grid, albeit not with not as much functionality. I realize this might not fall into the overall goals for the project, though. I’ll keep playing around and check out the rest of the wiki pages - glad Java to Ext scaffolding options are starting to emerge. Viktor Gamov2 years ago Hi firefoxSafari, // Controller getters Yes, it’s known issue with ExtJS 4.2 and it will be fixed in next release of CDB. As for now, you can grab the clear.override.app.Controller.js code from Github and place it in your project. If you have other issues, feel free to report to the issue tracker [1]. // Transactional Server-side component clear.transaction.djn.BatchGateway () uses JTA to perform transactional handling of batch members that sent by BatchManager (see Clear.data.DirectStore, sync() method) client-side component. If you don’t want to use JTA stuff, you need to provide your own implementation with signature described Clear.direct.ServerConfig.js (In BatchGateway.java find annotated @DirectMethod execute method). If you have some particular use case in mind, please, fill the bug in the issue tracker on the Github [1], and will try to help you with it. //Scaffolding The ExtJS Models generator can be used as a standalone utility. Here is an example how it can be used from command line ($JAVA_HOME/bin should be in the PATH). Also you can customize a service code generation even today. The templates (CDB uses XSL for the templates) are fully customizable. Please, look inside cdb_build folder of a generated project. FYI, Clear Data Builder does not wipe out the generated code, it only replaces the older source files with the newer versions. Consequently, if you rename your Java classes, it is your responsibility to delete the generated source files related to the old class. Long story short, you can throw away a generator part any time. [1] Cheers, Viktor firefoxSafari2 years ago Hi Viktor, Thanks for the excellent responses. It sounds like the toolkit has been very well thought out. Just a suggestion that some of these points would be good to have on the wiki Nice work! (note: third time I’ve tried to respond so apologies if there’s someday a flurry of dup comments). Comments are Gravatar enabled. Your email address will not be shown.Commenting is not available in this channel entry.
http://www.sencha.com/blog/productive-enterprise-web-development-with-ext-js-and-clear-data-builder/
CC-MAIN-2015-14
refinedweb
2,293
64.71
Subject: Re: [boost] Interest in adding support for the Bloomberg Standard Library From: Robert Ramey (ramey_at_[hidden]) Date: 2015-08-27 17:12:15 On 8/27/15 1:40 PM, Mathias Gaunard wrote: > Bloomberg has its own C++ standard library, BSL, which sits on top of > another standard library but replaces containers with their own versions. > The BSL containers are somewhat similar to Boost.Container's: they > provide stateful allocators, as well as backport some C++11 extensions > to C++03. > > Before I make all the necessary changes and do a pull request, pull request for which library? This sounds like you'd like to incorporate BSL into Boost containers. Is that what you mean or something else? I would > like to make sure the Boost community would be ok in including support > for this in Boost.Config. Wouldn't it be more appropriate to make a Bloomberg.Config which would #include <boost/config.hpp> ? > This library is fairly specific to one company and not used much > elsewhere, despite being open-source > (<>). We are also trying to phase out > usage of this library with the 'std' namespace (it can be configured to > use the 'bsl' namespace instead), but that's likely not going to happen > anytime soon. I'm not sure how this is relevant to Boost > > As part as providing support for this in Boost, we would also be > providing testers, mostly on big iron unix (AIX-powerpc, SunOS-sparc). > > Any interest? Well there would certainly be interest in getting more testers. Also getting underway will be the "Boost Library Official Maintainer" program. Sounds like this could be of on interest to Bloomberg. We'll be presenting it at CPPCon. Since Bloomberg is a sponsor of CPPCon I'm assuming you or someone like you will be there to participate. So there might be something good in all this? Robert Ramey Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2015/08/224985.php
CC-MAIN-2021-21
refinedweb
335
65.93
Some time ago, Patrick Smacchia (NDepend lead developer) offered me a NDepend Pro license to play around. NDepend is a tool providing a lot of features. The feature that impressed me from the very start is visualizing dependencies. Not just dependencies from classes to classes, or assemblies to assemblies; no from everything to everything. Like for example all assemblies that use somewhere the method Foo of class Bar. It works for assemblies, namespaces, types, methods and fields. But, what’s all this fuss about? Keeping a code base and its design as simple as possible over a long period of time is very difficult. It happens just too quickly that we loose the overview of how things are sticked together. And this is the moment when NDepend with its quick and easy dependency visualization comes to the rescue. Let’s take a look at an example. I use the state machine (bbv.Common.StateMachine) of the bbv.Common project as an example. The state machine assembly references two other assemblies of the bbv.Common project: bbv.Common.AsyncModules (for active state machines) and bbv.Common (string formatters and basic types): References of bbv.Common.StateMachine created with NDepend: select all assemblies that ‘bbv.Common.StateMachine’ uses directly or indirectly and visualized in graph view Now consider the scenario that I want to refactor the method ConvertToString(IEnumerable enumerable) in the class FormatHelper in the assembly bbv.Common. Therefore, I just select the method in the class browser of NDepend and select all methods that depend directly or indirectly on this method. Finally, I can visualize the result in the Graph view: Direct and indirect usages of ‘FormatHelper.ConvertToString’ in the bbv.Common.StateMachine assembly. Box size equals the lines of code the box represents and edge thickness represents how many members of the dependency are used. This took me about 3 seconds and I get a nice overview where this method is used. Now I know that a change to ‘FormatHelper.ConvertToString’ may have an impact on all this methods. And now the Untangling You’ve seen two tiny features of NDepend. But these two features already provide me a powerful tool to keep the dependencies in my code base simple. When I get the feeling that something in my design gets complicated or I simply lost the overview. I fire up NDepend and let me show the dependencies. For example for namespaces in bbv.Common.StateMachine: Namespaces of bbv.Common.StateMachine visualized with the NDepend Graph view. What immediately strikes the eye is the fat red arrow between bbv.Common.StateMachine and bbv.Common.StateMachine.Internals. That means, there are types in both namespaces that depend on types of the other namespace. A design smell for my clean code understanding. Therefore lets fire up the NDepend dependency matrix just for this connection (by choosing open this cycle on dependency matrix) and drill down into the namespaces: Dependency matrix of NDepend showing dependent elements: blue = element from top uses element on the left, green = element on the left uses element on top, black = both elements use their counterpart. With this information, I can start to untangle the namespaces to get code that is better and quicker understandable and easier to extend for users of the library. Obviously, there is quite some work to do here. Fortunately, nobody has complaint till now 🙂 Conclusion NDepend helps to quickly get an overview of a code base and what depends on what. Especially for code that is worked on for a long time, this helps tremendously, to reduce complexity. That’s it for now. But stay tuned, NDepend offers much more… Sidenote I’m also a heavy Resharper user. Resharper offers itself navigation and simple visualization of dependencies. However, NDepend delivers you the information needed to start untangling dependencies faster and with more easy. Why I like … posts are not about a tool or process being better that others, it’s just my thoughts what makes them useful for me in my projects. Nice article, thanks. We really have to spend more time digging into NDepend. What do you mean with Resharper simple visualization of dependencies? I can’t find such feature. @sizilium I mean the features in the “Inspect” menu of ReSharper.
https://www.planetgeek.ch/2011/11/13/why-i-like-ndepend-to-untangle-dependencies-in-my-code/
CC-MAIN-2020-10
refinedweb
709
58.48
Red Hat Bugzilla – Bug 155554 Wrong keyboard mapping for "slovene" Last modified: 2007-11-30 17:11:04 EST From Bugzilla Helper: User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3 Description of problem: Opening this bug as suggested in Version-Release number of selected component (if applicable): anaconda-10.2.0.47-1 How reproducible: Didn't try Steps to Reproduce: Additional info: system-config-keyboard and anaconda uses the keyboard models - I assume that rhgb should too import rhpl.keyboard_models k = rhpl.keyboard_models.KeyboardModels() name, xlayout, kbmodel, variant, options = k.modelDict["slovene"] How is the keymap wrong, and what should the correct one be? It is qwerty (probaly US, didn't check all 100 keys...). It should be 'slovene' ( 'sl' or 'si' in X terminology, I am not at the PC right now, so I can't check, but it is easy, one works and the other gives an error). It appears the keyboard is correct in anaconda, the console, and X (at least, it's certainly not qwerty - the Y and Z keys are transposed, and the bracket keys produce characters with various accents). firstboot appears to not be obeying the keyboard setting. Reassigning.
https://bugzilla.redhat.com/show_bug.cgi?id=155554
CC-MAIN-2018-34
refinedweb
211
57.57
The. The problem solution? - A function that will be called with each astng module built during a pylint execution, i.e. not only the one that you analyses, but also those accessed for type inference. - This transformation function is fairly simple: if the module is the 'hashlib' module, it will insert into its locals dictionary a fake class node for each desired name. - It is registered using the register_transformer method of astng's MANAGER (the central access point to built syntax tree). This is done in the pylint plugin API register callback function (called when module is imported using 'pylint --load-plugins'.! What's next?!. That's true and also what I wish. What I'm clumsily trying to tell is : we need help to collect problems with the standard library builtins/modules and to write such a plugin resolving them. Once identified, most problems should be easily fixed as demonstrated in this blog. And this is true of external libraries as well. wtf does pylint ? This is exactly what I wanted. Lets me easily avoid errors when using pytest, e.g. E1101:388,5:Test_LinuxUpgrades.test_PV1364: Class 'mark' has no 'bake' member where line 350 is @pytest.mark.bake Here's the plugin, edited to include just bake and skip members. Extend in the obvious way for your own local marks: from logilab.astng import MANAGER from logilab.astng.builder import ASTNGBuilder pytest_stub = ''' class mark(object): def __init__(self): pass def bake(self): return "" class skip(object): def __init__(self): pass ''' def pytest_transform(module): if module.name != 'pytest': return fake = ASTNGBuilder(MANAGER).string_build(pytest_stub) for stub in ('mark', 'skip'): module.locals[stub] = fake.locals[stub] def register(linter): MANAGER.register_transformer(pytest_transform) Thanks! --Glenn S.
https://www.logilab.org/78354
CC-MAIN-2020-50
refinedweb
285
59.4
where can i find out a detailed information about How to write a header file ? A header file is made up of pre-processor directives, classes, namespaces etc. a good place to look at is cplusplus.com. look at the classes, objects and namespaces chapters... My God I even had a comp science teacher ask me this.Arrrg one will go mad. It's simple.Cut a few funtions out of you code and paste them in a file with a .h extension and call #include "your_header_name.h" to include that. Note: not < > but " " if it's in the current directory else you have to supply the full or relative path. All the rules are same as normal C++ syntax. ---------------------------------------------- That was very simple thing.Headers can be used for more things.They can just contain funtions declarations without definitions.In that case it will be used to link to a static library. Eg.Make a header file with 2 funtion declarations like fun1(); fun2(); only Include it with a cpp file and call the funtions and compile. You will get no errors on compile but on linking you will see an error similar to the following: undefined module fun1() refferenced from Module main.cpp undefined module fun2() refferenced from Module main.cpp I hope you understand a header in not really diffrent from a cpp file.Btw you can also include .cpp files. Eg: #include "wow.cpp" It is very very simple: write some functions||define some macros||define structures/classes etc... DO NOT include a main() function save it with the name you want e.g header.txt/cpp/in/out/... you use it through: #include "..." if you have variables in your header, do not redeclare them in your programs or it will give you an error "Multiple declaration for variable..." :p Even if you include main() in a header and dont declare main() in any other funtion the program will complie and work properly.Headers are just a way to organise code. well if you include main() in a header that would be more like a program than like a header but anyway you can ;) did the computer science teacher ask you it on a test? did the computer science teacher ask you it on a test? You bumped a 6-year-old thread for that???? bump where can i find out a detailed information about How to write a header file ? Trying to learn c++. The tutorial is missing a .h (header file) ?
http://www.daniweb.com/software-development/cpp/threads/6294/how-to-write-a-header-file
CC-MAIN-2014-10
refinedweb
417
76.72
html html how to convert html page into jsp page Html :48:44 PM Author : SAMSUNG --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01...; <head> <meta http-equiv="Content-Type" content="text/html HTML it shows as null. here is the html code for date of birth: <tr> <...=""> <body onload="setValues html-jsp html-jsp If i want to get dynamic value in html textbox or in jsp,then how can I get the value,how the value will be transfered from servlet page to the html textbox.Thanx in advance.....Kindly help me HTML are learning JSP then it is must to learn HTML first. Here are the tutorials of HTML... HTML HTML is used for creating the web pages on Internet JSP Comment and HTML Comment JSP Comment and HTML Comment Difference between JSP Comment & HTML Comment ? JSP Comments are removed by the JSP Engine during the translation phase (JSP Comments are not even part of the compilation unit html form - JSP-Servlet html form how to retrieve database value in dropdown list box placed in html form Hi friend, Visit for more information. Thanks html-jsp - getparameter() - JSP-Servlet html-jsp - getparameter() Hi! friedns, This is my front end and I want to retrieve username and password in two different jsp pages. I used getParameter() with two form action as shown below. But I am not getting HTML - JSP-Servlet HTML To process a value in jsp project I have to set the text box as non editable. what is the attribute and value to be submitted... code. Visit for more information. send HTML Email with jsp and servlet send HTML Email with jsp and servlet Can You please show me how to send html Email using JSP and Servlet thank you html - JSP-Servlet explain in detain and send me code. login application in jsp...; } Login Application in JSP...; ------------------------------------------ Visit for more information. Thanks Amardeep javascript-html - JSP-Servlet javascript-html i want to dynamically create textfield with option button as another/remove when user presses in jsp page which will be in table.for example table contains one row with 2 columns,one textfield,second dropdown convert this html form to jsp convert this html form to jsp <html> <head> <script... Village Registration --> </body></html> JSP page includes html tags so you may change an extension. Please visit the following links html - JSP-Servlet java html java html program for jsp html - JDBC html How to insert a new column into HTML (or jsp) table dynamically? i have to print a table of html depending on number of subjects (where... jsp but i am not able to print them on the table because table columns convert html to excel using jsp convert html to excel using jsp i want to convert a html page into mcrosoft excel page using jsp.how i do HTML - JDBC HTML I created on html page with two comboboxes. when ever i select... combobox. please send me code of html Hi Friend, To do... it will fetch the name of the cities according to the country Id. Here is the JSP page html dropdownlist code - JSP-Servlet html dropdownlist code hi how to get textfield in html when i select the option others in the dropdown list, pls provide the code? Hi Friend, Try the following code: function show(){ var op java html -Type" content="text/html; charset=UTF-8"> <title>JSP Page<...java html program for jsp <meta http-equiv="Content-Type" content="text/html; charset html - WebSevices html hi how can i create "browse function" and also how can upload file or download file and save file also explain the example for each one Hi friend, For file upload visit to : html input passing to jsp method html input passing to jsp method i want code in which jsp method takes html input value which is in same page...... <html> <head> <%!public void method1() { **???how to read pid value here???** }%> HTML GRID HTML GRID how to retrieve data from mysql database in grid form using html and servlets? urgent.... import java.io.*; import java.sql....); } out.println("<html><h3>Pagination of JSP page</h3><body><:HTML Form in-place Editing - JSP-Servlet JSP:HTML Form in-place Editing I have an HTML form (form #1) which... beans. Perhaps you guys are better aware of in-place html form editing than me...://localhost:8080/examples/jsp/popup.jsp?id='+num,'mywindow','width=500, height JSP,JDBC and HTML(Very Urgent) - JSP-Servlet JSP,JDBC and HTML(Very Urgent) Respected Sir/Madam, Thanks... details from database using JDBC and JSP. The home page i.e HTML Page must contain... the code: I am not using any html. I used only jsp & jdbc. HTML tags in JSP HTML tags in JSP  ... the html tag inside the JSP code. In this example we have used...;title>Use of html tag in jsp code</title> </head> <body> i use HTML in jsp - JSP-Servlet i use HTML in jsp i want to make a list box of select state and corresponding to the selected state all the names of cities will be displayed...:// Link from html to jsp - Development process html link button , control should go to jsp page wat i mentioned in view... Friend, To give link from html page to jsp, you have to run the jsp page.After that specify the full path of jsp in html page with href tag. Use getting html list in a array getting html list in a array hi i want to get html unordered list in a array using jsp to run html code in web browser - JSP-Servlet to run html code in web browser how to run jsp file which calls html file on web browser?? Hi Friend, Try the following code: 1)form.jsp: Enter Name: 2)welcome.html: Add Profile Edit Include Static HTML Page in JSP Include Static HTML Page in JSP  ... html page in jsp. In JSP, there are two ways to include another web resource. 1. include directive and 2. jsp:include element. Using include directive JSP to add details to a database from a HTML form. JSP to add details to a database from a HTML form. Hi I'm a second year CS student who has to use JSP to validate a HTML form and add the details..... Can anyone tell me what is wrong with my code? html code first jar file with html jar file with html I have a jar file. On double click it shows an applet page. Please tell me how to connect that applet into html or jsp page Process HTML FORM data Process HTML FORM data Can a JSP page process HTML FORM data? Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick how to write a jsp form using html how to write a jsp form using html hi, i have written the code as below... but it is showing error. please help me how to resolve it. .html file...; </form> <p></body> </html> .jsp file < html - IDE Questions html how to run html page in eclipse You can't direct run a html/jsp page in eclipse. if it is pure static page then you can through the design tab. other wise type the addres of your page in eclipse browser html and servlet file html file with the jsp files amd servlet file insdie classes folder of tomcat. You...html and servlet file where to place the html and the servlet class files..in tomcat.. I have placed the html file under root and the class files HTML form - Java Beginners HTML form Hi, thank u for fast reply. I have two forms (form1 and form 2)with several fields in html. When i click the submit button... want jsp code for form navication. thanks, regards. sakthi Hi how to insert data in database using html+jsp how to insert data in database using html+jsp anyone know what is wrong with my code? print("<% /* Create string... < HTML HTML What is Semantic HTML? What are the reasons for validating a HTML html - Development process in this am using jsp and html. any body can help me plz its urgent Hi registration form in jsp function checkEmail(email... information, HTML HTML What is SPAN in HTML struts <html:text structs - Struts how can i display a value from database on jsp using struts form. the value should be populated on jsp load. can any body help me in this .... regards aftab jsp jsp code for jsp automatic genration using html jsp jsp how to pass jsp variable to an html page html html How to add the calendar in html code html html diffrence between html and xml Html Html What is HTML? What is a Hypertext link HTML HTML What is BODY in HTML document HTML HTML What is HTML? What is a Hypertext link html add a header in the html page what we can do to add a header in the html page jsp jsp write a code for jsp file generator to generate a jsp page automatically taking html page as input html html what we can do to add a header in the html page HTML HTML how can we give the unlimited size in the html html html i want a registration page in html with good background HTML HTML What is a tag? How can we use MARQUEE in HTML HTML HTML How do we specify page breaks in HTML web form(html) with jdbc web form(html) with jdbc need a example coding to develop a web form of data with jdbc Hi Friend, Try the following code: 1)form.html: <html> <form method="post" action=" html html Can we Access database through html page and how,if not then why html html For what is used HTML? Using HTML we can create a Web Page which can be viewed through a Web Browser over Internet. HTML describes... or the End Tag is defined as </> . The whole HTML document is enclosed Html Html i am select the dateofbirth through the html browser.but it can not save into the sql server 2008 database.any special code required to store the date in database by using java servlets HTML where i can store in the database SEND ME THE CODE FOR THIS IN JAVA AND HTML
http://www.roseindia.net/tutorialhelp/comment/20367
CC-MAIN-2015-06
refinedweb
1,762
79.4
The official Grafana docker image Running your Grafana image Start your image binding the external port 3000. docker run -i -p 3000:3000 grafana/grafana Try it out, default admin user is admin/admin. Configuring your Grafana container All options defined in conf/grafana.ini can be overriden using environment variables, for example: docker run -i -p 3000:3000 \ -e "GF_SERVER_ROOT_URL=" \ -e "GF_SECURITY_ADMIN_PASSWORD=secret \ grafana/grafana If we update the config file to use a database, Grafana tries to create a data directory in the homepath. Since that path is owned by root and grafana-server is running as grafana, it fails and essentially can't proceed. Can we have the homepath chowned to grafana.grafana as well as we do for GF_PATHS_DATA and GF_PATHS_LOGS. Hello, why I need to provide my dockerhub credentials to pull this image? Is this suppose to be the "offcial" "public" image? If this is an "official" image, why You don't user the "library" namespace, like other real official images ? You are missing double bracket GF_SECURITY_ADMIN_PASSWORD=secret" @robsonpeixoto See: How to install plugins? I need to create my own image? latest --> v4.0.1, maybe is better if you point it to latest --> v4.1.1 Regards as yangkwang has already asked: why is it not possible to enter using the dafault admin/admin user? latest tag broken: error: exec failed: permission denied Looks like the latest tag is not pointing to the real latest version for now (4.0.2). When you run latest image the actual version is 4.0.1 for some reason.
https://hub.docker.com/r/grafana/grafana/
CC-MAIN-2017-30
refinedweb
262
57.16
IoT Based Flood Monitoring System Using NodeMCU & Thingspeak Today in this project we are going to make IoT Based Flood Monitoring System Using NodeMCU, Ultrasonic HC-SR04 Sensor & Thingspeak IoT Platform. As we all know that Flood is one of the major well Known Natural disasters. It causes a huge amount of loss to our environment and living beings as well. So in these cases, it is very important to get emergency alerts of the water level situation in different conditions in the river bed. The purpose of this project is to sense the water level in river beds and check if they are in normal condition. If they reach beyond the limit, then it alerts people through LED signals with buzzer sound as well as internet applications. Here we are using the Ultrasonic HC-SR04 sensor to sense the river level and NodeMCU ESP8266 Microcontroller for data processing. The processed data will be uploaded to the ThingSpeak IoT Cloud Platform. Using which river levels can be monitored graphically from anywhere in the world. - Required Components of Flood Monitoring System - How this Flood Monitoring System Works? - Ultrasonic HC-SR04 Sensor - Schematic of IoT Based Flood Monitoring System - Flood Monitoring System Using NodeMCU -Video Demonstration - Set up a ThingSpeak account for Flood Monitoring & Alerting System - Setting up Arduino IDE for NodeMCU Board - Program Code explanation - Program Sketch/Code - Wrapping up Required Components of Flood Monitoring System These are the components required to make IoT Based Flood Monitoring System Using NodeMCU & ThingSpeak. - NodeMCU ESP8266 Development Board - Ultrasonic HC-SR04 Sensor - Red and Green LEDs - Buzzer - Jumper wire - Breadboard - Power Supply How this Flood Monitoring System Works? We have used ESP8266 NodeMCU to build many IoT projects before. The block diagram above shows the working of this IoT based flood monitoring system using the NodeMCU and IoT Platform. Here, the Ultrasonic sensor is used to detect river water levels. The raw data from the ultrasonic sensor is fed to the NodeMCU, where it is processed and sent to ThingSpeack for graphical monitoring and critical alerts. Here, the red LED and Buzzer is used to send an alert in a flooded condition. While Green LED is used for indicating Normal condition. are used to be alert in severe flood conditions, and green LEDs are used to indicate normal conditions. Ultrasonic HC-SR04 Sensor Ultrasonic sensors work on the principle of ultrasound waves which are used to determine the distance for an object. An Ultrasonic sensor generates high-frequency sound waves. When this ultrasound hits the object, it reflects as the echo that the receiver sense. We can calculate the distance to the target object using the time required to reach the receiver for Echo. Formula to calculate: Distance= (Time x Speed of Sound in Air (340 m/s))/2 Ultrasonic distance sensors are of two ultrasonic transducers. One of them acts as a transmitter that converts the electrical pulse of the microcontroller into an ultrasonic sound pulse and is received by the receiver for transmitted pulses. If it receives them, then it produces an output pulse whose time period is used to determine the distance from the object. Features: Working voltage: 5V Current working: 15mA Working frequency: 40HZ Measurement distance: 2cm - 4m Measuring Angle: 15 Degree. Trigging input pulse: 10uS Learn more about ultrasonic sensors through its previous projects such as Read Ultrasonic Sensor data through webserver on a realtime chart. Schematic of IoT Based Flood Monitoring System Interfacing NodeMCU ESP8266, Ultrasonic HC-SR04 Sensor, Buzzer, and LEDs (Red and Green) as shown in the following circuit diagram: Interfacing HC-SR04 Sensor to NodeMCU Connect Green and Red LEDs Negative Terminal to GND and Positive terminal to the D4 and D3 pin respectively. lastly, connect Buzzer GND to GND and Positive terminal to D5 pin of NodeMCU. Flood Monitoring System Using NodeMCU -Video Demonstration Set up a ThingSpeak account for Flood Monitoring & Alerting System After the successful interface of the hardware parts according to the circuit diagram above. Now its time to set up the IoT platform, where data can be stored for online monitoring. Here we are using ThingSpeak to store data. ThingSpeak is a very popular IoT cloud platform that is used to store, monitor, and process data online. Step 1: Sign up for ThingSpeak First go to ThingSpeak and create a new free MathWorks account if you don’t already have a MathWorks account. Step 2: Sign in to ThingSpeak Sign in to ThingSpeak using your credentials and create “New Channel“. Now fill the project details like name, field names, etc. Here we need to create three field area names such as Flood Live Monitoring, and Flood Status. Then click “Save Channel”. Step 3: Record the credentials Select the created channel and record the following credentials. Channel ID, which is at the top of the channel view. API key, which can be found in the API Key tab of your channel view. Step 4: Add widgets to your GUI Click “Add Widgets” and add two appropriate Indicator widgets. In my case, I have taken an indicator of flooding. Choose the appropriate field names for each widget. Setting up Arduino IDE for NodeMCU Board After the successful completion of the hardware setup. Now its time to program ESP8266 NodeMCU. To upload the code to NodeMCU using the Arduino IDE, follow the steps below: - Open the Ardino IDE, then go to File> Preferences> Settings. - Paste the URL: in the ‘Additional Board Manager URL‘ field and click ‘Ok’. Now. Now go to Tools> Board> Board Manager. In the Boards Manager window, type ESP8266 in the search box, select the new version of the board and click Install. After successful installation, go to Tools -> Board -> and select NodeMCU 1.0 (ESP-12E Module). Now you can program NodeMCU with Ardino IDE. After the above setup for programming NodeMCU. You can upload the complete code to ESP8266 NodeMCU. The step-by-step explanation of the full code is provided below. Program Code explanation Begin the code by including all the necessary library files in the code for ESP8266 boards. The ThingSpeak.h library is used for the ThingSpeak platform. It can be added to the Arduino IDE using the following steps: - In the Arduino IDE, choose Sketch/Include Library/Manage Libraries. - Click the ThingSpeak Library from the list, and click the Install button. #include "ThingSpeak.h" #include <ESP8266WiFi.h> Next, define the pins which are used for the Ultrasonic sensor, Buzzer and LEDs. #define redled D3 #define grnled D4 #define BUZZER D5 //buzzer pin Now, Enter the network credentials- i.e. SSID and password of your WiFi Network to connect the NodeMCU with the internet. Then the ThingSpeak account credentials: channel number, API Key, and Author Key. These all credentials were recorded while setting ThingSpeak IoT Platform. Hence, make sure, you have edited these credentials in place of these variables.]"; The variables are defined for timing purposes. unsigned long startMillis; unsigned long currentMillis; const unsigned long period = 10000; WiFiClient client; long duration1; int distance1; Basically, to connect NodeMCU to the internet, we call WiFi.begin function. To Check for the successful network connection WiFi.status() is used. Finally, after a successful connection, we print a message on the Serial Monitor with the NodeMCU IP address. Serial.begin(115200); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.println(WiFi.localIP()); Now we connect to the ThingSpeak IoT Platform using Provided credentials. For this, we need to use ThingSpeak.begin function. ThingSpeak.begin(client); For calculating the distance, an input pulse is given to the sensor through the trig pin of the HC-SR04 sensor. Here, a 2-microsecond pulse is given, then from the echo pin, the output pulse of the sensor is read. Finally, the distance is calculated in cm. digitalWrite(trigPin1, LOW); delayMicroseconds(2); digitalWrite(trigPin1, HIGH); delayMicroseconds(10); digitalWrite(trigPin1, LOW); duration1 = pulseIn(echoPin1, HIGH); distance1 = duration1 * 0.034 / 2; Then, an if-else condition is defined for the LED indications and Buzzer state for both Normal and Flood conditions. Here as per my setup, I have taken 4 cm as reference. But, you can change it as per your requirements. if (distance1 <= 4) { digitalWrite(D3, HIGH); tone(BUZZER, 300); digitalWrite(D4, LOW); delay(1500); noTone(BUZZER); } else { digitalWrite(D4, HIGH); digitalWrite(D3, LOW); } Finally, the river water level is uploaded to the ThingSpeak channel in interval of 10 seconds. if (currentMillis - startMillis >= period) { ThingSpeak.setField(1, distance1); ThingSpeak.writeFields(ch_no, write_api); startMillis = currentMillis; } Program Sketch/Code #include "ThingSpeak.h" #include <ESP8266WiFi.h> const int trigPin1 = D1; const int echoPin1 = D2; #define redled D3 #define grnled D4 #define BUZZER D5 //buzzer pin]"; unsigned long startMillis; unsigned long currentMillis; const unsigned long period = 10000; WiFiClient client; long duration1; int distance1; void setup() { pinMode(trigPin1, OUTPUT); pinMode(echoPin1, INPUT); pinMode(redled, OUTPUT); pinMode(grnled, OUTPUT); digitalWrite(redled, LOW); digitalWrite(grnled, LOW); Serial.begin(115200); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.println(WiFi.localIP()); ThingSpeak.begin(client); startMillis = millis(); //initial start time } void loop() { digitalWrite(trigPin1, LOW); delayMicroseconds(2); digitalWrite(trigPin1, HIGH); delayMicroseconds(10); digitalWrite(trigPin1, LOW); duration1 = pulseIn(echoPin1, HIGH); distance1 = duration1 * 0.034 / 2; Serial.println(distance1); if (distance1 <= 4) { digitalWrite(D3, HIGH); tone(BUZZER, 300); digitalWrite(D4, LOW); delay(1500); noTone(BUZZER); } else { digitalWrite(D4, HIGH); digitalWrite(D3, LOW); } currentMillis = millis(); if (currentMillis - startMillis >= period) { ThingSpeak.setField(1, distance1); ThingSpeak.writeFields(ch_no, write_api); startMillis = currentMillis; } } Basically, ThingSpeak will show a big green indicator while there is no flood. and in case of Flood a Red Indicator as shown below: Wrapping up This is just a basic model for an IoT Based Flood Monitoring System Using NodeMCU & ThingSpeak. We can improve this project for better performance. Hence, there is a lot of scope for improvising it. I hope you enjoyed the project and learned something new. 3 Comments when verify the code ” ‘D3’ was not declared in this scope” error is appearing…& what is the char auth[] = “mwa0000018384149”, Can you help me? This is Auther key of Thingspeak IoT Platform. Read or Watch coding part to know more i am getting error “D1” was not declared in this scope.Can u please help me with this.
https://theiotprojects.com/iot-based-flood-monitoring-system-using-nodemcu-thingspeak/
CC-MAIN-2021-43
refinedweb
1,711
56.25
Summary Some test cases have indeterminite results in some cases. These cases should be distinct from a passing or failing state of a test today. It is possible to turn tests off at compile time by using features determined by a build.rs script, however, this does not work well for cross compilation or when the build and test environment are otherwise quite different. Motivation Currently, tests in Rust's libtest have only a handful of end results: - success - failure (panic) - should panic (which must panic to succeed) - ignored (masked by default) While this works for the vast majority of cases, there are situations where tests must change their behavior based on the available runtime. While many of these cases can be detected at build time, this is just not the case in general. Cases that I, personally, have come across in various projects (Rust and non-Rust): - Cross-compilation.: In cross-compilation, build-time detection of the target's feature set is generally not possible in any kind of reliable way (including all of the following items). - Complicated dependency specifications: Tests which require specific things may be hard to test at configure or build time. Even if the list of things is possible to get, ensuring that when those things change that the build is redone to sync up with the prevailing environment is another problem altogether. This includes all of the following items, but is certainly not limited to them. - Kernel version/feature detection: While possible at configure time, adding a dependency that is meaningful to ensure that the test suite is recompiled when the running kernel version changes is an unnecessary burden. - OpenGL support: Detecting whether the runtime OpenGL is suitable for testing usually involves creating an OpenGL context and querying for its limitations. Again, adding a dependency for "OpenGL limitations" is a burden. Doing this during the configure or build.rsstep involves unnecessary complications. Many build systems do not even support running such code at configure time without building and running code itself (cf. CMake, autotools, etc.). Even if the build system is in a language which can make OpenGL contexts, it unnecessarily restricts what machines can build the project and its test suite. - Python module detection: This can also change external to the build system. Versions changing, availability in the given environment, etc. can all change externally. I've found it far easier to instead detect the module at test time and decide what to do at that point. - Complex test requirements: Kind of a grab bag of cases here. Generally, some tests may depend on some state of the enclosing build as to whether they are suitable or not. Requiring configure or build time detection of such things is either difficult or error-prone (as the detection code must be kept in-sync with the test itself). While it doesn't happen in Rust that often, in C++, some projects have examples which require various bits of the project to be built in order to actually work. Keeping the build system in the loop of what states of the project's build is suitable for each test is not easy when it is far easier for the test to just have a mechanism that says "this test is not suitable, please skip me". As an example within one of my own crates, this test detects whether the remaining tests in that module make sense. The best it can do is inform that the rest of the tests in that module are meaningless (or have them report "success" when they really didn't do anything of the sort). Guide-level explanation There may be cases where the results of a test are not useful in the current environment. Usually, this can be detected at build time and a cfg be enabled to change test function attributes or hide entire modules. However, some tests are sensitive to states of the environment that may change at any time over the test executable's life. Some examples include: - Is the running user an administrator or not? - Is there enough memory available for this test to succeed? - Are there enough CPU cores available? - Can a suitable OpenGL context be made for this test? - Is an X server available? - Is a hardware token available? In such cases, it is possible to add a skip_if attribute to tests to indicate when a test should be considered to have an indeterminate result in the current execution environment. The predicate item may be set to the path to a function which takes no arguments and returns an Option<String>. When this function returns None, the test will be executed while if it returns Some, the string value will be used as the reason the test could not be executed. As an example, a test which ensures that removing permissions from a file has the desired effect in the rest of the code generally will not work as intended when executing as root because removing read permissions from a file does not actually change anything in this case: fn is_root() -> Option<String> { if libc::getuid() == 0 { Some("untestable when running as root".into()) } else { None } } #[test] #[skip_if(predicate = is_root)] fn test_revoke_permissions() { // remove permissions from a file and make sure it is not readable. } While it would be possible to detect root permissions at build time, this would compile the test out completely even though it could be expected to work if a non-root user ran the test. The skip_if attribute supports a single argument, which must be supplied: predicate: the path to a function with a fn() -> Option<String>signature. If the predicate function panics, the test is considered to have failed whether or not should_panic is provided on the test function or not. Currently skip_if is only available for #[test] and #[bench] functions, not within doctests. Reference-level explanation The implementation of this is largely in libtest. The TestDescAndFn gains a new field skipfn which, if provided, is run before the test. If it returns a reason, a new test result is constructed and handled appropriately in the output formatters. If the skipping function panics, the test is considered to have failed regardless of #[should_panic] or not. The implementation takes the same panic-wrapping approach as the test itself does, but instead of handling panics and returning a result for should_panic to decide, panics are just treated as a hard failure. I have a work-in-progress implementation on my fork which implements it for #[test] and #[bench] functions. Adding support for doctests is left out for now. In addition, a few corner cases are left as "TODO" items, largely around what if the predicate is not suitable, error messages, and parsing the attribute into a callable.. Drawbacks This does make testing more complicated, but I don't know of another way of handling such dynamic requirements reliably from build.rs. Rationale and alternatives I think this design keeps itself out of the way for existing test suites which don't need to deal with this. For tests suites that do, it is easy to add a single attribute to the affected tests and implement a quick check. The cost of not doing this is that these test suites continue to have to do largely unsuitable or inaccurate checks in build.rs or report "fake" success reports for tests that aren't actually doing what they should due to environmental states. Prior art usually also has mechanisms where skipping is supported from within the test. Rust does not have a throwing mechanism (other than panic! which is already covered via the #[should_panic] attribute) and adding a return path seems excessive given that the "happy path" would then also need to "return" some kind of indication that the test ran fine. In addition, using an attribute to call another function makes it easier to handle when a collection of tests all need to skip for the same reason. Using an attribute allows them all to share the same code without adding anything which might constitute "noise" to the test function body itself. Prior art Other test harnesses support the concept of "skipping" tests. This is used as a state that is neither success nor failure and is usually used to indicate that a test is not applicable in the current environment. It is used as a separate state because without it, the test must either report success without actually testing what it purports to test or report failure and prevent "all green" states which is typically wanted within development workflows. CMake CMake, a very popular C++ build system (full disclosure, the RFC author is a CMake developer), supports this in its CTest tool which is a test harness runner (though it supports running commands rather than test functions directly). In CTest, tests can have "test properties" named SKIP_RETURN_CODE and SKIP_REGULAR_EXPRESSION which will cause the test to be skipped if it exits with the indicated return code or its output matches the given regular expression. This state is not reported as success or failure but as a third state of "skipped" (rendered on CDash in a "Not Run" column). add_test(NAME skip COMMAND …) set_test_properties(skip PROPERTIES SKIP_RETURN_CODE 125 SKIP_REGULAR_EXPRESSION "SKIPME") #include <stdio.h> int main(int argc, char* argv[]) { printf("SKIPME\n"); // Will cause the test to be skipped. return 125; // As will this; either is sufficient, but both are available. } Given the nature of CTest running arbitrary commands, there's no good way to indicate why a test was skipped. It is generally left to the test to print out its reasoning to stdout or stderr where the content will be preserved (by CTest) and displayed (when uploaded to CDash). Pytest The pytest framework is available for Python. Here, there are a few ways to indicate that a test should be skipped. - Static Declarative: The pytest.mark.skipdecorator which (optionally) accepts a reasonkeyword argument. This argument contains a description of why the test cannot be run. - Dynamic Declarative: The pytest.mark.skipiftakes a boolean as its only required argument. If this condition is True, the test is skipped (this additionally takes a reasonargument). - Imperative: The pytest.skipfunction may be called (with a required reasonpositional argument). This is used for more conditions which require runtime information in order to detect their suitability. This is also usable at the module level as well with the allow_module_level=Trueargument. @pytest.mark.skip(reason="I wrote this on a Monday") def test_garfield_static(): pass @pytest.mark.skipif(time.localtime().tm_wday == 0, reason="Mondays, am I right?") def test_garfield_dynamic(): pass def test_garfield_imperative(): if time.localtime().tm_wday == 0: pytest.skip(reason="Mondays, am I right?") Both declarative methods may be used at the class (group of test) level as well. RSpec Ruby's RSpec testing library supports skipping tests via a similar mechanism to the dynamic declarative and imperative modes available in pytest. They are reported as "Pending" in this case. RSpec.describe "an example" do example "is skipped dynamic declaratively", :skip => true do end example "is skipped dynamic declaratively with a reason", :skip => "blue moon" do end it "is skipped imperatively" do skip end end XCTest The XCTest test framework provided by Apple as part of its normal SDK provides XCTSkip which may be thrown from a test function to indicate that it should be skipped. Unresolved questions Should the return value of a skipfn be Option<String> or some other structured type? The downside of a more structured type is the requirement that the test crate exposes symbols which need to be used (currently all of these are for #[bench] tests and behind a feature gate). Should there be an imperative mechanism. If so, should it replace the attribute? I don't think so because the type that we want to panic on (using panic_any!) would likely live in the test crate. For similar reasons as the above, that would effectively lock usage of the imperative mechanism behind a feature gate. Should multiple skip_if attributes be supported? I don't think it's strictly necessary since making a function to call .or_else() on the chain of candidate skipping functions is possible already. But it could be added in the future (with specifications on the order in which they report skip reasons are collected). This does interact with eRFC 2318 (tracking issue) in that custom test frameworks would need to support skipping logic. Is predicate the best name for the argument name? I'm not sure it is, but couldn't come up with something better right now. Future possibilities In addition to skip_if(predicate = …), skip_if(cfg = …) might be plausible to let users know of a given test that is not available on their platform.
https://internals.rust-lang.org/t/pre-rfc-skippable-tests/14611
CC-MAIN-2021-21
refinedweb
2,115
61.56
If you are a .NET developer and you’ve got an assignment to integrate Quick Books with a .NET C# application then I guess there is something iniquitous you did in the past which goddess Fortuna didn’t like at all and now she is up to your retribution. The situation gets worse since there is not much help on web. So for those folks who consider themselves as “R n’ D champions” and got this assignment; you guys are in big trouble. Experience of integration of C# application with Quick Books was very challenging to me; and now here I am presenting in front of you what I achieved from spending nights after nights, head scratching and wall banging efforts. Introduction & Architecture: So let’s start by understanding what are the prerequisites of this project are: · Quick Books, obviously, make sure it’s installed with multi-user license. · Quick Books SDK, available here () search for Download the QBSDK 7.0 or latest. Now let’s quickly go through the design of my small application which will talk to Quick Books. Basically the purpose of this application is to show you how a .NET application can request and retrieve some information e.g. list of vendors from QB. Likewise, if .NET application wants to insert some data e.g. a vendor again; how it can be done. Following is the design architecture of the application we are about to build: Let me just quickly explain the above architecture and then we can move forward towards coding on this design. Presentation layer consists of a win form designed and developed in C#. Through this form we will perform our CURD (Create, Update, Read and Delete) operations. This form instantiates business objects Vendor, which is present in the Vendor.cs file. Common.cs contains some other helper business objects and classes used in application. Right besides Business Layer, we have Data Access Layer which includes RequestBroker.cs. This class does most of the data transactions with QuickBooks. Finally, quick book’s company file is the data layer. After quickly going through the simple design architecture let’s see how things work here. Foremost, let’s take a quick look at our vendor class which is a business object for Vendor DB/QB entity. Business Layer: [Serializable] public class Vendor { private string name; private string companyName; private string contactName; private string phoneNumber; private string faxNumber; private bool isActive; private string type; public string Name { get { return this.name; } set { this.name = value; } } public string Type { get { return this.type; } set { this.type = value; } } public string CompanyName { get { return this.companyName; } set { this.companyName = value; } } public string ContactName { get { return this.contactName; } set { this.contactName = value; } } public string PhoneNumber { get { return this.phoneNumber; } set { this.phoneNumber = value; } } public string FaxNumber { get { return this.faxNumber; } set { this.faxNumber = value; } } public bool IsActive { get { return this.isActive; } set { this.isActive = value; } } public Vendor() { this.name = this.companyName = this.contactName = this.phoneNumber = this.faxNumber = string.Empty; this.isActive = true; this.type = “Service”; // Lets set some default vendor type } public Vendor(string name) : this() { this.name = name; } #region Fill Request Methods public void FillViewRequest(IVendorRet vendorReturn, bool completeInformation) { if (vendorReturn.Name != null) this.name = vendorReturn.Name.GetValue(); if (completeInformation) { if (vendorReturn.CompanyName != null)(); } } public void FillViewRequest(IVendorRet vendorReturn) { this.FillViewRequest(vendorReturn, true); } public void FillAddTypeRequest(ref IVendorTypeAdd vendorTypeAddRequest) { vendorTypeAddRequest.Name.SetValue(this.type.ToString()); vendorTypeAddRequest.IsActive.SetValue(true); } public void FillAddRequest(ref IVendorAdd request) { if (this.name.Length > 0) { request.Name.SetValue(this.name); request.NameOnCheck.SetValue(this.name); } if (this.companyName.Length > 0) { request.CompanyName.SetValue(this.companyName); request.NameOnCheck.SetValue(this.companyName); } if (this.phoneNumber.Length > 0) request.Phone.SetValue(this.phoneNumber); if (this.faxNumber.Length > 0) request.Fax.SetValue(this.faxNumber); if (this.contactName.Length > 0) request.Contact.SetValue(this.contactName); request.IsActive.SetValue(this.isActive); request.VendorTypeRef.FullName.SetValue(this.type); } #endregion } Vendor class has some basic private data members and their corresponding public properties like name, phone, fax etc, one default constructor and an overloaded constructor with name parameter. For now, don’t worry about the coding done in Fill Request Methods region; I’m going to explain this region in short. Now let’s jump to Common.cs and see what are other common classes that I’ve made and how do they work. In Common.cs, first we have two enums: public enum QBOperationResult { Failed = 0, Succeeded, Warning, } QBOperationResult will tell us the result of any operation we’ll do with QB, e.g. if we send a request for getting the list of all the vendors in the QB file, either the request will be granted successfully or granted with some warning or completely denied. To fetch the correct response from QB, this enum will used. Next is: public enum QBSortDirection { Ascending = 0, Descending = 1, } Let’s suppose we get the list of 100 vendors from QB file, now what column we want to sort this list on and in what direction? QBSortDirection enum will be used in sorting the list in ascending or descending order. Next comes: [Serializable] public class QBOperationStatus { private string inputParamsXML; private QBOperationResult status; private string msg; private string methodName; private int spErrorID; private string spName; private string spErrorText; private XmlDocument xmlDoc; public string InputParamsXML { get { return inputParamsXML; } set { inputParamsXML = value; } } public QBOperationResult OperationResult { get { return status; } set { status = value; } } public string Message { get { return msg; } set { msg = value; } } public int SPErrorID { get { return spErrorID; } set { spErrorID = value; } } public string MethodName { get { return methodName; } set { methodName = value; } } public string SPName { get { return spName; } set { spName = value; } } public string SPErrorMessage { get { return spErrorText; } set { spErrorText = value; } } public XmlDocument XmlDoc { get { return this.xmlDoc; } } public QBOperationStatus() { this.spErrorText = this.spName = this.methodName = this.msg = string.Empty; this.status = QBOperationResult.Failed; this.xmlDoc = new XmlDocument(); } public QBOperationStatus(QBOperationResult operationResult) : this() { this.status = operationResult; } }. Fundamental purpose of this class is to compose QBOperationResult enum and get the status of any QB transaction. Next is the turn for: [Serializable] public class ComboBoxItem { private string _text; private int _value; public string Text { get { return this._text; } set { this._text = value; } } public int Value { get { return this._value; } set { this._value = value; } } public ComboBoxItem(string text, int value) { _text = text; _value = value; } public override string ToString() { return _text; } } This simple class is used to instantiate combo box items and then to access their Text and Value properties. Last in this file is: [Serializable] public class QBList<Entity> : CollectionBase { public Entity this[int index] { get { return (Entity)List[index]; } set { List[index] = value; } } public int Add(Entity value) { return (List.Add(value)); } public int IndexOf(Entity value) { return (List.IndexOf(value)); } public void Insert(int index, Entity value) { List.Insert(index, value); } public void Remove(Entity value) { List.Remove(value); } public bool Contains(Entity value) { return (List.Contains(value)); } public QBList<Entity> Clone() { QBList<Entity> list = (QBList<Entity>)this.MemberwiseClone(); return list; } public Entity GetEntity(string keyName, object keyValue) { if (keyName.Length == 0) return default(Entity); Hashtable htFromList = GetHashTable(keyName); if (htFromList.Count > 0) return (Entity)htFromList[keyValue]; return default(Entity); } public Hashtable GetHashTable(string keyColumnName) { Hashtable htFromList = new Hashtable(); if (keyColumnName.Length != 0) { foreach (Entity entity in this.List) { PropertyInfo propertyInfo = typeof(Entity).GetProperty(keyColumnName); if (null != propertyInfo) { Object propertyValue = propertyInfo.GetValue(entity, null); if (null != propertyValue && !htFromList.ContainsKey(propertyValue)) htFromList.Add(propertyValue, entity); } } } return htFromList; } } Instead of using Arrays or DataTables, I decided to make my own class, similar to Generic List class, derived from CollectionBase to use enriched methods of the parent class, plus my own customized functionality which suits current projects needs. Now before if move to the brain of the application i.e. RequestBroker.cs, I would prefer to explain how UI is working in this application. In that, first comes view vendor list screen: Presentation Layer: In this form I simply got a complete list of vendors present in the QB company file. Let’s take a look at the code responsible for that, you’ll be surprised to see the size of the code: - different version of Quickbooks, some programmers can’t see an “Add Application” button in above mentioned dialogue box. If you. So that’s pretty much it is. I hope code snippets and their line-by-line explanations and screenshots will help some programmer to find some solution to his/her assignment. If it does then please don’t forget to give me your feedback on this article. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Configuration; namespace prjQuickBookIntegration { public partial class frmViewVendorList : Form { public frmViewVendorList() { InitializeComponent(); } // Line numbers are marked for understanding the code and not the part of actual code private void frmViewVendorList_Load(object sender, EventArgs e) { 01 if (ConfigurationSettings.AppSettings[“QBFilePath”].Length > 0) { 02 RequestBroker broker = new RequestBroker(ConfigurationSettings.AppSettings[“QBFilePath”]); 03 QBOperationStatus opStatus = new QBOperationStatus(); 04 this.grdVendors.DataSource = new QBList<Vendor>(); 05 QBList<Vendor> qblVendor = broker.GetVendorList(ref opStatus, true); 06 this.grdVendors.DataSource = qblVendor; 07 if (opStatus.OperationResult == QBOperationResult.Succeeded) 08 this.txtResults.Text = qblVendor.Count.ToString() + ” records retrieved successfully.”; 09 else 10 this.txtResults.Text = “Vendors could not be retrieved successfully.\r\n” + opStatus.Message; } } } } This is one of the advantages of having a multi-tiered logic of your application that most of the complex part of the application is divided and scattered among different tiers and code looks a lot simple. The first line (line 01) of frmViewVendorList_Load method is checking if app.config entry for the company file path is given or not. App.config entry looks something like this: <add key=“QBFilePath“ value=“D:\shared\Wisdom.QBW“/> After config entry is found, I’m instantiating the RequestBroker class by calling the constructor which takes file path as parameter (line 02). Third line (line 03), instantiates our QBOperationStatus class so that it can be used in the QB operation about to be performed next. After that (Line 04), I’m assigning an empty QBList of type Vendor to my grid control to erase all the previous data, if any, present in the grid. In design time I added columns in grdVendors; these columns point to different properties of the vendor class, see screenshot below: Line 05, the heart of this method; calls the RequestBroker’s GetVendorList method and assigns the result to the QBList type list declared locally in this method. Line 06, sets the data source property of the grid to show the result set on the screen. Line 07 and onward are just the finishing touch of the method, checking the operation status, whether the operation was performed successfully or not. If the operation was, fortuitously, successfully performed then you’ll see the message in the text box below, with the number of vendors returned. In other case, however, you’ll get a message of failed operation along with its reason. Data Access Layer: I think now is the right time to see our RequestBroker class party-by-part. Request Broker class composes a struct called QBVersion. This structure is made basically for keeping the name of the country where the Quick book is installed, major and minor versions of the Quick book. The structure looks something like: public struct QBVersion { public string country; public short majorVersion; public short minorVersion; } At the top of the RequestBroker.cs import some namespaces as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Interop.QBFC7; To use Interop.QBFC7 you need to add references of two interop libraries and your references folder should look like this: That’s how RequestBroker class starts: public class RequestBroker { public static QBVersion QBVersion; public static string CompanyFilePath; public static string ApplicationName; private QBSessionManager sessionManager; private StringBuilder requestBrokerLog = new StringBuilder(); private string logFilePath; public string LogFilePath { get { return this.logFilePath; } set { this.logFilePath = value; } } I’ve kept QBVersion, CompanyFilePath and ApplicationName as static because an application can access only one QuickBook file at a time thus all the instances of this class can easily share the information about Quick book and the company file. CompanyFilePath is the actual physical path of the quick book file through which data will be sent and received back and forth to the our application. ApplicationName is name of our application. The exact same name will be registered at QuickBook telling that our [application name] application needs to share some data with it and it should grant whenever there is a request to view or insert data from this application. SessionManager is the class which will open and close the sessions between our application and QuickBooks. For each transaction we need to create and then close such sessions. RequestBrokerLog and logFilePath are the variables used to log all the activities and transactions and their results done by our application with QB. Following are three overloaded constructors used: /// <summary> /// Default constructor sets the country, version and application name fields of the class /// </summary> public RequestBroker() { RequestBroker.QBVersion.country = “US”; RequestBroker.QBVersion.majorVersion = 6; RequestBroker.QBVersion.minorVersion = 0; sessionManager = new QBSessionManager(); CompanyFilePath = @”D:\shared\Wisdom.QBW”; // Default path to company file ApplicationName = “WITQBInterface”; // Default application name } public RequestBroker(string filePath) : this() { CompanyFilePath = filePath.Length > 0 ? filePath.Trim() : string.Empty; } public RequestBroker(string country, short majorVersion, short minorVersion, string filePath, string applicationName) { if (country.Length > 0) RequestBroker.QBVersion.country = country; if (majorVersion > 0) RequestBroker.QBVersion.majorVersion = majorVersion; if (minorVersion > 0) RequestBroker.QBVersion.minorVersion = minorVersion; sessionManager = new QBSessionManager(); if (filePath.Length > 0 && File.Exists(filePath)) CompanyFilePath = filePath; if (filePath.Length > 0 && File.Exists(filePath)) this.logFilePath = filePath.Substring(0, filePath.LastIndexOf(“\\”) + 1) + “QBInterface.log”; if (applicationName.Length > 0) ApplicationName = applicationName; } As you might have noticed our Vendor form uses only the second constructor which further calls the default constructor; the third constructor has been written for future use. More or less, all the constructors are performing the same task i.e. initializing and instantiating the data members of the class. Now comes the heart of this class; the method that actually gets data from Quick books. /// <summary> /// This method gets all the active vendors from QB matching given criteria /// </summary> /// <returns></returns> // Line numbers are marked for understanding the code and not the part of actual code public QBList<Vendor> GetVendorList(ref QBOperationStatus opStatus, bool completeInformation) { 01 QBList<Vendor> qblVendor = new QBList<Vendor>(); try { 02 opStatus = BeginSession(); 03 if (opStatus.OperationResult == QBOperationResult.Succeeded) { 04 IMsgSetRequest messageSet = CreateRequestMsgSet(); 05 IVendorQuery vendorQuery = messageSet.AppendVendorQueryRq(); 06 vendorQuery.ORVendorListQuery.VendorListFilter.ActiveStatus.SetValue(ENActiveStatus.asActiveOnly); 07 IMsgSetResponse responseSet = this.GetResponse(messageSet); 08 this.sessionManager.CloseConnection(); 09 opStatus = GetResponseStatus(responseSet); 10 IResponse response; 11 ENResponseType responseType; 12 if (responseSet == null || responseSet.ResponseList == null) opStatus.Message += “\r\n” + “responseSet is null.”; else { 13 for (int i = 0; i < responseSet.ResponseList.Count; i++) { 14 response = responseSet.ResponseList.GetAt(i); if (response == null || response.Detail == null) continue; 15 if (response.Type == null) opStatus.Message += “\r\n” + “responseType is null.”; else { 16 responseType = (ENResponseType)response.Type.GetValue(); 17 if (responseType == ENResponseType.rtVendorQueryRs) { if (response.Detail == null) opStatus.Message += “\r\n” + “response Detail is null.”; else { 18 IVendorRetList vendorList = (IVendorRetList)response.Detail; 19 for (int vendorIndex = 0; vendorIndex < vendorList.Count; vendorIndex++) { 20 IVendorRet vendor = (IVendorRet)vendorList.GetAt(vendorIndex); if (vendor != null) { 21 Vendor iVendor = new Vendor(); 22 iVendor.FillViewRequest(vendor, completeInformation); 23 qblVendor.Add(iVendor); opStatus.Message += “\r\n” + “Vendor retrieved successfully.” + iVendor.Name; } } } } } } } } } catch (Exception ex) { opStatus.Message += “\r\n\r\n” + ex.Message; } finally { 24 this.sessionManager.EndSession(); } 25 return qblVendor; } Now let’s quickly skim through this method line by line. Line 01 simply creates a QBList of vendors. Line 02 starts a session with QB. Method BeginSession() returns the result of session open attempt; if the session is successfully opened it will return our OperationStatus as successful; line 03 checks the same. Line 04 instantiates a message request object, this class is imported from namespace QBFC7. This object tells QB what kind of operation is about to be performed in this session. After message request object has been successfully instantiated, we’ll use this object to create a vendor query object with line 05. Line 06 sets the filter of the vendor query we just created. Currently I’m setting a very simple filter i.e. all the active vendors will be retrieved. Line 07 calls QB to actually get the list of vendors. responseSet object now contains all the vendor list. Line 08 closes the connection after the response has been received successfully. Line 09 gets the response status. Lines 10 and 11 are basically just references of IResponse and ResponseType and will be explained in short. Line 12 checks whether we received anything from QB in response to our query or not. If nothing was returned then we’ll simply display “responseSet is null.” Otherwise we’ll proceed to else block. In line 13 we’ll loop through each and every item in responseList object. Each item of responseList is a Vendor object, all we need to do is convert QB’s vendor object into our business vendor object. In line 14 we are getting the ith item of the list and seeing if it is null or not; if it’s null then just skip the rest of the part of the loop and iterate to next item. Line 15 is checking if the responseType has been set properly, if yes then in Line 16 I’m getting the response type, which according to my calculations should be VendorType. Line 17 is again checking whether the response type is correctly set or not. Too defensive programming, isn’t it? Trust me, its worth when you are dealing with QB. In line 18 I finally get the list of the vendors in IVendorRetList object. Now I’m ready to loop through this list and see how many vendors I’ve got. That’s what I’m doing on line 19. Interop QBFC7, is enriched with classes that can work for any kind of .NET programmer’s needs. For example IVendorRetList is for keeping the returned list of vendors from QB and to keep one vendor object at a time we have IVendorRet object. In line 20 I’m getting one vendor object from the list and in next line I’m checking if it’s not null then I’m good to get that interop library object into my business object. If I get a solid IVendorRet object in line 20 then in line 21 I instantiate my business object and in line 22 I call business object’s FillViewRequest (will be explained later) method to get all the information from IVendorRet object to my Vendor business object. In line 23, after I have the vendor object fully populated I can add it in my custom list object. After setting “successful message”, I’m closing the session in finally block in line 24 and line 25 returns the successfully created vendor list to form to be displayed in grid. As I promised that I’ll explain FillViewRequest of vendor object so let’s see line-by-line how this method is working. Vendor class is populated with two overloaded FillViewRequest methods. public void FillViewRequest(IVendorRet vendorReturn) { this.FillViewRequest(vendorReturn, true); } This method simply calls its big brother with a hard coded true parameter. And the big brother is as follows: public void FillViewRequest(IVendorRet vendorReturn, bool completeInformation) { 01 if (vendorReturn.Name != null) 02 this.name = vendorReturn.Name.GetValue(); 03 if (completeInformation) { 04 if (vendorReturn.CompanyName != null) 05(); } } The purpose of this method is to take IVendorRet object as a parameter and then convert and return it into our business object. For this purpose at line 01 I’m checking if Name property is not null (defensive programming, as usual), if not then I’m get its value in line 02. Line 03 is checking if complete information was requested then perform the similar procedure as we did in line 01 and 02 to get the values of all other properties. Line 04 and 05 is another example of doing the same. We are pretty much done with understanding how this application works; the only thing that is left in this is how to add a new vendor in QB through our application and that I plan to explain in very near future. Now is the time I dwell upon the issues that you might face while setting up QB company file for giving rights to an external application to make CURD (Create, Update, Read and Delete) transactions to it. So before you download the code and start testing the application, there are a couple of settings in QB you need to make. For an external application to be successfully able to make CURD transactions these are the steps you need to follow: - Open company file in QB. - Go to File menu and select Switch to Single-user Mode as follows - Next thing you need to do is open Preferences dialog box by selecting View menu and then preferences. - In preferences dialog box select Integrated Applications. - In this dialog box select Company Preferences tab. - Uncheck both the checkboxes and Add an application name as follows - difference between versions of Quickbooks, some programmers don’t see an “Add Application” button in above mentioned dialogue box. If you can’t see such a button, try skipping that step and move forward to next steps. Try running your .NET application while QB is still running, if connection is successful, QB will display a certificate for admin to approve. Approve that certificate and this will add your application in the list of Approved Applications in your Quickbooks. So that’s pretty much it is. I hope code snippets and their line-by-line explanations and screenshots will help some programmer to find some solution to his/her assignment. If it does then please don’t forget to give me your feedback on this article. P.S. After reading this article if you are interested in knowing more about QuickBooks integration, and if you are interested in seeing how to add data in QuickBooks through .NET application, click here. Its a very good article about .NET and Quick Books integration. Its difficult to find good articles on this topic and this one answers most of the basic questions for novice to professional users. Thanks Comment by Usman Ahmed — September 9, 2008 @ 9:19 pm Hi, this is a great article. I am trying to accomplish a similar thing in my environment. Can you please forward that zip file of this application to my email. I would really appreciate for your help on this. Thank you, Vijay Nandivada Comment by Vijay — August 4, 2009 @ 9:45 pm Hi SIr, I am also integrate quick books to desktop application. I have a problem , how can i connect to quick books file for retrieve data of quick books. Please provide me complete code of above code on my email id :- amitkumar51287@gmail.com Comment by Amit Kumar — March 28, 2012 @ 2:04 pm Amit, can you give me your hotmail or yahoo email address? i tried sending you the code on gmail but for some reason it’s failing. Comment by Mukarram Mukhtar — March 30, 2012 @ 1:55 pm Hi, Can you please send me source file to my email address prabupep@gmail.com Comment by prabupep — July 28, 2012 @ 9:50 am Hi,This is nice article please send complete sample application with zipped folder. my mail id:mallareddy.amireddy@gmail.com thanks, Mallareddy Comment by MallaReddy — June 11, 2013 @ 6:39 am That was awesome. In-depth, easy to follow and to the point. Really appreciate that. Many thanks. Comment by Shujaat — September 12, 2008 @ 10:45 am this article was very helpful to me. thank you very much for writing such an easy and comprehensive article. saved a lot of my time. Comment by khurram — September 12, 2008 @ 10:47 am nice article, where is source code? i have QB with single user license; can i still connect my QB file to my windows .NET application? Comment by Boris — September 15, 2008 @ 5:40 pm Thanks for your comments everybody. @ Boris: Yes you can connect your .NET application with single user licensed QB. But then the company file can be accessed by either your application or Quickbooks at a time. Consider your .qbw file as a database and by license only one user (Quickbooks or .NET application) at a time can access it. I hope that answers your question. Comment by Mukarram Mukhtar — September 21, 2008 @ 10:36 am Sir can u please give me its project becouse i tried lots of time to run as u metion but its generate error. if u give me project files so its might be easy for me to undersatnd and use it. thnx zeeshan Comment by Zeeshan — October 31, 2008 @ 4:36 am i m using dotnet Framwork 2.0 and visual studio 2005 so have get lots of error when i build the project plz explain me as soon as u can . i want to create a application which get the date from sqlserver 2005 and using .net transfer in quickbooks and fatch data from quickbooks and transfer in seqlserver 2005 using .net . daily this process will be accure if u know any thing realted it plz help me i will be thnnx ful to u plz provide me ur using email addres so it is easy for me to comunicate with u tnx Zeeshan Comment by Zeeshan — October 31, 2008 @ 5:23 am i tried to open it but it does not run its generate the errror i m using visual studio 2005 Comment by zeeshan — October 31, 2008 @ 11:57 am AOa Mukarram plx tell me how to cmunicate with quick book to .net i want to sent vender and item data from .net framwork is 2.0 to Quickbook professional 2008. and also get the infromation from quickbooks and send to .net visual studio 2005 so please tell me which step i wil follow i asw ur inetgration code but it is not runiing it genrate error at session manager. sessionManager = {Interop.QBFC7.QBSessionManagerClass} QBXMLVersionsForSession = ‘((Interop.QBFC7.QBSessionManagerClass)(broker.sessionManager)).QBXMLVersionsForSession’ threw an exception of type ‘System.Runtime.InteropServices.COMException’ Error Mesasge is: base {System.SystemException} = {”BeginSession method has not been called or it did not succeed.”} ErrorCode = -2147220468 I have confustion at this position plz telll me what i will do i m using sqlserver 2005 and visual studio 2005 .netframwork 2.0 i have install quickbooks 2008 professional . i have ad referance files are Interop.QBFC7 Interop.QBXMLRP2 this dll file was not avalible in 2.0 framwork so it did not add : System.Linq; i m waiting ur response tnx Comment by zeeshan — November 3, 2008 @ 5:25 am A very good article.Just browsed it and soon I am going to dissect it. I am a so called R n’ D champions!! Hoping to use QB Online edition. Let me know if you have any inputs. Thanks a bunch Comment by koms — November 4, 2008 @ 8:01 pm Thanks Koms & Zeeshan. @ Zeeshan I have sent you an e-mail with attached zip file, it includes the .NET project which integrates with Quick Books. There are two win forms in this project; one simply displays list of vendors (form shown in the article above) and the other inserts a new vendor in QB. This is a 100% working application. Please read the code and try to understand what is going on in it and how you can modify to get it working for you. As I said in the article, this integration would be very challenging for developers; and there can be one of 100s of reasons that are failing your integration. For me it is not possible to answer questions of every individual on the web. I hope you would understand that. @ Koms You are most welcome to dissect it🙂 Please let me know if you have any problems during this dissection; I’ll forward you the same zip as well. Enjoy good programming, programmers… Comment by Mukarram Mukhtar — November 4, 2008 @ 8:24 pm Hi, this is a great article. I am trying to accomplish a similar thing in my environment. Can you please forward that zip file of this application to my email. I would really appreciate for your help on this. Comment by jitin — February 19, 2010 @ 9:17 am Mukarram, Can u pls send me the zip files. (patil_komal@yahoo.com)Thanks I was planning to use visual studio 2008(framework 3.5). What version did u use?? Comment by komal — November 4, 2008 @ 9:22 pm Hi, Can u pls send me the project zip files. (johariqbal@gmail.com) Thanks Comment by Johar — July 22, 2009 @ 10:06 am Mukarram, Can you please send me the zip files as well? (andrew@andrewhamilton.com) I tried to build up the project from the code you provided but I must be missing something. Thanks, Andrew Comment by mouserblitz — November 18, 2008 @ 4:59 am Hi, Can you Please send me the Project as a Zip file. Thanks in Advance Comment by Talwinder — July 28, 2010 @ 9:29 am Hi, Do you know how to connect to QB with .NET using web connector? I had tried to use QBFC and QBXML, i can get what i wish but i don;t really know how to connect to QB using web connector. Please advice. Thank you. Regards, YB Comment by yb — December 1, 2008 @ 6:09 am @ Komal & Andrew: Project files have been sent to you; please let me know if you have any questions and don’t forget to give your feedback here in the comments section of the article. @ YB: No idea about web connector. My project was, connecting QB with .NET over the LAN and after it was done I couldn’t get much chance to further explore it. Comment by Mukarram Mukhtar — December 7, 2008 @ 3:00 pm Please send me the code at the given Email address and Also told me that Can we export data from SQL Sever to Quick Books.Reply as soon as poosible. Regards Bilal Comment by Bilal Jalil — December 15, 2008 @ 8:35 am hey Mukarram, Great Stuff, can you please send me the project files as well? Thanks n regards, Arshad Jamal Comment by Arshad Jamal — December 16, 2008 @ 9:43 am ey Mukarram plz tell me how we integrate sqlsever with quickBook.i want to transfer sql server database date into quickbooks.plz guide me. (Send me Code or link to My Email Address) Javaidnazaim@hotmail.com Comment by javaid — December 22, 2008 @ 3:38 pm @ Bilal & Arshad: I’ve tried to send you the source code a couple of times but every time I send you the e-mail I get e-mail failure notice. Either type in your correct e-mail or give me an hotmail id. @ Javaid: Project files have been sent to you; please let me know if you have any questions and don’t forget to give your feedback here in the comments section of the article. Comment by Mukarram Mukhtar — December 23, 2008 @ 2:26 am Hey Mukarram, Thanks for trying to send email. here is my hotmail id — aj_saifi@hotmail.com regards, arshad jamal Comment by Arshad Jamal — January 12, 2009 @ 10:40 am Hey I loved this article… in it you mentioned .” This is exactly what I am attempting and I was wondering if you have completed this article and/if you happen to have a working code example for it… Thanks so much for taking the time for all of this… it has cleared A LOT up!!! Sincerely Ernie Comment by Ernie — January 15, 2009 @ 3:52 am I just read some of the responses… would you mind also sending me the zip file… I would greatly appreciate it Thanks again Ernie Comment by Ernie — January 15, 2009 @ 6:26 am Hi Mukarram, Can you send me the code files at aaftab@svam.com. Aso please let me know the version of .net required as i read in your comments that .net 2005 is creating problems. Thanks, Aaftab Comment by Aaftab — January 22, 2009 @ 3:09 pm Hi, Great article. I think, nobody has given complete article on this so far. Thanks a lot. Could you please send me the project files? Thanks in advance. Ravikumar pvsravikumar@yahoo.com Comment by Ravikumar — February 2, 2009 @ 9:43 am Hi Can you send me the code files at cherukumalla@gmail.com Comment by Srinivas Ch — February 2, 2009 @ 9:44 am Why not attach the source files to this page? Thanks for sharing your solution, if possible please add me to the email list. Comment by praet — February 12, 2009 @ 5:43 pm @Praet: Dude I tried a couple of times to find a way of attaching a zip or rar file, containing project files, with this article but to no avail. If you know how to do it, please let me know. In the meantime, enjoy the code I sent you… Comment by Mukarram Mukhtar — February 15, 2009 @ 5:47 am Hello webmaster I would like to share with you a link to your site write me here preonrelt@mail.ru Comment by Alexwebmaster — March 3, 2009 @ 11:55 am Hi Mukaram, I need to query the bills in QB using billQuery. I got the TxnID and EditSequence of the bill. How i should pass the value TxnID and EditSequence in BillQuery to get the bill? Comment by RP — March 4, 2009 @ 1:12 pm This is a great article. I have encountered many issues trying to navigate the same things. Do you have any more articles on this topic? Can I please get a copy of this project? My email is jbeerman7@hotmail.com. Thanks! Comment by Jason — March 5, 2009 @ 7:50 pm I would also appreciate it if you would send me the zip file. From reading the other comments I suppose I should also ask what version of .NET and Visual Studio you are using to create your app. Looking forward to the continuation of your posting. Are you still planning the addition? Thanks very much for your efforts! Comment by Curt — March 8, 2009 @ 3:34 am @ RP: I have abso-bloomo-lutely No clue on this dude. Do you think this project’s source files would give you any help? I can send you a zip file (for free, really!)🙂 @ Jason & Curt: I’ve sent you the zip file. Feel free to give me you feedback here (nobody ever does!) @ RP, Jason, Curt: Fellas, I couldn’t get much chance to work in this field after I completed that project. And frankly, I didn’t enjoy much working with this integration. QB people ought to give some more programmer friendly APIs. So far I don’t plan to write more on this topic. A nice article on .NET authentication, however, is coming up soon; in case you are interested, stay tuned😉 Comment by Mukarram Mukhtar — March 10, 2009 @ 2:44 am Hi Mukaram, awesome article. i’ve to integrate .NET with Quick Book. if you send me this project source then dat will be great help. ma mail address: samirmahmood_666@yahoo.com thanx Comment by LAMB OF GOD — April 2, 2009 @ 12:15 pm Hello Mukaram, I am actually working on a C# app. to integrate quickbooks with mysql database. I got the connection working between C# and mysql already but cannot figure out how to integrate C# with quickbooks. I have all the pre-requisites and wanted to ask you if you could send me the zip files as well via email. Thank you and awesome work. Comment by Luluboy — April 7, 2009 @ 9:25 pm Hi, Great Article. I would like to appreciate your affort in writing this article. Great work. Can you please sent me the project code/files. Thanks in Advance.. Comment by Baburam — April 17, 2009 @ 1:13 pm Hello sir, I have studying MCA final year and doing project year. So, lots of doubt in my mind. Please clear my doubts and also give some way of working routes. My application contains customer, product and invoice then how to connect with QuickBooks. Please give one by one step and integrate the data’s finally creating an invoice. Please suggest me my questions. Comment by Lakshmi — April 30, 2009 @ 9:42 am Sir, I would appreciate if you send the code to me. Thanks in advance. Comment by Dmitriy — May 3, 2009 @ 3:13 am This is a great Article! I have been looking for directions on how to integrate our in house application and this seems to be a great start WOuld it be too much trouble to ask you to send me a copy of the test appliction you mentioned so I can work out a number of issues I am having? Comment by Bill Gerold — May 7, 2009 @ 2:03 pm Hi can you please provide me the sourcecode for invoking the Quickbooks UI using .net2.0 Thanks Chandra Comment by chandrasekhar — May 12, 2009 @ 12:49 pm For all my dear readers, following is an interesting correspondence with one of my readers. It has been sorted in descending order, last e-mail on top. I hope you’ll enjoy it: ________________________________________ Dude!!! Are you gonna do anything by yourself or you want me to spoon feed you on each step? 😀 ________________________________________ Dear Mukarram, You wanted feedback on your article. It is really helpful and friendly. I have one little doubt though. 04 this.grdVendors.DataSource = new QBList(); 05 QBList qblVendor = broker.GetVendorList(ref opStatus, true); 06 this.grdVendors.DataSource = qblVendor; … After that (Line 04), I’m assigning an empty QBList of type Vendor to my grid control to erase all the previous data, if any, present in the grid… Are you sure we need that? It seems that reassigning data source on line 06 clears all previous data. When I commented out the 04 line, and pressed the Get List button several times, the number of records in the grid didn’t change. Can you suggest any materials on how to write checks using QuickBooks from my application (if it is possible at all), and how to update QB data file according to a SQL Server database? I really appreciate your generous help. Sincerely, Dmitriy ________________________________________ Yes, that worked! Thank you so much! Dmitriy ________________________________________ Can’t you see an “Add Application” button anywhere around this dialog box? As long as I remember there was a button which would let you add an application in this list but it will be hidden if your QB settings are different than as explained in the article. Since I don’t have a QB license any more, I can’t open a QB and look for this button for you. I would suggest, double-check that you’ve followed all the steps as explained in the article. After that, if you still. Hopefully that would help, let me know. Regards, Mukarram ________________________________________ Thank you very much! You wrote: “Uncheck both the checkboxes and Add an application name as follows”. But the problem is that I don’t know how to add the application name. The empty list of such names seems to be disabled. Could you please tell me anything about that? Thanks. Dmitriy ________________________________________ Hi Dmitriy, I’ve never seen this error before and therefore absolutely no idea about it. My guess would be, it’s related to access permissions in Quickbooks; and since surprisingly error message is also quite explanatory and programmer friendly, did you try giving your .NET application access rights on your QB file? Please see the last part of my article where I explain how to give these access rights. The part which starts from: “Now is the time I dwell upon the issues that you might face while setting up QB company file for giving rights to an external application …” Unfortunately I don’t have QB license any more; and menu options and dialoge boxes explained in the article might slightly differ from yours depending upon the QB version you are using. So on that part you are on your own 🙂 Hope that would help. Happy programming! Mukarram ________________________________________ Dear Mukarram, Maybe you could answer one question. After I ran your application, I received the following exception: Connection opened successfully. This application is unable to log into this QuickBooks company data file automatically. The QuickBooks administrator must grant permission for an automatic login through the Integrated Application preferences. If such permission was already granted, the administrator must revoke permission, save preferences, then grant the permission again. Could you tell how I can solve this problem? Thank you very much, Sincerely, Dmitriy ________________________________________ Hello Folks, Attached herewith is the zip file that you requested, it includes the .NET project which integrates with Quick Books. There are two win forms in this project; one simply displays list of vendors (form shown in the article) and the other inserts a new vendor in QB. This is a 100% working application. I hope you’ll be able understand what is going on in it and see how you can customize it for yourself. I’ll wait for your feedback. Thanks, Mukarram p.s. Sorry for the late reply baburam Comment by Mukarram Mukhtar — May 15, 2009 @ 9:41 pm Dear Mukarram I was glad to see someone creating a clear and sharp knowledge solution. I would like you contact me at my email. I would like to get your assistance on Quickbook integration. Thanks in advance Ran Comment by Ran — May 28, 2009 @ 8:29 pm Ran, You can ask your question here; if you need the source code, please let me know. Thanks Comment by Mukarram Mukhtar — June 1, 2009 @ 7:48 pm Hi can you pls send me the source code.. thank you.. mayil Comment by Mayil — March 1, 2012 @ 6:37 am Mayil, I’m unable to send you the e-mail. I keep on getting MAILER-DAEMON’s failure notice. Are you sure you’re typing in your e-mail address correctly? Comment by Mukarram Mukhtar — March 1, 2012 @ 5:17 pm Hi Mukarram Mukhtar, Thanks for your reply. I received your reply which says about the Failure notice in my mail inbox. Then I dont know the reason why you are not able to send me the source code… Again, My mail ID is : mailtomayil@gmail.com I am using Interop.QBFC11 assembly. The code: “opStatus = BeginSession();” not accepting. Can u tel me which class uses BeginSession() method. This method from the above assembly is void method. BeginSession(string qbFile, ENOpenMode openMode) But ur code says it should return some status like: opStatus = BeginSession(); pls resend me full the source code. Thanks Mayil Comment by Mayil — March 2, 2012 @ 6:41 am Can you give me your yahoo or hotmail e-mail id? Maybe that will work. Comment by Mukarram Mukhtar — March 3, 2012 @ 1:47 am My yahoo id mailtomayil@yahoo.co.in Comment by mayil — March 3, 2012 @ 5:37 pm Dear Mukarram, Thank you for the informative article. I found it very useful. Can you please let me know when do you plan to publish the code that shows how to migrate data to and from QB and SQL Server database via stored procedures? Thank you, Charmen Comment by Charmen — June 2, 2009 @ 3:03 pm Charmen, The project of data migration to and from QB and SQL Server is on top of my TODO list; however, I can’t give you an exact date at this point. What you can do is, subscriber to RSS feed of my home page; this way you’ll get an update whenever I’ll post that article. Thanks Comment by Mukarram Mukhtar — June 2, 2009 @ 4:16 pm Hi Mukaram, Great article. I also have to integrate .NET with Quick Books. I would greatly appreciate it if you could send the source as well. Regards, David Comment by David Cohen — June 8, 2009 @ 8:53 pm Great article. I also have to integrate .NET with Quick Books. I would greatly appreciate it if you could send the source as well. mallesh.varri@gmail.com Comment by Mallesh — June 24, 2009 @ 7:27 am Mallesh, the e-mail id you provided is not valid. I tried sending you the source code but got a postmaster failure message. Comment by Mukarram Mukhtar — June 24, 2009 @ 1:57 pm Hi Mukhtar, Iam glad you replied,Thanks a lot.Sorry for giving u the trouble.Here are my mailId’s mallesh.varri@gmail.com mallesh.varri@hotmail.com malleshv@convene-tech.com Plz try sending to these mail Id’s Once again thanks a lot. Comment by Mallesh — June 25, 2009 @ 5:19 am Hi Mukarram. Nice article with deialed information. Can you send me the zip file at bcamca_deepak@yahoo.co.in. I want to build on the project. Thanks and Regards Deepak Comment by Deepak — June 25, 2009 @ 11:29 am Hi, Can u pls send me the project zip files. (johariqbal@gmail.com) Thanks Comment by Johar — July 22, 2009 @ 10:25 am Hi, Can you please send me the source code. thanks in advance KHAN Comment by Khan — July 22, 2009 @ 11:01 am Hi Mukarram, I need the source code for the my assignment, please share me the code. thanking you Scott Comment by Scott — July 22, 2009 @ 11:56 am Johar, Khan & Scott, I tried sending you the source code but I received a postmaster failure message. My Hotmail account creates problems sometimes while sending e-mails to Gmail Ids; try giving me your Hotmail or Yahoo Ids. -Mukarram Comment by Mukarram Mukhtar — July 22, 2009 @ 12:15 pm AOA, try on this hotmailID thanks Khan Comment by Scott — July 22, 2009 @ 12:26 pm Oh so Johar, Khan and Scott, all 3 of them are actually one person? :-O Man, you didn’t have to request for the source code by using different names🙂 The source code is free for everyone; I would send you the code even if you tell me your name is Laaloo Parshad😀 Comment by Mukarram Mukhtar — July 22, 2009 @ 1:19 pm AOA, Please send on this email:(johar.khan@hotmail.com) thanks Comment by Johar — July 22, 2009 @ 12:48 pm Code is on its way Johar; please check your e-mail in a few minutes. If you don’t see my e-mail in next, let’s say 30 minutes, please let me know. Comment by Mukarram Mukhtar — July 22, 2009 @ 1:21 pm Thanks for sending me the code. I am getting this error while running your application Retrieving the COM class factory for component with CLSID {FC3C4882-C13E-46E7-96F1-CEE3133207B7} failed due to the following error: 80040154. Please guide me Comment by Johar — July 24, 2009 @ 4:36 am Johar, The source code I sent you was for reference and help. Albeit the application I sent you is a 100% working application, but if it is failing on your machine then please put some of your own effort to resolve it. It is really very difficult for me to trouble shoot everyones’ projects across the globe. I hope you would understand this. Thanks, Mukarram Comment by Mukarram Mukhtar — July 24, 2009 @ 2:39 pm Hi Mukarram, I have to integrate my application with quickbook and im in trouble!! It would be great help if you send me the source code. Thanks Samir Mahmood Comment by Samir Mahmood — July 28, 2009 @ 8:49 am Hi Mukarram, my add: samirmahmood_666@yahoo.com Thanks Samir Mahmood Comment by Samir Mahmood — July 28, 2009 @ 8:53 am Hi Mukarram, Nice and rare article on QuickBooks integration. The explanation of topic is also in a neat manner. I have just started working with QuickBooks. Found this article while googling for tutorials on it, somehow landed on your page and couldn’t leave this page without giving a feedback. Really great job. By the way, can you please send the code files to me too? My id is pranav(dot)net(at)live(dot)in Keep Going… All the very best! Best Regards, Pranav Ainavolu Comment by Pranav — July 31, 2009 @ 8:08 am Thanks Mukarram for the explanation Could you please send me the complete code to my email j4v4jive@yahoo.com Thanks in advance Comment by John — August 3, 2009 @ 8:19 pm hi, this is very good article. I am trying to accomplish the same. Can you please forward me that code .zip file to my email address which would be a very great help for me. Thank you, Vijay Comment by Vijay — August 4, 2009 @ 10:00 pm Vijay, For some bizarre reason I’m unable to send e-mail from my hotmail id to google addresses. Give me your hotmail or yahoo id so that I can send you the zip file. Thanks, Mukarram Comment by Mukarram Mukhtar — August 5, 2009 @ 12:10 am hello, can u mail the source code of the above to the id shanaj.ml@gmail.com . Its not working for me. Please. thanks Comment by Shan — August 10, 2009 @ 11:22 am hai, can u mail me the source code . My yahoo id is shanaj_ml2000@yahoo.com Thanks Comment by Shan — August 10, 2009 @ 1:23 pm Hello Everybody, I can’t send e-mails to gmail address so IF YOU NEED THE SOURCE CODE, GIVE ME YOUR HOTMAIL OR YAHOO ID. Thanks… Comment by Mukarram Mukhtar — August 10, 2009 @ 5:55 pm i guess you have your .net application and QB on the same machine, so this code works perfectly well for you. i need to do it remotely. how do i achieve that. the QBW file that i wish to access is sitting on 1 server and my .net application is on another server. Also i understand if you switch the account to multi – user, QB can be used simultaneously by my .net application and the person who is trying to insert some information in QB. Correct ? Any help would be appreciated. Thanks, Soniya. Comment by soniya — October 8, 2009 @ 8:12 pm Both of your assumptions are accurate. I’ve connected my .NET application with a QBW file not only when QBW file was on the same machine but also over LAN and VPN. So as long as there are no network access problems or no folder access rights issues, you should be able to connect remotely. Regarding multi-user, yes, .NET application and any other users can access QBW file simultaneously in multi-user mode. First let QBW file allow the application to access it, as explained in the last section of my blog. Once QBW file recognizes .NET application as an authorized application, then the application is just like any other user accessing the QBW file. I hope that answers your question. Comment by Mukarram Mukhtar — October 9, 2009 @ 1:57 pm Have you worked on fetching the sales order query. I am unable to find some fields in it. Can you please help me understand the IDN OSR !! Please email me back at soniyaw@yahoo.com Thanks, Soniya. Comment by soniya — October 14, 2009 @ 9:34 pm This is wonderful! Can you send the source to this account: jaredh@redmondinc.com Comment by Jared — October 15, 2009 @ 2:50 am @ Jared: Source code sent! @ Soniya: Sorry buddy, I’ve absolutely no idea of IDN OSR… Comment by Mukarram Mukhtar — October 15, 2009 @ 3:21 pm Hi Mukarram Sir, I think you have done an excellent job.I wonder how much dedication you put for this post.I am sure all developers will take it as a complete reference.Great job!!!!!! Please send me the zipped project file as I am getting some error when i attempt to implement the same. Can I use QB trial version for a test?.If QB trial is available,please give the link to download it. Thanks a lot and best regards, Binto Thomas Comment by Binto — October 30, 2009 @ 8:04 am meet.binto@gmail.com is a wrong e-mail address, I’m receiving e-mail failure notice. Comment by Mukarram Mukhtar — October 30, 2009 @ 2:14 pm I appreciate your effort for my request. you can mail me to meet.binto@gmail.com or meet.binto@yahoo.com. meet.binto@gmail.com is actually valid and I have been using since 5 years. Thanks & Regards Binto Thomas Comment by Binto — November 3, 2009 @ 4:42 am Thanks a lot for the effort taken for me.Actually meet.binto@gmail.com is valid since 5 years.You can mail me to meet.binto@gmail.com or meet.binto@yahoo.com Thanks & Regards, Binto Thomas Comment by Binto — November 3, 2009 @ 4:49 am The source code is great! It is important to tune QBVersion in the RequestVendor.cs file in order to achieve connectivity. I’m using a later version of Quick Books, for example, so I needed to set my attributes to: RequestEmployee.QBVersion.country = “US”; RequestEmployee.QBVersion.majorVersion = 8; RequestEmployee.QBVersion.minorVersion = 0; Sir, do you have examples of using stored procedures to talk to a database? I would like very much to see how something like spName works, for example. Or if anyone knows about an informative website? Thank you, again, for your hard work and wonderful examples! Comment by Jared — November 3, 2009 @ 6:09 am @ Binto: It seems your yahoo e-mail id worked. Let me know if you still didn’t get it. @ Jared: Right now I don’t know about any web link which does the task you mentioned. I’ll keep on looking and will let you know if I find anything good. Comment by Mukarram Mukhtar — November 3, 2009 @ 2:38 pm Mukarram:Thank you very much for your response around at such a lightening speed.I expect you will help me,if I require any assistance in building up the project.Once again thanks a lot. Comment by Binto — November 4, 2009 @ 4:21 am Dear Mukarram Mukhtar, ur source is so great! If possible, I wanna get ur source code. thanks, SuMay Comment by SuMay — November 4, 2009 @ 8:11 am Dear Mukarram, Great Stuff, can you please send me the project files as well? My id shwe713@gmail.com shwetadhake@rediffmail.com Comment by shweta — November 4, 2009 @ 11:36 am Your code is quite good can u mail me the code for the same My id is rameez7585@yahoo.co.in Thanks Comment by Rameez — December 9, 2009 @ 10:33 am Your code is quite good can u mail me the code for the same My id is binkoshy2@gmail.com. Thanks Comment by Binu — December 22, 2009 @ 6:57 am binkoshy2@gmail.com is an invalid e-mail address, I’m getting ‘mail delivery failed’ notice. Comment by Mukarram Mukhtar — December 22, 2009 @ 4:46 pm Dear Mukarram, I also have to integrate QB with C#.net in my web app. So, can u pls send me the source code? It’ll be much help Comment by Istiaq Ahmed — January 13, 2010 @ 9:18 am oh i forgot to mention my email @: prantor_23@yahoo.com Comment by Istiaq Ahmed — January 13, 2010 @ 9:20 am Hi Mukarram, I have found your article very helpful, but am having trouble getting a working example. Would it be possible to email me the zip files for the solution to my email address above? Comment by Joel — January 18, 2010 @ 10:31 pm this is very good article and your effort is appreciable. I am trying to accomplish the same. Can you please forward me that code .zip file to my email address Comment by Thanu K — January 27, 2010 @ 3:55 am sorry i forgot to mention my email thanukk@yahoo.com Comment by Thanu K — January 27, 2010 @ 3:57 am Great article! Can you forward source code to my email bavna14@yahoo.com Comment by bavna — January 31, 2010 @ 2:49 pm very Interesting and .. helpful .. thank you for your great work Comment by Ganesh — February 1, 2010 @ 6:15 am Hello Everybody, I sincerely thank you all for your appreciation and positive feedbacks. Like always, please do not hesitate asking me for any kind of help related to my articles. Regarding making source code automatically downloadable, as much as myself want to make this possible, unfortunately, I’m unable to find any way in wordpress domain to achieve it. Please continue asking for source code that I can forward to your e-mail addresses. Again, thank you all for your comments and all who thanked me for writing these articles, you are always most welcome🙂 Best regards, Mukarram Comment by Mukarram Mukhtar — February 1, 2010 @ 2:16 pm thanks for your work. it is very help! could you send me the project files to danewbie@yahoo.com Comment by Dan Ewbie — August 3, 2010 @ 11:33 pm good work! It is very helpful. Could you send project files to danewbie@yahoo.com? Comment by Dan Ewbie — August 4, 2010 @ 2:23 am Can you please forward source code to my email gknaravi@gmail.com thanks in advance🙂 Comment by Ganesh — February 2, 2010 @ 9:33 am Oopss! gknaravi@gmail.com is a wrong e-mail id; every time I try to send you the source code, I get failure notice. Comment by Mukarram Mukhtar — February 2, 2010 @ 2:53 pm Dear Mukarram, Nice article.. Can u email the project files to ‘jazeel123@hotmail.com’ or jazeelkm@yahoo.co.in‘ Thanks Jaz Comment by Jazeel — March 16, 2010 @ 8:47 am Hello Mukarram, Could you please email both quickbooks projects if possable to p_cusickATyahooDOTcom Also I only have Quickbook simple Start 10 for testing would that work or will I need to download a demo version? Thank PQSIK Comment by PQSIK — March 16, 2010 @ 8:38 pm Dear Mukarram, Nice Article Could you email the project files to ‘srinu.gandla@gmail.com’ Thanks srinivas Comment by Srinu — March 17, 2010 @ 7:03 am Srinu, I tried sending you the email but got ‘Email Failure’ notice because SMTP server couldn’t find your id. Comment by Mukarram Mukhtar — March 18, 2010 @ 7:11 pm it has problem with connection and also beginsession() function does not work..its defination does,nt given Comment by sadia — April 9, 2010 @ 9:37 am kindly send me source code at this id.ssarwar16@yahoo.com Comment by sadia — April 9, 2010 @ 10:35 am kindly send me the souce code at chuchabrown@yahoo.com. Thanks, Comment by chucha — April 11, 2010 @ 3:47 pm it’s great posting, this is all I need. kindly send me the source code at this email id transcore_e@hotmail.com. thanks in advance. Comment by Transcore — May 3, 2010 @ 4:30 am Hi Mukarram, Would you please send me your code? My email: trendepru@yahoo.com Thanks, Dung Nguyen Comment by Dung Nguyen — July 5, 2010 @ 8:03 am Hi Can you please send me the code, I am in much needed ra@mtccrm.com or rakesh.raipur@gmail.com I liked the way you have explained the things. Its relly cool yar Comment by rakesh agarwal — July 24, 2010 @ 10:51 am HI Can you send me code on the following mail id khajamohiddins@hotmail.com Regards Khaja Comment by Khaja — July 26, 2010 @ 11:35 am Hi, Can you Please send me the Project. Thanks in Advance Comment by Talwinder — July 28, 2010 @ 9:31 am talwindersinghbajw@gmail.com Comment by Talwinder — July 28, 2010 @ 9:37 am The e-mail id you gave is wrong, Talwinder. I’m getting mail sending failure message. Comment by Mukarram Mukhtar — July 28, 2010 @ 2:09 pm I would also like a copy of the project. Thanks Comment by Bob Mercier — July 31, 2010 @ 8:35 pm Hi, Could you please send me the code base for this? Thanks, Santosh. Comment by santosh — August 16, 2010 @ 4:13 pm Hi , Could you send me code at santosh_rec@yahoo.com Comment by santosh — August 16, 2010 @ 4:14 pm Hi there, could you forward me the code as well to erikhome@hotmail.com ? Thanks for posting this!!🙂 Comment by erik — August 26, 2010 @ 1:18 am I like your article, it’s great… could you email me the code? My email is edgardoalexiscorrea@hotmail.com thanks for everything😀 Comment by Edgardo — August 26, 2010 @ 8:37 pm Great Article for QuickBook Integration. Can you send me the source code for this article? My e-mail ID is pinky_1863@yahoo.co.in Comment by Pinky Patel — August 27, 2010 @ 2:35 pm Can you please send me the source code. Comment by Ajit Sanghera — September 17, 2010 @ 7:59 am Send me the source code on ajit@esoftech.com or sangheraajit@yahoo.com Comment by Ajit Sanghera — October 11, 2010 @ 6:37 am Can you please send me the source code Comment by Ajit Sanghera — December 3, 2010 @ 11:31 am Can you please send me then source code @ g.k.venkata@hotmail.com Thanks a lot. Comment by venkata — September 28, 2010 @ 6:08 pm Ajit & Venkata, I tried to send e-mails to both of you but I got an “e-mail failure” message that the e-mail addresses you gave are invalid. Too bad you guys can’t even type your e-mails correct. Thanks, Mukarram Comment by Mukarram Mukhtar — September 29, 2010 @ 1:48 pm I’ve been recently tasked to pull data from quickbooks and provide projections via excelspreads. any chance you can forward the code? it would be a big help! Comment by Joe — October 8, 2010 @ 5:16 pm Great article. It’s the first one I see with quickbooks and .net application. Can you send me this example please. It would be very appreciate. sstgelais@pcp-canada.com Comment by Tommy — October 8, 2010 @ 3:57 pm thank you very much for the source code of this project. It will be very usefull. Comment by Tommy — October 12, 2010 @ 2:51 pm you are very welcome, happy programming!🙂 Comment by Mukarram Mukhtar — October 12, 2010 @ 6:17 pm I like your artical.I have also integrate .Net application with quickBooks.Can you provide me source code on anant.radadia@gmail.com.It would be very appreciate. Comment by anant — October 21, 2010 @ 8:03 pm very Nice article Can you provide me source code on debajyoti2005in@gmail.com.It would be very appreciate. Comment by Debajyoti — November 8, 2010 @ 11:28 am hello Mukarram, this really a nice article but i have some problem regarding to this .i’ am very new to the quickbook .my problem is that i want to integrate quick book with .net from my system.the quickbook resides on server.so how can i do this? pls guide me if you can. thanks. Comment by Neha — December 15, 2010 @ 4:46 am will you please mail your code me on neoneha.mathur@gmail.com i want to see that if it help me out in understanding this quickbook integration with .net. Comment by Neha — December 15, 2010 @ 8:17 am Please send me the source code for this example on vasanvas@mail.ru. I write a program to work with data collection terminals with one hand and a QuickBooks files on the other hand. I’m using Framework 3.5, VB.Net and VisualStudio 2008. Thanks for advance… Comment by Andrey — January 8, 2011 @ 11:50 am that’s great Mr. if u can send me the source code for this application as i need to integrate my web application with multi quick book’s clients to insert invoices in their quick book Comment by Mahmoud — February 15, 2011 @ 3:57 pm Mukarram, would greatly appreciate if you could send me the source code of your sample application. Thanks in Advance Ali Comment by Ali — February 17, 2011 @ 7:41 am would greatly appreciate if you could send me the source code of your sample application. Comment by Mitesh — May 17, 2011 @ 6:00 am Could you please send the source? I’m still having problems. Thanks! Comment by Luis — May 30, 2011 @ 7:29 pm hi please send me the source code.. Comment by sundar — June 8, 2011 @ 10:22 am 33.I have been following both your tutorials on connecting to quickbooks. Please can you send me the source code. Here is my email address thindo@yahoo.com Comment by thindo — June 13, 2011 @ 4:11 am hello can u send me the source code my email id is ashu.sajwan@gmail.com and yahoo id is ashu_cool490@yahoo.co.in Ashish sajwan Comment by ashish sajwan — June 21, 2011 @ 6:53 am already sent it to you, do you want me to send it again? Comment by Mukarram Mukhtar — June 21, 2011 @ 2:05 pm Hi Great articles please can u send me the Source Code Comment by Faraz — July 4, 2011 @ 11:48 am Can I also get the source code zip file. Appreciate your time and effort. Thanks! Muthu Annamalai Comment by Muthu Annamalai — July 5, 2011 @ 1:37 am can you please send code for article. very nice. my email is edsmith.21@gmail.com Comment by ed — July 7, 2011 @ 8:07 pm Nice Article I just want to know that is it web application or window application which you integrated with quickbook? thanks and regards, Dipti Chalke Comment by Dipti Chalke — July 16, 2011 @ 12:59 pm windows application. Comment by Mukarram Mukhtar — July 18, 2011 @ 4:36 pm Hi, nice article, is it possible to obtain a zipped copy of your source code? my email: romea80@gmail.com many thanks! Comment by akyatbahay — August 8, 2011 @ 3:29 pm Hi, Can u please send the code to smk.mercy@gmail.com Comment by Mercy — August 10, 2011 @ 8:11 am hi Comment by kunni — August 10, 2011 @ 8:29 am Hi, Can u send the source code to smk.mercy@gmail.com Thanks, Mercy Comment by kunni — August 10, 2011 @ 8:39 am Could you send source code to : sarith_mic@yahoo.com, Thank u very much Comment by sarith — August 13, 2011 @ 8:48 am I’m using Framework 3.5, VB.Net and VisualStudio 2008. Could you send source code to toh.sarith@gmail.com Comment by Sarith — August 13, 2011 @ 8:50 am Great article! Would you please send the source code to leslievp74@yahoo.com? Thanks. Comment by Leslie Van Parys — August 20, 2011 @ 9:39 pm can you please send me the source code to raghavendraprasadb@hotmail.com Thanks in advance, Raghu Comment by raghu — August 22, 2011 @ 9:10 am I have created the connection with QB and able to access the invoice in the QB. When i try to debug in .net i got erro like “This application is not allowed to log into this QuickBooks company data file automatically. The QuickBooks administrator can grant permission for an automatic login through the Integrated Application preferences.” But i can access the invoice withour running debug. Can you please help me Comment by Anandakumar — August 22, 2011 @ 9:57 am Hi Guys, I have integrated the quickbook with C# application. Any one need help please contact me at anandakumar.hc@payoda.com Comment by Anandakumar — August 23, 2011 @ 4:22 am Dear Mukarram, Nice article. Can you please forward source code to my email reda_mechtri@msn.com thanks in advance Comment by Reda — August 25, 2011 @ 6:23 pm Can you mail me source code. Because in vendor class IVendorRet show assembly reference not found Comment by manish — September 8, 2011 @ 3:19 pm Manish, no please, no thank you, no praise of the article? Why don’t you ask one more time, and I’ll be more than happy to forward you the code, if it meets my nicely-asked criteria😉 Comment by Mukarram Mukhtar — September 8, 2011 @ 3:30 pm sir i am a beginner.. my boss is given me a task to integrated quickbook app withi C# .net application. I don’t know how to prepare quickbook but i had good knowledge of C#.. Can you give me a demo with screenshot that how to run the simple application… Pls. sir help me its Thanks… Comment by Rohit Kesharwani — September 9, 2011 @ 11:47 am So you think the screenshots and the demo in the above article are not good enough? Comment by Mukarram Mukhtar — September 9, 2011 @ 2:03 pm I have sdk Quickbook10.0 but i do not have a quick book software…. give me a link from where i can download and use it successfully. thanks. Comment by Rohit Kesharwani — September 9, 2011 @ 11:50 am You can download Free Trial version Quickbooks from the following link. But in order to get a professional version you’ll have to buy it. Probably your boss needs to spend some $$$ on that. Comment by Mukarram Mukhtar — September 9, 2011 @ 2:04 pm This blog is wonderful. There is generally all the correct information and facts at the guidelines of my fingers. Thank you and maintain up the excellent work! Comment by Danyell Lautz — September 11, 2011 @ 11:40 pm Thanks for your appreciation Danyell🙂 Comment by Mukarram Mukhtar — September 12, 2011 @ 1:44 pm Hi Mukarram, Can you, please, sind me .zip file with your demo application? Thank you. I appreciate your help Comment by Vlad — September 12, 2011 @ 5:06 pm I also, think this is great article…I am using VS 2010 and would be very appreciative if you would provide me with demo app that you are describing here…. -Vlad Comment by Vlad — September 12, 2011 @ 5:18 pm Hi, Great work and great article. I would like to appreciate your effort in writing this article. Can you please sent me the project code/files. Thanks in Advance.. Comment by Baburam — September 21, 2011 @ 11:59 am Great work….!!! Please send me source on my mail id – ankur.kalavadia at billcall.net adkalavadia at gmail.com Thanks in advance…..Keep it up. Comment by Ankur Kalavadia — October 8, 2011 @ 5:45 am great article. this will give clear idea about the quickbook integration. Please send me the source on my mail id. mohankmr86@yahoo.com. thanks in advance. Comment by Mohan — October 15, 2011 @ 5:03 am Hi, I have similar requirement as above mentioned. Can you please send the source code to me. My email ID is rajendra84prasad@gmail.com Thanks Comment by Rajendra — October 27, 2011 @ 9:36 am Hi, I have similar requirement as above mentioned. Can you please send the source code to me. My email ID is jdp221@comcast.net I have been killing my self trying to find info on the web. This is a great article. Great job! Thank you in advance for sending. Comment by Jay Patel — November 3, 2011 @ 11:29 pm I would also like the code file if possible, nguyenjg AT gmail.com Thanks.. great article Comment by jgnguyen — November 22, 2011 @ 11:48 am Can you please send the source code to me. My email ID is nishaverma.acs@gmail.com Comment by nisha — December 22, 2011 @ 6:15 am Nisha and Jgnguyen, I tried to send you the source file but I got Failure Notice on your e-mail addresses. Type your e-mail ids carefully, can you? Comment by Mukarram Mukhtar — December 22, 2011 @ 8:08 pm that is the correct email nguyenjg is the email address with (gmail.com) domain thanks again. Comment by jgnguyen — December 22, 2011 @ 8:23 pm how to get to know invoices is paid or not programmatic using c# Can u please provide code for this. and sample program. Comment by ummer — December 24, 2011 @ 12:14 am Very good article Mukarram Mukhtar. From the last three days i am trying to connect to QB. This article is very heplfull to me. Sharing your knowlwdge is very good Mukarram Mukhtar. you done a very good job and helping the people like me. can u please send me the source code so that i can able to implement this task very easily. My email id: bhanuprakash1207@gmail.com Thanks in advance Mukarram Mukhtar. Comment by bhanu prakash — December 24, 2011 @ 7:16 am Very good work. Can you please send me the source code. My email ID: bprakash1207@gmail.com Thanks in advance. Comment by prakash — December 25, 2011 @ 8:10 am Very good article. Can you please send me the source code. Email: trustfully11@gmail.com Thanks… Comment by David R — January 8, 2012 @ 3:26 pm Can you please share the source code. My email id rajendra84prasad@gmail.com Thaks, Rajendra. Comment by Rajendra — January 10, 2012 @ 9:24 am Good article with layered structure.can u please send me the source code to my mailid:srikanthreddy.gandluri@gmail.com Comment by Srikanth — January 11, 2012 @ 9:00 am David and Srikanth, I’m getting E-mail Sending Failure notice when I try to send you guys the source code. Comment by Mukarram Mukhtar — January 11, 2012 @ 6:29 pm Good article, This is what I was looking for. Can you please send me the source code. My mail id is kpsamad@gmail.com. Thanks in advance. Comment by Abdul Samad — January 24, 2012 @ 1:43 pm Very helpful article. Can I have a copy of your source code? My email add is marithe.2386@gmail.com Thank you so much!🙂 Comment by Marie — February 17, 2012 @ 3:05 pm Hi, I am trying to integrate QuickBooks to .NET application(Windows). Your article is much helpful. Can u send whole source code to my mail id. Comment by Mayil — February 28, 2012 @ 11:59 am Awesome man! You have done a great job yar! Your efforts of sharing knowledge should be definitely appreciated🙂 Please share me the source code to my mail ID jay (at) proteam (dot) in Comment by Jayasankar.N — February 28, 2012 @ 5:14 pm Jay, I’m unable to send you the e-mail. I keep on getting MAILER-DAEMON’s failure notice. Are you sure you’re typing in your e-mail address correctly? Comment by Mukarram Mukhtar — March 1, 2012 @ 5:17 pm Hello, I am a beginner and I need your source file. Can you please provide me at pranav.rajyaguru@gmail.com. Thanks in advanced… Pranav Comment by Pranav Rajyaguru — April 2, 2012 @ 3:38 pm Just the perfect thing which I was looking for. Great work ! . Please share the source code with me at disha07@live.com. Thanks in advance !🙂 Comment by Disha — April 23, 2012 @ 4:53 pm Good article with layered structure.can u please send me the source code to my mailid: srikanthfanz@gmail.com Comment by Srikanth — April 30, 2012 @ 9:39 am I am getting error for CreateRequestMsgSet , GetResponse , GetResponseStatus in RequestBroker.cs class. Error says that “doesn’t contain definition” I have included all references and assembly files as said in above tutorial but these three errors are stopping to move on. if anyone know about the solution please send me at alihassan@greypole.com . Thanks in Advance. Comment by Ali Hassan — May 7, 2012 @ 7:33 am Good article with layered structure.can u please send me the source code to my mailid: pet_a_007@yahoo.com Comment by Crux Cracker — May 9, 2012 @ 9:59 am Hi Mukarram, This is very nice article, i am new to quickbooks and don’t having idea about it. I want to integrate quickbooks and interact with asp.net application. Can you please provide me any sample app code.. Comment by Priyanka — May 11, 2012 @ 10:45 am Hi…Thanks for posting such a nice article. Can you please send me the code file as well at vivekpro26@gmail.com…Thanks in advance… Comment by Vivek — June 25, 2012 @ 7:15 am Hi Mukarram, nice detailed article can you provide me with your source code. I look forward to integrating it with QB. Thanks in advance @ rt.trevino@gmail.com Comment by Ricardo — July 3, 2012 @ 4:10 am Very nice article. Can you please forward that zip file of this application to my email. I would really appreciate. temp@dmhone.com Thanks Comment by Mike — July 3, 2012 @ 8:24 pm Hi, This looks perfect can you provide me with the source code at rt.trevino@gmail.com.. Thanks Comment by RT — July 5, 2012 @ 12:45 am Hi Mukarram, nice detailed article can you provide me with your source code. I look forward to integrating it with QB. Thanks in advance @ v_alex91@yahoo.com Comment by Alex — July 30, 2012 @ 12:33 pm Hi Mukarram, Great article you have here. I have been researching on how to integrate QB to our .NET apps and this seems to answer it. Can you send me the project file. Your response is greatly appreciated. Comment by Roger Kelly — August 1, 2012 @ 9:59 pm Hi Mukarram, I appreciate your great work on this. Please send me a copy of your source code at rogerny10@yahoo.com. Thanks in advance. Comment by Roger — August 3, 2012 @ 5:44 pm Hi Mukarram, Great article you have here, just what I am looking for. Kindly send me the source code to my email at rogerny10@yahoo.com, please. Comment by Roger kelly — August 6, 2012 @ 2:45 pm Hi Mukarram, Please send me a copy of your source code at cool_dude7289@yahoo.com . Thanks in advance. Comment by mark — August 11, 2012 @ 6:37 am Hi Mukarram, this is a very informative article.Can you send me a copy the source code to stevekaiy@gmail.com steve@kaiynetconsulting.com thanx. Comment by Steve Kagiri — August 15, 2012 @ 10:04 am I haveto integrate my c# asp.net application with quickbooks.can we pull data from web application data and display in quickbooks? Comment by RA — August 31, 2012 @ 2:50 am Hi, This is a great article. Can you please send me a copy of the source code to craju11@gmail.com Comment by chandra — September 18, 2012 @ 10:30 pm Assalamoalikum, Can you send me that code at mather2002@hotmail.com Comment by Ather Abbas — September 21, 2012 @ 6:34 pm Cannot Create QBXMlRP2 COM component. How to resolve this error? Comment by dev — November 1, 2012 @ 10:59 am Hi Mukkaram, Thank you for that information. Would you please send source code to: suemcneel@comcas.net Comment by Susette — November 2, 2012 @ 4:49 am Sorry I misspelled my email on the previous post. Comment by Susette — November 2, 2012 @ 4:50 am Excellent Article!!! Can you please send me article to my email address Comment by Gurbetteyim — November 25, 2012 @ 5:16 am Sorry I meant source code please/ Comment by Gurbetteyim — November 25, 2012 @ 5:16 am Very nicely written article… Please can you send the source code to hoseki210@gmail.com Comment by Sunder — December 3, 2012 @ 5:19 pm Hi..thank u for this excellent article. i’ve been banging my head to the computer for it. Can u please send the zip file for this project to ramna.kumar@gmail.com Thanks in Advance! Comment by Ramana — December 4, 2012 @ 6:46 am very nice post …I want to integrate quick books in windows application using c sharp …please can you send the source code to suresh@ Wesgrow.com thanks in advance Comment by Suresh Kutty — December 4, 2012 @ 5:26 pm Excellent. Very nicely written. Very nicely structured. Not only the 3 tier architecture is great but the way you have structured the classes is wonderful. You have paid great attention to every detail. I have learned so much by reading it today. i am very very thankful. An article like this helps us earn our daily bread. I glanced through the article. I am writing in detail after spending few hours reading the article today. I will be be grateful if you can send us the code – This and part 2. Thanks for everything. My mail id is hoseki210@gmail.com Comment by Sunder — December 4, 2012 @ 7:18 pm Excellent coding.. we learnt a lot here .. please give us the source code.my mail id sureshemanip@gmail.com Comment by suresh — December 5, 2012 @ 4:09 pm I am a beginner and I need your source file. Can you please provide me at rajibmitra0009@gmail.com. Thanks in advanced… Rajib Comment by Rajib Mitra — December 28, 2012 @ 11:26 am After several days of research, this is the best example that I have found. I am trying to connect with Quickbook using VS2008 and SQLServer. I am using a web page application that extracts data from SQLServer and wish to update Quickbooks. I am using VB. Could you provide your source code via email? Thanks in advance Roger Comment by Roger — February 23, 2013 @ 6:11 pm nice article. Can you please send the zip file for this project at shehzadzafarch@gmail.com Comment by Muhammad Shehzad — February 27, 2013 @ 4:11 pm Hi, nice article, can you please send your code details at girish85@hotmail.com Comment by girish — March 2, 2013 @ 7:48 pm great work man!!! Thanks…. can you please send the project in zip file @ saimshaukat@yahoo.com Regards Saim Shaukat Comment by Saim Shaukat — March 5, 2013 @ 10:59 am Can you please send it to mohsinraza4539@gmail.com too. Thanks in advance. Mohsin Thanks, Mohsin Raza On Tue, Mar 12, 2013 at 12:03 AM, Mukarram Mukhtar wrote: > ** > Saim Shaukat commented: “great work man!!! Thanks…. can you please > send the project in zip file @ saimshaukat@yahoo.com Regards Saim Shaukat” > Comment by Mohsin Raza — March 12, 2013 @ 6:54 am Can you please send it to mohsinraza4539@gmail.com too. Thanks in advance. Mohsin Comment by Mohsin Raza — March 12, 2013 @ 6:55 am Hi, Can you please send me the source code to my email,divyanmenon@hotmail.com Comment by Divya — March 15, 2013 @ 9:53 am can you email the project? to alberto.estrada1@gmail.com Comment by alby — March 16, 2013 @ 6:24 am Hi, Can I have the project? I’m starting a new project and will need to add record and retrieve. I have to complete in 1 month and am new. Comment by aestrada101 — March 17, 2013 @ 5:43 am Hello – I really appreciate the QuickBooks/.Net tutorial. It’s actually much more readable than Intuit’s documentation. May I please have a copy of the project? My email address is terryj@turnkeynet.com Thanks, Terry Comment by Terry — March 19, 2013 @ 10:13 pm Great tutorial. Could you email me a zip of the solution file too. my email is papa43boys@yahoo.com Comment by Ben — March 23, 2013 @ 9:35 pm I’m obviously late to this party, but I really appreciate your article and information and would very much like to receive a copy of the code. My email address is crosjn!yahoo.com. Comment by Jeff — April 15, 2013 @ 4:38 pm Nice Article. Can you send me a copy of the zip file of this application my email is markoliva19@gmail.com . Thanks man.. Comment by Mark — April 24, 2013 @ 8:48 am Nice one and appreciate you. can you send a copy of zip file to me, my email is bollamadhusudhanreddy@gmail.com. Thank you very much Terry… Comment by madhu — May 10, 2013 @ 6:02 am Hi, Can you please send me the source code to my email, karvendhan@gmail.com Comment by Karvendhan — May 17, 2013 @ 8:03 am How can I remove the Company preferences Integrated Application programatically using C# / QMXML / QBFC? Comment by Meena — May 20, 2013 @ 2:53 pm Can anyone help me? Its very urgent. I want to remove the Integrated Application from Company preferences programatically with SDK / C# / QBXML / QBFC Comment by Meena — July 31, 2013 @ 2:24 pm how can I remove integrated application from company preferences through c# sdk Comment by Meena — September 16, 2014 @ 1:17 pm tanx man. really helped from jumping off a cliff. thout i was alone with this C# quickbooks integration thing. tanx a million. pls drop off any more stuff about C# and quickbooks integration at my mail box: chini7000@gmail.com Comment by novichini — May 31, 2013 @ 4:32 pm Hi can you please send me the copy of zip file of the application to my emailid: priyanka.rao@pchase.co.uk You did a great job.. Comment by Priyanka — June 18, 2013 @ 11:28 am Hi This articles is very helpful.. But am getting pblms.. Can you send me a copy of the source code.. Nice Job. Comment by Azam — July 10, 2013 @ 6:41 am Hi , thanks for you article. I am in this big trouble🙂 can you please send me your code for this?! Is that possible to make connection to quickbooks database remotely? Thanks, poupak Comment by poupak — June 18, 2013 @ 9:39 pm Can anybody know that how can I connect multiple QBW file one by one. Like Open one file send some data from integrated application then close this connection and connect to another QBW file. Please help me. Its urgent. Comment by Meena Trivedi — October 14, 2013 @ 1:27 pm
https://mukarrammukhtar.wordpress.com/quickbooks-with-net/
CC-MAIN-2016-40
refinedweb
14,286
66.23
Hi. I cannot explain my question very well. I have an array of objects. Can i perform a search in this? Check the following code as example: public class test1 { public static void main (String[] args){ test2[] array = new test2[2]; for(int i=0;i<2;i++){ array[i]=new test2(); } int a=1, b=2; String c ="c", d = "d"; array[0].insert(a, c); array[1].insert(b, d); } } and public class test2 { int z; String y; public void insert(int z, String y) { this.z = z; this.y = y; } } I want check if int 1 (or String b) exists in array[i]. Is it possible? The array: array contains only Test2 objects. It does not contain either int or String objects. You must ask the Test2 object what it contains. Add methods to the Test2 class that will check for the contents that you want to test for. Then you can call those methods to determine the contents of a Test2 object. Ok, thanks for the reply. But can i perform this search with a for loop in the main test1 class? Is that possible? You can do the search in a for loop in any method that has access to the array. Sure. Suppose I had an array of Car objects, I could find the Fords with something like for (Car c : myArrayOfCars) { if (c.getManufacturer().equals("Ford") ... } Thanks all for the replies.
http://www.daniweb.com/software-development/java/threads/422389/search-in-array-of-objects-
CC-MAIN-2014-10
refinedweb
238
85.89
In today’s Programming Praxis exercise, our task is to write a solution to Ullman’s puzzle, which is to check whether there exists a subsequence of exactly length k of a series of real numbers that sums up to less than a given t. Let’s get started, shall we? A quick import: import Data.List Today’s exercise is a short one. My first attempt was basically converting the problem statement into Haskell syntax: ullman :: (Num a, Ord a) => a -> Int -> [a] -> Bool ullman t k = any (\s -> length s == k && sum s < t) . subsequences The Scheme solution uses a more efficient algorithm, so for the sake of completeness we’ll translate that into Haskell as well. This one runs in O(n log n) rather than O(n!) and it’s shorter to boot. ullman2 :: (Ord a, Num a) => a -> Int -> [a] -> Bool ullman2 t k = (< t) . sum . take k . sort Some tests to see if everything is working properly: main :: IO () main = do let xs = ] let ys = [3, 4, 3] print $ ullman 98.2 3 xs print $ ullman2 98.2 3 xs print . not $ ullman 5 2 ys print . not $ ullman2 5 2 ys Looks like it is. Tags: bonsai, code, Haskell, kata, praxis, programming, puzzle, ullman
http://bonsaicode.wordpress.com/2010/12/07/programming-praxis-ullman%E2%80%99s-puzzle/
CC-MAIN-2013-48
refinedweb
211
74.9
(Editor's note: The Google API can and has changed so be warned that the code in this article may need to be modified to account for any changes) This is the fourth article in a three article series examining a custom ASP.NET server control I developed to make using the Google Maps API easier for .NET developers. The focus of this article is to highlight the changes I made while porting the GMap control from ASP.NET 1.1 to ASP.NET 2.0. If you're not familiar with the GMap control, I highly recommend reading Part 1, Part 2, and Part 3 first. This article assumes four things to be covered are: ICallbackEventHandler– Using the new built-in callback features of ASP.NET 2.0. This code was developed and tested using Visual Studio 2005 Beta 2. I have not tested nor can I guarantee that that code will work in another version/build of Visual Studio. In the ASP.NET 1.1 version of the GMap control, I had to do a lot of extra work to make client callbacks function properly with ASP.NET pages. With .NET 2.0, Microsoft has made using client callbacks as easy as using regular server-side events. The code below shows the RaiseCallbackEvent() method. The only difference between this and the older version ( RaisePostbackEvent()) is the absence of the CallbackHelper.Write() and CallbackHelper.HandleError() calls. ASP.NET takes care of all of the plumbing and all of the client side JavaScript for us. public string RaiseCallbackEvent(string eventArgument) { string[] ea = eventArgument.Split('|'); string[] args = null; GPointEventArgs pea = null; string evt = ea[0]; string retVal = String.Empty; switch (evt) { // GMap Click event sends the coordinates of the click as event argument case "GMap_Click": args = ea[1].Split(','); pea = new GPointEventArgs(float.Parse(args[0]), float.Parse(args[1]), this); retVal = this.OnClick(pea); break; // GMarker Click event sends the coordinates of the click as event argument case "GMarker_Click": args = ea[1].Split(','); GPoint gp = new GPoint(float.Parse(args[0]), float.Parse(args[1])); GMarker gm = new GMarker(gp, args[2]); pea = new GPointEventArgs(gp, gm); retVal = this.OnMarkerClick(pea); break; // GMap Move Start event sends the coordinates of the center of the // map where the move started case "GMap_MoveStart": args = ea[1].Split(','); pea = new GPointEventArgs(float.Parse(args[0]), float.Parse(args[1])); retVal = this.OnMoveStart(pea); break; // GMap Move End event sends the coordinates of the center of the // map where the move ended case "GMap_MoveEnd": args = ea[1].Split(','); pea = new GPointEventArgs(float.Parse(args[0]), float.Parse(args[1])); retVal = this.OnMoveEnd(pea); break; // GMap Zoom event sends the old and new zoom levels case "GMap_Zoom": args = ea[1].Split(','); GMapZoomEventArgs zea = new GMapZoomEventArgs(int.Parse(args[0]), int.Parse(args[1])); retVal = this.OnZoom(zea); break; // GMap Client Load event case "GMap_ClientLoad": retVal = this.OnClientLoad(); break; // GMap Map Type Changed event case "GMap_MapTypeChanged": retVal = this.OnMapTypeChanged(); break; // Default: we don't know what the client was trying to do default: throw new System.Web.HttpException( String.Format("Invalid GMap Event Sender: {0} Event: {1}", this.ID, evt)); } return retVal; } Another great feature of ASP.NET 2.0 is the ability to embed files into an assembly (JPEGs, GIFs, js files, XSL files, etc.) and reference them in your pages. This magic is courtesy of the new ClientScriptManager. For more details on this process, read "Embedding Resources in ASP.NET 2.0 Assemblies" by Mark Hines. Version 1.1 of the GMap control relied on the developer to place the proper client files (GMapX.js, GMap.xsl, and CallbackObject.js) in a folder of their web application. This folder had to be referenced in the web.config file. Any changes made to the control required updating the control assembly and possibly the three supporting files. As you can see, this could become a maintenance nightmare. With .NET 2.0, these files are now embedded in the assembly directly. No need to manage multiple files, everything is wrapped up nicely in the DLL file. The code below found in AssemblyInfo.cs tells the framework that the two files GMapX.js and GMap.xsl can be found in the assembly. [assembly: System.Web.UI.WebResource("WCPierce.Web.GMapX.js", "text/javascript")] [assembly: System.Web.UI.WebResource("WCPierce.Web.GMap.xsl", "text/xml")] Obtaining a reference to the files for use in the page's rendered HTML is a simple method call. ClientScriptManager cs = Page.ClientScript; cs.RegisterClientScriptInclude(GMap.ScriptName, cs.GetWebResourceUrl(this.GetType(), "WCPierce.Web.GMapX.js")); The resulting output on your page looks something like this: If you plan on moving to .NET 2.0 and you haven't already, I strongly recommend learning about generics. Check out "Generics Explained" by zubinraj for a good overview on generics. For version 1.1 of the control, I used CodeSmith to generate a strongly-typed ArrayList for overlays, icons, controls, and points. This resulted in thousands of lines of code for five classes. But that is the price you had to pay for a truly strongly-typed ArrayList. Using generics, the code for GOverlays is now seven (7) lines instead of 2,662. using System; namespace WCPierce.Web.UI.WebControls { [Serializable] public class GOverlays : System.Collections.Generic.List<GOverlay> { } } Pretty amazing 'eh? Seven lines of code and I have a perfectly formed, strongly-typed ArrayList waiting to do my bidding. There are a lot of new features in Configuration for ASP.NET 2.0. For a complete look at the new features, check out "Managing Your ASP.NET Application". The main usage in GMap 2.0 is registering a custom control once in the web.config file and being able to use it throughout your application with full Intellisense. The blurb below shows a portion of the web.config file included in the code download. <pages> <controls> <!-- Register our custom controls --> <add namespace="WCPierce.Web.UI.WebControls" assembly="WCPierce.Web" tagPrefix="wcp"/> . . . </controls> </pages> With this line added you can easily add a GMap control to any page in your application like the code below. You also get full HTML Intellisense for free. <wcp:GMap This article was so short I'm almost embarrassed to call it an article. I wanted to keep it brief, and focus on the changes made to make the GMap take advantage of ASP.NET 2.0. If you want full details on the creation of the GMap control, check out Part 3 where I cover the code in depth. Until next time, Happy Mapping! General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/custom-controls/LatLaysFlat-Part4.aspx
crawl-002
refinedweb
1,100
68.57
Execute system commands in a Java Program By: Rajan Printer Friendly Format Most often in your Java programs you will find a need to execute system DOS commands. You can execute any system commands that are OS specific and then read the output of the system command from your Java program for further processing within the Java program. This sample Java Program executes the 'dir' command reads the output of the dir command prints the results. This is just for understanding the concept, however, you may execute just about any command using this Runtime.getRuntime().exec() command. import java.io.*; public class doscmd { public static void main(String args[]) { try { Process p=Runtime.getRuntime().exec("cmd /c dir"); p.waitFor(); BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); String line=reader.readLine(); while(line!=null) { System.out.println(line); line=reader.readLine(); } } catch(IOException e1) {} catch(InterruptedException e2) {} System.out.println(..can anyone please tell me how to run linux co View Tutorial By: ahmed at 2008-09-05 10:22:52 2. hey,m i suspend the process before start to execut View Tutorial By: koustubh nakate at 2010-04-01 22:16:16 3. Can u please tell me how to compile and execute a View Tutorial By: RJ at 2010-04-20 01:30:10 4. hey!!! can u pls tell me how to execute a java pro View Tutorial By: timothy at 2010-11-29 18:28:08 5. hey can u tell me a simple program to use the cmd View Tutorial By: Rakesh at 2011-08-08 10:56:47 6. hi gud mrng........ i wanna connectivity of View Tutorial By: sac at 2011-09-02 04:56:43 7. Hi, I want to run a bat file, below are the View Tutorial By: Rajshekar at 2011-10-28 06:07:06 8. Thanks.I was searching the internet for a lot of t View Tutorial By: Habi at 2011-12-22 07:43:51 9. Hi guys.i have a simple doubt. i want to ru View Tutorial By: Muthukumar at 2011-12-29 07:30:56 10. oh tnx a lot!i'v been lookin for a code like this! View Tutorial By: LES at 2012-01-13 12:55:09 11. Hey your help is really appreciated but I dont und View Tutorial By: farid khan at 2012-03-21 15:59:53 12. i want to make java editore in my major project.i View Tutorial By: pawan patel at 2012-04-14 11:15:19 13. I want to connect to your box and sniff your mapck View Tutorial By: lamer at 2012-06-19 22:29:51 14. Hi, i am working on ocap xlet project. here View Tutorial By: swati at 2012-07-09 08:39:13 15. its not working. View Tutorial By: raja at 2012-08-29 11:44:45 16. Hey guys it's working. If not then remove p.waitFo View Tutorial By: dileep at 2013-01-04 19:51:38 17. FILE:- lpton.pl...... ..................... View Tutorial By: Prats at 2013-02-02 17:33:40 18. Your article is very useful. But I View Tutorial By: Me at 2013-04-07 10:20:00 19. Thank you very much sir. One can simply exe View Tutorial By: rudhin at 2013-05-10 12:32:57 20. hai sir... this is ROSHAN I am searching for voice View Tutorial By: roshan at 2013-09-25 08:12:55 21. Runtime rt=Runtime.getRuntime(); String cmd View Tutorial By: saranya at 2014-10-30 05:36:36 22. Hi, I want to write an Android Application, View Tutorial By: Kara at 2014-11-20 07:39:03 23. hi i want to run a c program in java program but i View Tutorial By: jyothi at 2014-11-27 06:40:27 24. Thank you. but Program can't run. View Tutorial By: channgam at 2015-03-06 06:58:01 25. Hi , I want to a read file having a list of telnet View Tutorial By: Greta Pereira at 2017-03-14 10:44:53
https://java-samples.com/showtutorial.php?tutorialid=8
CC-MAIN-2022-21
refinedweb
692
67.76
C:\ cpan shell -- CPAN exploration and modules installation (v1.9751) Enter 'h' for help. cpan> i /^namespace::au/ Database was generated on Sat, 15 Dec 2012 08:49:58 GMT Bundle namespace::autoclean (BOBTFISH/namespace-autoclean-0.13.ta +r.gz) Module = namespace::autoclean (BOBTFISH/namespace-autoclean-0.13.ta +r.gz) 2 items found cpan> q Lockfile removed. C:\>mversion namespace::autoclean 0.12 C:\ --version C:\strawberry\perl\bin/cpan version 1.57 calling Getopt::Std::getopts +(version 1.06 [paranoid]), running under Perl version 5.12.3. [Now continuing due to backward compatibility and excessive paranoia +. See ``perldoc Getopt::Std'' about $Getopt::Std::STANDARD_HELP_VERSI +ON.] Nothing to install! [download] The same happened with a number of other modules. For Template I could install it by running "install Template" inside the CPAN shell, for namespace::autoclean I had to type: "install BOBTFISH/namespace-autoclean-0.13.tar.gz" Currently this is the set of modules that refuse to upgrad via the cpan script. Warning: prerequisite Class::C3::Componentised 1.001000 not found. We +have 1.0009. Warning: prerequisite Exporter::Declare 0.105 not found. We have 0.103 +. Warning: prerequisite File::ShareDir::Install 0.04 not found. We have +0.03. Warning: prerequisite HTML::Lint 2.10 not found. Warning: prerequisite HTML::Template 2.9 not found. We have 2.10. Warning: prerequisite IO::TieCombine 1.001 not found. We have 1.000. Warning: prerequisite List::MoreUtils 0.33 not found. We have 0.32. Warning: prerequisite Log::Contextual 0.004001 not found. We have 0.00 +304. Warning: prerequisite Log::Log4perl 1.35 not found. We have 1.33. Warning: prerequisite MIME::Types 1.34 not found. We have 1.31. Warning: prerequisite MetaCPAN::API 0.43 not found. Warning: prerequisite Modern::Perl 1.20120130 not found. We have 1.03. Warning: prerequisite Module::Install::ReadmeFromPod 0.16 not found. Warning: prerequisite Module::Refresh 0.17 not found. We have 0.16. Warning: prerequisite Module::ScanDeps 1.07 not found. We have 1.02. Warning: prerequisite MooseX::Role::Parameterized 1.00 not found. We h +ave 0.26. Warning: prerequisite MooseX::SetOnce 0.200001 not found. We have 0.20 +0000. Warning: prerequisite MooseX::Singleton 0.29 not found. We have 0.27. Warning: prerequisite MooseX::StrictConstructor 0.19 not found. We hav +e 0.16. Warning: prerequisite MooseX::Types::Perl 0.101341 not found. We have +0.101340. Warning: prerequisite POE 1.350 not found. We have 1.311. Warning: prerequisite POE::Test::Loops 1.350 not found. We have 1.312. Warning: prerequisite Package::Stash::XS 0.25 not found. We have 0.22. Warning: prerequisite Params::Validate 1.05 not found. We have 1.00. Warning: prerequisite Pod::Coverage 0.22 not found. We have 0.21. Warning: prerequisite SQL::Translator 0.11010 not found. We have 0.110 +08. Warning: prerequisite Scope::Upper 0.18 not found. We have 0.14. Warning: prerequisite Test::Reporter 1.58 not found. We have 1.57. Warning: prerequisite Test::SharedFork 0.19 not found. We have 0.16. Warning: prerequisite Test::TCP 1.15 not found. We have 1.13. Warning: prerequisite Try::Tiny 0.11 not found. We have 0 (Edit: Maybe pointing to an off-sync mirror or mini-cpan?) Can you reproduce the problem on a fresh system/VM? Cheers Rolf Any idea why and how to solve this? Check the config, check the mirror, upgrade CPAN::SQLite , cpandb --setup && cpandb --update , disable CPAN::SQLite ( cpan> o conf use_sqlite 0 ), turn on debugging/increase verbosity ( cpan> o debug all or set CPANSCRIPT_LOGLEVEL=ALL ), cpan> dump namespace::autoclean , ... Switch to cpanp/cpanm #!/usr/bin/perl use strict; use warnings; system("dual-lived namespace::autoclean -u"); system("dual-lived /^namespace::au/"); [download] #!/usr/bin/perl use strict; use warnings; system("dual-lived /^namespace/"); [download] Used as intended The most useful key on my keyboard Used only on CAPS LOCK DAY Never used (intentionally) Remapped Pried off I don't use a keyboard Results (441 votes), past polls
http://www.perlmonks.org/index.pl/jacques?node_id=1008987
CC-MAIN-2015-11
refinedweb
672
58.35
User-defined Functions in C Programming Language An important feature of C programming(and almost every other programming language) is that it allows us to create our own functions. In this tutorial, we will be focusing on how to make our own function. There are a few steps that need to be followed in order to create a function: - Function Declaration: Like variable declaration, a function declaration specifies the type of the function. - Function Definition: A function needs to be defined in order to be used. It is the actual function that we are going to work on. - Function parameters: They contain values or arguments that are sent by the calling function. - Function call: It is how we are going to call the function to get executed. The function that calls other functions in its body(usually main() function) are known as calling functions and the functions that get called are known as the called functions. This is a two-way communication process that involves sending arguments to the called function and then returning values from the called function to the calling function. Even if we do not have to return anything then we void as the return type. The figure below illustrates the control flow for functions: Function Declaration Defining the type of the function is important for creating a function. A function declaration specifies - the type of the function or return type, - the function name and - its parameters. It is usually done at the top of the program and indicates how the function shall be called. The actual function definition can be present anywhere in the program. Here is how it looks: return_type function_name(parameters); - Function return type: It indicates what type of value the function will return. Eg: int, double, float, char, etc. A function with void return type does not return any value. - Function name: A function name can be anything the user decides. Usually, a function name is kept according to the function it performs. - Function Parameter: It contains arguments and may or may not take values from the calling function. Here’s an example of a function declaration with integer return type and area as function name. int area(int,int); Function Definition The function definition consists of the function body along with the return type, function name and its parameters. Here is how it looks like: return_type function_name(parameter) { //body of the function } The body of the function contains a list of statements that gets executed once the function is being called. This is known as the called function and after execution of the called function the control goes back to the calling function. Function Parameter The function parameter contains the arguments that are passed by the calling function. They are placed within a pair of parenthesis and can have any number of arguments separated by commas. Every parameter has a specific datatype and it accepts only those values which can be assigned to that datatype. A function may or may not have a parameter. A function with no parameter is defined as follows: void sum() { //body of the function } In C Programming language, there are two types of function parameters: - Formal Parameter: The parameter which is written at the function definition is known as a formal parameter. - Actual Parameter: The parameter that is written at the function call is known as the actual parameter. The formal and actual parameters are shown below: int sum(int,int); void main() { int a ,b ; //body of main sum(a ,b );//actual parameter } int sum(int x, int y)//formal parameter { //body of the function } Function Call A function needs to be called by the calling function in order to get executed. There are two ways in which a function can be called: - Call by reference: In this method, the address of the parameter or argument is put in the formal parameter and then the values are accessed using the address in the actual parameter. Call by reference is done as follows: int sum(int *x,*y)// *x is the address which points to the value of the variable x stored in the address. - Call by value: In this method, the actual values are passed as an argument in the formal parameter and are accessed in the actual parameter. int sum(int x,int y) // x is the variable which contains the value so the value is directly passed to the function Note:- The difference between the above two is that, when we pass by reference then no new copy of the value is created i.e. the passed variable is used and even if we do not return anything from the called function then also the changes will reflect inside the calling function. Program on Function Here’s a simple program which prints the factorial of n numbers starting form 1 using functions: #include <stdio.h> long fact(int);//function declaration int main() { int i,n; long f; printf("Enter the range:\n"); scanf("%d",&n); //each number is sent to the function fact() and it returns the factorial of the number for(i=1; i<=n; i++){ //we are using call by value f=fact(i);//actual parameter printf("the factorial of %d is: %d\n",i,f);//prints the factorial of each number } return 0; } long fact(int x)//function definition with formal parameter { int i; long f=1; for(i=1; i<=x; i++) { f=f*i;//calculates factorial of the number } return f; } Output:- Enter the range: 5 the factorial of 1 is: 1 the factorial of 2 is: 2 the factorial of 3 is: 6 the factorial of 4 is: 24 the factorial of 5 is: 120 Learning never exhausts the mind. So, do come back for more. Hope this helps and you like the tutorial. Do ask for any queries in the comment box and provide your valuable feedback. Do Share and Subscribe. Keep Coding!! Happy Coding!! 🙂
https://www.codingeek.com/tutorials/c-programming/user-defined-functions-in-c-programming-language/
CC-MAIN-2018-26
refinedweb
988
57.2
How do you check if a string contains only numbers? I've given it a go here, need it in the simplest way. Thanks. import string def main(): isbn = input("Enter you're 10 digit ISBN number: ") if len(isbn) == 10 and string.digits == True: print ("Works") else: print("Error, 10 digit number was not inputted and/or letters were inputted.") main() if __name__ == "__main__": main() input("Press enter to exit: ") You'll want to use the isdigit method on your str object: if len(isbn) == 10 and isbn.isdigit(): From the isdigit documentation: str.isdigit() Return true if all characters in the string are digits and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent.
https://codedump.io/share/d1OuL8XwgELU/1/how-do-you-check-if-a-string-contains-only-numbers---python
CC-MAIN-2017-51
refinedweb
124
65.93
Test browser: Version of Chrome: 52.0.2743.116 It is a simple javascript that is to open an image file from local like 'C:\002.jpg' function run(){ var URL = ":\002.jpg"; window.open(URL, null); } run(); Here is my sample code. Please give me any suitable suggestions. Know this is kind of old, but see many questions like this... We use Chrome a lot in the classroom and it is a must to working with local files. What we have been using is "Web Server for Chrome". You start it up, choose the folder wishing to work with and go to URL (like 127.0.0.1:port you chose) It is a simple server and cannot use PHP but for simple work, might be your solution: Okay folks, I completely understand the security reasons behind this error message, but sometimes, we do need a workaround... and here's mine. It uses ASP.Net (rather than JavaScript, which this question was based on) but it'll hopefully be useful to someone. Our in-house app has a webpage where users can create a list of shortcuts to useful files spread throughout our network. When they click on one of these shortcuts, we want to open these files... but of course, Chrome's error prevents this. This webpage uses AngularJS 1.x to list the various shortcuts. Originally, my webpage was attempting to directly create an <a href..> element pointing at the files, but this produced the " Not allowed to load local resource" error when a user clicked on one of these links. <div ng- <div class="cssShortcutIcon"> <img ng- </div> <div class="cssShortcutName"> <a ng-{{ sc.ShtCut_Name }}</a> </div> </div> The solution was to replace those <a href..> elements with this code, to call a function in my Angular controller... <div ng- {{ sc.ShtCut_Name }} </div> The function itself is very simple... $scope.OpenAnExternalFile = function (filename) { // // Open an external file (i.e. a file which ISN'T in our IIS folder) // To do this, we get an ASP.Net Handler to manually load the file, // then return it's contents in a Response. // var URL = '/Handlers/DownloadExternalFile.ashx?filename=' + encodeURIComponent(filename); window.open(URL); } And in my ASP.Net project, I added a Handler file called DownloadExternalFile.aspx which contained this code: namespace MikesProject.Handlers { /// <summary> /// Summary description for DownloadExternalFile /// </summary> public class DownloadExternalFile : IHttpHandler { // We can't directly open a network file using Javascript, eg // window.open("\\SomeNetworkPath\ExcelFile\MikesExcelFile.xls"); // // Instead, we need to get Javascript to call this groovy helper class which loads such a file, then sends it to the stream. // window.open("/Handlers/DownloadExternalFile.ashx?filename=//SomeNetworkPath/ExcelFile/MikesExcelFile.xls"); // public void ProcessRequest(HttpContext context) { string pathAndFilename = context.Request["filename"]; // eg "\\SomeNetworkPath\ExcelFile\MikesExcelFile.xls" string filename = System.IO.Path.GetFileName(pathAndFilename); // eg "MikesExcelFile.xls" context.Response.ClearContent(); WebClient webClient = new WebClient(); using (Stream stream = webClient.OpenRead(pathAndFilename)) { // Process image... byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename)); context.Response.BinaryWrite(data1); context.Response.Flush(); context.Response.SuppressContent = true; context.ApplicationInstance.CompleteRequest(); } } public bool IsReusable { get { return false; } } } And that's it. Now, when a user clicks on one of my Shortcut links, it calls the OpenAnExternalFile function, which opens this .ashx file, passing it the path+filename of the file we want to open. This Handler code loads the file, then passes it's contents back in the HTTP response. And, job done, the webpage opens the external file. Phew ! Again - there is a reason why Chrome throws this " Not allowed to load local resources" exception, so tread carefully with this... but I'm posting this code just to demonstrate that this is a fairly simple way around this limitation. Just one last comment: the original question wanted to open the file " C:\002.jpg". You can't do this. Your website will sit on one server (with it's own C: drive) and has no direct access to your user's own C: drive. So the best you can do is use code like mine to access files somewhere on a network drive. Chrome specifically blocks local file access this way for security reasons. Here's an article to workaround the flag in Chrome (and open your system up to vulnerabilities): There is a workaround using Web Server for Chrome. Here are the steps: - Add the Extension to chrome. - Choose the folder (C:\images) and launch the server on your desired port. Now easily access your local file: function run(){ // 8887 is the port number you have launched your serve var URL = ""; window.open(URL, null); } run(); PS: You might need to select the CORS Header option from advanced setting incase you face any error any cross origin access error. 1) Open your terminal and type npm install -g http-server 2) Go to the root folder that you want to serve you files and type: http-server ./ 3) Read the output of the terminal, something kinda will appear. Everything on there will be allowed to be got. Example: background: url(''); You won't be able to load an image outside of the project directory or from a user level directory, hence the "cannot access local resource warning". But if you were to place the file in a root folder of your project like in MyProjectName\Content\my-image.jpg and referenced it like so: <img src="/Content/my-image.jpg" /> If you could do this, it will represent a big security problem, as you can access your filesystem, and potentially act on the data available there... Luckily it's not possible to do what you're trying to do. If you need local resources to be accessed, you can try to start a web server on your machine, and in this case your method will work. Other workarounds are possible, such as acting on Chrome settings, but I always prefer the clean way, installing a local web server, maybe on a different port (no, it's not so difficult!). See also: This issue come when I am using PHP as server side language and the work around was to generate base64 enconding of my image before sending the result to client $path = 'E:/pat/rwanda.png'; $type = pathinfo($path, PATHINFO_EXTENSION); $data = file_get_contents($path); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); I think may give someone idea to create his own work around Thanks You just need to replace all image network paths to byte strings in stored Encoded HTML string. For this you required HtmlAgilityPack to convert Html string to Html document. Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox. string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString(); // Decode the encoded string. StringWriter myWriter = new StringWriter(); HttpUtility.HtmlDecode(encodedHtmlString, myWriter); string DecodedHtmlString = myWriter.ToString(); //find and replace each img src with byte string HtmlDocument document = new HtmlDocument(); document.LoadHtml(DecodedHtmlString); document.DocumentNode.Descendants("img") .Where(e => { string src = e.GetAttributeValue("src", null) ?? ""; return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image"); }) .ToList() .ForEach(x => { string currentSrcValue = x.GetAttributeValue("src", null); string filePath = Path.GetDirectoryName(currentSrcValue) + "\\"; string filename = Path.GetFileName(currentSrcValue); string contenttype = "image/" + Path.GetExtension(filename).Replace(".", ""); FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); Byte[] bytes = br.ReadBytes((Int32)fs.Length); br.Close(); fs.Close(); x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes)); }); string result = document.DocumentNode.OuterHtml; //Encode HTML string string myEncodedString = HttpUtility.HtmlEncode(result); Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString; Google Chrome does not allow to load local resources because of the security. Chrome need http url. Internet Explorer and Edge allows to load local resources, but Safari, Chrome, and Firefox doesn't allows to load local resources. Go to file location and start the Python Server from there. python -m SimpleHttpServer then put that url into function: function run(){ var URL = "" /* or; */ window.open(URL, null); } 来源:
https://www.tfzx.net/article/4835.html
CC-MAIN-2021-17
refinedweb
1,347
59.5