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
One of the new features that was introduced in Windows 2000 has been a display property which will hide the keyboard mnemonic for a menu item or a dialog control until the Alt key is pressed. In other words, all the underlined characters which represent an Alt key combination to invoke that menu or control will not be drawn until the user indicates the intention to invoke a command with the keyboard rather than the mouse. The result of this behavior is to provide an interface which is not visually cluttered with underlined characters for people who choose to navigate the user interface with the mouse. The keyboard navigation hiding feature will be automatically enabled on Windows 2000 if the application uses the Windows look and feel and the "Hide keyboard navigation indicators until I use the Alt key" property is enabled in the Windows 2000 "Display Properties" control panel applet. These details will be of use to developers who are extending look and feels. The keyboard navigation hiding feature will automatically be enabled when a Windows Look and Feel Java application is run on Windows 2000. When the WindowsLookAndFeel is instantiated, it will read the DesktopProperty "win.menu.keyboardCuesOn". This value is stored in the UIManager and can be referenced using the key: "Button.isMnemonicHidingEnabled". The static methods setMnemonicHidden and isMnemonicHidden in WindowsLookAndFeelprovide access to this value. The existing BasicMenuItemUI.paintMenuItem() method is responsible for rendering the background, text, icon and mnemonic of a menu item. A new protected method, paintText() was extracted from paintMenuItem(), which is consistent in name and signature to a similar method in the BasicButtonUI hierarchy. The paintText() methods are overloaded in WindowsMenuItemUI and WindowsMenuUI. The body of the overloaded paintText method checks the isMnemonicEnabled flag in the WindowsLookAndFeel class to determine if the mnemonic should be hidden and then appropriately renders the text. BasicButtonUI already defined a protected method paintText. The WindowsButtonUI and similar classes overloaded this method in much the same manner. A new class was introduced, WindowsGraphicsUtils, to consolidate all the paintText methods. This was done because the Windows...UI classes don't follow the same inheritance hierarchy as the Basic..UI classes. A new RootPaneUI delegate called WindowsRootPaneUI was created for the Windows look and feel. This class had an action registered to reset the mnemonic hidden bit and repaint the ui when the Alt key was pressed. All these methods were added as result of implementing this feature. These methods will only have value to developers who wish to extend or create a Look and Feel. /** * Renders the text of the current menu item. * * @param g graphics context * @param menuItem menu item to render * @param textRect bounding rectangle for rendering the text * @param text String to render * @since 1.4 */ protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) /** * Windows implementation of RootPaneUI. One WindowsRootPaneUI * object is shared between all JRootPane instances. * * @version 1.1 08/16/00 * @author Mark Davidson * @since 1.4 */ public class WindowsRootPaneUI extends BasicRootPaneUI /** * A collection of static utility methods used for rendering the * Windows look and feel. * * @Version 1.1 08/16/00 * @author Mark Davidson * @since 1.4 */ public class WindowsGraphicsUtils /** * Sets the state of the hide mnemonic flag. This flag is used by the * component UI delegates to determine if the mnemonic should be rendered. * This method is a non operation if the underlying operating system * does not support the mnemonic hiding feature. * * @param hide true if mnemonics should be hidden * @since 1.4 */ public static void setMnemonicHidden(boolean hide) /** * Gets the state of the hide mnemonic flag. This only has meaning * if this feature is supported by the underlying OS. * * @return true if mnemonics are hidden, otherwise, false * @see #setMnemonicHidden * @since 1.4 */ public static Boolean isMnemonicHidden() /** * Gets the state of the flag which indicates if the old Windows * look and feel should be rendered. This flag is used by the * component UI delegates as a hint to determine which style the component * should be rendered. * * @return true if Windows 95 and Windows NT 4 look and feel should * be rendered * @since 1.4 */ public static Boolean isClassicWindows()
http://docs.oracle.com/javase/7/docs/technotes/guides/swing/1.4/keyboard_nav_hiding.html
CC-MAIN-2015-32
refinedweb
689
54.93
15.6: Spidering Twitter using a database - Page ID - 3259 In this section, we will create a simple spidering program that will go through Twitter accounts and build a database of them. Note: Be very careful when running this program. You do not want to pull too much data or run the program for too long and end up having your Twitter access shut off. One of the problems of any kind of spidering program is that it needs to be able to be stopped and restarted many times and you do not want to lose the data that you have retrieved so far. You don't want to always restart your data retrieval at the very beginning so we want to store data as we retrieve it so our program can start back up and pick up where it left off. We will start by retrieving one person's Twitter friends and their statuses, looping through the list of friends, and adding each of the friends to a database to be retrieved in the future. After we process one person's Twitter friends, we check in our database and retrieve one of the friends of the friend. We do this over and over, picking an "unvisited" person, retrieving their friend list, and adding friends we have not seen to our list for a future visit. We also track how many times we have seen a particular friend in the database to get some sense of their "popularity". By storing our list of known accounts and whether we have retrieved the account or not, and how popular the account is in a database on the disk of the computer, we can stop and restart our program as many times as we like. This program is a bit complex. It is based on the code from the exercise earlier in the book that uses the Twitter API. Here is the source code for our Twitter spidering application: from urllib.request import urlopen import urllib.error import twurl import json import sqlite3 import ssl TWITTER_URL = '' conn = sqlite3.connect('spider.sqlite') cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS Twitter (name TEXT, retrieved INTEGER, friends INTEGER)''') # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE while True: acct = input('Enter a Twitter account, or quit: ') if (acct == 'quit'): break if (len(acct) < 1): cur.execute('SELECT name FROM Twitter WHERE retrieved = 0 LIMIT 1') try: acct = cur.fetchone()[0] except: print('No unretrieved Twitter accounts found') continue url = twurl.augment(TWITTER_URL, {'screen_name': acct, 'count': '5'}) print('Retrieving', url) connection = urlopen(url, context=ctx) data = connection.read().decode() headers = dict(connection.getheaders()) print('Remaining', headers['x-rate-limit-remaining']) js = json.loads(data) # Debugging # print json.dumps(js, indent=4) cur.execute('UPDATE Twitter SET retrieved=1 WHERE name = ?', (acct, ))() cur.close() # Code: Our database is stored in the file spider.sqlite3 and it has one table named In the main loop of the program, we prompt the user for a Twitter account name or "quit" to exit the program. If the user enters a Twitter account, we retrieve the list of friends and statuses for that user and add each friend to the database if not already in the database. If the friend is already in the list, we add 1 to the friends field in the row in the database. If the user presses enter, we look in the database for the next Twitter account that we have not yet retrieved, retrieve the friends and statuses for that account, add them to the database or update them, and increase their friends count. Once we retrieve the list of friends and statuses, we loop through all of the user items in the returned JSON and retrieve the screen_name for each user. Then we use the SELECTstatement to see if we already have stored this particular screen_name in the database and retrieve the friend count ( friends) if the record exists.() Once the cursor executes the SELECT statement, we must retrieve the rows. We could do this with a for statement, but since we are only retrieving one row ( LIMIT 1), we can use the fetchone() method to fetch the first (and only) row that is the result of the SELECT operation. Since fetchone() returns the row as a tuple (even though there is only one field), we take the first value from the tuple using to get the current friend count into the variable count. If this retrieval is successful, we use the SQL UPDATE statement with a WHERE clause to add 1 to the friends column for the row that matches the friend's account. Notice that there are two placeholders (i.e., question marks) in the SQL, and the second parameter to the execute() is a two-element tuple that holds the values to be substituted into the SQL in place of the question marks. If the code in the try block fails, it is probably because no record matched the WHERE name = ? clause on the SELECT statement. So in the except block, we use the SQL INSERTstatement to add the friend's screen_name to the table with an indication that we have not yet retrieved the screen_name and set the friend count to zero. So the first time the program runs and we enter a Twitter account, the program runs as follows: Enter a Twitter account, or quit: drchuck Retrieving ... New accounts= 20 revisited= 0 Enter a Twitter account, or quit: quit Since this is the first time we have run the program, the database is empty and we create the database in the file spider.sqlite3 and add a table named At this point, we might want to write a simple database dumper to take a look at what is in our spider.sqlite3 file: import sqlite3 conn = sqlite3.connect('spider.sqlite') cur = conn.cursor() cur.execute('SELECT * FROM Twitter') count = 0 for row in cur: print(row) count = count + 1 print(count, 'rows.') cur.close() # Code: This program simply opens the database and selects all of the columns of all of the rows in the table If we run this program after the first execution of our Twitter spider above, its output will be as follows: ('opencontent', 0, 1) ('lhawthorn', 0, 1) ('steve_coppin', 0, 1) ('davidkocher', 0, 1) ('hrheingold', 0, 1) ... 20 rows. We see one row for each screen_name, that we have not retrieved the data for that screen_name, and everyone in the database has one friend. Now our database reflects the retrieval of the friends of our first Twitter account (drchuck). We can run the program again and tell it to retrieve the friends of the next "unprocessed" account by simply pressing enter instead of a Twitter account as follows: Enter a Twitter account, or quit: Retrieving ... New accounts= 18 revisited= 2 Enter a Twitter account, or quit: Retrieving ... New accounts= 17 revisited= 3 Enter a Twitter account, or quit: quit Since we pressed enter (i.e., we did not specify a Twitter account), the following code is executed: if ( len(acct) < 1 ) : cur.execute('SELECT name FROM Twitter WHERE retrieved = 0 LIMIT 1') try: acct = cur.fetchone()[0] except: print('No unretrieved twitter accounts found') continue We use the SQL SELECT statement to retrieve the name of the first ( LIMIT 1) user who still has their "have we retrieved this user" value set to zero. We also use the fetchone()[0]pattern within a try/except block to either extract a screen_name from the retrieved data or put out an error message and loop back up. If we successfully retrieved an unprocessed screen_name, we retrieve their data as follows: url=twurl.augment(TWITTER_URL,{'screen_name': acct,'count': '20'}) print('Retrieving', url) connection = urllib.urlopen(url) data = connection.read() js = json.loads(data) cur.execute('UPDATE Twitter SET retrieved=1 WHERE name = ?',(acct, )) Once we retrieve the data successfully, we use the UPDATE statement to set the retrieved column to 1 to indicate that we have completed the retrieval of the friends of this account. This keeps us from retrieving the same data over and over and keeps us progressing forward through the network of Twitter friends. If we run the friend program and press enter twice to retrieve the next unvisited friend's friends, then run the dumping program, it will give us the following output: ('opencontent', 1, 1) ('lhawthorn', 1, 1) ('steve_coppin', 0, 1) ('davidkocher', 0, 1) ('hrheingold', 0, 1) ... ('cnxorg', 0, 2) ('knoop', 0, 1) ('kthanos', 0, 2) ('LectureTools', 0, 1) ... 55 rows. We can see that we have properly recorded that we have visited lhawthorn and opencontent. Also the accounts cnxorg and kthanos already have two followers. them as retrieved, and for each of the friends of steve_coppin either add them to the end of the database or update their friend count if they are already in the database. Since the program's data is all stored on disk in a database, the spidering activity can be suspended and resumed as many times as you like with no loss of data.
https://eng.libretexts.org/Bookshelves/Computer_Science/Book%3A_Python_for_Everybody_(Severance)/15%3A_Using_Databases_and_SQL/15.06%3A_Spidering_Twitter_using_a_database
CC-MAIN-2019-43
refinedweb
1,514
68.3
C# Corner Tired of mapping your classes from one format to another? A convention-based, open source library can help alleviate some of those coding headaches. One of the great things about the .NET community is the wealth of open source projects that are available to you. In previous columns, I've written about my use of Castle Windsor (December 2011) and Rhino.Mocks (August 2011). In this article, I'm going to look at a powerful and extensible open source library found on GitHub called AutoMapper. It's an object-to-object mapping tool that helps you eliminate some of the tedious code needed to map your classes from one format to another. Writing Your Own Projections When I talk about "projections," what do I mean? In the Model-View-ViewModel (MVVM) pattern, a view model is bound to a Windows Presentation Foundation (WPF) window or user control (the view). The data in the ViewModel comes from model classes that probably come from a domain layer, an Object Relational Mapper (ORM) or some other mechanism. If I'm being sloppy when I implement my view model, I'll just take my data transfer objects (DTOs) from my ORM and give them to the view model, like so: public class MainWindowViewModel { public CustomerDTO Customer { get; set; } public void LoadCustomer() { // Load customer DTO from ORM (code elided) this.Customer = customerDto; } } This approach is easier because I don't have to think about which data needs to be bound in the view. But it presents a number of issues, the biggest concern being that I'm tightly coupling my application's data access layer to my presentation layer, which makes testing and refactoring more difficult. In addition, my view has direct access to the DTO. It could inadvertently access properties that could have unwanted side effects. Suppose I have a Customer object from NHibernate, an open source ORM for .NET that has an Orders property, which is lazy loaded. Any access to that property could cause additional SQL queries to be executed. Finally, it's more difficult to collaborate with a UI designer if I don't have a clearly defined set of properties that are available for binding or display. This may be less of an issue in larger shops, but if you're like me (with little talent for UI design) being able to interface with a graphic designer on my WPF layout is a huge bonus. So, to combat these issues, I create a focused ViewModel, as shown in Listing 1. This approach makes it clear what data is available for binding/display, but it adds quite a bit of work. I need to project my DTO data into my ViewModel data one field at a time -- a common problem in ASP.NET MVC applications. AutoMapper can make this job easier. Introducing AutoMapper The AutoMapper homepage is AutoMapper.org. You can install it via NuGet or download releases from the homepage. In this article, I'll cover AutoMapper 2.0, which is free for proprietary use under the MIT License. The latest version of the software has few breaking changes from the 1.x version, so much of this article will apply to earlier versions. The first step in using AutoMapper is to initialize your mappings. This is only done once per AppDomain. For ASP.NET MVC apps, this usually means Application_Start. For Windows or WPF applications, this is usually done before the first form or window is displayed. Initializing AutoMapper is easy. It has a number of default conventions for mapping that it recognizes; it also allows you to configure your own mappings if you encounter a situation not handled by AutoMapper. Here's how I refactored the WPF example using AutoMapper. First, I created a class that represents the data from the DTO that I want to use: public class CustomerInfo { public string Name { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } Next, I tell AutoMapper how to "map" the data from the CustomerDTO into this CustomerInfo class. Inside my App.xaml.cs, I override the OnStartup method so I can initialize AutoMapper before my WPF app displays the main view: protected override void OnStartup(StartupEventArgs e) { InitializeAutoMapper(); base.OnStartup(e); } private void InitializeAutoMapper() { Mapper.CreateMap<CustomerDTO, CustomerInfo>(); Mapper.AssertConfigurationIsValid(); } As you can see, very little setup is needed. The CreateMap call sets up a mapping between a source class and a destination class. AutoMapper has a number of built-in conventions to make setup of your mappings easier. Properties of the same name and type between the source and destination classes are simply copied as is by default. My CustomerInfo class and CustomerDTO class contain properties of the same name and type, so no additional setup is needed. The last line of InitializeAutoMapper ensures that all of my mappings are set up properly. This will throw an exception if I forget to define a mapping for one of the fields on the destination class. When you use AutoMapper, always include a call to AssertConfigurationIsValid -- it can save you a lot of headaches. It's akin to catching compile-time errors versus runtime errors. Finally, I changed my LoadCustomer method to use AutoMapper instead of manual mapping code: public void LoadCustomer() { // Load customer DTO from ORM (code elided) this.CustomerInfo = Mapper.Map<CustomerDTO, CustomerInfo>(customerDto); } Much cleaner! I don't even need to create an instance of CustomerInfo. I just tell AutoMapper to map the existing CustomerDTO to a CustomerInfo class and it automatically instantiates a new version of the CustomerInfo class, performs the mappings and returns the mapped destination object. Additional Conventions In addition to property name matching, AutoMapper allows destination properties to be obtained from a matching method. Imagine I have a complex EngineConfiguration class: public class EngineConfiguration { public string ModelNumber { get; set; } public int ModelYear { get; set; } public int CylinderCount() { return 8; } // Dozens of other properties removed for brevity } I want to display some simple engine information in my WPF application so I define a class for the data I want to display: public class EngineInfo { public string ModelNumber { get; set; } public int ModelYear { get; set; } public int CylinderCount { get; set; } } Initializing the mapping for these two classes inside InitializeAutoMapper is easy: Mapper.CreateMap<EngineConfiguration, EngineInfo>(); While the EngineConfiguration class doesn't contain a property called CylinderCount, it contains a matching method name with the same return type. Therefore, AutoMapper will use this method as the source for EngineInfo.CylinderCount. If AutoMapper can't find either a matching property name or method name for a particular destination property, it will look for a method on the source class called "GetXXX" where "XXX" is the name of the destination property. In the example code, the EngineInfo.CylinderCount property would look for "GetCylinderCount" if no GetCylinder property or method exists. Finally (if this wasn't enough!), if AutoMapper still can't find the source of the data for a destination property, it will split the property name into parts based on PascalCase notation and look for properties in the format [object].[propertyname]. For example, I have a CarSetup class that includes a reference to an EngineConfiguration: public class CarSetup { public string VIN { get; set; } public string Maker { get; set; } public Guid ExportCode { get; set; } public EngineConfiguration Configuration { get; set; } public int DefectRate { get; set; } } I need to display a car's VIN and the ModelNumber from the EngineConfiguration. I simply define my data class as: public class CarInfo { public string VIN { get; set; } public string ConfigurationModelNumber { get; set; } } And the mapping is: Mapper.CreateMap<CarSetup, CarInfo>(); When AutoMapper goes to populate the ConfigurationModelNumber, it won't find a property called "ConfigurationModelNumber," a method called "ConfigurationModelNumber" or a method called "GetConfigurationModelNumber." Therefore, it will break the destination property name into parts "Configuration.ModelNumber" and look in the CarInfo's Configuration property for the ModelNumber property. As you can see, the default conventions built in to AutoMapper make set up almost effortless. However, at times you may need more fine-grained control of your mappings. Luckily, AutoMapper supports this level of control. Customized Mappings The first thing most users run into with AutoMapper is a situation where they have one or two properties on the destination class that they want to set themselves -- the data can't come from the source class. Suppose I have a simple Employee database and expose some employee information: class Employee { public string Name { get; set; } public DateTime DateOfBirth { get; set; } public DateTime HireDate { get; set; } public Employee Supervisor { get; set; } } I've got an application that needs to display an employee's name along with how many sick days that person has used: class EmployeeStats { public string Name { get; set; } public int SickDaysUsed { get; set; } } The number of sick days used comes from a different system -- I won't find it in the Employee class. When setting up the mapping, I can start with the basic CreateMap: Mapper.CreateMap<Employee, EmployeeStats>(); But if I ask AutoMapper to validate my configuration with Mapper.AssertConfigurationIsValid it throws an exception because it doesn't know (and I haven't told it) how to map SickDaysUsed. I'll get this value from another system, so I'll just tell AutoMapper to ignore that field when performing a Map: Mapper.CreateMap<Employee, EmployeeStats>() .ForMember(d => d.SickDaysUsed, o => o.Ignore()); The ForMember method takes two lambdas: The first one identifies the destination field I'm setting up a mapping for and the second one identifies various options for the mapping. In this case, I use the AutoMapper Ignore option. My configuration is now valid. Using this mapping is as simple as: var employee = GetEmployee(); var stats = Mapper.Map<Employee, EmployeeStats>(employee); stats.SickDaysUsed = GetSickDays(employee); In other situations, you might want to define your own logic for mapping. Suppose I needed a simple form that displays an employee's name and years of service. I don't store how long the employee has been working -- only their hire date. Of course, it's trivial to calculate such a date -- but it's not something built in to AutoMapper. For this, I'll have to write some custom code for AutoMapper to use. I'm using the same Employee class defined for the last example. Now I need a class to store the view data: class EmployeeService { public string Name { get; set; } public int Years { get; set; } } Next, I define my mapping along with a special setting for the "Years" property: Mapper.CreateMap<Employee, EmployeeService>() .ForMember(d => d.Years, o => o.MapFrom(s => (DateTime.Now - s.HireDate).TotalDays/365)); This time, instead of using the Ignore option, I used the MapFrom option. This option takes a lambda that references the source object that's being mapped. I do a quick calculation of the employee's years of service based on the current date and hire date. This data is mapped to EmployeeService.Years. The MapFrom option provides an easy way to do simple calculations to determine the destination property value. Custom Value Resolvers Sometimes, the logic used in the MapFrom option gets a little complex -- even to the point that you'll want to unit test it. In that case, AutoMapper lets you create a standalone class to convert a value from one type to another. Let's say that for whatever reason (company merger, accounting laws), calculating the years of service got a bit more complex: "If an employee is 50 years old or older, years of service is determined based on hire date. If an employee is younger than 50 years old, years of service is 3 less than the number of years since the hire date." Normally, something like this would probably be domain logic placed somewhere in the domain model. But for the sake of this example, I'm going to create a custom value resolver: class YearsOfServiceResolver : ValueResolver<Employee, int> { protected override int ResolveCore(Employee source) { var age = DateTime.Now - source.DateOfBirth; if (age.TotalDays / 365 >= 50) { return (int) ((DateTime.Now - source.HireDate).TotalDays/365); } return (int) ((DateTime.Now - source.HireDate).TotalDays/365) - 3; } } The ValueResolver<TSource, TDest> type comes from AutoMapper. Simply inherit from that class and override the ResolveCore method to implement the logic. This customized logic is now in a class by itself and can be unit tested with the rest of my code. Now I need to tell AutoMapper to use this custom value resolver when mapping the EmployeeService.Years property: Mapper.CreateMap<Employee, EmployeeService>() .ForMember(d => d.Years, o => o.ResolveUsing<YearsOfServiceResolver>()); In addition to specifying the custom resolver via Resolve¬Using<Type> syntax, I could use the Microsoft .NET Framework 2.0 style of ResolveUsing(typeof(YearsOfServiceResolver)) or even provide a specific instance of the custom value resolver. Custom Type Converters Sometimes, the only thing you can do when converting one type to another is to take complete control of the conversion. This is where custom type converters come in. I once had a legacy system that stored the date in the Unix timestamp format. If you're not familiar with it, the Unix timestamp is the number of seconds that have passed since the Unix epoch of Jan. 1, 1970. So the value of 86,400 would represent Jan. 2, 1970 (1 second * 60 seconds per minute * 60 minutes per hour * 24 hours == 1 day or 86,400 seconds). I didn't want my ViewModels (or my controllers in ASP.NET MVC) to have to worry about doing the conversion. The solution was to create a custom type converter that would convert from the Unix time to a .NET DateTime. AutoMapper defines a generic interface for custom type converting. All I had to do was implement the logic to convert a double (the Unix date from the legacy system) to a .NET DateTime: class UnixDateConverter : ITypeConverter<double, DateTime> { public DateTime Convert(ResolutionContext context) { var source = (double) context.SourceValue; var unixEpoch = new DateTime(1970, 1, 1); var localDate = unixEpoch.AddSeconds(source).ToLocalTime(); return localDate; } } I tell AutoMapper to use this converter whenever it needs to convert a double to a DateTime by using the CreateMap call, but I add an option: Mapper.CreateMap<double, DateTime>().ConvertUsing<UnixDateConverter>(); This approach makes the converter global to AutoMapper -- there's no need to define this using ForMember calls on individual properties. I define it once at the beginning of my mappings and all other classes that have properties that need to be converted from double to DateTime will use this converter. List and Array Support Rarely do developers work on a single item. All of the examples so far have dealt with a single entity (an Employee, a Customer). In the real world, you're dealing with a collection of employees or customers. AutoMapper doesn't require special support for converting a list or an array of items. As long as I define the element type mapping, AutoMapper can handle enumerating the list, performing the mapping and returning a new, mapped list. All of the mappings I've showed so far don't need any changes (or additional mappings defined) to support a collection of employees: var partTimers = GetParttimeEmployees(); var mapped = Mapper.Map<IEnumerable<Employee>, IEnumerable<EmployeeStats>>(partTimers); The full range of supported collection types is documented on the AutoMapper Web site. Pre and Post Mapping Actions AutoMapper will also let you define code to run before and after the mapping process. The pre-condition is useful if you have a property on your source object that you want to use in the mapping, but it has to be loaded or initialized before it can be used (perhaps loaded from NHibernate). For this type of situation, use the BeforeMap method: Mapper.CreateMap<SelectedJob, Job>() .BeforeMap((s, d) => ...); The lambda gets access to both the mapped source object (the first parameter) as well as the destination object (the second parameter). Likewise, you can define an AfterMap lambda that will be called after AutoMapper has done its job: Mapper.CreateMap<SelectedJob, Job>() .AfterMap((s, d) => ...); The sample code download for this article demonstrates the BeforeMap and the AfterMap settings (access the sample code from VisualStudioMagazine.com/Steele0212). class UserDTO { public string Name { get; set; } public int Age { get; set; } } class UserInfo { public string Name { get; set; } public int Age { get; set; } public Uri HelpUri { get; set; } } I need to map the UserDTO information into the UserInfo class, but the UserInfo class is initialized with the HelpUri somewhere else in the application. In this situation, I can use the Map overload that accepts the source and the destination object: var info = GetUserInfo(); var dto = new UserDTO { Age = 33, Name = "Bob Smith", }; Mapper.Map(dto, info); You'll note in the sample code that I still had to define an Ignore for the HelpUri property on the destination object because it's pre-populated in the existing destination and I don't want AutoMapper doing anything with it. Controlling Destination Class Creation When AutoMapper creates your destination class for you, it uses the class' default, parameterless constructor. What if your destination class doesn't have a parameterless constructor? Or your destination class needs to come from a factory or an IoC container? AutoMapper has that covered. When defining a map with CreateMap, you can supply a lambda that will tell AutoMapper how to create the destination object. Here's an example where I need to map a Ninja class to a Fighter class. My destination class, Fighter, comes from an IFighterFactory: interface IFighterFactory { Fighter GetFighter(); } class Ninja { public string Name { get; set; } } public class Fighter { public Guid Id { get; set; } public string Type { get; set; } public string Name { get; set; } } When I define my mapping at application startup, I'll tell AutoMapper to use my factory to construct the Fighter class ("factory" refers to an existing IFighterFactory): Mapper.CreateMap<Ninja, Fighter>() .ConstructUsing(s => factory.GetFighter()) .ForMember(d => d.Id, o => o.Ignore()) .ForMember(d => d.Type, o => o.MapFrom(s => "NINJA")); Note that I also had to add two special mappings: The Id property is pre-populated from my factory as part of its creation and I don't want AutoMapper to change it. The Type property is hardcoded to "NINJA" during the mapping. Defining Your Own Profiles As you use AutoMapper more and more, you'll want to centralize the configuration of your mapping initialization. This makes the re-use of your mapping configuration throughout your application easier to share and maintain. AutoMapper calls these configuration classes "Profiles." You define your own profile by creating a class that inherits from AutoMapper.Profile. Listing 2, is an example Profile that I could've used in the sample code -- it only includes a few of the CreateMap calls. Configuring AutoMapper using a Profile is simple: Mapper.Initialize(c => c.AddProfile<SampleProfile>()); Mapper.AssertConfigurationIsValid(); With your configuration centralized, utilizing AutoMapper across multiple applications that share your domain libraries becomes much, much easier. AutoMapper is free software that can make mapping code easier to write and maintain while still giving you the flexibility to work in most any environment Printable Format > More TechLibrary I agree to this site's Privacy Policy.
https://visualstudiomagazine.com/articles/2012/02/01/simplify-your-projections-with-automapper.aspx
CC-MAIN-2018-39
refinedweb
3,203
53.31
Hide Forgot This bug was initially created as a copy of Bug #1927678 I am copying this bug because: This is a backport BZ for the BMO code that just landed in 4.8 ( so we can pull it into 4.7.z. Note this code relies on CAPBM code also being pulled in and backported, this is currently unmerged ( Description of problem: The current implementation of the reboot interface relies on the `reboot.metal3.io` annotation being applied via the MachineHealthCheck system, and whilst this works, the implementation for the Ironic provisioner first attempts to use a soft power off function, as implemented with this PR ( with the specific line of code here: In some circumstances, e.g. soft power off is issued but it doesn't get enacted, we can run into a situation where a three minute timeout must occur before the hard power off will be attempted. Unfortunately for use-cases where we want to rely on this interface to rapidly reboot hosts and recover workloads for high-availability purposes, e.g. virtual machine failover, this can lead to a circa 5 minute total recovery time, too long to be widely adopted for high-availability requirements. For high availability use-cases we should default to hardPoweroff(). We recognise that softPowerOff is favourable when we want to instruct the hosts to reboot but we want them to do this gracefully, e.g. software update, so the reboot interface needs to maintain the option for a soft reboot. Ideally we need to be able to select whether we first invoke the hard reboot or not, and make that configurable to the operator. Perhaps on a per-host basis with an annotation, or with a global config-map, or perhaps even via a MachineHealthCheck option. Some further discussion on this can be found here: and the suggestion is that we implement an extension to the reboot annotation, e.g. `reboot.metal3.io = {'mode': 'hard'}` where we override the default behaviour for circumstances in which customers need to enable much quicker recovery of workloads, if this is left off, we default to soft; I'm just not sure which mechanism could be used to get the MHC to label it this way. Version-Release number of selected component (if applicable): Tested with OpenShift 4.6.16 on virtualised baremetal (IPI install with Metal3 and virtualbmc). How reproducible: Every time Steps to Reproduce: 1. Deploy OpenShift baremetal IPI cluster via Metal3 2. Apply a MachineHealthCheck (see example below) 3. Cause the machine to go NotReady, e.g. sysrq or something 4. Observe the MHC logs to see that it recognises node unhealthy and trigger remediation after ~100 seconds (40s k8s timeout, 60s health check). 5. Remediation then takes a further ~200s, as 180s is lost on softPowerOff() which will fail under certain circumstances. Actual results: Recovery of workload takes circa 5 minutes, too long for a true HA scenario. Expected results: Recovery of workload takes circa 2 minutes maximum (can be further tweaked with tighter MHC timings, but we have to give k8s 40s by default - 4x10s notification timeouts) Additional info: MHC example- apiVersion: machine.openshift.io/v1beta1 kind: MachineHealthCheck metadata: name: workers namespace: openshift-machine-api annotations: machine.openshift.io/remediation-strategy: external-baremetal spec: maxUnhealthy: 100% selector: matchLabels: machine.openshift.io/cluster-api-machine-role: worker unhealthyConditions: - type: Ready status: Unknown timeout: 60s - type: Ready status: 'False' timeout: 60s Other resources that help explain where the softPowerOff() default came from: BMO bug report tracking the fact that we should do soft-shutdown BMO bugfix to make soft-shutdown the default BMO proposal for reboot API BMO PR to implement reboot API Since the problem described in this bug report should be resolved in a recent advisory, it has been closed with a resolution of ERRATA. For information on the advisory (OpenShift Container Platform 4.7.6 bug fix update), and where to find the updated files, follow the link below. If the solution does not work for you, open a new bug report.
https://bugzilla.redhat.com/show_bug.cgi?id=1936407
CC-MAIN-2022-21
refinedweb
674
50.77
I heard someone say the other day that the advantage of formal software validation methods is that they let you explore the corners, cases where intuition doesn’t naturally take you. This made me think of corners in the geometric sense. If you have a sphere in a box in high dimensions, nearly all the volume is in the corners, i.e. outside the sphere. This is more than a metaphor. You can think of software options geometrically, with each independent choice corresponding to a dimension. Paths through a piece of software that are individually rare may account for nearly all use when considered together. With a circle inside a square, nearly 78.5% of the area is inside the circle. With a ball sitting inside a 3-D box, 52.4% of the volume is inside the ball. As the dimension increases, the proportion of volume inside the sphere rapidly decreases. For a 10-dimensional sphere sitting in a 10-dimensional box, 0.25% of the volume is in the sphere. Said another way, 99.75% of the volume is in the corners. When you go up to 100 dimensions, the proportion of volume inside the sphere is about 2 parts in 1070, a 1 followed by 70 zeros [1]. If 100 dimensions sounds like pure fantasy, think about a piece of software with more than 100 features. Those feature combinations multiply like geometric dimensions [2]. Here’s a little Python code you could use to see how much volume is in a sphere as a function of dimension. from scipy.special import gamma from math import pi def unit_sphere_volume(n): return pi**(0.5*n)/gamma(0.5*n + 1) def unit_cube_volume(n): return 2**n def ratio(n): return unit_sphere_volume(n) / unit_cube_volume(n) print( [ratio(n) for n in range(1, 20)] ) * * * [1] There are names for such extremely large numbers. These names are hardly ever used—scientific notation is much more practical— but they’re fun to say. 1070 is ten duovigintillion in American nomenclature, ten undecilliard in European. [2] Geometric dimensions are perfectly independent, but software feature combinations are not. In terms of logic, some combinations may not be possible. Or in terms of probability, the probability of exploring some paths is conditional on the probability of exploring other paths. Even so, there are inconceivably many paths through any large software system. And in large-scale operations, events that should “never happen” happen regularly. 2 thoughts on “Formal methods let you explore the corners” OK, I should have been working instead of surfing the web. But I followed this link That pointed to an interesting article on Scientific American: An interesting piece on error correction using Sphere-packing. As I’m reading it, I remember your intriguing post about corners. I find it fascinating and fun when connections are made from random points.
https://www.johndcook.com/blog/2016/07/11/formal-methods-let-you-explore-the-corners/
CC-MAIN-2017-22
refinedweb
478
57.77
09 August 2011 09:07 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The plant’s current run rate is 80%, with a strong likelihood of further decline in output given disruptions to feedstock supply following recent fires at the Mailiao petrochemical complex, the source said. All its output will be for captive use, he said. FPCC supplies the bulk of its ECH produce to the epoxy resins plant of FPCC’s sister firm, Nan Ya Plastics, while a small quantity is shipped out, the source said. The ECH plant is due for a month-long turnaround in September. FPCC is expected to submit a detailed plan to the Taiwanese government on its plan to do safety checks at the Mailiao complex on 10 August, company sources said. This follows a string of fire incidents that led to the resignation of the company’s chairman and CEO early this month. Additional reporting
http://www.icis.com/Articles/2011/08/09/9483515/taiwans-fpcc-halts-ech-exports-from-mailiao-plant.html
CC-MAIN-2014-49
refinedweb
151
67.49
Hello all, Another update to the PI file generator for .NET objects. This one adds return type annotations for methods. It means that if you do something like: from System import Guid g = Guid.NewGuid() Wing knowsthat "g" is a Guid and provides the correct auto-complete members for it. This is *great*. See previous instructions on how to use the script. It now takes quite a *long* time to generate all 90 PI files. :-) There is a caveat with this currently: Many methods return types that are defined in other namespaces (especially types defined in System). Because those types are in another PI file, Wing doesn't recognise them. I'll work out how to fix this ("from System import *" at the top of each PI file might catch most cases). Secondly return types can currently return things like Array[int]() the indexing will cause Wing to effectively ignore the return type - so I should change this to Array(). Still - getting there step-by-step and this is already enormously useful to me. I'm currently using a truly horrible regular expression to pull the return type out of the docstring... I'll write this all up into a proper 'HOWTO: IronPython in Wing' once I have time. All the best, Michael >> > > > ------------------------------------------------------------------------ > > _________________________________________________ > Wing IDE users list > -- -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: generate_pi_for_net.py URL: <>
https://mail.python.org/pipermail/ironpython-users/2009-April/010158.html
CC-MAIN-2016-36
refinedweb
232
73.47
Java Access to SQL Azure via the JDBC Driver for SQL Server The Cloud Zone is brought to you in partnership with Iron.io. Discover how Microservices have transformed the way developers are building and deploying applications in the era of modern cloud infrastructure. I’ve written a couple of posts (here and here) about Java and the JDBC Driver for SQL Server with the promise of eventually writing about how to get a Java application running on the Windows Azure platform. In this post, I’ll deliver on that promise. Specifically, I’ll show you two things: 1) how to connect to a SQL Azure Database from a Java application running locally, and 2) how to connect to a SQL Azure database from an application running in Windows Azure. You should consider these as two ordered steps in moving an application from running locally against SQL Server to running in Windows Azure against SQL Azure. In both steps, connection to SQL Azure relies on the JDBC Driver for SQL Server and SQL Azure. The instructions below assume that you already have a Windows Azure subscription. If you don’t already have one, you can create one here:. (You’ll need a Windows Live ID to sign up.) I chose the Free Trial email after signing up). Connecting to SQL Azure from an application running locally I’m going to assume you already have an application running locally and that it uses the JDBC Driver for SQL Server. If that isn’t the case, then you can start from scratch by following the steps in this post: Getting Started with the SQL Server JDBC Driver. Once you have an application running locally, then the process for running that application with a SQL Azure back-end requires two steps: 1. Migrate your database to SQL Azure. This only takes a couple of minutes (depending on the size of your database) with the SQL Azure Migration Wizard - follow the steps in the Creating a SQL Azure Server and Creating a SQL Azure Database sections of this post. 2. Change the database connection string in your application. Once you have moved your local database to SQL Azure, you only have to change the connection string in your application to use SQL Azure as your data store. In my case (using the Northwind database), this meant changing this… String connectionUrl = "jdbc:sqlserver://serverName\\sqlexpress;" + "database=Northwind;" + "user=UserName;" + "password=Password"; …to this… String connectionUrl = "jdbc:sqlserver://xxxxxxxxxx.database.windows.net;" + "database=Northwind;" + "user=UserName@xxxxxxxxxx;" + "password=Password"; (where xxxxxxxxxx is your SQL Azure server ID). Connecting to SQL Azure from an application running in Windows Azure The heading for this section might be a bit misleading. Once you have a locally running application that is using SQL Azure, then all you have to do is move your application to Windows Azure. The connecting part is easy (see above), but moving your Java application to Windows Azure takes a bit more work. Fortunately, Ben Lobaugh has written a great post that that shows how to use the Windows Azure Starter Kit for Java to get a Java application (a JSP application, actually) running in Windows Azure: Deploying a Java application to Windows Azure with Command-Line Ant. (If you are using Eclipse, see Ben’s related post: Deploying a Java application to Windows Azure with Eclipse.) I won’t repeat his work here, but I will call out the steps I took in modifying his instructions to deploy a simple JSP page that connects to SQL Azure. 1. Add the JDBC Driver for SQL Server to the Java archive. One step in Ben’s tutorial (see the Select the Java Runtime Environment section) requires that you create a .zip file from your local Java installation and add it to your Java/Azure application. Most likely, your local Java installation references the JDBC driver by setting the classpath environment variable. When you create a .zip file from your java installation, the JDBC driver will not be included and the classpath variable will not be set in the Azure environment. I found the easiest way around this was to simply add the sqljdbc4.jar file (probably located in C:\Program Files\Microsoft SQL Server JDBC Driver\sqljdbc_3.0\enu) to the \lib\ext directory of my local Java installation before creating the .zip file. Note: You can put the JDBC driver in a separate directory, include it when you create the .zip folder, and set the classpath environment variable in the startup.bat script. But, I found the above approach to be easier. 2. Modify the JSP page. Instead of the code Ben suggests for the HelloWorld.jsp file (see the Prepare your Java Application section), use code from your locally running application. In my case, I just used the code from this post after changing the connection string and making a couple minor JSP-specific changes: <%@ page language="java" contentType="text/html; charset = ISO-8859-1" import = "java.sql.*" %> <html> <head> <title>SQL Azure via JDBC</title> </head> <body> <h1>Northwind Customers</h1> <% try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionUrl = "jdbc:sqlserver://xxxxxxxxxx.database.windows.net;" + "database=Northwind;" + "user=UserName@xxxxxxxxxx;" + "password=Password"; Connection con = DriverManager.getConnection(connectionUrl); out.print("Connected.<br/>"); String SQL = "SELECT CustomerID, ContactName FROM Customers"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(SQL); while (rs.next()) { out.print(rs.getString(1) + ": " + rs.getString(2) + "<br/>"); } }catch(Exception e){ out.print("Error message: "+ e.getMessage()); } %> </body> </html> That’s it!. To summarize the steps… - Migrate your database to SQL Azure with the SQL Azure Migration Wizard. - Change the database connection in your locally running application. - Use the Windows Azure Starter Kit for Java to move your application to Windows Azure. (You’ll need to follow instructions in this post and instructions above.) Thanks. -Brian The Cloud Zone is brought to you in partnership with Iron.io. Learn how to build and test their Go programs inside Docker containers. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/java-access-sql-azure-jdbc?mz=62447-cloud
CC-MAIN-2015-48
refinedweb
1,011
55.13
SwitchYard runtime configKeith Babo Mar 21, 2011 11:10 PM This has come up several times in the last week, so I figured I would start a thread for us to hash it out. We all recognize that there will be runtime-level configuration outside of the SwitchYard application configuration, but we've danced around it up to this point. I think we're getting to the point where we need to bang out an implementation and lose some of the hard-coded config we have stashed around. IINM, we can use the existing configuration implementation to support a separate config file, so I'm assuming that the plumbing is already present. All we need to do is settle on the initial set of config values and the basic structure. I'll kick this off with a few items: 1) The list of component activators is currently hard-coded in the deployer implementation. 2) The bus provider(s) configuration (e.g. local, HornetQ, etc.) 3) Registry configuration details. Not an issue today because we have not distributed the registry, but I'm guessing that this will come up when we go to use JGroups or Infinispan. 4) List of out-of-the-box transfomers available. I know there are more, so please pile on with others. 1. Re: SwitchYard runtime configTom Fennelly Mar 23, 2011 1:09 PM (in response to Keith Babo) So are we talking about a process whereby these runtime configs are loaded based on a classpath scan for one or more runtime config files? For example, out-of-the-box transformers are placed in META-INF/switchyard/transforms.xml and would only contain TransformsModel data? 2. SwitchYard runtime configKeith Babo Mar 25, 2011 7:10 AM (in response to Tom Fennelly) That's a good point about META-INF/transforms.xml. For the benefit of folks that did not see our #switchyard IRC conversation yesterday, here are the use cases we talked about for transformer configuration: 1) we have a stock set of transformers that we define and these are wrapped up in a definition file inside a jar 2) the user might want to supply instance/domain-wide transforms and those can be put in the runtime config 3) lastly, there may be application-specific transforms and those go in switchyard.xml The runtime configuration I was referring to when I originally created this thread was #2 above. It's a configuration that controls the configuration of a service domain and anything it creates (registry, bus, activators, etc.). Looks like we will need to add config support for #1 as well.. 3. Re: SwitchYard runtime configTom Fennelly Mar 30, 2011 8:15 AM (in response to Keith Babo) Keith Babo wrote:. One uber config namespace for everything? Not sure how nicely that would play with the configuration code, since it relies on the namespacing to split out the configs. One uber config namespace would mean all the config stuff we currently have split out for core, transform, soap, bean etc would all be piled in together. In time, I'd say that could become a big blob. It would work... just saying that I wouldn't really like it... I think having the separate concerns split out cleanly into their own namespaces is nice. 4. SwitchYard runtime configKeith Babo Mar 30, 2011 8:34 AM (in response to Tom Fennelly) We definitely can't have one uber namepsace for everything, because it destroys our modularity and extensibility support. To be perfectly honest, I can't remember what point I was trying to make with the single schema thing. ;-) I think I might have meant that the runtime configuration that I referred to in the first post can all go in the same schema. One risk with the modular configuration is that you end up with a schema for each element in the name of modularity. Certainly there are cases where this is appropriate (e.g. component schemas), but we should try to group schema definitions when they are related (e.g. runtime configuration).
https://community.jboss.org/message/595152
CC-MAIN-2015-22
refinedweb
678
60.85
Geb (pronounced “jeb”) is the answer to the challenges of browser automation. It is a very effective tool to perform automation testing over the web. Geb originated out of the need to make browser automation (initially for web testing) less complicated, hassle-free and more efficient. It may be utilized for programming, extracting data from the web and automating the manual web tasks. Additionally, Geb is a cross-browser tool for automation testing. Geb functions as a developer-driven tool for automating the collaboration between web browsers and web content. It runs the WebDriver in Groovy language. The beauty of Geb testing tool is that it combines the best features of Groovy programming language, jQuery, WebDriver and Page Object Modelling to provide powerful, robust & dynamic content inspection, selection and web interaction. What makes Geb unique when compared to other automation testing tools available in the market is its syntax. It is similar to jQuery that is normally used for querying the HTML pages easily. Secondly, it has integrated support for the Page Object pattern. Geb provides great help for functional web testing through integration with some broadly used and common testing platforms including Spock, Grails, JUnit, Cucumber-JVM, TestNG, etc. We will see how Geb can be integrated with Grails framework in the later part of this article. What You Will Learn: Practical Uses As already discussed in the introduction of this Geb tutorial, it can be used: - As a Testing tool on multiple browsers like chrome, Firefox, Internet explorer, etc. (The same automation script can be run on different browsers to perform web testing of your application.) - To automate User acceptance and functional test cases. - To automate test scenarios created for functional or web testing of any application. - To cover the end to end testing including the UI (User Interface) validation and DB (Database) validation. - As a Developer’s tool for automating the interaction between a web browser and web content. Advantages - Geb is a free, open-sourced tool. It is licensed under the Apache License, Version 2.0. - Easy and simple to automate web testing. - Geb’s Page Objects and Groovy DSL make tests readable to the extent that they almost look like plain English. - Runs the tests fast and thus saves the time and cost of testing. - Compatible with different browsers like IE, Firefox, Chrome, and HTMLUnit. - It executes the tests in the real browser. It is as if testing in the real environment- the one that the user would see. - It makes the regression testing easy. You can run the Geb automated test cases to check if any existing functionality is breaking after a fix or change in the application. - While using Geb for automation testing, minimal test code changes are required if there are any UI changes in your application. So, it reduces the effort & duplication of code. - It helps 360 degrees (or maximum) testing coverage within the single script. Prerequisites Before getting started, we need to download and install the software. At the central Maven repository, Geb is available as a single Geb-core jar. Click here to install it on your machine. You will need the above Geb-core jar, a web driver implementation, and the selenium-support jar to get Geb working on your machine. Please refer to the below installation and usage section of the book of Geb to install the tool and get it running => Geb installation and usage manual. Getting Started As already discussed, Geb can be integrated with different testing frameworks. Depending on the framework you have chosen, you will need to install the related plugin. For example: Grails (Grails is a very famous framework for web applications) to write automation test scripts and automate the test scenarios. If you wish to use Geb for your Grails functional testing, you can install the related plugin from here grails-geb plugin. This plugin handles the baseUrl and reportsDir configuration items. Learn with Example Let me now show how to write a Geb script to automate a test scenario. Take the below test scenario: The execution steps are: Here is the Geb automation tool script for the above scenario: import geb.Browser Browser.drive { go "" //verify if we are on the correct page assert title=="Google" //enter softwaretestinghelp.com into the search field $("input",name:"q").value("softwaretestinghelp.com") //wait for the change to results page to happen //(google updates the page dynamically without a new request) waitFor{ title.endsWith("Google Serach")} //is the first link to softwaretestinghelp.com? def firstLink = $("li.g,0).find("a.l") assert firstLink.text()= ="Software Testing Help - A Must Visit Software Testing Portal" //click the link firstLink.click() //wait for Google's javascript waitFor { title = ="Software Testing Help - A Must Visit Software Testing Portal" } } You can now try writing a simple GEB script on your own referencing the above example. Database validation testing through Geb script: Any web automation testing is divided into three parts: - UI Validation – Validating the data reflected on the user interface (front end) before & after the automation test scenario run. - DB Validation – Validating the data reflected in the database (backend) before & after the automation test scenario run. - Actual Test flow/ Script flow. The Geb script written to automate a test scenario can contain the code for all of the above three sections. The Geb script in the above example section was for automating the test flow and UI validation. Similarly, you can write a test script for database validation. For any DB validation test, you can always use the below template as an outline for your code: def validateDB(/*define all variables here*/) { def errorMessages = "" try { Configuration conf = (new ConfigurationLoader()).getConf() def sql = Sql.newInstance(conf.readValue("dbPath", ""), conf.readValue("dbUserName", ""), conf.readValue("dbPassword", ""), conf.readValue("dbDriverName", "")) /* Populate any required variables */ } /* Give print commands here to print required values */ def qry = /* select statement to pull all required values from database */ println "SQL=$qry" sql.eachRow(qry) { row -> /* ‘if’ block to perform validation and returning error in case of any variations */ } catch(Exception e) { println "EEEE=$e" } return errorMessages } Few useful Methods in Geb - When your test case scenario involves multiple tabs and windows: Whenever you come across an application that opens up new windows or tabs, For example when clicking on a link with a target attribute set, you can make use of withWindow() and withNewWindow() methods to execute code in the context of other windows. - The drive method: Browser class contains a static method – drive(). This method gives an extra convenience to Geb scripting. All top level method calls and property accesses are implied to be against the browser. - Making Requests: Browser instances uphold a baseUrl property that is employed to resolve all relative URLs. It is usually most preferable to define your base URLs with trailing slashes and not to use leading slashes on relative URLs. - Changing the Page: With the help of useful page() methods, it is feasible to change the page instance without making a new request. - Quitting the Browser: The browser object provides quit() and close() methods (that simply handover the task to the base driver). Drawbacks of this tool - Geb executes WebDriver in the Groovy language. The whole idea behind this is to make the use of WebDriver easier and simpler. So, when you using Webdriver through Geb, only Groovy programming language will be supported. But, if you directly use WebDriver, it supports many languages like Ruby, C#, Python, Java. - I would not suggest the use of Geb for small projects – It works awesome for enormous tasks but takes a hit on small activities. If your web application does not contain multiple pages and forms through which the information needs to flow, you may discover Geb really costs you additional time than it spares. - It is very particular about what environment your website application utilizes. Geb is required to be well integrated into a specific environment to make it function fine. More resources: - Check out the Book of Geb here for detailed documentation and examples. - Here is a sample project showing the integration of Geb with grails. Conclusion Geb is very useful in automating test case scenarios. It is useful to automate web, functional and user acceptance testing. It supports multiple browsers and can be integrated with different frameworks. It combines the power of WebDriver, elegance of jQuery Selection, the robustness of Page Object Modelling and expressiveness of Groovy. Geb scripts are both developer and user-friendly providing better test coverage and accelerated testing while making it more efficient at the same time. About the author: This is a guest post by Priya K. She is having 4+ years of experience in IT Services with expertise in Testing and support for various applications. Feel free to post your Geb automation testing queries in comments. 10 thoughts on “Geb Tutorial – Browser Automation Testing Using Geb Tool” Thank you for the getting started tutorial. Someones can compare this framework with Selenium ? Its really a good starting point for geb learning. Hi Priya I am using GEB Cucumber Groovy test framework, where i have feature files and corresponding Step Def file. Now i want to work on reporting part, which is the best tool(Test NG, Extent Reports) to integrate to get good good reports. Also need to basic Code on integrating TestNG or Extent report to Cucumber Geb Groovy test framework. Looks like need update code part of the tutorial. There is website title already changed to “Software Testing Complete Guide — Software Testing Help” This part needs to be fixed also: def firstLink = $(“li.g,0).find(“a.l”) Someones can compare this framework with Selenium ? no GUI, only scripting – it really sucks! I can’t get this script to run. What may I be doing wrong? I’m getting this error: Caught: java.lang.NoClassDefFoundError: geb/error/UnableToLoadException java.lang.NoClassDefFoundError: geb/error/UnableToLoadException at geb.Browser.(Browser.groovy:61) at geb.Browser.drive(Browser.groovy:1028) at geb.Browser$drive.call(Unknown Source) at firstGroovy.FirstGeb.run(FirstGeb.groovy:4) I’ve got your script on a groovy file, and the following GebConfig.groovy file: package firstGroovy /* This is the Geb configuration file. See: */ import org.openqa.selenium.chrome.ChromeDriver import org.openqa.selenium.firefox.FirefoxDriver // Use firefox as the default // See: driver = { new ChromeDriver() } environments { // run as “gradle -Dgeb.env=chrome cucumber” // See: chrome { driver = { new ChromeDriver() } } } baseUrl = “” baseNavigatorWaiting = true atCheckWaiting = true I’ve added geb-core, selenium-support jars, as well as selenium libs into buildpath. Any clues? how to take screenshots when used GEB+TESTNG+GRADLE Hi, How will I fetch dynamic URL if I go that URL using some action button? Thanks.
https://www.softwaretestinghelp.com/geb-tutorial-browser-automation-testing-using-geb-tool/
CC-MAIN-2021-21
refinedweb
1,772
56.35
Am Wed, 08 Feb 2017 21:41:24 +0000 schrieb Mike <n...@none.com>: > On Wednesday, 8 February 2017 at 18:27:57 UTC, Ilya Yaroshenko > wrote: > > 1. Why your company uses D? > > We don't use D. > > > 2. Does your company uses C/C++, Java, Scala, Go, Rust? > > C/C++. Currently exploring Rust. > > > 3. If yes, what the reasons to do not use D instead? > > * The powers that be in my company are the kind of C programmers > that can't understand why anyone would want to use C++ (i.e. > Electrical engineers that write software). I always felt like C is the better designed language when compared to C++. Of course C misses many features of C++ and C also has some badly designed features (preprocessor, header/include system, function pointer syntax, array [n] not attached to the type but to the variable identifier). But among some useful features C++ also adds much more noise on top of the already existing C misfeatures: ugly template syntax, iostreams/pipe syntax, operator overloading for controversial operators, c++ namespaces, multiple inheritance, ... Of course C has limited means for abstraction and therefore is not suitable for certain projects. But the language feels 'cleaner' imho, C++ sources files using templates and similar features are often hard to read. But OTOH I'm an electrical engineer as well ;-) -- Johannes
https://www.mail-archive.com/digitalmars-d-announce@puremagic.com/msg32770.html
CC-MAIN-2018-47
refinedweb
225
65.62
I'm investigating some 4k stack issues with our driver, and I noticedthis ordering in do_IRQ:asmlinkage unsigned int do_IRQ(struct pt_regs regs){ ...#ifdef CONFIG_DEBUG_STACKOVERFLOW /* Debugging check for stack overflow: is there less than 1KB free? */ { ... }#endif ...#ifdef CONFIG_4KSTACKS for (;;) { ... switch to interrupt stack }#endifIs the intention of this stack overflow check to catch a currentlyrunning kernel thread that's getting low on stack space, or is theintent to make sure there's enough stack space to handle the incominginterrupt? if the later, wouldn't you want to potentially switch toyour interrupt stack to be more accurate? (I recognize that often youwill have switched to an empty stack, unless you have nestedinterrupts)Thanks,Terence-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2005/3/30/248
CC-MAIN-2014-52
refinedweb
142
52.8
11 April 2012 09:29 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The producer has not decided how long the shutdown will last, the source said, adding that poor margins were another reason for the production halt. The margins of producing solvent oils have been squeezed by high feedstock costs and weak demand, according to the source. Although the shutdown is expected to decrease the supply of aromatic solvent oils in northern No 100 and No 150 solvent oils were traded at yuan (CNY) 8,800-8,900/tonne ($1,395-1,410/tonne) and CNY 8,650-8,750/tonne EXW (ex-works), respectively, in northern China on 10 April, unchanged from the previous day, according to C1 Energy,
http://www.icis.com/Articles/2012/04/11/9548932/chinas-tianjin-xingyuan-chemical-shuts-solvent-oil-unit.html
CC-MAIN-2013-48
refinedweb
120
53.55
Details - Type: Bug - Status: Resolved - Priority: Major - Resolution: Fixed - Affects Version/s: JRuby 1.7.0.pre1 - Fix Version/s: JRuby 1.7.0.pre2 - Component/s: None - Labels:None - Number of attachments : Description Assume that s is a method that yields a single object: def s(a) yield(a) end def somethingelse s(obj) {|a, b| [a, b]} end When somethingelse executes, MRI will call obj.toAry, and if toAry returns [:thing, :otherthing], a gets :thing and b gets :otherthing. In jruby, a gets obj, and b gets nil, and obj.toAry is not called. This is tested in rubyspec/language/block_spec.rb Appears to work fine as of 1.7pre2.
http://jira.codehaus.org/browse/JRUBY-6125
CC-MAIN-2014-41
refinedweb
112
68.16
Client Side Layout Managers At runtime, Zen builds a page description on the server and ships it to the client, where the page description is unpacked, expanded, and displayed as specified. This is the classic browser-based web application that serves previously laid-out pages to remote users upon receiving their requests for display. In this case, the Zen application maintains full control over what it shows to the user. For more about this typical case, see the section “Zen Pages at Runtime” in the “Zen Client and Server” chapter of Using Zen. Client side layout provides a useful exception to this typical case. This chapter explains how to add components to Zen pages that permit a user to initiate client side adjustments to the page layout after the page has been rendered on the client. That is, the user directly manipulates the page layout by clicking and dragging the mouse. Under this model, the user interface runs in a web browser, but it is not confined to the strict request-response interchange of a web application. Rather, the browser is the means for delivering a dynamic user interface that might otherwise be written in a language such as Visual Basic. Zen supports this type of application by providing several options for client side layout management. Using Active Groups to Manage Layout The simplest option for client side layout management is to write Zen pages using the built-in client side layout managers. These built-in components are called active group components. Each of them is a Zen group component, with special capabilities to permit direct manipulation on the client side. Each active group is also a client side layout manager; the terms are interchangeable. The built-in active groups are: - - <corkboard>, which may contain <dragGroup> components <desktop>, which may contain <dragGroup> components <snapGrid>, which may contain <dragGroup> components This chapter describes how to use the built-in active groups. The next several sections describe: Vertical and Horizontal Active Groups Active Groups that Resize Proportionally Calculating Percentages for Three-Way Splits If you want to customize active group behavior in a way that applies to all components within the group, you can use the Zen client side library module to write your own client side layout manager (active group). For a full reference guide, see the chapter “Client Side Library” in this book. Vertical and Horizontal Active Groups Suppose a designer wants to divide the screen into four regions: A fixed menu area across the top An output pane across the bottom A detailed information display area on the right A main work area that would expand to use all remaining window real estate once the other areas had been addressed The designer also wants the user to be able to interactively adjust how much of the screen is devoted to the output and detail panes at runtime. Furthermore, the designer wants the layout to automatically adjust to changes in window size. That is, increasing the browser window to full screen mode would resize the main work and supplemental detail areas while leaving the size of the menu and output areas fixed. The following figure shows a conceptual view of this design: The <activeVGroup> and <activeHGroup> are ideally suited for addressing these design objectives. Unlike <vgroup> and <hgroup> which are ultimately based on HTML tables, active groups use CSS and JavaScript to divide their available screen area into discrete subsections. This subdivision is always a binary split, resulting in top and bottom children for vertical divisions, or left and right for horizontal divisions. This binary geometry is an implementation constraint, but not a design restriction. Active groups can be nested within one another to create the illusion of multi-way splitting of the available screen real estate. An example of this is shown in the previous figure where there are three divisions along the vertical: the menu area at the top, the combined main and supplemental areas across the center, and the output area at the bottom. You can provide the layout shown in the previous figure by using three nested active groups as shown in the following Zen page class: Class MyApp.ActiveTest Extends %ZEN.Component.page { Parameter #outerSplit { width:100%; height:100%; } </style> } XData Contents [ <activeVGroup id="outerSplit" noResize="true" handleThickness="1" split="30" > <group enclosingStyle="width:100%;height:100%;background:white;"> <!-- Menu Area --> </group> <activeVGroup id="innerVSplit" split="-150" > <activeHGroup id="horizontalSplit" split="80%" > <group enclosingStyle="width:100%;height:100%;background:#ccccff;"> <!-- Main Work Area --> </group> <group enclosingStyle="width:100%;height:100%;background:#ccffff;"> <!-- Supplemental Detail Area --> </group> </activeHGroup> <group enclosingStyle="width:100%;height:100%;background:cyan;"> <!-- Output Area" --> </group> </activeVGroup> </activeVGroup> </page> } ClientMethod onloadHandler() [ Language = javascript ] { ZLM.refreshLayout(); } ClientMethod onlayoutHandler() [ Language = javascript ] { ZLM.notifyResize(document.body); } } In the previous code example: The <activeVGroup> called outerSplit divides the window vertically into two regions. The top area is 30 pixels tall, is not user adjustable, and is partitioned off from the bottom area by a divider that is 1 pixel wide. The bottom area uses all but 31 pixels of the window’s height; 31 is the top height plus the handle thickness. The top area contains the label identifying the menu area. The bottom area contains an additional <activeVGroup>. The <activeVGroup> called innerVSplit again divides the window vertically where one region is 150 pixels tall. In this case, however, the split property is negative, indicating that the property is referring to space reserved for the bottom area. By default, the split is user adjustable and displays an adjustment bar of sufficient thickness to be easily grabbed by the mouse pointer. The constraints set up by the two <activeVGroup> elements have the effect of reserving 30 pixels at the top of the window, 150 pixels at the bottom, and a few (actually, 8) for adjustment and partition bars. All remaining vertical pixels are funneled into the first child of the innerVSplit group. This child is an <activeHGroup> that partitions the middle band of the window into the main work area and the supplemental detail area. This split is an 80% division of the available window width and is user adjustable by default. Active Groups that Resize Proportionally <activeVGroup> and <activeHGroup> allow “size to fit” operations on their contents. The following four steps are required to enable this functionality. Once this is set up, the groups automatically expand to fill the window on initial page load and adjust their sizes automatically in response to window resize events: The <page> component must have its layout attribute set to "none": <page xmlns="" layout="none"> This shifts responsibility for page layout from the server to the browser. The outermost active group in the XData Contents block must have its CSS width and height explicitly set to 100%. This can be set using the enclosingStyle attribute for the <activeVGroup> or <activeHGroup>. Alternatively you can do it as shown in the previous example of a Zen page class: Define a CSS style rule: XData Style { <style type="text/css"> #outerSplit { width:100%; height:100%; } </style> } ...and apply this rule to the outermost active group using the id attribute: XData Contents [ <activeVGroup id="outerSplit" noResize="true" handleThickness="1" split="30" > <!-- Everything else --> </activeVGroup> </page> } The following must be true all the way down the hierarchy of group components, from the top-level <page> container down to any group that you wish to resize automatically along with the window that contains it. If you do not wish a group to resize in this way, these restrictions are not necessary: No active group can use the layout attribute. Every group that is not an active group must have its CSS width and height attributes set to 100%. The previous Zen page class example adheres to these rules. It also shows examples of using the enclosingStyle attribute, instead of a formal CSS style rule, to define the CSS width and height. For example: <group enclosingStyle="width:100%;height:100%;background:#ccffff;"> onloadHandler and onlayoutHandler methods in the Zen page class must call back into the Zen client side library module to ensure that any user adjustments to the window size force a recalculation of the active groups’ geometry. The previous Zen page class example shows the correct calls, as follows: ClientMethod onloadHandler() [ Language = javascript ] { ZLM.refreshLayout(); } ClientMethod onlayoutHandler() [ Language = javascript ] { ZLM.notifyResize(document.body); } Calculating Percentages for Three-Way Splits The following class code shows how to implement a page that requires areas of the screen to be split three ways, using the binary splits provided by <activeVGroup> and <activeHGroup>. This design has the following features: The screen has a 10% top margin, 10% bottom margin, 12.5% left and right margins and a work area in the middle. Thus, the main work area consumes 75% of the width and 80% of the height of the available pixels in the window. The main work area is divided into thirds. Each of these thirds has its own vertical scroll bar. Resizing the window resizes these areas automatically. Visible handle thicknesses shows how the screen is being cut up. Setting handleThickness to zero would make these handles disappear entirely. The following figure shows a conceptual view of this design: You can create the layout by using active groups as shown in the following Zen page class: Class MyApp.LayoutTest Extends %ZEN.Component.page { Parameter #outerSplit { width:100%; height:100%; } </style> } /// This XML block defines the contents of this page. XData Contents [ <activeVGroup id="outerSplit" noResize="true" handleThickness="1" split="90%" > <activeVGroup id="topMarginSplit" noResize="true" handleThickness="1" split="11%" > <!-- Top Margin --> <group id="Top"/> <activeHGroup id="rightMarginSplit" handleThickness="1" noResize="true" split="88%" > <activeHGroup id="leftMarginSplit" handleThickness="1" noResize="true" split="14%" > <!-- Left Margin --> <group id="Left"/> <group layout="none" enclosingStyle="width:100%;height:100%;background:#ccccff;"> <!-- Main Work Area --> <activeHGroup id="outerThreeway" noResize="true" handleThickness="2" split="67%" > <activeHGroup id="innerThreeway" noResize="true" handleThickness="2" split="50%" > <group id="leftLeft" enclosingStyle="width:100%;height:100%;overflow:scroll;background:#ffcccc;"> <label value="Left-Left"/> </group> <group id="leftRight" enclosingStyle="width:100%;height:100%;overflow:scroll;background:#ccffcc;"> <label value="Left-Right"/> </group> </activeHGroup> <group id="rightRight" enclosingStyle="width:100%;height:100%;overflow:scroll;background:#ffffcc;"> <label value="Right-Right" /> </group> </activeHGroup> </group> </activeHGroup> <!-- Right Margin --> </activeHGroup> </activeVGroup> <!-- Bottom Margin --> </activeVGroup> </page> } ClientMethod onloadHandler() [ Language = javascript ] { ZLM.refreshLayout(); } ClientMethod onlayoutHandler() [ Language = javascript ] { ZLM.notifyResize(document.body); } } In this example, the binary nature of active group splits, combined with this design’s requirement that all geometries be measured in percentages, requires the developer to pay close attention to the underlying constraints enforced by active groups. Within the main work area, the developer achieves an equal three-way split by nesting two horizontal splits. The outer split divides the total area at 67%, giving two-third of the horizontal pixels to the left child and one-third to the right. The inner split divides the left child at 50%, not 33%. Dividing the two-thirds area evenly in half yields the desired result of visually splitting the total area into equal thirds. A similar technique correctly balances the left and right margins of the page relative to the central work area. The outer split divides the total area at 88%, giving the larger portion to the left child and creating a 12% right margin. The inner split divides the left child at 14%, not 12%. This produces a left margin that is of equal width to the right margin created by the outer split. The central work area is now approximately 75% of the window width and is correctly centered between the left and right margins. Adding Objects Dynamically In order to dynamically add a child object to an active group such as <desktop>, <corkboard>, or <snapGrid>, the active group needs to do client-side initialization of the child object. The first step is to make sure that the entire DOM object is ready before calling the initialize code. Do this by calling the refreshContents() method with a parameter of 1 or true, to force a synchronous object creation. Next re-initialize the active group and its children. You can do this with a call to ZLM.initLayout(), provided that the active group itself was statically defined as part of the base page. You can call ZLM.initLayout() repeatedly as needed, but does take time to run, so if you know you are creating a number of drag groups in a row, it is best to call refreshContents() once after all the new children have been added, and call ZLM.initLayout() once after refreshContents() returns. You can add windows individually, but batching them when feasible cuts down on server chatter and client-side processing. As an example, the following code shows the proper order for the calls to add an empty, resizable drag group from the client without a full page refresh. XData Contents [ <hgroup> <button caption="add" onclick="zenPage.addClientSide();"/> </hgroup> <snapGrid id="snapGrid" cols="10" rows="10" enclosingStyle="height:500px;width:500px;background-color:silver"> </snapGrid> </page> } ClientMethod addClientSide() [ Language = javascript ] { var sg=zen("snapGrid"); var dg=zenPage.createComponent("dragGroup"); dg.homeCol=1; dg.homeRow=1; dg.rowSpan=2; dg.colSpan=2; dg.header="new"; sg.addChild(dg); sg.refreshContents(1) ZLM.initLayout(); } <activeHGroup> and <activeVGroup> An <activeHGroup> is an active group that displays a two-part split pane with left and right partitions, optionally separated by a moveable adjustment bar. An <activeHGroup> can have only two child components. The first child defined in the <activeHGroup> appears in the left partition and the second child appears in the right partition. The “H” in the <activeHGroup> name means horizontal. There is also an <activeVGroup> for the same functionality with vertical alignment. The split panes for <activeVGroup> are top and bottom rather than left and right. Usually, both children of an <activeHGroup> or <activeVGroup> are groups. Each of these child groups defines the layout for its partition. The two children of an <activeHGroup> or <activeVGroup> may contain any number or type of Zen components, according to their usual allowances and restrictions, depending on which types of group they are: <hgroup>, <desktop>, <activeVGroup>, and so on. <activeHGroup> and <activeVGroup> each have the following attributes. <activeHGroup> and <activeVGroup> divide the screen as specified by the split property based on the size of the window at the time the page is loaded, and allow the user to readjust this layout as desired with the adjustment handles. You can reset the size of the panes programmatically, including changing whether the split is calculated as a fixed size or a ratio. If the value of the split property is a string ending in a percent sign, such as “75%,” the split is calculated as a ratio. If the value of split is a string ending in px, such as “75px,” the split is calculated as a fixed width. If the value of split is a number, such as 50%, the split is resized using the specified number and retaining whatever units are in use at the time. For example, the following code fragment creates an <activeVGroup> with split set to the default value of 50%: <activeVGroup id="activeVGroup" handleThickness="5"> <vgroup> <hgroup> <button caption="Change To Pixels" valign="top" onclick="zenPage.changeSize('pixels');" /> <button caption="Change To Percent" valign="top" onclick="zenPage.changeSize('percent');" /> <button caption="Change Size Same Units" valign="top" onclick="zenPage.changeSize('same');" /> </hgroup> </vgroup> </activeVGroup> The onclick event handler for the buttons changes the size and units of the split, as follows: ClientMethod changeSize(mode) [ Language = javascript ] { var avgr = zenPage.getComponentById('activeVGroup'); switch (mode) { case 'pixels': avgr.setProperty('split',"75px"); break; case 'percent': avgr.setProperty('split',"75%"); break; case 'same': avgr.setProperty('split',30); break; } } If you want the groups to automatically recalculate their layouts in response to a resize of the base window itself, you need to add the following call inside the optional onlayoutHandler JavaScript callback method for the Zen page: ZLM.notifyResize(document.body); When this call is in place, the notifyResize function is called automatically both when the page first loads and in response to window resizing at the browser level. Placing notifyResize in the onlayoutHandler callback allows you to place other “resizing reactions” in the onlayoutHandler callback, if you desire further processing. For more about onlayoutHandler, see the section “Zen Layout Handler.” <corkboard> A <corkboard> may contain one or more <dragGroup> components. A <corkboard> is an active group whose child components may visually overlap. As soon as the user clicks on a <dragGroup> in a <corkboard>, that <dragGroup> comes to the foreground. The user can subsequently drag the <dragGroup> and drop it in a new position in the <corkboard>. The dragged component overlays everything else inside the <corkboard>. No other component, besides the dragged component, is moved out of its current position. The user cannot move components into or out of the <corkboard>. Direct manipulation can only occur within the <corkboard> container. The immediate children of a <corkboard> component must be <dragGroup> components, but there are no restrictions placed on the contents of the <dragGroup> components themselves. A <dragGroup> may contain any component that is valid in a group. <corkboard> has the following attributes. <desktop> A <desktop> may contain one or more <dragGroup> components. A <desktop> is an active group that “tiles” its child components so that each one is fully visible and none of them overlap. As soon as the user clicks on a <dragGroup> in a <desktop>, that <dragGroup> comes to the foreground. The user can subsequently drag the <dragGroup> and drop it in a new position in the <desktop>. When the user drags and drops a <dragGroup> component into a new position, the dragged component moves the other <dragGroup> components in the <desktop> out of its way. All <dragGroup> components change position after the dragged component is dropped. The user cannot move components into or out of the <desktop>. Direct manipulation can only occur within the <desktop> container. The immediate children of a <desktop> component must be <dragGroup> components, but there are no restrictions placed on the contents of the <dragGroup> components themselves. A <dragGroup> may contain any component that is valid in a group. <desktop> has the following attributes. The underlying geometric model for the <desktop> is a simple one based on rows and columns. For this reason the <desktop> component supports row and column style settings that can enforce row and column alignment constraints on the <dragGroup> components that it contains. The arrangement of <dragGroup> components within the <desktop> varies, but in general this arrangement is biased in favor of “row collapse.” This means that if a <dragGroup> is removed from a given row, any other groups in the same row move to the left, collapsing the length of the row and possibly creating blank space at the extreme right end of the row. This convention maximizes the use of the visible portions of the window and minimizes the need for horizontal scrolling. You can suggest an initial layout of the <dragGroup> components within the <desktop> by supplying CSS styles such as valign:top and align:left for these components. You can also set the CSS style properties top and left to explicit pixel values; for example: <dragGroup enclosingStyle="top:150px; left:233px;" > <!-- contents of drag group here --> </dragGroup> When rendering the <desktop> component, Zen makes every effort to abide by such suggestions within the other constraints that are currently active. However, row and column styles, automatic row collapse, and the prohibition against overlapping <dragGroup> components make it impossible to guarantee that the placement suggested via CSS is respected exactly. The <desktop> component has the following attributes. It is possible to query, save, and restore the <desktop> state. The <desktop> component provides JavaScript methods that allow you to save and restore a particular user’s choice of geometry for the <desktop> — that is, how the user sized and placed components within the <desktop> during a previous session with the Zen page. You can work with this information as follows: layout=getState() The getState method returns a string that records the <desktop> state. The format for this string is an internal encoding that you do not need to understand in order to use this method. Simply store the string, in any way desired, to retrieve it for later use with restoreState. restoreState(layout) Inputs a string that tells the <desktop> which geometry to use when it displays. layout must be a string that was previously acquired using getState. The restoreState method does not actually open any windows. It takes whatever windows happen to be open, and restores them to where they were when the layout string was saved. <desktop> Row Style The <desktop> can enforce sizing and alignment constraints on the <dragGroup> components within its rows. You can choose a configuration by assigning a value to the rowStyle attribute. Valid values are: FILL_ROW — All groups within a row have the height of the tallest group in the row. By default the top and bottom edges of all the sub-windows align. Height is allowed to vary from one row to the next. ALIGN_ROW_TOP — (the default) The top edge of all <dragGroup> components within a row align. The height of individual <dragGroup> components within the row is allowed to vary. The row spacing is driven by the tallest group within the row. ALIGN_ROW_CENTER — All <dragGroup> components are centered vertically within their respective rows. The height of individual <dragGroup> components is allowed to vary. The row spacing is driven by the tallest group within the row. ALIGN_ROW_BOTTOM — The bottom edge of all <dragGroup> components within a row align. The height of individual <dragGroup> components within the row is allowed to vary. The row spacing is driven by the tallest group within the row. FILL_UNIFORM — All <dragGroup> components within the desktop take on the height of the tallest <dragGroup>. This results in all rows being uniformly spaced vertically and all <dragGroup> components being both top and bottom aligned. ALIGN_UNIFORM_TOP — All rows within the desktop take on uniform spacing dictated by the height of the tallest group within the component. Within each row, the top edges of individual <dragGroup> components align. The height of individual <dragGroup> components is allowed to vary. ALIGN_UNIFORM_CENTER — All rows within the desktop take on uniform spacing dictated by the height of the tallest group within the component. Within each row, individual <dragGroup> components are centered vertically. The height of individual <dragGroup> components is allowed to vary. ALIGN_UNIFORM_BOTTOM — All rows within the desktop take on uniform spacing dictated by the height of the tallest group within the component. Within each row, the bottom edges of individual <dragGroup> components align. The height of individual <dragGroup> components is allowed to vary. <desktop> Column Style In general, the <desktop> geometry conventions are biased towards rows. In fact, by default the <desktop> does not recognize the existence of columns. However, assigning a value to the colStyle attribute alters this behavior, so that the <desktop> counts all the first elements of the rows as column one, all the second elements as column two, and so forth. Unlike rows, which repack themselves when they are removed or added, columns are allowed to have embedded gaps in which a short row does not reach a given column. You can choose a column style, and force <desktop> to recognize columns, by assigning a value to the colStyle attribute. If you do not, the concept of columns is ignored and only row-based constraints apply. Valid values for colStyle are: FILL_COLUMN — All <dragGroup> components within a given column take on the width of the widest group within the column. All <dragGroup> components become both left and right aligned. The spacing of the columns is allowed to vary from one column to the next ALIGN_COLUMN_LEFT — The width of the column is dictated by the width of the widest group within that column but the width of individual sub- windows is allowed to vary. All <dragGroup> components are left aligned within their columns. The spacing of the columns is allowed to vary from one column to the next ALIGN_COLUMN_CENTER — The width of the column is dictated by the width of the widest group within that column, but the width of individual <dragGroup> components is allowed to vary. All <dragGroup> components are centered within their columns. The spacing of the columns is allowed to vary from one column to the next ALIGN_COLUMN_RIGHT — The width of the column is dictated by the width of the widest group within that column, but the width of individual <dragGroup> components is allowed to vary. All <dragGroup> components are right aligned within their columns. The spacing of the columns is allowed to vary from one column to the next FILL_WIDTH — The total width of the longest row dictates the layout bounds for the entire <desktop>. The widths of <dragGroup> components within shorter rows are scaled up proportionately to ensure that right edge of the last group in each row is aligned with that of every other row in the <desktop>. ALIGN_WIDTH_LEFT — Similar to FILL_WIDTH. The <dragGroup> components within rows are horizontally spaced based on the width of the longest row. The widths of individual <dragGroup> components are not padded, creating the appearance of random spacing within a row. ALIGN_WIDTH_CENTER — Similar to FILL_WIDTH. The <dragGroup> components within rows are horizontally spaced based on the width of the longest row. The widths of individual <dragGroup> components are not padded, and the <dragGroup> components are centered within the revised spacing bounds. ALIGN_WIDTH_RIGHT — Similar to FILL_WIDTH. The <dragGroup> components within rows are horizontally spaced based on the width of the longest row. The widths of individual <dragGroup> components are not padded, and the <dragGroup> components are right aligned within the revised spacing bounds. FILL_UNIFORM — All columns take on the width and spacing dictated by the widest <dragGroup> within the <desktop>. All <dragGroup> components are given uniform width, and are automatically left and right aligned ALIGN_UNIFORM_LEFT — Similar to FILL_UNIFORM, but all <dragGroup> components within a column are left aligned. ALIGN_UNIFORM_CENTER — Similar to FILL_UNIFORM, but all <dragGroup> components within a column are centered within the column spacing. ALIGN_UNIFORM_RIGHT — Similar to FILL_UNIFORM, but all <dragGroup> components within a column are right aligned. <snapGrid> A <snapGrid> is an active group which can contain one or more <dragGroup> components, organized so that each one is aligned with a grid. The number of rows and columns specified defines the underlying grid. The resulting grid is a normalized space, meaning that a four column layout results in the width of each column being 25% of the total width. You can define different layouts for portrait and landscape page orientation, such that the number of columns and rows changes if the geometry of the <snapGrid> becomes taller than it is wide (or vise versa). This is particularly useful for adapting layouts on devices such as tablets and mobile phones. The immediate children of a <snapGrid> component must be <dragGroup> components, but there are no restrictions placed on the contents of the <dragGroup> components themselves. A <dragGroup> may contain any component that is a valid child of a group. Child components may visually overlap. A <dragGroup> in a <snapGrid> comes to the foreground when the user clicks on it. If the appropriate user gestures are enabled, the user can drag and drop the <dragGroup>. When dropped, a <dragGroup> snaps to the closest grid lines. The grid itself does not scroll, however the <dragGroup> components in the grid may. The user cannot move components into or out of the <snapGrid>. Direct manipulation can only occur within the <snapGrid> container. <snapGrid> has the following attributes. Dynamic and Static Layout The ability to resize and drag and drop <dragGroup> components in a <snapGrid> is primarily controlled by the <dragGroup>. The attributes moveEnabled and resizeEnabled specify whether you can move or resize the group. <dragGroup> also relies on the header and the resize button to provide affordances for user drag and resize gestures. Without them, the drag group cannot be moved or resized. You can use the <snapGrid> method broadcast to control various aspects of appearance and behavior for all <dragGroup> components in the grid. The method restyleHeaderStyles in the class ZENDemo.SnapGridDemo in the SAMPLES namespace illustrates this use of broadcast. broadcast sends a signal to each of the active drag group components in the snap grid. Valid signals include: resize – call the onresize handler for each of the drag groups. disableResize – remove the resize button from the lower right corners of the drag groups. disableMaxToggle – redefine the drag group header to be a drag handle rather than a maximize button. enableMaxToggle – redefine the drag group header to be a maximize button rather than a drag handle. enableResize – restore the resize button to the lower right corners of the drag groups. processAppMessage – simply pass the value given to the <dragGroup> children. Subclasses of <dragGroup> can override the default processAppMessage() method to extend the broadcast facility to address application specific signals. The mechanism only passes a single value argument, but this value can take the form of a JSON string or an arbitrary JavaScript object so multiple discrete data can be packaged into a single broadcast value. removeDragHeader – completely hide the drag handle and resize the window to use the recovered space. restoreDragHeader – restore the drag handle and resize the window to account for the newly used space. setBodyStyle– given a JSON representation of a style object in value, add the given rules to the existing style of the drag body. setHeaderStyle – given a JSON representation of a style object in value, add the given rules to the existing style of the drag header. setHeaderLayout – set the headerLayout property of all child drag groups to the given value. Note that when you run ZENDemo.SnapGridDemo , it comes up with headers and resize buttons visible, and you can move and resize the drag groups. The Remove Headers button removes these affordances, and as a result, the grid layout is static. The Restyle Headers button restores the headers functioning as maximize buttons. Orientation-specific Layout The <snapGrid> component can adjust the layout of rows and columns in response to the geometry of the window it is being viewed in. The properties rowsPortrait and colsPortrait specify the number of rows and columns for portrait mode, and rowsLandscape and colsLandscape for landscape mode. If you set only one of these two sets of properties, Zen uses the default row and column values for the unspecified set. This feature is useful when creating applications to be viewed on a device such as a cell phone or tables, that changes the display orientation when the orientation of the device changes. The following example codes a page that responds to changes in window geometry when viewed in a browser. CSS sets the height and width of the <snapGrid> to 100%, and the page layout must be set to “none” as described in the section “Active Groups that Resize Proportionally.” Class demo.SnapGridLP Extends %ZEN.Component.page { /// This Style block contains page-specific CSS style definitions. XData Style { <style type="text/css"> #snapGrid { width: 100%; height: 100%; background-color: silver; } </style> } /// This XML block defines the contents of this page. XData Contents [ <snapGrid id="snapGrid" colsLandscape="10" colsPortrait="5" rowsLandscape="5" rowsPortrait="10" > <dragGroup id="dg1" onclick="" moveEnabled="true" resizeEnabled="true" headerLayout="C" header="1" homeCol="1" homeRow="1" colSpan="1" rowSpan="1"> </dragGroup> </snapGrid> </page> } } <dragGroup> A <dragGroup> is the only Zen group component that can be the direct child of a <desktop>, <corkboard>, or <snapGrid>. The <dragGroup> itself can contain any component you can put in a group. A <dragGroup> can display a header bar, which can have a text label and various buttons. A <dragGroup> can be resized, maximized, minimized, closed, and restored by clicking its buttons and by dragging the header or the resize icon in the lower right corner. In many ways the <dragGroup> is similar to a desktop window such as you would typically see on a Macintosh or PC desktop. <dragGroup> has the following attributes.
https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=GZAP_drag_and_drop
CC-MAIN-2021-49
refinedweb
5,325
53
Subject: [OMPI users] MPI_Intercomm_create hangs From: jody (jody.xha_at_[hidden]) Date: 2012-01-23 11:03:56 Hi I've got a really strange problem: I've got an application which creates intercommunicators between a master and some workers. When i run it on our cluster with 11 processes it works, when i run it with 12 processes it hangs inside MPI_Intercomm_create(). This is the hostfile: squid_0.uzh.ch slots=3 max-slots=3 squid_1.uzh.ch slots=2 max-slots=2 squid_2.uzh.ch slots=1 max-slots=1 squid_3.uzh.ch slots=1 max-slots=1 triops.uzh.ch slots=8 max-slots=8 Actually all squid_X have 4 cores, but i managed to reduce the number of processes needed for failure by making the above settings. So with all available squid cores and 3 triops cores it works, but with 4 triops cores it hangs. On the other hand, if i use all 16 squid cores (but no triops cores) it works, too. If i start the application not from triopps, but froim another workstation, i have a similar pattern of Intercomm_create failures. Note that with the above hostfile a simple HelloMPI works also with 14 or more processes. The frustrating thing is that this exact same code has worked before! Does anybody have an explanation? Thank You I managed to simplify the application: #include <stdio.h> #include "mpi.h" int main(int iArgC, char *apArgV[]) { int iResult = 0; int iNumProcs = 0; int iID = -1; MPI_Init(&iArgC, &apArgV); MPI_Comm_size(MPI_COMM_WORLD, &iNumProcs); MPI_Comm_rank(MPI_COMM_WORLD, &iID); int iKey; if (iID == 0) { iKey = 0; } else { iKey = 1; } MPI_Comm commInter1; MPI_Comm commInter2; MPI_Comm commIntra; MPI_Comm_split(MPI_COMM_WORLD, iKey, iID, &commIntra); int iRankM; MPI_Comm_rank(commIntra, &iRankM); printf("Local rank: %d\n", iRankM); switch (iKey) { case 0: printf("Creating intercomm 1 for Master (%d)\n", iID); MPI_Intercomm_create(commIntra, 0, MPI_COMM_WORLD, 1, 01, &commInter2); break; case 1: printf("Creating intercomm 1 for FH (%d)\n", iID); MPI_Intercomm_create(commIntra, 0, MPI_COMM_WORLD, 0, 01, &commInter1); } printf("finalizing\n"); MPI_Finalize(); printf("exiting with %d\n", iResult); return iResult; }
http://www.open-mpi.org/community/lists/users/2012/01/18245.php
CC-MAIN-2014-49
refinedweb
340
55.34
Agenda See also: IRC log <trackbot> Date: 02 June 2009 <mgylling> [hmm, got disconnected] In any case he is not yet online though I spoke to him an hour or so ago <mgylling> ... and heres another +1 for relaxng Well, it's good to have some Ralxing expertise around Masayasu used to be our relax expert <mgylling> I know relaxng quite well too (consider it my second tongue after swedish) <MoZ> what happened ? We're dropping the call until Shane arrives staying in the IRC channel <MoZ> ok please ping me when you're back so OK <Tina> ShaneM: Steven is on a school run, I believe; I'll call in when lunch is done. <ShaneM> thanks <alessio> hi all, wasn't it at 13.00 UTC? <ShaneM> yes <ShaneM> Steven is tied up for a little while. roland, what's your plan <alessio> ok... thx shane <Tina> ... my phone is broken, again. I'm IRC only, folks. back <ShaneM> hey steven. some of us are here - just waiting on you and roland. Given the number of issues we need to review in order to resubmit the PERs, I request that we schedule another 4 hour vF2F meeting. I suggest we try to do it Tuesday, 2 June at noon UTC: We are starting, MoZ, Alessio, Tina, mgylling <ShaneM> <scribe> Scribe: Steven Shane: I reduced the list to 11 issues ... We received a formal objection from Ian Hickson Steven: About text/html? Shane: Yes, he doesn't like it Steven: I believe that doesn't have to be a show-stopper Shane: And there is Bjoern's mail, that wasn't sent to us <Tina> ShaneM: do we have a link to the formal objection? Steven: I haven't checked it rigorously, but I believe that points to issues he had already sent us ... but we should make sure ... that all his issues made it into the issue tracker Shane: Agreed ... So we have 11 issues that we should look at Shane: I replied to this ages ago ... anyway appx C is gone Steven: Who, quite honestly is going to misunderstand this? Shane: We replied, he didn't answer, what do we do? Steven: we have followed process. Issue closed Shane: Marked as closed, but ... we advise against the XML declaration ... and say use UTF 8 or a higher-level protocol ... he asks a question, Steven replied, he didn't respond. Therefore we have met process. Steven: Issue closed Shane: This is an error in the DTD ... The DTD has been fixed ... is it OK for a PER? Steven: Yes, it doesn't break any browsers, it was a clear error <ShaneM> Shane: there is an updated editors' draft <ShaneM> Updated references section is at Shane: I have split the references into informative and normative ... need an OK from you ... POSIX is for MAY, SHOULD etc ... there was a formal objection because the objector wanted us to point to 5th edition of XML ... but we decided against that because of the change to name token Steven: I remember having that discussion ... isn't 5th edition just v1.1 back ported to 1.0? Shane: Regardless Steven: We deliberately made this decision, so I think we should defend it at the transition call ... I mean, the real thing we are trying to achieve here is adding schemas Shane: Anyone object to pointing to 4th edition? Moz? Shane: we refer to 2e of namespaces, an obvious improvement ... Are there any of the informative refs things that have to be normative? (I will update the ref to M12N) ... some of them aren't even referenced Steven: Chop 'em out then. ... they may be leftovers from appx C Shane: Fixing them now ... three left, MIME, MOD, and MathML Steven: Looks good ... closes this issue Shane: I will reply <alessio> Shane: Tobias asked us to fix it in XHTML2 ... but Jim Ley brings it to XHTML 1 <ShaneM> I said "objects are independent entities within the page. Navigation is local to the <ShaneM> object and its own processing. This is defined in HTML 4." Shane: but I claim it is an HTML 4 problem ... where the question is already answered Steven: Good answer <MoZ> Moz : I'm with 4th edition. Since Namespace with XML is still not in sync with 5th edition Steven: Thanks MoZ, that is good <ShaneM> Steven: lang and xml:lang are normatively defined elsewhere; I think it would be wrong to normatively define anything here ... if you use both, with different values, well, that's your own silly fault Markus: Are the datatypes the same? Shane: I think one is a subset of the other ... so it is possible to have a value of xml:lang that is not a legal value of @lang ... (in theory) Steven: Didn't we want both lang and xml:lang for the same reason as name/id Shane: There is a difference, largely because of accessibility software ... we were trying to be good XML citizens by including xml:lang <MoZ> You have no choice to use xml:lang. It comes with XML 1.0 (as well as xml:space) Steven: If we change the wording on this now, we would be leaving PER territory <ShaneM> Good point. In XHTML 1.1 we say ." Steven: it could invalidate existing UAs ... In XHTML 1.1, we are expanding the number of allowable documents, and not invalidating existing UAs Shane: Section c.7 has been removed, so the comment doesn't apply Steven: It does, because he wanted something added to the normative requirements ... which is out of scope, because these attributes are defined elsewhere ... and I will argue that at the transition call 5 mins break for coffee back Shane: WHat do we do; I have kept the anchors with a pointer to the place where they now are Roland: That's the best we can do Shane: He's written a validator against appx C, and that broke the error messages in his validator <Tina> Who wrote a 'validator' ? Bjoern Steven: This isn't the first time this has happened with a W3C spec (anchors changing) Shane: Well, they don't get a 404 <ShaneM> sorry - just a minute Steven: We defer to XML on the definition of whitespace ... and even point that out in 4.7 <ShaneM> Steven: I still think that XML definition of whitespace on input, and CSS definition on output is the good answer ... and not add anything else. The spec at 4.7 says exactly what it should do Shane: Issue closed ... we are rejecting his request, no edits are associated with this change Shane: Nothing to do with this document. ... Do we want to add a schema? Steven: Let's not give ourselves any more work Shane: OK, this comment is not associated with XHTL 1.0 anymore Shane: I think he was misinterpreting this section <ShaneM> item 3 Shane: It means "@name does not create a fragment identifier" Steven: Looking at the wording of his comment, he is asking for changes wrt to appx C, which is gone. So I think the issue is closed Shane: I have made the changes ... they make no changes to an UA ... and anyway, all the datatypes map to CDATA Steven: So this is just editorial ... names of datatypes that are otherwise equivalent Steven: So we just take out the second part of the sentence? Shane: Yes, get rid of duplication Steven: I can live with that Shane: I will make that change ... It is in an informative section anyway <Tina> Which list is 6332 on? <ShaneM> 6232 is in the voyager issues thing - Steven is getting a link now <Tina> Thanks;user=guest;selectid=6232;statetype=-1;upostype=-1;changetype=-1;restype=-1 <ShaneM> Ian's objection is here: Steven: What can I say except that I disagree? ... ALl we do is give guidelines on getting documents to render in HTML UAs S/ALl/All/ <ShaneM> 5.1 in third edition current reads: XHTML Documents which follow the guidelines set forth in [XHTMLMIME] informativ <ShaneM> For information on delivering XHTML 1.0 Documents to user agents that do not natively handle this media type, see [XHTMLMIME] . <ShaneM> So the final text for 5.1 would read: XHTML 1.0 Documents should be be labeled with the Internet Media Type "application/xhtml+xml" as defined in [RFC3236]. For information on delivering XHTML 1.0 Documents to user agents that do not natively handle this media type, see [XHTMLMIME] . <ShaneM> any objections to this text? Steven: This is an informative section, right? Shane: Yes ... I'll suggest the change to the commentator ... So we are done, modulo checking for missed comments, and checking new comments on the PERs <Tina> I have none <ShaneM> ... Roland searches email archives ... <Roland> Shane: Yes, this is new Roland: We'll talk about it when we get to 1.1 ... it is in the wrong place, but let's add it to the issues system <ShaneM> Shane: There are 21 issues ... most trivial ... I haven't done the final pass ... first issue is @id on script ... fixed and closed Steven: HTML4 disallows these with exclusions ... and for XHTML we used English text <Tina> What's the reasoning behind that change? TIna - because XML doesn't have exclusions Steven: Oh but wait, Modularization uses exclusions! Shane: We were so clever! ... we win! ... "Content exclusions should be defined by the rules in M12N, which can't be expressed in all schema grammars" <MoZ> That's where I think Relax NG + NVDL could help <MoZ> (It's more Relax NG + Schematron to be fair) <ShaneM> Shane: Ruby does it right too! Steven: So the reply is that the spec is clear, and does the right thing <ShaneM> XHTML 1.1 references the XHTML M12N and Ruby Recommendations. Those Recommendations define content models using an abstract content model grammar, and these are specifically excluded already. While the underlying implementation(s) may not be able to enforce these exclusions because of limitations in their grammars, the restrictions are nontheless normative. Steven: using the definitions as required by M12N Fixed Shane: We don't make changes to work round bugs in software ... wrong approach Steven: Agreed Shane: Fixed Roland: Keep it as is Steven: We could consider it for XHTML2 ... it has a reasonable use-case ... this would take us out of PER territory <Roland> Shane: Fixed Shane: We have an objection because this is not fixed Roland: You think we should be pragmatic Shane: Yes, we should just do what UAs do now Steven: The tests make it look like it should be a URI ref <ShaneM> <img usemap="lala"> Shane: external references have never been implemented ... so this wouldn't affect current implementations ... You have to change this in m12n <ShaneM> Steven: then the issue is on the wrong spec Shane: Then I'll move it there Shane: Editorial; fixed Shane: Handle this tomorrow [ADJOURN] This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/SH/Sh/ Succeeded: s/tand/stand/ Succeeded: s/TH// Succeeded: s/is is an/This is an/ Succeeded: s/draft/ draft/ Succeeded: s/edition/edition of XML/ Succeeded: s/Stevrn|/Steven/ Succeeded: s/�m/'em/ Succeeded: s/MOz/MoZ/ Succeeded: s/edf/def/ Succeeded: s/SH/Sh/ Succeeded: s/anyway// Succeeded: s/tence/tence?/ Succeeded: s/63/62/ Succeeded: s/SH/Sh/ Found Scribe: Steven Inferring ScribeNick: Steven WARNING: Replacing list of attendees. Old list: Markus Roland Steven New list: Steven Roland ShaneM Alessio Default Present: Steven, Roland, ShaneM, Alessio Present: Steven Roland ShaneM Alessio Tina MoZ Markus Regrets: Gregory Agenda: Found Date: 02 Jun 2009 Guessing minutes URL: People with action items:[End of scribe.perl diagnostic output]
http://www.w3.org/2009/06/02-xhtml-minutes.html
CC-MAIN-2013-48
refinedweb
1,970
72.97
CACHEFLUSH cacheflush - flush contents of instruction and/or data cache #include <asm/cachectl.h> int cacheflush(char *addr, int nbytes, int cache); cacheflush flushes contents of indicated cache(s) for user addresses in the range addr to (addr+nbytes-1). Cache may be one of: cacheflush returns 0 on success or -1 on error. If errors are detected, errno will indicate the error. The current implementation ignores the addr and nbytes parameters. Therefore always the whole cache is flushed. This system call is only available on MIPS based systems. It should not be used in programs intended to be portable. One page links to cacheflush(2):
http://wiki.wlug.org.nz/cacheflush(2)
CC-MAIN-2015-32
refinedweb
106
68.87
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. dynamic template for list views Hi Guys, the goal is to customize a List View <tree> that changes the background colour of a specific cell if a Key/Value Pair is matched. So I tried to write my own template for the ListView in static/src/js and xml, which I copied out of the web module template, and add my own Javascript into my view_list.js, also from the web module, included my attf condition to the xml, added the paths to __openerp__.py But now every List in OpenErp changes colors (css classes) so in Details: got the ListView Template from /usr/lib/pymodules/python2.7/openerp/addons/web/static/src/xml/base.xml <templates id="template" xml: ... <table t- <t t-` ... and then to the : <td t- <t t-</td> -added THIS -->>> #{value_check(record.get(column.id), column.id) ? 'oe_custom_view' : 'oE_3o'} The /addons/web/static/src/js/view_list.js is exactly the same but I added: value_check: function (value, key) { return ((key=="name") && (value=="test")); }, so the condition can be matched. So everything works so far but instead of only turning the cell colors of my module, every list view in open erp is changed. Did I overwrote that by not changing the js or xml names and attributes? How can I fix this so only my own view is affected? ThX Peter At I found this: t-extend=template BODY Parameters: template (String) -- name of the template to extend Works similarly to OpenERP models: if used on its own, will alter the specified template in-place; if used in conjunction with t-name will create a new template using the old one as a base. But if i add a t-name like <t t- my custom template isn't used anymore. How do I tell openERP to use my CustomTemplate instead of the standard? so I tried a different approach and got the solution
https://www.odoo.com/forum/help-1/question/dynamic-template-for-list-views-42453
CC-MAIN-2017-04
refinedweb
348
62.68
Thanks a lot, I can compile and boot the kernel now.But still the keyboard does not work...Regards Georg ChiniAndrew Morton wrote:> Georg Chini <georg.chini@triaton-webhosting.com> wrote:> >>Hello out there,>>>>tried to build Kernel 2.6.0-test6-bk4 on my>>sparc32 machine and found that the function>>sched_clock is missing in time.c. Can anyone>>tell me what I have to put there? Please CC>>to me.>>> > > This is the minimal version to get you going.> > A better implementation would use a higer-resolution counter, if the> hardware has such a thing.> > > diff -puN arch/sparc/kernel/time.c~sparc32-sched_clock arch/sparc/kernel/time.c> --- 25/arch/sparc/kernel/time.c~sparc32-sched_clock 2003-10-04 11:53:19.000000000 -0700> +++ 25-akpm/arch/sparc/kernel/time.c 2003-10-04 11:53:41.000000000 -0700> @@ -617,3 +617,12 @@ static int set_rtc_mmss(unsigned long no> return -1;> }> }> +> +/*> + * Returns nanoseconds> + */> +> +unsigned long long sched_clock(void)> +{> + return (unsigned long long)jiffies * (1000000000 / HZ);> +}> > _-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2003/10/4/107
CC-MAIN-2014-15
refinedweb
197
53.78
Sometimes good performance seems to be in direct conflict with programmer-understandable types. This post is about ways to get fast parity checking on natural number types, while also maintaining as many invariants as possible automatically. The example here is definitely contrived—if you wanted fast numeric parity calculations you could just check the lowest bit. However, it’s a pretty good stand-in for more complicated encodings, and how we can play with them to make them both performant and easy to understand. Along the way we’ll briefly touch on some cool Haskell language extensions: type families, GADTs, and data kinds. Let’s start with a tiny subset of the Prelude, and we’ll also define a Bool type as well as the not operation on it which we can use later. import Prelude((++), Show(..)) data Bool = True | False deriving Show not :: Bool -> Bool not False = True not True = False Hopefully this is straightforward. Here’s our stand-in for an existing type with a focus on understandability by human programmers. We’re encoding natural numbers as Peano numerals, where Z means 0, and S means successor. Let’s also throw in a helpful succ function for finding successors. Our version of succ here only needs to provide the S constructor, which means it’s simple to write and easy to understand. For whatever reason, the other constraint on our type is that we want fast parity checking, i.e. a way to tell whether a number is even or odd. Let’s write a version of that now. even :: Nat -> Bool even Z = True even (S Z) = False even (S (S n)) = even n odd :: Nat -> Bool odd n = not (even n) Here we’re deconstructing our Nat and recursively finding out whether it’s even by reducing the number by two, and checking the parity of that. Intuitively, this works, because we always end at one of the base cases and are making the number smaller at each step. However, it’s rather slow. We’re taking around \(n/2\) steps to check the parity of a number \(n\), which means the runtime of this function grows linearly with the size of its input. Let’s see if we can do better. Here’s another idea: we can encode odd and even numbers separately. This way, there’s an easy way to check a number’s parity from its encoding in a single step. Maybe our new data type looks like this: ZZ is the equivalent of Z in Nat, but now we have both an SO (“odd successor”) and an SE (“even successor”). This makes the succ function a bit more complicated now: succPar :: ParityNat -> ParityNat succPar ZZ = SO ZZ succPar n@(SO _) = SE n succPar n@(SE _) = SO n We want the SEs and SOs to alternate, which we can do as shown. However, note that now there’s a higher burden on people writing functions dealing with ParityNat as opposed to just plain Nats. Along with additional cases to handle, there are more places for implementations to contain errors. We’re also relying on people to use succ now, rather than just the plain data constructors. At least our new parity checking functions are speedy: evenPar :: ParityNat -> Bool evenPar ZZ = True evenPar (SO _) = False evenPar (SE _) = True oddPar :: ParityNat -> Bool oddPar n = not (evenPar n) There’s another encoding option, which puts more burden on the author of the encoding, but hopefully automatically enforces more constraints for later users of the library. We can push parity checking into the types. First, let’s make a new type for the parity itself. If this seems weirdly familiar, that’s because it’s isomorphic to Bool which we defined earlier. We can also define a “ not” operation on Paritys, but first let’s take one step back. If we want to enforce parity in types, having Even and Odd terms isn’t that helpful. We need to promote Parity to a kind, and promote Even and Odd to types. While we’re at it, let’s also add the type families extension so we can define the equivalent to our not function, but at the type level instead of the term level. All in all, we’ll want the following extensions enabled: Now we can define the type-level equivalent of not, but for Parity instead of Bool. Let’s call it “ Opp”. Here’s its definition: type family Opp (n :: Parity) :: Parity type instance Opp 'Even = 'Odd type instance Opp 'Odd = 'Even This may look bizarre, but it’s more or less just a different syntax for defining a function. Opp takes a Parity called n and returns a Parity. The opposite of even is odd, and the opposite of odd is even. The ticks in front of 'Even and 'Odd remind us that these have been promoted from terms to types. We can now define our constructors analogous to Z and S. This stuff here is the reason we needed GADTs. data Natural :: Parity -> * where Zero :: Natural 'Even Succ :: Natural p -> Natural (Opp p) instance Show (Natural p) where show Zero = "Zero" show (Succ n) = "(Succ " ++ show n ++ ")" Breaking this down a bit further, a Natural is a type which takes something of kind Parity and gives us back a normal type (something of kind *). Zero is even, and the Succ of any Natural has the opposite parity as that Natural. The successor function is again trivial to write. Weirdly, it now almost doesn’t make sense to have even and odd functions. Because this information is encoded in the types, it’s already sort of carried along with every Natural. However, just for the sake of completeness we can write something like this: This was a brief tour of a few possible encodings for a small bit of data with additional outside constraints on it. The first encoding was very simple, but runtime for operations we care about a lot ( even and odd) was too slow. We switched to the more performant ParityNat, but this came at the cost of ease of use when writing functions using that type. Finally, we sort of pushed the problem up to the type level so that anything of type Natural 'Even has even parity, and likewise any Natural 'Odd has odd parity. This did away with the need for parity checking as functions, but comes at the cost of a more complicated type system encoding of our desired result. Like so many places in engineering, this provides an interesting example of multiple tradeoffs that have to be balanced. Normally I lean towards “clarity at most costs”, sacrificing performance to make programmers’ jobs more manageable. However, occasionally understandability has to be traded away for enhancements of the details of how our programs actually run, and this tradeoff is more common as systems become more heavily relied upon by others.
https://vitez.me/parity-clarity
CC-MAIN-2020-16
refinedweb
1,157
59.74
Hi. I don't want players with 0 scores to appear on the leaderboard. So I'm checking if their score is 0, and If so, I don't submit them to the leaderboard. But I then want to query the very bottom of the leaderboard from the server - so I can display the bottom of the leaderboard with the players 0 score at the bottom. But to do that, I need to get the bottom of the Leaderboard. No I can get the leaderboard around the player (which is of no use, as the player wont exist in the leaderboard yet). And I can get the leaderboard starting from a position in the leaderboard - which isn't of any use for this scenario as I don't know how many entries are in the leaderboard in order to say "start from here". Is there an easy way to do this? It's easy to get the top 10 entries in the leaderboard. But how do I query the bottom 10 entries? A nasty way of doing it would be to keep polling the server, starting at entry 10, then adding 10, etc etc until it gets to the end. But there must be a better way? Using unity - if that's any help? Answers Answers and Comments 2 People are following this question. Can't retrieve some profiles due to API Error in Playfab Leaderboard (Unity) 1 Answer error CS0246: The type or namespace name 'PlayFab' could not be found,error CS0246: The type or namespace name 'PlayFab' could not be found 1 Answer Best Approach for getting leaderboards (Login by FB) 1 Answer How to call advance drop tables? 1 Answer Converting playfab login system to linked steam system? 1 Answer
https://community.playfab.com/questions/31349/leadboard-get-bottom-of-table.html
CC-MAIN-2022-05
refinedweb
293
77.67
Hello, This is my first post. I am trying to teach myself C++ and am having a hard time with a function problem. This is not for homework, I simply want to learn something about C++ and I have no one else to ask. The problem I am having is a simple function. The problem in the book states: Write a program that repeatedly asks the user to enter pairs of numbers until at least one of the pair is 0. For each pair, the program should use a function to calculate the harmonic mean of the numbers. The function should return the answer to main(), which should report the result. The harmonic mean of the numbers is the inverse of the average of the inverses and can be calculated as follows: harmonic mean=2.0xXxY/(x+y) Here is what I have gotten so far: #include<iostream> using namespace std; void harmonic(int x, int y, float h); int main() { int x; int y; float h; while ( x != 0) { cout <<"Enter first integer: (or 0 to quit)"; cin >> x; cout <<"Enter second integer: (or 0 to quit)"; cin >> y; harmonic(x,y,h); cout <<"The harmonic mean is: \n" << h <<endl; } system("PAUSE"); return EXIT_SUCCESS; } void harmonic(int x, int y, float h) { h=(2*x*y)/x+y; } I think as a side note I should mention that I am using DEV-C++. The output, when I enter x=2 and y=2, is 3.21412e-039. When I enter a "0", the program simply stops. What have I done wrong? Any help will be greatly appreciated.
https://www.daniweb.com/programming/software-development/threads/99073/i-need-help-with-a-simple-function
CC-MAIN-2017-17
refinedweb
269
78.89
Magic Methods and Predefined Constants in PHP PHP provides a set of special predefined constants and magic methods to your programs. Unlike the constants you would set using define(), the value of the constants depend on where they are used in your code and are used to access read-only information about your code and PHP. The magic methods are reserved method names you can use in your classes to hook into special PHP functionality. If you haven’t heard about PHP’s magic methods and constants yet, then this article is for you! I’ll review some of the more useful ones and how you can use them in your code. Predefined Constants The predefined constants are used to access information about your code. The constants here are written in all capital letters between double underscores, like __LINE__ and __FILE__ for example. Here are some of the useful constants that are made available by PHP: __LINE__returns the line number in the source file the constant appears at, like this: <?php echo "line number: " . __LINE__; // line number: 2 echo "line number: " . __LINE__; // line number: 3 echo "line number: " . __LINE__; // line number: 4 __FILE__represents the name of your file, including its full path, like this: <?php echo "the name of this file is: " . __FILE__; // the directory and name of file is: C:wampwwwindex.php __DIR__represents only the path to the file: <?php echo "the directory of this file is: " . __DIR__; // the directory of this file is: C:wampwww __CLASS__returns the name of the current class: <?php class Sample { public function __construct() { echo __CLASS__; } } $obj = new Sample(); // Sample __FUNCTION__returns the name of the current function: <?php function mySampleFunc() { echo "the name the function is: " . __FUNCTION__; } mySampleFunc(); //the name of function is: mySampleFunc __METHOD__represents the name of the current method: <?php class Sample { public static function myMethod() { echo "the name of method is: " . __METHOD__; } } Sample::myMethod(); // the name of the method is: myMethod __NAMESPACE__returns the name of the current namespace: <?php namespace MySampleNS; echo "the namespace is: " . __NAMESPACE__; // the name space is: MySampleNS Magic Methods Magic methods provide hooks into special PHP behavior. Unlike the constants earlier, their names are written in lower/camel-case letters with two leading underscores, like __construct() and __destruct(). __construct() is magic method which PHP invokes to create object instances of your class. It can accept any number of arguments. <?php class MySample { public function __construct($foo) { echo __CLASS__ . " constructor called with $foo."; } } $obj = new MySample(42); // MySample constructor called with 42 As its name implies, the __destruct() method is called when the object is destroyed by PHP’s garbage collector. It accepts no arguments, and it is commonly used to perform any clean up operations that may be needed such as closing a database connection. <?php class MySample { public function __destruct() { echo__CLASS__ . " destructor called."; } } $obj = new MySample; // MySample destructor called Our next magic methods deal with property overloading, and provide a way for PHP to handle calls to properties and methods that have not been defined (or are not accessible to us). PHP invokes the __get() method if a property is undefined (or inaccessible) and called in a getter context. The method accepts one argument, the name of the property. It should return a value which is treated as the value of the property. The __set() method is called for undefined properties in a setter context. It accepts two arguments, the property name and a value. <?php class MySample { private $myArray = array(); public function __set($prop, $value) { $this->myAarray[$prop] = $value; } public function __get($prop) { return $this->myArray[$prop]; } public function __isset($prop) { return isset($this->myArray[$prop]); } public function __unset($prop) { unset($this->myArray[$prop]); } public function __toString() { return __CLASS__ . ":" . $this->name; } } $obj = new MySample(); if (!isset($obj->name)) { $obj->name = "Alireza"; } echo $obj->name; // Alireza echo $obj; // MySample:Alireza In the above example code, the property name is not defined in the class. I attempt to assign the value “mysample” to it, and PHP invokes the magic method __set(). It receives “name” as the $prop argument and “Alireza” as $value, and I store the value in the private $myArray array. The __get() method works in a similar fashion; when I output $obj->name, the __get() method is called and “name” is passed in for the $prop argument. There are other magic methods which help us with retrieving and inspecting inaccessible member variables as well which appear in the sample code: __isset(), __unset(), and __toString(). Both __isset() and __unset() are triggered by the functions with the same name (sans the underscores) in PHP. __isset() checks whether the property is set or not, and accepts one argument which is the property we want to test. __unset()receives one argument which is the name of the property that the program wants to unset. In many cases, representing an object as string is useful, such as for output to a user or another process. Normally PHP presents them as ID in memory, which is not good for us. The __toString() method helps us represent the object as a string. The method is triggered in any situation where an object is used as a string, for example: echo "Hello $obj". It can also be called directly like any other normal public method, which is preferable to hacks such as appending an empty string to force coercion. Summary OOP programming can produce more maintainable and testable code. It helps us create better and standard PHP code. Also, it makes it possible to take advantage of the magic methods and constants which PHP makes available. Image via Stepan Kapl / Shutterstock - niloofar - Saeed Moslemi - Alex Gervasio - Mohammed Sadiq - Jalal Khan - Awais Kazimi - Arvind
http://www.sitepoint.com/magic-methods-and-predefined-constants-in-php/
CC-MAIN-2015-18
refinedweb
940
63.8
Live. Namespaces are the XML solution to the classic language problem of one word meaning two things in different contexts. Take " windows ," for example. In the context of houses , "windows" are holes in the wall through which we can look. In the context of computers, " Windows " is a trademark of the Microsoft Corporation and refers to words more than once for different meanings. Second, they allow you to group together words that are related to each other using a computer to look through an XML document for all elements with a certain namespace is easy. RSS 1.0 uses namespaces to allow for modularization . The modularization of RSS 1.0 means that developers can add new features to RSS 1.0 documents without changing the core specification. In RDF terms, this means we have included another vocabulary. Modularization has great advantages over RSS 0.9x's method for including new elements. For starters, anyone can create a module: there are no standards issues or any need for approval, bar making sure that the namespace you use has not been used before. And, it means RSS 1.0 is potentially far more powerful that RSS 0.9x, with modules adding features for syndicating details of streaming media, Wikis, real-world events, and much more, not to mention the simplicity of adding the hundreds of vocabularies that already exist in the RDF community. We'll look at many different modules in Chapter 7, but in the meantime, Example 6-1 shows a sample RSS 1.0 document that uses four additional modules: Dublin Core, Syndication, Company, and Text Input. <?xml version="1.0" encoding="utf-8"?> <rdf:RDF > <image rdf: <textinput rdf: <items> <rdf:Seq> <rdf:li rdf: </rdf:Seq> </items> </channel> >
https://flylib.com/books/en/1.115.1.35/1/
CC-MAIN-2018-43
refinedweb
290
56.96
Data Science Workshop 1 (Part 4): Pandas — Continued Hi, This is Part 4 of Workshop 1. We are continuing the discussion on the Pandas library. The code of this part is available below. We are starting from where we left in the last part. Here is the YouTube video on Data Science Workshop 1, Part 4. Contents Creating a new column I can even create a new column. Let’s say that I want to create a new column named MyNewCol. Let us say that this new column should contain the summation of the columns Hello1 and Hello2. We write, df1['MyNewCol']=df1['Hello1']+df1['Hello2'] If we print df1, we will see the following content. This new column, MyNewCol, contains the summation of the cells of columns Hello1 and Hello2. We can do these things using spreadsheet software like excel. Here, we are doing it programmatically. df1 could have many rows and many columns in a real dataset. For simplicity, we only created this small data table. Removing a column from a Pandas DataFrame Let’s say, I want to delete a column from the DataFrame df1. Let’s say, I want to delete the column Hello3. The function to delete is drop. We state, df1.drop and then we provide the column name “Hello3”. Additionally, we have to mention an axis indicating whether we want to delete a row (axis=0) or a column (axis=1). The syntax to delete the column Hello3 will be: df1.drop('Hello3', axis=1, inplace=True) The parameter, inplace=True, confirms the deletion from the DataFrame. Without the parameter, inplace=True, a view will be shown indicating how the DataFrame would look like if the removal occurs. After the removal of the Hello3 column, the df1 will have the following content. Why do we have such a parameter named inplace for the DataFrame’s drop operation? The parameter, inplace=True, is to ensure that something is not removed accidentally. If someone intends to delete something, she/he needs to write this syntax, inplace=True, to ensure deliberate removal. This parameter, inplace=true, is a cautionary step. Selecting a subset of a DataFrame I will use the iloc of DataFrame to select a subset of a DataFrame. iloc is a mechanism to use integer positions or indices. In a set of square brackets, I can provide a list of integers indicating which rows I want to select. In the list of indices, I can prove a range like this — range(1, 3). This range means integer 1 is slected, integer 2 is selected. Integer 3 is NOT slected in the range function. That is, the first parameter of the range function is the starting integer of a range, and the second parameter is the last integer but an excluded one. That is, range (1, 3) provides numbers 1 and 2. Range(5, 10) provides numbers 5, 6, 7, 8, and 9. It will not include 10. Therefore, this iloc function with range(1, 3) will select rows 1 and 2. We can select both rows and columns using the iloc function. Consider the following iloc function. df1.iloc[range(1, 3), range(1, 3)] It will select the following part from df1. Retrieving the actual data part from a DataFrame I reminded the audience of the workshop that df1 is a DataFrame. That means you have some metadata around the actual data. Hello1, Hello2, and the other header names are information about the data. The row identifiers are also information pieces about the actual data. The headers or additional information pieces are sometimes called metadata. Metadata is data about the actual data. To receive the actual data the without the headers or the metadata pieces, you can use the values field. You can just run df1.values to retrieve the core data part. Notice that the core data part is an array, which is a NumPy array. Generally, we apply our machine learning algorithms on this core NumPy array. As I said earlier, Pandas is built on top of NumPy. The wrapped-around items, such as headers and many other Pandas functions, help data scientists analyze and process data. More resources on the Pandas library There are many more items in Pandas, such as merging, join, selection, conditional selection, and concatenation. Here is the official site for Pandas: Code You can download the Jupyter Notebook file from here. After unzipping it, you will get the ipynb file. You can either use Google Collab or Jupyter Notebook to open the ipynb file. If you are using a regular Python editor like Spyder, then you can copy the code below and paste it on the editor and save the content to a file with .py extension. import numpy as np import pandas as pd from numpy.random import randn np.random.seed(50) radt = randn(5, 4) print("The generated 5x4 NumPy array:") print(radt) df1 = pd.DataFrame( radt, columns=['Hello1', 'Hello2', 'Hello3', 'Hello4'] ) print("Printing the entire DataFrame, df1") print(df1) print("Printing the Hello1 columns") print(df1['Hello1']) print("Printing Hello1 and Hello3 columns") print(df1[ ['Hello1', 'Hello3'] ]) df1['MyNewCol']=df1['Hello1']+df1['Hello2'] print("After creating MyNewCol that sums up Hello1 and Hello2 columns:") print(df1) df1.drop('Hello3', axis=1, inplace=True) print("After dropping the Hello3 column") print(df1) print("Printing a subset using iloc") print(df1.iloc[range(1, 3), range(1, 3)]) print('Values only:') print(df1.values) We will see a few more items of Pandas in the upcoming videos when we will work with scikit-learn’s machine learning algorithms. Here is the link to the next workshop video.
https://computing4all.com/data-science-workshop-1-part-4-pandas-continued/
CC-MAIN-2022-40
refinedweb
943
66.94
… I know this post is overdue, but I’m happy to say that in the time since MIX has elapsed, my wife and I have sold our condo and moved to a new home. I’ve also transition to a new contract, and I am excited to get my feet wet my new project. Despite the delay, it was a wonderful experience. This was my first year at MIX. The content, announcements, and the networking were all memorable. I only wish I could’ve attended all the sessions. This year was filled with a number of announcements at the two keynotes I did my best to update my twitter feed with some of the cool ones. The first keynote was focused around recent release of IE9, the next generation of web, ASP.NET MVC3, and HTML5, and the new release of IE 10 Platform Preview 1…… Using Ninject and Dependency Injection to enhance your ASP.Net MVC application’s Multi-Tenant Application. Using Ninject and Dependency Injection to enhance your ASP.Net MVC application’s Multi-Tenant Application. Discover how to use Inversion of Control and Dependency Injection to enhance your web application’s Multi-Tenant Application. Here is a really simple way to handle a session expiration in asp.net MVC using a base controller. Having all controller inherit from a basecontoller and overriding the OnActionExecuting event allows for checking the session before all actions are executed. Here is the code public class BaseController : Controller { protected override void OnActionExecuting (ActionExecutingContext filterContext) { // If session exists if (filterContext.HttpContext.Session != null) { //if new session if (filterContext.HttpContext.Session.IsNewSession) { …… I have been doing some work and research with ASP.NET MVC 2.0. My first interest was to try to figure out how to get Dependency Injection working with ASP.NET. I started doing investigating how to link in Springframework.net. This direction led me down a track that required some manual configuration. This is when i found S#arp Architecture [dead link], which I found very interesting since it gave you the benefits without the configuration up front. S#arp Architecture is a project template for Visual Studio that will set you up with a ASP.NET MVC application that is already wired up for Dependency Injection and using nHibernate for data access. more information can be found on the S#arp Architecture website and wiki. My findings so far have been very positive. Within about 45 minutes I had a web application with some basic CRUD functionality. ……
https://blog.tallan.com/tag/aspnet-mvc/
CC-MAIN-2019-04
refinedweb
418
57.77
Hi, In c how the linkage of Standard Library Functions happens? Please explain me. Suri well you know it's called by an include: #include <stdio.h> which go at the top of the source file. that makes the compiler look where it knows libraries are stored. when you give it an include to look for and if the file name is in < > brackets it'll try and find it in the standard place. any functions that are in stdio.h are then useable by the code that follow beneath the include. if the file name is enclosed in quotes like: #include "header.h" it'll look first in the same directory as where your source code is for that file, if it doesn't find it there it'll then look for it in the standard place. that's how i understand it anyway. hth. yep that's pretty much how it works. once the function you are calling is found it pretty much inserts the code from the called library function into your code.yep that's pretty much how it works. once the function you are calling is found it pretty much inserts the code from the called library function into your code. Nope. Nice try, but that isn't quite it. Try compiling the following: Now remove the #include <stdio.h> and try compiling again. Notice that the program compiles JUST fine and runs the SAME way.Now remove the #include <stdio.h> and try compiling again. Notice that the program compiles JUST fine and runs the SAME way.Code:#include <stdio.h> int main(void) { printf("Hello world\n"); return 0; } So, what's the deal then and what exactly is in this header file <stdio.h>. Well, if you open it, you'll notice the only thing that it contains is a few #define and #include lines (defining things like TRUE, FALSE, NULL etc. and possibly including other .h files ), and function prototypes. So where's the actual function code then?? The answer is very simple. All C compilers come with a bunch of libraries and the linker looks at those libraries by default, unless you specify alternative libraries to the linker. The standard library is usually called libc.a (for *NIX), libc.lib (for Visual c++), CS.LIB or CL.LIB (for Turbo C) etc. The linker that comes with the C compiler will automatically look at the standard libraries BY DEFAULT unless told otherwise specifically. All that the header files have are function prototypes, so that the compiler may know ahead of time, to typecast arguments to the correct types, if needed. If a C compiler can't find the function prototype, it'll assume that you've called it with the correct number/type of arguments and leave it to the linker to link them together! This explains why our sample hello world program works whether you include stdio.h or not. So how are these libraries created. Basically, when you compile C programs, this is how the process works: { C Source Files } ==> Compiler ==> {Object Files} {Object Files} + { Third Party Object Files } + { Libraries} ==> Linker ==> {Executable} The C compiler takes C source files and compiles them into Object files. An object file contains machine code + stub information to enable the linker to join the functions together to form the final executable. Hence, third party people can distribute only the object files and the header (.h files), and you can still create an executable using their object files. However, if you have a large number of object files, then they become a little unmanagable, especially, if you implement one or two functions per file. So, you can combine a bunch of object files into a library using a library tool. Depending on the compiler, the name of the tool varies. For example, Turbo C has TLIB.EXE, Visual C++ calls it LIB.EXE, C++ Builder has a wizard etc. You can use the library tool to take a bunch of Object files and organize them into a library. The standard library is built essentially the same way. Hope this helps! that's great information. certainly helps me. further question: how could i find out all the connected library files? find out what/where they all are? the reason i ask is because i am attempting to make an all in one easy to install version of gnu's gcc (for mac os x). i'm pretty naive on the whole thing, and after finally managing to build and install gcc (using apple's gcc that comes with apple's dev tools) i then copied over the freshly installed gcc to another machine (that didn't have dev tools or gcc) and found much to my surprise, but probably not to yours, that compilation needs more than just a compiler. so i need to find out what else is needed, that a development environment has, that a standard environment doesn't have (apart from the compiler obviously) i've found out i need an assembler and linker apparently. also the standard c libraries as they're also not included in a gcc install. how can i find out which libraries are needed by gcc? is that possible? how did you make the connection between stdio.h and libc.a (or different name for different system)? or is it just something you picked up rather than found out via the code/files? >> how could i find out all the connected library files? find out what/where they all are? Hopefully this page contains what you need. You also need all the header files under /usr/include, or whatever the equivalent is, under Mac OS X. Usually the library files are in /usr/lib (or /usr/local/lib) and the binaries are in /usr/bin (or /usr/local/bin) on a *nix system, and since OSX has a FreeBSD heritage, it might be in the same place (Don't take my word for it though! :)). >> how did you make the connection between stdio.h and libc.a (or different name for different system)? or is it just something you picked up rather than found out via the code/files? Comes with experience and writing apps that needed to be linked to libraries other than the standard libraries (this happens a lot, if you're writing code for handheld scanners or other such embedded systems). It's precisely when I was deprived of the standard libraries when I became aware of them :) I do the same thing but got past this problem. We just use a telnet client on the scanner that telnets to the application server using 802.11b. Love writting apps that run on our scanners. :)I do the same thing but got past this problem. We just use a telnet client on the scanner that telnets to the application server using 802.11b. Love writting apps that run on our scanners. :) Joe How To Ask FAQ | How To Be A Hacker | Hacker Mindset | jQuery yes that look very useful. it's got 'dependancies' listed which is very usefull. thanks.yes that look very useful. it's got 'dependancies' listed which is very usefull. thanks.
http://forums.devshed.com/programming-42/linakge-standard-library-functions-49606.html
CC-MAIN-2017-09
refinedweb
1,200
75.2
Create Smart Links Using TagHelpers in ASP.NET Core 1.0 The latest release of ASP.NET MVC has a new feature called TagHelpers. Let's see what trouble we can get into today by creating hyperlinks that think for themselves. I was extremely excited about the latest version of ASP.NET MVC when it came out. I looked at all of the features and was wondering what this "TagHelper" was. After reading up on these little gems, I realized that TagHelpers are similar to HtmlHelpers. Honestly, they feel more like HtmlHelpers...but this time, they are in disguise. If you need a refresher on UrlHelpers or HtmlHelpers, here are a list of earlier posts about each topic. When I said "in disguise," our mild-mannered HTML can now be a TagHelper. You need to pay attention to what attributes are added to your HTML. For example, let's say you want to create a home link so users can navigate back to the home page. Using TagHelpers, a simple one would look like this: <a asp-Home Page</a> Notice what I'm talking about? Did you see the new attributes asp-controller and asp-action? These attributes are part of the TagHelper classes "shipped" with the latest ASP.NET MVC 6 (source code) When you run your web app, the LinkTagHelper renders out to this: <a title="Back to home page" href="/">Home Page</a> As I said, you need to pay particular attention to your tag elements and attributes.. The details of these TagHelpers are available here. But I know what you're thinking... ...How do I create my own TagHelpers? If you are going to create your own TagHelper, my advice is to either find an existing TagHelper and inherit from it or create a new one by inheriting from the TagHelper class. Creating a Custom TagHelper For my CMS (Content Management System), I work with a lot of links on my site (just like any other webmaster), but one of my big problems I face is that some links on my site navigate to dead links on other sites. How can I fix that? While yelling can't be good for anyone, I need to be more pro-active and provide a better user experience for my audience. Why not create a SmartLink? I'm defining a SmartLink as a special tag that piggy-backs off of the anchor tag. So we're essentially adding more functionality to the HTML anchors through TagHelpers. A SmartLink works like this: while the page renders, the SmartLink will check to see if the link is broken or not. If it's broken, we deactivate the link and render plain text instead. So let's get started. Make a "Fingerprint" I created a brand new ASP.NET MVC 6 project and selected the ASP.NET 5 Preview in 2015. After my project loaded, I created a TagHelper folder in the root of the project. Once I had my folder, I created a new class called SmartLinkHelper and started thinking about this SmartLink class. First off, we don't need to exert ourselves when we already have an AnchorTagHelper available. Let's use that. [HtmlTargetElement("a", Attributes = SmartLinkAttributeName)] public class SmartLinkHelper : AnchorTagHelper { private const string SmartLinkAttributeName = "smart-link"; } Every TagHelper has to have a "fingerprint" so .NET can identify the tags it needs to render. The fingerprint for our SmartLink is the anchor tag ('a') and a "smart-link" attribute. Our smart link will have the following signature: <a smart-linkValid Link (to cnn.com)</a> Everything will be the same for our anchor tags, but we will add a "smart-link" attribute to identify it to .NET on which class to call when rendering our smart link. You can even define your own custom tag. Of course, we need to have an href. Why? Funny thing about the AnchorTagHelper...it's geared more towards an MVC ActionLink methodology as opposed to a general hyperlink. So yes, we need to add a Url attribute for external sites. Here's what we have so far: . For my particular needs, I decided to go with an async approach because I'm doing a lot of webpage calling. Why not spin up another thread to let me know if a webpage is available or not?. @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" @addTagHelper "*, SmartLinksDemo" I also added this HTML to the bottom just for a simple demonstration. <hr /> <div class="row"> <div class="col-md-12"> <h2>Smart Link Demo</h2> <ul> <a title="Back to home page" href="/">Home Page</a> <li><a asp-Home Page</a></li> <li><a smart-linkValid Link (to cnn.com)</a></li> <li><a smart-linkBad Link on purpose</a></li> </ul> </div> </div> Once you have this HTML included in your View, you are ready to test out your SmartLink TagHelper. Finish it! Here is our final SmartLink TagHelper. ); } private static void MergeAttributes(TagHelperContext context, TagHelperOutput output) { // Merge the attributes and remove the smart-link and activate attributes. var attributesToKeep = context.AllAttributes .Where(e => e.Name != SmartLinkAttributeName) .ToList(); if (!attributesToKeep.Any()) return; var attributes = context.AllAttributes.Except(attributesToKeep); foreach (var readOnlyTagHelperAttribute in attributes) { output.Attributes.Add(new TagHelperAttribute { Name = readOnlyTagHelperAttribute.Name, Value = readOnlyTagHelperAttribute.Value, Minimized = readOnlyTagHelperAttribute.Minimized }); } } private static void RemoveLink(TagHelperOutput output, string content) { output.PreContent.SetContent(String.Empty); output.TagName = ""; output.Content.SetContent(content); output.PostContent.SetContent(String.Empty); } private async Task<HttpStatusCode> GetStatusCode() { try { using (var client = new HttpClient()) { var msg = new HttpResponseMessage(); await client.GetAsync(Url); return msg.StatusCode; } } catch { return HttpStatusCode.InternalServerError; } } }. If I can help you in any way with TagHelpers, post a comment below and I will give it my best "college try."
https://www.danylkoweb.com/Blog/create-smart-links-using-taghelpers-in-aspnet-core-10-D3
CC-MAIN-2020-45
refinedweb
953
67.35
Need help to count emoticons from a Twitter search API? Rupinder Sandhu Greenhorn Joined: Mar 13, 2013 Posts: 3 posted Mar 13, 2013 19:12:37 0 Hey I have code that allows me to get data from a Twitter Search API. However I am having trouble counting the emoticons. I have a text file, with 126 emoticons, that I have classified against numbers 1-6. These numbers represent emotions. So one column is emoticons and next to it is the corresponding number. How do I read the text file that has both emoticon and number, and search the API and count the emoticons that it catches. So for example 1 1 =) 1 :-) 2 :@ 2 > 3 3 :-( etc. That is how the text file is set up. So every time an emoticon is caught in the search API, I want the count for each number to increase. How do I go about doing that? I have looked all over the web, which is how I noticed this forum. String emoticons = urlstr; // looks at the Twitter search API Pattern pattern = Pattern.compile("(\\Q:)\\E|\\Q:(\\E|\\Q:D\\E|\\Q:')\\E|" + "\\Q=)\\E)"); Matcher matcher = pattern.matcher(emoticons); /*while(matcher.find()) { System.out.println(matcher.group()); }*/ int counter = 0; for(int i=0;i<emoticons.length();i++){ if(emoticons.charAt(i)== ')' + ':' ){ counter++; } } System.out.println(emoticons + " = " + counter); I have tried that, but I have to input a pattern . And it gives me a count, but not one that is correct, because I checked manually. Campbell Ritchie Sheriff Joined: Oct 13, 2005 Posts: 32599 4 posted Mar 14, 2013 02:44:42 0 Welcome to the Ranch Why are you using the + operator with char s? Do you realise that char s are not letters, but numbers ? So your + will not give you the String at all? You can still use == , but it will not give you the result you want. I think you need to go back to a piece of paper and write down exactly how you intend to identify those emoticons. You cannot do it on screen, only on paper. then come back and tell us how you got on Rupinder Sandhu Greenhorn Joined: Mar 13, 2013 Posts: 3 posted Mar 14, 2013 16:08:12 0 Ok since you pointed that out about the char. I decided to put the emoticons into a Switch statement that deals with Strings. How do i go through statements and access the Twitter API, and count the emoticons this way?? Please help.. public class Happiness { int emoticon = 0; // I am unsure, why i need this bit String emoticonString;{ switch (emoticon) { case 1::)";break; case 49: emoticonString = "X-D";break; case 50: emoticonString = "B-)";break; case 51: emoticonString = ":>";break; case 52: emoticonString = "8-D";break; } System.out.println(emoticonString); } How do I count the emoticons, when it passes through all those cases? I have also thought of doing an array public class Fear { String [] anArray ={">.<", ">.<", "O_0"}; But i have no idea, how to carry on. How do i query the array so that it goes through the Twitter api and gives me a count if it catches any of the elements? Campbell Ritchie Sheriff Joined: Oct 13, 2005 Posts: 32599 4 posted Mar 15, 2013 02:38:33 0 That is not a switch which uses Strings, but a switch which uses int s. It will of course always print null . There is some poor design there, a class with no methods and no constructor. It might compile, but it is of no use to anybody. What do you mean by, “// I am unsure, why i need this bit”? Rupinder Sandhu Greenhorn Joined: Mar 13, 2013 Posts: 3 posted Mar 17, 2013 13:36:03 0 Hey, I managed to solve my problem. You can close this thread. I agree. Here's the link: - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3. subject: Need help to count emoticons from a Twitter search API? Similar Threads searching a string in an HTML file Regular Expression for Detecting Emoticons Counting exact matches of substring. search files in directory for string and return count Reading an array of numbers from a txt file All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/607235/java/java/count-emoticons-Twitter-search-API
CC-MAIN-2013-20
refinedweb
725
81.02
How ConcurrentHashMap is implemented in Java ConcurrentHashMap is introduced as an alternative of Hashtable and provided all functions supported by Hashtable with an additional feature called "concurrency level", which allows ConcurrentHashMap to partition Map. ConcurrentHashMap allows multiple readers to read concurrently without any blocking. This is achieved by partitioning Map into different parts based on concurrency level and locking only a portion of Map during updates. Default concurrency level is 16, and accordingly Map is divided into 16 part and each part is governed with a different lock. This means, 16 thread can operate on Map simultaneously until they are operating on different part of Map. This makes ConcurrentHashMap high performance despite keeping thread-safety intact. Though, it comes with a caveat. Since update operations like put(), remove(), putAll() or clear() is not synchronized, concurrent retrieval may not reflect most recent change on Map. In case of putAll() or clear(), which operates on whole Map, concurrent read may reflect insertion and removal of only some entries. Another important point to remember is iteration over CHM, Iterator returned by keySet of ConcurrentHashMap are weekly consistent and they only reflect state of ConcurrentHashMap and certain point and may not reflect any recent change. Iterator of ConcurrentHashMap's keySet area also fail-safe and doesn’t throw ConcurrentModificationExceptoin.. Default concurrency level is 16 and can be changed, by providing a number which make sense and work for you while creating ConcurrentHashMap. Since concurrency level is used for internal sizing and indicate number of concurrent update without contention, so, if you just have few writers or thread to update Map keeping it low is much better. ConcurrentHashMap also uses ReentrantLock to internally lock its segments. ConcurrentHashMap putifAbsent example in Java ConcurrentHashMap examples are similar to Hashtable examples, we have seen earlier, but worth knowing is the use of putIfAbsent() method. Many times we need to insert entry into Map if it's not present already, and we wrote following kind of code: synchronized(map){ if (map.get(key) == null){ return map.put(key, value); } else{ return map.get(key); } } Though this code will work fine in HashMap and Hashtable, This won't work in ConcurrentHashMap; because, during put operation whole map is not locked, and while one thread is putting value, other thread's get() call can still return null which result in one thread overriding value inserted by other thread. Ofcourse, you can wrap whole code in synchronized block and make it thread-safe but that will only make your code single threaded. ConcurrentHashMap provides putIfAbsent(key, value) which does same thing but atomically and thus eliminates above race condition. See Core Java for Inpatients for more details about how to use this method effectively: See Core Java for Inpatients for more details about how to use this method effectively: When to use ConcurrentHashMap in Java ConcurrentHashMap is best suited when you have multiple readers and few writers. If writers outnumber reader, or writer is equal to reader, than performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable. Performance of CHM drops, because you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map. ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads. As javadoc states, CHM is also a good replacement of Hashtable and should be used whenever possible, keeping in mind, that CHM provides slightly weeker form of synchronization than Hashtable. Summary Now we know What is ConcurrentHashMap in Java and when to use ConcurrentHashMap, it’s time to know and revise some important points about CHM in Java. 1. ConcurrentHashMap allows concurrent read and thread-safe update operation. 2. During the update operation, ConcurrentHashMap only locks a portion of Map instead of whole Map. 3. The concurrent update is achieved by internally dividing Map into the small portion which is defined by concurrency level. 4. Choose concurrency level carefully as a significantly higher number can be a waste of time and space and the lower number may introduce thread contention in case writers over number concurrency level. 5. All operations of ConcurrentHashMap are thread-safe. 6. Since ConcurrentHashMap implementation doesn't lock whole Map, there is chance of read overlapping with update operations like put() and remove(). In that case result returned by get() method will reflect most recently completed operation from there start. 7. Iterator returned by ConcurrentHashMap is weekly consistent, fail-safe and never throw ConcurrentModificationException. In Java. 8. ConcurrentHashMap doesn't allow null as key or value. 9. You can use ConcurrentHashMap in place of Hashtable but with caution as CHM doesn't lock whole Map. 10. During putAll() and clear() operations, the concurrent read may only reflect insertion or deletion of some entries. That’s all on What is ConcurrentHashMap in Java and when to use it. We have also seen little bit about internal working of ConcurrentHashMap and how it achieves it’s thread-safety and better performance over Hashtable and synchronized Map. Use ConcurrentHashMap in Java program, when there will be more reader than writers and it’s a good choice for creating cache in Java as well. Further Learning Java Fundamentals: The Java Language by Jim Wilson Java Fundamentals: Collections Java Concurrency in Practice Related Java Concurrency and Collection Tutorials from this blog 17 comments : one more thing I want to share Javin... interviewer was possibly expecting a simple answer, such as: •if the whole map is synchronized for get/put operations, adding threads won't improve throughput because the bottleneck will be the synchronized blocks. You can then write a piece of code with a synchronizedMap that shows that adding threads does not help •because the map uses several locks, and assuming you have more than one core on your machine, adding threads will improve throughput The example below outputs the following: Synchronized one thread: 30 Synchronized multiple threads: 96 Concurrent one thread: 219 Concurrent multiple threads: 142 So you can see that the synchronized version is more than 3 times slower under high contention (16 threads) whereas the concurrent version is almost twice as fast with multiple threads as with a single thread. It is also interesting to note that the ConcurrentMap has a non-negligible overhead in a single threaded situation. This is a very contrived example, with all the possible problems due to micro-benchmarking (first results should be discarded anyway). But it gives a hint at what happens. public class Test1 { static final int SIZE = 1000000; static final int THREADS = 16; static final ExecutorService executor = Executors.newFixedThreadPool(THREADS); public static void main(String[] args) throws Exception{ for (int i = 0; i < 10; i++) { System.out.println("Concurrent one thread"); addSingleThread(new ConcurrentHashMap ()); System.out.println("Concurrent multiple threads"); addMultipleThreads(new ConcurrentHashMap ()); System.out.println("Synchronized one thread"); addSingleThread(Collections.synchronizedMap(new HashMap ())); System.out.println("Synchronized multiple threads"); addMultipleThreads(Collections.synchronizedMap(new HashMap ())); } executor.shutdown(); } private static void addSingleThread(Map map) { long start = System.nanoTime(); for (int i = 0; i < SIZE; i++) { map.put(i, i); } System.out.println(map.size()); //use the result long end = System.nanoTime(); System.out.println("time with single thread: " + (end - start) / 1000000); } private static void addMultipleThreads(final Map map) throws Exception { List runnables = new ArrayList<> (); for (int i = 0; i < THREADS; i++) { final int start = i; runnables.add(new Runnable() { @Override public void run() { //Trying to have one runnable by bucket for (int j = start; j < SIZE; j += THREADS) { map.put(j, j); } } }); } List futures = new ArrayList<> (); long start = System.nanoTime(); for (Runnable r : runnables) { futures.add(executor.submit(r)); } for (Future f : futures) { f.get(); } System.out.println(map.size()); //use the result long end = System.nanoTime(); System.out.println("time with multiple threads: " + (end - start) / 1000000); } } @Saral Saxena, great comment. Yes, you are right on single threaded environment, ConcurrentHashMap is tough slow than Hashtable and HashMap. On scalability front, it achieves using concurrency level by dividing Map into segment, with each segment having its own lock. Thanks Javin,..As I have shown in the above example the two methods simply add 1 million entries to the map. the first one is run in the main thread, the second one is run with an executor service that has 16 threads. To try make to help the CHM, I count with a step of 16 (so one thread will put 0, 15, 31 etc, the second thread 1, 16, 32 etc) which should reduce lock contention and associate each thread with one lock (there are 16 locks, based on the hashcode of the key modulo 16). Note that the effect is more pronounced with more threads (with 100 threads, the sychronized version really suffers). In your code snippet, doesn't the "synchronized(map)" part actually lock the map? If you want your example to be relevant, shouldn't the if {} else {} be without the synchronized() block? Hi @mattnguyen, if you don't synchronized then that code snippet will create data race, where one thread calling get() getting null, just before another thread putting value, which result in overriding that value. synchronized is required to get the desired functionality, i.e. only insert,if not present. Did any one really faced questions like How ConcurrentHashMap works or internal implementation of ConcurrentHashMap in Java interview? is that a real question or hypothetical? 8. ConcurrentHashMap doesn't allow null as key or value.!! Then how the putIfAbsent will work, the example you gave..if(map.get(key)==null) @suresh, yes I faced these questions in an interview recently Does ConcurrentHashMap uses ReadWriteLock internally for allowing multiple thread to read and block only for writers? I am not sure, but thought this may be a good question here. @Anonymous, ConcurrentHashMap doesn't use ReadWriteLock, instead it uses multiple tables (arrays) known as Segment, each with there own lock. This concept is known as lock-stripping, this means, you don't need to lock whole map during write operation, only relevant segment gets locked. This is optimized for more reading than updating activity. Even a call to size() may perform poor because, in worst case a call to size() may lock all segment for calculating entries in each segment and then adding them up. As I said, ConcurrentHashMap is optimized for multiple readers with few writers. Just want to high light one important limitation of ConcurrentHashMap, client side locking is not possible as there is no lock, which can guard whole map. Though this limitation is somewhat addressed by adding ConcurrentMap interface and providing atomic function for compound operations e.g. putIfAbsent(), remove() or replace(key, oldValue, newValue) Don't use ConcurrentHashMap, instead create your own concurrent Map by using ReentrantReadWriteLock and high performance Map based on your need e.g. EnumMap, primitive maps from trove library. "concurrent retrieval may not reflect most recent change on Map" That's imprecise and misleading. From the Javadoc: "Retrievals reflect the results of the most recently completed update operations" (for put() and remove()). "For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries" on one hand, you have said that CHM has concurrent reads and THREAD SAFE writes, on the other hand you said "Since update operations like put(), remove(), putAll() or clear() is not synchronized". if updates are not synchronized then how come it has thread safe writes? Hi, I have littlebit confusion about this. You mentioned that only portion of map is locked while put operation is going on. I assume the segment in which map is putting entry is getting locked. Does it allow get() (read) operation on that segment? Because you mentioned: "because, during put operation whole map is not locked, and while one thread is putting value, other thread's get() call can still return null" this means get operation is allowed on locked region? you also mentioned: "because you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map" which means read operation is blocked by write operation. I found these two statements ambiguous and I started getting confused. hey can you please explain how it actually work. What is tree been node, how it allow multiple updates, how it increase size, why we need to declare initial capacity for performance. Hello Navrattan, rest of things about ConcurrentHashMap is same as HashMap except that it divides the map into segments and lock those segments instead of locking the whole Map. You specify size at the start to prevent resizing because that is expensive as it involves creating a new array and copying content from old array to new one.
http://javarevisited.blogspot.com/2013/02/concurrenthashmap-in-java-example-tutorial-working.html?showComment=1362216581149
CC-MAIN-2018-09
refinedweb
2,123
52.39
Pavel Agov1,555 Points Code Challenge: Slice Function Task 4 Solution not accepted? After searching on the forums, it appears that the reverse_evens() solution is as follows: def reverse_evens(items): return items[::2][::-1] My question is - how is this different than the below: return items[-1::-2] I tried submitting the second solution but it was not accepted. I've tried this in workspaces, and it seems that the output is the same with both even and odd-length lists. Is it related to the order of operations when reversing and traversing the list ? What am I missing? 1 Answer Chris FreemanTreehouse Moderator 55,457 Points The two functions don't alway give the same results. Examine the code below and its output: # code def reverse_evens_1(items): return items[-1::-2] def reverse_evens_2(items): return items[::2][::-1] print("reverse_evens_1([1, 2, 3, 4, 5]):") print(reverse_evens_1([1, 2, 3, 4, 5])) print("reverse_evens_2([1, 2, 3, 4, 5]):") print(reverse_evens_2([1, 2, 3, 4, 5])) print("reverse_evens_1([1, 2, 3, 4, 5, 6]):") print(reverse_evens_1([1, 2, 3, 4, 5, 6])) print("reverse_evens_2([1, 2, 3, 4, 5, 6]):") print(reverse_evens_2([1, 2, 3, 4, 5, 6])) #output reverse_evens_1([1, 2, 3, 4, 5]): [5, 3, 1] reverse_evens_2([1, 2, 3, 4, 5]): [5, 3, 1] reverse_evens_1([1, 2, 3, 4, 5, 6]): [6, 4, 2] reverse_evens_2([1, 2, 3, 4, 5, 6]): [5, 3, 1] Notice that an even number of item produces an incorrect result in reverse_evens_1 The first solution starts at the last item and includes every other item moving toward the first item. The second solution takes every other item start from the front of list then reverses it. Pavel Agov1,555 Points Pavel Agov1,555 Points I see where I was wrong now, thank you !
https://teamtreehouse.com/community/code-challenge-slice-function-task-4-solution-not-accepted
CC-MAIN-2019-26
refinedweb
302
50.2
Apache OpenOffice (AOO) Bugzilla – Issue 56031 import of ppt file containing "dim after animation" Last modified: 2017-05-20 10:55:16 UTC Some of my slides in .ppt format have bullet points that I bring on by 1st level paragraphs. Some are set in .ppt to have "dim after animation." After they are imported, some don't show "dim after animation." But the first line nevertheless does dim, and the others don't. The whole set of bullet points can't be done right in OO without removing the animation, and then adding animation back in. I can provide specific .ppt files if you like. Created attachment 30454 [details] problems with "dim after animation" import Reassigned. Set to new and change the target. I can reproduce the bug. Please have a look if this is duplicate to issue 41546. @cl->cgu: how can it be duplicate to issue 41546 when this issue is already integrated in m131, didn't you check on a current milestone? Also, does this issue realy only happens under linux? Reset assigne to the default "issues@openoffice.apache.org".
https://bz.apache.org/ooo/show_bug.cgi?id=56031
CC-MAIN-2020-29
refinedweb
184
68.97
Hey, I was wondering how to have Fscanf loop and do multiple calculations for 4 different employee numbers with 4 different hours and 4 different pay rates. #include <stdio.h> double pay_calc (double hours_worked, double pay_rate) { double tax,gross_pay,net_pay; gross_pay = hours_worked * pay_rate; if (hours_worked > 40) gross_pay = hours_worked * (pay_rate *1.5) ; tax = gross_pay * .03625; net_pay = gross_pay - tax; return net_pay; } int main() { FILE *input; int employee_number; double hours_worked, pay_rate; input = fopen("pay_file.txt", "r"); fscanf (input, "%d", &employee_number); /*printf ("Enter in hours worked: "); scanf ("%lf", &hours_worked);*/ fscanf (input, "%lf", &hours_worked); /*printf ("Enter in pay_rate: "); scanf ("%lf", &pay_rate);*/ fscanf(input, "%lf", &pay_rate); fclose(input); printf ("%d's pay is %lf\n", employee_number,pay_calc(hours_worked, pay_rate)); return 0; } This is how I set up pay_file.txt 101 44 7.50 102 30 6.00 103 40 8.50 105 48 12.00 Thanks in advance for any help.
https://www.daniweb.com/programming/software-development/threads/358409/loop-fscanf
CC-MAIN-2018-43
refinedweb
145
58.48
- Type: Bug - Status: Open - Priority: P1: Critical - Resolution: Unresolved - Affects Version/s: 5.12.3, 5.13, 5.14, 5.15 - Fix Version/s: None - Component/s: Quick: Core Declarative QML - Labels:None - Environment:Linux, Debian 9.11 with Qt 5.11.3 gcc64 (also seen on windows/msys) - Platform/s: The formatting of text in a QML Text object that has `textFormat: Text.RichText` is wrong for lines that follow a unordered list <ul> with a <br> that is indented itself. See the following example: import QtQuick 2.12 import QtQuick.Window 2.12 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") Text { textFormat: Text.RichText text: "<ul><li>one</li><li>two</li></ul> <br> Hello world indented <br> Hello world also indented <ul><li>one</li><li>two</li></ul> <br> Hello world not indented" } } Observed is that the first two "hello world ..." lines are indented on the same level as the closed <ul>. I would not expect any of the "hello world ..." lines to be indented since the HTML standard prescribes that whitespace in the source is displayed as a single whitespace.
https://bugreports.qt.io/browse/QTBUG-81662
CC-MAIN-2020-40
refinedweb
189
58.48
Using One Object Per Event Type With Publish And Subscribe (Pub/Sub) Yesterday, I was reading an interesting article by Miller Medeiros that compared different types of publish and subscribe mechanisms. Publish and Subscribe (Pub/Sub) is nothing new - if you use jQuery at all, you've probably been using Pub/Sub a lot (even without thinking about it). In the article, however, Miller described a Pub/Sub approach that I had never seen before: Signal. In the signal approach, each event type is defined by an individual event beacon. So, rather than binding to a generic event dispatcher, a subscriber would bind to a specific object that codes for a single event type. In the more generic, flexible approach to event binding, a subscriber would bind to an event beacon, supplying both an event type and an event callback: - eventedObject.bind( "someEvent", subscriberCallback ); In this case, the subscriber is binding to the event type, "someEvent," and would like the function, "subscriberCallback" to be invoked when that event is dispatched. In the Signal approach, the event binding is performed on an event beacon that codes for a specific event: - eventedObject.someEvent.bind( subscriberCallback ); The main difference here is that in the first approach, "someEvent" is an arbitrary string value; and, in the latter approach, "someEvent" is a property of the evented object. In theory, both of these approaches are the same - they allow for publishers to expose an event-binding surface; and, they allow subscribers to bind to specific event types. In practice, however, the major difference is that the Signal approach requires a more formalized event architecture; rather than creating just-in-time, string-based event types, each event has to be defined explicitly ahead of time as a property of the evented object before subscribers can even bind to it. As Miller points out in his pro/cons list, this is probably a good constraint. Since I had never seen this kind of Pub/Sub architecture before, I thought it would be good to experiment with a little code. And, to make it more fun, I wanted to explore some of the jQuery 1.7 Callbacks information that Addy Osmani discussed in his Demystifying jQuery 1.7's $.Callbacks article. In the following demo, I'm creating a Signal class (which wraps $.Callbacks) and then I'm using it to define several event types on a given object. - <!DOCTYPE html> - <html> - <head> - <title> - Using One Object Per Event Type With Publish And Subscribe - </title> - <script type="text/javascript" src="./jquery-1.7rc1.js"></script> - <script type="text/javascript"> - // = $.Callbacks(); - } - // Define the class methods. - Signal.prototype = { - // I bind an event handler. - bind: function( callback ){ - // Add this callback to the queue. - this.callbacks.add( callback ); - }, - // I dispatch the event with the given parameters. - dispatch: function(){ - // Invoke the callbacks. - this.callbacks.fireWith( - this.context, - arguments - ); - }, - // I unbind an event handler. - unbind: function( callback ){ - // Remove the callback from the queue. - this.callbacks.remove( callback ); - } - }; - // -------------------------------------------------- // - // -------------------------------------------------- // - // -------------------------------------------------- // - // -------------------------------------------------- // - // Create an instance of Sarah - var sarah = {}; - // Set the name. - sarah.name = "Sarah"; - // Create an event collection. In this scenario, each event - // is defined by an actual object - not just an event publish - // and subscribe entry point. - sarah.events = { - wakeUp: new Signal( sarah, "wakeup" ), - shower: new Signal( sarah, "shower" ), - gotoWork: new Signal( sarah, "gotowork" ), - gotoHome: new Signal( sarah, "gotohome" ), - sleep: new Signal( sarah, "sleep" ) - }; - // Execute one day. - sarah.live = function(){ - this.events.wakeUp.dispatch( "Stretch!" ); - this.events.shower.dispatch( "Rubba-dub-dub" ); - this.events.gotoWork.dispatch( "Hmmph" ); - this.events.gotoHome.dispatch( "Yawwwn" ); - this.events.shower.dispatch( "Oooooooh" ); - this.events.sleep.dispatch( "Sleeeepy!" ); - }; - // -------------------------------------------------- // - // -------------------------------------------------- // - // Bind to shower events. - sarah.events.shower.bind( - function( metaData ){ - // Log event. - console.log( this.name, "[Shower]:", metaData ); - } - ); - // Execute one day in the life of Sarah. - sarah.live(); - </script> - </head> - <body> - <!-- Left intentionally blank. --> - </body> - </html> As you can see, the Signal class represents a single event type. It then exposes two subscriber methods: - bind( callback ) - unbind( callback ) This Signal class is then instantiated for each event type available on the "sarah" object. When we bind to events on sarah, we aren't binding to sarah itself; rather, we are binding to the event surface exposed by sarah. And, when we run the above code, we get the following console output: Sarah [Shower]: Rubba-dub-dub Sarah [Shower]: Oooooooh While this approach does feel a bit awkward, probably due to its novelty, I like the fact that I have to explicitly define my object's event types. I suspect that this would force me to think more holistically about my object architecture. And, I think there would be improved readability and maintainability in being able to see all the events defined in a single place. Reader Comments Nice write-up and video, I hope more people understands the benefits of having a concrete object to each event type and not relying on strings. I'm not sure if it was by coincidence but [DART DOM event system]() is very similar to Signals, they use a namespace called "on" to store all the event types instead of "events" tho... [js-signals]() have a couple extra features like disable/enable a signal, remove all the callbacks at once, ability to set default parameters and change the execution context (`this` object) for each handler. It also doesn't require jQuery and works on nodejs as well. Cheers. This pretty much like the signal/slot system in Qt. Classes have signals and slots and you connect signals to slots. When the signal is emited(fired) it calls all the slots connected to it in an arbitrary order. It must feel somewhat awkward in javascript since the event mechanism is already somewhat native to language unlike in Qt where it was build to make gui easier to make in c++. [sorry for the double post] Qt code sample Yep Guillaume, it's very similar to Qt, AS3-Signals (js-signals was based on AS3-Signals) was based on Qt signals/slots and C# Events. ActionScript 3 native Events are very similar to DOM2 events (in fact it was based on DOM3 events), and still a lot of AS3 developers started using Signals instead of the native event model (even for native events), the main reason for that is because it doesn't rely on strings (code completion, live error checking / compiler errors, can be added to interfaces, etc..) [more info about it](). In JavaScript it makes sense to create a custom pub/sub system since the language doesn't provide an easy way to dispatch custom events ( is really awkward and verbose). Cheers. @Miller, The JS Signal stuff looks pretty interesting. I enjoyed, especially, that you included a Naming convention for the event types. Although naming stuff is supposed to be one of the hardest parts of computer science, I happen to think that naming event-types is especially difficult. I never know if I should to present tense or past tense... or if it should depend on whether or not the event can be cancelled. @Guillaume, It is definitely a bit strange, especially since every event type I've looked at up to this point has been string-based with a generic, flexible binding. But, while it is awkward, there is something that I really do like about it :) @Miller, Having the code-completion aspect is really nice. I use an Eclipse-based editor which, when dealing with Html / JavaScript, uses Aptana under the cover (or so I'm told); in general, this seems to have really good code completion - so, Im sure it would pick on these object-based events quite easily. Heck yeah :D
http://www.bennadel.com/blog/2276-using-one-object-per-event-type-with-publish-and-subscribe-pub-sub.htm
CC-MAIN-2014-41
refinedweb
1,266
62.17
BackgroundIn last few posts we saw various I/O streams. We saw example code for byte stream and character stream.We saw BufferedStream and we even saw how to take input from standard input using BufferedReader.Now lets see how can we use Scanner to take input and understand When and why do we use it? Why scanning? Objects of type scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators. Lets see how Scanner works by taking an example. Example code public class ScannerDemonstartor{ public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("inFile.txt"))); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } } Code Analysis and Explanation As explained earlier Scanner scan word by word, basically part of line separated by a separator(default is a white space). If you want this separator to be your separator they you do something like below - s = new Scanner(new BufferedReader(new FileReader("inFile.txt")),"mySeparator"); Remaining structure of code is very much similar to what we have explained in last few posts.One more thing we use .hasNext() method to check if more tokens exist. Using scanner to take input from Standard input Scanner sc = new Scanner(System.in); String readLine = sc.nextLine(); int readInt = sc.nextInt(); boolean readChar = sc.nextBoolean(); and so on..... In this way you can take any data type as input.We would mostly use Scanner class to take standard inputs in all our future code so understand this completely.Do let me know if you have any questions.
http://opensourceforgeeks.blogspot.com/2013_03_10_archive.html
CC-MAIN-2019-43
refinedweb
296
60.21
Wallpaper Other 6 comments thank's - Jan 23 2005 Wallpaper Other 6 comments A new wallpaper for my laptop! :-) - Jul 22 2004 Wallpaper Other 9 comments Where are you practicing? I live in Rome too :) - Jun 14 2004 I love the effect on kanji and Uyeshiba is the best man and philosopher i've ever studied! I can see a nice pic of "the last samurai" film :) Thank's for your excellent work!! oss... Ciao!! ^_^ - Jun 15 2004 Great work... i've ever dream something like this!!! Thank's!!! - May 21 2004 Wallpaper Other 2 comments It's so simple to delete the text!! :) Cut the text and fill the blank space with the color of the sky! =) - Feb 25 2004 Wallpaper Other 5 comments can you post only the logo layer? So i can use it with every bg! - Feb 24 2004 Karamba & Superkaramba 15 comments ----- bunker@slackbox:~$ superkaramba superkaramba: TaskManager::TaskManager() Traceback (most recent call last): File "/home/bunker/.superkaramba/themes/custom_xmms/custom_xmms.py", line 5, in ? import xmms.control ImportError: No module named xmms.control ------------------------------------------------------ What does ImportError mean? ----- Where i can download it? I use slackware 9.1. Google isn't my friend in this situation :) - Nov 22 2003 KDE Plasma Screenshots 3 comments What did you do for play counterstrike under linux??? It's an emulated version? - Nov 10 2003 Icon Sub-Sets 24 comments I use this theme by now! I'll wait for future release! - Sep 29 2003 Wallpaper Other 6 comments Bye! - Dec 17 2002 Ice-WM Themes 5 comments TitleBarCentered=1 in default.theme file - Dec 12 2002 Wallpaper Other 6 comments PS: good work guy! - Nov 30 2002 I will install it as soon as possible!! Bye - Nov 07 2002 thank's - Jan 23 2005
https://www.pling.com/u/bunker/
CC-MAIN-2020-29
refinedweb
296
77.43
Null checking is an essential part of developing quality C# code. If code attempts to access a member of a null object reference, it throws a NullReferenceException. However, using if statements to check for null references can make the code more verbose. The null-coalescing and null-conditional operators can reduce the amount of code that needs to be written to avoid a NullReferenceException. This article explains how to use these operators. Consider this code. It throws a NullReferenceException. 1internal class Program 2{ 3 private static void Main(string[] args) 4 { 5 Item item = null; 6 Console.WriteLine($"Name: {item.Name}"); 7 } 8} 9 10internal class Item 11{ 12 public string Name { get; } 13} To fix this code, we could add an if statement to check for null. 1private static void Main(string[] args) 2{ 3 Item item = null; 4 5 if (item != null) 6 { 7 Console.WriteLine($"Name: {item.Name}"); 8 } 9 else 10 { 11 Console.WriteLine($"Name: "); 12 } 13} However, the above code increases the complexity and creates another code path. Another way to solve this issue is to use a null-conditional operator, ?. 1private static void Main(string[] args) 2{ 3 Item item = null; 4 Console.WriteLine($"Name: {item?.Name}"); 5} The part to the right of the ? only evaluates if the part to the left is not null. Otherwise, the code returns null. So, in the case above, item?.Name evaluates to null, but it does not throw an exception because there is no attempt to access a member on a null reference. Use the null-conditional operator on members of namespaces, types, array elements, access methods, or to invoke delegates. The class below has two methods that raise an event. The dangerous version throws a NullReferenceException if there is no event handler attached. The safe version does not. It is always safe to call the method, even when there is no event handler attached. 1public class LongProcess 2{ 3 public event EventHandler<string> Finished; 4 5 public void FinishSafely() 6 { 7 Finished?.Invoke(this, "The process finished successfully"); 8 } 9 10 public void FinishDangerously() 11 { 12 Finished.Invoke(this, "The process finished successfully"); 13 } 14} ?? is the null-coalescing operator. It returns the value of the part on the left if it is not a null reference. Otherwise, it returns the value of the part on the right. Use this operator to fall back on a given value. In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned. This code returns the name of an item or the default name if the item is null. As you can see, this operator is a handy tool when working with the null-conditional operator. 1private static void Main(string[] args) 2{ 3 var defaultName = "Default"; 4 Item item = null; 5 Console.WriteLine($"Name: {item?.Name ?? defaultName}"); 6 Console.ReadLine(); 7} Output: Default From C# 7 onwards, it has been possible to use the null-coalescing operator to shorten the validation of arguments. This class requires the message argument in the constructor. Before C# 7, validation would require an if statement. 1internal class MessageProcessor 2{ 3 private readonly string _Message; 4 5 public MessageProcessor(string message) 6 { 7 if (message == null) throw new ArgumentNullException(nameof(message)); 8 _Message = message; 9 } 10} Using the null coalescing operator allows this to be shortened to the code below. 1internal class MessageProcessor 2{ 3 private readonly string _Message; 4 5 public MessageProcessor(string message) 6 { 7 _Message = message ?? throw new ArgumentNullException(nameof(message)); 8 } 9} Null checking is important for code stability. The null-conditional operator can be used to simplify null checking. The null-coalescing operator is a great complement to it and can further simplify code where the aim is to return something other than null.
https://www.pluralsight.com/guides/using-conditional-and-null-coalescing-operators
CC-MAIN-2022-40
refinedweb
638
57.98
Message-ID: <760798784.6843.1413798698644.JavaMail.haus-conf@codehaus02.managed.contegix.com> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_6842_1030791419.1413798698643" ------=_Part_6842_1030791419.1413798698643 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: W= indows Scripting Host (WSH) scripting with VBScript - only it= 's for Java. Once installed into Groovy, <= strong>Scriptom allows you to script ActiveX or <= strong>COM Windows components from Groovy.=20 What this means is that you can use Groovy to automate Word or Excel documents, control Internet Explorer= , make your PC talk using the Microsoft Speech API, monitor processes with WMI (Windows Management Instrume= ntation), or browse the Windows Registry using WSh= ell (among many, many other things). It is also a convenient= way to talk to custom VB6 or COM-enabled Microsof= t.NET libraries (compare this to the administrative headaches of g= etting Java and .NET to talk using Of course, Scriptom can be used only on Microso= ft Windows.=20 Scriptom is bundled into the Groovy Windows-Installer, and the most current version can be d= ownloaded from this page (see below). The codebase is considered = stable and feature-complete. The Jacob project -&nbs= p;Scriptom's foundation - was started in = 1999 and is being used in thousands of production applications worldwide.&n= bsp; Scriptom is only a few years old, but it is = ;already stable and mature because it is built on an existing, be= st-of-breed platform.=20 Scriptom gives you all the COM-scripti= ng power of Jacob, only it is a lot easier.=20 The Scriptom team=20 Scriptom 1.5 requires Groovy 1.5. = ;Because of dependencies on Jacob 1.14, Scriptom= strong> also requires Java 1.5 or higher.=20 Download the project archive(s) and extract the fi= les.=20 Install the jar file and DLL file(s) into your project, and optionally i= nstall an update from Microsoft:=20 The project archive contains all the Scriptom source fi= les, Java source files from Jacob, and an ANT bu= ild script. To save space, the Groovy JAR files have been omitted from= the archive. For a successful compilation, Groovy JAR files mus= t be added to the project/lib fo= lder.=20 The latest build requires Groovy 1.5.=20 Scriptom includes source files from Jacob<= /strong> version 1.14. You don't need to download it= from the Jacob project on SourceForge.net.=20 To build the project, run project/buil= d/make.bat.=20 The build process requires Java 1.5 or higher (= Java 1.6 recommended) and ANT 1.6.5 or better.=20 Scriptom 1.5 is a substantial upg= rade to previous versions of Scriptom, and is not back= ward compatible. We hope you will agree that it is worth a littl= e code rework to get all these great new features!=20 Scriptom 1.5 is not backward compatible with previ= ous versions of Scriptom. To get your scripts runnin= g again, do this:=20 going to have it speak asynchronously and wait until it is d= one.=20 import org.codehaus.groovy.scriptom.* import org.codehaus.groovy.scriptom.tlb.sapi.SpeechVoiceSpeakFlags; import org.codehaus.groovy.scriptom.tlb.sapi.SpeechRunState; //Definitive proof that you CAN talk and chew gum at the same time. Scriptom.inApartment { def voice =3D new ActiveXObject('SAPI.SpVoice') voice.Speak 'GROOVY and SCRIPT um make com automation simple, fun, and gr= oovy, man!', SpeechVoiceSpeakFlags.SVSFlagsAsync while(voice.Status.RunningState !=3D SpeechRunState.SRSEDone) { println 'Chew gum...' sleep 1000 } } println 'Speaker is done.'=20 If you have scripted COM before, you are probably used to using "ma= gic numbers" throughout your code in place of COM constants. In = this code sample, we're using fully-qualified constants instead.=20.=20!=20 Some additional examples included with Scriptom:=20 Consuming Visual Basic 6 (VB6) and Visual Basic= .NET COM-enabled DLLs.=20 All known (unresolved) issues and feature requests are listed in the Scriptom Jira database.=20 Changes to each build are summarized in the Change Log.=20 Recent builds of Scriptom can be found here. Older versions are archiv= ed:=20
http://docs.codehaus.org/exportword?pageId=35422273
CC-MAIN-2014-42
refinedweb
695
59.8
If a computer only has Adobe Reader installed, can an application running on that computer interact with a pdf document via OLE? In particular, can an application on that computer use AcroExch.App and AcroExch.AVDoc objects? Example code: #import "acrobat.tlb" rename_namespace("ACROBAT"), auto_rename ACROBAT::CAcroAppPtr app("AcroExch.App"); ACROBAT::CAcroAVDocPtr avDoc("AcroExch.AVDoc"); ACROBAT::CAcroPDDocPtr pdDoc; avDoc->Open(TEXT("c:\\example.pdf"), TEXT("")); pdDoc = avDoc->GetPDDoc(); pdDoc->OpenAVDoc("Title"); Currently creating app gives error: Invalid class string Thanks! > If a computer only has Adobe Reader installed, can an application running on that computer interact with a pdf document via OLE? No, > In particular, can an application on that computer use AcroExch.App and AcroExch.AVDoc objects? No. No, it cannot. Reader doesn't support COM/OLE automation. Thank you for the very fast response. One follow-up question: Assume I buy Adobe Acrobat to develop this application and use OLE to interact with pdf documents in the application. Will my clients need to also buy Adobe Acrobat for the application to work on their computers? Or can I package it with my application behind the scenes? Thanks again! Yes, your clients would need to purchase Acrobat for your application to work. It needs to be installed on every computer on which your software would operate. And remember that Acrobat can NOT be automated to do work for someone not licensed to use it.... Related to this post, lets say I get the approval from Adobe (RIKLA stuff), will these classes work for Reader plugin? i.e AcroAppClass and CAcroPDDoc If not, what are the Reader plugin APIs available in SDK that does text extraction and highlight functionality in Reader (which is my only 2 requirement now). No, because they simply do not exist in Reader. They only exist in Acrobat. But if you are writing a plugin, why do you need them? There are much better APIs (PDWordFinder, etc.) available to you via plugins... What I was trying is to get hold of ActiveDoc once I pass on the control from Plugin code to my C# code, so that I can extract text and do the highlight stuff with the help of AcroAppClass and CAcroPDDoc. Ok. PDWordFinder will solve one of my problem as it will work for Reader. Now I can extract text from a Reader document and send it to my C# Form from plugin. Now, from that Windows Form code, how can I highlight a particular word back in the PDF document. Is there a Reader supported API (#HiliteEntry?) Yeah, that won't work with Reader - sorry! You will need to do the extraction in the plugin and then send that extracted text to the C# code. You will need to send info back to the plugin to tell it what you want hilited and then it can do it... Thats great,atleast I have a way to talk back to Reader document from C#. Can you please point me some SDK sample code which does this handshake? Meaning, invoking the plugin method from outside plugin code (in my case from C# Winform to plugin code to highlite a word). Sorry, no samples of this type of thing - but that's because it's not Acrobat/Reader centric. Do whatever you want to communicate... Thanks! But if there is a sample which atleast invokes a plugin method from outside, that will really help me to proceed further. Or any direction of this sort will also helpful. Can any one answer my previous question? I am searching SDK documentation and I found something called HFT. Is that the solution for my requirement, i.e invoking a plugin method from outside? Please let me know. Replying to my own questions above....found a DDE (very old IAC technique and not usually recommended tough ) way to talk to Acrobat/Reader instance (called as DDE Server). There is a sample project which demonstrates DDE and it is in C++. As I need to talk from my Winform, I am gonna use Ndde (open source) to talk back to Acrobat/Reader instance. It would be more helpful if some sample code/project is available in SDK to demonstrate IAC via COM/OLE as DDE is a very old technique. -AT Adobe Reader doesn't support COM/OLE - only DDE. Irosenth, this is kinda contradicting. I remember you were saying "If Adobe approves your Reader plugin, then it can do what ever". Meaning COM/OLE/Named pipes. I thought COM/OLE is available for Reader, but your above reply says it strictly supports only DDE (which is gud for me as I hav explained above, am using DDE to send messages back to Reader instance to invoke the Highlite plugin function ). Please can you clarify why COM/OLE is not available for Reader and why only old technique, DDE is available for Reader? Sorry - OK for you to do from your plugin. (I was referring to built-in support) Thats convincing to me and good to know that Reader will support IAC via COM apart from DDE. I will try to create a COM component and expose the Highlite API, add reference to my C# Winform and invoke it from there. Hi Athirukk from above posts, it appear you have worked good deal to edit pdf docs without using SDK ( with the help of plugins/DDE). can you please help me what was the result . as i have the similar issue (ActiveX is not able to create objects for data points i have in the code @ ). apprciate any guidance. regards Sidharth Sid - What I had achieved using Ndde (opensource) is to make a connection from .Net code (Winform) to C++ code (Adobe Plugin). All my code does is to invoke C++ code from .Net to retrieve (read only) the contents/text of a PDF document and I did not do any EDITING. What are you trying to achieve? -AT athirukk- i need to write reference text on pdf docs..with acrobat this is possible as confirmed by Irosenth....however was thinking if it is possible without spending any money... i will look at ndde....however any direction u want me to point .. Without spending money you can't create plug-ins for Adobe Reader. As Bernd mentioned, you have to get RIKLA from Adobe to make your plugin work for Reader.
http://forums.adobe.com/thread/720961
CC-MAIN-2014-10
refinedweb
1,060
66.64
12 January 2007 16:37 [Source: ICIS news] By Nigel Davis LONDON (ICIS news)--?xml:namespace> Some European nations may seek quick wins to meet national targets but the pressure will be on firms that process materials to make further cuts. The European Commission (EC) this week unveiled proposals to cut EU greenhouse gas emissions by 20% by 2020 if there is no international agreement and by 30% in the case of a climate change agreement among developed countries. Its energy policy package encompasses energy efficiency, security of supply, energy technologies and key competitive aspects of Raising energy efficiency has been on the chemical industry agenda for years. Remember energy accounts for more than 50% of the variable costs of production of most materials. But as the EU policies develop, chemical companies are more than likely to have to pay more for primary energy. They will also be pressed hard to become more energy efficient and to reduce their carbon footprint. Some companies will gain – the likes of Rhodia and Ineos Fluor certainly as they obtain carbon emission reduction credits for newly applied carbon abatement technology – but most will not. The knee jerk reaction from the sector on release of the new energy plans could have been expected. But was it necessary? The sector is worried about its international competitiveness. In an ideal world the playing field would be level but in reality it is not. European civil servants and politicians have come to better understand the role of chemicals in modern life as they have put together the Reach legislative package. But the message has to be hammered home that energy and industrial competitiveness run hand in hand. That does not have to mean that countries or industrial sectors can continue to be profligate with energy. Increased energy efficiency can put them in good stead. The argument is not so well made for the reduction of carbon emissions. But if a proper cost is put on carbon and trading mechanisms made to work effectively, then great strides are possible. For The true challenge is not technical or indeed related to energy markets but political. “I believe we can be more creative in finding effective and workable policies well beyond the EU borders while avoiding the cumbersome UN process,” said director general of the European chemicals trade group Cefic, Alain Perroy, this week.He is right. But the chemicals sector can also be more creative in its approach to global warming. The clever companies embrace the concept and seek out opportunities to be more forward looking. In the UK this week companies in the Confederation of British Industry (CBI) created a Climate Change Task Force which included companies as diverse as supermarket chain Tesco, British Airways, BP, BT and steel producer Corus. It met for the first time on Friday (12 January). “Climate change poses a challenge to business, as a major source of emissions, but it also presents significant opportunities,” CBI director general Richard Lambert said. “Business needs to be at the heart of the debate to ensure it can play its role effectively alongside other key players," he added. The climate change group looks as much towards the opportunities presented by the EU’s more proactive climate change policy as towards the threats. The chemical industry would do well to show that it is willing to think along similar
http://www.icis.com/Articles/2007/01/12/1120300/insight-the-challenge-of-carbon-control.html
CC-MAIN-2015-06
refinedweb
561
51.99
11 November 2010 14:13 [Source: ICIS news] TORONTO (ICIS)--Braskem’s third-quarter net income fell 14% to reais (R) R554m ($320m) from R645m in the 2009 third quarter, largely due to a 9% year-over-year depreciation of the US dollar versus the Brazilian reais, the Brazilian petrochemicals and plastics major said on Thursday. Since Braskem holds net exposure to the US dollar, any change in the exchange rate impacted its financial results, the company said. Overall third-quarter net revenues rose to R7.28bn, up 26% from R5.79bn in the 2009 third quarter. Earnings before interest, tax, depreciation and amortisation (EBITDA) fell 7% to R1.03bn, largely because of a “compression in resin-feedstock margins in the international market” and the appreciation in the reais, the company said. Third-quarter EBITDA margin was 14.2%, down 5 percentage points from 19.2% in the 2009 third quarter. Third-quarter operating rates were over 90%, Braskem said. During the quarter, Braskem started up a “green ethylene plant” at its Trifuno petrochemical complex, it added. Going forward, Braskem said it expected to see relatively slower global growth in the current fourth quarter. However, slower global growth would not affect Braskem’s domestic market in ?xml:namespace> “ “In ($1 = R
http://www.icis.com/Articles/2010/11/11/9409634/braskem-q3-net-income-falls-14-to-r554m-on-currency-effects.html
CC-MAIN-2014-15
refinedweb
211
58.38
Hi folks, Do you have JUnit support on the Scala plugin roadmap? That is, to be able to run JUnit tests written in Scala directly from IDE. At the moment we have a separate Java module for tests because of this. It would be nice to simplify the project structure by moving those to Scala eventually. Note, users of other test tools would benefit from this feature too if they provide @RunWith compatible JUnit runner. Cheers, Joni Hi folks, junit4 is not acala compatible in general (no nesting annotations in scala), but running junit3 should be pretty easy I see. But it would still be useful. For instance specs BDD tool provides a JUnit4 compatible runner: and so does JDave: This is a common way to benefit from existing JUnit tools without using JUnit API itself. Cheers, Joni Some JUnit support provided now. Also as TestNG support. Some JUnit support provided now. Also as TestNG support.]]> I can't figure out how to get JUnit support to work with Scala. I'm using the latest version of the plugin as of this date. I'm actually using Specs with the JUnit4 runner. I create a JUnit run configuration but on running it complains that "No tests found in package ...". I'm not sure what to do. I have classes named ...Test. Did you try something like this ? That definitely does not work. HOWEVER, a java file in my scala project totally works: package test.scala.com.twitter.service.cachet.test.unit; import junit.framework.TestSuite; import org.junit.Test; public class Goop { @Test public void testgoo() { assert(2 == 3); } } Actually the Java code causes a test class to be found but not a test method. so no tests run but the test runner comes up and goes green. if you have git installed, `git clone git://github.com/nkallen/cachet.git` That's my code with all of the IntelliJ files too. You can see the behavior. the scala test isn't found and the java one doesn't have individual tests. If you figure out how to get that to work, what I really want to work is `CacheEntrySpecTest`. Nick, This is not bug, but feature, which is not implemented yet. You're able to run your JUnit4-testclass by Ctra-Alt-F10 on class directly but you cannot do it for the whole package, cause we haven't implemented appropriate indices yet. We're doing our bet to implement them for next release. With best regards, Ilya
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206003609-JUnit-support
CC-MAIN-2020-24
refinedweb
419
68.36
Opened 8 years ago Closed 8 years ago Last modified 7 years ago #11067 closed defect (fixed) Mainnav Wiki and metanav Help/Guide visibility should be determined by fine-grained permissions Description The Wiki mainnav entry is hidden and the Help/Guide metanav entry is shown for an anonymous user when the following TracFineGrainedPermissions configuration is specified: [wiki:WikiStart@*] anonymous = WIKI_VIEW [wiki:*] * = However, Wiki should be shown and Help/Guide should be hidden. This has been discussed on the mailing list. Attachments (1) Change History (10) by , 8 years ago comment:1 by , 8 years ago t11067-r11682-1.patch is the first attempt to fix the issue. My reasoning is that the Wiki mainnav entry points to WikiStart, so we should be checking fine-grained access to WikiStart before showing the Wiki mainnav entry. The same for the Help/Guide metanav entry and TracGuide. However, what I just said is not strictly true, because the user could be changing where the navigation entry points through a configuration such as the following: [mainnav] wiki.href = /wiki/TracSupport Fixing the issue for various mainnav/ metanav configurations will require more extensive changes and is complex. If the user specifies a wiki page in wiki.href (e.g. /wiki/TracSupport), then we can easily check for fine-grained access to that wiki page by accessing the mainnav configuration in wiki.web_ui.get_navigation_items, but it is possible that the user would point to another realm or somewhere else entirely. The only sensible thing to do is to parse wiki.href into a realm and id, construct a Resource object and perform the fine-grained permissions checks. I'd be happy to work up a patch for that, but it seems like a lot of work, so I'd like to get some feedback on what makes sense before going down the route. I think the patch would look something like this (untested, more changes would be needed to handle URLs pointing outside of Trac such as those shown in TracNavigation#Notes): def get_navigation_items(self, req): # returns None for label if item not enabled label, realm, id = self.get_mainnav_config('wiki') if label is not None: resource = Resource(realm, id) if 'WIKI_VIEW' in req.perm(resource): yield ('mainnav', realm, tag.a(label, href=req.href(realm, id), accesskey=1)) # returns None for label if item not enabled label, realm, id = self.get_mainnav_config('help') if label is not None: resource = Resource(realm, id) if 'WIKI_VIEW' in req.perm(resource): yield ('mainnav', realm, tag.a(label, href=req.href(realm, id), accesskey=1)) If t11067-r11682-1.patch will be accepted and you'd like some functional tests then I'd be happy to add those. (Apparently I confused the CC field with the Keywords field when creating the ticket, and don't have permissions to fix it now.) comment:2 by , 8 years ago comment:3 by , 8 years ago I spent some more time looking into the code and found that the Wiki and Help/Guide navigation entries are actually pretty unique in that they are the only navigation entries that, by default (without an overriding [mainnav] / [metanav] configuration), direct to a specific resource id. All of the other entries direct to a "parent" page that doesn't have a resource id. For example, initially I thought Admin would follow the same pattern, but a user will see the Admin entry if they have access to at least one admin panel. I suppose this has been fairly well tested already since users can have PERMISSION_GRANT and PERMISSION_REVOKE, enabling them to see only the Permissions admin panel. I found that fine-grained permission checks are not implemented for any of the admin panels, but that can be the subject of a different ticket (#11069). I propose scheduling the fix in t11067-r11682-1.patch for 1.0.2, and the more extensive work of pulling parts of Chrome.prepare_request into get_navigation_items for next-dev-1.1.x, in a separate ticket (anticipating several iterations of patches). Patch against r11682 of the trunk.
https://trac.edgewall.org/ticket/11067
CC-MAIN-2021-10
refinedweb
675
53.31
11 IntroductionLevel set methods are mathematical tools for transforming surfaces. Thesesurfaces are described by a signed-distance-function, that given a point returnsthe distance to the surface. The surface separates the inside and the outside ofsome object, it is therefore often referred to as the interface. On a computer,one stores an implicit representation of the interface. That is, we store a valuefor each pixel, representing the distance from that pixel to the surface. Insidethe object, this distance is negative, and outside it is positive, see figure 1 for asmall example, with a circle with unit radius, centred in a 3 × 3 grid. 0.41 0 0.41 0 −1 0 2 Picking a surface distance at time t0 and solving equations thus allows forthe calculation of the surface at a later timestep t1 . Every time we calculatethis step forward in time, we risk corrupting our φ matrix, so that it is no longerdescriping a signed distance function. It is therefore vital to re-normalize it toa signed distance function. How this is done in practice is covered later on. The first part of this paper will cover how we solve a level set equation, howwe reinitialize our signed distance function representation and what the Narrowband method is all about. The second part of the paper will consider itself with our basic frameworkfor working with level sets. This can be seen as a guide to how to write a levelset solver, or at least how we have done it. The third part descripes applications of our framework. In this part we willdescripe how to generete exciting φ matrixes and how to perform the binaryoperations union, intersection and minus. We will look at different speed func-tions, including a speed function for morphing between different φ. Finally wewill look at the detection of edges in images. 1.1 Solving1.1.1 Advection by vector field ∂φA possible solution to the equation ∂t = H is H = −V · ∇φ (1) where ∇φ = ( ∂φ ∂φ ∂x , ∂y ) and V is a vector field. Solving the level set equation thus amounts to moving the interface in thedirection of a vector field. This field can depend on a set of variables. 3 The idea is to pick a vector field and for each coordinate calculate ∇φ, dotthis with V and see where it takes you. The main problem is, of course, tocalculate ∇φ = ( ∂φ ∂φ ∂x , ∂y ), from our grid representation. This is where magical calculus kicks in. We can approximate this value ina point, using the upwind scheme. Given a point (x, y) ∈ R2 and a vectorv = (vx , vy ) = V (x, y), the upwind scheme dictates that − ∂φ φx = φ(x + 1, y) − φ(x, y) if vx < 0 ≈ − (2) ∂x φ x = φ(x, y) − φ(x − 1, y) if vx > 0 ∇φ |∇φ|2 H = −v · ∇φ = −a · n · ∇φ = −a · · ∇φ = −a · = −a · |∇φ| (3) |∇φ| |∇φ| As you see, we now only need to find the length of the gradient. One way ofdoing this, is using equation 2, but this is not as precise as Godunovs method.This method dictates how to find ( ∂φ 2 ∂φ 2 ∂x ) and ( ∂y ) , but it can not be used tofind ∂φ ∂φ ∂x or ∂y , which is obviously the reason why not to use it in the generalvector field case. . . When ( ∂φ 2 ∂φ 2 ∂x ) and ( ∂y ) are calculated, they can be used to find |∇φ|. Withthis we can find ∂φ ∂t ≈ −a · |∇φ| which then again can be used to find φnew , byusing the Euler method. So how do we calculate ( ∂φ 2 ∂φ 2 ∂x ) and ( ∂y ) ? Godunov dictates that max(max(φ− 2 + 2 ∂φ 2 x , 0) , min(φx , 0) ) if a < 0 ( ) ≈ (4) ∂x max(min(φx , 0) , max(φx , 0)2 ) − 2 + if a > 0 4where φ− + x and φx are defined as in (2). That’s all there’s to it! 1.2 Re-normalisationA signed distance function φ has the property, that its length |φ| is close toone at all time. This, however, is not always the case when we solve level setequations. There is nothing in the methods described above that guaranteesthis. What is needed is a so-called re-normalisation. In our implementation, thisis done by solving the Eikonal Equation ∂φ ∂t = Sign(φ)(1 − |∇φ|) where Sign isa continuous sign function . In our implementation Sign(φ) = √ 2 φ 1 . φ +|∇φ| If you examine this equation, you will notice that it is similar to the equationfor advection in the normal direction. Therefore, the same method can be usedfor solving it! We simply use −Sign(φ) as the speed a, and solve it usingGodunov and Euler. This equation should be solved enough times to ensure that the system isreasonable stabile around the interface. The idea is, that if this is done for all 1 If it was not, we would have no method for solving it 5points, it will give the points just beside the interface a reasonable value. In thenext iteration the next layer will have a reasonable value and so on, and so on. −3 3 All values outside this band are assumed to have a value of ±γ, until theyare close enough for the gamma-band to suck them in. To ensure this we usea so-called safe-tube. The safe-tube is defined as all the points that are not inthe gamma-band, but who do have a neighbour that is. When a point entersthis magical safe-tube, its value is set to ±γ, depending on the sign of its luckyneighbour, who is small enough to get into the gamma-band. The gamma-bandtogether with the safe tube is called the narrow band. Please notice, that this ensures that the value in the point can be used bye.g. the Godunov scheme to calculate the length of the gradient. It might not 2 Hence the name 6be precise, but it is precise enough3 , and after the re-normalisation it will beeven more precise. As you might have guessed, or already know, we only need to re-normaliseas many times as this gamma-band is wide, divided by the maximum step sizein our CFL condition. In our case, we have chosen a γ of three. If we start out with such a gamma-band and a safe-tube, we first solve ourlevel set equation in the gamma-band. When we are done, we re-normalise inthe gamma-band. We can now estimate the values in the safe-band better, andthe values in it is therefore updated. How this is done is described in the nextsection. We now have to rebuild our gamma-band and safe-tube. This can be donein a naive way, and in a smart way. We have obviously chosen the latter, andhow it is done, is described in section 2.3.n 72 Framework Level Set 2.1 Phiφ holds distances to the interface, recall that we only sample in a finite numberof grid points. φ give access to manipulate the value in the individual gridpoints. A φ can be asked to renormalise itself, using the same methods as the narrowband. The specialised versions of φ is described in 3.1. Implementation The distances is held in a 2D array. The only class that usesrenormalize is the ImagePhi. Details about the implementation of renormalizecan be found in the description of the narrow band. 8time step4 , this is done to propagate the changes through the entire γ-band.Since the re-normalisation moves pixels in the γ-band closer to the interface,it is necessary to rebuild the safe tube. This is done by using Manhattan citydistance. Finally the narrow band is asked to rebuild itself. The level set is responsible for doing morphologic operations, opening andclosing, as well as different ways of moving the level set forward in time. 2.2.1 ImplementationThe level set has a pointer to the narrow band and φ. Safe translation Since we cannot make time steps larger than our CFL con-dition, we have to split a long steps into several smaller steps. Opening The idea of opening is to first contract the interface for a certainamount of time, and afterwards expand the interface for the same amount oftime. Opening removes bumps and spikes on the interface.Solver oldSolver = nb.getSolver();Solver normalDirectionSolver = new NormalDirectionSolver(new ContractingSpeedFunction());nb.setSolver(normalDirectionSolver);safeTranslationInTime(d); normalDirectionSolver = new NormalDirectionSolver(new ExpandingSpeedFunction());nb.setSolver(normalDirectionSolver);safeTranslationInTime(d); nb.setSolver(oldSolver); step. However, it works! This is probably because small time steps are followed by small timesteps, and thus the interface is not moving enough for the inaccurate values to be a problem. Instead we should use another CFL condition. 9 Since the narrow band has information about all the interesting pixels inthe level set, computations that involve all pixels are send through the narrowband. 2.3.1 SolveAsks the solver to transform all the pixels in the γ band, one by one. Implementation We iterate through all the pixels in the narrow band andask the solver for the new distance of those pixel with mask 2. All these newdistances are stored in a new φ. Implementation The solver iterates over all pixel in the narrow band andask the solver for the advection of those with mask = 2. The maximum timestep is calculated as: 1 (8) advectionmax · 2 2.3.3 Re-normalisation2.3.4 Rebuild bandsRebuilding the bands is done in two stages: First the γ-band is rebuild, andthen a new safe tube is added. 2.3.5 ImplementationWe have chosen to implement the rebuilding of the narrow band in what wethought was the most intuitive way. By construction of the narrow band, allpixels in the new γ-band are already in the old narrow band. To constructthe new γ-band we simply run through the pixels in the old narrow band andadd those whose updated distance is smaller than γ to the γ-band. The new 10members of the γ-band are all prior members of the safe tube that was movedwithin γ-distance when updating the city distance. To make a new safe tube,we run through the new γ-band and remember all the neighbour pixels that arenot already in the γ-band. Notice that all new pixels in the safe tube are eitherneighbours of pixels from the old safe tube, that entered the γ-band, or pixelsthat just moved out of the γ-band. 2.4 SolverThe solver is responsible for doing operations on a single given pixel. Theseoperations include finding the length of the gradient, finding the advection andsolving the level set equation. We have done two types of solvers; a normal direction solver and a vectorfield solver. They have the same functionality, but the computations differ quitea bit as described in 1.1. The vector field solver depend on actually finding thethe gradient, whereas the normal direction solver only uses the length of thegradient. 2.4.3 AdvectionThe solver can tell us how far a a pixel will move if t = 1 is used. 11it by t. Updating a pixel is therefore done in the following way: −−−−−−−→ −−−−→ φnew (x, y) = φold (x, y) − t · ∇φold (x, y) • V (x, y) (10) Implementation The following three lines are all it takes to find the newdistance in a pixel (x, y).float[] grad = gradient(phi, x, y);float[] v = V.getVector(x, y, phi);return (phi.get(x, y) - t*(grad[0]*v[0] + grad[1]*v[1])); 123 ApplicationsThere are many different applications of the level set method. In this part ofthe paper, we will briefly describe some of the more usable methods and ourimplementation of them in our framework. 3.1.1 CircleThe simplest of forms to represent p in a level set. As you very well know, a point(x1 , y1 ) has the distance (x0 − x1 )2 + (y0 − y1 )2 to the point (x0 , y0 ), and ifwe define a circle with centre p in (x0 , y0 ) and with radius r, the distance from apoint (x1 , y1 ) to the circle is (x0 − x1 )2 + (y0 − y1 )2 − r. Please notice, thatthis means, that the points inside the circle have a negative distance, as wedesire. 13 c −c 14} The code for reinitialisation is stored in Phi, as it might come in handy inother situations. The most important thing to notice is, that the reinitialisationuses the sign in the grid to calculate the norm using Godunov. It is worth noticing, that one should rebuild the narrow band after combiningthe functions. It is also worth noticing, that the φs do not have to be accurateeverywhere. It is a sufficient condition, that they are accurate around theirnarrow bands. Remember, that all the values outside the band are assumedto have numerical values greater than γ, and they are clamped to such a valueupon entering the safe band anyway. 3.2.1 ImplementationThe implementations are made as methods in our Phi super class. These meth-ods take a Phi object, which it uses to change the object on which the methodis invoked. As an example, consider the following code implementing the union of twoPhi objects.public void union(Phi phi){ for(int x = 0; x < getWidth(); x++) for(int y = 0; y < getHeight(); y++) if(get(x, y) > phi.get(x, y)) grid[x][y] = phi.get(x, y);} Whenever these methods are called, one should always remember to rebuildthe narrow band! 153.3 Simple speed functionsAs previous mentioned, speed functions, used to advect an interface in the nor-mal direction, can depend on any number of parameters. There are, however,two extremely simple speed functions. These are the speed function for ex-panding any given interface, and the speed function for collapsing any giveninterface. The expanding speed function is simply 1 at all time, in any point. This willgive us a constant expansion along the normals. Similarly the collapsing speed function is simply −1 at all time, in all points. 3.3.1 ImplementationThe implementation is very simple. Here is the code for getting the speed in apoint when we want to expand the interfacepublic float getSpeed(int x, int y, Phi phi) { return 1; } 3.4 Morphing A very cool effect in computer graphics is the morphing of objects from oneshape to another. This can very easy be achieved in level sets, using advectionin the normal direction. If we have two overlapping Phi objects, we can definea speed function from the primer to the latter by ∂φ = (φ − φtarget · |∇φ|) (12) ∂t It is worth noticing we have changed the sign, as compared to [KMJ], thereason being we have a negative sign inside the interface, and a positive signoutside. 163.4.1 ImplementationMorphing is just implemented as a fancy speed function. This speed functionneeds to know φtarget at all points. Please notice that φtarget has to stay asigned distance function in all points at all time. The speed depends on φtarget , and the φ we are moving. target is thereforegiven at the construction time of the object. 3.5.1 ImplementationThe idea is to translate the interface forward in time using one of the two simplespeed functions and advection in the normal direction. How far into time weare going to translate it, differs from data set to data set, but we can not alwaysmake the translations in big steps. Since we are restricted by a CFL condition,we must take many small steps. This is easily implemented. We have chosen to implement it in our Level Setclass. 17public void safeTranslationInTime(float time){ while(time > 0) { float maxTimeStep = nb.maxTimeStep(phi); step(Math.min(time, maxTimeStep)); time -= maxTimeStep; }} This translation method can then be used to perform a morphological open-ing on the surface. This is also implemented in the Level Set class. 18 This image can then be used to find the direction to the nearest edge,just by finding the derivatives in the image. These derivatives will point fromthe nearest edge to the point we are standing in. If we negate such a derivative,we have a vector field pointing towards the edges. We can use this vector field inour advection by vector field scheme. We simply create a figure that is smallerthan the shape in the image, and place the shape inside the shape. We thenadvect the figure by the vector field scheme, thus growing outwards until it hitthe edges, where the vector field is zero. The ingenious thing is, that aroundthe holes in the shape, the derivatives will point in opposite directions, and pullthe interface out into a straight line. Please consult figure 8 for a clarification. This has the effect, that the derivatives will be very close to zero vectors,and the interface stops moving, filling the gaps with straight lines. Brilliant, isit not? Another strategy is creating a large interface, that you are absolutely surecovers the entire shape, and collapse it. The result is the same, unless of course,there a several disjoint shapes in you image. 3.6.1 ImplementationTo get rid of the noise, one would typically use an image filter. In this projectwe have used a Gaussian filter as described in ([Ima02]) to clear out the noise.This filter simply makes a weighted approximation of the value in each pixel,by looking at their neighbourhood. The pixel value in each point is weightedusing a kernel of size 2 · k + 1 × 2 · k + 1 where k is chosen in advance. 1 (i−k−1)2 +(j−k−1)2 Gi,j = 2 ·e 2·σ2 (13) 2·σ ·πand the new value in each point (x, y) is simply X Gi,j · Ix−i+k,y−j+k (14) 19where Ix,y is the value in the original image. As mentioned, the next step is to find the edges of the shape(s) in the image. This is done in a series of steps, as described by Michael Bang Nielsen in amail5 : • Compute an image, A, where every pixel is the norm of the gradient in the smoothed image. The derivative of x in a pixel is defined as the value in the pixel to the left minus the value in the pixel to the right, divided by 2. The derivative of y is found in a similar manner. • Compute another image, B, where every pixel is the gradient at the cor- responding position in image A dotted with the normal from the corre- sponding position in the image. • Compute an image, C, where every pixel is the numerical value of the gradient in the image dotted with the normal. • Now you have to look for zero-crossings in image B. Basically a pixel is a zero crossing if any of its neighbouring pixels have a different sign, or if the value of the pixel itself is zero. A pixel is classified as an edge if it is a zero-crossing and if the value at the corresponding pixel in image C is higher than some threshold. We have chosen 107 as our threshold.Please notice that we need the integer value in the pixels. The only question that remains is, how do we compute the distance to thenearest edge in every point? We have chosen to do it the easy way, using citydistance. We create a new image where all points on edges gets the value 0,and all other points get the highest possible value, that is, the distance fromthe top left corner to the bottom right corner. We then update all the distancesusing the Manhattan city distance scheme. We first update the values from thetop left corner down to the bottom left. We then update them the other way.This guarantees, that all the distances are a correct approximation, in the citydistance scheme. Next we just use these distances to compute a vector field. The implemen-tation is straight forward. Please remember, that one has to negate the vectorfield, so that is does not point away from the edges, but onto them.public float[] getVector(int x, int y, Phi phi) { float dxG = (D[x + 1][y] - D[x - 1][y]) / 2; float dyG = (D[x][y + 1] - D[x][y - 1]) / 2; float[] v = new float[2]; v[0] = -dxG; v[1] = -dyG; return v;} . . . easy and simple. 5 The following is taken directly from that mail, and edited to explain the tricky parts 20References[ea99] Peng et. al. A pde-based fast local level set method. Journal of Com- putational Physics 155, 1999.[Ima02] Computer Vision - A modern Approach. Prentice Hall, 2002.[KMJ] Ross T. Whitaker Sean Mauch Ken Museth, David E. Breen and David Johnson. Algorithms for interactive editing of level set models. 21
https://www.scribd.com/document/49111260/LevelSet
CC-MAIN-2019-43
refinedweb
3,445
63.39
pypet 0.1b.4 A toolkit for numerical simulations to allow easy parameter exploration and storage of results. pypet The new python parameter exploration toolkit: pypet manages exploration of the parameter space and data storage into HDF5 files for you. IMPORTANT! The program is currently under development, please keep that in mind and use it very carefully. Before publishing the official 0.1.0 release I will integrate pypet first in my own research project. Thus, I have a more profound testing environment than only using unittests. Accordingly, you still have to deal with the naming 0.1b.X for a little while. However, unless it is really, really, really necessary I do not plan to change the API anymore. So feel free to use this beta version and feel free to give feedback, suggestions, and report bugs. Use github () issues or write to the pypet Google Group () :-) Thanks! Requirements Python 2.6 or 2.7 - tables >= 2.3.1 - pandas >= 0.12.0 - numpy >= 1.6.1 - scipy >= 0.9.0 For git integration you additionally need - GitPython >= 0.3.1 To utilize the cap feature for multiprocessing you need - psutil >= 2.0.0 If you use Python 2.6 you also need - ordereddict >= 1.1 What is pypet all about? Whenever you do numerical simulations in science, you come across two major challenges. First, you need some way to save your data. Secondly, you extensively explore the parameter space. In order to accomplish both you write some hacky I/O functionality to get it done the quick and dirty way. This means storing stuff into text files, as MATLAB m-files, or whatever comes in handy. After a while and many simulations later, you want to look back at some of your very first results. But because of unforeseen circumstances, you changed a lot of your code. As a consequence, you can no longer use your old data, but you need to write a hacky converter to format your previous results to your new needs. The more complexity you add to your simulations, the worse it gets, and you spend way too much time formatting your data than doing science. Indeed, this was a situation I was confronted with pretty soon at the beginning of my PhD. So this project was born. I wanted to tackle the I/O problems more generally and produce code that was not specific to my current simulations, but I could also use for future scientific projects right out of the box. The python parameter exploration toolkit (pypet) provides a framework to define parameters that you need to run your simulations. You can actively explore these by following a trajectory through the space spanned by the parameters. And finally, you can get your results together and store everything appropriately to disk. The storage format of choice is HDF5 () via PyTables (). Package Organization This project encompasses these core modules: - The pypet.environment module for handling the running of simulations - The pypet.trajectory module for managing the parameters and results, and providing a way to explore your parameter space. Somewhat related is also the pypet.naturalnaming module, that provides functionality to access and put data into the trajectory. - The pypet.parameters module including containers for parameters and results - The pypet.storageservice for saving your data to disk Install Simply install via pip install –pre pypet (–pre since the current version is still beta) Or Package release can also be found on. Download, unpack and python setup.py install it. pypet has been tested for python 2.6 and python 2.7 for Linux using Travis-CI (). However, so far there was only limited testing under Windows. In principle, pypet should work for Windows out of the box if you have installed all prerequisites (pytables, pandas, scipy, numpy). Yet, installing with pip is not possible. You have to download the tar file from and unzip it (using WinRaR, 7zip, etc. You might need to unpack it twice, first the tar.gz file and then the remaining tar file in the subfolder). Next, open a windows terminal and navigate to your unpacked pypet files to the folder containing the setup.py file. As above run from the terminal python setup.py install. By the way, the source code is available at. Documentation and Support Documentation can be found on. There is a Google Groups mailing list for support: If you have any further questions feel free to contact me at robert.meyer (at) ni.tu-berlin.de. Main quantities and monitors () Easily extendable to other data formats! Exploration of the parameter space of your simulations Merging of trajectories residing in the same space Support for multiprocessing, pypet can run your simulations in parallel Dynamic Loading, load only the parts of your data you currently need Resume a crashed or halted simulation Annotate your parameters, results and groups Git Integration, let pypet make automatic commits of your codebase Quick Working Example The best way to show how stuff works is by giving examples. I will start right away with a very simple code snippet. Well, what we have in mind is some sort of numerical simulation. For now we will keep it simple, let’s say we need to simulate the multiplication of 2 values, i.e. z=x*y. We have two objectives, a) we want to store results of this simulation z and b) we want to explore the parameter space and try different values of x and y. Let’s take a look at the snippet at once: from pypet.environment import Environment from pypet.utils.explore import cartesian_product!') # Create an environment that handles running our simulation env = Environment(trajectory='Multiplication',filename='./HDF/example_01.hdf5', file_title='Example_01', log_folder='./LOGS/') # Get the trajectory from the environment traj = env.v_trajectory # Add both parameters traj.f_add_parameter('x', 1.0, comment='Im the first dimension!') traj.f_add_parameter('y', 1.0, comment='Im the second dimension!') # Explore the parameters with a cartesian product traj.f_explore(cartesian_product({'x':[1.0,2.0,3.0,4.0], 'y':[6.0,7.0,8.0]})) # Run the simulation with all parameter combinations env.f_run(multiply) And now let’s go through it one by one. At first we have a job to do, that is multiplying two values:!') This is our simulation function multiply. The function uses a so called trajectory container which manages our parameters. We can access the parameters simply by natural naming, as seen above via traj.x and traj.y. The value of z is simply added as a result to the traj object. After the definition of the job that we want to simulate, we create an environment which will run the simulation. # Create an environment that handles running our simulation env = Environment(trajectory='Multiplication',filename='./HDF/example_01.hdf5', file_title='Example_01', log_folder='./LOGS/', comment = 'I am the first example!') The environment uses some parameters here, that is the name of the new trajectory, a filename to store the trajectory into, the title of the file, a folder for the log files, and a comment that is added to the trajectory. There are more options available like the number of processors for multiprocessing or how verbose the final HDF5 file is supposed to be. Check out the documentation () if you want to know more. The environment will automatically generate a trajectory for us which we can access via: # Get the trajectory from the environment traj = env.v_trajectory Now we need to populate our trajectory with our parameters. They are added with the default values of x=y=1.0. # Add both parameters traj.f_add_parameter('x', 1.0, comment='Im the first dimension!') traj.f_add_parameter('y', 1.0, comment='Im the second dimension!') Well, calculating 1.0 * 1.0 is quite boring, we want to figure out more products, that is the results of the cartesian product set {1.0,2.0,3.0,4.0} x {6.0,7.0,8.0}. Therefore, we use f_explore in combination with the builder function cartesian_product. # Explore the parameters with a cartesian product traj.f_explore(cartesian_product({'x':[1.0,2.0,3.0,4.0], 'y':[6.0,7.0,8.0]})) Finally, we need to tell the environment to run our job multiply with all parameter combinations. # Run the simulation with all parameter combinations env.f_run(multiply) And that’s it. The environment will evoke the function multiply now 12 times with all parameter combinations. Every time it will pass a traj container with another one of these 12 combinations of different x and y values to calculate the value of z. Moreover, the environment and the storage service will have taken care about the storage of our trajectory - including the results we have computed - into an HDF5 file. So have fun using this tool! - Cheers, - Robert Miscellaneous Acknowledgements Thanks to Robert Pröpper and Philipp Meier for answering all my python questions You might wanna check out their SpykeViewer () tool for visualization of MEA recordings and NEO () data Thanks to Owen Mackwood for his SNEP toolbox which provided the initial ideas for this project Thanks to the BCCN Berlin (), the Research Training Group GRK 1589/1, and the Neural Information Processing Group () for support Tests Tests can be found in pypet/tests. Note that they involve heavy file I/O and you need privileges to write files to a temporary folder. The tests suite will make use of the tempfile.gettempdir() function to create such a temporary folder. You can run all tests with $ python all_tests.py which can also be found under pypet/tests. You can pass additional arguments as $ python all_tests.py -k –folder=myfolder/ with -k to keep the HDF5 files created by the tests (if you want to inspect them, otherwise they will be deleted after the completed tests), and –folder= to specify a folder where to store the HDF5 files instead of the temporary one. If the folder cannot be created the program defaults to tempfile.gettempdir(). Running all tests can take up to 15 minutes. The test suite encompasses more than 300 tests (including the BRIAN based tests) and has a code coverage of more than 90%! License BSD, please read LICENSE file. Legal Notice pypet was created by Robert Meyer at the Neural Information Processing Group (TU Berlin), supported by the Research Training Group GRK 1589/1. robert.meyer (at) ni.tu-berlin.de Marchstr. 23 MAR 5.046 D-10587 Berlin - Author: Robert Meyer - Documentation: pypet package documentation - License: BSD - Categories - Development Status :: 4 - Beta - Intended Audience :: Science/Research - License :: OSI Approved :: BSD License - Natural Language :: English - Operating System :: OS Independent - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 2 :: Only - Topic :: Scientific/Engineering - Topic :: Utilities - Package Index Owner: SmokinCaterpillar - DOAP record: pypet-0.1b.4.xml
https://pypi.python.org/pypi/pypet/0.1b.4
CC-MAIN-2017-04
refinedweb
1,799
50.12
setSuperClass questionhuiben Jun 26, 2003 4:17 PM I try to alter the super class of a class, and this replace all occurance of the old super class, including reference to the old super class methods. But I don't want this, I want the reference to older super class method remain, while just change the super class name (i.e. change the 'extends') how can we do this? thanks ben 1. Re: setSuperClass questionShigeru Chiba Jun 30, 2003 9:35 AM (in response to huiben) The reason why I don't add a method for doing that is that it lets the users wrongly change the super class to break the consistency. Why do you want to do that? I would like to know if there is a real example. (If yes, I want to add a method for doing that.) 2. Re: setSuperClass questionhuiben Jul 8, 2003 9:55 AM (in response to huiben) consider the following 4 classes: public class A { // root class // some methods } public class B { public static void method(A obj) { // do something with object of class A } } public class C extends A { public void method2() { B.method(this); // param is super class A } } public class D extends A { } my situation is to make C extends D instead of A, i.e. public class C extends D { // and D extends A, so C also extends A } since D also extends A, so C is still a subclass of A, just that D is inserted in between. using Javassist setSuperClass method, this will break the invocation of B.method, because B.method parameter signature is class A, but setSuperClass change it to class D. as a result, I got method not found exception. i.e. it tries to look for B.method(D) instead of B.method(A). I think setSuperClass blindly replace all occurance of A with D is the root of this problem. It does not consider that there are external dependency with A (in my case, B.method() is depend on A, not D) that's why I need a different way to setSuperClass. what do you think chiba? thanks ben 3. Re: setSuperClass questionShigeru Chiba Jul 9, 2003 3:02 AM (in response to huiben) OK, I understand this issue. Give me time. 4. Re: setSuperClass questionShigeru Chiba Aug 23, 2003 1:40 AM (in response to huiben) Sorry for my too long silence. I think Ben is right so I made a decision to change the semantics of setSuperclass() so that setSuperclass() only changes the extend clause and constructors. Note: constructors may call the super's constructor. If the super class is changed, the constructor body must be instrumented.
https://developer.jboss.org/thread/93803
CC-MAIN-2018-39
refinedweb
449
72.87
Build MyTested.AspNetCore.Mvc is a unit testing library providing an easy fluent interface to test the ASP.NET Core MVC framework. It is testing framework agnostic so that you can combine it with a test runner of your choice (e.g. xUnit, NUnit, etc.). It is strongly advised to start with the tutorial in order to get familiar with MyTested.AspNetCore.Mvc. Additionally, you may see the testing guide or the API reference for a full list of available features. MyTested.AspNetCore.Mvc is 100% covered by more than 1800 unit tests and should work correctly. Almost all items in the issues page are expected future features and enhancements.asp-net-core mvc fluent-testing assertion-methods assertion-library asp-net-core-mvc test-framework This is fork of Troy's project PagedList(). The main difference is that X.PagedList is a portable assembly. It means you can use it not only in Web projects but also in Winforms, WPF, Window Phone, Silverlight and other .NET projects. PagedList is a library that enables you to easily take an IEnumerable/IQueryable, chop it up into "pages", and grab a specific "page" by an index. PagedList.Mvc allows you to take that "page" and display a pager control that has links like "Previous", "Next", etc.net-core pagination asp-net-core asp-net-mvc paginator asp-net-core-mvc This package gives you typed expression based routing and link generation in a ASP.NET Core MVC web application. Currently working with version 1.1.0. You can install this library using NuGet into your web project. There is no need to add any namespace usings since the package uses the default ones to add extension methods.asp-net-core asp-net-core-mvc fluent-extensions strongly-typed routing azure-cosmos-db web-api asp-net-core-mvc asp-net-core-web-api A ⚗️ Sieve is a simple, clean, and extensible framework for .NET Core that adds sorting, filtering, and pagination functionality out of the box. Most common use case would be for serving ASP.NET Core GET queries. In this example, consider an app with a Post entity. We'll use Sieve to add sorting, filtering, and pagination capabilities when GET-ing all available posts.sort filter pagination aspnetcore asp-net-core-mvc netcore2 Code sample detailing how to create custom roles in ASP.NET core on startup and role-based authentication using role checks and policy based checks. the dotnet run command simultaneously re-compiles and runs the kestrel-server.asp-net-core aspnetcore asp-net asp-net-core-mvc role-based-access-control role-manager authorization When I read about Electron.NET (a variant of Electron with C# and dotnet core for the "server" process), I was hooked but wanted a React and Typescript front-end sample. That quest led to creating this repo which works on Windows, macOS and Linux operating systems. You'll need Node.js (v.8.x) and .NET Core SDK installed on your computer in order to start or build this app. I personally like to use VS Code when working on the HTML/JS bits and Visual Studio when working on the C# code (they play nice together), but that's just a personal preference.electron electron.net react typescript mobx c-sharp dotnet-core dotnet-standard asp-net-core asp-net-core-mvc A .
https://www.findbestopensource.com/tagged/asp-net-core-mvc
CC-MAIN-2019-51
refinedweb
562
57.87
JustLinux Forums > Community Help: Check the Help Files, then come here to ask! > Programming/Scripts > PCI shared memory - unresolved symbol __ioremap PDA Click to See Complete Forum and Search --> : PCI shared memory - unresolved symbol __ioremap Nick Vun 04-14-2001, 11:16 AM I wrote a module to scan the PCI display controller memory using ioremap(). No problem in compiling the module. But when I insmod the module, an error message appears - "unresolved symbol __ioremap()". What is the problem ? Thanks for any help. Nick Qubit 04-14-2001, 02:29 PM Give us some more information... 1) Wild guess: versioning? (It's allways versioning :)) 2) Wild guess, slightly more educated though: are you actually using __ioremap() or ioremap()? Be sure to use the non-underscore variant, as the underscore variant is not exported. Nick Vun 04-14-2001, 10:15 PM I used ioremap() in the modules. I also suspect it is versioning, so I do a "make mrproper" etc to rebuild the kernel, but the problem remain. My system was originally installed with RH 6.* (2.2.14), which I upgraded to RH7.0 (2.2.16), but I have since then upgraded the kernel to 2.2.18 and include the lpp patch. Can it be the library glib that I used ? Thanks. Qubit 04-15-2001, 03:45 AM Do a "cat /proc/ksyms | grep ioremap" and see what happens. Can it be the library glib that I used ? I don't think so, since the only "library" your module will use is the kernel itself :) My guess is that this is more of a technical problem, so check your kernel config: do you have a valid System.map in /boot? Nick Vun 04-15-2001, 08:31 AM Cat of /proc/ksyms shows c010fa4c __ioremap_R9eac042a I have my System.map symbolic link to my actual System.map_2.2.18. Cat of System.map shows c010fa4c T __ioremap c01f8974 ? __kstrtab___ioremap c01fec78 ? __ksymtab___ioremap When I compiled my modules, printk is indicated (as warning message during compilation) to correctly link to the printk_R7**** as shown in the /proc/ksyms. A few other kernel functions like pci_read_** are all indicated to link as that shown in the /proc/ksyms I noticed that all these successfully linked kernel functions do not have the __ associated with the c*** T __ioremap in the System.map file The header files I included in the module are <linux/kernel.h> <linux/module.h> <asm/io.h> <linux/pci.h> Qubit 04-15-2001, 02:09 PM Man, that's really strange. The only thing there's left is to turn off versioning in the kernel. I once had similar problems (with printk) that went away when I turned off versioning. I really think this is a technical problem though, because you're not supposed to use the __-functions. Now, ioremap just calls __ioremap (which is also exported, contrary to what I said before ;)), __ioremap is implemented in arch/i386/mm/ioremap.c, and exported somewhere else (the file has 'ksyms' in it, that's all I remember). So, there don't seem to be any strange things on behalf of the kernel, and I suppose you did everything right (right includes), so the problem must be (as the error indicates) during the linking. Sorry I can't help you there. Do you mind turning off versioning and recompiling? [ 15 April 2001: Message edited by: Glaurung ] pinoy 04-15-2001, 04:55 PM Did you compile with optimization on? ie -O Nick Vun 04-16-2001, 12:39 PM Hi - I got the insmod working with ioremap (i.e. able to insmod) For some reason, I have included the option -DMODVERSIONS in my Makefile. It is working fine for the other modules that I have written so far. By removing this option, the module can be inserted with no error message for the __ioremap. I don't know why it is so, and I also can't remember why I have included -DMODVERSIONS option on the first place now ;-) Another thing, according to gcc manual, I should have used -O3 in order to use inline function. But using -O3 and -O semms to have no difference in my case. (Earlier I also tried turning off the versioning and it works as expected. But I was curious why it doesn't work with versioning, and turn it back on again) Thanks guys for your suggestions ! (but still wondering what really happened) Qubit 04-16-2001, 01:34 PM It's cool to see that you made your module work :) Aside: if you don't want to have anymore problems with defining MODVERSIONS, do #ifdef CONFIG_MODVERSIONS #define MODVERSIONS #include <linux/versions.h> #endif It might also be linux/version.h, I don't know for sure. justlinux.com
http://justlinux.com/forum/archive/index.php/t-45629.html
crawl-003
refinedweb
802
73.47
Opened 6 years ago Closed 4 years ago Last modified 4 years ago #8758 closed (fixed) get_tag_uri in /django/utils/feedgenerator.py breaks with port numbers Description The following function: def get_tag_uri(url, date): "Creates a TagURI. See" tag = re.sub('^http://', '', url) if date is not None: tag = re.sub('/', ',%s:/' % date.strftime('%Y-%m-%d'), tag, 1) tag = re.sub('#', '/', tag) return u'tag:' + tag }} - ... breaks for domain names with a port number, such as as this produces the following TAG value: {{{ tag:example.org:8080,2007-09-21:/ }}} From and you can see that the TAG URI should not contain the port number. The following patch should be able to extract the domain name from the link: {{{ - tag = re.sub('^http://', '', url) + tag = str(urllib.splitport(urllib.splithost(urllib.splittype(url)[1])[0])[0]) }}} Attachments (2) Change History (8) comment:1 Changed 6 years ago by Daniel Pope <dan@…> - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 5 years ago by arthurk - Owner changed from nobody to arthurk - Status changed from new to assigned Changed 5 years ago by arthurk Changed 5 years ago by arthurk regression test comment:3 Changed 5 years ago by arthurk - Version changed from SVN to 1.0 I added a diff and a unit test for a new get_tag_uri method which relies on urlparse instead of going through some regular expressions. Please review. comment:4 Changed 5 years ago by arthurk - Triage Stage changed from Unreviewed to Accepted comment:5 Changed 4 years ago by russellm - Resolution set to fixed - Status changed from assigned to closed comment:6 Changed 4 years ago by russellm Note: See TracTickets for help on using tickets. Why not use urlparse.urlparse(url).hostname ?
https://code.djangoproject.com/ticket/8758
CC-MAIN-2014-10
refinedweb
293
62.88
Interaction Terms in Python Vanilla OLS Say we’ve got a dataset from warnings import filterwarnings filterwarnings('ignore') from yellowbrick.datasets import load_bikeshare X, y = load_bikeshare() Where we measure the number of DC-area bikes rented y.head() 0 16 1 40 2 32 3 13 4 1 Name: riders, dtype: int64 Based on a number of features X.head() And just shoving everything into a Logistic Regression seems to work… alright from statsmodels.api import OLS import statsmodels.api as sm X_const = sm.add_constant(X) model = OLS(y, X_const).fit() model.summary() Warnings: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. But at the same time, have good reason to believe that there’s some colinearity/interaction at play with our features. from yellowbrick.features import Rank2D visualizer = Rank2D(algorithm='pearson', size=(600, 500)) visualizer.fit_transform(X) visualizer.poof(); C:\Users\Nick\Anaconda3\lib\site-packages\yellowbrick\features\rankd.py:215: YellowbrickWarning: RankD plots may be clipped when using matplotlib v3.1.1, upgrade to matplotlib v3.1.2 or later to fix the plots. warnings.warn(msg, YellowbrickWarning) Interaction Terms From here, a good data scientist will take the time to do exploratory analysis and thoughtful feature engineering– this is the “More Art than Science” adage you hear so often. But we’re trying to be home by 5, so how do we cram everything in and see what shakes out? Getting Values Thankfully, the PolynomialFeatures object in sklearn has us mostly-covered. It’s originally used to generate sequences of (b_i1 * x_i) + (b_i2 * x_i^2) + ... for each feature in X, taking us from n features to 2^n features (in the case of PolynomialFeatures(degree=2), anyhow). We’re not interested in polynomials, per se, but if you squint, the same itertools magic™ that powers the backend of this can also be used to provide all pairwise feature combinations, with minimal rewriting. They provide this, ez pz, with the interaction_only flag. And so we go from X.shape (17379, 12) To an expected $\frac{p * (p - 1)}{2}$ pairs, plus our original p features, plus a bias term p = len(X.columns) (p * (p-1)) / 2 + p + 1 79.0 Coolio from sklearn.preprocessing import PolynomialFeatures interaction = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False) X_inter = interaction.fit_transform(X) X_inter_const = sm.add_constant(X_inter) X_inter_const.shape (17379, 79) Now we brazenly throw it into a new model, and… oh. A lot of features called x model = OLS(y, X. Feature Names? The interaction object keeps track of the names of our feature combinations… sort of print(interaction.get_feature_names()) ['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11', 'x0 x1', 'x0 x2', 'x0 x3', 'x0 x4', 'x0 x5', 'x0 x6', 'x0 x7', 'x0 x8', 'x0 x9', 'x0 x10', 'x0 x11', 'x1 x2', 'x1 x3', 'x1 x4', 'x1 x5', 'x1 x6', 'x1 x7', 'x1 x8', 'x1 x9', 'x1 x10', 'x1 x11', 'x2 x3', 'x2 x4', 'x2 x5', 'x2 x6', 'x2 x7', 'x2 x8', 'x2 x9', 'x2 x10', 'x2 x11', 'x3 x4', 'x3 x5', 'x3 x6', 'x3 x7', 'x3 x8', 'x3 x9', 'x3 x10', 'x3 x11', 'x4 x5', 'x4 x6', 'x4 x7', 'x4 x8', 'x4 x9', 'x4 x10', 'x4 x11', 'x5 x6', 'x5 x7', 'x5 x8', 'x5 x9', 'x5 x10', 'x5 x11', 'x6 x7', 'x6 x8', 'x6 x9', 'x6 x10', 'x6 x11', 'x7 x8', 'x7 x9', 'x7 x10', 'x7 x11', 'x8 x9', 'x8 x10', 'x8 x11', 'x9 x10', 'x9 x11', 'x10 x11'] Assuming that a bevy of xi xjs aren’t much more useful than the output of model.summary() we can do some hacky, Python nonsense to decode a bit. For starters, we want to create a dictionary that maps xi to its corresponding feature name in our dataset. We’ll use the itertools.count() function, as it’s basically enumerate, but plays better with generator expressions. from itertools import count x_to_feature = dict(zip(('x{}'.format(i) for i in count()), X.columns)) x_to_feature {'x0': 'season', 'x1': 'year', 'x2': 'month', 'x3': 'hour', 'x4': 'holiday', 'x5': 'weekday', 'x6': 'workingday', 'x7': 'weather', 'x8': 'temp', 'x9': 'feelslike', 'x10': 'humidity', 'x11': 'windspeed'} Next, you know it’s Sound Data Science™ when we break out import re Finally, this little diddy goes through and makes the appropriate substitutions for xi to their respective feature names, then replaces spaces with underscores so pandas references isn’t such a chore # necessary so `x11` gets a chance to swap before # before `x1` leaves us with "season1" where we wanted # "windspeed" feature_keys = list(x_to_feature.keys())[::-1] features = [] for feature in interaction.get_feature_names(): for key in feature_keys: feature_name = x_to_feature[key] feature = re.sub(key, feature_name, feature) feature = re.sub(' ', '_', feature) features.append(feature) Then we’ll slap these feature names onto our big ol’ dataset import pandas as pd import statsmodels.api as sm X_all_inter = pd.DataFrame(X_inter, columns=features) X_all_inter_const = sm.add_constant(X_all_inter) And refit model = OLS(y, X_all. And that’s Data Science! from IPython.display import Image Image('images/we_did_it.jpg')
https://napsterinblue.github.io/notes/machine_learning/regression/interaction_terms/
CC-MAIN-2021-04
refinedweb
833
55.64
Cheap Promotional Gifts for Airline Company Travel Agency Customized Printed Hard Plastic PVC Suitcase Tags US $0.3-0.4 / Piece 1000 Pieces (Min. Order) Guangzhou Panyu Zhongcun Jiashang Crafts Factory Germany company and travel agent 863-865MHZ audio system tour guide, Long working distance outdoor wireless tour guide system US $24-27 / Piece 1 Piece (Min. Order) SZ Wise Unite System Technology Co., Ltd. China Promotional gifts Sourcing Agent, Drinkware Buying Purchase Agency, Barware Merchandising buyer office US $1-100 / Piece 1 Unit (Min. Order) Shanghai Star Industry Co., Ltd. Sunon makro japanese office furniture officetable prices for travel agency US $181-286 / Set 1 Set (Min. Order) Foshan Esun Furniture Company Limited Long Custom Promotional Luggage Tag For Travel Agency US $0.34-0.44 / Piece 3000 Pieces (Min. Order) Zhejiang Daijun Crafts Co., Ltd. Opal Infotech Experienced in Providing Professional Travel & Tourism Website Designs for your Agency US $450-3000 / Piece 1 Piece (Min. Order) OPAL INFOTECH Customized personalised PVC/Plastic luggage membership card for Airlines,Travel Agency with pvc/metal strap US $0.05-0.35 / Pieces 500 Pieces (Min. Order) Shenzhen Jing Ka Technology Company Limited Promotional gifts custom company logo soft pvc fridge magnet for travel agency US $0.7-0.85 / Piece 500 Pieces (Min. Order) Dongguan Box Gifts Co., Ltd. Luggage Wrapping Machine/airport luggage wrapping machine for travel agency US $2000-5000 / Set 1 Set (Min. Order) Shandong Dyehome Intelligent Equipment Co., Ltd. 46 inch information lcd android Kiosks 1080P with 6 point IR touch for travel, agencies, pharmacy. Department store, Banks, US $1-5000 / Set 1 Set (Min. Order) Shenzhen Usenda Digital Technology Limited Company Bangladesh Mapower Recruiting Agencies US $500-800 / Unit 20 Units (Min. Order) DHAKA OVERSEAS & TRAVELS Responsive Website Design and Development for Travel Agency US $300-1500 / Unit 1 Unit (Min. Order) GALAGALI MULTIMEDIA china direct sales custom zinc alloy map lapel pin for travel agency US $0.29-0.46 / Pieces 10 Pieces (Min. Order) Zhongshan Senni Gifts Co., Ltd. Nepal Travel, Nepal Tour, Tour Company in Nepal, Nepal Travel Agency US $100-2000 / Piece 1 Piece (Min. Order) WELCOME NEPAL TREKS PVT.LTD. Experienced Taobao/Tmall/1688 buying agent from China Paypal Available From China to worldwide US $1-99 / Set 1 Set (Min. Order) Guangzhou Tanndy International Trading Co., Ltd. Back pack, School backpack, travel backpack Vietnam Buying Agent, Vietnam sourcing services US $5.0-5.0 / Bags 6000 Bags (Min. Order) MEKONG DELTA IMPORT EXPORT COMPANY LIMITED Professional international commodity city looking for chinese agent US $50-100 / Piece 1 Piece (Min. Order) Guangzhou Legotta Plastic Products Co., Ltd. Guangzhou China Reliable Air Ticket Travel Agents With Low Commission Rate US $0.1-1 / Carton 1 Carton (Min. Order) Guangzhou Zokea Clothing Co., Ltd. professional realiable export yiwu agent US $1-1.5 / Piece 15000 Pieces (Min. Order) Yiwu Muhui Imp&Exp Co., Ltd. YZJN Buying agent vacuum travel bags Purchasing agent inspection factory service US $10-50 / Case 1 Case (Min. Order) Xuchang YIZHIJINNUO Trade Co., Ltd. Yiwu Map travel agent china export market Import Company US $100-500 / Cubic Meter 20 Cubic Meters (Min. Order) ZheJiang SUNCLOSE Technology Co.,Ltd. 2014 New Products On Market That Is 8600mAh Travel Charger For Smartphone And Iphone And Samsung US $16-17 / Piece 300 Pieces (Min. Order) Shenzhen Puretek Electronics Co., Limited Joyroom company looking for distributor or agent 2018 hot seller universal 2.1A portable single usb travel charger US standard US $0.95-2.05 / Piece 20 Pieces (Min. Order) Shenzhen Nito Power Source Technology Co., Limited 14oz custom takeaway ceramic coffee mug with silicone sleeve and silicone cover US $0.6-1.5 / Piece 2000 Pieces (Min. Order) Liling Longhui Ceramic Co., Ltd. Laundry detergent Sheets,nano technology apparel detergent US $0.01-0.02 / Piece 100000 Pieces (Min. Order) Shenzhen Yinglian Huitong Technology Company Ltd. Consultation. Document preparation for invitations to EU, Schengen, residence permit, company establishment etc "Smart Business Agency" 0.0% High quality aluminum die cast mini travel rolling suitcase luggage case China sourcing services US $13.9-13.9 / Pieces 2 Pieces (Min. Order) Shenzhen Haiyi E-Commerce Logistics Co., Ltd. Corporate Logo Soft PVC Rubber Luggage Tag Travel Agency Gifts Member Gifts Bag Tags US $0.35-0.55 / Piece 100 Pieces (Min. Order) Asny Craft Factory Travel name pvc business card size luggage tag, airlines luggage tag hard plastic credit card size US $0.001-0.004 / Piece 1 Piece (Min. Order) Shenzhen Sanben Machinery Company Limited Namibia hunting and shuttle and tours serivices/package/agency car hire US $1500.0-1500.0 / Pieces 500 Pieces (Min. Order) KWADO SHUTTLE AND TOURS AGENCY CC import export company names for travel agent multipurpose mobile universal travel adapter US $6.72-6.77 / Piece 100 Pieces (Min. Order) Dongguan Jiushang Electric Co., Ltd. best gift luggage tag for VIP TRAVELERS US $0.95-0.95 / Pieces 300 Pieces (Min. Order) Dongguan Airuilong Gifts Ltd. 2015 well sale/supply good quality and price hospitality amenities US $0.4-1 / Set 5000 Sets (Min. Order) Yangzhou Liangshuang Cosmetics Co., Ltd. High speed mixer grouting agent liquid filling machine automatic US $10.0-10.0 / Set 1 Set (Min. Order) Zhengzhou Bainte Machinery Equipment Co., Ltd. Lightweight Polyester Cotton Business document bag with top handles US $3.5-3.5 / Piece 3000 Pieces (Min. Order) Boomerang (H.K.) Company Anti-uv rectangular mosquito nets company US $1-5 / Piece 1000 Pieces (Min. Order) Fujian Yamei Industry & Trade Co., Ltd. Tour Operator (travel agent) Kotoz Company EU. Visa only for full booking. 1 Pair (Min. Order) Kotoz Company Fancy Gift ! Magnetic Levitation Globe for Fancy Gift ! travel agency promotion gift US $10-30 / Piece 200 Pieces (Min. Order) HCNT Industrial Company Ltd. Professional travel agent company audio system tour guide, school training wireless tour guide system US $1-19 / Piece 1 Piece (Min. Order) SZ Wise Unite System Technology Co., Ltd. - About product and suppliers: Alibaba.com offers 197 company travel agency products. About 8% of these are bag parts & accessories, 5% are business travel packages, and 5% are other business travel services. A wide variety of company travel agency options are available to you, such as tag, tft, and office furniture. You can also choose from plastic, rubber, and wooden. As well as from free samples. There are 176 company travel agency suppliers, mainly located in Asia. The top supplying countries or regions are China, Vietnam, and India, which supply 80%, 5%, and 3% of company travel agency respectively. Company travel agency products are most popular in North America, Eastern Europe, and South America. You can ensure product safety by selecting from certified suppliers, including 12 with ISO9001, 2 with BSCI, and 2 with Other certification.
https://www.alibaba.com/showroom/company-travel-agency.html
CC-MAIN-2019-39
refinedweb
1,127
61.12
The Map interface maps unique keys to value means it associate value to unique keys which you use to retrieve value at a later date. Some of the key points are : HashMap<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>(); import java.util.*; public class MapDemo { public static void main(String[] args) { Map m1 = new HashMap (); m1.put("Ankit", "8"); m1.put("Kapil", "31"); m1.put("Saurabh", "12"); m1.put("Apoorva", "14"); System.out.println(); System.out.println("Elements of Map"); System.out.print(m1); } } Output : If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions. Ask Questions? Discuss: Java HashMap - Java Tutorials Post your Comment
http://www.roseindia.net/javatutorials/javahashmap.shtml
CC-MAIN-2013-20
refinedweb
139
69.18
module that instantiates a couple of factories Hi Koji, I have written a library that automatically instantiates an IAnalysisFactory for interactive use. When importing the module in ipython, it bails out. Running the import a second time works, so I assume it's a threading problem again. Are threads actually used in batch mode ? There's no gui that could block I/O. Please see the attached script. start ipython from paidaUtilities import paida You can see that importing works the second time around. This is python2.4, on Scientific Linux 3. paida from cvs head. module that instantiates a couple of factories Logged In: YES user_id=734761 Originator: NO Sorry for my late reply. After some investigations, the problem is due to the deep part of current PAIDA architecture. As you pointed out, PAIDA uses (and has to use) "threading" module even in the batch mode and the problem is (partly) related to it. This will be fixed PAIDA4 which is planned to use separate processes instead of threads... Logged In: YES user_id=1366327 Originator: YES Hi Koji, Thanks for the reply. Very interesting approach to use separate processes rather than threads. How do they communicate? I think threads would be good enough, if they only get started when actually invoking the plotter. Anyways, it's not a big bug, so it doesn't bother me too much. My Analysis is starting to move into the "hot phase", so PAIDA will get some more serious testing. Keep rocking. Cheers, Jan Logged In: YES user_id=734761 Originator: NO In PAIDA4, they will communicate with normal and wide used internet protocols like TCP/IP. If we use PAIDA with another application that uses thread like ipython and wxPython, we always have some problems due to it. It is because the applications (including PAIDA) that use threading module tend to forget to pay attention to each other. This invokes the problems like main loop process inside GUI and timing treatment. Anyway, this way will boost PAIDA to new level. Please continue to help PAIDA development. Log in to post a comment.
https://sourceforge.net/p/paida/bugs/8/
CC-MAIN-2017-22
refinedweb
349
67.15
User Details - User Since - Jan 3 2013, 3:07 PM (349 w, 2 d) Fri, Sep 13 How many symbols are there today? Do we want this overhead of a function call for each? Could you instead return a count and array pointer (like argc and argv) or have a "foreach" function that takes a block and calls it back for each symbol? May 6 2019 Can this be conditionalized to not happen on macOS/iOS? I can see needing this on platforms where pthreads is optional, but it looks like this code will apply to macOS too, which introduces risk there. Jan 25 2019 Apr 10 2018 LGTM Oct 31 2016 Sep 30 2016 Jul 19 2016 LGTM Jan 7 2016 Dec 11 2015 Dec 10 2015 Dec 8 2015 LGTM Jul 24 2015 Jun 24 2015 LGTM May 20 2015 Mar 2 2015 Thanks for working on this! Mar 1 2015 Feb 13 2015 LGTM Feb 5 2015 LGTM Jan 27 2015 All those comparisons in compareAtomSub() are part of the system linker on darwin. See: Leaving this pass as-is and adding a new simple pass that ELF (and maybe COFF) uses instead is fine with me. Sure two passes is conceptually clean, but if it turns out that running sort() twice for mach-o makes linking slower for mach-o than it currently is, then that is not ideal. There maybe lots of other parts of this LayoutPass that mach-o needs but ELF does not. Why not just prune away at this until you get pass that is fast enough for ELF. Then split this in to two passes. One for mach-o and one for ELF, and let the drivers choose the pass to use. Jan 26 2015. Jan 14 2015 but they went away after adding -lc++abi. Jan 13 2015 It will just work. libstdc++.dylib re-exports symbols from libc++abi.dylib: Jan 12 2015 I see. Given my comment in the previous patch about parallelism, I was expecting to see a change in the latest patch about when parsing happens. But you changed mach-o parseFile() a while ago to instantiate a File object, but not parse it until doParse() was invoked. So all is good. Just the parseFile() name confusing me. It still looks like mach-o files are parsed immediately (not in parallel). If that is intentional, because reworking the mach-o logic is complicated, then leave a FIXME comment there. Jan 7 2015 This seems to have lost the parallel reading/parsing of input files. It looks like parseFile() called by the driver is triggering the actual parsing and parse() called by the Driver in parallel just returns the error code from the parse. Jan 6 2015 Two comments: - This refactoring has taken so many steps, I'm beginning to think one big patch where we can see the end design might have been better... - The ErrorFile concept makes me wonder if that should be the approach for all parseFile() implementations. Rather than having a result parameter is that is a vector they append to and returning an error_code, they simply return a vector of Files and any errors are encoded as ErrorFiles in that vector. Jan 5 2015 Dec 23 2014 The libcompiler_rt.dylib in the OS is built using darwin_bni.mk. I don't know anything that uses darwin_fat.mk. Dec 19 2014 LGTM Dec 18 2014 LGTM The static linker does not need to interpret LC_RPATH in linked dylibs, so there is no need to write a test case that it can. I see what you are trying to do, but it leaves the pass-generated atoms in an odd state. All the other atoms (from .o files) still have their file() method returning their original file. But the pass-generated atoms now have their file() return the temp mergedFile. When inspecting atoms in the Writer, it is nice to be able to see where they came from. This patch looses that. Dec 12 2014 The method Reader::parseFile() no longer has an appropriate name (since it no longer parses). It now just constructs a File object. Dec 5 2014 commited in r 223528 Dec 4 2014 Colin's calculation is based on the bumpvector containing only the *pointer* to the Reference. The current implementation has a vector< SimpleReference>, so the wasted space is not just a pointer size (repeatedly doubled). A SimpleReference is 64 bytes in size, so that value keeps getting doubled (and wasted). Won't "RefList _reference" leak the nodes of the linked list But using the BumpVector makes the code cleaner too right ? Only because you are adding new BumpVector code. We could also add a new BumpList class to ADT and that would make the lld code very clean too. A downside to BumpVector is that as the vector grows (by adding References), the capacity is doubled by bump allocating a new chunk. All the previous allocations (e.g. if current at 8 elements, the allocs for 1, 2, and 4) are wasted space in the bumpptr pool. Dec 3 2014 Even if you add a std::vector<std::unique_ptr<Reference>> to lld::File (so the SimpleReferences are deleted when the File is deleted), you still need a std::vector<SimpleReference*> in each SimpleDefineAtom to track which references are used by that atom. And the allocations for that vector would be leaked if the Atom is BumpPtr allocated. This still seems too complicated. But it is a step in the right direction, so LGTM. Dec 2 2014 Can you just generalize ShouldInstrumentGlobal() to return false for all cstring_literals sections? The linker is always going to coalesce sections of that type. Nov 21 2014 The big problem I still see is that this does not fix the issue of multiple different file kinds in one InputElement. Nov 12 2014 Regarding testing, if you are ok limiting the test to run on darwin, you could have .ll files which you compile and use the system linker to produce the final executable which then has its debug map processed. The common code looks good to me. Nov 6 2014 Funny. I just ran into this myself linking libc for arm64. Some of the .o files inside static archives are not 8-byte aligned, so the read64() is asserting. I think the read64() assert may be too aggressive. It may need to fallback to memcpy() for reading unaligned data, rather that asserting. Oct 29 2014 I'm not a clang driver guy, but it would probably be cleaner to leave AddLinkRuntimeLib() as is, and instead add the CmdArgs.push_back()s inside the if (Sanitize.needsAsanRt()). Oct 27 2014 LGTM Oct 21 2014 committed in r220330 Oct 20 2014 Oct 16 2014 The ArchHandlers look much better! Oct 15 2014 How come in the ArchHandler_x86_64 you use: write32(loc, value, false); but inside ArchHandler_arm64 you use: write32(loc, value, _isBig); How come in the ArchHandler_x86_64 you use: write32(loc, value, false); but inside Oct 14 2014 LGTM LGTM Oct 13 2014 LGTM The MachOObjectFile constructor is already walking the load commands. If there is a LC_UUID, you can have the constructor save it off in an ivar. Oct 7 2014 committed in r219260 fixes from latest Rafael comments. Rework to use getFileAux() Oct 2 2014 committed in r218893 Oct 1 2014 Sep 30 2014 committed in r218718 Sep 26 2014 should we add a special case to the reader to convert them to weak undefines? That is what I was thinking. But you should investigate how this works with the gnu linker. Does the linker really hard code "__tls_get_addr" to be special? Or does it always implicitly link with ld.so? to complete linking an executable, all symbols must be resolved and we cannot finish it with undefined references I guess I was not clear. I did not mean where does the *definition* of tls_get_addr come from. I was asking where does the *undefine* for tls_get_addr come from? If that undefine is "weak", that tells the linker that if no definition is found, to assume it was in some DSO. Seems like that is what you are special casing tls_get_addr to do. One area of linking not fleshed out in lld is the "canBeNullAtBuildtime" attribute for UndefinedSymbols. That was intended to model ELF weak undefines. Is that how tls_get_addr works with gnu ld? If so, then getting canBeNullAtBuildtime to work in general could solve this specific issue without needing to special case tls_get_addr. Sep 25 2014 There are two issues: committed in r218463 Sep 19 2014 Add doxygen comments and unit tests. Sep 18 2014 Is there some C++ language feature we can use to mark the Twine class in a way that causes a warning/error on these incorrect usages? Sep 17 2014 - Don't most build system invoke the compiler to invoke the linker? How are you overriding the linker? Can you redirect to a script that invokes lld with -flavor and $@ - Yes, shifting argv is not right. We need the -flavor and its arg removed, so argv[0] is still the command name. The original design was that -flavor had to be the first arg (so incrementing argv worked). But now the use of ParseArgs() means that -flavor is being searched for everywhere in the arg list. That is a mismatch. Sep 12 2014 I assume that preload() return immediately, and that it is expected to spin off some thread to parse an archive member? If so, we have no overall throttle on how many threads will be started (a hundred undefines could spin up 100 threads). Also, how is the archive reader to coordinate if the Resolver gets to the point it really wants an object file to fulfill and undefine but some other thread is busy parsing that member? Interesting. That is the way I used to write C++, but I thought the LLVM convention preferred anonymous namespaces. After reading the current LLVM convention doc, I see that static is better in this case. I'll retrain my fingers :-) Sep 11 2014 LGTM Sep 10 2014 committed as r217566 Sep 9 2014 Adding support for "ld" on *nix meaning use-gnu-driver is reasonable, but it is an additional feature (which I have no way to test). A few nits, but over all a great start. Sep 5 2014 LGTM Sep 3 2014 committed in r217112 Just add a StringMap ivar to ELFLinkingContext. Have notifySymbolTableCoalesce() add the atom name to the map when overriding a weak atom. In buildDynamicSymbolTable() check for atom->dynamicExport() OR (atom->scope() == scopeGlobal and its name is in the StringMap). Sep 2 2014 LGTM. Thanks for tracking this down. Aug 29 2014 committed in r216808
https://reviews.llvm.org/p/kledzik/
CC-MAIN-2019-39
refinedweb
1,790
72.05
= Fedora Weekly News Issue 117 = Welcome to Fedora Weekly News Issue 117 for the week of January 21st, 2008. In Announcement, we have "And the F9 codename winner is...", "FUDCon F9 Survey available" and "Fedora Unity releases updated Fedora 7 Re-Spins". In Planet Fedora, we have "Summer coding project ideas for Fedora", "Red Hat, rocking hard", "The name game" and "My big announcement". To join or give us your feedback, please visit. 1. Announcements 1. And the F9 codename winner is... 2. FUDCon F9 Survey available 3. Fedora Unity releases updated Fedora 7 Re-Spins 2. Planet Fedora 1. Summer coding project ideas for Fedora 2. Red Hat, rocking hard 3. The name game 4. My big announcement 3. Marketing 1. FUDCon video: New face of Fedora 2. Linux Format Interviews Jack Aboutboul 3. Max Spevack talks to Linux.com 4. Spinning a Fedora Linux Live CD 4. Ambassadors 1. Ambassador Needed for Florida Linux Show 2. Ambassador Needed for Linux Fest Northwest 3. FAmSCo Summary 5. Developments 1. YUM Proxy Cache Safety, Storage Backend 2. Disable SELinux To Use Revisor 3. Long-term Support Release 4. F9 Alpha Spinning 5. SELinux And Chroot 6. Fedora 9 For Asus Eeepc 7. BIND: Less Restrictive Modes And Policy 8. What Is A Fedora Developer? 9. Erratum 6. Advisory Board 1. Requests To The Fedora Board 2. Fedora 7 Unity Re-Spin 7. Documentation 1. Works in Progress 2. Release Notes Summary 8. Infrastructure 1. Continuing issues with xen 2. Some Network issues affecting fedora servers 9. Security Week 1. Enterprise-grade Linux: Five network security FOSS apps 2. Growing virus production taxes security firms 10. Security Advisories 1. Fedora 8 Security Advisories 2. Fedora 7 Security Advisories 11. Events and Meetings 1. Fedora Board Meeting Minutes 2008-01-22 2. Fedora Ambassadors Steering Committee Meeting 2008-01-21 3. Fedora Documentation Steering Committee (Log) 2008-01-22 4. Fedora Engineering Steering Committee Meeting 2008-01-24 5. Fedora Infrastructure Meeting (Log) 2008-01-24 6. Fedora Release Engineering Meeting 2008-01-21 7. Fedora Testing (BugZappers) Meeting 2008-01-02 8. Fedora SIG EPEL Meeting Week 04/2008 9. Fedora SIG KDE Meeting Week 04/2008 12. Ask Fedora 1. Fedora on Older Hardware 2. OEM Installation 3. Compiling Kernel 4. Bluetooth and Multimedia Keys 5. Prayer Time for Fedora [[Anchor(Announcements)]] == Announcements == In this section, we cover announcements from Fedora Project. Contributing Writer: ThomasChung === And the F9 codename winner is... === JoshBoyer announces in fedora-announce-list[1], "Fedora 9 (Sulphur) Try as they might, the Bathysphere lobbyists failed in their quest to have the little round ships be the moniker for Fedora 9. Instead, by a narrow margin, the community has chosen Sulphur to be the codename for Fedora 9." [1] === FUDCon F9 Survey available === PaulFrields announces in fedora-announce-list[1], !" [1] === Fedora Unity releases updated Fedora 7 Re-Spins === JeroenVanMeeuwen announces in fedora-announce-list[1], "The Fedora Unity Project is proud to announce the release of new ISO Re-Spins (DVD and CD Sets) of Fedora 7. These Re-Spin ISOs are based on Fedora 7 and all updates released as of January 18th, 2008. The ISO images are available for i386, x86_64 and PPC architectures via jigdo starting Thursday, January 24th, === Summer coding project ideas for Fedora === KarstenWade points out in his blog[1], "Summer." [1] === Red Hat, rocking hard === DavidNielsen points out in his blog[1], "Forbes reports the 25 fastest growing Tech companies, our friends at Red Hat comes in at 11th. Many congratulations to Red Hat on the fine result." [1] === The name game === JoshBoyer points out in his blog[1], "The timing was totally different this time around so that the Art team could have more time to create artwork for the release. Also, there's no real reason to keep it secret until the last minute. We tried this for this release to see if it made a difference anywhere. If it doesn't produce something that most people view as good we can always change back." [1] === My big announcement === TomCallaway points out in his blog[1], "I've known about this for some time, as have a lot of people, but it hasn't been publicly announced anywhere yet. The paperwork went through earlier this week, so it is official now: I'm now the Fedora Engineering Manager inside Red Hat." "Also, this means that February 2008 is going to be a busy month for me. Right now, I'm planning to attend SCALE 6X[2] and FOSDEM '08[3], with Capricon 28 (not a Linux event) shoved in the middle." [1] [2] [3] [[Anchor(Marketing)]] == Marketing == In this section, we cover Fedora Marketing Project. Contributing Writer: ThomasChung === FUDCon video: New face of Fedora === RahulSundaram reports in fedora-marketing-list[1], ." [1] === Linux Format Interviews Jack Aboutboul === RahulSundaram reports in fedora-marketing-list[1], "Fedora's dedication to opening everything is not just for hackers – it has a wider importance in that our approach is an agent for social change" [1] === Max Spevack talks to Linux.com === RahulSundaram reports in fedora-marketing-list[1], ." [1] === Spinning a Fedora Linux Live CD === RahulSundaram reports in fedora-marketing-list[1], "The Fedora project has added a powerful tool to its Linux distribution to build your own live CD. With a single livecd-creator command and a kickstart file listing the software you want, you can create a desktop, gaming, or Web server to run live on most PCs. This article gives details of how to do that." [1] [[Anchor(Ambassadors)]] == Ambassadors == In this section, we cover Fedora Ambassadors Project. Contributing Writer: JeffreyTadlock === Ambassador Needed for Florida Linux Show === A post the Fedora-Announce-List[1] was made asking for a Fedora Booth presence at the Florida Linux Show on February 11th, 2008. If there are any Ambassadors in the region, please check the Help Wanted: Events page [2] and add your name to the event. [1] [2] === Ambassador Needed for Linux Fest Northwest === JesseKeating posted to the Ambassador's list [1] looking for Ambassadors to help staff a Fedora booth at Linux Fest Northwest. The event has been added to the Help Wanted: Events page [2]. If you can help, please add your name to the event. [1] [2] === FAmSCo Summary === The Fedora Ambassador Steering Committee held its first meeting since the initial meeting to elect a chairman of the committee. The following highlights some of FAmSCo's discussion on mailing lists and from that meeting. * In efforts to help keep fellow Ambassadors informed as to what FAmSCo is doing the committee will be communicating summaries of activites through the Fedora News project. * FAmSCo meetings have moved to the public #fedora-meeting channel. FAmSCo will be meeting every two weeks on Monday's at 20:00 UTC, with the next meeting being 2008-02-04. The Meetings page [1] will contain summaries of past meetings. * FAmSCo is discussing going back through the Ambassador Verification list [2] and following up with any Ambassadors who have not signed the CLA and offering to help with the process or removed the name from the list if needed. * FAmSCo is also discussing a better way to receive feedback from Ambassadors regarding events, Ambassador operations and more. Early discussions mention the possibility of a web form to simply using an email alias. [1] [2] [[Anchor(Developments)]] == Developments == In this section, we cover the problems/solutions, people/personalities, and ups/downs of the endless discussions on Fedora Developments. Contributing Writer: OisinFeeley === YUM Proxy Cache Safety, Storage Backend === This week's Intensely Detailed Thread Prize has been awarded to the exchange started[1] by WarrenTogami concerning the best manner in which YUM and HTTP mirrors can handle proxy caches. Warren had received some interesting feedback from a ''squid''[2] developer, HenrikNordström and explained several ways in which caching proxies could cause YUM metadata to fall out of sync with the actual upstream RPM packages. The main conclusion seemed to be that it would be best to make the filenames of the repodata contain distinguishing information. Warren proposed several other ways relying on HTTP response headers as potential alternate solutions, including the use of ETags[2]. [1] [2] Warren's specific suggestion that the repodata filenames be modified to include timestamps was tempered by his worry that older clients unable to handle the renaming would hamper migration, but JesseKeating[3] and ChuckAnderson[4] did some testing and found that YUM was able to handle the situation as far back as "FC5, yum-2.6.1-0.fc5, ftp and http baseurls". [3] [4] JamesAntill threw an exception[5] when NicolasMailhot commented "I made the same analysis several months ago when I setup my own local mod_proxy cache. I'm glad to see Warren is getting through better than me at the time." James counterposed the relative success resulting from the method of flaming the "stupid yum developers" on @fedora-devel versus discussion on the IRC channels #yum, #yum-devel and the subsequent opening of bug reports and development. Nicolas responded that this was an example of shooting the messenger and that the problem had been reported many times. James' response was to cite[6] possible shortage of resources and to point out that SethVidal is usually very responsive when approached through the method which James had described. [5] [6] A very long and interesting sub-thread was opened[7] by LesMikesell who was interested in the divergent question of how it would be possible to change YUM so that non-cooperating users in the same netblock would be served files from the same local cache. [7] There seemed to be general agreement that the transition to versioned filenames of repodata could work. AlanCox noted[8] that keeping two versions of the most up-to-date repodata, one with the newer filenaming scheme would cover the case of older, incompatible clients and new clients. JamesAntill suggested[9] that SHA1 sums be used instead of timestamps and that YUM would need to be modified to clean up metadata in /var/cache/yum. He also suggested that Warren should discuss the issue on #yum. [8] [9] === Disable SELinux To Use Revisor === A problem with running SELinux while attempting to run the FedoraUnity Project's ''revisor'' tool[1], for creating re-spins of Fedora, was brought[2] to the attention of the list by ValentTurkovic. Valent posted screenshots of AVC denials and suggested that the respective programming teams should sort out the problem. [1] [2] JohnDennis suggested that the actual alert could be saved from ''setroubleshoot'' and could then be entered into bugzilla instead of using a screenshot, but Valent responded[3] that the developers should just try and compose a respin with ''revisor'' and that this was typical of a pattern in Fedora: "looks like nobody actually does testing of these new features." A quick clarification was issued[4] by JefSpaleta to the effect that ''revisor'' was not used internally by the Fedora Project. CaseyDahlin pointed out that the ability to respin Fedora easily was being advertised and people expected it to work, to which JesseKeating responded[5] that '"We" cannot help what some other parts of the project choose to tout (:' [3] [4] [5] The core of the problem was outlined[6] by JefSpaleta when he explained that SELinux interacting with any chroot-like apparatus was a problem, and re-emphasized that Valent's apparent belief that Fedora release-engineering would have seen the problems was incorrect as ''revisor'' was not used internally. Jef also argued that while re-spin generation tools should issue alerts that SELinux should be disabled, they should not automatically disable SELinux. JesseKeating deepened[7] the explanation with the information that "installing a new policy in the chroot will actually cause that policy to activate on the running kernel and then you have policy that doesn't match labels, watch the fun!" and suggested that SELinux should be disabled entirely or at least put in permissive mode before trying to use chroot-dependent tools such as ''revisor'', ''pungi'' or ''livecd-creator''[8]. [6] [7] [8] Valent returned to the attack (see FWN#116 "AVC:Denied {trolling} For PID=666 Comm={SELinuxRemove}"[9]) on SELinux leading JohnDennis to remind[10] him that he was free to disable it whenever he liked but that the goal of the Fedora Project was to "smooth out the bumps rather than disabling the technology." A brief response from Valent led DanWalsh to explain[11] the problem further and this resulted in opening up the thread to interesting, problem-solving contributions. Dan's take was that the chroot and the host both use the same kernel, so the loading of new SELinux policies _within_ the chroot actually affects the host kernel. Dan wondered whether the solution could be virtual machines, or getting the chroot to run a separate kernel, or tricking SELinux within a chroot into doing nothing. As part of the brainstorming TillMaas suggested[12] that separate xattr namespaces could be part of the solution. JamesMorris took up[13] the virtual machine idea and wondered if ''lguest'' would be suitable due to being scriptable and booting nearly instantaneously and DanielBerrange added[14] the suggestion that LVM snapshots would provide disposable disk-images which could be booted as guests. [9] [10] [11] [12] [14] JesseKeating played the role of realist and asked[15] for them to "get back to me when it works on x86_64, ppc, ppc64, ia64, s390, s390x, sparc, sparc64, arm, alpha..." DouglasMcClendon mentioned his ''qfakeroot'' scripts again and an interesting exchange occurred[16] which explored the speed of qemu, the flakiness of kqemu and the non-availability of qemu for PPC and an acknowledgment[17] that Douglas' ''qkfakeroot'' is "pretty cool" in its ability to eschew root privileges even if it takes too long to be used as a standard compose tool by Fedora release-engineering. [15] [16] [17] Two separate threads later resulted from this and are covered in this same FWN#117 as "What Is A Fedora Developer?" and "SELinux And Chroot". === Long-term Support Release === The issue of whether it was possible to have a "long term support" release of Fedora was floated[1] by DavidMansfield. David's courteous post recognized that this might be mistaken for flame-bait and acknowledged that teampower might be a constraint. David explained[2] that the absence of many tools such as ''gnumeric'' and ''git'' and some of the "cool" tools from the livna and rpmforge repositories from CentOS/RHEL was a problem for him. [1] [2] CaseyDahlin was the first of many to suggest[3] that David should take a look at the EPEL repositories. HorstvonBrand added[4] that the purpose of Fedora was to make obtaining freely distributable software easy and that this ruled out some of the programs in livna and rpmforge. [3] [4] AndrewFarris recalled[5] the now defunct FedoraLegacy project and a sub-thread exploring the problems of trying to maintain a long-term release evolved including a discussion of whether RHEL in conjunction with the EPEL repository was in effect "Fedora LTS". [5] [6] JefSpaleta welcomed[7] the idea of a "Fedora LTS" but cautioned that the idea seems to originate in Canonical's specific business model and that it is hard to see where this fits in to the Fedora space. His post was very encouraging but challenged proponents to expand upon a potential business plan. [7] Discussion of whether FedoraLegacy actually failed, whether failure is actually beneficial and what was learned took up the remainder of the thread[8]. [8] === F9 Alpha Spinning === Some figures for the sizes of ISOs for Fedora 9 Alpha spin were posted[1] by LukeMacken. Included was a diff between the F8-Live-i686 and F9-Alpha-Live-i686 Desktop spins. [1] Suggestions were made[2] by HansdeGoede to reduce the size of the ISOs a little including splitting up ''gnome-games'' and perhaps removing ''httpd'' from the LiveCD. LubomirKundrak suggested that ''httpd'' was there because of WebDAV file sharing[3]. [2] [3] RahulSundaram wanted[4] to make sure that the latest content was going into the Games LiveCD and offered to keep it updated in livecd-tools. This led BillNottingham to query whether keeping the contributed spin configs in ''livecd-tools'' itself and ColinWalters suggested[5] keeping them in the same CVS directory as comps. [4] [5] SzabolcsSzakacsits took pains to emphasize[6] that the apparent growth of ''ntfs-3g'' did not take into account that ntfs-3g changes had enabled the removal of ''fuse'' and a consequent overall decrease of 109MB. KevinKofler did not approve of some of the changes as he claimed that they essentially created a static copy of fuse into ntfs-3g. [6] [7] === SELinux And Chroot === As a result of the discussions over how to improve the interaction between chroots and SELinux JamesMorris created a bugzilla[1] entry and requested that concerned parties add requirements. He noted[2] that a related issue under discussion was the distribution of policy when the host and target have differing policies. [1] [2] === Fedora 9 For Asus Eeepc === The lucky OrionPoplawski had been playing around with a new toy in the form of the ultra-portable Asus Eee PC and reported[1] that he had encountered issues with the ethernet adapter (Attansic Tech L2 100Mbit), the wireless adapter (Atheros AR5007EG) and the Flash RAM harddrive. [1] ColinWalters suggested that as Orion wanted to minimize writes to the flash drive (as there are a limited number) it would make sense to make the filesystem read-only, in effect creating a "Live OS" on it with the exception of /home which would be stored on an SD card. [2] The use of ''jffs2'' was recommended[3] by JohnPalmieri on the basis of its use in the OLPC. John added that modern flash used "randomized writes" (presumably wear-leveling) and thus was less likely to see the problems encountered with journal writing in ext3 filesystems or FAT on the older hardware. He suggested also eliminating any /swap partition and looking out for a new FS which was reputed to be better for large flash drives. Some doubt was cast on this by JonathanUnderwood as apparently the drives do not appear as flash to the OS. [3] [4] JoshBoyer and RubenKerkhof suggested that the ''logfs'' and ''ubifs'' filesystems might be what John was thinking about. Josh thought that the wear-leveling was done by a controller and not the actual flash chip. [6] === BIND: Less Restrictive Modes And Policy === An announcement of a major revision of BIND file modes was made[1] by AdamTkac. Adam proposed that only ''/etc/rndc.key'' and ''/var/log/named.log'' should be restricted to the root user and that other binaries should be readable by non-root users. He also proposed that the ''/var/named/*'' subtree would be writable by ''named''. Adam sought objections. [1] SteveGrubb wondered[2] which other users would be expected to share a DNS server and pointed out that it was "a high value target for hackers". [2] EnricoScholz suggested[3] that only the ''slaves/'' and ''data/'' directories had to be writable, but that ''pz/'' and other parts of the chrooted filesystem used by named had to be read-only. AndrewFarris wondered why and ManuelWolfshant recalled[4] BIND's past history of providing a remote root. He also stated a preference for the general principle of granting the minimal rights necessary. After Enrico confirmed this AdamTkac explained[5] that /var/named was supposed to be writable by design. [3] [4] [5] A later comment mentioned[6] that there was a problem with coredumps and in discussion with ChuckAnderson Adam cited a bugzilla entry which documents the problem. [6] === What Is A Fedora Developer? === Several hours after the extensive discussions[1] of the need to disable SELinux while using chroot-dependent compose tools ValentTurkovic initiated[2] another thread about using ''revisor'' in which he asked for guidance as to whether he was encountering bugs or making usage errors. [1] FWN#117 "Disable SELinux To Use Revisor" [2] This thread had the potential to turn sour shortly after Valent was advised[3][4] by several people that the FedoraUnity project were the experts on ''revisor'' and Valent responded[5] by echoing the comment made[6] (and answered!) previously in the earlier thread in which he had been involved. Namely he claimed that "I thought since I'm using a really loudly advertised fedora feature, and config files which all of them are provided from fedora and not some 3rd party that this is the correct list." [3] [4] [5] [6] JesseKeating responded[7] calmly with the question "You are aware that the vast majority of software in Fedora is developed and discussed at their respective upstream locations, right?" JefSpaleta produced[8] one of his typically insightful explicatory posts in which he drew a distinction between upstream developers who contribute to Fedora and "Fedora developers" who produce infrastructure which allows the Fedora Project to be a conduit between users and upstream projects. [7] [8] === Erratum === In FWN#114 "SELinux Rants"[1] we mentioned that the copying of directories using ''tar'' should be done with the "--xattrs" option in order to preserve the context labels. DavidHighley subsequently contacted us to report that he had experienced problems using this method. David later helpfully reported that ''tar-1.17-5.fc8'', which is available as an update appears to fix[2] the apparently broken storage of SELinux and extended attributes which David was reporting. Thanks to David for the follow-up on this issue. [1] [2] [[Anchor(AdvisoryBoard)]] == Advisory Board == In this section, we cover discussion in Fedora Advisory Board. Contributing Writer: MichaelLarabel === Requests To The Fedora Board === RahulSundaram has made five requests on the fedora-advisory-board list[1]. These requests come down to logistics with such appeals as posting an agenda prior to each meeting, posting the meeting minutes more promptly, and differing opinions on community board member nominees. The message with responses can be read on the mailing list[2]. [1] [2] === Fedora 7 Unity Re-Spin === For those not yet ready to upgrade to Fedora 8, the Fedora Unity[1] project has released updated spins of Fedora 7. These new ISOs contain all of the Fedora 7 updates as of January 18. The announcement and download links can be found on the fedora-advisory-board list[2]. [1] [2] [[Anchor(Documentation)]] == Documentation == In this section, we cover the Fedora Documentation Project. Contributing Writer: JohnBabich === Works in Progress === Work continues on the Desktop User Guide (DUG) and the Administration Guide (AG). The goal is to include both guides in the official Fedora 9 release. === Release Notes Summary === KarstenWade proposed a canonical release summary [1]. "We can use clever ...Include... statements that draw only specific parts, so each 'mirror' of the canonical summary can show the most appropriate fragment. Anyone interested in doing this work? It involves: * Working out a single canonical location from amongst the several Releases / # / Release Summary, Docs / Beats / Over View, Press release needs (more lightweight), etc. * Define a format for that page so that it can be fragmented (if needed) for different summaries * Write up a process for jamming all that together * Publicize/evangelize" JonathanRoberts agreed [2] and cited the KDE Project as doing an excellent job in this regard. RahulSundaram [3] concluded: "As the person behind both of these documents, let me note that release notes overview was meant to be more technical while the release summary was born out of an earlier effort to do press releases via the community. Also due to general lack of contributions (even though Jonathan Roberts and others did help for Fedora 8), the time taken to write a proper release summary was almost an entire night last time and that too way later than the release notes string freeze. We need to decide whether the overview in release notes can be the kind of content that release summary currently is. If that is preferred, let me know and I will do that from Fedora 9 onwards. I wouldn't mind more people helping out either." [1] [2] [3] [[Anchor(Infrastructure)]] == Infrastructure == In this section, we cover the Fedora Infrastructure Project. Contributing Writer: HuzaifaSidhpurwala === Continuing issues with xen === MikeMcGrath reports [1], xen1 started exhibiting these issues when we moved from FC6 to RHEL5 GA. It was assumed to be hardware issue because of how sporatic the issues were and because we actually do have RHEL5 on other xen hosts. The iscsi issue may or may not be a red herring but some of the reports listed in the ticket suggests a kernel / poweredge bug that we may be hitting. We had moved all non-redundant guests off of xen1 onto the more stable xen2 box. After upgrading xen2 to RHEL5 we started seeing the same problems with it. There's a few things we can try, Mike will be doing so on xen1 with proxy4 as our test host since its competely redundant and has, in the past, crashed that box. In the future though they should all be in similar specs (1U box, 8 core 16-32G memory) [1] === Some Network issues affecting fedora servers === MikeMcGrath reports [1], Seems a link between AT&T and level3 was down. Mike was monitoring the situation but there's little we can do about it right now. The link came back after some time. [1] [[Anchor(SecurityWeek)]] == Security Week == In this section, we highlight the security stories from the week in Fedora. Contributing Writer: JoshBressers === Enterprise-grade Linux: Five network security FOSS apps === iTWire has a story detailing five open source security applications: As more security applications are gobbled up by large firms, open source projects gain a unique advantage. Anytime an organization needs to make money, they are willing to draw a gray line with respect to their ethics. As most open source projects don't rely on corporate funding, they can be more strict with respect to what they call malware. It is quite likely that as the volume of malware increases, this advantage will become more clear. === Growing virus production taxes security firms === The Register points out the current problem with growing malware trends: The rate at which malware is growing is quite alarming. If this trend continues it will become impossible for anti virus firms to keep ahead of the wave. The current attitude toward malware is to take a very reactive approach. Most groups don't focus on stopping the cause of problems, but rather treating the symptoms. While there is certainly a great deal of money to be made in treating symptoms, the well is going to dry up eventually. [[Anchor(SecurityAdvisories)]] == Security Advisories == In this section, we cover Security Advisories from fedora-package-announce. Contributing Writer: ThomasChung === Fedora 8 Security Advisories === * xorg-x11-server-1.3.0.0-39.fc8 - * libXfont-1.3.1-2.fc8 - * hsqldb-1.8.0.8-1jpp.5.fc8 - * mantis-1.1.1-1.fc8 - * clamav-0.92-6.fc8 - * bind-9.5.0-23.b1.fc8 - * xorg-x11-server-1.3.0.0-40.fc8 - * kernel-2.6.23.14-107.fc8 - * pulseaudio-0.9.8-5.fc8 - * icu-3.8-5.fc8 - === Fedora 7 Security Advisories === * clamav-0.92-6.fc7 - * mantis-1.1.1-1.fc7 - * xorg-x11-server-1.3.0.0-15.fc7 - * hsqldb-1.8.0.8-1jpp.5.fc7 - * boost-1.33.1-15.fc7 - * libXfont-1.2.9-3.fc7 - * bind-9.4.2-3.fc7 - * xorg-x11-server-1.3.0.0-16.fc7 - * pulseaudio-0.9.6-2.fc7.1 - * icu-3.6-20.fc7 - [[Anchor(EventsMeetings)]] == Events and Meetings == In this section, we cover event reports and meeting summaries from various Projects and SIGs. Contributing Writer: ThomasChung === Fedora Board Meeting Minutes 2008-01-22 === * === Fedora Ambassadors Steering Committee Meeting 2008-01-21 === * === Fedora Documentation Steering Committee (Log) 2008-01-22 === * === Fedora Engineering Steering Committee Meeting 2008-01-24 === * === Fedora Infrastructure Meeting (Log) 2008-01-24 === * === Fedora Release Engineering Meeting 2008-01-21 === * === Fedora Testing (BugZappers) Meeting 2008-01-02 === * === Fedora SIG EPEL Meeting Week 04/2008 === * === Fedora SIG KDE Meeting Week 04/2008 === * [ === Fedora on Older Hardware === Robert Myers <mystinar comcast net>: In the development of Fedora 9, is there any work being done to improve it's performance on older hardware? If so, will the performance increases be noticeable on, say, a 450mhz Pentium III with 256 megabytes of RAM? --- The major features for Fedora 9 are listed at. While there isn't any special focus in Fedora 9 to make it work on older hardware, we typically inherit a number of performance improvements from the upstream projects that we integrate, including many key projects where Fedora developers are major contributors. As an exmaple, OLPC (One Laptop Per Child) project is based on Fedora, and since OLPC is a resource constrained environment, our participation results in improvements that make it easier and more efficient to run on older hardware. * To add to that, there are a couple of Fedora spins developed currently that target older hardware or low resource systems in which you might be interested. * * === OEM Installation === Shannon Mendenhall <mendenhall shannon comcast net:I was wondering when or if you are going to include a OEM install in your next version (fedora 9). I was hoping so it would make it easier for OEM builders to leave the client to set up there time zone, user name, password, ect... thanks, I look forward to hearing your reply. --- Actually, we've had this feature since the first version of Fedora. Refer to Also, Fedora provides a number of sophisticated and easy to use tools to make further customizations. Take a look at === Compiling Kernel === Sd <elesar cable netlux org>: How I can compile your kernel? Where I got kernel-source? --- An easy question, thanks to the nice documentation at. Note that this is already referenced from the release notes at === Bluetooth and Multimedia Keys === Zlatko (Email withheld on request) First of all, I would like to thank You for Fedora 8. I'm using Fedora since first edition, and now, I can say that Fedora is highly improved, and can be used almost for everything. I'm using Fedora on my laptop exclusively for business purposes, and also I'm using Fedora on my desktop computer at my home for watching TV, watching DVD, playing various games, Internet surfing, and so on, and everything is working OK. But, there is a slight problem in using fedora on my laptop. So, on to the problem... :-) My integrated bluetooth wont work, unless I do the following: 1. I start laptop with Windows Vista 2. I restart from Vista to Fedora Each time I do this, bluetooth works fine. But, if I turn off computer, and start it again directly to Fedora, bluetooth wont work, and system wont recognize any bluetooth device. I have described this problem on Fedora forum, also, but nobody answered my question so far, even I have posted that post month ago. Here is the link to that post: And also, if I may ask, is there a plan to support so-called "Fn" functions? For example, on my Toshiba Satellite P200-10C, when I press "Fn + F8" I should be able to activate/deactivate wireless/bluetooth, but instead, nothing happens. I surely hope that You will consider these questions, and help small users such as I am... :-) Thanks in advance... --- Another user asks a similar question Yuan Yijun <bbbush yuan gmail com>: I use a Dell 640m which have some external "multimedia button" to control music volume. And I used to close the lid while playing some background music. When the lid is closed, these buttons are not functional at all, so I cannot mute it without open the lid && login (because of gnome-screensaver). How to make them work? Thanks! --- The bluetooth issue as well as multimedia keys not working on your laptops out of the box appear to be bugs/enhancement requests that can reported directly to. We are continuously enhancing Fedora to support components like Bluetooth and multimedia keys to work better, and we appreciate your feedback. Use the following references: * * === Prayer Time for Fedora === Riam budhi <riam_3000 hotmail com>:. Refer to * -- Thomas Chung
http://www.redhat.com/archives/fedora-announce-list/2008-January/msg00013.html
CC-MAIN-2015-32
refinedweb
5,389
52.19
take a look Code:#include <iostream> using namespace std; void input (int test[5]) { int i; for(i=0;i<5;i++) { cout<<"Enter a number: "; cin>>test[i]; } } int main() { int array[5]; input(array); for(int i=0;i<5;i++) { cout<<array[i]; //shows the same values that i have input using the //function cout<<endl; } return 0; } I am passing array to function but it is being passed by reference..Could you please explain this concept? Why is this being passed as reference even though i am not using & operator to pass it as reference. I wrote a bubble sort algorithm using the same concept and i passed the array to function and did not return anything but it sorted the array in my main function which is weird as i did not pass the array by reference. I passed it like in the above program. Could you guys please explain this?I've been trying to find answer on Google but haven't been able to find it yet.Hopefully you guys can help.
http://cboard.cprogramming.com/cplusplus-programming/154004-passing-array-function.html
CC-MAIN-2014-35
refinedweb
179
68.81
On most platforms, symbols are private to a plugin module unless explicitly exported. However, on MacOS/X, symbols in plugin modules are typically public by default. Prior to MacOS/X 10.1, symbols in plugins existed in a flat namespace shared by the application and all plugin modules. This means that it was possible for symbols defined in one plugin to conflict with those defined in the application or in other plugins. As of MacOS/X 10.1, Apple introduced the concept of two-level namespace, in which symbols for a plugin exist within that plugin's own namespace, thus eliminating the problem of symbolic conflicts between plugins and the application, or plugins and other plugins. On other platforms, where plugin symbols are private by default, plugin modules are themselves link against any required static libraries in order to satisfy external symbolic references. Historically, this differed from pre-10.1 MacOS/X in which it was customary to link the application against any libraries which might have been required by plugin modules, rather than linking the plugin modules, themselves, against the libraries. There are a couple problems with this older approach. The approach used by other platforms, where plugin modules are linked directly against any static libraries which they require, has several advantages. Prior to the introduction of two-level namespaces with MacOS/X 10.1, in order to avoid the fragility of flat namespaces, and in order to avoid having to invent special case solutions to work around these problems, the MacOS/X port of Crystal Space emulated the model of dynamic linking used on other platforms. This was accomplished by linking plugin modules against the static libraries which they require, rather than linking those libraries into the application. The one major pitfall which makes employment of this approach difficult in a flat namespace, is that of symbolic conflicts where the same symbol is defined in more than one place. This problem can occur, for instance, when more than one plugin module links with the same static library, and when both a plugin module and the application link against the same static library. To work around this problem, the MacOS/X port takes advantage of DYLD's `NSLinkEditErrorHandlers' which allows the loader to ignore duplicate symbols at load time. Although this special manual symbol management is not required with two-level namespaces, the functionality is nevertheless retained for backward compatibility with older MacOS/X releases. This document was generated using texi2html 1.76.
http://www.crystalspace3d.org/docs/online/manual-1.0/cs_6.1.1.3.html
CC-MAIN-2015-22
refinedweb
414
51.38
In this article I would like to share my experience of using Microsoft Robotics Studio with a Lego Mindstorms NXT robot. I want to present my view on the topic, not as an expert in robotics, but rather from the perspective of a software developer with an interest in robotics and of positive technology in general. Maybe my enthusiasm could encourage some of you to get your hands dirty and try writing some code yourself, because I believe that writing code, facing, and overcoming real problems, is the best way to learn. Most software written today is for web, desktop or server applications and only a few dare to enter the field of robotics, and even they in most cases are primarily involved with a low level code, very close to the hardware. So what about all of us who have great experience with a high level managed code? Do we have any chance to do something in this area? Apparently, and fortunately, the answer to this question is ‘Yes, we do’. But would we want to? Wouldn’t that be a waste of our time? Many times the field of robotics has been compared to the early days of the information technology revolution, 30 years ago gigs were primarily working with electronics and only a few considered writing software as a cool and inspiring. And yet those that dared to enter this new realm became pioneers in a whole new page in the history of the human technology. We are now in the same situation with the emerging field of robotics. But wait a minute, wasn’t the robotic revolution been promised by science fiction writers and futurists, so many times, for so long, and somehow it is always ‘just coming’? Well it took us longer than we thought. In fact in 50s and 60s people envisioned it as a purely hardware task. Now we know: you can’t have intelligence without a more or less sophisticated software. Later when we had the software we were lacking the computational power. But now it is all slowly but surely coming together. We are just entering the multi-core era, the price for hardware becomes cheaper and cheaper almost every day and the number of developers being capable of writing good software is as never high. And most of all we do have real robot in this very moment, roaming the surface of the planet Mars, exploring the depths of our oceans, building cars and airplanes and even vacuuming our homes. Yes, so much more can be said about this, but because we are developers, we know that a line of code worth more that a thousand word, so let’s just see how we could apply our skills in building real robots. Microsoft Robotics Developer Studio is a tool that will help you to start writing real code without having to do all the low level tasks by yourself. Lego Mindstorms NXT on the other hand is a relatively cheap robot, with a lot of flexibility that is already very well integrated with Microsoft Robotics Studio. My explanations will be focused in using them together, because this is a good and affordable choice, but please note that this is just one of many options currently existing on the market, and you could very well choose to start with something else. I have setup a sample project on the codeplex site and you can also check my demo videos on YouTube here and here. What is required to start? For this particular solution you will need Visual Studio, the free express version is enough, and Microsoft Robotics Studio which is also free. In terms of hardware, you will need Lego Mindstorms NXT. My first version uses two motors, ultrasonic sensor, two bumpers and a compass, and the second uses two motors, ultrasonic sensor, bumper, accelerometer, and a compass. But you could choose your own setup as adding and configuring sensors is relatively easy and quick. One thing that you will probably want to have as well is a Bluetooth Connector because having a robot with an USB cord is no fun. But before jumping to the steps of building a real robot, we have to at least briefly cover some background tools that underlie Microsoft Robotics Studio. In particular those are CCR (Concurrency and Coordination Runtime) and DSS (Decentralized Software Services). Concurrency and Coordination Runtime (CCR) CCR is a .NET library that abstracts many common problems that you will face in a multi-threaded, multi-core environment. Writing your own thread synchronization and coordination code can often be a tedious task that takes your focus away from the critical problems that you want to solve and you waste a big part of your time in what we often call plumbing tasks. Code that normally spreads on many pages will be just a few lines long with the CCR. Let’s review some of the most common uses of CCR that you may benefit from. For many of the examples that I will mention you can look at my service class code. First of all let’s see how you would send data across threads. This is done by the use of generic Ports. You can think of a Port as a first-in-first-out queue of objects of the generic type you chose. For example If we want to post a string that will be handled by another method in another thread, we would use: This also is what happens when when a sensor sends data to the service. An object with the information from the sensor is sent to a Port and received by your handler. We will see how to subscribe to events coming from sensors in a bit. One very common application of CCR is in the use of Iterators. When you want to execute a sequence of actions in a non-blocking way, you would normally have to spawn a thread and have a separate method for each action. With CCR you can write your code in a sequential way within a single method and have it being executed as a sequence of background tasks. You can see that in the Initialize method of my service. A simplified version follows below: The method is executed in steps separated by yield return statements and treated as separate methods. However you write it as a sequence of actions. To start this iterator you call SpawnIterator method passing your iterator method as a parameter. You have the SpawnIterator method available because the DSS service inherits from from Microsoft.Ccr.Core.CcrServiceBase where it is defined. If you want to use the same approach for a class that does not inherit from CcrServiceBase your code could look like this: Here we create a thread pool with number of threads equal to the number of processors indicated by the zero in the Dispatcher constructor. We could have specified a specific number of threads instead. Then we create dispatcher queue that we will use for the activation of the concurrent tasks. As you can see CcrServiceBase abstracts for you the creation of a Dispatcher and DispatcherQueue. At the bottom of the Initialize method you can see how I use the Activate method also inherited from the CcrServiceBase class to subscribe to asynchronous callbacks coming from the sensors. You could read the first line of this code as follows: Expect to receive SonarSensorUpdate object (meaning an object posted on a Port<sonarsensor.SonarSensorUpdate>) from the UltrasonicSensorOperations object (here named ultrasonicNotify) and handle it with method UltrasonicHandler. UltrasonicHandler method must accept SonarSensorUpdate parameter. The other lines follow the same logic. The flag true indicates that the subscription is going to be persistent. If we set this value to false, only the first data received will be handled. Choice arbiter is the other CCR tool that worth mentioning. For example you can see how I use it to check for error when setting the current power for the motors of the robot. Here I set the power and the response can either be success, in which case I do nothing, or failure, in which case I issue an error warning. The methods SetDrivePower returns PortSet of success or failure messages. PortSet is a set of Ports, in this case the Port<DefaultResponseUpdateType> and Port<Fault>. Two handlers are passed for whatever message comes first. I will wrap up my CCR introduction here, as this is not the primary topic of this article but I strongly encourage you to read the MSDN article introducing CCR available here and to look at the source code attached to the article. Special points on interest are the use of Arbiter.MultipleItemReceive method that allows you to process data in batches and Arbiter.Interleave method that would allow you to define tasks that should be executes concurrently, exclusively or as a clean up task ending all other handlers. Decentralized Software Services (DSS) DSS is build on top of CCR and represent a restful service oriented environment. Each sensor or actuator (for example motor) is represented as a separate service. When you start your service two applications will open: a command prompt and a browser. The browser will point to a view of all your services, by default running on port 50000. There you could browse each registered service to view their properties and current state. The main class that will implement the connection to the sensors and actuators of your robot is a DSS Service. The service runs within the Robotics Studio Installation Directory/bin/DssHost.exe process. Some of the features that DSS gives you are implementation of publisher-subscriber model, lifetime management, security management, logging, service composition and others. For more information on the topic I would advise looking at MSDN introduction to the DSS available here. Putting it all together The project that I have setup is available on Codeplex it represents a LEGO NXT robot, that navigates it’s way and avoids obstacles. With it there is a WPF application that draws the current position of the robot and the state of it’s sensors. But let’s start with the basic setup of the project. In order to understand how the DSS host process is wired to the service we have to look at the debug start actions and command line arguments of the DSS Service project. The start actions point to the DssHost.exe file and the command line arguments are as follow: Make sure that the start action points to the DssHost.exe file. By executing the start action we run the DssHost.exe process while passing along our manifest file LegoBotPrimaService.manifest.xml located in the Config folder of the LegoBotPrimaService project. All the sensors and actuators are defined in this manifest file. Each one is identified by unique namespace. In addition to that, the Service tag of each sensor or actuator points to a separate XML configuration file. Before trying to execute the service you should make sure you have the Bluetooth connection established properly. Connect your Bluetooth to an USB port. Find the Bluetooth icon in the system trey at the lower right corner of your Windows. Right click on the icon and choose Show Bluetooth Devices. Then choose Add Device and you will have to confirm the password on the LEGO side. Once you have the connection established, right click that device and look at the Hardware tab. Under the Name column there you will find the number of the COM port. This is the number you need to specify in the SerialPort node of the LegoBotPrimaService/Config/LEGO.NXT.Brick.Config.xml file. My current architecture of the solution is not that important as this is just one of many possible ways of assembling things together. However I would like to stress a few points that I find important: - Be kind to your robot and write your tests first. It will be difficult to debug a problem or behaviour if you rely on running it on the real robot each time. You need a way to easily turn a real problematic behaviour in a unit test. The way I tried to achieve this is by having my logger to generate real C# code calls that I can copy, paste and with only a few modifications turn into unit tests. They will not only be important to solve your current problems, but also they will ensure that future modifications will not alter the expected behaviour. - Do not forget that you are working in a multi-threaded environment. Each time you collect a data coming from the sensors, remember that it may be accessed by different threads. Make sure you have the right locks in place. - Make your setting easily configurable Quite often you will need to adjust settings for a different environment, or after altering the expected behaviour. Remember that App.config file of your service can not be used as a configuration because the real process is DssHost.exe, unless of course you load a separate application domain, but the easiest option is to use DssHost.exe.config file located in the Robotics Studio Installation Directory/bin folder. Make sure you prefix your configurations to avoid interference of the configurations of different robots. Tips for overcoming common problems Here I would like to briefly mention some common problems that you may encounter: - Make sure your project is located in the root of your Robotics Studio Installation folder. For example if your user is called john, by default, the path will be C:\Users\john\Microsoft Robotics Dev Studio 2008 R3\LegoBotPrima - Make sure that LEGO brick configuration file holds the right COM port number, matching what you would see in the Bluetooth Device Properties – Hardware Tab – Name Column - Make sure that the sensor or actuator namespace used in the manifest file matches the one specified in the Identifier attribute of the Contract class of your sensor. Use Reflector to disassemble the sensor assembly and look at the literal for the contract identifier. For example if you want to see it for the Compass sensor you will reflect bin\HiTechnic.Y2007.M07.proxy.dll assembly under Microsoft.Robotics.Services.Sample.HiTechnic.Compass.Proxy namespace, Contract class and Identifier attribute. - Make sure that the root node name of your sensor XML file matches the name of the sensor state class, as well as all the property names. For example my LEGO.NXT.v2.touchsensor.config.xml file has as root TouchSensorState node that matches TouchSensorState class name defined in bin\NxtBrick.Y2007.M07.proxy.dll assembly Microsoft.Robotics.Services.Sample.Lego.Nxt.TouchSensor.Proxy namespace. - Make sure that the SerialPort for each sensor matches the slot that you connected this sensor on the LEGO brick. For example if you have connected the compass sensor on the third sensor input your HiTechnicCompassSensor.Config.xml SensorPort node should look like <SensorPort>Sensor3</SensorPort> The same way MotorPort node in the LEGO.NXT.v2.drive.config.xml file, should hold corresponding MotorA, MotorB or MotorC values. Conclusion Microsoft Robotics Studio combined with LEGO Mindstorms NXT robot can offer affordable and relatively easy way for any .NET developer to start writing real robotic applications. Yes this is just a basic app and so much more can be done but if you haven’t tried writing robotic apps yet, I hope this article can encourage you to try. I am sure you will be surprised how easy it is and also how much fun is to see something so much resembling a living creature coming from your own code.
https://www.simple-talk.com/dotnet/net-framework/using-microsoft-robotics-developer-studio-with-lego-mindstorms-nxt-robot/
CC-MAIN-2017-09
refinedweb
2,604
61.26
SQL Anywhere uses the following rules for encoding names that are not legal XML names (for example, column names that include spaces): XML has rules for names that differ from rules for SQL names. For example, spaces are not allowed in XML names. When a SQL name, such as a column name, is converted to an XML name, characters that are not valid characters for XML names are encoded or escaped. For each encoded character, the encoding is based on the character's Unicode code point value, expressed as a hexadecimal number. For most characters, the code point value can be represented with 16 bits or four hex digits, using the encoding _xHHHH_. These characters correspond to Unicode characters whose UTF-16 value is one 16-bit word. For characters whose code point value requires more than 16 bits, eight hex digits are used in the encoding _xHHHHHHHH_. These characters correspond to Unicode characters whose UTF-16 value is two 16-bit words. However, the Unicode code point value, which is typically 5 or 6 hex digits, is used for the encoding, not the UTF-16 value. For example, the following query contains a column name with a space: and returns the following result: Underscores (_) are escaped if they are followed by the character x. For example, the name Linu_x is encoded as Linu_x005F_x. Colons (:) are not escaped so that namespace declarations and qualified element and attribute names can be generated using a FOR XML query. When executing queries that contain a FOR XML clause in Interactive SQL, you may want to increase the column length by setting the truncation_length option.
http://dcx.sap.com/1201/fr/dbusage/ug-sqlxml-a--b-3488944b.html
CC-MAIN-2018-09
refinedweb
272
50.67
Using the function on GR-KURUMI, Analog input ADC vol. Handling analog signal by microcontroller In real world, all sort of phenomena are filled with analog signal while MCUs are in the digital world. Analog signal needs to be converted into digital signal somehow. An ADC ‘Analog to Digital Converter’ function, which converts analog signal into digital one, fortunately equipped with MCU in many cases, MCU can handle analog signals. Or HDC1000, temperature-humidity sensor, also has ADC, MCU can use digital signals directly. Unsettled analog signal Remember learning how to use the scale when we are elementary school student. Take an average by measurement several times or several rulers. The degree of the scale for typical measuring tools are at variance. In the analog world, every amounts has an error, which is unavoidable. The degree of measured values are unstable, of scale, the sensibility of visual inspection as well. Even the scale of a ruler made of metal,it's known to expand or shrink depend on ambient temperature. We can’t pursue the accuracy endlessly, it’s important to find an acceptable range, up to the xxx decimal place. When you measure analog signals, set the accuracy in advance. Roughness of Digital signal In digital world, defined clearly, the accuracy of the figure is infinite. On the other hand, analog signal has continuity, every point has error range. Think about resolution of ADC built in microcontroller.For example, the resolution of ADC on GR-KURUMI is 10bit which is allowed to show the figure in 1024 ways. divide by 1024 gives 3.2mV. Converting into digital signal; 0~1023. 0 is 0mV. 1 is 3.2mV, 2 is 6.4mV….. 1023 is 3296.8mV. So what's 1.6mV going to be?The output of ADC, 1.6mV will be either 0 (0mV) or 1 (3.2mV), the error is 1.6mV against actual value. If the resolution of ADC is 11bit, 1.6mV will be 1. How about 0.8mV? If the resolution of ADC is 12bit, 0.8mV will be 1. Converting from analog signal to digital signal, this approach of increment of resolution is often used to improve accuracy.However, in RL78/G13 case, the resolution of ADC is fixed at 10bit. Measuring temperature with a thermometer build in microcontroller RL78/G13 on GR-KURUMI has built in temperature inside, we can see temperature easily. Let’s try. Nothing special. Generate new project on WEB compiler, realize the function in source code 'gr_sketch.cpp' automatically. getTemperature(TEMP_MODE_CELSIUS); is the function which take temperature data with Celsius from a built-in thermometer. Open this program on GR-KURUMI through COM port, output the temperature only once. Measuring temperature with an analog temperature sensor When we say analog temperature sensor, there are several types. When we say analog temperature sensor, there are several types. Thermistor, platinum are popular, here we use TMP36GT9Z, IC type. Since supply voltage range is 2.7V~5.5V, MCU can be used with 3.3 V supply voltage. When outputting, sensor convert temperature into voltage in a ratio of 10mV per 1℃. Rising temperature by 1℃, 10mV increase in voltage. As for temperature sensor, usually making 25℃ a criterion since it’s normal temperature. Since TMP36GT9Z is set at 750mA when it is 25℃, when the voltage taking from ADC convert into temperature, specify the reference point at 25℃. With this sensor, measure temperature range up to 50℃. output value by sensor is 1.25V when its 50℃. Buy TMP36GT9Z from Marutsu. Setting the accuracy At the beginning, need to Know the accuracy on TMP36GT9Z. Datasheet shows the error range ±1℃ at 25℃, ±2℃ during -40℃~125℃. To recognize a change easier, set the accuracy to the first decimal place. Connection with temperature sensor Operation Here is the sample code for the program which output temperature to serial regularly. Improving accuracy Here is the output data as below. In a ratio of 10mV per 1℃, rising temperature by 0.1℃, 1mV increase in voltage. Considering that the resolution of ADC is 10bit, as I already mentioned, 3.2mV is the lowest figure digital signal can show. Is there any good ideas to improve accuracy to the first decimal place? The effective resolution come from standard voltage divided by ADC resolution. As for standard voltage, RL78/G13 on GR-KURUMI has three options such as 1.45V standard voltage generated inside, outside as well as power supply voltage (VCC). Please refer to the function "analogReference". Arguments DEFAULT:VCC INTERNAL:Built in voltage 1.45V EXTERNAL:Choose an option of “fixed at VCC on board” Assume the standard voltage is 1.45V, resolution is around 1.4mV, we can see some progress. However, as datasheet shows, internal voltage has an error range, 1.38V at minimum, 1.5V at maximum. Though it’s more stable than VCC which is affected by possible fluctuation of supply voltage. Usually, we take advantage of external standard voltage. Unfortunately it's not available on GR-KURUMI. There are many types of IC which allow to generate standard voltage. Pick from them on demand. Again, to improve accuracy, rather than the method of using hardware, extract the necessary data compensated from the deviation such as average of taking analog signal data several times, running mean, least-squares method. Verifying the measurement of the temperature How do we check whether the measured temperature by GR-KURUMI is corrected? A standard measuring tool or thermometer is required for comparing. Checking to see the error range of the thermometer widely appeared on the market.The error range ±1℃~2℃ is normal at 25℃。 Other temperature sensors of IC type as well. Searching high-precision measurement of temperature on the web, found this document. Click here. An error range ±1℃ would be no problem in the case of measurement of room temperature. ※Need to pick higher – precision one to reduce the electrical charges for air conditioner even a little. As standard, found the tester with thermometer function and its accessory K type of heat electric body in my house. K- type of heat electric body is a small sensor made by bonding together sheets of two different metals. As picture show, fitting on the tip of a cable in a bared state. IC type temperature sensor is much bigger than K- type of heat electric body, the difference in size affect on the one in thermal capacity. Bring in 50℃ ambient temperature, IC type temperature sensor react slow while K type of heat electric body react quickly. More over K type of heat electric body is sensitive to the slightly flowing air. Comparing the two, the same condition is required. As one of methods, standard thermometer and evaluation object are packed with cotton and aluminum foil to avoid wind, take some time to compare the two altering temperature in refrigerator or heating hotplate slowly. Record the output of the IC temperature sensor at each temperature and plot in the graph. In normal temperature range, as the output of IC temperature sensor tends to become the straight line on a certain degree, Let’s multiple the value coming from ADC by compensate coefficient taking from plot to approach actual measurement figure. Notice on mounting on board Even improved accuracy or compensated, if IC temperature sensor is mounted near the devices which consume big power such as micro controller, wireless module or power supply, it would be affected by them and can’t measure temperature correctly. Keeping away from the device consuming big power, need to mount the position not filled with heat. Also keep away from the case as IC temperature sensor is affected by heat capacity if it adhere to the case. Handling AC signal The trans has been distributed to measure AC current, widely used for the electronic kit because of energy-saving boom. Also used for measuring consumption current on electric apparatus or current on switchboard. The signal which ADC handle on GR-KURUMI would be DC in 0~3.3V or 0~1.45V. When measure AC, signal swing in a plus or minus direction. Acting isolation, take trans as picture shows, convert the output current at secondary side into voltage, then apply DC bias on the voltage so that microcontroller can handle. Take advantage of ADC dynamic range by adjustment of middle point and oscillation. For example, If standard voltage is 3.3V, set the middle point as 1.65V, oscillation as ±1.5V at maximum current. The value of the AC is calculated by Root Mean Squire (RMS). Graph shows the simulation plot that the oscillation of current is assumed to be ±1A in the peak. Actually, it's approximately 0.707Arms. Actual current waveform, it won’t be sine wave in good shape like this. Electric apparatus using switching power supply has a more complex waveform. This graph in excel file consist of 32pcs of data per one wave, described with plot by every 0.625ms. In East Japan, the frequency of power supply is 50Hz, 20ms period. 20ms divided by 32 data equals 0.625ms. When described in excel file, go backward the process that set the oscillation from the current value of 0.707Arms, then draw up 32 data, plot this data to draw sign waveform. Using ADC, let AC waveform convert into digital data by every 0.625ms. Remove the DC portion from each data due to applying DC bias. Definition of AC waveform is the waveform which the total amount of the oscillation will be zero for a period, if add digital data for a waveform, only DC portion will be left, average will be the DC value which is applied DC bias. Please refer to the formula in the left. If remove the DC portion from original data, only AC portion will be left. Average of integral each value’s squire for AC portion per one wave, take root of the value as actual data. Please refer to he formula in the left. Provisionally, take AC waveform as digital data with 1/32 period of one wave,The more complicate actual waveforms are,, the more data is needed to be converted with shorter period and higher resolution. Automation of taking analog signal Taking AC is necessary to be executed with right period and high frequency. With analogRead, it’s difficult to perform with a fixed time period and a constant CPU load since software is trigger in conversion to digital data. However RL78/G13 will be convert it automatically, storage it into RAM since it has timer coincide with ADC and DMAC. Let’s try this function. ※This function is not supported by library, need to set the resister of the peripheral function by yourself. Direct access to the resister of RL78/G13 As an advantage of library conforming to Arduino, even you don’t have much knowledge about hardware of RL78/G13, it would help operation in its own way.Apart from library support, let’s operate microcontroller. Handling register, include these file as below. #include <iodefine.h> #include <iodefine_ext.h> An option for trigger of ADC conversion Here is the block diagram for ADC on RL78/G13. Please refer to the point in the red circle for the input for the trigger of ADC conversion. The interruption generated at RTC would be a trigger for INTRTC. The interruption of timer 0, channel 1 would be a trigger for INTTM01. The interruption of 12bit interval timer would be a trigger for INTIT. INTRTC is not available since RTC is going to be used as clock.As for INTTM01, original oscillation of timer is 32MHz, the system clock generated by high speed on-chip oscillator. Accuracy of oscillation is within +/-1% in normal temperature range if operation voltage is 3.3V. INTIT can’t be used since it’s working on management per millimeters unit. INTTM01 is used by divided original oscillation. The issue is if we can set the ratio by which original oscillation is divided without residue. Divided 32MHz by 50Hz x 32 gives you just 20000. INTTM01 is an option for trigger. Showing how to reset the value of timer as below. Using scan mode ADC on RL78/G13 has scan mode which can convert several analog inputs all at once. It’s helpful when you need to handle several inputs. Please keep in mind the followings. Under scan mode function, make sure to select four channels, moreover there is a constraint on channel combination. ※Please refer to the chart. Please don’t select the terminals having set as digital for conversion channel. Let’s scan ANI0~ANI3 this time ※In GR-KURUMI case, ANI0 is connect to 3.3V, ANI1 connected to GND. Both ANI2 and ANI3 are available for analog input. Triggering as INTTM01 50HZ x 32 , generate the conversion data with 8byte by every 0.625ms. Showing how to reset the value of ADC. Using DMAC The data converted by scan mode will be signal-processed after it’s transferred into memory. To have AC wave form signal processed, the data is required for a wave portion. It’s assumed to be 32 data this case. For scan mode, 32 x 4 x 2byte of the data is transferred to memory. DMAC 'Direct Memory Access Controller' would be help you.Under specified condition, DMAC automatically transfer the data from peripheral I/O to memory or from memory to peripheral I/O, instead of CPU. The interruption from ADC is a trigger for DMAC this time.When the data transfer is completed preset number of times, DMAC can happen interruption to CPU.CPU can execute other tasks until the data transfer is complete, process the data later. As of setting of DMAC, original data is data-register of ADC and transferred to SRAM area secured in global variables.The size of data is 16bit, the times of transfer is 32x4times. Laminate buffer for data storage, in order to prevent it from being overwritten by DMAC while CPU signal processing. Registration of user interruption For procedure for interruption, please refer to interrupt_handlers.c under gr_common/RLduino78/portable/e2studio/RL78 DMA1 interruption will be INT_DMA1. This is the program calling for procedure of DMA interruption. 【The example for procedure of triggering ADC】 This is the program for procedure of triggering ADC. Actual signal processing is not mentioned. MVP information@chobichan General hard engineer.. submitting his writing for technical magazine occasionally. twitter account:
http://gadget.renesas.com/en/atelier/article_06.html
CC-MAIN-2018-43
refinedweb
2,413
58.69
Opened 6 years ago Last modified 5 years ago #4124 enhancement new Re-implement twisted.mail.imap4's parsers using real parser technology Description twisted.mail.imap4 deals with the rather complicated task of parsing the IMAP4 protocol (in both directions - the protocol is not symmetrical) with a series of alternately naive, gross, broken, inefficient, poorly tested, and very nearly unmaintainable hacks, tricks, kludges, and plain stupidity (I can say this, I wrote most of it). #4049 has at last convinced me that this parsing code must be rewritten. This will be difficult for a number of reasons: - The IMAP4 grammar is somewhat complicated. This is probably surmountable, but it would be good if someone with significant experience developing parsers could be involved in the process. - There is a lot of grammar to account for. - Quirks of the existing parser are exposed to the application-level APIs. The most reasonable resolution to this may be the introduction of new APIs and the deprecation of old ones. Of course, figuring out how to continue to support the old APIs with a new parser in place may be tricky. - The client and server presently approach the problem from different directions, sharing almost none of their parsing code (but of course not exactly none - that would be too easy). - The current parser is wrong in a number of places, yet all the existing tests are passing, so the existing test suite is clearly not sufficient to demonstrate that the new parser is correct. I think it would be nice if this opportunity were taken to approach parser development differently than it is usually approached in Twisted. If possible, declaratively specifying much or all of the grammar and using this to automatically generate the parser would be preferable (and if we can do it here, I doubt any other protocols will give us much trouble). However, I won't say this is necessary outright, as it is more important to have a working parser than to have a parser with a neat implementation. See these other open IMAP4-related tickets for some idea of the current problems: Change History (9) comment:1 Changed 6 years ago by khorn - Cc khorn added comment:2 Changed 6 years ago by ralphm comment:3 Changed 6 years ago by darkporter I remember reading about how Zed Shaw used Ragel to write mongrel (ruby web server). I wonder if anything similar exists for python? It might be useful for IMAP. comment:4 Changed 6 years ago by khorn For no particular reason, I was thinking about this today, and I think a "plan" for doing this might look something like: - Decide what should be the "public" API for IMAPServer/IMAPClient. Make everything else "private" (is there a convention for naming private methods in the Twisted coding standard? I didn't see one...) and deprecate the public interfaces of those attributes/methods. - Isolate the parsing code. Its' kind of all over the place at the moment. A given IMAP line in IMAPServer for instance, goes though a bunch of functions and gets parsed a bit at a time in lots of different places. This by itself isn't sucha a bad thing, but it gets mixed up with a bunch of the other code (like the protocol code, etc.) and needs to be isolated better. Bits of code (functions or whatever) should either be parsing, or doing something else. Ideally you'd end up with something like (simplified!): def lineReceived(self, line): # pre-parsing stuff here func, args, kwargs = parse_line(line) func(*args, **kwargs) # post-parsing stuff here or maybe even def lineReceived(self, line): # pre-parsing stuff here partial_func = parse_line(line) partial_func() # post-parsing stuff here where parse_line() does some partial function application. Not sure if that's really useful though. At any rate, once the parsing code is more isolated, it will be much easier to experiment with various parsing strategies. I'm not really sure this is even feasible until at least some isolation work is done. comment:5 Changed 6 years ago by exarkun As far as the implementation of parsing goes, that sounds fine. It doesn't address the really tricky part, though, which is the structure of the objects created from parsing server responses and passed back to application code. That's what I was trying to describe with the third point in the ticket description. This is most evident in for the fetch methods. Server responses are parsed into complicated nested list/tuple/string structures which aren't really ideal to work with. These will probably have to be reproduced based on the results of the new parser to preserve backwards compatibility, but we'll want a new, better structure at some point too. comment:6 Changed 6 years ago by khorn AH, yes, I see...I had mostly been looking at the server parsing. Still, I don't think this is necessarily a _huge_ obstacle, though it doesn't look like it will be a lot of fun to straighten out. At least, it's not much huger that replacing the parsing code of the module :). comment:7 Changed 5 years ago by khorn An interesting experiment in this arena might be using pyMeta to reimplement a small part of the parsing here, for example parseNestedParens. If I have time I might do this, but I thought I'd mention it here in case a) someone else thinks it's worth pursuing, and b) they get to it before I do. comment:8 Changed 5 years ago by khorn comment:9 Changed 5 years ago by <automation> - Owner exarkun deleted For the XPath-ish parsing in Words, yapps2 is used. Maybe that is a way forward?
http://twistedmatrix.com/trac/ticket/4124
CC-MAIN-2015-40
refinedweb
955
60.35
ASUKA - Snackbars, Dialogs and more, the simple way. A Simple and Clean approach to Snackbars, Dialogs, ModalSheets and more in a single provider. Explore the docs » · Report Bug · Request Feature Table of Contents About The Project Asuka is a Dart package that aims to simplify and keep a clean approach when implementing some visual elements from Flutter like Snackbars, Dialogs and ModalSheets. With few and intuitive lines of code you can have those in your project without the hassle of having to code them from scratch, while having the option of quickly removing them if need be. This project is distributed under the MIT License. See LICENSE.txt for more information. Sponsors Getting Started To get Asuka in your project follow either of the instructions below: a) Add Asuka as a dependency in your Pubspec.yaml: dependencies: asuka: any b) Use Dart Pub: dart pub add asuka How to Use Add the following code where you call your Material App: import 'package:asuka/asuka.dart'; MaterialApp( builder: Asuka.builder, navigatorObservers: [ Asuka.asukaHeroController //This line is needed for the Hero widget to work ], ); Now you just have to call the named constructors for each widget that you want to use: import 'package:asuka/asuka.dart'; Asuka.showSnackBar(SnackBar( content: Text("Hello World"), )); AsukaSnackbar.success("success").show(); For more examples, please refer to the Documentation Features - ✅ Snackbars - ✅ Dialog - ✅ BottomSheet - ✅ ModalBottomSheet - ✅ Overlay Right now this package has concluded all his intended features. If you have any suggestions or find something to report, see below how to contribute to appropriate tag. Don't forget to give the project a star! Thanks again! - Fork the Project - Create your Feature Branch ( git checkout -b feature/AmazingFeature) - Commit your Changes ( git commit -m 'Add some AmazingFeature') - Push to the Branch ( git push origin feature/AmazingFeature) - Open a Pull Request Remember to include a tag, and to follow Conventional Commits and Semantic Versioning when uploading your commit and/or creating the issue. Flutterando Community Acknowledgements Thank you to all the people who contributed to this project, without you, this project would not be here today. Maintaned by Built and maintained by Flutterando.
https://pub.dev/documentation/asuka/latest/index.html
CC-MAIN-2022-40
refinedweb
354
52.6
Hooks were introduced in React v16.8.0. Prior to that, if we had written a functional component and wanted to add state or make use of lifecycle methods to perform operations such as data fetching and manual DOM manipulation, the functional component had to be converted into class based component. However, introduction of Hooks made adding state and performing those operations in functional component possible. It also helped in keeping the mutually related code together rather than splitting the code based on lifecycle methods. Hooks don't work inside classes rather they let us work with React without the need for class. In this post, we will learn about the built-in useState() Hook and how to use it in a functional component. We will also understand the difference in initializing, updating and accessing the state in class component as compared to functional component. Following are the two rules of Hooks that needs to be followed: Hooks should always be called at the top level of the React function which means it shouldn't be called inside loops, conditionals or nested functions. This is done to ensure that Hooks are called in the same order each time a component renders. Never call Hooks from regular JavaScript functions. Instead, call it from React function components or custom Hooks. As the name suggests, useState Hook is used to add state to function components. The syntax for useState is as below: const [state, setState] = useState(initialState); // assigns initialState to state // setState function is used to update the state useState() returns an array with exact two values. Array destructuring can be used to store these values in different variables. The first value returned represents the state and the second value returned is a function that can be used to update the state. You can give any name to these two variables. For our understanding, we'll name the state variable as state and the function that updates it as setState. You can follow this convention of assigning any name to state variable and then prefixing it with 'set' to form the function name. The 'initialState' argument passed to useState sets the initial state. On subsequent re-renders, state is updated through the setState function returned from the useState Hook. Now, let's take a look at the following code block which represents a class component with state import React, { Component } from "react"; export default class App extends Component { constructor(props) { super(props); this.state = { weather: 'hot', disabled: false } } render() { return ( <div> <p>The weather is {this.state.weather}</p> <button onClick={() => this.setState({weather: 'cloudy', disabled: !this.state.disabled})} disabled={this.state.disabled}> Change weather </button> </div> ); } } When the above class component gets rendered to the screen, you get a paragraph The weather is hot with a 'Change weather' button below it. On clicking the button, the component re-renders and output changes to The weather is cloudy with the button getting disabled. In a class component, you can initialize state in the constructor by using this.state. In the above example, it is initialized to {weather: 'hot', disabled: false}. Any update to state is done through this.setState and respective values can be accessed using this.state.weather and this.state.disabled. The state is defined as an object and all the state updates done through this.setState is merged into that object as class component can have a single state object only. Therefore, {weather: 'cloudy', disabled: !this.state.disabled} gets merged with the previous value and state is updated. In order to initialize, update or access any value from state in a class component, you always need to use this keyword. Now, let's take a look at the following functional component using the State Hook that works the same way as the earlier class component // import useState Hook from "react" package import React, { useState } from "react"; export default function App() { const [weather, setWeather] = useState('hot'); // "weather" value initialized to "hot" const [disabled, setDisabled] = useState(false); // "disabled" value initialized to "false" return ( <div> <p>The weather is {weather}</p> <button onClick={() => { setWeather('cloudy'); // setWeather('cloudy') updates the "weather" to "cloudy" setDisabled(!disabled); // setDisabled(!disabled) updates the "disabled" to "true" }} disabled={disabled}>Change weather</button> </div> ); } In order to use state in functional component, you first need to import useState Hook from React. Unlike class component where you can have a single state object only, functional component allows you to have multiple state variables. Here, weather and disabled state variables are initialized to the argument passed to useState Hook. This argument can be of any type such as number, string, array or object unlike class component where state is initialized to object only. On clicking the button, setWeather and setDisabled functions are called with new state values passed to it. React will then re-render the component by passing the new weather and disabled values to it. In a functional component, updating a state value always replaces the previous value unlike class component where state updates are merged. In the above example, new state values are not dependent on previous state values. Therefore, we directly pass new value to state update function. In scenarios where new state value depends on previous state value, you can use the following functional update format to update the state. setState(previousStateValue => { // newStateValue determined using previousStateValue return newStateValue; }) This functional update format is used to update the state depending on the previous state value. In this post, you learnt about the useState() Hook that makes it possible to use state in a functional component without transforming it into a class component. You learnt how to initialize, update and access the state variables in a functional component using Hooks. Thank you for taking the time to read this post 😊 Hope this post helped you!! Please share if you liked it. I would love to connect with you on Twitter. Do share your valuable feedback and suggestions you have for me 👋
https://raunaqchawhan.hashnode.dev/understanding-the-react-usestate-hook
CC-MAIN-2022-05
refinedweb
992
53.71
This preview shows pages 1–3. Sign up to view the full content. 1 Announcements - Lecture 11 • Read “Goto” Considered Harmful – goto statements are no longer allowed – All programs can be implemented with only sequence, selection and iteration logic constructs – Example in the book on pg. 114 is wrong! • Assignment 3 out on Monday – Coding standards are in effect • Exam 1 a week from today in class (Ch. 1-9) – Sample exam to be posted on Tuesday • Topics for today – Functions (Ch. 9) and functional programming Book Example – pg. 114 • Problem – you need to break out of a loop from within a switch construct or a nested loop /* with goto */ while ( . . . ) { switch (expression) { case 1: … . . .goto loopDone; } } loopDone: . . . /* without goto */ int fag = FALSE; { switch (expression) { case 1: … . . {fag = TRUE; break;} } } . . . Functions in a Nutshell • A function is a series of statements called by their given name (e.g. main ) • It is the essential building block for complex C programs – It is how we divide our large program into smaller sub- programs to manage complexity • Behavior is similar to a mathematical function: y = f ( x,z ) – Arguments are values passed in ( ) – optional – Returns a value through the function name – optional • Many previously written standard functions are in the library for your use • You can write your own functions too, and then call them or reuse them A Function as a Module values sent in from function calling statement via the arguments supplied in ( ) (optional) Resultant value returned (optional), or function actions that have some other effect Function operation As in, for example: double x, y, z; /* assume they get values */ y = sqrt (x); getchar ( ); printf (“hello\n”); z = average (x, y); double average (double a, double b) { return (a + b) / 2.0; } C Standard Library Functions • See appendix D of the book for all the functions available • In various library (header) files (.h) – stdlib – stdio – math – time – ctype – string – assert – a few others Top Down Functional Programming main sub1 sub2 sub3 sub4 subsub1 subsub2 subsub3 subsub4 sss1 sss4 calls calls calls calls A ±unctional hierarchy diagram View Full Document This preview has intentionally blurred sections. 2 How does this work? • Partitioning the problem – Let’s us divide a big problem into small problems – No one part is highly complex – However a balance must be achieved between too many and too few functions • Too few may lead to complexity of the size of each • Too many may lead to complexity of the number of interconnects • Many ways to partition a problem – this is one of the fundamentals of the craft of design • Identifying relatively independent functions is key to – Reducing complexity – Increasing clarity – Increasing reusability – Modularizing our programs • A function operates on data passed through the This note was uploaded on 03/15/2010 for the course EE 16005 taught by Professor Krasner during the Spring '10 term at University of Texas at Austin. - Spring '10 - KRASNER Click to edit the document details
https://www.coursehero.com/file/5818787/lecture11-feb12/
CC-MAIN-2017-17
refinedweb
491
54.15
The final is a very important keyword in java, which is used to restrict user. A programmer must not declare a variable or class with the name "Final" in a Java program. We can have final methods, final classes, final data members, final local variables and final parameters. When an array is declared as final, the state of the object stored in the array can be modified. It must be made immutable so that modifcations are not made. The final keyword can be applied to: Syntax of final class:- final class test { //body of class // final class } syntax of final variable:- class test1 { final int=20;//final variable } Syntax of final method class test3 { final void run(){// final method } Note: Exampleof final jeyword in Java: public class FinalExample { public static void main(String[] args) { int variable=10; System.out.println("Final Variable:"+variable); variable=15; } public final void getName() { String finalmethod="value"; System.out.println("finalmethod :"+finalmethod); } } Output If you enjoyed this post then why not add us on Google+? Add us to your Circles Liked it! Share this Tutorial Discuss: Java final keyword Post your Comment
http://roseindia.net/java/example/java/core/java-final-keyword.shtml
CC-MAIN-2014-42
refinedweb
187
53.81
How to create & query images and files using GraphQL with AWS AppSync, AWS Amplify, and Amazon S3 Storing and querying for files like images and videos is a common requirement for most applications, but how do you do this using GraphQL? One option would be to Base64 encode the image and send as a string in the mutation. This comes with disadvantages like the encoded file being larger than the original binary, the operation being computationally expensive, and the added complexity around encoding and decoding properly. Another option is to have a separate server (or API) for uploading files. This is the preferred approach and the technique we will be covering in this tutorial. To view or try out the final example project, click here. How it all works You typically would need a few things to make this work: - A GraphQL API - A storage service or database for saving your files - A database to store the GraphQL data including a reference to the location of the file Take for example the following schema for a product in an E-commerce app: type Product { id: ID! name: String! description: String price: Int image: ? } How could we use this image field and make it work with our app to store and reference an image? Let's take a look at how this might work with an image stored in Amazon S3. Using Amazon S3 there are two main types of access: private and public. Public access means anyone with the file url can view or download it at any time. In this use case, we could reference the image url as the image field in the GraphQL schema. Since the image url is public anyway, we don't care who can view the image. Private access means that only authenticated users can view or download the file. In this use case, we would only store a reference to the image key (i.e. images/mycoolimage.png) as the image field in the GraphQL schema. Using this key, we can fetch a temporary signed url to view this image on demand from S3 whenever we would like it to be viewed by someone. In this tutorial, you'll learn how to do both. Creating the client In this tutorial I will be writing the client code in React, but you can use Vue, Angular, or any other JavaScript framework because there is minimal code that is React specific. Create a new client project, change into the directory and install the amplify and uuid dependencies: npx create-react-app gqlimages npm install aws-amplify aws-amplify-react uuid cd gqlimages Public access The first example we will create is a GraphQL API that has public image access. The GraphQL type that we will be working with is a Product with an image field. We want this product's image to be public so it can be shared and visible to anyone viewing the app, regardless if they are signed in or not. The GraphQL schema we will use is this: type Product { id: ID! name: String! description: String price: Int image: String } How could we implement the API for this? For mutations - Store the image in S3 - Send a mutation to create the Product in the GraphQL API using the image reference along with the other product data For Queries - Query the product data from the GraphQL API. Because the image url is public, we can just render the image field immediately. Creating the services To build this API, we need the following: - S3 bucket to store the image - GraphQL API to store the image reference and other data about the type - Authentication service to authenticate users (only needed in order to upload files to S3) The first thing we will want to do is create the authentication service. To do so, we'll initialize an Amplify project and add authentication. If you have not yet installed & configured the Amplify CLI, click here to view a video walkthrough. amplify init amplify add auth ? Do you want to use the default authentication and security configuration? Default configuration ? How do you want users to be able to sign in when using your Cognito User Pool? Username ? What attributes are required for signing up? Email Next, we'll create the storage service (Amazon S3): amplify add storage ? Please select from one of the below mentioned services: Content (Images, audio, video, etc.) ? Please provide a friendly name for your resource that will be used to label this category in the project: gqls3 ? Please provide bucket name: <YOUR_UNIQUE_BUCKET_NAME> ? Who should have access: Auth and guest users ? What kind of access do you want for Authenticated users? ❯◉ create/update ◉ read ◉ delete ? What kind of access do you want for Guest users? ◯ create/update ❯◉ read ◯ delete Finally, we'll create the GraphQL API: amplify add api ? Please select from one of the below mentioned services (Use arrow keys): GraphQL ? Provide API name: (gqls3) ? Choose an authorization type for the API: API key ? Do you have an annotated GraphQL schema? N ? Do you want a guided schema creation? Y ? What best describes your project: Single object with fields ? Do you want to edit the schema now? Y When prompted, update the schema located at /amplify/backend/api/gqls3/schema.graphql with the following: type Product @model { id: ID! name: String! description: String price: Int image: String } Next, we can deploy the API using the following: amplify push ? Next, we'll configure index.js to recognize the Amplify app: import Amplify from 'aws-amplify' import config from './aws-exports' Amplify.configure(config) Now that the services have been deployed, we need to update the S3 bucket to have a public /images folder so that anything stored in the folder can be viewed by anyone. Warning: when making an S3 folder public, you should make sure that you never store any sensitive or private information here as the folder is completely open for anyone to view it. In this case, we are simulating an E-commerce app where we have public images for our products that would go on the main site. Open the S3 console at and find the bucket that you created in the previous step. Next, click on the Permissions tab to update the bucket policy. Update the policy to the following. You need to update the Resource field to your bucket's resource name (i.e. the arn:aws:s3:::gqlimages6c6fev-dev needs to be replaced with the name for your bucket): { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::gqlimages6c6fev-dev/public/images/*" } ] } two main functions: createProduct- uploads the product image to S3 and saves the product data to AppSync in a GraphQL mutation listProducts- queries the GraphQL API for all products import React, { useEffect, useState } from 'react'; import { Storage, API, graphqlOperation } from 'aws-amplify' import uuid from 'uuid/v4' import { withAuthenticator } from 'aws-amplify-react' import { createProduct as CreateProduct } from './graphql/mutations' import { listProducts as ListProducts } from './graphql/queries' import config from './aws-exports' const { aws_user_files_s3_bucket_region: region, aws_user_files_s3_bucket: bucket } = config function App() { const [file, updateFile] = useState(null) const [productName, updateProductName] = useState('') const [products, updateProducts] = useState([]) useEffect(() => { listProducts() }, []) // Query the API and save them to the state async function listProducts() { const products = await API.graphql(graphqlOperation(ListProducts)) updateProducts(products.data.listProducts.items) } function handleChange(event) { const { target: { value, files } } = event const fileForUpload = files[0] updateProductName(fileForUpload.name.split(".")[0]) updateFile(fileForUpload || value) } // upload the image to S3 and then save it in the GraphQL API async function createProduct() { if (file) { const extension = file.name.split(".")[1] const { type: mimeType } = file const key = `images/${uuid()}${productName}.${extension}` const url = `{bucket}.s3.${region}.amazonaws.com/public/${key}` const inputData = { name: productName , image: url } try { await Storage.put(key, file, { contentType: mimeType }) await API.graphql(graphqlOperation(CreateProduct, { input: inputData })) } catch (err) { console.log('error: ', err) } } } return ( <div style={styles.container}> <input type="file" onChange={handleChange} style={{margin: '10px 0px'}} /> <input placeholder='Product Name' value={productName} onChange={e => updateProductName(e.target.value)} /> <button style={styles.button} onClick={createProduct}>Create Product</button> { products.map((p, i) => ( <img style={styles.image} key={i} src={p.image} /> )) } </div> ); } const styles = { container: { width: 400, margin: '0 auto' }, image: { width: 400 }, button: { width: 200, backgroundColor: '#ddd', cursor: 'pointer', height: 30, margin: '0px 0px 8px' } } export default withAuthenticator(App); To launch the app, run npm start. To see the completed project code, click here and open the src/Products.jsfile. Private Access The next example we will create is a GraphQL API with a type that has a private image field. This image can only be accessed by someone using our app. If someone tries to fetch this image directly, they will not be able to view it. For the image field, we'll create a GraphQL type type that holds all of the information we need in order to create and read private files from an S3 bucket, including the bucket name and region as well as the key we'd like to read from the bucket. The GraphQL type that we will be working with is a User with an avatar field. We want this avatar image to be private so it can be only be visible to someone signed in to the app. The GraphQL schema we will use is this: type User { id: ID! username: String! avatar: S3Object } type S3Object { bucket: String! region: String! key: String! } How could we implement the API to make this work? For mutations - Store the image in S3 - Send a mutation to create the User in the GraphQL API using the image reference along with the other product data For Queries - Query the product data from the API (including the image reference) - Get a signed URL for the image from S3 in another API call To build this app, we need the following: - Authentication service to authenticate users - S3 bucket to store image - GraphQL API to store the image reference and other data about the type Building the app If you did not build the app in the previous example, go back and build the above project (create the authentication service, GraphQL API, and S3 bucket) in order to continue. We can now update the schema located at /amplify/backend/api/gqls3/schema.graphql and add the following types: type User @model { id: ID! username: String! avatar: S3Object } type S3Object { bucket: String! region: String! key: String! } Next, we can deploy the changes: amplify push ? Do you want to update code for your updated GraphQL API Yes ? Do you want to generate GraphQL statements (queries, mutations and subscription) based on your schema types? This will overwrite your cu rrent graphql queries, mutations and subscriptions Yes three main functions: createUser- (uploads the user image to S3 and saves the user data to AppSync in a GraphQL mutation) fetchUsers- Queries the GraphQL API for all users fetchImage- Gets the signed S3 url for the image in order for us to render it and renders it in the UI. import React, { useState, useReducer, useEffect } from 'react' import { withAuthenticator } from 'aws-amplify-react' import { Storage, API, graphqlOperation } from 'aws-amplify' import uuid from 'uuid/v4' import { createUser as CreateUser } from './graphql/mutations' import { listUsers } from './graphql/queries' import { onCreateUser } from './graphql/subscriptions' import config from './aws-exports' const { aws_user_files_s3_bucket_region: region, aws_user_files_s3_bucket: bucket } = config const initialState = { users: [] } function reducer(state, action) { switch(action.type) { case 'SET_USERS': return { ...state, users: action.users } case 'ADD_USER': return { ...state, users: [action.user, ...state.users] } default: return state } } function App() { const [file, updateFile] = useState(null) const [username, updateUsername] = useState('') const [state, dispatch] = useReducer(reducer, initialState) const [avatarUrl, updateAvatarUrl] = useState('') function handleChange(event) { const { target: { value, files } } = event const [image] = files || [] updateFile(image || value) } async function fetchImage(key) { try { const imageData = await Storage.get(key) updateAvatarUrl(imageData) } catch(err) { console.log('error: ', err) } } async function fetchUsers() { try { let users = await API.graphql(graphqlOperation(listUsers)) users = users.data.listUsers.items dispatch({ type: 'SET_USERS', users }) } catch(err) { console.log('error fetching users') } } async function createUser() { if (!username) return alert('please enter a username') if (file && username) { const { name: fileName, type: mimeType } = file const key = `${uuid()}${fileName}` const fileForUpload = { bucket, key, region, } const inputData = { username, avatar: fileForUpload } try { await Storage.put(key, file, { contentType: mimeType }) await API.graphql(graphqlOperation(CreateUser, { input: inputData })) updateUsername('') console.log('successfully stored user data!') } catch (err) { console.log('error: ', err) } } } useEffect(() => { fetchUsers() const subscription = API.graphql(graphqlOperation(onCreateUser)) .subscribe({ next: async userData => { const { onCreateUser } = userData.value.data dispatch({ type: 'ADD_USER', user: onCreateUser }) } }) return () => subscription.unsubscribe() }, []) return ( <div style={styles.container}> <input label="File to upload" type="file" onChange={handleChange} style={{margin: '10px 0px'}} /> <input placeholder='Username' value={username} onChange={e => updateUsername(e.target.value)} /> <button style={styles.button} onClick={createUser}>Save Image</button> { state.users.map((u, i) => { return ( <div key={i} > <p style={styles.username} onClick={() => fetchImage(u.avatar.key)}>{u.username}</p> </div> ) }) } <img src={avatarUrl} style={{ width: 300 }} /> </div> ) } const styles = { container: { width: 300, margin: '0 auto' }, username: { cursor: 'pointer', border: '1px solid #ddd', padding: '5px 25px' }, button: { width: 200, backgroundColor: '#ddd', cursor: 'pointer', height: 30, margin: '0px 0px 8px' } } export default withAuthenticator(App, { includeGreetings: true }) To launch the app, run npm start. To view or try out the final example project, click here.. Be the first one to comment
https://dabit3.hashnode.dev/managing-file-and-images-in-graphql-with-aws-amplify-and-aws-appsync-cjxg1oh6c001301s10oepur52
CC-MAIN-2019-39
refinedweb
2,211
55.74
Session is a data structure saved on the server-side, which is used to track the status of users. This data can be saved in clusters, databases, and files. Cookie is a mechanism for clients to save user data, and it is also a way to implement Session. This article introduces how to manage Session and Cookie in Python flask framework. 1.What is Session & Cookie. 1.1 What is Session. Because HTTP protocol is a stateless protocol, when the web server needs to record the user’s status, it needs to use some mechanism to identify the specific user. This mechanism is the so-called Session. In a typical scenario, such as a shopping cart, when someone clicks the order button to put a book into the shopping cart, because the HTTP protocol is stateless, you don’t know which user operates it. Therefore, the server needs to create a specific session for the user to identify and track it. Only in this way can you know how many books are there in the shopping cart. This session is saved on the server-side and has a unique session ID. 1.2 What is Cookie. How does the server identify a specific client user? This is when cookies come to the stage. Each time when a client sends an HTTP request to the web server, it will send the corresponding cookie information to the server. Most applications use cookies to implement session tracking. When creating a session for the first time, the server will tell the client that it needs to record a session ID in the cookie, and later the client will send the session ID to the server for each HTTP request, then the web server can know which client sends the request for each time. 2. How To Manage Session & Cookie In Python Flask Framework. The session mechanism in Flask is to encrypt the sensitive data and put it into a session, then save the session into a cookie. When the client makes an HTTP request for the next time, the session data is directly obtained from the cookie sent by the web browser, and then Flask program can decrypt the original session data from it. This operation saves more server overhead because the data is stored in the client. You may worry about the security of this method because all the data is stored in the local browser, which is easy to be stolen, but the security is always relative, and Flask also has its own special encryption algorithm for Session, so you don’t have to pay too much attention to the security. 2.1 Flask Session Management. - First, we need to import the Flask session package. from flask import session - Generate a SECRET_KEY value. The SECRET_KEY is used to encrypt and decrypt session data, and if your secret key changes every time when you start the server, you can’t use the previous SECRET_KEY to decrypt session data. We can set it to a fixed value in Flask configuration file config.py like below. import os import binascii # Generates a random 24 bit string secret_key_value = os.urandom(24) # Create the hex-encoded string value. secret_key_value_hex_encoded = binascii.hexlify(out) # Set the SECRET_KEY value in Flask application configuration settings. app.config['SECRET_KEY'] = secret_key_value_hex_encoded - Set data in Flask session. Because session and cookie are dictionaries in the form of key-value pairs, you can add them directly by dictionary method. session['email'] = '[email protected]' - Get Flask session data value by key. session.get('email') session['email'] - Set Flask session expiration time ( if it is not set, the session will expire automatically when the web browser exit ). # Set session parameter PERMANENT_SESSION_LIFETIME's value in config.py file. The PERMANENT_SESSION_LIFETIME's value is a datetime.timedelay data type. app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) session.permanent = True - Remove Flask session data. # Remove one session data. session.pop('username') del session['username'] # Remove all session data. session.clear() 2.1 Flask Cookie Management. - Set cookie. The default cookie is a temporary cookie, which will be invalid when the browser is closed. You can set cookie max_age value to set the cookie validation period in seconds. # Get the web server HTTP response. resp = make_response("success") # Set cookie in the HTTP response object. The cookie name is cookie_name, the cookie value is cookie_value, it will expire in 3600 seconds. resp.set_cookie("cookie_name", "cookie_value", max_age=3600) - Get cookie. Get the cookie through request.cookies, it returns a dictionary object, you can get the corresponding value in the dictionary. # Get request cookies. cookies = request.cookies # Get cookie value by cookie name. cookie_value = cookies.get("cookie_name") - Remove cookie. Delete cookie use HTTP response object’s deleting_cookie(cookie_name)method. The deletion here just makes the cookie expire, not really delete the cookie. # Get http response object. resp = make_response("del success") # Invoke delete_cookie() method to delete a cookie by cookie name. resp.delete_cookie("cookie_name") - Flask Manage Cookie Example Source Code. # Import Flask, make_response, request package. from flask import Flask, make_response, request app = Flask(__name__) # Add /set_cookie url route. @app.route("/set_cookie") def set_cookie(c_1, p_1, c_2, p_2, c_3, p_3): resp = make_response("success") ''' Set cookie, the default cookie is a temporary cookie which will expire when web browser close. ''' resp.set_cookie(c_1, p_1) resp.set_cookie(c_2, p_2) # Set cookie expiration time in 3600 seconds through max_age cookie attribute. resp.set_cookie(c_3, p_3, max_age=3600) return resp # Add /get_cookie url route. @app.route("/get_cookie") def get_cookie(cookie_name): """ Get a cookie through request.cookies. It will return a dictionary object. """ cookie_value = request.cookies.get(cookie_name) return cookie_value # Add /delete_cookie url route. @app.route("/delete_cookie") def delete_cookie(cookie_name): """ Remove cookie by HTTP response object's delete_cookie(cookie_name) method. It just make the cookie expire not really remove the cookie. """ # Get http response object. resp = make_response("del success") # Remove the cookie by invoking the delete_cookie() method. resp.delete_cookie(cookie_name) return resp if __name__ == '__main__': app.run(debug=True)
https://www.code-learner.com/how-to-use-session-and-cookie-in-python-flask-framework/
CC-MAIN-2021-43
refinedweb
987
59.09
How does React componentDidUpdate work I previously wrote an article about componentDidMount, and how that’s a great lifecycle to make API calls, and to make DOM manipulation. But I had a couple questions about another use case. These are questions that you may have as well. - Is there a better place to make DOM manipulation? - How to do I continue making API calls after React state or props have changed? After doing a bit of Googling, I found out about componentDidUpdate. This was the answer to my problems, and it might be yours too. What is componentDidUpdate? This is a lifecycle in React that gets called right after a change in props or state change has occurred. componentDidUpdate(prevProps, prevState, snapshot) This method provides the previous props and state values. This way it allows you to do a comparison of a before and current snapshot. componentDidUpdate(prevProps, prevState) { if (prevProps.foo !== this.props.foo) { // ... do something } } If you’re curious to know what the snapshot variable is about checkout this article. When does componentDidUpdate get called? To be more specific here is how the breakdown looks like componentWillReceiveProps() shouldComponentUpdate() componentWillUpdate() render() componentDidUpdate() componentDidUpdate is always the last lifecycle to get called for a React component. componentDidUpdate does not get called after the first initial render() lifecycle. When to use componentDidUpdate method? Well this goes back to my initial problems. DOM manipulation after render Sometimes third party libraries don’t have a React version, and requires to manipulate the DOM directly. For example, this site uses PrismJS to highlight code blocks. And the content is being brought over an API. I need to highlight all the code blocks that are found once the content is dumped onto the page. import Prism from 'prismjs'; class PostPage extends React.Component { componentDidMount() { // Takes care of the first render Prism.highlightAll(); } componentDidUpdate() { // Takes care of all other renders Prism.highlightAll(); } render() { // ... rendering API content } } In the example above, I’m using the componentDidMount lifecycle to highlight all <code> blocks. And just incase the PostPage component is going to get new props or state updates, I need run Prism.highlightAll() again to make sure my <code> blocks stay pretty. API Calls This is also a great place to make additional API calls after a certain React prop or state has changed. For example, let’s say a React component can only grab user data after certain prop has been passed down. class UserNavBar extends React.Component { componentDidUpdate() { if (this.props.isAuth) { // ... fetch user data (profile pic, name, email, etc) } } render() { // ... rendering user nav bar content } } class AuthWrapper extends React.Component { state = { isAuth: false, }; componentDidMount() { this.setState({ isAuth: true }) } render() { return <UserNavBar isAuth={this.state.isAuth} /> } } Change state or dispatch with Redux This is also a great place to update your React state or stores (Redux or Mobx) after a certain value has been presented. I’m going to add a bit more to the UserNavBar component I created above. I’m going to cache the data on to its local React state, so I don’t have to constantly make fetch calls. class UserNavBar extends React.Component { state = { user: null, }; componentDidUpdate() { if (this.props.isAuth) { fetch(' .then(res => res.json()) .then(data => this.setState({ user: data })); } } render() { // ... rendering user nav bar content } } Beautiful! Whenever the AuthWrapper component says my user has been authenticated, my UserNavBar component will fetch the data. But, there is one big problem here! componentDidUpdate gets called after every prop or state has changed. And from the look above, my userNavBar will be an infinite loop of state change. Avoid infinite loop in componentDidUpdate So you need to be very careful, and add good conditionals if you modify state or stores within componentDidUpdate. I’m going to update my UserNavBar componentDidUpdate method. componentDidUpdate() { if (this.props.isAuth && !this.state.user) { fetch(' .then(res => res.json()) .then(data => this.setState({ user: data })); } } Now I’m checking to make sure the state property user is falsey before I fetch. Conclusion Just to recap what was covered in this article. The componentDidUpdate get’s called after the React component props or state has changed. This method is best use for: - DOM manipulation after the component has rendered - API calls after specific conditions have been met - Update React state or stores like Redux, and Mobx after a set of conditions have been met Use good conditions to avoid infinite loops of updates, and unnecessary API calls. I like to tweet about React and post helpful code snippets. Follow me there if you would like some too!
https://linguinecode.com/post/how-react-componentdidupdate-works
CC-MAIN-2022-21
refinedweb
760
58.48
(if proxy settings are detected),, in a case insensitive approach, must be a bytes object). An example of using Content-Type header with data argument would be sending a dictionary like {"Content-Type":" application/x-www-form-urlencoded;charset=utf-8"}. method should be a string that indicates the HTTP request method that will be used (e.g. 'HEAD'). If provided, its value is stored in the method attribute and is used by get_method(). Subclasses may indicate a default method by setting the method attribute in the class itself. Changed in version 3.3: Request.method argument is added to the Request class. Changed in version 3.4: Default Request.method may be indicated at the class level.,. HTTPBasicAuthHandler will raise a ValueError when presented with a wrong Authentication scheme.. When both Digest Authentication Handler and Basic Authentication Handler are both added, Digest Authentication is always tried first. If the Digest Authentication returns a 40x response again, it is sent to Basic Authentication handler to Handle. This Handler method will raise a ValueError when presented with an authentication scheme other than Digest or Basic. Changed in version 3.3: Raise ValueError on unsupported Authentication Scheme. data URLs. New in version 3.4.. Changed in version 3.4. Request.full_url is a property with setter, getter and a deleter. Getting full_url returns the original request URL with the fragment, if it was present.. Changed in version 3.4: Changing value of Request.data now deletes “Content-Length” header if it was previously set or calculated. boolean, indicates whether the request is unverifiable as defined by RFC 2965. Request subclass, or by passing a value in to the Request constructor via the method argument. New in version 3.3. Changed in version 3.4: A default value can now be set in subclasses; previously it could only be set via the constructor argument. Return a string indicating the HTTP request method. If Request.method is not None, return its value, otherwise return 'GET' if Request.data is None, or 'POST' if it’s not. This is only meaningful for HTTP requests. Changed in version 3.3: get_method now looks at the value of Request.method. Request.full_url'. in that case. the python.org website uses utf-8 encoding as specified in it’s. >>>) Here is an example of doing a PUT request using Request: import urllib.request DATA=b'some data' req = urllib.request.Request(url='', data=DATA,method='PUT') f = urllib.request.urlopen(req) print(f.status) print(f.reason) without charset parameter >>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': request (normally the request type is GET). The data argument must be a bytes object in standard application/x-www-form-urlencoded format; see the urllib.parse.urlencode(). Cleans up temporary files that may have been left behind by previous calls to urlretrieve(). Deprecated since version 3.3. OSError: A chunk number, the maximum size chunks are read in and the total size of the download (-1 if unknown). It will be called once at the start andllib.parse.urlencode() function. - version¶ Variable that specifies the user agent of the opener object. To get urllib to tell servers that it is a particular user agent, set this in a subclass as a class variable or in the constructor before calling the base constructor. Deprecated since version 3.3., local files, and data URLs. Changed in version 3.4: Added support for data URLs. The caching feature of urlretrieve() has been disabled until someone finds.
https://docs.python.org/dev/library/urllib.request.html
CC-MAIN-2014-15
refinedweb
585
52.97
Ads Via DevMavens and make some things easier. However, what I found is that If you are using business objects that provide a generic data abstraction layer you end up having to some work to have typed DataSet work within that framework. Particularly you have to make sure that you pre-create your DataSet before letting the framework code create one for you so that framework knows to use your typed DataSet. The biggest problem is that you can't recast a typed DataSet from a regular DataSet, but the data must be loaded into it from the start. This is no big deal if you do this in normal front end data code but requires some setup in a business object environment. For my business objects this means something like: public class busCustomer : wwBusiness { public busCustomer() this.Tablename = "wws_customers"; this.ConnectionString = App.Configuration.ConnectionString; this.DataSet = new dsCustomers(); } … Not a big thing, but remembering this and enforcing it at all business objects is an issue. Probably the biggest issue I see is related to work flow with typed DataSets. You generate typed DataSets by dropping tables onto the XSD designer or manually building XSD definitions. The process is not difficult but if you have a lot of tables that change frequently synchronizing the DataBase and the schema for the typed DataSet becomes a big issue. You have to manually drop the tables onto the XSD designer to get the generation to occur. This means you have to manually manage the schema from which the DataSet is generated. Make a change to the database and you have to make sure you remember that the XSD is also updated. To make things worse in my environment every business object uses its own DataSet, so I would tend to require many separate XSD files (essentially one or more for each table that a business object 'owns'). The other issue I have with the typed DataSet is that if you look at the code generated there's a fair amount of overhead. Specifically the first time run a query and fill a table all the tables are created along with their column definitions. Although this provides a good typed interface there's a fair amount of overhead here that is incurred everytime you instantiate and load data into the typed DataSet. While this may be OK in Windows Forms apps in a Web app the constant reloading will occur a fair amount of overhead. As a review: To get a DataRow then you have to do something like this: // *** Noramlly you'd do this in the bus obj // *** for demo do raw Execute here int Result = Customer.Execute("select pk,Address from wws_customers","wws_customers"); // *** Standard DataRow access Customer.DataRow = Customer.DataSet.Tables["wws_customers"].Rows[0]; string Company = (string) Customer.DataRow["Company"]; Customer.DataRow["Company"] = "13 Hanalou Road"; // *** Typed Data Row access dsCustomers.wws_customersRow CustRow = (dsCustomers.wws_customersRow) Customer.DataRow; Company = CustRow.Company; CustRow.Address = "32 Elm Street"; It seems to me that the key feature of a typed DataSet is the typed DataRow. The rest of the functionality that the typed DataSet is useful but not crucial and frankly not worth the overhead IMHO. One way to approach this might be to build something a bit simpler - something like a wrapper for a DataRow that can be assigned on an as needed basis. I'll have more on this topic in the next entry...
http://west-wind.com/weblog/posts/146.aspx
crawl-002
refinedweb
570
61.06
A function f: X → X is measure-preserving if for each iteration of f sends the same amount of stuff into a given set. To be more precise, given a measure μ and any μ-measurable set E with μ(E) > 0, we have You can read the right side of the equation above as “the measure of the set of points that f maps into E.” You can apply this condition repeatedly to see that the measure of the set of points mapped into E after n iterations is still just the measure of E. If X is a probability space, i.e. μ( X ) = 1, then you could interpret the definition of measure-preserving to mean that the probability that a point ends up in E after n iterations is independent of n. We’ll illustrate this below with a simulation. Let X be the half-open unit interval (0, 1] and let f be the Gauss map, i.e. where [z] is the integer part of z. The function f is measure-preserving, though not for the usual Lebesgue measure. Instead it preserves the following measure: Let’s take as our set E an interval [a, b] and test via simulation whether the probability of landing in E after n iterations really is just the measure of E, independent of n. We can’t just generate points uniformly in the interval (0, 1]. We have to generate the points so that the probability of a point coming from a set E is μ(E). That means the PDF of the distribution must be p(x) = 1 / (log(2) (1 + x)). We use the inverse-CDF method to generate points with this density in the Python code below. from math import log, floor from random import random def gauss_map(x): y = 1.0/x return y - floor(y) # iterate gauss map n times def iterated_gauss_map(x, n): while n > 0: x = gauss_map(x) n = n - 1 return x # measure mu( [a,b] ) def mu(a, b): return (log(1.0+b) - log(1.0+a))/log(2.0) # Generate samples with Prob(x in E) = mu( E ) def sample(): u = random() return 2.0**u - 1.0 def simulate(num_points, num_iterations, a, b): count = 0 for _ in range(num_points): x = sample() y = iterated_gauss_map(x, num_iterations) if a < y < b: count += 1 return count / num_points # Change these parameters however you like a, b = 0.1, 0.25 N = 1000000 exact = mu(a, b) print("Exact probability:", exact) print("Simulated probability after n iterations") for n in range(1, 10): simulated = simulate(N, n, a, b) print("n =", n, ":", simulated) Here’s the output I got: Exact probability: 0.18442457113742736 Simulated probability after n iterations n = 1 : 0.184329 n = 2 : 0.183969 n = 3 : 0.184233 n = 4 : 0.184322 n = 5 : 0.184439 n = 6 : 0.184059 n = 7 : 0.184602 n = 8 : 0.183877 n = 9 : 0.184834 With 1,000,000 samples, we expect the results to be the same to about 3 decimal places, which is what we see above. Related post: Irrational rotations are ergodic. (A transformation f is ergodic if it is measure preserving and the only sets E with f –1(E) = E are those with measure 0 or full measure. Rational rotations are measure-preserving but not ergodic. The Gauss map above is ergodic.) 2 thoughts on “Fractional parts, invariant measures, and simulation” Great post as usual. There is an entire book on the subject. * Computational Ergodic Theory, Choe, Geon Ho () He has lots of Maple code there. Also, I was wondering, why did you call $f(x) = 1/x- \lfloor 1/x \rfloor$ as Gauss map? Is it well known map in the literature? Any reference to this. Viana and Oliveira call it that function the Gauss map in their book “Foundations of Ergodic Theory.” It’s closely related to continued fractions. Presumably its name comes from work by Gauss on continued fractions. Gauss had his fingers is so many pies that there are probably many functions called a “Gauss map.” The one that comes to mind is the one from differential geometry, mapping a point on a surface to a point on the unit sphere.
https://www.johndcook.com/blog/2017/06/18/fractional-parts-invariant-measures-and-simulation/
CC-MAIN-2018-34
refinedweb
707
65.12
Recently, Java changed its release cycle to a more rapidly cadence, affecting the way the language evolves overtime. With this new cadence, features can now reach the market faster. Besides that, this cadence enables the community to work on (and deliver) smaller features instead of expending all their energy on the big changes (e.g., lambda, generics, and modules). Throughout the next sections, you will learn about Amber, the project that incubates small, productivity-oriented Java language features. "Stay on top of Project Amber and learn what productivity-oriented @java language features will arrive soon." Project Amber Project Amber, as explained on its homepage, is an effort focused on "exploring and incubating smaller, productivity-oriented Java language features that have been accepted as candidate JEPs under the OpenJDK JEP process." At the time of writing, this project has already delivered two enhancements and is planning on delivering five more. Let's learn about these enhancements. Not sure what JEP (JDK Enhancement Proposal) means? Check out this article and learn more about the Java platform and the community process that is responsible for evolving it. Enhancements delivered The first enhancement already released, called Local-Variable Type Inference, was introduced in Java 10 and allows developers to reduce the ceremony associated with writing Java code while maintaining Java's commitment to static type safety. With this enhancement, developers can now declare variables like this: var list = new ArrayList<String>(); // infers ArrayList<String> var stream = list.stream(); // infers Stream<String> List<String> list = new ArrayList<String>(); Stream<String> stream = list.stream(); The second enhancement, called Local-Variable Syntax for Lambda Parameters, was introduced in Java 11 and extends the Local-Variable Type Inference feature by allowing var to be used when declaring the formal parameters of implicitly typed lambda expressions. For example, with this enhancement, if you write the following code: IntStream.of(1, 2, 3, 5, 6, 7) .filter((var i) -> i % 3 == 0) .forEach(System.out::println); Java will have no problem identifying that the i variable is an integer. Enhancements being developed Besides the enhancements already released, Project Amber is planning on delivering Lambda Leftovers, Pattern Matching, Switch Expressions, Raw String Literals, and Concise Method Bodies. Lambda Leftovers The Lambda Leftovers enhancement aims at bringing two new features to the Java language. First, this enhancement will allow developers to use an underscore (_) to denote an unnamed lambda parameter. Second, the enhancement will allow lambda parameters to shadow variables already defined in the enclosing context. For example, this last feature will enable developers to write code as follows: Map<String, Integer> msi = ... String key = computeSomeKey(); msi.computeIfAbsent(key, key -> key.length()); In this case, the inner key variable will cause no conflict with the external one (derived from the computeSomeKey() call). Pattern Matching The Pattern Matching enhancement will allow developers to be more concise when dealing with the instanceof operator. For example, with this feature, whenever developers want to check if an object is a String and use it as such, instead of doing this: if (obj instanceof String) { String s = (String) obj; // use s } They will be able to do this: if (obj instanceof String s) { // can use s here } By using the new pattern matching feature, developers will reduce the overall number of explicit casts in Java programs considerably. For example, as type test patterns are particularly useful when writing equality methods, instead of having a method like this: @Override public boolean equals(Object o) { return (o instanceof CaseInsensitiveString) && ((CaseInsensitiveString) o).s.equalsIgnoreCase(s); } Developers will be able to simplify the code (and avoid the explicit cast), as shown here: @Override public boolean equals(Object o) { return (o instanceof CaseInsensitiveString cis) && cis.s.equalsIgnoreCase(s); } Switch Expressions The Switch Expressions enhancement will enable developers to use the switch feature as either a statement (the traditional way) or as an expression (the simplified version). This change will simplify some code, as you can see on the following code snippets. The first one shows how you would use the traditional switch keyword to make a decision: switch (day) { case MONDAY: case FRIDAY: case SUNDAY: System.out.println(6); break; case TUESDAY: System.out.println(7); break; case THURSDAY: case SATURDAY: System.out.println(8); break; case WEDNESDAY: System.out.println(9); break; } The second one shows how you would use the simplified version to achieve the same result: switch (day) { case MONDAY, FRIDAY, SUNDAY -> System.out.println(6); case TUESDAY -> System.out.println(7); case THURSDAY, SATURDAY -> System.out.println(8); case WEDNESDAY -> System.out.println(9); } Pretty nice, huh? "The new Switch Expressions proposal will allow @java developers to use switch as expressions to write more concise code." Raw String Literals The Raw String Literals enhancement will add, as the name states, raw string literals to the Java programming language. This type of string can span multiple lines of source code and does not interpret escape sequences, such as \n, or Unicode escapes, of the form \uXXXX. Among its goals, the enhancement plans on: - make it easier for developers to express sequences of characters in a readable form, free of Java indicators; - supply strings targeted for grammars other than Java; - and supply strings that span several lines of source without supplying special indicators for new lines. One good way to see the benefits of this enhancement is to consider what you would need to do to write a long SQL query: String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` " + "WHERE `CITY` = ‘INDIANAPOLIS' " + "ORDER BY `EMP_ID`, `LAST_NAME`;"; By using Raw String Literals you will be able to rewrite the previous code snippet as follows: String query = ``SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` WHERE `CITY` = ‘INDIANAPOLIS' ORDER BY `EMP_ID`, `LAST_NAME`; ``; Concise Method Bodies The Concise Method Bodies enhancement is all about supporting more concise methods in the Java programming language. The Java 8 version, released back in 2014, introduced what is known as the Lambda Expressions enhancement. This enhancement, known as Java's first step into functional programming, allowed developers to define methods that do not belong to any class. As such, these methods (which have a very concise syntax) can be passed around as if they were objects and can be executed on demand. For example, prior to the Lambda Expressions introduction, if you needed to do some calculation and return an integer, you would have to find a class where to define a new method: public static class Utils { public static int calculate(Object someParameter) { // ... calculate return result; } } After that, you would be able to call this method whenever you wanted, after importing the Util class. With the introduction of this new feature, you can now replace all this boilerplate with something much simpler: ToIntFunction<Object> calculate = (Object o) -> { // ... calculate return result; }; The code above, instead of belonging to some random class (like Utils, on the example), can be written and called right where you need it. This can be considered the first concise methods introduced in the programming language. Now, back to the Concise Method Bodies enhancement that Project Amber will introduce, when this feature is released, developers will be able to apply this kind of syntax in more places. For example, if you ever did something like creating a method like this: int length(String s) { return s.length(); } In the near future, you will be able to rewrite it like this: int length(String s) -> s.length(); Conclusion As you learned in this short blog post, Project Amber is the project that you have to keep an eye on to learn about the productivity-oriented features that will arrive at the Java programming language soon. If you want to stay on top of this, follow us on Twitter, or subscribe to our.
https://auth0.com/blog/the-future-of-java-2019-project-amber/
CC-MAIN-2020-45
refinedweb
1,284
50.87
If you're looking for Apache Ambari Interview Questions & Answers for Experienced or Freshers, you are at right place. There are lot of opportunities from many reputed companies in the world. According to research Apache Ambari has a market share of about 49.30%. So, You still have opportunity to move ahead in your career in Apache Ambari Administration. Mindmajix offers Advanced Apache Ambari Interview Questions 2020 that helps you in cracking your interview & acquire dream career as Apache Ambari Administrator. If you would like to Enrich your career with a Apache Ambari certified professional, then visit Mindmajix - A Global online training platform: “Apache Ambari Online Training” Course. This course will help you to achieve excellence in this domain. Q1: What are the three layers where the Hadoop components are actually supported by Ambari? Ans: The three layers that are supported by Ambari are below: 1. Core Hadoop 2. Essential Hadoop 3. Hadoop Support Q2: What is Apache Ambari? Ans: The Apache Ambari is nothing but a project which is solely focused to make life simple while using Hadoop management system. This software helps or provides comfort zone in terms of the following aspect: 1. Provisioning 2. Managing 3. Monitoring Hadoop clusters 4. Provides intuitive interface 5. It is backed up RESTful API’s. 6. Provides an easy to use Hadoop management web UI Q3: What are the areas where Ambari helps the system administrators to do? Ans: With the help of Ambari, system administrators will be able to do the following easily, they are: 1. Provision of Hadoop Cluster 2. Manage a Hadoop cluster 3. Monitor a Hadoop Cluster Q4: What bit version that Ambari needs and also list out the operating systems that are compatible? Ans: The Apache Ambari is compatible with 64-bit version and the following are the operating systems that go well with Ambari implementation: 1. Debian 7 2. Ubuntu 12 and 14 3. SLES (Suse Linux Enterprise Server) 11 4. OEL (Oracle Enterprise Linux 6) and 7 5. CentOS 6 and 7 6. RHEL ( Redhat Enterprise Linux) 6 and 7 Q5: What is the latest version of Ambari that is available in the market and what is the feature that they have added in it? Ans: The latest version of Ambari that is available in the market is Ambari 2.5.2. Within, this version they have added a feature called: Cross stack upgrade support. Q6: What is Repository? Ans: A repository is nothing but space where it hosts the software packages which can be used for download and plus install. Q7: What is Yum? Ans: The Yum is nothing but a package manager which actually fetches the software packages from the repository. On RHEL/CentOS, typically “yum”, ON SLES, typically “Zipper”. Q8: What is a local repository and when it is useful while using Ambari environment? Ans: A local repository is nothing but a hosted space in the local environment. Usually, when the machines don't have an active internet connection or have restricted or very limited network access a local repository should be set up. With this setup, the user will be able to obtain Ambari and HDP software packages. Q9: How many types of Ambari Repositories are available? Ans: The types of Ambari Repositories are listed below: 1. Ambari: This is for Ambari server, Ambari agent and other monitoring software packages 2. HDP: This is used to host Hadoop Stack packages 3. HDP-UTILS: All the utility packages for Ambari and HDP are available 4. EPEL: It stands for “Extra Packages for Enterprise Linux. It has a set of additional packages for the Enterprise Linux Q10: What are the different methods to set up local repositories? Ans: There are two ways to deploy the local repositories. It actually depends on your active Internet connection and based on that we can execute it. 1. First of all mirror the packages to the local repository 2. If the first method doesn’t work out good for you then download all the Repository Tarball and start building the Local repository Q11: How to set up local repository manually? Ans: This process is only used when there is no active internet connection is not available. So to set up a local repository, please follow the below steps: 1. First and foremost, set up a host with Apache httpd 2. Next is to download Tarball copy for every repository entire contents 3. Once it is downloaded, one has to extract the contents Q12: What are the tools that are needed to build Ambari? Ans: The following tools are needed to build Ambari: 1. If you are using Mac then you have to download Xcode from the apple store. 2. JDK 7 3. Apache Maven 3.3.9 or later 4. Python 2.6 or later 5. Node JS 6. G++ Q13: What are the independent extensions that are contributed to the Ambari codebase? Ans: The independent extensions that are contributed to the Ambari Codebase are as follows: 1. Ambari SCOM Management Pack 2. Apache Slider View Q14: Is Ambari Python Client can be used to make good use of Ambari API’s? Ans: Yes, Ambari Python client can be used to make good use of Ambari API’s. Q15: What is the process of creating Ambari client? Ans: The following code will do help you to create an Ambari client: from ambari_client.ambari_api import AmbariClient headers_dict={'X-Requested-By':'mycompany'} #Ambari needs X-Requested-By header client = AmbariClient("localhost", 8080, "admin", "admin", version=1,http_header=headers_dict) print client.version print client.host_url print"n" Q16: How can we see all the clusters that are available in Ambari? Ans: all_clusters = client.get_all_clusters() print all_clusters.to_json_dict() print all_clusters Q17: How can we see all the hosts that are available in Ambari? Ans: all_hosts = client.get_all_hosts() print all_hosts print all_hosts.to_json_dict() print"n" Q18: What does Ambari Shell can provide? Ans: The Ambari shell can provide an interactive and handy command line tool which actually supports the following: 1. All the available functionality in Ambari Web-app 2. All the context-aware command availability 3. Tab completion 4. Any required parameter support if needed Q19: What are the core benefits for Hadoop users by using Apache Ambari? Ans: The Apache Ambari is a great gift for individuals who use Hadoop in their day to day work life. With the use of Ambari, Hadoop users will get the core benefits: 1. Installation process is simplified 2. Configuration and overall management is simplified 3. It has a centralized security setup process 4. It gives out full visibility in terms of Cluster health 5. It is extensively extendable and has an option to customize if needed. Q20: What are the different life cycle commands in Ambari? Ans: The Ambari has a defined life cycle commands and they are as follows: 1. Start 2. Stop 3. Status 4. Install 5. Configure It is very flexible in terms of adding or removing or reconfiguring any of the services at any time. Q21: What are the tools that are used in Ambari Monitoring? Ans: Ambari Monitoring tools actually use two different open source projects for its monitoring purpo2ses, they are as follows: 1. Ganglia 2. Nagios Q22: What is Ganglia is used for in Ambari? Ans: It is one of the tools that is used in Ambari, it is mainly used for the following purpose: 1. Monitoring 2. Identifying trending patterns 3. Metrics collection in the clusters 4. It also supports detailed heatmaps Q23: What is Nagios is used in Ambari? Ans: It is one of the tools that is used in Ambari, it is mainly used for the following purpose: >> First and foremost it is used for health checking and alerts purpose >> The alert emails can be one of notifications type, service type, host address etc Q24: What are the other components of Ambari that are important for Automation and integration? Ans: The other components of Ambari that are imported for Automation and Integration are actually divided into three pieces of information: 1. Ambari Stacks 2. Ambari Blueprints 3. Ambari API Actually, Ambari is built from scratch to make sure that it deals with Automation and Integration problems carefully. Q25: In which language is the Ambari Shell is developed? Ans: The shell is developed in Java and it actually based on Ambari REST client and the spring shell framework. Q26: Before deploying the Hadoop instance, what are the checks that an individual should do? Ans: The following is the list of items that need to be checked before actually deploying the Hadoop instance: 1. Check for existing installations 2. Set up passwordless SSH 3. Enable NTP on the clusters 4. Check for DNS 5. Disable the SELinux 6. Disable iptables Q27: List out the commands that are used to start, check the progress and stop the ambari server? Ans: The following are the commands that are used to do the following activities: To start the Ambari server ambari-server start To check the Ambari server processes ps -ef | grep Ambari To stop the Ambari server ambari-server stop
https://mindmajix.com/apache-ambari-interview-questions
CC-MAIN-2020-45
refinedweb
1,514
67.15
Hello, I gave a shot for PythonAnywhere and it seems promising but I'm facing issue with starting my BaseHttpServer, which works fine on localhost. I'm trying to start server like this: self._server = HTTPServer(("localhost", 8080), RequestHandler) self._server.serve_forever() Is it proper way ? I don;t know the concept of WSGI, should I implement following method ? def application(environ, start_response): if environ.get('PATH_INFO') == '/': status = '200 OK' content = 'Server is up' How start BaseHttpServer with WSGI ? I don't want to make a big refactor because it works fine on localhost .. I have also my RequestHandler: class RequestHandler(BaseHTTPRequestHandler)
https://www.pythonanywhere.com/forums/topic/11811/
CC-MAIN-2018-47
refinedweb
102
61.33
a fast function taking either variable or collection as argument I want to create a function which takes either variable or collection as argument. If the input is any kind of collection, function should be taken of every element in it and return a numpy array of results. Currently, I do in this way: def simplefunc(x): <some code here> # it is assumed that x is a single variable return <some single result> def arrayfunc(x): try: #check if we have a collection x_iterator = iter(x) except TypeError: #this is a single expression return simplefunc(x) else: # iterate through iterable x ret=[] for xx in x: ret.append(simplefunc(xx)) return numpy.array(ret) It works as is, however, I do not think this is the fastest way possible,especially the method to figure out if the input is a collection. I also do not like that strings are considered as collections and split to chars (I can stand it though). Is there a more elegant way? I tried also to call arrayfunc() recursively on each element of collection (instead of simplefunc()), to handle collections of collections in the same way, however, it runs into infinite loop on strings. I have to check if the input is a string explicitly. Perhaps using 'map(function, sequence)' would help? 'try: L = map(simplefunc, x) ...'. See Thanks a lot... this I may have overlooked while googling.. However, this does not work if I have some other non-sequence parameters in my function Maybe better to post this as an answer? Your function above doesn't have non-sequence parameters, so I'm not sure how you plan to deal with those. You could always make a partial function (look up partial in the functools package). List comprehensions deal nicely with this too.
https://ask.sagemath.org/question/8536/a-fast-function-taking-either-variable-or-collection-as-argument/?answer=12982
CC-MAIN-2019-51
refinedweb
299
63.09
Marketting website työt gather emails and make html letter ...my name is Andrew and I've been developing a startup company for the last 6 months. Now that we are ready to lauch our marketting campaign, we would like to redesign our website to better represent what we do. Our current website is : [kirjaudu nähdäksesi URL:n] We would like to change up the whole thing so we look less like a IT firm, and more like an Hi EveryOne , I am looking for lead generating executive , who can generate foreign countries lead for our company , we will pay 5% on each conversion of project . Kindly message who are interested for the same . Thanks I OWN APPLIANCES business so my business is all about srached, dent and new open box i need someone to market my items online, speak with customers and should have good ideas and experience on this field i offer price match we have the best pricing on the market, we offer deliveries ,, we finaice 3 months with zero % same as cash and more than that need seo , smo website design , content writer ,doodle , video I need a sales man for marketting in Thailand who can handle our sales in Thailand. .. the various jobs and opportunities available 2- how to get that A startup website based on affiliate marketting. Url is [kirjaudu nähdäksesi URL:n] – or&... I'm looking to start a business selling online active wear, in particular for :) online marketting ..experience n copy writting I am new to video blogging and creating motivational videos and to test my skills. Need help in creating technical v...Need help in creating technical videos and youtube marketing from powerpoint presentations. kindly bid only if you have at least 10k subscribers and experience in youtube marketting. i am trying for the first time so my budget is low we have our product drone for which marketing is to be done Ther eAre around 40 pages for content based on web designing and digital marketting . looking for template designer for email marketting i am manager of newpaper KASHMIR READER . We have starting publishing in 2010 . I want change my layout of the newspaper and...READER . We have starting publishing in 2010 . I want change my layout of the newspaper and also need logo letterhead and other stationaery designing. In addition if you have marketting plan how to attract reader so i need it ...would like to work marketing masters who is located in Ukraine. Who can find for me customers in any way online marketting or email maketting or onlive advertisement all are possible for me. But i am not strong about online sale and marketting also i dont want to make some budget about it. I am ready to share with you %20 of my profit. For more details SEO for travel website, Social pages my site is [kirjaudu nähdäksesi URL:n] I need a sales and marketting person to sell my workshops. Responsibilities include lead generation,telecalling,fixing meetings with decision makers,negotiating,closing training programmes. I have a basic wordpress mounted and want someone to fully design it as a blog and as an e-commerce / affiliate marketting website marketting and branding lead generation We need a website for our company with affliate login, merchant login etc. There must be some pages to describe our services and we need to integrate third party API to make Login system . I'm going to sell my software product for accounting management system. I'm finding marketer to help me sell my software system. I want to create a email deliverability ,I mean i am working in one email marketting company for my own purpose i want email headers any one knows about it We are hiring some one who: - Speaks English fluently - Is disciplined - Is reliable - Can find potential customers via Google, LinkedIn,... - Will send e-mails to prospects - Will follow up discussions - Flexible short term contract - Possibility for long term relationship i am looking for someone who can do the digital marketing and Email marketing for my website. your work would include creating email campaign & sending emails to current subscribers once a week, and manage my social media account (Facebook, twitter, Instagram, linked in etc) I would prefer someone with some experience in content writing. Hi we are looking expert in Sales and Marketting for b2b business who can work full time and monthly payment. Preferred Location - India I will like to build my marketting video for a product I am building. We are developing a website at this current stage but in the meantime I have a set of videos I need to promote to start showing proof of concept that my videos will be able to provide a return (consider this an experiment). The videos are of Art nature, sensual some say erotic. we are startup and i need a expert who works parttime with us for marketting our bussiness is multi-seller retail startup I need a someone who have the ability to send millions of emails directly to inbox. Let me know if you can. We need dealers at various place for marketting our gps products. We are developing IT company in tiruppur, tamilnadu. We were doing various products relevants to IT. We need marketting executive who can easily sell our product in and around tamilnadu. Create A Logo For A Company By The Name Textricks it is a digital marketting company so it should Go With The Business Type. Make The Best Use Of Your Creativity we are startup . i need a experinced digital marketter expert for it We are coming with some bunch of videos to be released 1/ ev... the videos are conceptual- storylike music video. I want someone who could intelligently get the video across right audience, who could work with SEOs, all social media Marketting platforms, and also uploading on various apps like [kirjaudu nähdäksesi URL:n], tik-tok, dubsmash and stuff for the promotion. I want you to promote my service through email marketing. You must blast my email newsletter through your smtp server. You must also have the email need some help with finding some leads. I need someone who can set uo campain for an adult CPA offers. Please read carefully instructions provided before bidding on this project. If you bid that means you are confident enough to work on the basis of instructions provided. We are an independent software testing company and we need someone with high marketing skills who can manage our social media platform, inbound content marketting and can generate inbound leads havin...
https://www.fi.freelancer.com/job-search/marketting-website/
CC-MAIN-2018-51
refinedweb
1,100
59.94
From: Laszlo Ersek <address@hidden> According to ISO C99 / N1256 (referenced in HACKING): > 6.5.8 Relational operators > > 4 For the purposes of these operators, a pointer to an object that is > not an element of an array behaves the same as a pointer to the first > element of an array of length one with the type of the object as its > element type. > > 5 When two pointers are compared, the result depends on the relative > locations in the address space of the objects pointed to. If two > pointers to object or incomplete types both point to the same object, > or both point one past the last element of the same array object, they > compare equal. If the objects pointed to are members of the same > aggregate object, pointers to structure members declared later compare > greater than pointers to members declared earlier in the structure, > and pointers to array elements with larger subscript values compare > greater than pointers to elements of the same array with lower > subscript values. All pointers to members of the same union object > compare equal. If the expression /P/ points to an element of an array > object and the expression /Q/ points to the last element of the same > array object, the pointer expression /Q+1/ compares greater than /P/. > In all other cases, the behavior is undefined. Our AddressSpace objects are allocated generally individually, and kept in the "address_spaces" linked list, so we mustn't compare their addresses with relops. Convert the pointers subjected to the relop in rom_order_compare() to "uintptr_t": > 7.18.1.4 Integer types capable of holding object pointers > > 1 [...] > > The following type designates an unsigned integer type with the > property that any valid pointer to void can be converted to this type, > then converted back to pointer to void, and the result will compare > equal to the original pointer: > > /uintptr_t/ > > These types are optional. Cc: "Michael S. Tsirkin" <address@hidden> Cc: Alistair Francis <address@hidden> Cc: Paolo Bonzini <address@hidden> Cc: Peter Maydell <address@hidden> Cc: address@hidden Fixes: 3e76099aacb4dae0d37ebf95305369e03d1491e6 Signed-off-by: Laszlo Ersek <address@hidden> Reviewed-by: Alistair Francis <address@hidden> Reviewed-by: Michael S. Tsirkin <address@hidden> Signed-off-by: Michael S. Tsirkin <address@hidden> --- hw/core/loader.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hw/core/loader.c b/hw/core/loader.c index c0d645a..4574249 100644 --- a/hw/core/loader.c +++ b/hw/core/loader.c @@ -818,7 +818,7 @@ static QTAILQ_HEAD(, Rom) roms = QTAILQ_HEAD_INITIALIZER(roms); static inline bool rom_order_compare(Rom *rom, Rom *item) { - return (rom->as > item->as) || + return ((uintptr_t)(void *)rom->as > (uintptr_t)(void *)item->as) || (rom->as == item->as && rom->addr >= item->addr); } -- MST
https://lists.gnu.org/archive/html/qemu-devel/2016-11/msg05506.html
CC-MAIN-2019-35
refinedweb
446
51.68
15th February 2014 5:45 pm Django Blog Tutorial - the Next Generation - Part 4 Hello again! As promised, in this instalment we’ll implement categories and tags, as well as an RSS feed. As usual, we need to switch into our virtualenv: $ source venv/bin/activate Categories It’s worth taking a little time at this point to set out what we mean by categories and tags in this case, as the two can be very similar. In this case, we’ll use the following criteria: - A post can have only one category, or none, but a category can be applied to any number of posts - A post can have any number of tags, and a tag can be applied to any number of posts If you’re not too familiar with relational database theory, the significance of this may not be apparent, so here’s a quick explanation. Because the categories are limited to one per post, the relationship between a post and a category is known as one-to-many. In other words, one post can only have one category, but one category can have many posts. You can therefore define the categories in one table in your database, and refer to them by their ID (the reference to the category in the post table is referred to as a foreign key). As usual, we will write a test first. Open up blogengine/tests.py and edit the line importing the Post model as follows: from blogengine.models import Post, Category Also, add the following method before test_create_post: This test checks that we can create categories. But categories aren’t much use unless we can actually apply them to our posts. So we need to edit our Post model as well, and to do so we need to have a test in place first. Edit the test_create_post method as follows: What we’re doing here is adding a category attribute to the posts. This attribute contains a reference to a Category object. Now, we also want to test adding, editing, and deleting a category from the admin interface. Add this code to the AdminTest class: This is very similar to the prior code for the posts, and just checks we can create categories via the admin. We also need to check we can apply these categories to posts, and that they don’t break the existing tests: Here we basically take our existing post tests in the admin interface and add the category to them. Finally, we edit the PostViewTest class to include categories: Now it’s time to run our tests: This is the expected result. We need to create our Category model. So let’s do that: Note that we add Category before Post - this is because Category is a foreign key in Post, and must be defined in order to be used. Also, note that we add the category attribute as a ForeignKey field, like User and Site, indicating that it is an item in another table being references. We also allow for category to be blank or null, so the user does not have to apply a category if they don’t wish to. If we run our tests, they should still fail: The category table hasn’t yet been created, so we need to use South to create and run the migrations: If we then run our tests again, some of them will still fail: That’s because we haven’t registered the categories in the admin. So, that’s our next job: Now we try again: It passes! Let’s do a quick sense check before committing. Run the server: $ python manage.py runserver If you visit the admin, you’ll see the text for category is Categorys, which is incorrect. We also don’t have a good representation of the category in the admin. Let’s fix that: Let’s commit our changes: Now, as yet our categories don’t actually do all that much. We would like to be able to: - List all posts under a category - Show the post category at the base of the post So, let’s implement that. First, as usual, we implement tests first: All we do here is assert that for both the post pages and the index, the text from the category name is shown in the response. We also need to check the category-specific route works. Add this method to PostViewTest: This is very similar to the previous tests, but fetches the absolute URL for the category, and ensures the category name and post content are shown. Now, let’s run our new tests: Let’s take a look at why they failed. test_category_page failed because the Category object had no method get_absolute_url. So we need to implement one. To do so, we really need to add a slug field, like the posts already have. Ideally, we want this to be populated automatically, but with the option to create one manually. So, edit the models as follows: We’re adding the slug attribute to the Category model here. However, we’re also overriding the save method to detect if the slug is set, and if not, to create a slug using the slugify function, and set it as the category’s slug. We also define an absolute URL for the category. Now, if you run the tests, they will fail because we haven’t made the changes to the database. So, we use South again: $ python manage.py schemamigration --auto blogengine Then run the migration: $ python manage.py migrate Now, running our tests will show that the tables are in place, but we still have some work to do. The index and post pages don’t show our categories, so we’ll fix that. First, we’ll fix our post list: Next, we’ll take care of our post detail page: Note that in both cases we include a link to the category URL. Now, we should only have one failing test outstanding - the category page. For this, generic views aren’t sufficient as we need to limit the queryset to only show those posts with a specific category. Fortunately, we can extend Django’s generic views to add this functionality. First, we edit our URLconfs: Note we import a new view from blogengine.views called CategoryListView. Next, we create that listview: This is quite simple. We import the ListView, as well as our models. Then we extend ListView by getting the slug from the request, fetching the appropriate category, and returning only those posts that have that category. If the category does not exist, we return the empty Post object list. We haven’t had to set the template manually as it is inherited from ListView. If you run the tests, they should now pass: So let’s commit our changes: Tags are fairly similar to categories, but more complex. The relationship they have is called many-to-many - in other words, a tag can be applied to many posts, and one post can have many tags. This is more difficult to model with a relational database. The usual way to do so is to create an intermediate table between the posts and tags, to identify mappings between the two. Fortunately, Django makes this quite easy. Let’s write the tests for our tagging system. As with the categories, we’ll write the tests for creating and editing them first, and add in tests for them being visible later. First we’ll create a test for creating a new tag object: Next, we’ll amend the test for creating a post to include tags: Note the difference in how we apply the tags. Because a post can have more than one tag, we can’t just define post.tag in the same way. Instead, we have post.tags, which you can think of as a list, and we use the add method to add a new tag. Note also that the post must already exist before we can add a tag. We also need to create acceptance tests for creating, editing and deleting tags: These tests are virtually identical to those for the Category objects, as we plan for our Tag objects to be very similar. Finally, we need to amend the acceptance tests for Post objects to include a tag: Here we’re just adding tags to our Post objects. Now it’s time to run our tests to make sure they fail as expected: So here we can’t import our Tag model, because we haven’t created it. So, we’ll do that: Our Tag model is very much like our Category model, but we don’t need to change the verbose_name_plural value, and we amend the absolute URL to show it as a tag rather than a category. We also need to amend our Post model to include a tags field: Note that tags is a ManyToManyField, and we pass through the model we wish to use, much like we did with the categories. The difference is that one tag can be applied to many posts and a post can have many tags, so we need an intermediate database table to handle the relationship between the two. With Django’s ORM we can handle this quickly and easily. Run our tests and they should still fail: Again, we can easily see why they failed - the blogengine_tag table is not in place. So let’s create and run our migrations to fix that: Now, we run our tests again: We can’t yet amend our tags in the admin, because we haven’t registered them. So we do that next: Now, if we run our tests, they should pass: Time to commit our changes: Now, like with the categories beforehand, we want to be able to show the tags applied to a post at the base of it, and list all posts for a specific tag. So, first of all, we’ll amend our PostViewTest class to check for the tags: We create a tag near the top, and check for the text in the page (note that to avoid false positives from the categories, we set the name of the tags to something different). We do this on both the index and post pages. We also need to put a test in place for the tag-specific page: Again, this is virtually identical to the category page, adjusted to allow for the fact that we need to get a specific tag. If we now run our tests, they should fail as expected: So, we need to implement the following things: - Show tags on the index page - Show tags on the post pages - Create a page listing the posts with a specific tag As we have seen already with the categories, this is actually quite simple. First, we’ll sort out the tags on the index page: This is quite simple. We retrieve all the tags with post.tags.all and loop through them. We then do basically the same for the individual post pages: This should resolve two of our outstanding tests: The final test is for the tag pages. As we saw with the categories, we can limit our querysets on specific pages. So we’ll extend the ListView generic view again to handle tags: Note that here, Tag objects have access to their assigned Post objects - we just use post_set to refer to them and get all of the posts associated with that tag. Next we’ll add the URLconfs: We import the Tag model and the TagListView view, and use them to set up the tag page. If we now run our tests again, they should pass: Well done! Time to commit: RSS Feed For the final task today, we’ll implement an RSS feed for our posts. Django ships with a handy syndication framework that makes it easy to implement this kind of functionality. As usual, we’ll create some tests first. In this case, we won’t be adding any new models, so we don’t need to test them. Instead we can jump straight into creating acceptance tests for our feed. For now we’ll just create one type of feed: a feed of all the blog posts. In a later instalment we’ll add feeds for categories and tags. First of all, we’ll implement our test. Now, in order to test our feed, we need to have a solution in place for parsing an RSS feed. Django won’t do this natively, so we’ll install the feedparser Python module. Run the following commands: Once that’s done, feedparser should be available. You may wish to refer to the documentation as we go to help. Let’s write our test for the RSS feed. First, we import feedparser near the top of the file: import feedparser Then we define a new class for our feed tests. Put this towards the end of the file - I put it just before the flat page tests: Run the tests and you’ll see something like this: We’re getting a 404 error because the post feed isn’t implemented. So let’s implement it. We’re going to use Django’s syndication framework, which will make it easy, but we need to enable it. Open up django_tutorial_blog_ng/settings/py and add the following under INSTALLED_APPS: 'django.contrib.syndication', Next, we need to enable the URLconf for this RSS feed. Open up blogengine/urls.py and amend the import fromblogengine.views` near the top: from blogengine.views import CategoryListView, TagListView, PostsFeed Further down, add in the following code to define the URL for the feed: Note that we imported the PostsFeed class, but that hasn’t yet been defined. So we need to do that. First of all, add this line near the top: from django.contrib.syndication.views import Feed This imports the syndication views - yes, they’re another generic view! Our PostsFeed class is going to inherit from Feed. Next, we define the class: This is fairly straightforward. We define our title, link, and description for the feed inside the class definition. We define the items method which sets what items are returned by the RSS feed. We also define the item_title and item_description methods. Now, if we run our tests, they should pass: Let’s commit our changes: And that’s enough for now. Don’t forget, you can get the code for this lesson by cloning the repository from Github and running git checkout lesson-4 to switch to this lesson. Next time we’ll: - Implement a search system - Add feeds for categories and posts - Tidy up the user interface Hope to see you then!
https://matthewdaly.co.uk/blog/2014/02/15/django-blog-tutorial-the-next-generation-part-4/
CC-MAIN-2019-35
refinedweb
2,457
69.62
11 June 2013 22:18 [Source: ICIS news] CAMPINAS, Brazil (ICIS)--Brazil state-run oil producer Petrobras has delayed the start-up of its Abreu e Lima refinery to November of this year, the company said on Wednesday. The first train of the refinery, which is located in the state of Pernambuco, should be complete by November and the second by May 2015, the company said. The refinery originally was scheduled for start-up in June of this year. "A lot of factors contribute for variations in the deadline [of the project] such as technical contingencies, strikes, urban and environmental conditionings, bad weather, among other [things]," Petrobras said in a statement. Petrobras and Petroleos de Venezuela (PDVSA) had talked about partnering on the Abreu e ?xml:namespace> PDVSA is to have a 40% stake in the project. However, PDVSA has been unable to secure a $10bn (€7.5bn) loan to pay for the stake. Petrobras said it could develop the refinery alone if PDVSA leaves the
http://www.icis.com/Articles/2013/06/11/9677635/brazilian-refinerys-start-up-delayed-until-november.html
CC-MAIN-2014-52
refinedweb
166
61.97
Groovy Advice Needed for Shakespeare Web Service Client By Geertjan-Oracle on Dec 11, 2009() } } That allows me to get at the play, speaker, and text from my Java code as follows: public class Demo { public static void main(String[] args) { ShakesWsClient client = new ShakesWsClient(); client.findQuote("fair is foul"); System.out.println(client.getPlay()); System.out.println(client.getSpeaker()); System.out.println(client.getWords()); } } Ant output: 12 Dec 2009 4:04:10 PM org.apache.cxf.endpoint.dynamic.DynamicClientFactory outputDebug INFO: Created classes: com.xmlme.webservices.GetSpeech, com.xmlme.webservices.GetSpeechResponse, com.xmlme.webservices.ObjectFactory 12 Dec 2009 4:04:11 PM groovyx.net.ws.AbstractCXFWSClient getBindingOperationInfo WARNING: Using SOAP version: 1.1 MACBETH ALL Fair is foul, and foul is fair: Hover through the fog and filthy air. BUILD SUCCESSFUL (total time: 6 seconds) Anyone out there with suggestions for how to improve my Groovy code (even further)? By the way, I believe that Groovy's web service support is the best thing about Groovy, especially if you mainly want to continue working in Java. Hi Geertjan. I'd love to see out of the box support for SOAP web services in Groovy, but as usual the appealing look example like your's doesn't even compile with Groovy 1.8.3: The import groovyx.net.ws.WSClient cannot be resolved. What am I missing here? Do I need a magic @Grab annotation? Cheers, Marcus Posted by marcus on December 12, 2011 at 11:10 PM PST # This reflects my experiences with magic Groovy libs promising 'easy SOAP service consumption': Don't use it. Just have a look at the development status of GroovyWS: dormant. Marcus Posted by Marcus on December 12, 2011 at 11:14 PM PST #
https://blogs.oracle.com/geertjan/entry/groovy_advice_needed_for_shakespeare
CC-MAIN-2015-11
refinedweb
290
57.16
# GooWee - A little desktop for little windows # jcw, 2004-10-07 package require Tk bind . <F5> { destroy . } ;# ramdebugger convenience namespace eval gw { variable version 0.1 proc layoutScreen {} { variable version wm title . "GooWee $version" set bg #fffff0 . configure -bg $bg pack [frame .desk -bg $bg -height 500 -width 750] -expand 1 -fill both pack [frame .ctl -height 50] -fill x -padx 3 -pady 3 text .ctl.t -bg $bg -height 2 -bd 0 -highlightcolor #c0c0c0 pack .ctl.t -fill both .ctl.t insert end "Press F1..F4 to switch or F5 to quit. " # fgcolor bgcolor -----arrow-bitmask----- hside vtitle createTop 1 #ffcccc #fff0f0 80/C0/E0/F0/F8/FC/FE/FF right bottom createTop 2 #ccffcc #f0fff0 01/03/07/0F/1F/3F/7F/FF left bottom createTop 3 #ccccff #f0f0ff FF/7F/3F/1F/0F/07/03/01 left top createTop 4 #dddddd #f0f0f0 FF/FE/FC/F8/F0/E0/C0/80 right top focusOn 1 } proc createTop {n fgcolor bgcolor bits hside vtitle} { variable arrows if {![info exists arrows($n)]} { set arrows($n) [makeArrow $bits] } set w .desk.f$n frame $w -bg white -highlightthickness 1 \ -highlightbackground $fgcolor -highlightcolor $fgcolor frame $w.bar label $w.bar.t -bg $bgcolor -text F$n -anchor w label $w.bar.a -bg $bgcolor -image $arrows($n) -width 15 frame $w.top -bg white -bd 0 pack $w.bar -fill x -side $vtitle pack $w.bar.a -fill y -side $hside pack $w.bar.t -expand 1 -fill x -side $hside pack $w.top -expand 1 -fill both -side $vtitle setSize $n 350 200 bind . <F$n> "::gw::focusOn $n" bind $w <FocusIn> "::gw::setColor $n $fgcolor; raise $w" bind $w <FocusOut> "::gw::setColor $n $bgcolor" bind $w.bar.t <1> "::gw::focusOn $n" bind $w.bar.a <1> "::gw::focusOn $n %x %y" bind $w.bar.a <B1-Motion> "::gw::trackSize $n %x %y" } proc makeArrow {b} { set d [string map [list #m 0x[string map {/ ,0x} $b]] { #define _width 8 #define _height 8 static char _bits[] = { #m }; }] return [image create bitmap -data $d] } proc focusOn {n {x ""} {y ""}} { variable rx $x ry $y focus .desk.f$n.top } proc trackSize {n x y} { variable rx variable ry set w .desk.f$n set ax [string map {1 + 2 - 3 - 4 +} $n] set ay [string map {1 + 2 + 3 - 4 -} $n] set nx [expr [winfo width $w] $ax ($x-$rx)] set ny [expr [winfo height $w] $ay ($y-$ry)] setSize $n $nx $ny } proc setSize {n nx ny} { #XXX cannot use winfo before geometry has been determined #XXX but winfo will be required to deal with desk resizing set sx [.desk cget -width] ;#set sx [winfo width .desk] set sy [.desk cget -height] ;#set sy [winfo height .desk] incr sx -3 if {$nx > $sx-25} { set nx [expr {$sx-25}] } if {$ny > $sy-30} { set ny [expr {$sy-30}] } if {$nx < 45} { set nx 45 } if {$ny < 25} { set ny 25 } switch $n 1 - 4 { set x 3 } default { set x [expr {$sx-$nx}] } switch $n 1 - 2 { set y 3 } default { set y [expr {$sy-$ny}] } place .desk.f$n -width $nx -height $ny -x $x -y $y } proc setColor {n color} { set w .desk.f$n $w.bar.t configure -bg $color $w.bar.a configure -bg $color } layoutScreen } (Obsolete info about making multiple toplevels work omitted, now that it all works with slave interps)NEM Regarding the hack to get each app to see a different toplevel widget, I seem to remember that child interps can load Tk with a particular container widget acting as the root for that interp. [2] has details - it's part of the Safe Base package.jcw - Aha! Thanks, I now also found Embedded Toplevels. Right now, the GooWee "toplevels" are frames. Given that I don't want the usual windows manager borders/decorations, I assume that the way to do it is: 1) create new frameless toplevel, 2) embed it in frame via the -use & -container options, 3) pass the resulting toplevel to scripts (trapping wm title), or 4) use the ::save::loadTk approach with a slave interpreter, as you suggest. Interesting - I never knew such things were possible. Will need to explore the x-platform combinations. Inter-process is less important for me.Brian Theado - I dug into the ::safe::loadTk a bit and here is a way of doing it using a plain slave interpreter instead of a safe slave interpreter. I guess "package require Tk" looks at the contents of argv for options such as -use [3]. package require Tk pack [frame .f -container 1] interp create s s eval [list set argv [list -use [winfo id .f]]] s eval { package require Tk pack [text .t] }To illustrate that the slave's text widget is embedded, try: pack forget .fand see the text widget disappear.jcw - W(h)ee! Thanks Brian, for such a clean solution. Now goowee.kit runs unmodified scripts with a . top-level in a non-safe slave interpreter (only tested on Linux so far) - yes! I only had to wrap "wm deiconify" in a catch in SR's weeCalc, to make it run like a main app. Lost the ability to set the title, will be fixed later.Whoops, I seem to have lost the ability to switch on F1..F4. No doubt because the window has no way to activate another one.Brian Theado - I haven't seen that behavior, but I do notice on Windows XP, a text widget (like one created in the above code snippet) can't get the focus whatever I try (clicking, explicitly calling focus in the slave). Button clicks (i.e. clicking tags) work fine. A post on c.l.t [4] suggests this problem exists for entry widgets as well.20dec04 Brian Theado - The focus problem for embedded text and entry widgets has been resolved in CVS head for win32. See discussion of tk bug 842945 [5 08oct04 jcw - GooWee 0.3 adds the GRIDPLUS package, and uses it to present a little welcome screen and basic documentation (this only just scratches the surface of what GRIDPLUS can do). There's still a problem with F1..F4 and button click focus, but the context is very transparent to each weeApp. Resizing the entire desktop now works. Exit is redefined in each slave to only tear down the corresponding app & window. Apps can be launched and replaced using "::gw::launch <n> appname". 14oct04 jsi - Very impressing! I played a little with the Goowee.kit + tclkit 8.4.2.6 on WIN NT4SP6 and on WIN XP Home SP1. Switching focus via F1..F4 works fine. Using F5 to end Goowee works fine too. I noticed that ending Goowee with ALT-F4 (the usual hotkey on windows) or the X-Button in the title-bar crashes Tclkit - as long as one of the four Goowee-windows contains weeCalc. Category Application - Category GUI
http://wiki.tcl.tk/12608
CC-MAIN-2017-04
refinedweb
1,153
75.1
Important: Please read the Qt Code of Conduct - Failing to load QODBC3 driver on Mac OS X Mojave - Mark Durkot last edited by Mark Durkot Hello guys, I've been recently trying to connect to MS SQL Server using Qt 5.14.1. My current OS is Mac OS X Mojave 10.14.6 After I built ODCB driver I get an error message while running the project: // objc[13030]: Class QMacAutoReleasePoolTracker is implemented in both /Users/md/Qt/5.14.1/clang_64/lib/QtCore.framework/Versions/5/QtCore (0x101d21030) and /Users/md/Qt/5.14.1/clang_64/plugins/sqldrivers/libqsqlodbc.dylib (0x10608e6c8). One of the two will be used. Which one is undefined. objc[13030]: Class QT_ROOT_LEVEL_POOL__THESE_OBJECTS_WILL_BE_RELEASED_WHEN_QAPP_GOES_OUT_OF_SCOPE is implemented in both /Users/md/Qt/5.14.1/clang_64/lib/QtCore.framework/Versions/5/QtCore (0x101d210a8) and /Users/md/Qt/5.14.1/clang_64/plugins/sqldrivers/libqsqlodbc.dylib (0x10608e740). One of the two will be used. Which one is undefined. objc[13030]: Class KeyValueObserver is implemented in both /Users/md/Qt/5.14.1/clang_64/lib/QtCore.framework/Versions/5/QtCore (0x101d210d0) and /Users/md/Qt/5.14.1/clang_64/plugins/sqldrivers/libqsqlodbc.dylib (0x10608e768). One of the two will be used. Which one is undefined. objc[13030]: Class RunLoopModeTracker is implemented in both /Users/md/Qt/5.14.1/clang_64/lib/QtCore.framework/Versions/5/QtCore (0x101d21120) and /Users/md/Qt/5.14.1/clang_64/plugins/sqldrivers/libqsqlodbc.dylib (0x10608e7b8). One of the two will be used. Which one is undefined. QObject::moveToThread: Current thread (0x7fdd61c03af0) is not the object's thread (0x7fdd61e89900). Cannot move to target thread (0x7fdd61c03af0) You might be loading two sets of Qt binaries into the same process. Check that all plugins are compiled against the right Qt binaries. Export DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries are being loaded. QSqlDatabase: QODBC3 driver not loaded QSqlDatabase: available drivers: QSQLITE QODBC QODBC3 QPSQL QPSQL7 Error "Driver not loaded Driver not loaded" // the isDriverAvailable("QODBC3") return TRUE I've installed unixODBC and FreeTDS. Then I built ODCB doing: PathToQt/5.14.1/clang_64/bin/qmake "INCLUDEPATH+=/usr/local/unixODBC/include" "LIBS+=-L/usr/local/unixODBC/lib -lodbc" odbc.pro Than running make and than make install. Everything seemed to be okay... No errors occurred. My c++ code. I know it may be not correc: db = QSqlDatabase::addDatabase("QODBC3"); db.setConnectOptions(); QString dns = QString("DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Trusted_Connection=Yes;").arg("localhost").arg("QtTestDataBase"); db.setDatabaseName(dns); if (!db.open()) { qDebug() << "Error" << db.lastError().text(); return; } So the Error printed with qDebug() is: "Driver not loaded Driver not loaded" Maybe I should try reinstalling Qt? I would appreciate your help, guys. Thank you. Hi, don't think you need to reinstall anything, but it is a bit tricky to get ODBC up and running on a Mac, Luckily this has been covered before on this forum, for example this answer is very useful. I just tested on a brand new Mac, with MacOS 10.15.4. First I installed Homebrew and Qt 5.14.1, then, as you did, the mandatory rebuild of Qt's ODBC plugin (so that it uses unixodbc and not iodbc). I followed the forum answer above, here is my version for Qt 5.14.1 (which is installed in the default place ~/Qt): $ brew install freeTDS $ cd ~/Qt/5.14.1/Src/qtbase/src/plugins/sqldrivers $ sed -i -e 's/-liodbc/-lodbc/' configure.json $ ~/Qt/5.14.1/clang_64/bin/qmake -- ODBC_PREFIX=/usr/local/Cellar/unixodbc/2.3.7 $ make sub-odbc $ cp plugins/sqldrivers/libqsqlodbc.dylib ~/Qt/5.14.1/clang_64/plugins/sqldrivers Then I started an MSSQLServer on 192.168.1.100 and tested with a Qt console program, here is the .pro file: QT -= gui QT += sql CONFIG += c++11 console CONFIG -= app_bundle SOURCES += main.cpp and here is the main.cpp: #include <QCoreApplication> #include <QTextStream> #include <QDir> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlRecord> #include <QtSql/QSqlError> #include <QSqlQuery> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // try to load the SQL ODBC plugin auto db = QSqlDatabase::addDatabase("QODBC3"); if (!db.isValid()) qFatal("addDatabase(QODBC) failed :-("); // prepare the args QString sServerIP = "192.168.1.100"; QString sDatabase = "northwind"; QString sUsername = "sa"; QString sPassword = "adminsa"; // setup dummy DSN name and where the freeTDS .so driver file is QString sDSN = "dsn1"; QString sFilename = "/usr/local/lib/libtdsodbc.so"; // create an .odbc.ini file on our home directory QFile fOdbc(QDir::homePath() + "/.odbc.ini"); if (!fOdbc.open(QFile::WriteOnly | QFile::Text)) qFatal("open ~/.odbc.ini for write failed"); QTextStream tsOdbc(&fOdbc); tsOdbc << "[" << sDSN << "]" << "\n"; tsOdbc << "Driver = " << sFilename << "\n"; tsOdbc << "Servername = " << sDSN << "\n"; tsOdbc << "Database = " << sDatabase << "\n"; tsOdbc.flush(); fOdbc.close(); // create a .freetds.conf file on our home directory QFile fFreeTds(QDir::homePath() + "/.freetds.conf"); if (!fFreeTds.open(QFile::WriteOnly | QFile::Text)) qFatal("open ~/.freetds.conf for write failed"); QTextStream tsFT(&fFreeTds); tsFT << "[" << sDSN << "]" << "\n"; tsFT << "host = " << sServerIP << "\n"; tsFT << "port = 1433" << "\n"; tsFT << "tds version = 7.0" << "\n"; tsFT.flush(); fFreeTds.close(); db.setDatabaseName(sDSN); if (!db.open(sUsername,sPassword)) qFatal("open() failed, error = '%s'",qUtf8Printable(db.lastError().text())); QTextStream cout(stdout); // party on the db (dump all the customers) auto query = QSqlQuery("select * from Customers"); auto columns = query.record().count(); while (query.next()) for (auto c = 0; (c < columns); ++c) cout << QString::number(c) << " : " << query.value(c).toString() << "\n"; // that's all folks db.close(); } and it runs fine and prints all the Northwind db's customers. Note: on MacOS it's very difficult to use the kind of databasenames you use (i.e "..DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Trusted_Connection=Yes;"), instead I create 2 files: .odbc.ini and .freetds.conf Forgot one thing: for umlaut characters to appear correctly from the Northwind's customers (in the test program above), like these: ... 4 : Berguvsvägen 8 5 : Luleå ... you should add a "client charset" line to the .freetds.conf file, like this: QTextStream tsFT(&fFreeTds); tsFT << "[" << sDSN << "]" << "\n"; tsFT << "host = " << sServerIP << "\n"; tsFT << "port = 1433" << "\n"; tsFT << "tds version = 7.0" << "\n"; tsFT << "client charset = UTF-8" << "\n"; P.S. I have an old MSSQLServer 2008 R2, if you have a more recent version, you might need to change the "tds version..." in the .freetds.conf file to something higher, like 7.3. - Mark Durkot last edited by Mark Durkot @hskoglund First thank you for such a quick reply I appreciate it. It might be a stupid question of mine but following your guide I ran into problem at the beginning: sqldrivers$ make sub-odbc make: *** No rule to make target `sub-odbc'. Stop. If I run just "make" I can't find the libqsqlodbc.dylib anywhere What does actually "sub-odbc" do? I also don't get any Configuration Summary after running qmake script @Mark-Durkot You might have some debris left over from previous builds. To be sure, nuke the whole Src directory and download it again (I use Qt's MaintenanceTool to remove "Sources" and install "Sources" again). Now you should have a clean slate, try the "sed.." and "qmake..." steps again, hopefully you'll get a Configuration Summary this time. The make sub-odbc command tells make to build the subtarget odbc (and skip the subtarget sqlite). - Mark Durkot last edited by @hskoglund Dear mate, I have to say huge THANK YOU for your help! I'm sorry for taking your time! Finally after reinstalling Sources I got all the terminal commands running perfect and giving no errors! I also successfully connected to my database and was able to read data! Tack så mycket (if your are from Sweden) :) @Mark-Durkot Thanks! Sure, I'm native Swedish. Don't worry about the time, last week I got the Corona (the flu, not the beer), felt like an old man for a couple of days, this week I am well again but staying at home. So answering questions on this forum is a great way to stay in touch with the outside world :-) - Mark Durkot last edited by @hskoglund Ohh, I wish you get in a completely fit form as soon as possible (to be able to go get the Corona beer now))) :) @Mark-Durkot No worries, I'm back in business, went looking today for one of these:
https://forum.qt.io/topic/112909/failing-to-load-qodbc3-driver-on-mac-os-x-mojave
CC-MAIN-2020-40
refinedweb
1,382
59.3
I can’t remember the last time I dabbled with Phoenix. Whenever it was, I was messing with channels and all the real time goodness. This year at Elixir Conf I heard about a lot of new changes in Phoenix from Chris McCord and sure enough, when I sat down to create a Phoenix JSON API, most of the tutorials and examples I found were outdated. Phoenix 1.3 was released in July and with it came Contexts. They land with an admittedly bad name (says Chris), but provide a beneficial grouping of related functionality and a good foundation for application growth. The addition of Contexts also means one extra parameter for the mix phx.gen.json generator to specify its grouping. Be sure to have the dependencies for creating a new Phoenix app installed. If you’re not sure what that means, take a look at the guides for installation. Once Phoenix is installed you can verify the version with mix. > mix phx.new --version Phoenix v1.3.0 mix phx.new also happens to be the command to create a new Phoenix project. Brunch.io is included in a default Phoenix app for compiling assets and uses npm, but when developing strictly a JSON API there are no assets and thus, brunch can be omitted. There is also no visual piece and the html layer can also be omitted. > mix phx.new --no-brunch --no-html {api_name} This will kick off creation of the API and prompt to download dependencies. Once completed there are just a few minor “clean up” items to make it truly an API-only Phoenix application. lib/{api_name}_web/channelsdirectory > rm -rf lib/{api_name}_web/channels test/{api_name}_web/channelsdirectory > rm -rf test/{api_name}_web/channels lib/{api_name}_web/endpoint.exfile, remove this line: socket "/socket", {ApiName}Web.UserSocket lib/{api_name}_web/endpoint.exfile, remove this line: only: ~w(css fonts images js favicon.ico robots.txt) and be sure to remove the , on the preceding line. lib/{api_name}_web.exfile, remove these lines: def channel do quote do use Phoenix.Channel import TossWeb.Gettext end end Inside of config/dev.exs the settings for the database connection in development can be found. Be sure the username and password properties reflect your environment. username: "postgres", password: "", The next step is to create the database for this API: run mix ecto.create. This example will provide blog post records, so we will need a Post module. To create the module the mix phx.gen.json generator will be used. It requires the Context, the singular module name, and the plural table name. Everything after the initial 3 arguments will be attributes for the model. For this example Post will be grouped inside the Blog context, and we will start with just title and an is_published boolean flag. As mentioned earlier, having context now allows us to group logical pieces of the API together. If later a Comment module was added to this API, for example, it could also be grouped within the Blog context. I’m sure you can think of other useful progressions of this grouping as the API grows. > mix phx.gen.json Blog Post posts title:string is_published:boolean Remove the functions in the newly generated post_controller that will not be used for this example: the create, update, and delete methods. Removing these methods means we can also remove the alias for the Post module on line 5. alias {ApiName}.Blog.Post Be sure to run mix ecto.migrate. The API now has the changes in the database and the Post module and controller. In order to now hit the controller, the routes need to be added into the lib/{api_name}_web/router.ex file. When writing an API I prefer to namespace resources into a specific API version. In order to do this, the scope "/api" block needs to be expanded a bit. scope "/api", {ApiName}iWeb, as: :api do pipe_through :api scope "/v1", V1, as: :v1 do resources "/posts", PostController, only: [:index, :show] end end To confirm that the new routes exist as expected, run mix phx.routes and see them listed out: > mix phx.routes v1_post_path GET /api/v1/posts {ApiName}Web.V1.PostController :index v1_post_path GET /api/v1/posts/:id {ApiName}Web.V1.PostController :show When looking closely at the routes that are listed above, you can see a naming difference. The listed controller name is {ApiName}Web.V1.PostController but opening the lib/{api_name}_web/controllers/posts_controller.ex shows a different module name: {ApiName}Web.PostController. This will have to be renamed to match and to group controllers within the same API version, it can be contained within its own lib/{api_name}_web/controllers/v1 folder. > mkdir v1 > mv posts_controller.ex v1/ And then rename the controller module to {ApiName}Web.V1.PostController. A similar thing will have to happen for the corresponding view. Right now we don’t have to worry too much about the contents of the lib/{api_name}_web/views/post_view.ex because it will be replaced soon enough - but this file will have to also belong to a lib/{api_name}_web/views/v1 folder and the module renamed to {ApiName}Web.V1.PostView. > mkdir v1 > mv posts_view.ex v1 And then rename the view module to {ApiName}Web.V1.PostView. In the View module, there also is an alias that needs to be updated on line 3 to reflect the new namespace: alias {ApiName}Web.V1.PostView Spin up the server with mix phx.server and using your preferred REST client try and hit. Make sure you have Content-Type: application/json in whatever REST client you happen to use. You should receive an empty response. { "data": [] } Seed data in a Phoenix app is straightforward and there is some foundation laid to create consistency. There is a file named priv/repo/seeds.ex which we can put our seed data for the database. We can just write direct inserts to our database in here and then we can run it with mix run. alias {ApiName}.Repo alias {ApiName}.Blog.Post Repo.insert!(%Post{title: "Getting started with Phoenix and JSON API", is_published: true}) Repo.insert!(%Post{title: "Next steps with Phoenix and JSON API", is_published: false}) This can be executed with mix run priv/repo/seeds.ex. Now hit again and you should see the two records returned as JSON. { "data": [ { "id": 1, "is_published": true, "title": "Getting started with Phoenix and JSON API" }, { "id": 2, "is_published": false, "title": "Next steps with Phoenix and JSON API" } ] } This is all great and it’s almost a good beginning. All that needs to happen now is for the response to be in the JSON-API specification. This is made easier with the use of the [jaserializer][ja-serializer] package. Dependencies for a Phoenix app get added to mix.exs in the defp deps do block. At the time of writing this, the newest version of jaserializer is 0.12.0 so be sure to confirm your versions are up to date. Add a line in the defp deps do block of mix.exs to include this new dependency. {:ja_serializer, "~> 0.12.0"} Whenever a new dependency is added to an Elixir app, mix deps.get needs to be run. json-apimime-type We need to configure the json-api mime-type to serialize JSON API. This can be done inside config/config.exs config :phoenix, :format_encoders, "json-api": Poison config :mime, :types, %{ "application/vnd.api+json" => ["json-api"] } After modifying Plug, we have to recompile: > mix deps.clean plug --build > mix deps.get And now we can add the json-api plug to the api pipeline defined in lib/{api_name}_web/router.ex. If you know for sure your API will only accept json-api then you can remove the existing json from the plug list. pipeline :api do plug :accepts, ["json-api"] end There are two different ways to configure the views in a Phoenix API to serialize with jaserializer. One is by adding a use statement to each individual View module: use JaSerializer.PhoenixView This is useful if you want to pick and choose when you will be serializing in JSON API or something else. If this is an evergreen API, though, chances are you plan on building everything out as a JSON API endpoint, so you’ll need this for each View. We can add the use statement collectively to all View modules by adding it to the lib/{api_name}_web.ex file under the def view do block: def view do quote do use Phoenix.View, root: "lib/{api_name}_web/templates", namespace: {ApiName}Web use JaSerializer.PhoenixView ... Now the alteration to the lib/{api_name}_web/views/v1/post_view.ex can happen. Now that we are using jaserializer our views become a definition of what we want to serialize. Inside the view file we could define relationships or individual attributes. The Post model in this API is simple and just has two attributes but more info on how to serialize relationships can be found in the jaserializer github README. Update the View file to serialize the attributes for our model: defmodule {ApiName}Web.V1.PostView do use {ApiName}Web, :view attributes [:title, :is_published] end Right now the controller is rendering index.json and show.json in the respective action handlers. This needs to be updated with the correct content type of json-api, and the posts and data to correspond to the JSON API specification. Update the index block: render(conn, "index.json-api", data: posts) Update the show block: render(conn, "show.json-api", data: posts) Now if we hit we will see the expected response for our inserted data returned in JSON API format! { "data": [ { "attributes": { "is-published": true, "title": "Getting started with Phoenix and JSON API" }, "id": "1", "type": "post" }, { "attributes": { "is-published": false, "title": "Next steps with Phoenix and JSON API" }, "id": "2", "type": "post" } ], "jsonapi": { "version": "1.0" } } And similarly, if we travel to our first record will be returned in JSON API format as well. { "data": { "attributes": { "is-published": true, "title": "Getting started with Phoenix and JSON API" }, "id": "1", "type": "post" }, "jsonapi": { "version": "1.0" } } Congratulations! You have your first JSON API with Phoenix! Please feel free to kindly share your corrections, misinformations, or suggestions in the comments.
https://hbrysiewicz.com/2017-09-21-phoenix-api-starter.html
CC-MAIN-2021-43
refinedweb
1,722
66.44
I love strftime. It has been around for such a long time that it is almost second nature to me. And yet, Dart does not have strftime, which makes me sad. Even when first reported, the Dart maintainers indicated that they favored an internationalization approach to date formatting. I have remained skeptical ever since. Today, I am going to give it a try. I still think it likely that I will end up writing my own strftime package in Dart, but let's see first. That said, I have to admit that the default date/time format in Dart is very much to my liking. The only date/time format that I like is ISO 8601, which is just what Dart does. In my HTTP logging code, I have been directly interpolating a DateTimeobject ( now) into a string: log(req) { req.response.done.then((res){ var now = new DateTime.now(); print('[${now}] "${req.method} ${req.uri.path}" ${logStatusCode(res)}'); }); }The result is a very sensible iso8601 string with millisecond precision: [2013-09-02 13:32:04.825] "DELETE /widgets/958c9320-f0d0-11e2-c5d0-df3be6475337" 204 [2013-09-02 13:32:04.829] "GET /widgets/958c9320-f0d0-11e2-c5d0-df3be6475337" 404I am not used to seeing that level of precision in HTTP logs, but I rather like it. Still, what if I wanted to remove it and add the numeric timezone (e.g. -0500) to make the timestamp more Apache-like? I start by adding the intlpackages to the list of dependencies in my project: name: plummbur_kruk description: A real pretend server for testing. #... dependencies: # ... intl: anyThen I Pub install my newest dependency (along with its dependencies): ➜ plummbur-kruk git:(master) ✗ pub install Resolving dependencies............................ Downloading logging 0.6.19 from hosted... Downloading unmodifiable_collection 0.6.19 from hosted... Downloading intl 0.6.19 from hosted... Downloading analyzer_experimental 0.6.19 from hosted... Downloading args 0.6.19 from hosted... Dependencies installed!Finally, I import the intlpackage into my code: library plummbur_kruk; import 'dart:io'; import 'package:json/json.dart' as JSON; import 'package:intl/intl.dart'; // ...Now, to add the timezone to the iso8601 date, I ought to be able to use the default format with the time zone appended. The add_jz()method ought to do the trick: // ... final DateFormat _timestamp = new DateFormat().add_jz(); String get timestamp { return _timestamp.format(new DateTime.now()); } // ...Only that blows up pretty badly: Uncaught Error: UnimplementedError Stack Trace: #0 _DateFormatPatternField.formatTimeZone (package:intl/src/date_format_field.dart:385:5) #1 _DateFormatPatternField.formatField (package:intl/src/date_format_field.dart:174:38) #2 _DateFormatPatternField.format (package:intl/src/date_format_field.dart:112:25) #3 DateFormat.format.<anonymous closure> (package:intl/date_format.dart:231:63) #4 List.forEach (dart:core-patch/growable_array.dart:182:8) #5 DateFormat.format (package:intl/date_format.dart:231:26) #6 timestamp (package:plummbur_kruk/server.dart:226:27) #7 log.<anonymous closure> (package:plummbur_kruk/server.dart:219:15) ...After a bit of digging, I find that I have a pretty darn good knack for finding the one thing in libraries that is not quite done: // packages/intl/src/date_format_field.dart // ... String formatTimeZoneId(DateTime date) { // TODO: implement time zone support throw new UnimplementedError(); } // ...Darn it. Well, I am not going to get exactly what I want from the DateFormatclass, but I would still like to get a feel for how it works. As I said, I rather prefer the ISO 8601 format for date formatting, but if I wanted more of a standard Apache log along the lines of: [02/Sep/2013:09:28:08 -0400]How easy is it to make? Actually, it is quite easy: final DateFormat _timestamp = new DateFormat('dd/MMM/y HH:mm:ss');This produces: Now: 02/Sep/2013 22:22:30Aside from Apache's ridiculous colon-before-the-time thing, this is exactly what I want. But there is no way that I am going to remember those “skeleton” formats. The thing that strftime always had going for it (and even the datecommand) was that the hours, minutes, and seconds are all capital letters: $ date +%H:%M:%S 22:28:15Anything beyond that and I can pretty much infer given that times are uppercase: date +'%Y-%m-%d %H:%M:%S' 2013-09-02 22:29:50The mixing and matching of case in Dart's DateFormatfeels awkward in comparison. The documentation makes mention of standards (ICU/JDK), so hopefully it will be comfortable for others. I can live with it as is. Before calling it a night, I give the internationalization a whirl. The way this works in Dart is that a top-level initializeDateFormat()call is made. The return value is a Future, which completes when the specified locale is loaded (from the filesystem or from a webserver), at which point code can run. For a server-side test, I use: import 'package:intl/intl.dart'; import 'package:intl/date_symbol_data_local.dart'; main() { initializeDateFormatting(null, null).then((_) { // timestamp here... }); }The arguments to initializeDateFormatting()are a little different depending on which file is imported. The one that I choose, date_symbol_data_localactually ignores both arguments—hence the two nulls. For other imports, the first argument indicates the locale to be loaded, which cuts down on bandwidth. With the import that I have chosen, I just load all of the locales. To use a locale, I supply it as the second argument to a DateFormatconstructor: main() { initializeDateFormatting(null, null).then((_) { print('Now: ${timestamp}'); }); } final DateFormat _timestamp = new DateFormat('dd/MMM/y HH:mm:ss', 'fr_FR'); String get timestamp { return _timestamp.format(new DateTime.now()); }The result is: $ dart date_format_test.dart Now: 02/sept./2013 23:48:50Which is (I guess) the short month version of September in French. I am still unsure about using this in an actual application. Does the entire application have to wait until the locale data is loaded? If not that, then does each individual field get wrapped in that Future? Questions for another day. For now, it is good to know that internationalization is baked into the language from the outset. Day #862
https://japhr.blogspot.com/2013/09/date-formatting-in-dart.html
CC-MAIN-2018-22
refinedweb
1,005
51.85
have done this on one of my solutions where I had to keep photos of all visitors at some company. This question crops up quite often, and the answer is always the same. Have a look at some of these articles too: HTH The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified! Regardless, you need to avoid adding the images directly into the database - plays havoc with all kinds of database issues - not least of which is size and manageabilty of the database in general. The thing with filestream can depend on who "owns" the data and what external resources need access (and type of access). If you consider the single main difference as a point of ownership, it helps put things into perspective. SQL owns filestream. It has to be enabled : EXEC sp_filestream_configure @enable_level = 3 The owner of the SQL Server Service should really be a domain user so that the domain user can "own" the directory / data repository on disk (ie in its own private namespace on the local NTFS) and uses it's own naming philosophies based on a mandatory row GUID, and so is essentially masked from the user. From a web / internet perspective, it is not the user or web server needing access, it is the SQL Server Service needing access. It does have benefits in being "owned" by SQL server - things like backups and versioning are readily handled. Going external means you have to manage. But then it can be quite seperate to the SQL Server, can have different security policies in place and can have other applications directly accessing the images. So, there are two viable alternatives. One which is the equivelent of capturing the image as at a point of time within the database realm, and the other using a file / path pointer inside the database to and externally available folder. Both keep the blob data outside the database and that is really the bottom line for the question as asked. Keep it external.
https://www.experts-exchange.com/questions/24287765/vb-net-sql-server-solution-store-images-in-file-system-or-database.html
CC-MAIN-2018-17
refinedweb
341
60.75
27 March 2008 23:28 [Source: ICIS news] HOUSTON (ICIS news)--West European and North American polypropylene (PP) producers should be ready to close unprofitable operations as an unprecedented level of global capacity builds up, an industry consultant said on Thursday. “In 2007, about 200,000 tonnes of PP capacity were shut down in West Europe and ?xml:namespace> Sagel told attendees at the CMAI World Petrochemical Conference here that Western European and North American producers also should be prepared to lose their export position. North American producers have recently depended heavily upon exports to bring balance to their domestic market, he explained. “Your future plans should include contingencies to deal with the potential that exports may not be there to sustain your operating rates,” he said. A continuous wave of new projects is expected to hit the PP industry with 9m tonnes/year being added in the 2008-2010 period. There is a concentration of new projects in the Middle East and Asia but also new capacity in Europe, During the first quarter of 2008, 2.5m tonnes/year of new capacity started up around the world and even a larger amount of 2.7m tonnes/year is expected to start up in the fourth quarter this year. Sagel explained that as excess capacity builds up, a fierce battle will take place for export markets. “Any producers with uncompetitive costs of production are going to have a hard time maintaining their export positions,” he added. For more on polypropylene
http://www.icis.com/Articles/2008/03/27/9111378/Hard-times-ahead-for-some-PP-plants-consultant.html
CC-MAIN-2014-42
refinedweb
250
51.18
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway. In .NET 2.0, the notion of nullable types has been added. But I have the feeling that lots of developpers miss some basic understanding about this. So I have decided to add here some thoughts and explanation about the nullable types. Note that a primitive type has the following declaration in the .NET framework: public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int> In comparison, the Nullable<T> class has the following declaration: public struct Nullable<T> where T: struct int? i = null; //Equivalent to "Nullable<int> i = null;" Console.WriteLine(i); //Display "" Console.WriteLine(i.HasValue); //Display "False" Console.WriteLine(i.Value); //Generates a "InvalidOperationException : //Nullable object must have a value" Console.WriteLine(typeof(int?)); //Display "System.Nullable`1[System.Int32]" Console.WriteLine(i.GetType()); //Generates a "NullReferenceException" int? j = 10; Console.WriteLine(j); //Display "10" Console.WriteLine(j.HasValue); //Display "True" Console.WriteLine(j.Value); //Display "10" Console.WriteLine(j.GetType()); //Display "System.Int32" On generic types, you have the “default” operator. This operator returns the default value for a generic parameter type, meaning: public class GenericClass<T> { public override string ToString() { object o = default(T); return o == null ? "null" : o.ToString(); } public static void Main() GenericClass<int> myInt = new GenericClass<int>(); GenericClass<object> myObject = new GenericClass<object>(); Console.WriteLine(myInt.ToString()); //Display “0” Console.WriteLine(myObject.ToString()); //Display “null” } The nullable types are in fact the structure “Nullable<T>”that expose a method “GetValueOrDefault”. This method will act as the “default” operator in case the nullable types do not have any value. int? i = null; //To be able to add the value of a nullable type, we can use the “Value” property //after testing that this type has a value. int total1 = 0; if ( i.HasValue ) total1 += i.Value; if ( j.HasValue ) total1 += j.Value; Console.WriteLine(total1); //Or we can use the “GetValueOrDefault” method on the object int total2 = i.GetValueOrDefault() + j.GetValueOrDefault(); Console.WriteLine(total2); It will of course depend of the cases, but usually the second syntax will allow having clearer (and shorter) code. int? k = 20; Console.WriteLine(i < j); //Display "False" Console.WriteLine(i > j); //Display "False" Console.WriteLine(i == j); //Display "False" Console.WriteLine(i != j); //Display "True" Console.WriteLine(k < j); //Display "False" Console.WriteLine(k > j); //Display "True" Console.WriteLine(k == j); //Display "False" Console.WriteLine(k != j); //Display "True" So you can use the comparison operators without any problem. You don’t need to test the “HasValue” property before doing the comparison. Just keep in mind that this very short syntax is converted by the compiler as follows : //The following syntax i < j //is transformed (at compile-time) into (i.GetValueOrDefault() < j.GetValueOrDefault()) && (i.HasValue & j.HasValue) Just note that if you need to do a special treatment in the “null” case, you will have to use the “HasValue” property. if ( i < j ) { // Only in the case i AND j have a value AND i.Value < j.Value else // Will be called whenever i OR j do not have a value OR i.Value >= j.Value My team and I are working for two years on a big XP project now. Among the 8 developpers, we can find all the levels and all the educations. Some are engineers - for which IT is their first choice - and some were doing another job and have decided to switch direction. Of course this does not mean that a kind of developper is better than another one, but this mean that we all have a different approach to a same problem, a different point of view, interpretation and understanding, depending of our experience, meaning habits, past and education. Most of us had not done XP before this project, meaning that we had learned the methodology progressively and we have started to own it and to "customize" it to our needs. For some of the group, XP has oftenly been considered as an excuse to do less. I mean I encounter people saying "No we shouldn't do that, because XP is iterative and so we should do only what we need for now. Let's do it simple, not more". Said like that, it seems to be fully correct. Nevertheless, there is a huge misunderstanding behind this word of "simple". Are we speaking of "simple code" or of "simpler solution" ? There seem not to be any difference but it's huge and will drive all the future development. We could turn this question in another one - as it is in my view to exact ending of it - shall we throw the code in the future or shall we make it evolve ? I have regulrarly fought during these 3 years to say : "simple do not mean to write very basic (too basic) code. So simple that this code will be thrown away in the next iteration because it is too simple (understand too low level, too concrete, without any level abstraction raised) to evolve". I'm now reading the book "Extreme.NET" by Neil Roodyn. Not a very recent one so the .NET part is a bit outdated but the "philosophical part" is still very accurated. There is a very nice sentence in it that, in my view, summarize all this to give a simple answer ;-) And by "simple" here, I mean an answer that should be able to make all developpers think about themselves and what they produce. "Simple does not mean easy. Developpers who are starting out often misinterpret this as "Do the easiest thing you can possibly do." [Pierre-Emmanuel Dautreppe's note : I would even say : "Do the more stupid thing you can"] This is incorrect; simple is often a lot harder to achieve than complicated. [...] The switch statement is easier to write, but the polymorphism provides a simpler solution." A "simple solution" means a clear and open solution, a solution that will be simple to make evolve, that won't be reluctant to changes. At the same time, Roy Osherove speaks about unit testing and call them TATs or TTLs, meaning "Throw-Away Tests" and "Tests That Lasts". For sure, it's a point that should make all of us think about our work. For sure, I will come back often to this point in the future. Didier Pieroux has sent me this interesting news ! I will simply translate the information he gave me: "Here is a news that has probably been unnoticed in the .NET world but for sure not in the world criticism systems: The interest of this news is not the fact that we can develop in ADA on the .NET stack but that this is now followed and developped by a major actor on the ADA world (contrary to A# that has been developped by a university of the USAF [Note : United States Air Force]). Of course, ADA will not takie some market positions to C# or VB. Of course, ADA won't become more popular because it is available on .NET. No the main important thing is - in my opinion - that it seem to have a demand of the domain that are traditionnaly ADA-oriented (and so Unix-oriented) to open to the .NET world (and so Microsoft). Until now, I had only seen from these domains a true interest to Java. A good news for the "Microsoftees" world in general . Interesting also, thare has been a previous initiative to compile ADA to JVM. Today, this initiative is in a clinical death state. I imagine that if AdaCore do a similar step to .NET, this means they think it will be more successfull than with Java !" Interesting step indeed ! And do not forget that in the same time Microsoft also do a step in the opposite direction with Silverlight and Linux. Loïc Bar has regrouped many articles speaking of that in this news. Crystal Reports may generate some temporary files ('*.tmp', '*.rpt') in a temp folder (typically the c:\windows\temp folder or you temp folder in "Local Settings"). This is not a big deal because these files are quite small (between 0k and 200k for the ones I have seen during my investigations) but it can be a potential problems as they are very numerous (till 10 for a single export) and contains some potentially sensitive information (some data of your exports). I have seen that these files are generated by the following methods: How to correct this problem ? Of course, you could call only the "Dispose()" method as it will call internally the "Close()" method, or even not calling any of them but using the "using" syntax CITCON (Continuous Integration & Testing Conference) comes to Brussels in October 19th & 20th (friday evening and saturday). Interested in 1-day of great conference about CI and testing ? Join me there ! Be careful, it's limited to the first 100 subscribee so hurry up. Need more information about CITCON ? Visit their website dedicated to Brussels !
http://www.pedautreppe.com/2007/09/default.aspx
CC-MAIN-2017-43
refinedweb
1,501
65.52
Introduction to Monte Carlo Tree Search The subject of game AI generally begins with so-called perfect information games. These are turn-based games where the players have no information hidden from each other and there is no element of chance in the game mechanics (such as by rolling dice or drawing cards from a shuffled deck). Tic Tac Toe, Connect 4, Checkers, Reversi, Chess, and Go are all games of this type. Because everything in this type of game is fully determined, a tree can, in theory, be constructed that contains all possible outcomes, and a value assigned corresponding to a win or a loss for one of the players. Finding the best possible play, then, is a matter of doing a search on the tree, with the method of choice at each level alternating between picking the maximum value and picking the minimum value, matching the different players' conflicting goals, as the search proceeds down the tree. This algorithm is called Minimax. The problem with Minimax, though, is that it can take an impractical amount of time to do a full search of the game tree. This is particularly true for games with a high branching factor, or high average number of available moves per turn. This is because the basic version of Minimax needs to search all of the nodes in the tree to find the optimal solution, and the number of nodes in the tree that must be checked grows exponentially with the branching factor. There are methods of mitigating this problem, such as searching only to a limited number of moves ahead (or ply) and then using an evaluation function to estimate the value of the position, or by pruning branches to be searched if they are unlikely to be worthwhile. Many of these techniques, though, require encoding domain knowledge about the game, which may be difficult to gather or formulate. And while such methods have produced Chess programs capable of defeating grandmasters, similar success in Go has been elusive, particularly for programs playing on the full 19x19 board. However, there is a game AI technique that does do well for games with a high branching factor and has come to dominate the field of Go playing programs. It is easy to create a basic implementation of this algorithm that will give good results for games with a smaller branching factor, and relatively simple adaptations can build on it and improve it for games like Chess or Go. It can be configured to stop after any desired amount of time, with longer times resulting in stronger game play. Since it doesn't necessarily require game-specific knowledge, it can be used for general game playing. It may even be adaptable to games that incorporate randomness in the rules. This technique is called Monte Carlo Tree Search. In this article I will describe how MCTS works, specifically a variant called Upper Confidence bound applied to Trees (UCT), and then will show you how to build a basic implementation in Python. Imagine, if you will, that you are faced with a row of slot machines, each with different payout probabilities and amounts. As a rational person (if you are going to play them at all), you would prefer to use a strategy that will allow you to maximize your net gain. But how can you do that? For whatever reason, there is no one nearby, so you can't watch someone else play for a while to gain information about which is the best machine. Clearly, your strategy is going to have to balance playing all of the machines to gather that information yourself, with concentrating your plays on the observed best machine. One strategy, called UCB1, does this by constructing statistical confidence intervals for each machine where: - \(\bar{x}_i\): the mean payout for machine \(i\) - \(n_i\): the number of plays of machine \(i\) - \(n\): the total number of plays Then, your strategy is to pick the machine with the highest upper bound each time. As you do so, the observed mean value for that machine will shift and its confidence interval will become narrower, but all of the other machines' intervals will widen. Eventually, one of the other machines will have an upper bound that exceeds that of your current one, and you will switch to that one. This strategy has the property that your regret, the difference between what you would have won by playing solely on the actual best slot machine and your expected winnings under the strategy that you do use, grows only as \(\mathcal{O}(\ln n)\). This is the same big-O growth rate as the theoretical best for this problem (referred to as the multi-armed bandit problem), and has the additional benefit of being easy to calculate. And here's how Monte Carlo comes in. In a standard Monte Carlo process, a large number of random simulations are run, in this case, from the board position that you want to find the best move for. Statistics are kept for each possible move from this starting state, and then the move with the best overall results is returned. The downside to this method, though, is that for any given turn in the simulation, there may be many possible moves, but only one or two that are good. If a random move is chosen each turn, it becomes extremely unlikely that the simulation will hit upon the best path forward. So, UCT has been proposed as an enhancement. The idea is this: any given board position can be considered a multi-armed bandit problem, if statistics are available for all of the positions that are only one move away. So instead of doing many purely random simulations, UCT works by doing many multi-phase playouts. Selection The first phase, selection, lasts while you have the statistics necessary to treat each position you reach as a multi-armed bandit problem. The move to use, then, would be chosen by the UCB1 algorithm instead of randomly, and applied to obtain the next position to be considered. Selection would then proceed until you reach a position where not all of the child positions have statistics recorded. Expansion The second phase, expansion, occurs when you can no longer apply UCB1. An unvisited child position is randomly chosen, and a new record node is added to the tree of statistics. Simulation After expansion occurs, the remainder of the playout is in phase 3, simulation. This is done as a typical Monte Carlo simulation, either purely random or with some simple weighting heuristics if a light playout is desired, or by using some computationally expensive heuristics and evaluations for a heavy playout. For games with a lower branching factor, a light playout can give good results. Back-Propagation Finally, the fourth phase is the update or back-propagation phase. This occurs when the playout reaches the end of the game. All of the positions visited during this playout have their play count incremented, and if the player for that position won the playout, the win count is also incremented. This algorithm may be configured to stop after any desired length of time, or on some other condition. As more and more playouts are run, the tree of statistics grows in memory and the move that will finally be chosen will converge towards the actual optimal play, though that may take a very long time, depending on the game. For more details about the mathematics of UCB1 and UCT, see Finite-time Analysis of the Multiarmed Bandit Problem and Bandit based Monte-Carlo Planning. Now let's see some code. To separate concerns, we're going to need a Board class, whose purpose is to encapsulate the rules of a game and which will care nothing about the AI, and a MonteCarlo class, which will only care about the AI algorithm and will query into the Board object in order to obtain information about the game. Let's assume a Board class supporting this interface: class Board(object): def start(self): # Returns a representation of the starting state of the game. pass def current_player(self, state): # Takes the game state and returns the current player's # number. pass def next_state(self, state, play): # Takes the game state, and the move to be applied. # Returns the new game state. pass def legal_plays(self, state_history): # Takes a sequence of game states representing the full # game history, and returns the full list of moves that # are legal plays for the current player. pass def winner(self, state_history): # Takes a sequence of game states representing the full # game history. If the game is now won, return the player # number. If the game is still ongoing, return zero. If # the game is tied, return a different distinct value, e.g. -1. pass For the purposes of this article I'm not going to flesh this part out any further, but for example code you can find one of my implementations on github. However, it is important to note that we will require that the state data structure is hashable and equivalent states hash to the same value. I personally use flat tuples as my state data structures. The AI class we will be constructing will support this interface: class MonteCarlo(object): def __init__(self, board, **kwargs): # Takes an instance of a Board and optionally some keyword # arguments. Initializes the list of game states and the # statistics tables. pass def update(self, state): # Takes a game state, and appends it to the history. pass def get_play(self): # Causes the AI to calculate the best move from the # current game state and return it. pass def run_simulation(self): # Plays out a "random" game from the current position, # then updates the statistics tables with the result. pass Let's begin with the initialization and bookkeeping. The board object is what the AI will be using to obtain information about where the game is going and what the AI is allowed to do, so we need to store it. Additionally, we need to keep track of the state data as we get it. class MonteCarlo(object): def __init__(self, board, **kwargs): self.board = board self.states = [] def update(self, state): self.states.append(state) The UCT algorithm relies on playing out multiple games from the current state, so let's add that next. import datetime class MonteCarlo(object): def __init__(self, board, **kwargs): # ... seconds = kwargs.get('time', 30) self.calculation_time = datetime.timedelta(seconds=seconds) # ... def get_play(self): begin = datetime.datetime.utcnow() while datetime.datetime.utcnow() - begin < self.calculation_time: self.run_simulation() Here we've defined a configuration option for the amount of time to spend on a calculation, and get_play will repeatedly call run_simulation until that amount of time has passed. This code won't do anything particularly useful yet, because we still haven't defined run_simulation, so let's do that now. # ... from random import choice class MonteCarlo(object): def __init__(self, board, **kwargs): # ... self.max_moves = kwargs.get('max_moves', 100) # ... def run_simulation(self): states_copy = self.states[:] state = states_copy[-1] for t in xrange(self.max_moves): legal = self.board.legal_plays(states_copy) play = choice(legal) state = self.board.next_state(state, play) states_copy.append(state) winner = self.board.winner(states_copy) if winner: break This adds the beginnings of the run_simulation method, which either selects a move using UCB1 or chooses a random move from the set of legal moves each turn until the end of the game. We have also introduced a configuration option for limiting the number of moves forward that the AI will play. You may notice at this point that we are making a copy of self.states and adding new states to it, instead of adding directly to self.states. This is because self.states is the authoritative record of what has happened so far in the game, and we don't want to mess it up with these speculative moves from the simulations. Now we need to start keeping statistics on the game states that the AI hits during each run of run_simulation. The AI should pick the first unknown game state it reaches to add to the tables. class MonteCarlo(object): def __init__(self, board, **kwargs): # ... self.wins = {} self.plays = {} # ... def run_simulation(self): visited_states = set() states_copy = self.states[:] state = states_copy[-1] player = self.board.current_player(state) expand = True for t in xrange(self.max_moves): legal = self.board.legal_plays(states_copy) play = choice(legal) state = self.board.next_state(state, play) states_copy.append(state) # `player` here and below refers to the player # who moved into that particular state. if expand and (player, state) not in self.plays: expand = False self.plays[(player, state)] = 0 self.wins[(player, state)] = 0 visited_states.add((player, state)) player = self.board.current_player(state) winner = self.board.winner(states_copy) if winner: break for player, state in visited_states: if (player, state) not in self.plays: continue self.plays[(player, state)] += 1 if player == winner: self.wins[(player, state)] += 1 Here we've added two dictionaries to the AI, wins and plays, which will contain the counts for every game state that is being tracked. The run_simulation method now checks to see if the current state is the first new one it has encountered this call, and, if not, adds the state to both plays and wins, setting both values to zero. This method also adds every game state that it goes through to a set, and at the end updates plays and wins with those states in the set that are in the plays and wins dicts. We are now ready to base the AI's final decision on these statistics. from __future__ import division # ... class MonteCarlo(object): # ... def get_play(self): self.max_depth = 0 state = self.states[-1] player = self.board.current_player(state) legal = self.board.legal_plays(self.states[:]) # Bail out early if there is no real choice to be made. if not legal: return if len(legal) == 1: return legal[0] games = 0 begin = datetime.datetime.utcnow() while datetime.datetime.utcnow() - begin < self.calculation_time: self.run_simulation() games += 1 moves_states = [(p, self.board.next_state(state, p)) for p in legal] # Display the number of calls of `run_simulation` and the # time elapsed. print games, datetime.datetime.utcnow() - begin # Pick the move with the highest percentage of wins. percent_wins, move = max( (self.wins.get((player, S), 0) / self.plays.get((player, S), 1), p) for p, S in moves_states ) # Display the stats for each possible play. for x in sorted( ((100 * self.wins.get((player, S), 0) / self.plays.get((player, S), 1), self.wins.get((player, S), 0), self.plays.get((player, S), 0), p) for p, S in moves_states), reverse=True ): print "{3}: {0:.2f}% ({1} / {2})".format(*x) print "Maximum depth searched:", self.max_depth return move We have added three things in this step. First, we allow get_play to return early if there are no choices or only one choice to make. Next, we've added output of some debugging information, including the statistics for the possible moves this turn and an attribute that will keep track of the maximum depth searched in the selection phase of the playouts. Finally, we've added code that picks out the move with the highest win percentage out of the possible moves, and returns it. But we are not quite finished yet. Currently, our AI is using pure randomness for its playouts. We need to implement UCB1 for positions where the legal plays are all in the stats tables, so the next trial play is based on that information. # ... from math import log, sqrt class MonteCarlo(object): def __init__(self, board, **kwargs): # ... self.C = kwargs.get('C', 1.4) # ... def run_simulation(self): # A bit of an optimization here, so we have a local # variable lookup instead of an attribute access each loop. plays, wins = self.plays, self.wins visited_states = set() states_copy = self.states[:] state = states_copy[-1] player = self.board.current_player(state) expand = True for t in xrange(1, self.max_moves + 1): legal = self.board.legal_plays(states_copy) moves_states = [(p, self.board.next_state(state, p)) for p in legal] if all(plays.get((player, S)) for p, S in moves_states): # If we have stats on all of the legal moves here, use them. log_total = log( sum(plays[(player, S)] for p, S in moves_states)) value, move, state = max( ((wins[(player, S)] / plays[(player, S)]) + self.C * sqrt(log_total / plays[(player, S)]), p, S) for p, S in moves_states ) else: # Otherwise, just make an arbitrary decision. move, state = choice(moves_states) states_copy.append(state) # `player` here and below refers to the player # who moved into that particular state. if expand and (player, state) not in plays: expand = False plays[(player, state)] = 0 wins[(player, state)] = 0 if t > self.max_depth: self.max_depth = t visited_states.add((player, state)) player = self.board.current_player(state) winner = self.board.winner(states_copy) if winner: break for player, state in visited_states: if (player, state) not in plays: continue plays[(player, state)] += 1 if player == winner: wins[(player, state)] += 1 The main addition here is the check to see if all of the results of the legal moves are in the plays dictionary. If they aren't available, it defaults to the original random choice. But if the statistics are all available, the move with the highest value according to the confidence interval formula is chosen. This formula adds together two parts. The first part is just the win ratio, but the second part is a term that grows slowly as a particular move remains neglected. Eventually, if a node with a poor win rate is neglected long enough, it will begin to be chosen again. This term can be tweaked using the configuration parameter C added to __init__ above. Larger values of C will encourage more exploration of the possibilities, and smaller values will cause the AI to prefer concentrating on known good moves. Also note that the self.max_depth attribute from the previous code block is now updated when a new node is added and its depth exceeds the previous self.max_depth. So there we have it. If there are no mistakes, you should now have an AI that will make reasonable decisions for a variety of board games. I've left a suitable implementation of Board as an exercise for the reader, but one thing I've left out here is a way of actually allowing a user to play against the AI. A toy framework for this can be found at jbradberry/boardgame-socketserver and jbradberry/boardgame-socketplayer. This version that we've just built uses light playouts. Next time, we'll explore improving our AI by using heavy playouts, by training some evaluation functions using machine learning techniques and hooking in the results. UPDATE: The diagrams have been corrected to more accurately reflect the possible node values. UPDATE: Achievement Unlocked! This article has been republished in Hacker Monthly, Issue 66, November 2015.
http://jeffbradberry.com/posts/2015/09/intro-to-monte-carlo-tree-search/
CC-MAIN-2018-09
refinedweb
3,141
64.2
February 8, 2017 09:12 Healthcare Tracking System for Dementia Patients and Elderly (Part 2) In the first part, I have talked about the Hexiwear (923-6084) platform and how we can detect the falling using gyroscope and accelerometer data. I also mentioned that Hexiwear supports mbed platform which makes programming so easy. In this section, I am going to activate the OLED screen to notify user and Bluetooth to inform the emergency service. Then, I will mention how to create an android app using Evothings and connect the smartphone to the Hexiwear. Let's start with the OLED display. Hexiwear has a 1.1” full-colour OLED display. It can be programmed to inform the user. In order to use the OLED display, we need to add the Hexi_OLED_SSD1351.h library file and initiate the driver. The code below sets the text properties, background colour and text position. Once the template is set, we only need to change the text. void initOLED() { char text[20]; /* Text Buffer */ /* Get OLED Class Default Text Properties */ oled_text_properties_t textProperties = {0}; oled.GetTextProperties(textProperties); /* Turn on the backlight of the OLED Display */ oled.DimScreenON(); /* Fills the screen with solid black */ oled.FillScreen(COLOR_BLACK); /* Change font color to Blue */ textProperties.fontColor = COLOR_BLUE; oled.SetTextProperties(textProperties); /* Display Bluetooth Label at x=15,y=0 */ strcpy((char *) text,"DesignSpark"); oled.Label((uint8_t *)text,15,0); /* Display Text at (x=20,y=15) */ strcpy((char *) text,"HexiCare"); oled.Label((uint8_t *)text,20,15); /* Change font color to blue */ textProperties.fontColor = COLOR_BLUE; oled.SetTextProperties(textProperties); /* Set text properties to white and right aligned for the dynamic text */ textProperties.fontColor = COLOR_WHITE; textProperties.alignParam = OLED_TEXT_ALIGN_RIGHT; oled.SetTextProperties(textProperties); } In a similar manner to OLED, we can also add Bluetooth just adding ready libraries and have connectivity. Libraries make programming easy but mbed not only supports huge repositories of libraries but also it brings hardware abstraction. It is kind of remove the complexities of the dealing with the underlying hardware technology and make you focus on the software algorithms. #include "Hexi_KW40Z.h" // BLE ... KW40Z kw40z_device(PTE24, PTE25); // BLE (UART TX, UART RX) ... int main() { ... Thread txThread; // Thread to handle sending BLE ... } ... void txTask(void) { while (true) { // Send alarm data kw40z_device.SendFaintAlarm(faintAlarmBLE); Thread::wait(1000); } } The previous faint detection algorithm changes the faintAlarmBLE variable. If faint is detected, faintAlarmBLE becomes one and it is transmitted to the phone every second. I prefer to send the data repeatedly to ensure it is transmitted. I know that this is a power hungry method but I haven't designed the whole system and there is no recovery in the transmission so I want to be sure data is transmitted in all cases. After adding the BLE feature, the next thing is to create an Android App. I haven't written an Android app before so I prefer hybrid systems which provide flexibility of creating mobile apps using HTML and JavaScript. Evothings is one of the hybrid tools. I chose this because there is a webinar which explains how to create apps for Hexiwear. It is a great tool you don't need to learn native Android but there are some problems. Evothings is a kind of cloud base, and I had to wait for the servers to be updated before starting the coding. If you have a deadline, it may affect your schedule. Second, Evothings doesn't have a built-in SMS option. I was looking to add this functionality but the program stoped working. Luckily, my app is almost finished, I just need to add SMS or calling option. Although Evothings doesn't have a plugin for SMS, it supports Cordova plug-in. In this link, it describes how to add the SMS feature to the Evothings Studio. If you have experience with native mobile development, it might be better to write the app there. If you want to use the one I modified, it is also on the GitHub. Mehmet is an Embedded Systems Engineer and he loves to play with new boards(toys). He is looking for PhD opportunities. Lately, he has created a website mehmetbozdal.com where he shares his knowledge and postgraduate experience.
https://www.rs-online.com/designspark/healthcare-tracking-system-for-dementia-patients-and-elderly-part-2
CC-MAIN-2017-30
refinedweb
693
58.99
This is not functionally the same exact program - I didn't have a copy of his Perl program on hand when I wrote it, but I thought it would be a good demonstration to Python novices to show how to do the same sort of problems in Python. Some notes: Python modules can define functions and classes,and can also execute any arbitrary statements the first time they are imported ( or anytime they are reload(module) -ed. ) When python modules are imported, their __name__ attribute is usually equal to the name of the module, However, when a python script is run as a (stand-alone) program, it's name is equal to "__main__". This allows modules to both contain common function definitions imported and used by other modules, and to contain a stand-alone main routine. ( If it is not a stand-alone program, I will often include test code that exercises the modules functions. ) Python module os.path, has a function 'walk', that recursively walks thru a directory and applies a function to the filelist for that directory. The filelist can be modified to control further processing, so you can prune the tree at a certain point. The function in this version doesn't do anything fancy- it just appends files to a filename list. Later processing and selection can also be done by selecting items from the list with 'filter', a builtin Python function that takes a function that returns a boolean value (0 or 1), and a list, and returns the elements of the list for which the function is true. filter(lambda f: os.stat(f)[ST_SIZE] > size, apply(find, args)) The test here is a simple one line expression, so a lambda expression funcion is used. For a more complicated test, a multi-line function can also be defined with 'def' . 'apply' is used because args may be a variable number of arguments. If it was defined to take a single arg ( wich could be a list or a tuple of items), then "find( arg )" would be sufficient. The default sort function in Python can sort different types of objects ( the order of different types is arbitrary but consistent) and composite objects. One sorting trick is to create tuples that have the proper indices as initial values for the tuple. A ( number, string, anything-else ) tuple will always sort by first, the number, then the string, and then, the anything-else. So sort-by-date/size is done by turning each file name in the list into a ( date|size, filename ) tuple. Python's builtin map function is like Lisp's map. It takes a function of N args, followed by N sequences: files = map( lambda f: (os.stat(f)[ST_MTIME], f), files ) Just an example: Not complete, not completely debugged, and not checked for portability ( In fact, I just noticed that I used '.' as the default, instead of getting the pwd ( which on a Mac, probably has a different literal designation.)) Usage: find.py [-D|-N|-S] [-R] [-s size] [pathnames...] -D : sort by modification date/time -N : sort by filename -S : sort by size -R : reverse order of sort -s size : include only files >= size size can be an expression using +/-* and ending in a character code [KkMm][Bb] multiplier: 0.5Mb, 100K, 8*2048+512, etc. pathnames can include ~user or $VAR expansions. No pathname indicates the current directory. Maybe I'll try a more complete program later, but my interest is not so much in duplicating the functionality and interface of find ( as find2perl does ) : I find often find myself struggling to figure out how to get find to do what I want - I would prefer to try to figure out a *better* interface. - Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU> - UVA Department of Molecular Physiology and Biological Physics #!/usr/local/bin/python # find.py # import os,sys,string from stat import ST_SIZE,ST_MTIME from time import ctime expanduser = os.path.expanduser expandvars = os.path.expandvars def expand( name ): # handle $HOME/pathname or ~user/pathname return expandvars( expanduser( name )) if os.name in ( 'posix', 'dos' ): DO_NOT_INCLUDE = ( '.', '..' ) # don't include these for dos & posix else: DO_NOT_INCLUDE = ( ) # I don't know what this should be for Mac def find( *paths ): list = [] for pathname in paths: os.path.walk( expand(pathname), append, list ) return list def append( list, dirname, filelist ): for filename in filelist: if filename not in DO_NOT_INCLUDE: filename = os.path.join( dirname, filename ) if not os.path.islink( filename ): list.append( filename ) def evalsize( sizestr ): mult = 1 # this allows "10k", "1M" as abbreviations: if sizestr[-1] in ('b', 'B' ) : sizestr = sizestr[:-1] if sizestr[-1] in string.letters : if sizestr[-1] in ( 'k', 'K' ): mult = 1024 elif sizestr[-1] in ( 'm', 'M' ) : mult = 1024*1024 else: raise RuntimeError, 'No mutiplier for: '+ arg[-1] sizestr = sizestr[:-1] # using 'eval()' rather than 'string.atoi()' # allows "10*1024", "0.25*1M" expressions: size = eval( sizestr ) * mult # also "1024*1024/2" or "1/2.0m" but NOT "1M/2" # multiplier letter must be last char! # 1/2.0m is (1/2.0)*1m , NOT 1/(2m) # and 1/2m is integer division 1/2 = 0 ! return size from Getopt import Getoptd by_date = '-D' by_size = '-S' by_name = '-N' reverse = '-R' opt_str = 'DSNRs:' if __name__ == '__main__' : opt = Getoptd( sys.argv[1:], opt_str ) if opt.has_key('-s'): size=evalsize( opt['-s']) else: size = 0 args = () for each in opt['']: args = args + ( each, ) if not args : args = ( '.', ) # current directory if size: # select files > size files = filter(lambda f: os.stat(f)[ST_SIZE] > size, apply(find, args)) else: files = apply( find, args ) if opt.has_key(by_date): # turn each filename into a ( MTIME, filename ) tuple pair files = map( lambda f: (os.stat(f)[ST_MTIME], f), files ) files.sort() if opt.has_key(reverse): files.reverse() for f in files: print string.ljust(f[1],52), ctime( f[0] ) elif opt.has_key(by_size): # turn each filename into a ( SIZE, filename ) pair files = map( lambda f: (os.stat(f)[ST_SIZE], f ), files ) files.sort() if opt.has_key(reverse): files.reverse() for f in files: print string.ljust(f[1],52), '%9d' % f[0] else: if opt.has_key(by_name) : files.sort() if opt.has_key(reverse): files.reverse() for f in files: print f # # Getopt.py: # # getopt returns a tule-air of list of tuple-pairs and list of args. # The results are easier to handle if they are returned as a # dictionary. # Use Getoptd().has_key() to check for existance of a switch # and Getoptd()[] to retrieve it's value. # non-option arguments are entered with a empty string '' key. # from getopt import getopt def Getoptd( args, argstr ): opts, args = getopt( args, argstr ) d = { '':args } for opt in opts: d[opt[0]] = opt[1] return d
https://legacy.python.org/search/hypermail/python-1994q2/0116.html
CC-MAIN-2021-43
refinedweb
1,120
65.32
Mercari’s Image Classification Experiment Using Deep Learning Introduction Hi, my name is Takuma Yamaguchi. I am a software and machine learning engineer at Mercari. These days, Artificial Intelligence (AI) is a very popular buzzword. We also often see terms, such as Deep Learning and Deep Neural Networks, which are both subsets of AI and machine learning. I would like to share our image classification experiment using deep learning. Neural Network Winter Deep learning is a variation of neural network techniques. At the 7th International Conference on Document Analysis and Recognition (ICDAR 2003) held in Edinburgh, Scotland, Simard et al. (Microsoft Research) said in their paper Best Practices for Convolutional Neural Networks Applied to Visual Document Analysis this conference as a student and I made a presentation on digit detection and recognition.) At that time, many researchers were being attracted to other algorithms like Support Vector Machine (SVM) and others. What Brought Deep Learning Back? Some researchers, such as Yann LeCun, Geoff Hinton, Yoshua Bengio, and Andrew Ng, continued to study neural networks. Thanks to their achievements, algorithms based on deep learning have achieved better results than other algorithms in many tasks and competitions, including ILSVRC2012. I really like this talk of theirs about the struggles during the Neural Network Winter: Deep Learning Gurus Talk about History and Future of Machine Learning. After seeing what this group of researchers achieved, many others started using deep learning techniques again. Due to the large amounts of data and huge computational resources required, breakthroughs in deep learning algorithms, coupled with the latest hardware improvements, have made deep learning more practical than ever before. This TED talk by Fei-Fei Li (director of Stanford’s Artificial Intelligence Lab and Vision Lab) helps to further explain why why large amounts of data are needed for AI. (I visited Stanford University two years ago, but unfortunately I wasn’t able to meet her…) Image Classification One of the practical applications of deep learning is image classification/object recognition. We prepared a data set of 1 million images within Mercari, taken from 1,000 categories (so 1,000 images per category). We used 90% of the images for training and the other for evaluation. Sample Images Training We conducted our image classification experiment using TensorFlow. TensorFlow is Google’s open source machine learning library. It’s not just for neural networks and can be used for a variety of other machine learning tasks. We used the Inception-v3 model, a powerful image classification algorithm based on deep neural networks. In order to train the model from scratch, we needed data in the TFRecord format. A script for converting images to TFRecord format data is included in the repository. ImageNet is a common academic image data set for image classification. The data set is described in the TED talk above. The Inception-v3 model also uses this data set as a training example. Although we didn’t depend on ImageNet, we did use imagenet_train.py as described in the README. This algorithm is available for any image data set, and works as-is for 1,000 or fewer categories, each category having around 1,000 images. And, even if your data has more categories, all you have to do is change the number of categories/images In recent years, it has become more common to use GPUs for machine learning. It is possible to train the model without GPUs, but this may take several months to obtain practical results. Even when using a single GPU, due to GPU memory limitations, the batch size for training the Inception-v3 model should be less than or equal to 32 for our environment (AWS EC2 p2.xlarge) using a single TESLA K80 GPU. In general, a larger batch size leads to better results. One of the comments in inception_train.py states: # With 8 Tesla K40’s and a batch size = 256, the following setup achieves # precision@1 = 73.5% after 100 hours and 100K steps (20 epochs). Based on. This allows us to monitor and check the training status and models through a web browser. Sample of the Model Some Metrics Training Loss We decided to stop the training at 90K steps. If we had kept training, the training loss would continue to improve little by little, and the final results would be better. However, we decided to stop at 90K due to time constraints. … Finally, we got: precision @ 1 = 0.4332 recall @ 5 = 0.7033 Discussion The accuracy was worse than we had expected… Here are some possible reasons for why we got such a result. Some categories are very similar, such as, “Men > Shoes > Sneakers” and “Women > Shoes > Sneakers.” Also some varieties of clothing for men and women tend to share similarities. Moreover, some categories such as “Tickets” cannot be recognized without OCR (Optical Character Recognition). This is needed, for example to classify tickets for events featuring Japanese artists or foreign artists, as well as things like bus and train tickets, etc. Sample Results In tensorflow/models/inception, the scripts are used for batch training and evaluation. When we want to use a trained model for non-batch image classification tasks, we only need to write about 20 lines of code. import tensorflow as tf from inception import inception_model as inception from inception import image_processingFLAGS = tf.app.flags.FLAGSimage = image_processing.image_preprocessing(tf.read_file(‘(‘/path/to/train/dir’) saver.restore(sess, ckpt.model_checkpoint_path) top_k_values, top_k_indices = sess.run(top_k) print(‘Label IDs: ‘, top_k_indices) print(‘Scores: ‘, top_k_values) Classification score is not treated in the imagenet_eval. Since it would be helpful to know the confidence of the classifications, we added this line of code scores = tf.nn.softmax(logits). This value is actually calculated in the inception model, but is not returned. After this, we get the classification results for the image. (‘Label IDss: ‘, array([[ 64, 202, 206, 292, 600]], dtype=int32)) (‘Scores: ‘, array([[ 0.57124287, 0.37565342, 0.00791241, 0.0067259 , 0.00576101]], dtype=float32)) We applied this trained model to some images. image score — category 0.296 — Men > Shoes > Sneakers 0.067 — Sports > Other Sports > Basketball 0.045 — Sports > Other Sports > Athletics 0.041 — Babies & Kids > Shoes > Sneakers 0.310 — Women > Shoes > Sneakers 0.296 — Men > Shoes > Sneakers 0.067 — Sports > Other Sports > Basketball 0.045 — Sports > Other Sports > Athletics 0.041 — Babies & Kids > Shoes > Sneakers 0.173 — Electronics > Audio Equipments > Earphones 0.124 — Electronics > TV/Video Equipments > Cables 0.113 — Electronics > Audio Equipments > Cables 0.098 — Hobbies > Video Games > Game Consoles 0.072 — Electronics > Beauty & Health > Hair Irons 0.585 — Hobbies > Toys & Stuffies > Stuffies 0.107 — Babies & Kids > Toys > Music Boxes 0.095 — Babies & Kids > Toys > Rattles 0.028 — Women > Accessories > Key Rings 0.019 — Hobbies > Toys & Stuffies > Character Goods 0.663 — Others > Groceries > Fruits 0.300 — Others > Groceries > Vegetables 0.005 — Home > Annual Events > Gifts 0.002 — Others > Groceries > Processed Foods 0.002 — Others > Groceries > Others 0.665 — Cars & Motorcycles > Cars > Cars (non-Japanese) 0.192 — Cars & Motorcycles > Cars > Cars (Japanese) 0.055 — Cars & Motorcycles > Cars > Catalogs 0.008 — Cars & Motorcycles > Motorcycles > Motorcycles 0.006 — Cars & Motorcycles > Cars > Car Parts (Japanese) Looks like something we can use! Conclusion I hope you enjoyed reading about our image classification experiment. Thanks to TensorFlow and other OSS, we didn’t need to write any new code. As you can see, knowledge of machine learning is not necessarily required for a simple image classification task. Nowadays, all we need are large amounts of labeled data and huge computational resources for image classification tasks. Deep learning methodology is helping to dramatically improve not only image classification, but also other machine learning applications such as speech recognition, natural language processing, and so on. However, deep learning still has some problems, e.g. the huge computation time and training difficulties. Currently, I am interested in model compression of deep neural networks, since deep models usually have a huge number of parameters. If they could be represented by fewer parameters, deep learning would be even more useful. For now, I hope that we will be able to provide a better user experience through machine learning!
https://medium.com/mercari-engineering/mercaris-image-classification-experiment-using-deep-learning-9b4e994a18ec
CC-MAIN-2021-21
refinedweb
1,348
50.23
I have Flask-Spyne server (web service) and I want to return (return to client after he will ask) a XML file. I want to do this: from flask import Flask from flask_spyne import Spyne from spyne.protocol.soap import Soap11 from spyne.model.primitive import Unicode, Integer, Float, DateTime from spyne.model.complex import Iterable app = Flask(__name__) spyne = Spyne(app) class dotazNaOracleDB(spyne.Service): __service_url_path__ = '/soap/oracleservice'; __in_protocol__ = Soap11(validator='lxml'); __out_protocol__ = Soap11(); @spyne.srpc(DateTime, DateTime, _returns="What to put here?") def oracle(DATE_INCOME, DATE_ISSUE): #from OracleDB_Procedure import UlozeniDoXML #UlozeniDoXML(DATE_INCOME, DATE_ISSUE); s = open("Databaze.xml"); return s; if __name__ == '__main__': app.run(host = '127.0.0.1'); If you want to return it as a regular string inside a document, you must set your _return type to Unicode. If you want to return it as an xml document, you must parse it ( etree.parse("Databaze.xml")) and return the resulting ElementTree instance. Your return type in this case should be AnyXml. Also see these examples: Sending as string isolates your document from parent context. It's a bit more inefficient (e.g. < character becomes <) but otherwise harmless. Sending as document makes your document part of the SOAP message. It's more efficient but makes it inherit namespace prefixes from the parent document which may cause slight changes to the document -- i.e. what you put in and what you get back out may not be equal byte-for-byte (but equivalent nevertheless). It totally depends on the use case. If in doubt, return as string.
https://codedump.io/share/cf1ts4LeUQAS/1/how-can-i-return-an-xml-file-with-spyne
CC-MAIN-2017-34
refinedweb
259
52.15
Drawing new features Our feature editor can now be used for loading data and modifying features. Next up, we'll add a Draw interaction to allow people to draw new features and add them to our source. First, import the Draw interaction (in main.js): import Draw from 'ol/interaction/Draw'; Now, create a draw interaction configured to draw polygons and add them to our vector source: map.addInteraction( new Draw({ type: 'Polygon', source: source, }) ); The type property of the draw interaction controls what type of geometries are drawn. The value can be any of the GeoJSON geometry types. With our draw interaction in place, we can now add new features to our vector source.
https://openlayers.org/workshop/en/vector/draw.html
CC-MAIN-2021-43
refinedweb
115
64
If. For creating project the SDK provides a lot of project templates: And also you can include or exclude frameworks for your project. After creating the project, MKB file will be created. MKB file is main file of every Marmalade SDK project, it’s a plain text file that describes all project settings. MKB files are used to specify project configuration and deployment configuration. This file is used to generate project files for Visual C++ or Xcode (In the documentation you can found a lot information about MKB format, how to include sub projects, libraries, assets, etc). And after that, when you will have Xcode project files, which will be generated from MKB file from console or Marmalade Hub, you can run Xcode and start working. Before you begin, you should understand the Marmalade’s architecture. This SDK achieves its cross-platform due to two component parts. It’s a loader and S3E binary system. All the code that you write for your app is compiled and linked into a module(known as an S3E binary) which is executed by a loader program. The S3E binary can therefore be thought of as similar to a Windows dynamic link library (DLL) and indeed on the Windows platform it is actually implemented as such. The loader is a pre-compiled native binary that acts as an abstraction layer and which provides a consistent programming interface across each supported platform. It takes care of any platform specific requirements including initialisation and termination and handling of events such as user inputs or incoming calls. The loaderwill include implementations written in the platform's native OS language, for example Objective-C on iOS or Java on Android. Your app is written to use the API implemented by the loader and therefore a single S3E binary can be used across all platforms with matching architecture types. The Marmalade APIs are divided between Marmalade System, Middleware, and Extension Development Kit (EDK). Marmalade System (S3E), it’s a platform abstraction layer, entirely C-based API which provides abstraction from the underlying operating system. This is low level API which allows you to work, for example, with audio, surface interaction, file IO, etc. The Middleware modules provide higher-level functionality. For example, working with 2D and 3D graphics, animations, resource managing, etc. These modules use C++ object-oriented interfaces, are provided as libraries. There are IwGx (2D and 3D rendering), IwUI (User interface), IwHTTP (interface for performing HTTP and HTTPS requests), IwUitl and IwGeom (provide basic geometry types and utility functions), IwGL (API that performs extra OpenGL ES), IwGxFont (Fonts), etc. This modules you can combine with each other. Let’s begin to create simple application, which just show the image on center of the screen. First of all, you should add assets to MKB project file, like a that: assets { (data) textures } And add image to folder data/textures. After that let’s write the code: #include "s3e.h" #include "Iw2D.h" #include "IwGx.h" // Main entry point for the application int main() { // Initialise graphics system(s) Iw2DInit(); // Create an image from a PNG file CIw2DImage* image = Iw2DCreateImage("textures/image.png"); // Set image position const float x = (IwGxGetScreenWidth() * 0.5) - (image->GetWidth() * 0.5); const float y = (IwGxGetScreenHeight() * 0.5) - (image->GetHeight() * 0.5); CIwFVec2 imagePosition = CIwFVec2(x, y); // Loop forever, until the user or the OS performs some action to quit the app while (!s3eDeviceCheckQuitRequest()) { // Update the input systems s3eKeyboardUpdate(); s3ePointerUpdate(); // Clear screen with black color Iw2DSurfaceClear(0xff000000); // Draw an image Iw2DDrawImage(image, imagePosition); // Draws Surface to screen Iw2DSurfaceShow(); // Sleep for 0ms to allow the OS to process events etc. s3eDeviceYield(0); } // Terminate modules being used delete image; Iw2DTerminate(); return 0; } Compile and run the project, and you can see something like that: I will not explain the code as it is pretty simple, I want to draw attention, that you will not forget about the fact that you should add new source files or assets directly to MKB file, not in your current IDE. For deploying project to iOS or Android you should build project with GCC configuration and after that in your Marmalade Hub you can do it. Marmalade’s developers have created a useful and simple tools for setup project details (such as icons, launcher images, provision profiles, etc) with a huge amount of documentation, and I think for any developer will not make difficulties to create build for different platforms and install it on device. Happy coding!
https://www.factorialcomplexity.com/blog/getting-started-with-marmalade-sdk
CC-MAIN-2019-35
refinedweb
744
52.49
Ben Wing <ben at 666.com> wrote: > > sorry to be casting multiple ideas at once to the list. i've been > looking into other languages recently and reading the recent PEP's and > such and it's helped crystallize ideas about what could be better about > python. > > find myself constantly writing stuff like > > text="Family: %s" % self.name [snip] > maybe_errout(i"[title], line [lineno]: [errstr]\n") This can be done now via: maybe_errout("%(title)s, line %(lineno)i: %(errstr)s\n"%locals()) > def __str__(self): > return i"CCGFeatval([self.name], parents=[self.parents], > licensing=[self.licensing])" With the proper mapping, this is trivial... class namelookup: def __init__(self, namespace): self.ns = namespace def __getitem__(self, name): ns = self.ns names = name.split('.') try: if names[0] in ns: ns = ns[names[0]] names = names[1:] except IndexError: raise KeyError("bad namespace") for n in names: if hasattr(ns, n): ns = getattr(ns, n) else: return "<name not found>" return ns >>> class foo: ... a = 1 ... b = 2 ... >>> foo = foo() >>> print "%(foo.b)i + %(foo.a)i"%namelookup(locals()) 2 + 1 >>> While I understand the desire for better string interpolation, many of your needs can be covered with pre-existing string formatting. You can even write a handler for "{2} and {1} or {3}" as "%(2)s and %(1)s or % (3)s"%positional(a, b, c). Toss it into site.py, and you can use it whenever. If you want this to be fully in regards to Py3k, post on the py3k mailing list: python-3000 at python.org - Josiah
https://mail.python.org/pipermail/python-dev/2006-December/070177.html
CC-MAIN-2016-30
refinedweb
259
66.64
- 15 Feb, 2012 10 commits into a shared helper module. also made a minor adjustment to compare() test data. some test cases were adjusted accordingly, too. - 14 Feb, 2012 1 commit so that they will be shared with NSEC3PARAM. - 13 Feb, 2012 17 commits - Jelte Jansen authored see ticket #1668 of honoring C++ namespaces). Conflicts: src/bin/auth/tests/query_unittest.cc - Stephen Morris authored "string.h" is requested to define memset(). - 11 Feb, 2012 8 commits - 10 Feb, 2012 4 commits the original code would still throw an exception (bad_alloc) due to the resulting huge size of alloc request, but it should be better to catch it explicitly.
https://gitlab.isc.org/isc-projects/kea/-/commits/001717c6baf2ed1929f9a585408ae66f26eed014
CC-MAIN-2022-21
refinedweb
108
66.94
[source = "csharp"] using SlimDX; using SlimDX.Multimedia; using SlimDX.XAudio2; public class Sound { public static XAudio2 device; public static MasteringVoice mv; public static void Initialize() { device = new XAudio2(); mv = new MasteringVoice(device); } public static void PlayBGM(string name) { WaveStream stream = new WaveStream(name); AudioBuffer buffer = new AudioBuffer(); buffer.AudioData = stream; buffer.AudioBytes = (int)stream.Length; buffer.Flags = BufferFlags.EndOfStream; SourceVoice sourceVoice = new SourceVoice(device, stream.Format); sourceVoice.SubmitSourceBuffer(buffer); sourceVoice.Start(); } 9 replies to this topic #1 Members - Reputation: 100 Posted 11 February 2010 - 08:49 AM Hello, I look at SlimDX and DirectX samples for XAudio2 (they look exactly alike). I couldn't find any tutorials besides these for XAudio2 so I got some questions. 1. I can play simple sounds in XAudio2 with the example. I was just wondering if this way is feasible for playing lots of sounds at once. 2. Using this way, wouldn't I be using a ton of memory? Or should I have a list of Streams with preloaded wav / ogg files? 3. Do I need an AudioBuffer for each sound I want to play? Or can I play multiple sounds at once with one AudioBuffer? 4. I couldn't figure out how to load an ogg file with XAudio2, does anyone know how? thank you Sponsor: #2 Members - Reputation: 189 Posted 12 February 2010 - 01:55 AM Quote: Information on XAudio2 is a little thin :( Each IXAudio2SourceVoice can play one sound, and you can use the same buffer with multiple IXAudio2SourceVoice 's. This is mostly useful for sound effects. What I do is load the entire wav file into a buffer (sound effects generally are not that big), and then just pass the buffer to each new IXAudio2SourceVoice to play the sound. This way very little memory is used for playing each sound. I don't know how you would do ogg/vorbis from .net. I used the reference libogg and libvorbisfile to decode the track into PCM data I could send to XAudio2. Here I kept a one source voice to one set of buffers ratio. I had 2 fairly large buffers (around 5 seconds of stereo audio each). When the source voice finished playing one, I loaded the next block of data into it and resubmitted it. Here is some bits of my code (C++) for streaming ogg/vorbis. ...run every few seconds if(voice) { XAUDIO2_VOICE_STATE state; voice->GetState(&state); if(!almostDone)//more data to play if(state.BuffersQueued < BUFFER_COUNT) fillBuffer(); else if(state.BuffersQueued == 0)//all buffers played and no more to come stop();//finished } void fillBuffer() { size_t readBytes; //fill a buffer with audio data, returns false if there is no more data to come after this if(!data->read(buffers[currentDiskReadBuffer], BUFFER_COUNT, &readBytes)) almostDone = true; assert(readBytes > 0); //submit buffer XAUDIO2_BUFFER buffer = {0}; buffer.pAudioData = buffers[currentDiskReadBuffer]; buffer.AudioBytes = readBytes; if(almostDone) buffer.Flags |= XAUDIO2_END_OF_STREAM; if(FAILED(voice->SubmitSourceBuffer(&buffer))) throwex(XAudio2Error); //cycle buffers (++currentDiskReadBuffer) %= BUFFER_COUNT; } //handles the loading of vorbis audio data, in this case streaming //I could also stream .wav files if I wanted using a WavData class, however //since I only use those for sound effects, i normally read the entire thing at once into a buffer and then close the WavData object. //ie WavData::read(data, WavData::getLengthBytes(), &read) class VorbisData : public AudioData ... bool VorbisData::read(unsigned char *data, unsigned targetBytes, unsigned *readBytes) { unsigned bytes = 0; int sec = 0; int ret = 1; memset(data, 0, targetBytes); //Read in the bits while(ret > 0 && bytes<targetBytes) { //read and decode the next bit of data //returns bytes read, or <0 for errors ret = ov_read(&vorbisFile, (char*)data+bytes, targetBytes-bytes, 0, 2, 1, &sec); bytes += ret; } *readBytes = bytes; switch(ret) { //eof case 0:return false; //errors case OV_HOLE: logWrite(LOG_ERROR, L"Vorbis: Interuption in audio data.\n"+sourceName); return false; case OV_EINVAL: logWrite(LOG_ERROR, L"Vorbis: Failed to read headers.\n"+sourceName); return false; case OV_EBADLINK: logWrite(LOG_ERROR, L"Vorbis: Invalid stream section.\n"+sourceName); return false; //more data default:return true; } } #3 Members - Reputation: 238 Posted 12 February 2010 - 02:22 AM Quote: I'll give some hints gathered from using XAudio2 in my engine : 1) Dispose the voice on a secondary thread cause the dispose works only when the XAudio2 thread is COMPLETELY IDLE, so it may take 1-2 ms. It is safe to do so (the MSDN agrees) 2) As you are using SlimDX, take extremely care to the GC usage as the last version is affected by a "bug" (or as they say "feature") that create tons of MB of trash for 100-200 sounds played. (Try searching the issue on their tracker, its related to the event OnProcessingPassStart and affect even if you don't use it) 3) As far as I know you need a separate audiobuffer for each voice, you may reuse the same audiobuffer, but only after the buffer has been completely read. (There is an event if i'm correct) 4) You have to parse by yourself (or using a library), create a waveformat and pass the data to XAudio2. Its not a one-click process. (The same for Mp3 or XWM or even WAV (but the WAV format parse is done by the SlimDX guys)) I don't have experience with OGG, but as for XWM i pass the compressed data to the XAudio2 thread (correctly parsed and divided) #4 Members - Reputation: 100 Posted 12 February 2010 - 06:35 AM Thank you Fire Lancer and feal87. This info is very helpful! #5 Members - Reputation: 100 Posted 12 February 2010 - 10:24 AM I use your method Fire Lancer. It crashes when I do lots of sounds in quick succession though. I guess this is because last source voice is still trying to read from buffer when I change it to a new sound. I try FlushSourceBuffers() but that does not help. Is there way to do this? I try FlushSourceBuffers() but that does not help. Is there way to do this? #6 Members - Reputation: 100 Posted 12 February 2010 - 02:11 PM Here is my code, I call PlaySound every 50ms or so. I get this error when I try to submit the source buffer. It plays the sound once but when I try and play it again is when I get the error. Specified argument was out of the range of valid values. Parameter name: readLength I get this error when I try to submit the source buffer. It plays the sound once but when I try and play it again is when I get the error. Specified argument was out of the range of valid values. Parameter name: readLength [source = "csharp"] using SlimDX; using SlimDX.Multimedia; using System; using System.IO; using System.Collections.Generic; using SlimDX.XAudio2; public class Sound { public static XAudio2 device; public static MasteringVoice mv; public static AudioBuffer ab; public static AudioBuffer se; public static void Initialize() { device = new XAudio2(); mv = new MasteringVoice(device); ab = new AudioBuffer(); se = new AudioBuffer(); } public static void PlaySound(string name) { se.AudioData = Logic.s[name]; se.AudioBytes = (int)Logic.s[name].Length; se.Flags = BufferFlags.None; SourceVoice sv = new SourceVoice(device, Logic.s[name].Format); sv.SubmitSourceBuffer(se); // Errors here sv.Start(); } public static void LoadSounds() { // Load all our sounds into dictionary Logic.s = new Dictionary<string, WaveStream>(); DirectoryInfo di = new DirectoryInfo(@"C:\Work\Sounds\"); FileInfo[] fi = di.GetFiles("*.wav"); foreach (FileInfo f in fi) { WaveStream s = new WaveStream(f.FullName); Logic.s.Add(Path.GetFileNameWithoutExtension(f.Name), s); } } } #7 Members - Reputation: 238 Posted 12 February 2010 - 08:04 PM Set the position of the stream of the audiobuffer to 0. That's the problem. If you leave it as is, it try to start from the end of the buffer...:P If you leave it as is, it try to start from the end of the buffer...:P #8 Members - Reputation: 100 Posted 12 February 2010 - 08:52 PM ty for reply feal87, it works now :) it works now :) #9 Members - Reputation: 189 Posted 12 February 2010 - 09:55 PM Quote: The important thing is you must 100% guarantee you wont change the buffer while its being played, that's why for streaming I only ever have the one source voice per set of buffers, cause there always changing. To make the guarantee you have a couple of options: 1) Load all the sounds you want into buffers (at the start of a level or whatever), then unload them at the end of the level after terminating any playing sounds. 2) Create a way to tell if the buffer is still being used. My method was to add some reference counting to my buffer objects, increment it when I play it, then decrement it when the source voice is finished. This way I know if its safe to change the buffer in any way. In .NET I assume the buffer objects get garbage collected? In which case option 2 is more or less done for you. Load your sounds into brand new buffers, and when your done playing new instances of it clear your references to it. When XAudio2 is also done with it, the GC should be able to reclaim the memory. EDIT: It probably worth noting that by buffer I mean the actual data buffer, not the AudioBuffer object that takes a reference to it, those are cheap to create, use very little memory, (assuming .NET didn't do something with them, in C++ the equivalent object is just a small data structure) and should generally be created once for each time you play the "real buffer" IMO. You can see I did this in the "//submit buffer" portion of the code I posted. EDIT2: Also be sure to set XAUDIO2_END_OF_STREAM flag as needed. If you don't XAudio2 will complain that the source is being starved when it runs out of data to play. #10 Members - Reputation: 100 Posted 13 February 2010 - 08:40 AM i see, thx again Fire Lancer
http://www.gamedev.net/topic/561895-xaudio2/
CC-MAIN-2014-10
refinedweb
1,662
62.17
you can easily crop the image in python by using roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]] In order to get the two points you can call cv2.setMouseCallback("image", mouse_crop). The function is something like this def mouse_crop(event, x, y, flags, param): # grab references to the global variables global x_start, y_start, x_end, y_end, cropping # if the left mouse button was DOWN, start RECORDING # (x, y) coordinates and indicate that cropping is being if event == cv2.EVENT_LBUTTONDOWN: x_start, y_start, x_end, y_end = x, y, x, y cropping = True # Mouse is Moving elif event == cv2.EVENT_MOUSEMOVE: if cropping == True: x_end, y_end = x, y # if the left mouse button was released elif event == cv2.EVENT_LBUTTONUP: # record the ending (x, y) coordinates x_end, y_end = x, y cropping = False # cropping is finished refPoint = [(x_start, y_start), (x_end, y_end)] if len(refPoint) == 2: #when two points were found roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]] cv2.imshow("Cropped", roi) cv2.imwrite("crop.jpg",roi) You can get details from here : Mouse Click and Cropping using Python
https://answers.opencv.org/answers/182449/revisions/
CC-MAIN-2021-04
refinedweb
184
58.32