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
A loop statement allows you to execute a statement multiple times. Two loop statements, for and while, test at the top of the loop. The do statement tests at the bottom, thereby ensuring that the loop body executes at least once. This section describes the loop statements. See Section 4.6 for additional statements that affect or control loop execution. A loop statement can declare variables in the scope of the loop's substatement. Every time the loop iterates, it reenters the substatement scope. This means objects that are declared in the substatement (and in the loop's condition) are created and destroyed with every loop iteration. A while statement repeats a statement while a condition is true. The syntax is: while ( condition ) statement The condition is evaluated and converted to bool. If the value is true, statement is executed, and the loop repeats. If the value is false, the loop finishes and execution continues with the subsequent statement. Thus, if condition is false the first time it is evaluated, the statement is never executed. A continue statement in a while loop branches to the top of the loop, and execution continues with the evaluation of condition. A break statement exits immediately. A while loop is typically used for unbounded iteration, that is, when you don't know beforehand how many times a loop will iterate. Example 4-5 shows how the while loop can be used to control I/O. #include <algorithm> #include <iostream> #include <iterator> #include <ostream> #include <string> #include <vector> // Sort lines of text. int main( ) { using namespace std; string line; vector<string> data; while (getline(cin, line)) data.push_back(line); sort(data.begin( ), data.end( )); copy(data.begin( ), data.end( ), ostream_iterator<string>(cout, "\n")); } A for loop is a generalization of the traditional counted loop that appears in most programming languages. The syntax for a for loop is: for ( init ; condition ; iterate-expr ) statement The init, condition, and iterate-expr parts are optional. The init part of the for statement can be an expression or a simple declaration. The init part offers more flexibility than a condition. While a condition can declare only one name, the init part can declare multiple names. The syntax for the init part is: specifier-list declarator-list or: expression As with the condition, the scope of the init part extends to the end of statement. The init, condition, and iterate-expr parts are in the same scope as the loop body. See Chapter 2 for more information about specifiers and declarators. The for loop starts by executing the init part, if present. It then evaluates the condition (just like a while loop). If the condition is true, the loop executes statement. It then evaluates iterate-expr and reevaluates condition. This process continues while condition is true. If condition is false, the loop finishes and execution continues with the subsequent statement. Thus, the init part is evaluated exactly once. The condition is evaluated at least once. The statement might be executed zero times. The most common use of a for loop is to count a bounded loop, although its flexibility makes it useful for unbounded loops, too, as you can see in Example 4-6. // One way to implement the for_each standard algorithm template<typename InIter, typename Function> Function for_each(InIter first, InIter last, Function f) { for ( ; first != last; ++first) f(*first); return f; } // One way to implement the generate_n standard algorithm template<typename OutIter, typename Size, typename Generator> void generate_n(OutIter first, Size n, Generator gen) { for (Size i = 0; i < n; ++i, ++first) *first = gen; } A continue statement in a for loop branches to the top of the loop, and execution continues by evaluating the iterate-expr and then the condition. A break statement exits the loop without evaluating the iterate-expr. See Section 4.6 later in this chapter for examples of break and continue. The init, condition, and interate-expr parts are all optional. If the init or iterate-expr parts are omitted, nothing happens to initialize the loop or after the statement executes. If the condition is omitted, it defaults to true. The do statement is like a while statement, except that it tests at the end of the loop body. The syntax is: do statement while ( expression ) ; The statement is executed, then the expression is evaluated and converted to bool. If the value is true, the statement is repeated and the expression is checked again. If the expression is false, the loop finishes and execution continues with the subsequent statement. Thus, statement is always executed at least once. A continue statement in a do loop jumps to the end of statement, and execution continues with the evaluation and test of expression. A break statement exits immediately.
http://etutorials.org/Programming/Programming+Cpp/Chapter+4.+Statements/4.5+Loops/
CC-MAIN-2016-44
refinedweb
791
56.96
Answered by: Open window in C# wpf - Hello, i have two windows in my project, and have a button in the main window and when i press it i want window2 to open. How do this work in C# - Moved by Nishant SivakumarModerator Monday, July 27, 2009 12:11 AM It's a WPF query (From:Visual C# General) - Moved by nobugzMVP, Moderator Monday, July 27, 2009 12:38 AM (From:Windows Presentation Foundation (WPF)) Question Answers The Build Action for window1 is set to Page, and the Custom Tool is set to MSBuild:Compile Change : <Window xmlns="" xmlns:x="" x:Class="Window1" to : <Window xmlns="" xmlns:x="" x:Class="SecureArchiving.Window1" All replies - Although I have not used WPF often, I think this should be as simple as in Winform. Tried this and it worked as i expected: VB: Dim w2 As Window2 = New Window2() w2.Show() C# should be Window2 w2 = New Window2(); w2.Show(); Thanks for the repsonse.It works but it opens a blank window, my window have a interface. Can you show the actual code you tried? Also, does the designer show your window's child controls correctly? The Code i tried was this:Window1 w2 = new Window1();w2.Show(); Window1 is your main window, right? The 2nd window that you want to call is probably Window2 (just a guess). If so you need to do : Window2 w2 = new Window2(); w2.Show(); My main window is LoginWindow =), and my second window is window1 hehe =), should be the other way around but =) Ok, so this Window1 (your 2nd window), does it show up correctly in the designer? Yes its show up correctly in the designer. That's weird (typically you have the reverse problem). Can you paste the xaml here? - Here is the xaml code for window1: <Window xmlns="" xmlns: <Window.Resources> </Window.Resources> <Window.Triggers> </Window.Triggers> <Grid x: <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stroke="{x:Null}" RadiusX="8" RadiusY="8"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF8BC400" Offset="0"/> <GradientStop Color="#FF4A6800" Offset="0.991"/> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <Label Foreground="#FF626262" Opacity="1" Background="#00000000" FontFamily="Gautami" FontSize="13" FontWeight="Normal" HorizontalAlignment="Center" Margin="0,-1,0,0" VerticalAlignment="Top" Height="30" Content="Secure Archiving"/> <Menu Background="{x:Null}" Foreground="#FFFFFFFF" HorizontalAlignment="Left" Margin="5,5,0,0" VerticalAlignment="Top" Width="198" Height="27"> <MenuItem Header="File"/> <MenuItem Header="Edit"/> <MenuItem Header="Download"/> <MenuItem Header="Settings"/> </Menu> <Canvas HorizontalAlignment="Left" Margin="8,28,0,0" x: <Rectangle Fill="#FFFFFFFF" Visibility="Visible" Width="256" Height="25" Stroke="{x:Null}" RadiusX="5" RadiusY="5"/> <TextBox Foreground="#FF000000" BorderBrush="{x:Null}" Background="{x:Null}" BorderThickness="0,0,0,0" Width="234" Height="21" Canvas. </Canvas> </Grid> </Window> - Nothing wrong there as far as I can see. When you run it, you get a blank white window? No green background and no menu? no menu no green. its wpf btw, if it have something to do with that.Its just white. Okay, I copy/pasted that into a test project and it runs fine. Perhaps you are doing something in code - can you post the cs file too? - It is possible that you are not calling InitializeComponent in the window constructor. If so that's your problem. - Did not have the InitializeComponent(); in the Public Window1()But if i insert it i get errorThe name 'InitializeComponent' does not exist in the current context.The CS code looks like this. using MySql.Data.MySqlClient; using MySql.Data; using System; using System.Data; using System.Configuration; using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Data.Common; using System.Diagnostics; namespace SecureArchiving { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } } } - Your project doesn't seem to be correctly setup for xaml compilation. Did you manually create a new C# project and then add references? - The Build Action for the xaml file must be set to Page, and Custom Tool set to MSBuild:Compile. The Build Action for window1 is set to Page, and the Custom Tool is set to MSBuild:Compile Change : <Window xmlns="" xmlns:x="" x:Class="Window1" to : <Window xmlns="" xmlns:x="" x:Class="SecureArchiving.Window1" - Once you make the above change, you should be able to call InitializeComponent in the constructor.
http://social.msdn.microsoft.com/Forums/vstudio/en-us/cda70903-edc7-4788-9405-8ba55a1e36ff/open-window-in-c-wpf?forum=wpf
CC-MAIN-2013-48
refinedweb
757
52.26
On Wed, 2006-05-03 at 17:49 -0400, Michael DeHaan wrote: > Given no other replies to this commentary, I think we're ok on the > PyYaml 3000 front (what to do about syck-python is another issue, and > I'm willing to let it slide if a good working alternative can get out > there). > > I do have people interested in reviewing this (Toshio, you are welcome > to as well), but I lack a potential sponsor for my first package. Can > anyone jump on board and help me out? The module itself was already > built with distutils, so the spec only moves it into a more reasonable > namespace and numbering scheme. > If you put together a good package, I'll sponsor you. I don't have much time right now (I've promised to review python-ctypes and I have to get an upstream release of qa-assistant out the door.) If someone else wants to do an initial review to make sure the package conforms to the Fedora Guidelines and runs okay I can do a final review for sponsorship much quicker. It would also be nice if you reviewed one or two packages before being sponsored. This helps in two ways: 1) it shows that you've read and understand the packaging guidelines. 2) it's good packaging karma (someone has to review your package, you review someone else's) > Here's the bugzilla: > Looks like you're keeping up to date with upstream which is good. I'll leave notes in the bug. -Toshio Attachment: signature.asc Description: This is a digitally signed message part
https://www.redhat.com/archives/fedora-extras-list/2006-May/msg00266.html
CC-MAIN-2017-09
refinedweb
268
68.91
System Administration Commands - Part 1 System Administration Commands - Part 2 parse_dynamic_clustertoc(1M) System Administration Commands - Part 3 - NIS+ client and server initialization utility nisinit -r nisinit -p Y | D | N parent_domain host... nisinit -c [-k <key_domain>] -H host | -B | -C coldstart nisinit initializes a machine to be a NIS+ client or an NIS+ root master server. It may be easier to use nisclient(1M) or nisserver(1M) to accomplish this same task. isolated. Specifies that the parent directory is a NIS version 2 domain. Specifies that the parent directory is a DNS domain. command to initialize the machine as an NIS+ client. If the coldstart file is from another client in the same domain, the nisinit command may be safely skipped and the file copied into the /var/nis directory as /var/nis/NIS_COLD_START. Specifies that the host hostname should be contacted as a trusted NIS+ server. The nisinit command will iterate over each transport in the NETPATH environment variable and attempt to contact rpcbind(1M) on that machine. This hostname must be reachable from the client without the name service running. For IP networks this means that there must be an entry in /etc/hosts for this host when nisinit is invoked. Specifies that the nisinit command should use an IP broadcast to locate a NIS+ server on the local subnet.. This option specifies the domain where root's credentials are stored. If it is not specified, then the system default domain is assumed. This domain name is used to create the /var/nis/NIS_COLD_START file. nisinit returns 0 on success and 1 on failure. Example 1 Initializing. example# nisinit -r This environment variable may be set to the transports to try when contacting the NIS+ server (see netconfig(4)). The client library will only attempt to contact the server using connection oriented transports. This file contains a list of servers, their transport addresses, and their Secure RPC public keys that serve the machine's default domain. This file describes the root object of the NIS+ namespace. It is a standard XDR-encoded NIS+ directory object that can be modified by authorized clients using the nis_modify() interface. This file describes the namespace that is logically above the NIS+ namespace. The most common type of parent object is a DNS object. This object contains contact information for a server of that domain. Internet host table. See attributes(5) for descriptions of the following attributes: NIS+(1), uuencode(1C), nisclient(1M), nisserver(1M), nisshowcache(1M), sysinfo(2), hosts(4), netconfig(4), nisfiles(4), attributes(5) NIS+ might not be supported in future releases of the Solaris operating system. Tools to aid the migration from NIS+ to LDAP are available in the current Solaris release. For more information, visit.
http://docs.oracle.com/cd/E26505_01/html/816-5166/nisinit-1m.html
CC-MAIN-2015-27
refinedweb
457
56.35
Summary: Use a Windows PowerShell function to find WMI classes with specific qualifiers. Microsoft Scripting Guy Ed Wilson here. In Thursday’s article, I talked about using the Set-WmiInstance cmdlet to work with WMI classes. One of the parameters, the class parameter, works with WMI singleton objects. Now, it is certainly possible to use WBEMTest to find singleton WMI classes. Such a WMI class is shown in the following figure in the WBEMTest utility. But with 1,085 WMI classes in Root\Cimv2, it is faster and more fun to use a WMI schema query. WMI schema queries are mentioned on MSDN, but there are no Windows PowerShell examples. I decided I needed to write a Windows PowerShell function that would query the schema to find the singleton classes for which I was looking. In addition, there are other class qualifiers I was interested in seeing as well. For example, there is a supportsupdate qualifier that lets me know that I can use that class to make modifications to a computer. There are other qualifiers that are even more important: abstract and dynamic. As an IT pro, I want to query dynamic WMI classes, and not the abstracts. For ease of use, I uploaded the script to the Scripting Guys Script Repository. I ended up writing a function I could use to find classes with specific qualifiers. As shown in the following figure, there are a few singleton WMI classes. I opened the function in the Windows PowerShell ISE, ran the script once to load the function into memory, and then I went to the command pane and typed the following command: Get-WMIClassesWithQualifiers -qualifier singleton The command and associated output are shown in the following figure. A WMI schema query queries the meta_class WMI class. It uses the isa keyword to specify from which WMI class I want to return the schema information. That part is rather simple. The difficult part was getting the quotation marks placed in the right position to enable automatic querying. Here is the query line I derived: $query = “select * from meta_class where __this isa “”$($class.name)”” “ I am interested in the qualifiers; therefore, I choose only the name of the WMI class and the qualifiers. This line appears is shown here: $a = gwmi -Query $query -Namespace $namespace | select -Property __class, qualifiers If the qualifiers contain the qualifier I am looking for, I return the WMI class name: if($a.qualifiers | % { $_ | ? { $_.name -match “$qualifier” }}) { $a.__class } The core portion of the script, with the aliases removed is shown here: Param([string]$qualifier = “dynamic”, [string]$namespace = “root\cimv2”) $classes = Get-WmiObject -list -namespace $namespace foreach($class in $classes) { $query = “Select * from meta_class where __this isa “”$($class.name)”” “ $a = Get-WmiObject -Query $query -Namespace $namespace | Select-Object -Property __class, qualifiers if($a.qualifiers | ForEach-Object { $_ | Where-Object { $_.name -match “$qualifier” }}) { $a.__class } } #end foreach $class Well, that is about it for today. I hope you enjoy the function, and have an awesome quite interesting, if you have to look for WMI clsses with special properties. But I'm afraid there is hardly any more use for querying the meta classes, than that, what you presented here. So it is really a special purpose area, but it's good to know how if you have to …! Klaus.
https://blogs.technet.microsoft.com/heyscriptingguy/2011/10/22/use-a-powershell-function-to-find-specific-wmi-classes/
CC-MAIN-2016-44
refinedweb
554
63.7
I hoping that you can suggest a solution (or point me to someone else) to an authentication issue for BI reports using TM1 where the users are from multiple domains. The situation: they have users from multiple domains that have been granted access to BI and to TM1. They have user based security in TM1 so they need to pass through the credentials to TM1 - can't use a single signon. Users can access the TM1 cubes through TM1 web without any issue. The problem occurs when they publish a package to the cube and choose "External Namespace" for the Signon on the Data Source connection. It appears that you can only choose one namespace for the connection - and the preliminary tests prove that. If they log into BI from a domain that is different than the one chosen on the data source connection then they are prompted to logon to that other domain. I have attempted to add another connection to the Data Source (see attachment), which points to the same TM1 cube but uses a different namespace for the signon, and I expected that BI should just choose the connection where they can actually authenticate against, but it shows the logon page for the namespace used on the last connection. Thanks in advance. They are using BI 10.1.1 and TM1 9.5.2 Stephen Topic SystemAdmin 110000D4XK 250 Posts Pinned topic BI reports using TM1 where the users are from multiple domains 2012-12-20T14:56:34Z |
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014922075
CC-MAIN-2016-07
refinedweb
251
67.89
17 May 2011 09:45 [Source: ICIS news] SINGAPORE (ICIS)--SABIC will collaborate with ?xml:namespace> The 260,000 tonne/year plant is expected to come on stream in 2015. It will be located in northern China at the production site of Sinopec SABIC Tianjin Petrochemical Co (SSTPC), a 50:50 joint venture of the two companies, SABIC said. Financial details were not disclosed. Polycarbonate is a plastic used in producing components for automotive parts, compact discs and other consumer products. SSTPC, which has been operational since last year, produces a range of petrochemical products including ethylene, polyethylene (PE), ethylene glycol (EG), polypropylene (PP), butadiene (BD) and phenol. For more on SABIC
http://www.icis.com/Articles/2011/05/17/9460330/sabic-sinopec-to-build-260000-tonneyear-pc-plant-in-china.html
CC-MAIN-2014-10
refinedweb
112
56.15
How fast do I talk?. As I now give lots of conference talks, this has become a professional issue: - It’s harder to understand what I say - The talks are much denser, as I cover more ground per minute - I need to write a lot more material to cover the time slot, which is mentally exhausting - I can’t guess how much time a draft takes without reciting it. I want to slow down. But “slowing down” is hard. How slow is slow enough? How do I practice speaking slowly? How fast do I talk, anyway? I could recite a fixed text and see how long it takes, but that’s too artificial for me. I want real data of how fast I slur my talks. I need to take existing talks and count my average words per minute. And I want to do this cheaply and quickly, without having to listen to the whole talk and painstakingly count the words. This means automatic transcription. I’m also a big believer in showing the whole process. I took notes through the project so I could share how I did things and the issues I ran into. The Goal Here’s what I need: - The total count of words I say in a conference talk. This would let me find my overall speaking pace. - A way to remove sections that are not me talking. This would be things like speaker introductions, applause at the end, questions. Including them will give me poorer data. - A way to measure my pace at finer resolution than “one talk”. Then I could measure standard deviation, or how much my speaking rate varies over the course of the talk. - A way to plot my pace over the course of a talk. Then I can see if difference speaking paces correspond to different sections of the talk, or if I uniformly speed up the further into the talk I get. The MVP is getting the total words per minute (wpm). That’s just words-in-talk / talk-time. As a first-order estimate, let’s look at Barack Obama’s Inaugural Address. That’s 120 words a minute. Assuming I want a 10% variance, I should be able to miss something like 12 words a minute and still be accurate enough. I don’t need good transcription, just any transcription. Even if it’s bad, if it gets most of the words right then I can get useful data. This means I can use something off-the-shelf and not worry about its accuracy. So the short term goal: transcribe the audio from a video of my talk. I downloaded a copy of my distributed systems and TLA+ talk to try this with. Transcription I assumed that transcription software would just output the text without any timing info. If I wanted the get the timing, I’d have to manually match up the audio and transcription. Alternatively, I can break the audio into minute-long segments and transcribe them individually. Since finding the total wpm is my priority, let’s start with transcribing everything at once. Local Transcription I found this guide to transcribing audio. Here’s what I did: - Install ffmpeg, pydub, and SpeechRecognition. - Use ffmpegto convert the mp4 to wav. - Load the wav until a python REPL with pydub, for passing into SpeechRecognition. - Discover that SpeechRecognitiononly accepts paths to audio files, not the memory representations (or file objects). Using pydubwas unnecessary. - Directly import the .wav into SpeechRecognition. Run the recordfunction. - Get a timeout error from the Google API, which the package used by default. Read the docs, find that local transcription uses sphinx and I need to install both Sphinxbaseand Pocketsphinx. - Neither sphinxhas a linux package, I need to compile them myself. Download both, follow the setup directions, run make. Get dependency errors. - Install bison, pulseaudio-libs-devel, and the python 2 development packages. Rerun make. - Try to use SpeechRecognitionagain. Get a new error. I need the pocketsphinxPython package. pip install pocketsphinx. Fail due to missing dependencies. Install swig. Run again, find it’s missing a C header. Track down the source and install alsa-lib-devel. - Run SpeechRecognition.Recognizer().record(). Wait for it to complete. - Drum fingers. - Drum fingers. - Drum fingers. Hm, maybe trying to transcribe 30 minutes of speech at once was a bad idea. The lack of any progress indicators isn’t helping. Out of curiosity, I look up how much it would cost to transcribe it manually. While searching for that I find that AWS just released a new transcription service. It’s apparently pretty inaccurate, but hey, I don’t need quality for this. At this point PocketSphinx has been running for 15 minutes. I leave it running and while I try out AWS. AWS Transcription - Upload the mp4 to an S3 bucket. - Select it in the transcription service. - Click “transcribe”. - Download the transcription. Total time, from discovering the service to getting the final file, is about 20 minutes. By this point Sphinx still hasn’t finished running. The transcription file is a json with the following format: { job_name, account_id, results: { transcripts: { [{transcript}] }, items: [{ start_time, end_time, alternatives [{}], type }] }, status } The start time is per word, in seconds. The two item types are “pronounciation” and “punctuation”; we only care about the former. “Punctuation” items do not have a start_time field. Since I have the start times per word, I don’t actually need the transcript itself. I can just extract the start times into an array and analyze that. There will be a few errors in the array, because the transcription gets some of the words wrong. At various points it transcribed “TLA+” as “Kelly Plus”, “Taylor Plus”, “till a plus”, and “Chile Plus”. But I don’t need it to be accurate. The talk is over 6,000 words long. It can add 300 extra words and still come under half my error budget. Analyzing the Data Choice of Language I have two options for the data analysis. First, there’s Python. Python is a workhorse. JSON parsing is easy and building out queries is straightforward. Python is my fallback language if I don’t have anything better to use. The other option is J. I’ve complained about J before: it’s arcane and hard to express what you want to do in its ultra-terse language.1 I’d say I’m a low-end intermediate J programmer, so I’ll be able to do the analysis, but there’s not guarantee it will be any easier than Python. The big problem is going to be parsing the JSON. J is an array language: it’s designed to work with homogenous arrays. All elements of an array must be the same type, and all subarrays must have the same length. JSON, by contrast, is designed around heterogenous arrays, leading to an impedance mismatch. On the other hand: I’ve had this idea for a while that J would make a good “interactive querying language”. It doesn’t matter if it’s hard to read if nobody else will ever read it. In fact, terseness is an advantage here. Compare writing i = 1 for j in [x**2 for x in range(1, 20)]: i *= j to */ *: }. i.20 I wanted to explore this idea more, so picked J for this project. Also, I like playing around with J. Sue me. The Analysis J can only store homogenous arrays. Every element of the array must have the same type and every subarray must be the same length. This makes it extremely difficult to store strings, let alone nested data! J uses boxing to get around this. A box can wrap any value, turning it into a single atom. This means the following two are the same type: ] x =: <'hello' '┌─────┐ │hello│ └─────┘' ] y =: <1 2 3 ; 4 5 6 '┌─────────────┐ │┌─────┬─────┐│ ││1 2 3│4 5 6││ │└─────┴─────┘│ └─────────────┘' The dec_pjson_ library function converts the JSON string into a set of nested boxes. Dictonaries are represented as 2-column tables, where the first element is the key and the second is the value.2 dec_pjson_ '{"a": [1, 2], "b": {"c": 3}}' '┌─┬─────┐ │a│1 2 │ ├─┼─────┤ │b│┌─┬─┐│ │ ││c│3││ │ │└─┴─┘│ └─┴─────┘' I can’t elegantly select by “key” here; it’s easier to select the corresponding table position instead. After that I need to filter out the punctuation items. I kludged out the first J script in about ten minutes. require 'convert/pjson' js =. dec_pjson_ fread 'codemesh-transcription.json' match =: ;: 'type pronunciation' lm =. -:&match@{: p =. (#~ lm"2) > (2 1;1 1) {:: js times =. ". > 1 {"1 0 {"2 p I’m not going to explain how it works. It very roughly corresponds to the following Python version, which I wrote in about three minutes: import json with open("./codemesh-transcription.json") as file: transcript = json.loads(file.read()) items = transcript['results']['items'] words = [float(i['start_time']) for i in items if i['type'] == 'pronunciation'] I expect J to be both faster and more concise than Python, but neither is true here. The Python script is only slightly longer than the J script. It also runs much faster, completing in less than a tenth of the time. Most of this time difference is due to dec_pjson_ being slow as heck. Here’s where I made a mistake. I wanted to prove to myself that the J would be a lot terser if I could just reduce my character count more. This then consumed 2 hours of my life. I eventually got this: require 'convert/pjson' js =: dec_pjson_ fread 'codemesh-transcription.json' t =. ". > (1&=&(L."0)#]) 0 1&{:: &.> (2 1;1 1) {:: js Then I spent another hour trying to make it more “elegant”, and eventually reached this: require 'convert/pjson' js =: dec_pjson_ fread 'codemesh-transcription.json' t =: ". 1 {::"1 ((<'start_time')&e."1 #]) ; (2 1;1 1) {:: js Which is more elegant, trust me on this. It’s still much slower than the Python (still gotta decode the JSON). I spent even more time trying to optimize the runtime. That’s the big problem with J: it gets you obsessed with golfing. I need to emphasize that this entire process was pointless. The 3 hour version didn’t get me better data than the version I wrote in ten minutes. That pokes a hole in my “J as a query language” idea. On the other hand, I did learn a lot about how to better handle JSON in J… let’s get back to the transcriptions, shall we? Analysis Now that we have an array of numbers, J becomes a little easier to work with. t is a list of all the times that I started saying a word, in seconds. The last time in the array is _1 {. t and corresponds to the total time I spent talking. The length of the array is the number of words I said, so divide the length by the last time will give my words per second. After that it’s just a multiplication to get my words per minute: t 6.04 6.17 6.24 6.36 ... wpm =: (60&*) @ (# % _1&{.) wpm times 188.84 189 words per minute is already pretty fast, and it’s actually an underestimate. After I finished speaking there was five minutes of questions, which were less dense word-wise. If I want to get how fast I spoke during the talk itself, I need to filter out everything past the end of the talk, which was at 1920 seconds. wpm 1920 (>#]) t 194.005 So about 200 words a minute. I also want to see how much this varies over time. To do that, I want to divide the times into bucket intervals, say 1 minute per bucket. I can do that by dividing each time by 60 and rounding down. bucket =: <.@%~ t2 =: 60 bucket 1920 (>#]) t That gives me, for each word, which bucket it falls in. Once I have that, I want to count how many words are in each bucket. Generating the minute counts ( mc) is surprisingly easy in J, once you know the trick. First, we have u~ y ↔ y u y. Second, x u/. y partitions y into arrays using x as the keys, and then applies u to each partition. This means that u/.~ y will collect identical elements and apply u to all of them. For example: 1 2 1 </. 'abc' '┌──┬─┐ │ac│b│ └──┴─┘' </.~ 'aba' '┌──┬─┐ │aa│b│ └──┴─┘' {./.~ y would get the head of each partition. Since every element of the partition is is the same minute, this is equivalent to getting the corresponding bucket. #/.~ y counts every element of each partition, which is equivalent to the number of words that fall into that bucket. Finally, we stitch the two arrays together with ,..3 ] mc =. |: ] ({. ,. #)/.~ t2 0 1 2 3 197 196 186 195 . . . As a sanity check, we should get the average of the wpm and make sure it’s close to our old value. I also recall the standard deviation as being “the square root of the mean of the differences of the values and the mean squared”, which is a lot easier to express in J than it is to express in English. We use the “under” operator &.:: if *: means “square”, then f&.:*: y ↔ sqrt(f(y^2)). mean =: (+/%#) 1 { mc mean ; (+/%#)&.:*: mean - (1 { mc) '┌───┬───────┐ │194│13.5254│ └───┴───────┘' They’re about the same, meaning that we’ve got it mostly right. J comes with a built in plot library called, creatively enough, ‘plot’. require 'plot' r =: 1 { mc plot r ,: 0 That’s a peak speed of over 220 words per minute. I need to slow down. Slowing Down How do I slow down? Same way I do anything: practice. When I’m trying to speak slowly and carefully, I slow down by about a third, to roughly 130 wpm. That’s my first target: practice saying something at 130 wpm. Let’s grab an arbitrary paragraph of text:. That’s 55 words. At my normal conference rate, I’d say that in 16 seconds. At 130 wpm, it’d be 25 seconds. I practiced saying that with a stopwatch and quickly found out that saying that in 25 seconds is just awful. Anything past 20 seconds and it feels like I’m just aiming for the metric instead of clarity. At 20 seconds, that’s 165 wpm. Is 130 wpm too slow? I don’t think so. The problem here is that speech isn’t uniform. A speech has pauses, meaningful silence, quotes, points you rush for emphasis, etc. I want to hit 130 wpm on average, not for every single thing I say. Some things might be faster, some might be slower. The smaller the rehearsal sample, the less likely that it’s a representative sample. 260 words, or about 2 minutes, seems like it would be more representative. I took a talk draft, made several two-minute chunks, and spent some time each day practicing them. After a while I could comfortably hit 130 wpm. After that, I added this to my vim config: function! g:Exo_vwal() let s:worddict = wordcount() if has_key(s:worddict, "visual_words") return s:worddict["visual_words"] else return s:worddict["words"] endif endfunction " Extraneous stuff removed au BufNewFile,BufRead *.talk.md setlocal statusline+=/%{g:Exo_vwal()/130} Now, when I open a file of filetype .talk.md, it shows the expected length of the talk in the status bar. If I visually select a snippet, I can also see how long that particular snippet takes. I still need to rehearse the talk to get the actual time, of course, but it’s a good first-order estimate. I can look at a section and immediately see if it’s roughly the right length or not. Results This was all in preparation for What We Know We Don’t Know, my talk on empiricism in software engineering. That talk felt easier on me, but I wanted to confirm I really was speaking more slowly. Once the video went online, I transcribed it and did the same analysis:4 mean ; (+/%#)&.:*: mean - (1 { mc) '┌───────┬───────┐ │162.816│25.1771│ └───────┴───────┘' It looks like the previous graph, but the y-axis is different. My mean is 162 wpm. It might not be 130, but it’s much better than 194. The deviation is much higher than before, but that’s expected, as I varied this talk’s tempo. Finally, I maxed out at 201 WPM, unlike before, when I hit 221 WPM. Here’s a graph of both together. My latter talk was about 6 minutes longer. What surprised me, though, was that the two talks covered the same amount of content. They both were around 6000 words total. That makes the whole analysis feel more “feasible” to me. Slowing down is easier on both me and the audience, but it doesn’t come at the cost of information. Takeaways Overall I’m glad I did this project. It gave me useful information that materially improved my speaking skills. I still need to regularly practice pacing, as otherwise I’ll slip back to 200 WPM. Other takeaways: - Automated transcription is cheap if you don’t need accuracy. - It’s feasible to introspect the way I do things and then use that information to do them better. - J isn’t the data querying tool I hoped it’d be. - Rehearsing is good. Thanks to Alex ter Weele for feedback. - I’m going to assume a tiny bit of knowledge of J. If this is your first encounter, I have some more beginner-friendly articles here and here. [return] - This means dec_psjon_isn’t compliant with the JSON spec: if you have a duplicate key, it will create two rows. [return] - When editing this post I wondered why I was creating the first row, because I never actually used it. It’s because we might have a minute with no words in it at all! Without the first row, we have no way to knowing if this happened. With the first row, we’d see a gap in the incrementing numbers. In practice, though, there weren’t any gaps. Commenting your decisions is a good idea! [return] - This took me over 30 minutes to redo. First, I forgot how to import files in J, and then processing the file wasn’t working. After 15 minutes of searching, I discovered I had written &e."1instead of @e."1. J I love you but you’re killing me here. [return]
https://hillelwayne.com/post/talk-fast/
CC-MAIN-2020-05
refinedweb
3,076
76.11
Tom Dringer Joined Activity Hi, I am having to use a different computer whilst mine is in for repair. So i generated the SSH keys to be used for deployment with Hatchbox. Using [email protected] or [email protected] just gives me an error Permission denied (publickey). Does anyone know a fix for this? I am locked out of my server and i desperately need to check the logs for an error which is giving me a white screen of death. Thanks Wow thats awesome! @joshBrody - just check default scope is only going to be in the model or the controller i guess? I've just checked and i don't have default scope anywhere Hi everyone. I am currently trying to order some ActiveRecord records by score. In my controller i have: def index @pagy, @drivers = pagy( Driver.select( 'drivers.*', '(drivers.no_races + drivers.no_poles + drivers.no_podiums + drivers.no_wins) AS score' ).reorder('drivers.score DESC'), page: params[:page], items: 16 ) end I am using Pagy for the pagination. As the code shows, I do a query to select all drivers and then add together 3 columns in the table as 'score'. I then want to order by score going from high to low and show 16 records per page. When the page loads it seems to order by driver id. I can't see anywhere else that i have an order by, but i did add reorder to override anything else. Anyway for whatever reason i'm stuck with the wrong ordering. Any direction is appreciated :-) Mockup - Ok i made a staging enviroment in my app, which i guess could be the issue. I have environment variables on Hatchbox using staging, rather than p[roduction. I'll dig deeper. Thanks Cool can i set this somewhere? My path should be pretty default. Its just app/ Hi, I am deploying to hatchbox and everything appears fine until i load the site up in the browser. Looking at the logs there is no public/index.html. On my development environment there is also no index file in public. I am using Rails 6 which apparently doesn't build a public index.html file? Posted in Postgres issues I now have Postgres running on my local machine nicely. My issue now is i can't run a migration due to the following error: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "drivers" does not exist LINE 8: WHERE a.attrelid = '"drivers"'::regclass There should be a relationship between a user and a driver, where the user has one driver. In my user (Devise) model I have has_one :driver and in my driver migration I have: t.string :user_id t.belongs_to :user So in the driver table the user_id field should hold the user.id. Any direction is appreciated. Posted in Postgres issues Hi, So as i began a project earlier in the year, i decided to go full Docker for deployment. That was all good except debugging and stuff proved difficult so this weekend i decided to make the project native and use something for deployment. Long story short, now i have gone back to a native based project (i.e no Docker), my Postgres installation (which was fine in the beginning) now just does not work. I had issues with port numbers (which i have since managed to fix) and no issues with database not found. To make things worse, i think (i'm on macos and using Rubymine) i have Postgres installed via the OS, multiple versions by Homebrew, and some from standalone Postgres apps. So obviously with these issues, i can;t start my app or run migrations etc. Has anyone had this issue when moving away from Docker? My error at the moment is no database named "xxx". I thought when i did i migration its all taken from the database.yml? I've run commands like rake db:create and similar. I'm not totally sure the db i am connected to is even the right one. Posted in Pretty urls with FriendlyID Discussion Is it possible to to make the url "{id}-{user.fname}-{user.lname}"? It seems to work fine clicking on links, but as soon as i try to create, edit, or delete anything i get route not found. Hi, I want to validate my image upload field by making a user upload only a square image (i.e 200px x 200px). I'm basically wanting square image dimentions so it will resize and nicely and not look disproportional. Can this be done? Thanks Anyone interested in this, in the news controller under def index you can just add the variable @students = Students.all or whatever and it really is as simple as that. I'm thinking i need to look at Nested Resources? Hi, I’m not even sure I’m using the correct terminology here (sharing resources among controllers) but here goes. Imagine I have a page called students with the usual CRUD functionality and another page with another controller called news or something. If the student page had a table called students with first name, second name etc ... how would I use the student table in the news template so I could do a for each student to list names or whatever? This is where things start to fall apart in my understanding of Rails. Thanks! Posted in Liking Posts Discussion I am also having the 404 issue but it's something to do with routes i'm guessing? ActionController::RoutingError (uninitialized constant Developments): and then in the console: POST [HTTP/1.1 404 Not Found 1343ms] When i run rake routes I get the following: new_development_like GET /developments/:development_id/like/new(.:format) developments/likes#new edit_development_like GET /developments/:development_id/like/edit(.:format) developments/likes#edit development_like GET /developments/:development_id/like(.:format) developments/likes#show PATCH /developments/:development_id/like(.:format) developments/likes#update PUT /developments/:development_id/like(.:format) developments/likes#update DELETE /developments/:development_id/like(.:format) developments/likes#destroy POST /developments/:development_id/like(.:format) developments/likes#create Any feedback is appreciated. Thanks! Wow that really is above and beyond! Thank you so much! Thanks for the feedback. I get the same error still, but this time much more detailed. Uncaught ReferenceError: toastr is not defined <anonymous> (index):38 dispatch turbolinks.js:75 notifyApplicationAfterPageLoad turbolinks.js:994 pageLoaded turbolinks.js:948 e turbolinks.js:872 start turbolinks.js:882 start turbolinks.js:1040 <anonymous> application.js:24 <anonymous> application-51d3c38d384dcac9fb08.js:2 Webpack 3 localhost:3000:38:5 <anonymous> (index):38 dispatch turbolinks.js:75 notifyApplicationAfterPageLoad turbolinks.js:994 pageLoaded turbolinks.js:948 e turbolinks.js:872 (Async: EventListener.handleEvent) start turbolinks.js:882 start turbolinks.js:1040 <anonymous> application.js:24 <anonymous> application-51d3c38d384dcac9fb08.js:2 I have cleared my cache and all the usual things. Is there anything i should be looking out for in those errors? I load my js in the head tag on my application layout file <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> Thanks Sure, so for example. I am trying to add Toastr. I have installed via Yarn. In my javascript/packs/application.js I have require("toastr") I also have an application_helper.rb which i saw from a tutorial about adding Toastr so i have: def toastr_flash flash.each_with_object([]) do |(type, message), flash_messages| type = 'success' if type == 'notice' type = 'error' if type == 'alert' text = "<script>toastr.#{type}('#{message}', '', { closeButton: true, progressBar: true })</script>" flash_messages << text.html_safe if message end.join("\n").html_safe end Then I call toastr_flash in my views/layouts/application.html.rb. The error i get is Uncaught ReferenceError: toastr is not defined Any direction is appreciated. Hi. I am fairly new to Rails and so far I have been unsucessful at adding any JS to my Rails 6 project. I have seen many videos and tutorials but i seem to run in to the same issue. Basically I get "xxx is undefined" for every script. I'm thinking my scripts are called at the wrong time or in the wrong order. I'm using Webpacker for my JS. Thanks
https://gorails.com/users/35309
CC-MAIN-2021-04
refinedweb
1,343
60.21
Introduction to Programming Languages/Algebraic Data Types This chapter presents an overview on how some of the most popular abstract data types can be implemented in a more functional way. We begin with the important concept of Algebraic Data Types (ADTs). They are the main mechanism used to implement data structures in functional languages. We than proceed to present functional implementations of many popular data types such as stacks and queues. Algebraic Data Types[edit] Most programming languages employ the concept of types. Put simply, a type is a set. For instance, the type int in the Java programming language is the set of numbers whereas the type boolean is made of only two values: true and false. Being sets, types can be combined with mathematical operations to yield new (and perhaps more complex) types. For instance, the type int boolean (where denotes the Cartesian product) is a set of tuples given by: [[w:Algebraic_data_type|Algebraic Data Types] are a formalism used to express these compositions of types. In ML, these types are declared with the keyword datatype. For instance, to declare a type weekday containing seven elements, in ML, we write: datatype weekday = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday The vertical bar is used to denote union. Indeed, an algebraic datatype is often the union of simpler types. Each of these subsets has a unique label. In our example above, we have seven different labels. Each label distinguishes a singleton set. In other words, the cardinality of our weekday type is seven, as this type is the union of seven types which have cardinality one. A Boolean type can be declared as follows: datatype Boolean = True | False And the union of booleans and week days is declared as follows: datatype BoolOrWeek = Day of Weekday | Bool of Boolean; Whereas its Cartesian product can be declared as: data BoolAndWeek = BoolWeekPair of Boolean * Week; Algebraic Data Types have two important properties. The first is the fact that they can be pattern matched. Pattern Matching is a simple mechanism that allows a function to be implemented as a series of cases triggered by the tags that appear on the left hand side of the declarations. For example, we could write a function to test if a Weekday is part of the Weekend as follows: fun is_weekend Sunday = True | is_weekend Saturday = True | is_weekend _ = False Patterns are tried one at a time, from top to bottom, until one of them matches. If none match, the ML runtime throws an exception. Wildcards can be used, as we did above with _. This pattern matches any Weekday. The label that is associated with each subset of a datatype is essential for pattern matching, as it distinguishes one subset from the other. The other important property of Algebraic Data Types is the fact that they can have recursive definitions. Thanks to that, structures such as binary trees can be defined quite concisely. The example bellow shows a tree of integer keys. datatype tree = Leaf | Node of tree * int * tree; Algebraic Data Types can also be _parametric_, thus depending on other types. This allows us to define more generic structures, which increases modularity and reuse. For instance, a generic tree can be defined as follows: datatype 'a tree = Leaf | Node of 'a tree * 'a * 'a tree; Where the ' sign is used to indicate that 'a can be any type. A tree of weekdays, for instance, has type weekday tree. The fact that Algebraic Data Types can be defined recursively offers a great deal of flexibility. In the next sessions, we will show examples of how Algebraic Data Types can be used to implement some common data structures. Disjoin Unions[edit] As we have explained before, algebraic Data types represent disjoin unions of simpler types. As a new example, the type bunch, below, describes the union of two types: a polymorphic 'a type, and a polymorphic list type. datatype 'x bunch = One of 'x | Group of 'x list; The function size below, of type 'a bunch -> int illustrates how this type can be used. This function returns the number of elements in an instance of bunch: fun size (One _) = 1 | size (Group x) = length x; Disjoint unions can also be implemented in languages that do not support the concept of labeled types. For instance, we could implement the type bunch in C, but, in this case, the compiler does not have enough information to check the correctness of the program: #include <stdio.h> #include <stdlib.h> enum bunch_tab {ONE, GROUP}; typedef union { int one; int* group; } bunch_element_type; typedef struct { bunch_element_type bunch_element; unsigned tag; } bunch; bunch* createOne(int i) { bunch* b = (bunch*)malloc(sizeof(bunch)); b->tag = ONE; b->bunch_element.one = i; return b; } void printBunch(bunch* b) { switch(b->tag) { case ONE: printf("%d\n", b->bunch_element.one); break; case GROUP: { int i = 0; while (b->bunch_element.group[i] != 0) { printf("%8d", b->bunch_element.group[i]); i++; } } } } int main(int argc, char** argv) { while (argc > 1) { int i; argc--; i = atoi(argv[argc]); bunch* b1 = createOne(i); printBunch(b1); } } A union of types in C is defined by the union construct. In this example, we use a structure of such a union, plus an integer representing the label, i.e., the type identifier. The programmer must be careful to never produce inconsistent code, because the language is not able to enforce the correct binding of labels and types. For instance, the function below is valid, yet wrong, from a logic perspective: bunch* createOne(int i) { bunch* b = (bunch*)malloc(sizeof(bunch)); b->tag = GROUP; b->bunch_element.one = i; return b; } The function is wrong because we are labeling the type with the constant GROUP, which was designed, originally, to denote instances of bunch having several, and not just one integer element. In ML, or in any other language that supports labeled disjoint unions, such mistake would not be possible.
http://en.wikibooks.org/wiki/Introduction_to_Programming_Languages/Algebraic_Data_Types
CC-MAIN-2014-49
refinedweb
982
60.85
JAX-RS: Easily Bridge Platforms with Services and JSON JAX-RS is part of Java EE, which makes creating web services in Java a cinch. You can also create Java applications that call web services easily thanks to the javax.ws.rs.client.Client class, also part of JAX-RS. Even better, you can easily handle and convert JSON data as parameters to your web service calls so that you can call Java web services from JavaScript or other platform languages. Let's take a look. The Library Web Service Let's say you're implementing the database and related services for your local library. You might want to build the lookup service (where books are searched by title or other criteria) as a web service so that you can build multiple applications in different languages to access them. For instance, your web service can be called by a web application for people using their browser at home, from Objective-C for people using an iOS application, or from Java for people using an Android application, and so on. With JAX-RS, you can build this service — and others in your library application — in Java with plain-old-Java-objects (POJOs) and some annotations. First, we define a Book object like so: public class Book { String title; String author; String publisher; String revision; String description; // getters and setters here… } Next, we have a basic lookup service that lets you pre-populate the book library with book information, and then search for them: public class LookupResource { static HashMap<String,Book> books = new HashMap<>(); public Book getBook(String title) { // Lookup a book by given title System.out.println("Looking up title: " + title); return books.get(title); } public void storeBook(Book book) { // Make sure we have a valid book if ( book == null || book.getTitle() == null ) { return; } System.out.println( "Storing book: " + book.getTitle() ); books.put(book.getTitle(), book); } } To web service-enable this class you add the proper annotations and import the javax.ws.rs.* package classes as shown here: import java.util.HashMap; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("/lookup") public class LookupResource { static HashMap<String,Book> books = new HashMap<>(); // Process HTTP GET requests to lookup books @GET @Produces(MediaType.APPLICATION_JSON) public Book getBook(@QueryParam("title") String title) { // Lookup a book by given title System.out.println("Looking up title: " + title); return books.get(title); } // Process HTTP POST requests to store books @POST @Consumes(MediaType.APPLICATION_JSON) public void storeBook(Book book) { // Make sure we have a valid book if ( book == null || book.getTitle() == null ) { return; } System.out.println( "Storing book: " + book.getTitle() ); books.put(book.getTitle(), book); } } We'll look at these annotations in detail in a moment. For now, we need to create a Java EE application to deploy this service. To do this, create a Java EE project in your favorite IDE, and add the code above as well as an Application class like this: import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("libraryapp") public class LibraryApp extends Application { } Since I created a Java EE project named MyJAXRSProject, the full URL to access my library web service deployed locally is available here. Annotations Before we go any further, let's take a step back and look at the annotations in the LookupResource class one at a time. First, the @Path annotation indicates that this service will be accessible through the URL: http://<server>:<port>/<context>/<application>/lookup". The @GET and @Produces and @Consumes annotations are used to indicate that only JSON data will be accepted and returned. So far so good, but JSON can be a little messy to deal with in Java. Again, JAX-RS makes this easy as well. Let's explore that now. JAX-RS Client Application Using the javax.ws.rs.client.Client and javax.ws.rs.client.ClientBuilder classes, we can gain access to a javax.ws.rs.client.WebTarget — our web service in this case — that we can make calls to and from a Java application. For instance, to access the web service we built above, we would need the following code: Client webclient = ClientBuilder.newClient(); WebTarget target = webclient.target(""); To store a book in the library database using this service, you need to send JSON data via an HTTP POST. The javax.ws.rs.client.Entity class is used to take a Book object and encode it as JSON data transparently: Book book = new Book(); book.setTitle("..."); ... Entity.entity(book, MediaType.APPLICATION_JSON) You pass the result of this call as a POST request to the service with this line of code: target.request().post( Entity.entity(book, MediaType.APPLICATION_JSON), Book.class); As a result, JSON will be passed to the web service, where it will be reassembled into a Java object for you, thanks to JAX-RS, and then stored in the HashMap of library books. To look up the book later, you need to make a GET request where the book search criteria (i.e., the title) is passed as a parameter: Book book = target.queryParam("title", title) .request(MediaType.APPLICATION_JSON) .get(Book.class); Although you specified JSON as the data format for your service, JAX-RS allows you to write Java code that deals with POJOs instead. To prove that JSON is indeed used to pass data around, just call the GET method from a browser. In this example, assume I added my book, Java Messaging, to the library previously. Typing the following URL in a browser: will yield the following JSON result: {"author":"Eric J. Bruno","description":"As software becomes more complex, and the Web is leveraged further, the need for messaging software continues to grow. Virtually all software written today requires at least one form of internal, and even external, communication. Java Messaging explores the various methods of intra-process and inter-process messaging for Java software, such as JavaBean events, JMS, JAX-RPC, JAXM, SOAP, and Web Services. Programmers will learn the basics of these APIs, as well as how, when, and why to use each one, including how to use them in combination, such as combining SOAP with JMS over a WAN. The book begins by walking the reader through simple intra-process communication using JavaBean events. A set of classes is constructed that extend JavaBean events beyond one JVM, transparently using JMS. The messaging paradigms of JMS are explained thoroughly, including in-depth discussions on the theory and mechanics of message queues. Design patterns and helper classes are also explored, which ultimately combine to form a generic messaging framework that helps programmers avoid common pitfalls.. By the end of the book, programmers will not only understand the various messaging paradigms, but they will also understand how to architect complex distributed applications that use them together — with a framework that provides a running start.","publisher":"Cengage Learning","revision":"1","title":"Java Messaging"} JAX-RS not only allowed us to easily turn a set of POJOs into a web service, it also helped us bridge the worlds of JavaScript and mobile technology by transparently handling the JSON details for us. Happy coding! -EJB
http://www.drdobbs.com/jvm/jax-rs-easily-bridge-platforms-with-serv/240165852?cid=SBX_ddj_related_mostpopular_default_jvm&itc=SBX_ddj_related_mostpopular_default_jvm
CC-MAIN-2014-35
refinedweb
1,210
55.44
Well, this problem has a nice BFS structure. Let's see the example in the problem statement. start = "hit" end = "cog" dict = ["hot", "dot", "dog", "lot", "log"] Since only one letter can be changed at a time, if we start from "hit", we can only change to those words which have only one different letter from it, like "hot". Putting in graph-theoretic terms, we can say that "hot" is a neighbor of "hit". The idea is simpy to begin from start, then visit its neighbors, then the non-visited neighbors of its neighbors... Well, this is just the typical BFS structure. To simplify the problem, we insert end into dict. Once we meet end during the BFS, we know we have found the answer. We maintain a variable dist for the current distance of the transformation and update it by dist++ after we finish a round of BFS search (note that it should fit the definition of the distance in the problem statement). Also, to avoid visiting a word for more than once, we erase it from dict once it is visited. The code is as follows. class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { wordDict.insert(endWord); queue<string> toVisit; addNextWords(beginWord, wordDict, toVisit); int dist = 2; while (!toVisit.empty()) { int num = toVisit.size(); for (int i = 0; i < num; i++) { string word = toVisit.front(); toVisit.pop(); if (word == endWord) return dist; addNextWords(word, wordDict, toVisit); } dist++; } } private: void addNextWords(string word, unordered_set<string>& wordDict, queue<string>& toVisit) { wordDict.erase(word); for (int p = 0; p < (int)word.length(); p++) { char letter = word[p]; for (int k = 0; k < 26; k++) { word[p] = 'a' + k; if (wordDict.find(word) != wordDict.end()) { toVisit.push(word); wordDict.erase(word); } } word[p] = letter; } } }; The above code can still be speeded up if we also begin from end. Once we meet the same word from start and end, we know we are done. This link provides a nice two-end search solution. I rewrite the code below for better readability. Note that the use of two pointers phead and ptail save a lot of time. At each round of BFS, depending on the relative size of head and tail, we point phead to the smaller set to reduce the running time. class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { unordered_set<string> head, tail, *phead, *ptail; head.insert(beginWord); tail.insert(endWord); int dist = 2; while (!head.empty() && !tail.empty()) { if (head.size() < tail.size()) { phead = &head; ptail = &tail; } else { phead = &tail; ptail = &head; } unordered_set<string> temp; for (auto itr = phead -> begin(); itr != phead -> end(); itr++) { string word = *itr; wordDict.erase(word); for (int p = 0; p < (int)word.length(); p++) { char letter = word[p]; for (int k = 0; k < 26; k++) { word[p] = 'a' + k; if (ptail -> find(word) != ptail -> end()) return dist; if (wordDict.find(word) != wordDict.end()) { temp.insert(word); wordDict.erase(word); } } word[p] = letter; } } dist++; swap(*phead, temp); } return 0; } }; Plz clarify my doubt! Thanks. :) First of all, thanks for your detail comment. But in your first solution, I think, "wordDict.erase(word);" can be deleted(the first statement in function addNextWords), because it is not necesary since you have deleted the word when it is pushed in the queue, so it just influence the beginWord, we delete the beginWord if it exist in toVisit. Firstly, thank you for the detailed explanation. It is very helpful! I have a question here, since the problems requests "shortest transformation sequence ", I see you return "dist" when finding the endword. How can you make sure dist is the smallest? Thank you! Well, since adjacent words can only have one different letter and we search for the next words while sticking to this requirement using BFS, the dist will be the answer when the endWord is hit. I did not understand why you pushed wordDict.insert(endWord); in the beginning. How is it making the solution easy? As even without it it is working Share my java Solution, 26ms, use a HashMap to mark whether a word is not yet visited or it is visited by head / tail queue. public class Solution { public int ladderLength(String beginWord, String endWord, Set<String> wordList) { HashMap<String, Integer> h = new HashMap(); for (String i : wordList) h.put(i, 0); ArrayList<String> l = new ArrayList(), r = new ArrayList(); l.add(beginWord); r.add(endWord); h.put(beginWord, 1); h.put(endWord, -1); int i = 0, j = 0; while (i < l.size() && j < r.size()) { int curStep = h.get(l.get(i)); char[] c = l.get(i).toCharArray(); for (int t = 0; t < c.length; t++) { char cc = c[t]; for (char x = 'a'; x <= 'z'; x++) if (x != cc) { c[t] = x; String y = String.valueOf(c); if (h.containsKey(y)) { int step = h.get(y); if (step == 0) { l.add(y); h.put(y, curStep + 1); } else if (step < 0) { return curStep - step; } } c[t] = cc; } } i++; curStep = h.get(r.get(j)); c = r.get(j).toCharArray(); for (int t = 0; t < c.length; t++) { char cc = c[t]; for (char x = 'a'; x <= 'z'; x++) if (x != cc) { c[t] = x; String y = String.valueOf(c); if (h.containsKey(y)) { int step = h.get(y); if (step == 0) { r.add(y); h.put(y, curStep - 1); } else if (step > 0) { return step - curStep; } } c[t] = cc; } } j++; } return 0; } } Thank you for sharing this awesome code! It's straightforward and easy to understand and well explained. The following is my take based on your code, added some comments and used more explicit variable names. Hope it could help somebody. class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { /* Search from both ends. From 'beginWord', find the set of words which are one character from 'beginWord'. Do the same to 'endWord', form a set of words one character from 'endWord'. Check each word in the smaller of 'beginWord'/'endWord', if it is in the other set. If it is, we are done. Otherwise, for each word in 'begigWord'/'endWord', update the set (by changing one character) */ unordered_set<string> head, tail, *smallerSet, *biggerSet; head.insert(beginWord); tail.insert(endWord); int dist = 1; while (!head.empty() && !tail.empty()) { ++dist; smallerSet = (head.size() < tail.size()) ? &head : &tail; biggerSet = (head.size() < tail.size()) ? &tail : &head; unordered_set<string> reachableWords; //for (auto itr = smallerSet->begin(); itr != smallerSet->end(); ++itr) for(const auto& w: *smallerSet) { string word(w); wordDict.erase(word); for (int i = 0; i < (int)word.length(); ++i) { char letter = word[i]; for (int c = 0; c < 26; ++c) { word[i] = 'a' + c; if (biggerSet->find(word) != biggerSet->end()) return dist; if (wordDict.find(word) != wordDict.end()) { reachableWords.insert(word); wordDict.erase(word); } } word[i] = letter; } } swap(*smallerSet, reachableWords); } return 0; } }; Seems having problem for the second solution. If the endWord is one character different from the beginWord, and the beginWord is not in the dictionary, it will return 2, but actually the length could either be zero or larger than 2. @nosrepus That is because in the end you need to return 0, not dist. dist is always returned when the last word is found, in the loop. int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { int res = 1; deque<string> candidate; deque<string> cur; cur.push_back(beginWord); wordList.erase(beginWord); string temp; while (!cur.empty()) { while (!cur.empty()) { beginWord = cur.front(); cur.pop_front(); for (int i = 0;i<endWord.size();i++) { temp = beginWord; for (int j = 0;j<26;j++) { temp[i] = 'a' + j; if (temp == endWord) return res+1; if (temp != beginWord&&wordList.find(temp) != wordList.end()) { candidate.push_front(temp); wordList.erase(temp); } } } } swap(cur, candidate); res++; } return 0; } Thanks for sharing! Here's my similar Java version. I use visited set explicitly rather than modify dict which is more straightforward in my view. update (2017/03/01): wordList is of List type now. And all transformed words (including endWord) must be in dictionary. For more efficiency, please refer to my bidirectional BFS solution (). public int ladderLength(String beginWord, String endWord, List<String> wordList) { Set<String> dict = new HashSet<>(wordList), vis = new HashSet<>(); Queue<String> q = new LinkedList<>(); q.offer(beginWord); for (int len = 1; !q.isEmpty(); len++) { for (int i = q.size(); i > 0; i--) { String w = q.poll(); if (w.equals(endWord)) return len; for (int j = 0; j < w.length(); j++) { char[] ch = w.toCharArray(); for (char c = 'a'; c <= 'z'; c++) { if (c == w.charAt(j)) continue; ch[j] = c; String nb = String.valueOf(ch); if (dict.contains(nb) && vis.add(nb)) q.offer(nb); } } } } return 0; } Hey! I just want to thank you so much for actually explaining your solutions. Most people just copy and paste from their OJ but you actually take the time to explain. So thanks for that. Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/16983/easy-76ms-c-solution-using-bfs
CC-MAIN-2017-51
refinedweb
1,488
68.67
Base types, Collections, Diagnostics, IO, RegEx… The main feature of the System.TimeZoneInfo class (previously named System.TimeZone2 in CTPs prior to .NET Framework 3.5 Beta 1) is to enable .NET developers to seamlessly work with Windows time zones in their applications. This includes enabling .NET applications to take advantage of the new Windows Vista Dynamic Daylight Saving Time functionality, which allows the operating system to store historically accurate time zone information (this includes both past and future time zone data). With the release of .NET Framework 3.5 Beta 1, the BCL team has received several questions regarding time zone support in Windows and the differences between time zone support on Windows XP and on Windows Vista. In this article, I’ll attempt to explain a little bit about how time zones work in Windows so that .NET developers can have a better understanding of what happens under the hood when they use System.TimeZoneInfo to perform common time zone related tasks in their code. Windows computers store time zone data in the Windows Registry. Before discussing the storage layout of time zones in the registry, I want to issue a standard disclaimer about modifying the Registry (e.g., please don’t email me if you inadvertently destroy your computer while changing registry values with regedit.exe. :-) ): All time zones installed on the computer are stored in the following registry hive: Each time zone has its own unique key under this registry hive. Sub-keys are used to store information about the time zone such as the display name, standard name, daylight name, and the optional daylight start and daylight end times. As you can see above, the display strings are loaded either from the Multilingual User Interface (MUI) DLL, tzres.dll, or straight from the registry, when MUI support is unavailable. MUI-enabled operating systems such as Windows Vista contain MUI_Display, MUI_Std, and MUI_Dlt keys, which are indirectly controlled by the operating systems regional settings. On down-level platforms such as Windows XP and Windows Server 2003, only the Display, Std, and Dlt keys exist. The Display, Std, and Dlt key values are localized only in the default language of the operating system. Because of the Windows time zone registry architecture, CurrentUICulture settings do not impact the values of these TimeZoneInfo properties. Here is a sample program that demonstrates the use of the TimeZoneInfo properties described above: using System; public class TimeZoneInfoSample { private static void Main() { String id = "Alaskan Standard Time"; TimeZoneInfo tzi; try { tzi = TimeZoneInfo.FindSystemTimeZoneById(id); } catch (TimeZoneNotFoundException e) { Console.WriteLine(id + " not found on the local computer: " + e); return; catch (InvalidTimeZoneException e) { Console.WriteLine(id + " is corrupt on the local computer: " + e); Console.WriteLine("TimeZoneInfo.Id = " + tzi.Id); Console.WriteLine("TimeZoneInfo.DisplayName = " + tzi.DisplayName); Console.WriteLine("TimeZoneInfo.StandardName = " + tzi.StandardName); Console.WriteLine("TimeZoneInfo.DaylightName = " + tzi.DaylightName); Console.WriteLine("TimeZoneInfo.BaseUtcOffset = " + tzi.BaseUtcOffset); Console.WriteLine("TimeZoneInfo.SupportsDaylightSavingTime = " + tzi.SupportsDaylightSavingTime); } } The Dynamic DST sub-key stores historical time zone data. Windows Vista comes pre-installed with this historical time zone data for many time zones. Windows XP and Windows Server 2003 users can download the February 2007 cumulative time zone update (KB931836) to get these registry keys:. Windows XP and Windows Server 2003 operating systems do not currently use the Dynamic DST data by default (even when the data exists after the KB931836 update is installed), but System.TimeZoneInfo is smart enough to use the Dynamic DST historical data when it exists, on any operating system version. TimeZoneInfo contains the static property “TimeZoneInfo.Local” which loads the current, local time zone off of the computer and returns a TimeZoneInfo object. While loading the local time zone, TimeZoneInfo checks the operating system settings to see whether or not daylight saving time should be obeyed. Computer users generally control this setting through the Date and Time control panel — specifically the ‘Automatically adjust clock for Daylight Saving Time’ checkbox: Depending on the version of Windows being used, this checkbox will set either the “DisableAutoDaylightTimeSet” or the “DynamicDaylightTimeDisabled” registry key values to one (1): HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation "DynamicDaylightTimeDisabled"=dword:00000001 "DisableAutoDaylightTimeSet"=dword:00000001 When daylight saving time is disabled for the local time zone, “TimeZoneInfo.Local” will return a TimeZoneInfo object with “TimeZoneInfo.SupportsDaylightSavingTime” set to False. Any TimeZoneInfo.ConvertTime(...) calls using this TimeZoneInfo instance will not take daylight saving time into account. I and others have asked many times over the course of more than a year. But there has never been a response. Why must you create more proprietary solutions for something that already exists? Take a look at tz: A thin wrapper class around it would be ideal, rather than this new TimeZoneInfo. Why are we still messing with the registry in this day and age... For all but the most unique requirements, that is an automatic bug in my book. Next point, which is slightly off topic, but still time-related. The present DateTime class is unacceptable. I would like a UTC-only DateTime class. Timezones can be handled as offsets from that. Sure, I can use the existing DateTime class as UTC, but why must I make the exact same settings ever single time? There is always the chance that I will forget somewhere and end up needing to fix a bug later. If you are not willing to do the work, then _let_ me. However, you have sealed the type and not offered any interfaces. Either 1) unseal it (easiest), and / or 2) create an IDateTime interface, apply it to DateTime, and fix all necessary signatures (the better solution in the end, but much more work and less likely.) Hi Chronos, Thanks for your comments. >> Re: tzinfo The TimeZoneInfo feature is a wrapper around the time zone functionality that is already provided by the Windows operating system today. Also, TimeZoneInfo does provide the necessary APIs for a developer to import the tzinfo data into custom time zones that are not currently present in Windows. >> Re: UTC-DateTime Stay tuned for future blog posts :-) Josh, Thanks for the response. I have a few comments. > The TimeZoneInfo feature is a > wrapper around the time zone > functionality that is already > provided by the Windows > operating system today. As this post mentions, though, some of that functionality is only available in Vista. An update (KB931836) will need to be installed for earlier versions. And when future updates are made (as there recently were earlier this year), then more updates will need to be installed. As a developer, I can not assume that all clients will have the necessary updates installed. So I suppose that I will need to always import tc into custom timezones to ensure functionality. Which brings us back to the original situation. Wrapping tc itself would free the need to install updates and would be platform independent. I am really looking forward to any progress or developments regarding a UTC-DateTime type. Please keep us informed.)’. This does not solve the obvious missing piece of the DateTime object...no time zone information. So..if I use DateTime anywhere and it get's consumed in the another time zone there is NO WAY of knowing exactly when the event happened. Wierd that after all this time (no pun intended) this has not been addressed. David, We actually have a new type in the .NET Framework 3.5 Beta 1 called DateTimeOffset. This new date time structure is made up of a date time and an offset relative to the UTC time zone. DateTimeOffset includes most of the functionality of the current DateTime and allows seamless conversion to DateTime as well. TimeZoneInfo also works with both DateTime and DateTimeOffset. We'll have more information on DateTimeOffset in a future blog post. I look forward to proper time zone handling in the future. But I have to write apps today that handle timezones. Any articles/links on converting UTC to/from any arbitrary time zone in .NET today ? This is for browser apps, where converting to user's time would be done on the middle-tier web-server. There would be lots of users from different time zones, so ToLocalTime in the middle tier doesn't work, as there are many local times. (Ok for smart-client, but not browsers). I assume it's all obtainable from the Win32 API, but I'd hate to re-invent the wheel if it's already been done. Thanks. Hi Andy, Please see this bcl team blog post which contains a download link with the sample time zone code you requested: I hope this helps. Thanks, Josh Thanks for chosing a better name than System.TimeZone2. There was a lot of debate over the original name; I'm glad that the BCL team decided to go with a better name. Looking forward to that post on the new DateTime structures :-) Anders, Thanks for your comments on the class change. I like the new name much better as well. :-) Good to see some work being done on the TimeZone stuff. Though, I would like to add my vote to having DateTime internals being in UTC. Obviously, for historical reasons (past naivety/arrogance), this is going to be a problem. In which case I think there may be case for a new type/class branch, for use by any new, observant code. Anyway, as I'm feeling a little Roger Ramjety [1] this morning interesting, so: I find your use of the term "Registry Hive", um, interesting... [1] Roger Ramjet, the old cartoon series - protein pill - nit-pick... :) Josh, thanks for the link to the .NET 2.0 code, excellent! For the existing .NET 2.0 sample: On a multi-lingual app which may run on any localized version of Windows XP/Windows Server 2003 (US, Japanese, French, etc.), what value do we use to uniquely identify a timezone ? The Registry Key, DisplayName, StandardName, Index, or something else, and will that be the same on Vista ? Does the DisplayName vary depending on the language of the O/S ? If so, I assume we should display the DisplayName, but store the StandardName behind the scenes - is that correct ? Another issue is mapping windows timezones to Java timezones (i.e. Olson names). I'll need to build that myself in .NET 2.0, but could .NET 3.5 provide a GetOlsonName() method ? From other blog posts discussing TimeZoneInfo in .NET 3.5, it seems only the Registry Key is constant across different localized versions of Windows, so we need to use that as the time zone id. On another point, it seems the time zone names in Windows are just wrong! Has the whole planet missed this ? Windows says I'm in GMT, but that's only true for 6 months of the year. Right now I'm in British Summer Time (BST), but not according to time zone names in control-panel, which still say "(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London", when I'm actually +01:00 due to daylight saving. I don't expect this to change, but the Olson names do seem more sensible, e.g. Europe/London. Then again, Cities do get renamed! I wrote the following tz database support (purely in C#) in the PublicDomain package for exactly the points chronos and Andy raise above: The TzDateTime class wraps the DateTime class (because I couldn't extend it), as well as exposing the TimeZone, which can be serialized as a string across any wire. The TzTimeZone class then represents all current and historical data extracted from the tz database. Finally, the TzDatabase class reads the tz database into logical form, emits C#, which is then placed into a static initializer in the PublicDomain.dll. This means that the only way to update a tz database change is to send out a new version of PublicDomain.dll. I am open to criticism on this strategy, but I wanted to avoid having to read resources files from the DLL or from the filesystem to lessen the impact of consumers of PublicDomain not to require FileIOPermission. By the way, all of this support is very experimental, and I would be very excited for comments, questions, criticisms, or help to code more of it! Thanks and I am glad that Microsoft continues to work on the current time zone support. Kevin Grigorenko
http://blogs.msdn.com/b/bclteam/archive/2007/06/07/exploring-windows-time-zones-with-system-timezoneinfo-josh-free.aspx
CC-MAIN-2015-06
refinedweb
2,052
55.95
Arrow for Better Date and Time in Python Manipulating date and time is a common scenario in any programming language. Without the help of a handy library, it can become a tedious job requiring sufficient effort. Let's have a look at the Arrow library, which is heavily inspired by popularly used Python libraries Moment.js and Requests. Arrow provides a friendly approach for handling date and time manipulation, creation, etc. From the official documentation: Arrow is a Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. It implements and updates the datetime type, plugging gaps in functionality, and provides an intelligent module API that supports many common creation scenarios. Getting Started With Arrow To get started with the Arrow library, you need to have Python installed on your system. Also make sure you have pip, Python package manager, installed in your environment. Now install Arrow using pip. pip install arrow You'll learn how to use Arrow in your web application development project for date and time manipulation, creation, etc. So let's start by creating a web application using Python Flask. Using pip, install Python Flask, if it's not already installed. pip install Flask Create a file called app.py which would be the Python application file. Add the following code to app.py: from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Welcome to Arrow Library" if __name__ == '__main__': app.run() Save the above changes and run the application using python app.py, and you should have the application running on. Local Time to UTC Time & Vice Versa One of the most common scenarios that you face in a web application development project is fetching the local time, converting the local time to UTC (Coordinated Universal Time) time and then converting UTC time to local time for display in a web application based on time zone. To use Arrow in your Python Flask project, you need to import the library in app.py. import arrow Once it's imported, you can straight away use the arrow object for date and time manipulation and creation. Let's create a route and method to fetch the local time. Add a route called getLocalTime and its corresponding method. Arrow provides a method called now to get the current local time. Use the now method to get the local time, and to return the date you need to convert it into ISO format. Here is how the code looks: @app.route("/getLocalTime") def getLocalTime(): local = arrow.now() return local.isoformat() Save the above changes and restart the server. Point your browser to and you should be able to view the local time. Normally, you tend to save the date and time in UTC format in databases and display the local time by converting the UTC time to local time. So let's have a look at how to convert the local time to UTC time for database storage. Create a route and method called getCurrentUtcTime. In order to get the current UTC time, arrow provides a method called utcnow. You can use it to get the current UTC time as shown: @app.route("/getCurrentUtcTime") def getCurrentUtcTime(): utc = arrow.utcnow() return utc.isoformat() The above method gets the current UTC time. If you already have a date and time for which you want to get the UTC, arrow provides a to method for doing this. Using the to method, you need to provide the time zone to which you need the date and time to be converted. So, here is how you can convert the local time to UTC: @app.route("/getUtcTime") def getUtcTime(): local = arrow.now() utc = local.to('utc') return utc.isoformat() When you save the date and time in the database, you save it as a timestamp. To get the UTC timestamp, you need to call the .timestamp attribute of the object. arrow.now().timestamp You cannot show the UTC timestamp when displaying data to the client side. You need to convert the UTC timestamp to local time. In order to do that, you first need to create the arrow object using the arrow.get method. Then you can use the arrow.to method to convert the UTC time to local time. Here is how the code looks: @app.route("/convertUtcToLocal") def convertUtcToLocal(): local = arrow.now() utcTimeStamp = local.to('utc').timestamp localDateObj = arrow.get(utcTimeStamp).to('local') return localDateObj.isoformat() Save the above changes and restart the server. Point your browser to and you should be able to view local time retrieved by converting the UTC timestamp to local time. Manipulating Date & Time Most of the time, it's required to manipulate the date and time by adding or removing a few hours, minutes, etc. to the datetime object. Arrow provides two methods called replace and shift for manipulating the datetime object. Let's say that you have an arrow datetime object. Now you want to replace a few things in the datetime object. You want to alter the minute and second of the datetime. >>> localDateTime = arrow.now() >>> localDateTime <Arrow [2017-09-29T07:39:29.237652+05:30]> To replace the minute and second of the localDateTime, you can use the replace method provided by the arrow library. Here is how the syntax looks: >>> localDateTime.replace(minute = 01,second = 01) <Arrow [2017-09-29T07:01:01.237652+05:30]> If you want to increment the datetime by a certain parameter like day, hour, week, etc., you can use the shift method. All you need to do is provide the parameter using which you need to shift the datetime. Let's say you need to increment the datetime by one day. The code would be like this: >>> localDateTime = arrow.now() >>> localDateTime <Arrow [2017-09-29T08:03:57.806785+05:30]> >>> localDateTime.shift(days = +1) <Arrow [2017-09-30T08:03:57.806785+05:30]> To decrement the datetime by two days, the code would be like: >>> localDateTime.shift(days = -2) <Arrow [2017-09-27T08:03:57.806785+05:30]> Formatting the Date Using Arrow In order to format the datetime as per your custom format, you can use the format method provided by arrow. For example, to format datetime to YYYY-MM-DD format, you need to use the following code: >>> localDateTime = arrow.now() >>> localDateTime <Arrow [2017-09-29T08:32:28.309863+05:30]> >>> localDateTime.format('YYYY-MM-DD') u'2017-09-29' Similarly, to format datetime to YYYY-MM-DD HH:mm:ss format, you need to use the following code: >>> localDateTime <Arrow [2017-09-29T08:32:28.309863+05:30]> >>> localDateTime.format('YYYY-MM-DD HH:mm:ss') u'2017-09-29 08:32:28' Human-Friendly DateTime Representation Arrow provides a method called humanize to represent the datetime in a human-friendly representation. Most of the time, the user needs to know how much time it has been since a particular time. You can use the humanize method to show the user how much time it has been since now. Here is some example code: >>> currentDate = arrow.now() >>> currentDate <Arrow [2017-09-29T22:05:26.940228+05:30]> >>> currentDate.humanize() u'just now' As seen in the above code, if you use humanize to represent how much time it has been since the current datetime, it would show the above result. Now let's take a look at a prior date. >>> earlierDate = arrow.now().shift(days=-3) >>> earlierDate <Arrow [2017-09-26T22:07:39.610546+05:30]> >>> earlierDate.humanize() u'3 days ago' As seen in the above code, you just used the humanize method with an earlier date, and it shows the relative number of days with respective to the current date. You can also use humanize to show the relative number of days between two dates. For example: >>> laterDate = arrow.now().shift(days=+3) >>> laterDate <Arrow [2017-10-02T22:10:58.505234+05:30]> >>> earlierDate = arrow.now().shift(days=-3) >>> earlierDate <Arrow [2017-09-26T22:11:11.927570+05:30]> >>> earlierDate.humanize(laterDate) u'5 days ago' As seen in the above example, you created a later date and an earlier date by shifting the number of days. Then you checked the relative number of days from earlierDate to laterDate using the humanize method, which printed the above message. Converting to a Different Time Zone Arrow provides a convert method to convert the local time to a preferred time zone. For example to convert the local time to UTC time, you can use the following command: >>> arrow.now().to('utc') <Arrow [2017-09-30T16:58:45.630252+00:00]> To convert the UTC time back to the local time zone, you can use the following code: >>> utcTime = arrow.now().to('utc') >>> utcTime <Arrow [2017-09-30T17:01:30.673791+00:00]> >>> utcTime.to('local') <Arrow [2017-09-30T22:31:30.673791+05:30]> To convert the UTC time to any specific time zone, you can specify the time zone and you'll get the time from that particular time zone. For example: >>> utcTime.to('America/New_York') <Arrow [2017-09-30T13:01:30.673791-04:00]> In the above code, you specified the UTC time to be converted to the America/New_York time zone, and similarly you can provide any time zone that you want the UTC to be converted to. Wrapping It Up In this tutorial, you saw how to use Arrow, a Python library for date and time manipulation, creation and formatting. From a developer point of view, the Arrow library seems to be a complete fit for date and time manipulations when used in a Python project. Additionally, don’t hesitate to see what we have available for sale and for study in Envato Market, and don't hesitate to ask any questions and provide your valuable feedback using the feed below. Do you have any prior experience using the Arrow library? What is your point of view? Did you face any issues while using the library? Do let us know your thoughts and suggestions in the comments below. Source: Tuts Plus
http://designncode.in/arrow-for-better-date-and-time-in-python/
CC-MAIN-2018-13
refinedweb
1,682
67.45
(V.2.1, undocumented prior to V.2.1.3) IPCName, defaulting to FIREBIRD since V.2.0, is the kernel namespace where the XNET instance for direct local connection on Windows is created. On Vista and some other Windows platforms, it was usually necessary to edit this parameter to add the prefix “Global\” in order to ensure that the local client running under a restricted account would have the authority to create this namespace. A change in V.2.1 made it so that the connection routine would apply the prefix to the default IpcName unconditionally if the user's first attempt failed due to restricted permissions.
http://www.firebirdsql.org/file/documentation/release_notes/html/rnfb21x-fbconf-ipcname.html
CC-MAIN-2018-39
refinedweb
108
54.93
A checkbox list in org-mode with one value Posted October 05, 2015 at 07:15 PM | categories: emacs, orgmode | tags: | View Comments Updated December 09, 2016 at 03:10 PM A while ago I had a need for a checklist in org-mode where only one value would be checked at a time. Like a radio button in a browser form. That isn't as far as I know a feature yet, but it was not hard to achieve thanks to the org-element api. My simple idea is to make a function that will be added to the org-checkbox-statistics-hook. The function will uncheck all the boxes, and recheck the one you just clicked with a hybrid of manipulating the cursor and inserting characters with org-element code. We will use an attribute on the checklist to indicate it is a "radio" list. This seems like a feature that might already exist, but I couldn't find it. Here is the code we run. First, we make sure we are on a plain list that has an attr_org property of ":radio", that way this won't apply to all lists, just the radio lists. Then, we loop through each element in the structure, and if it is checked, we replace [X] with [ ]. Then, we reinsert the X and delete a space, which puts [X] where we originally clicked, or used C-c C-c. Finally, we add it to the hook, so it only gets run when a checkbox is changed via clicking with org-mouse, or C-c C-c. Of course, this doesn't work if you type X in the box. (require 'dash) (defun check-hook-fn () (when (-contains? (org-element-property :attr_org (org-element-property :parent (org-element-context))) ":radio") (save-excursion (loop for el in (org-element-property :structure (org-element-context)) do (goto-char (car el)) (when (re-search-forward "\\[X\\]" (line-end-position) t) (replace-match "[ ]")))) (forward-char) (insert "X") (delete-char 1))) (add-hook 'org-checkbox-statistics-hook 'check-hook-fn) Here is a regular checklist. You can check as many as you want. [X]one [X]two [ ]three Now, here is a radio checklist. Only one item at a time can be checked. Nice! [ ]a [ ]b [X]c It is worth noting here that if we put a name on the list, it becomes an addressable data source. First we need this convenient function to get the data associated with a named list. (defun org-get-plain-list (name) "Get the org-element representation of a plain-list with NAME." (catch 'found (org-element-map (org-element-parse-buffer) 'plain-list (lambda (plain-list) (when (string= name (org-element-property :name plain-list)) (throw 'found plain-list)))))) org-get-plain-list Now, let's use that to get the value of the checked item in the "test" list. We define the item as everything after the [X] and get it from a regular expression match. (defun get-radio-list-value (list-name) "Return the value of the checked item in a radio list." (save-excursion (loop for el in (org-element-property :structure (org-get-plain-list list-name)) if (string= (nth 4 el) "[X]") return (progn (let ((item (buffer-substring (car el) (car (last el))))) (string-match "\\[X\\]\\(.*\\)$" item) (match-string 1 item)))))) (get-radio-list-value "test") c Perfect. This has lots of potential applications. Data collection and quizzes come to mind, with associated ability to autograde and aggregate the data! Copyright (C) 2016 by John Kitchin. See the License for information about copying. Org-mode version = 9.0
http://kitchingroup.cheme.cmu.edu/blog/2015/10/05/A-checkbox-list-in-org-mode-with-one-value/
CC-MAIN-2019-26
refinedweb
604
71.44
I of the available options is Elm, the brainchild of former Googler Evan Czaplicki. What do you get in the box? - Pure functional programming - Type inference (like everything these days) - Functional-Reactive-Programming-style time-varying values (“signals”) - a REPL - elm-reactor, which compiles, runs and serves your code when it is saved by your editor - a neat DOM creation language. I never understand why people want to use HTML-like syntax as in (say) JSP; it’s horrible! - a nice package installer What, after a lot of shaking, doesn’t fall out of the box? - Typeclasses - Any IDE that can do refactoring (many can do syntax highlighting) OK, we can live with that, let’s go! You can see my work on github. It renders a list of objects that can be reordered by drag and drop. With a bit more effort if could become a proper package, if anyone’s interested. General impressions The Elm development experience is very nice; the lack of typeclasses means that the standard unreadable Haskell errors (the Glasgow Haskell Compiler seems to think that nearly every error is caused by a missing typeclass) are nowhere to be seen. In general the error messages from the elm compiler are extremely helpful, but of course type inference gives you nasty problems where it gives some expression a type which you did not mean it to have and then it breaks somewhere else; this seems inevitable. Pure functional programming gives you the normal nice properties that, because side effects and global variables are banned, you know exactly what each function’s inputs and outputs are, which makes your code easy to reason about and refactor. The core libraries are pretty small; lots of functions that a Haskeller might expect to be there are not (such as const and splitAt). Writing these or finding them in another package is fairly simple, but at the cost of polluting your code with lots of little functions that don’t get reused because no-one knows where to find them or what you have called them. The lack of typeclasses I felt in two places: Firstly, there are many packages that expose an andThen function. In each case this is where Haskell would have made the appropriate type a Monad, then we would be using monadic-do notation to make the code look simpler. With Elm we have to use andThen (admittedly a better name than Haskell’s >>=) by hand, which looks confusing and nasty. On the other hand, if you are unsure about Monads, you can use andThen happily until eventually you feel the need for better notation- this could be the “Aha!” moment you need to understand Monads! The second place I really felt the need for typeclasses was in testing, more of which later. Functional Reactive Programming? You may have read about Elm’s interesting concept of “signals“, which are time-varying functions. These are miles away from Conal Elliott-style Behaviours and Events, being just piecewise-constant functions of time, but this is nice because the simplicity makes it clear what is going on and how it should be used, at the expense of some expressive power. But before you go diving into Elm signals, know this: you just don’t need to know about signals unless you are going to be hacking on the deepest of Elm’s libraries. Although the set of functions that you can use with signals (merges, maps, filters, fold-over-past-values and so on) seems at first to cover everything you need, eventually you’ll realise they permit only one sensible architecture: funnel all signals you are ever going to need into a single signal and update your model with a single function that does everything. This is encapsulated with Html.App.program and friends, so you should just use those and forget about using signals directly. But this leads to a worry: If everything needs to be updated in one big function, how can I make reusable components? Is function composition going to be enough? Reusability The Elm architecture ties together the following four functions which you must supply to Html.App.program: - An initial Model for your App - A function for converting your Model to a fresh virtual HTML View every time something changes (Elm will diff this against the current view to perform minimal updates on your behalf) - A function for updating your Model according to messages it has received (either from some JavaScript you are running or from onClicks and similar in your View), and producing commands to send to JavaScript (HTTP requests, for example) - A function for Subscribing to events from JavaScript (mouse movements, for example) based on the state of your Model So any component is a four-tuple (or record) of initial state, view function, update function and subscriptions function. Actually I found that there is potentially one more. My draglist does not only need to know these four things about the elements to be dragged, but also what command needs to be sent when a reordering has happened. Composing components like this is actually very pleasant. Here is the code that puts components consisting of a label, a number and + and – buttons to change the number into a draglist: import Draglist exposing (init, view, update, subscriptions) import Html.App as App import Platform.Sub as Sub import Platform.Cmd as Cmd import Html exposing (span, button) import Html.Events exposing (onClick) import List main = App.program { init = init <| List.map initItem ["one", "two", "three"] , view = view viewItem , update = update updateItem repositionCommand , subscriptions = subscriptions (\_ -> Sub.none) } type alias ItemModel = { text : String , number : Int } type ItemMsg = Up | Down initItem text = ItemModel text 0 viewItem { text, number } = span [] [ Html.text text , button [onClick Down] [Html.text "-"] , Html.text <| toString number , button [onClick Up] [Html.text "+"] ] updateItem msg model = ( case msg of Up -> {model| number = model.number + 1} Down -> {model| number = model.number - 1} , Cmd.none ) repositionCommand from to newList = Cmd.none -- change this to send an HTTP Post or whatever It’s a bit annoying to have to specify each of these four things instead of having generic Component types that can be combined in a standard way, but we can see here how Draglist’s init function takes a list of models and update takes an update function as well as a command-producing function with an odd type. These are specific to this case, so it would seem foolish to try to genericise this. It is easy, though, to see how we could write some function that takes a couple of components and puts them together in a div, something like: par a b = { init = let (ma, cmdA) = a.init (mb, cmdB) = b.init in ((ma, mb), Program.Cmd.batch [ Program.Cmd.map Either.Left cmdA , Program.Cmd.map Either.Right cmdB ]) , view = \(ma, mb) -> div [] [ Html.App.map Either.Left (a.view ma) , Html.App.map Either.Right (b.view mb) ] , update = \msg (ma, mb) -> case msg of Left msgA -> let (ma', outMsg) = a.update msgA ma in ((ma',mb), Program.Cmd.map Either.Left outMsg) Right msgB -> let (mb', outMsg) = b.update msgB mb in ((ma,mb'), Program.Cmd.map Either.Right outMsg) , subscriptions = \(ma,mb) -> Sub.batch [ Program.Sub.map Either.Left (a.subscriptions ma) , Program.Sub.map Either.Right (b.subscriptions mb) ] } This works, but it is perhaps not all that useful because it gives no way for the two components thus joined to interact with each other. You can imagine re-writing this every time you want to join two components together, each time changing the update function to notice if one of the parts has been changed in a way that is interesting to the other part and taking appropriate action. Not nice. Although I did not try this, if I were to write a big application in Elm I would worry that a seemingly trivial move of a component from one part of the page to another could trigger a distressing amount of tedious re-work. Some nice publish and subscribe support could be really nice to avoid this. I’m not at all sure how this could be made idomatic in Elm; perhaps the easiest way might be to use a little bit of JavaScript to receive commands and route them back to Elm via subscriptions. Testing Unit Tests Of course I love Haskell QuickCheck. Why test that your function behaves correctly for inputs [2,3] and Just 5 when you could test that it behaves correctly for any list and any maybe? I love the fact that, in Haskell, you can write prop_reversingAReverseIsId xs = xs == reverse (reverse xs) And that’s enough to test this identity for a variety of inputs. Being so concise relies on typeclasses, and Elm does not have typeclasses. The equivalent Elm looks like this: fuzz2 (list int) "reversing a reverse is id" <| \xs -> Expect.equal (reverse (reverse xs)) xs Originally, my love for QuickCheck led me to the elm-check package, which I would urge you to avoid. The equivalent in elm-check is: claim "reversing a reverse is id" `that` (\xs -> reverse (reverse xs)) `is` (\xs -> xs) `for` list int How anyone can bear to write that is beyond me. elm-check does not play well with Elm’s standard testing infrastructure either, so just use the fuzzN functions from the Fuzz module of the standard elm-test package. Testing the UI So we can easily and relatively nicely test our functional code. But what about our components and apps? Sadly, the story here is not so great. Notice that the signatures for init, view, update and subscriptions functions all have one of Cmd, Html or Sub in their return values. This means that to test these functions properly requires being able to look inside these return values, however all we have is testing for equality. For Cmd and Sub testing for equality will usually suffice, so init, update and subscriptions functions can probably be tested adequately, but this will usually not be the case for view! We need the ability to test that a particular element is present, or has a particular attribute, or contains certain text. This leaves a gaping hole in testing. Selenium is a possibility, but that’s bad enough when you have control of the order in which elements and attributes are added to and removed from the DOM; with Elm there is a virtual-DOM differ doing this work for us, so who knows what Selenium will see as intermediate states? Creating your own transparent HTML structure which is then converted into Elm’s Html is a possible way round this, but so ugly. Debugging Although static typing means the compiler catches many errors, it is still easy to get Elm stuck in an infinite loop that chews through all available memory then crashes. The stack trace of an Elm out-of-memory crash just shows that the crash happened in Elm, and as Elm compiler does not produce readable JavaScript, Elm is essentially not step-debuggable. This is annoying, but not fatal if you run your code regularly. So, is Elm ready for production? Ease of Programming I have no doubt that Elm is a great introduction to Functional Programming. I would highly recommend it for use in the classroom, and junior professional programmers of reasonable skill will have little trouble picking it up. Your intermediate “why can’t we just use Language X everywhere” types are likely to be more resistant, but their opinions don’t count. The fact that certain things are missing compared to Haskell, such as do-notation, monads and typeclasses, actually helps its ease-of-use. Elm has a well-thought-out, practical feel. Scalability So many languages and frameworks make easy things easier and hard things harder. Elm is not quite one of these. As you scale up, you’ll benefit from pure functions and the testability and composability this provides. Elm is also mercifully short of ‘magic’; all interactions are clear in your code. The downside is that you’ll end up with more and more boilerplate-like routing code that looks ugly and will need to be changed whenever the structure of your page changes (however useful CSS is for separating look and content, HTML defines the structure of both and Elm code must reflect this structure). I would also be worried, if making a large single-page application (that is, an application is served up from a single request which contains many apparent “pages” of content), about all those signals being routed through the same signal. Would it not get very slow? I don’t know. Testing The most annoying aspect of Elm is that we cannot (without serious pain) escape Selenium tests, when Elm seems so close to allowing us to do so. However, the tests that you can do in Elm’s are as good as any other, but really better because your functions are pure so tests will not be dependent on the environment. Mixability with JavaScript I have not tested this, but from what I read this seems pretty good. Conclusion I am sure that Elm can work in production; it seems solid, easy to learn and lacking in surprises. The cases in which it is likely to excel are for smallish components that have complicated internal interactions, such as diagram builders, graphical schedule makers or games. In these applications Elm’s simplicity, conciseness and ease of development will shine, while avoiding the problems of scalability and difficulty of testing the HTML. It would probably disappoint as the sole client-side language for a large application. 2 Comments And the next thing to try is Kotlin in the browser… 🙂 I’ve just been trying to get Kotlin->JavaScript to work. I had some limited success (the command-line tools do basically work) but my conclusion is that, at the moment, Kotlin->JavaScript is only for people who need it so badly they are either prepared to pour days into getting it to work or who are prepared to work without proper tooling. I totally failed to get IntelliJ’s kotlin plugin to understand my source and its dependencies. I could not work out how to get gradle to put the JS libraries I was using somewhere I could get to them. Without a working build tool and IDE, this is already fringy stuff. The documentation for Kotlin/JavaScript is not usable. So you want to know how to interoperate with JavaScript? No problem! Just use nativeinvoke! The documentation for that says: Really? In what universe does that make a gram of sense? Getting anything more than hello world to work in Kotlin/JavaScript is an exercise in frustration.
https://tech.labs.oliverwyman.com/blog/2016/09/22/elm-any-good/
CC-MAIN-2020-05
refinedweb
2,462
60.14
Hi All, I'm working on a simple listview structure. My requirement is basically to show elements in list. I want HasUnevenRows=true because few elements are single lined & few are multi lined. Here is the code snippet I'm using. <ListView ItemsSource="{Binding FireOrExplosionList}" HasUnevenRows="true" Grid. <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label Text="{Binding Path=.}" TextColor="{StaticResource TextColor}" /> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> But here the problem is that I'm getting space in the list which is not required. You can see the below image where the space in marked in a rectangle. Now If I'm changing the code to the following & removing the HasUnevenRows property then the space is not coming but rows in listview are not looking good as they are taking fixed height. <ListView ItemsSource="{Binding FireOrExplosionList}" RowHeight="25" Grid. <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label Text="{Binding Path=.}" TextColor="{StaticResource TextColor}" /> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> So my requirement is to enable HasUnevenRows property but get rid of the unwanted space. Please provide a solution for this. Thanks, Priyabrata @PriyabrataDash: (and at all other readers of this thread) Have you found a solution for this problem? I show some (bound) ListViews on a page (without XAML). The ListViews are added on a StackLayout, the data (text) have variable length. So... according to the variable length, I set HasUnevenRows to true (what works). The problem is, that the whole height of the ListView seems to be calculated wrong in XF (or in the StackLayout). Like in the example of Priyabrata, the contend is showed correct in the ListView, but a lot of unneeded space is added (and showed) at the end of the ListView. I have tried everything (LayoutOption's) that came to my mind for the ListView and for the StackLayout - nothing works. Sure.. I can set a RowHight and a HighRequest for the ListView, but I don't want to do it, as it should adjust the Height automatically also e.g. on a tablet with more space (so that an item only takes 1 Line instead if 3 Lines like on a Phone). I use HasUnevenRows also on other ListViews where it works, but on these pages, the ListView takes more space as the whole page. Maybe this is a bug that only occurs, if the ListView (Height) is smaller then the Page (Height)? Can someone help me...? Thanks Is this happening when you use ScrollViewinside of a StackLayout? If so the ScrollViewtakes the complete space of the StackLayoutas far as I can say that. And the calculation for the height is buggy or something. It should work if you set the height of the surrounding StackLayout. Something like this should be ok: Oh man, you don't know how long I've fiddled with this and never found a solution... It happens when I use a Grid layout for my viewcell, but disappears when I use nested StackLayouts, but that's too expensive. It also happened in other cases, one time I spent so much time trying to fix it only to discover it's because I render an image which is too big and it gets scaled down to fit, even though it gets scaled down anyway, it still causes the row to have extra space... Bottom line: Using Xamarin.Forms cross platform viewcells is: @RaphaelSchindler: Thanks for your reply But... unfortunately it's not as easy.... Short code-snippets: The page is a registration page with various controls. As the page has to be scrolled, the content is set to ScrollView. ) In the example-code, a ListView LV_CB_Interessen is added to the ErfassenStack (SL). The LV_CB_Interessen then is bound to a List with some "selection-entrys" whereby a DataTemplate is used (check-image to show, if an item is selected or not and text to the text) => This is in fact a "MultiSelect-ListView". Problem: I have to care, that the whole ListViews (all contained entry's) are showed in the ScrollView (as Scrolling of a ListView in a ScrollView don't work since a few versions in Android If I set HasUnEvenRows to true and don't set a HighRequest to the ListView (what would be the/my target), the rows are showed/calculated correct, but the whole ListView takes way to much space (a lot of empty space after the ListView). If I set a HighRequest, it is overtaked. But then, I have to set it depending on the platform and also the device (phone / tablet) as on a iPhone, more space is needed to show all entry's as on a Android-phone whereby on a Tablet in landscape orientation less space is needed (as the entry is showed in just one line). So the (my) base-problem is, that the HeighRequest of the LV is not calculated correct automatically (with HasUnevenRows = true). Hope this explain my problem Can you show me a screenshot because I have no idea what you are doing^^ @RaphaelSchindle: Yes of course See .pdf @RaphaelSchindler: I think, your username in my last posting have cut the last char... Do you have any idea..? Else, I have - at least for now - to implement the (bad) workaround (set a fix HeightRequest to the LV's for each platform) @FredyWenger Ah dang you're using Well, I don't know if that helps but try to nest the ListView()inside of ScrollView(). Now I get it ListViewinside of a StackLayoutand set the Heightof the StackLayoutto a value that is comfortable for you. Or maybe you don't have to explicitly set the Height. Those redrawing and calculating of dynamic things like ListViewor ScrollViewis really not perferct right now. @RaphaelSchindler: As you can see in my code-snipped, the LV already is in a StackLayout... But I have tried to add one more SL.. same behavior... So... think, that this is a XF bug (Height(Request) of ListView with HasUnEvenRows is calculated wrong) and implement now my (bad!) workaround (as I don't have the time to wait...). Nevertheless... thanks for our try to help... And... If someone else have a solution... please post here Please make your voice heard on my bugzilla bug. I asked them to revisit the viewcell height. It seems like a one time thing (so it uses whatever height is in the viecell, as opposed to being able to calculate it per list view item) and in any case I want to have a delegate so I can sue it with the fast grid cell techniques I've published. @GeorgeCook: Added a comment... To All, I communicated with Xamarin support regarding this & seems like this is a known issue to them. This issue was supposed to be addressed in Release 1.4, but still it's pending. What we can do for this is raise our voice count more in BugZilla. @PriyabrataDash : Thanks for your posting here. Can you post a link to the bug in BugZilla? Any update on this? All issues related to ListView are fixed for iOS & Android platform in the latest build as per the statements by Xamarin. Nothing specific they mentioned about XForms though. @BrunoPasquini, could you please check if the problem still persists in latest XForms build. @FredyWenger : I couldn't able to find the BugZilla issue for this one.I'm searching more & if possible you also search this one by keywords in BugZilla. Thanks. @PriyabrataDash: I don't have filled a additional bug, but have added a comment to the bug of George here: But I had a look at my code (as I don't have remembered me, what I have done to solve the problem) I still have the ugly workaround in place: => This is ugly, but works Sorry, But I could not stop myself from laughing after reading this work around. I must say you are clever & good in maths. If possible share the code. Thanks for sharing your fix for this. @PriyabrataDash: Sorry, But I could not stop myself from laughing after reading that you have asked for posting the code => This is no solution, only a workaround for exactly my problem As I wrote in my old posting, I have the problem only on specific page with some specific ListViews that are smaller as the Page-Height and contains a special ViewCell (text + check-icon). I use ListViews on various other pages (with dynamic Input) without problems. On the problem-page, I use ListViews as "Single-Checkbox" (tap = select / unselect), "Radiobuttons" (tap select the tapped entry and unselect all other entries), and "Multiselect-ListViews/Checkboxes" (select n out from n). Therefore, I know exactly what I have to show (static items). But... O.K.... Example: "calculate" Height: Example: Fix value for ListView ("LV_CB_AlterDarfAngezeigtWerden"): Hello All, Did any one get the proper solution? @FredyWenger : what about you? @Neelam: . I have redesigned my app completely, of cause the many problems that occurs, if you want to use a ListView in a ScrollView I ended up to add PopUp's for any ListView, I have to show from a ScrollView (if you show the ListView on a PopUp, you don't have this problem). You can find the details here: And.. you can find more links to documentations, if you click my profile... Hope this helps @FredyWenger I am not finding any code for PopUp's for any ListView. @Neelam: The information's are on the page1 of the mentioned thread, direct link to page1. You have to click the attached .pdf to see the informations Thanks @FredyWenger, I followed your advice with the tweak. I also had to make a bit of an ugly hack to make the list shrink a bit. My ListView has an x:Name, and I'm putting the HeightRequest within PropertyChanged Event, and the event setting within the ContentPage constructor. I noticed the event was being called multiple times with the Height Property and the Y Property as well, so I supposed it would be a good idea to hack and slash there. Hope this is helpful as well. @FredyWenger @PabloBiagioli Uneven rows and scroll view is still broken. It cannot calculate height correctly and ScrollTo does not work properly because of it. Has anyone made a more elegant workaround when using ScrollTo? Thanks. But this will only work if you dont have unevenrows how can we make it working when we have uneven rows It's 2017 now, and the ListView with HasUnevenRows set to True still a problem for iOS I also faced to this issue, A solution is, we have to set the Height of the list view according to the height of number of rows manually in code behind. Below link describes how I did fix it in the normal way... And also I have tried to calculate the height using MVVM when changing the Item source of the List View. It also became successful. And I wrote an article that how to do it. and the article consists of my code. Can't believe this is still such an issue!!! Anyway, using @BuddhimaKudagama 's suggestion but with binding and strictly MVVM. While that solution claims to be MVVM, i'd argue that it's a little fringe since we're defining observable collections in code behind. But, more than that, i prefer to use binding and keep everything clean in an easy to read viewModel class which provides 99% of what the view needs to simply bind to. This is what I did: ViewModel for my specific page: In your listview, simply bind to the new property. Another solution might be to write a behavior to calculate row height and thus also the height of the ListView. Like this: public class ListViewAutoSizeBehavior : Behavior { ListView _ListView; ITemplatedItemsView Cells => _ListView; private readonly int _extraPaddingPerRow;
https://forums.xamarin.com/discussion/38028/listview-space-issue-when-hasunevenrows-true-need-a-solution
CC-MAIN-2020-05
refinedweb
1,963
71.14
Introduction When I wrote up my post about the ways of interacting with Excel from .Net I listed a number of .Net components that can be used for reading and writing native Excel files; I left you with the hard task of picking one for yourself. Today I'm going to write you a helping hand. Over the last couple of days I've been doing some bug fixing on a little utility we have that analyses an Excel spreadsheet and creates named ranges for cells that are formatted in particular styles. The biggest bug I wanted to fix was terrible performance. When I first looked at the application a couple of months ago the performance was unbelievable: never mind making a cup of coffee whilst it did its stuff; we could go home and get a good nights kip before it delivered the results. It didn't take long to pin most of the blame for that on Excel COM Interop: each call to a property or method on a COM object has a significant overhead, and we were querying the Style property of each cell in a 120Mb workbook! Hence my interest in .Net components for loading Excel files: I had a license to Syncfusion XlsIO available, and by switching the code to use that instead of Excel Automation through COM, the time to query cell styles dropped to almost nothing. However, XlsIO has some performance issues of its own (more on these in a moment), and it still could take up to an hour for the whole operation to complete. So I decided to have a look at the other components in the market place. In the hope that there will be at least one other person on the web who finds this useful, I'm recording my first impressions of several of these Excel IO components. I'm not claiming that these are objective reviews: your kilometreage will almost certainly vary. Syncfusion XlsIO I've been using XlsIO on and off for a couple of years. Mostly, it has helped me get the job done; several times it has been the cause of temporary localised baldness. My thoughts: - It has an API that covers the vast majority of Excel features - The API is mostly consistent with the Excel COM API, though there are several exceptions to catch you out: Workbooks.Add vs Worksheets.Create being one trivial example. - There are some highly non-trivial differences from the Excel COM API. For example, the Excel Range object has Rows and Columns properties that return references to collections; the XlsIO Range object has properties with the same names, but each return arrays of Range objects and allocate a new array every time you access the property. This is a huge performance pitfall for the unwary. - The Range model is different to Excel's in that in XlsIO, a Range can only contain one Rectangular region, whereas excel allows Ranges to be created that are the union of many rectangular regions. - As I hinted in the introduction, there are other performance problems. In my large (120Mb) workbook, deleting a single row could take up 20 seconds. Deleting Named ranges was another costly operation. Excel demonstrates that these operations don't have to take that long. - The documentation is sparse, to put it politely, and the class reference often doesn't state more than the obvious. "ICombinedRange: represents a Combined Range" being one typical example. I have however had assurances from Syncfusion that they are working to improve this. XLSReadWrite I started my exploration of other components by downloading and installing XLSReadWrite. Then uninstalling it again. Call me a CLR snob, but I didn't like the thought of working with a component that is clearly designed for Delphi. This showed because the API commits two capital crimes: Every type in is prefixed with a T; and most of the namespaces contain just one type. The other point to note about XLSReadWrite is that the "shape" of the API is nothing like Excel's so any code you have using COM Interop would need a lot of reworking to use this component. ActiveXLS I'm afraid that CLR snobbishness also put me off ActiveXLS. The ActiveXLS team produce Spreadsheet components for both .Net and Java, and it appears that the .Net version is a straight port of the Java version: it is the paired "get_" and "set_" methods, and the absence of Properties that give the game away. Surely an organisation selling a component "optimised for Visual Studio" (as the home page claims) should make .Net developers feel at home and at least use Pascal casing for methods, rather than camel casing (which everybody knows should only be used for method parameters)? The other thing that struck me as odd was that in the ActiveXLS forums (which have been active since 2006) there have only been about 200 posts. Is it that they have an intuitive API with superb documentation: or perhaps a very small user-base? Maybe I'm just cynical. SpreadsheetGear SpreadsheetGear was the component I finally settled on. This appears to be far and away the most mature (though correspondingly the most expensive) of the components that I looked at. Though I didn't try that part of it, this component also offers Windows Forms controls for editing spreadsheets. My impressions: - The Object model is very similar to Excel's, and easy to learn. It didn't take me long to port my code from XlsIO (which is also similar to Excel). - One big inconsistency is that properties giving access to cells use a 0-based index system rather than the 1-based system in Excel. - The Range model is (as far as I can tell) identical to Excel's. Intersect and Union methods are provided for Ranges and seem to work as I'd expect. - There's a surprising omission in the API in the current version (2007): no support for Styles. If you need style support you'll need to get the 2008 version (currently in beta). - All the non-public code is obfuscated. This can cause problems when debugging. For example when I was trying to look at the Workbook.Names collection in the Quick Watch window (VS 2008) I expanded one of the Name items in the collection, but was unable to inspect any of its properties. It was only by rewriting the expression in Quick Watch window to include a cast to IName that I could see the property values. - SpreadsheetGear do not have any public forums that I could find: the only way to get support is to fill in a form and wait for them to get back to you. - Performance of the component was very good. Remember the application that took all night with COM Interop, and up to an hour with XlsIO? It now takes under a minute with SpreadsheetGear. - As a bonus, here's the answer to an issue that took me an afternoon to figure out (and has caught me out again since then). When you supply a Range address to an IName (whether by using Names.Add or IName.RefersTo) remember to prefix it with an "=" sign; otherwise the IName.RefersToRange property won't get updated. Honourable Mentions - I tried contacting Independentsoft about Spreadsheet.Net but never received a link to the evaluation download. I would judge by the website that this component isn't going to be as complete or mature as the others. - Gembox Software offer a completely free version of their spreadsheet control, limited to 5 worksheets of 150 rows each. Unfortunately they don't seem to offer an evaluation version of the full product, so I wasn't able to try it out on my big workbook. A quick scan of the online help shows that the API is not dissimilar to Excel's, and does follow the .Net framework design guidelines. - FarPoint Spread does Excel import and export, but its focus is on providing a spreadsheet-like Grid component, so I didn't look into this any further. - Infragistics have Infragistics.Excel but it looks like it can only be purchased as part of one of their suites. From the documentation, it doesn't look as fully featured as either XlsIO or SpreadsheetGear. - ComponentOne is another component suite vendor that has lumped an Excel IO component in with their suite. Again, the documentation shows that it has fairly limited capabilities compared with the leaders. - Aspose.Cells is a component that appears, by my reading of its documentation, to sit somewhere in the middle of the market, in terms of functionality and price. Aspose is a vendor that sells components for .Net and Java. and gets it right: the API's are "localised" for the framework culture. The .Net API gets Properties and Pascal cased methods, and the Java API keeps its get and set methods. 11 comments: I think you catch the same problem as me in XlsIO... but trick is that if you sit a little with any profiler then you will find that in most cases can be found less expensive in time XlsIO operation. As syncfusion support said it's due to Excel API interfaces they have to keep... You can ask syncfusion support for assist and after a while got optimized code from syncfusion developers. BTW can you provide a sample of code?! for testing on other commercial components?! Could you give a sample code in VBA or XlsIO or SpreadsheetGear (or better all of them) which was so much faster in SpreadsheetGear? (I really want to see it with my eyes) I didn't get round to creating any proper benchmarks, and I would be embarassed to release the code I have to the world: it's not fit to be seem ;-). As I mentioned, it was a couple of specific API calls when used with a very large workbook that caused the problem with XlsIO - on the whole performance wasn't too bad. The problem with the Delete row call seemed to be to do with checking and updating possible formula references to the row. SpreadsheetGear just didn't have this problem; they have obviously coded that part more efficiently. Ranges with union of multiple rectangular ranges is also supported by Syncfusion's XlsIO. Here is how it can be done: //Union of multiple ranges IRanges rangeCollection = mySheet.CreateRangesCollection(); IRange range1 = mySheet.Range["A1:A2"]; IRange range2 = mySheet.Range["C1:C2"]; rangeCollection.Add(range1); rangeCollection.Add(range2); rangeCollection.Text = "XlsIO"; Thanks Dhivya. I was aware that you can use RangesCollection like that, but my point was that the standard IRange object isn't the same as Excel's. Also, the Merge operation on Ranges only works if ranges can be merged to form one Rectangle; it fails if ranges are disjoint. Thanks for posting this. As somebody who is altogether unfamiliar with programmatically reading/writing excel spreadsheets yet finding myself needing to do so, I found this post to be a good starting point for my own research. Dave, Glad I could help. Perhaps you might like to add your rating to the post :-) Sam Here are my first impressions on some of the products you didn't look at in depth. To give some perspective, my goal was to find a component that would let me create a spreadsheet that will be filled out by users. I needed to use dropdown lists for some columns, driven off of named ranges. Because my needs are fairly simple, I decided to see if any of the cheaper products would work for me. Performance with large data sets is not my primary concern. Gembox is very limited. It supports writing values, functions, and some simple formatting. It doesn't support setting validation for cells, which is needed to create dropdown lists. Their documentation is pretty sparse, and they only give a few trivial examples of how to use their APIs. Apose has an API that is much more fully featured, and from what I can tell, fully supports the full range of excel's validation options for cells. Their documentation was pretty good, and they provided lots of examples. It supports everything I need to do, and I'll likely be using it. Dave, Thanks for posting that. I'm sure readers with requirements like your will find that helpful. Sam Hay, Was also looking into excel libs, but for my purposes only needed to read excel. Found this to be really inexpensive compared to the others. If you have trouble posting a comment, try pressing the Preview button first - works for me!
http://blog.functionalfun.net/2008/08/which-net-excel-io-component-should-i.html
crawl-002
refinedweb
2,107
63.29
2D vector?[code] #include <vector> vector<vector<int> > 2dVector;//2d vector vector<int> 1dVector;//normal vec... <CMath>Getting angles between 2 3d points.Thanks for your help I the code I now have is: [code] float getAngle (float x1,float y1,float z1,flo... <CMath>Getting angles between 2 3d points.Thanks for your answers. @ne555 Yes I need 2 angles, because it's 3d. See this image, to understand ... <CMath>Getting angles between 2 3d points.I need to get a cannon to schoot on my target. It is a 3d game. I need to get 2 angles between t... OpenGL triangles invisible .obj loaderDoes nobody know how to fix this? This user does not accept Private Messages
http://www.cplusplus.com/user/kajgies/
CC-MAIN-2016-22
refinedweb
119
72.42
Pelemay is a native compiler for Elixir, which generates SIMD instructions. It has a plan to generate for GPU code. Pelemay = The Penta (Five) “Elemental Way”: Freedom, Insight, Beauty, Efficiency and Robustness For example, the following code of the function map_squarewill be compiled to native code using SIMD instructions by Pelemay. defmodule M do require Pelemay import Pelemay defpelemay do def map_square (list) do list |> Enum.map(& &1 * &1) end def string_replace(list) do list |> Enum.map(& String.replace(&1, "Fizz", "Buzz")) end end end Potentially, Pelemay may support any architectures that both Erlang and Clang or GCC are supported. We've tested it well on the following processor architectures: We've tested it well on the following OS: I'm so sorry but Windows isn't be supported because of changing the builder of Pelemay. We've tested it on the following Elixir versions: We've tested it on the following OTP versions: We've tested it on Clang 6 or later and GCC 7 or later. Potentially, Clang and GCC that supports auto-vectorization can generate native code with SIMD instructions by Pelemay. Pelemay also supports Nerves. Pelemay requires Clang or GCC and make. Environment Variable CCis recommended being set the path of the C compiler you want to use. Add pelemayto your list of dependencies in mix.exs: def deps do [ {:pelemay, "~> 0.0.15"}, ] end Documentation is generated with ExDoc and published on HexDocs. The docs will be found at.
https://xscode.com/zeam-vm/pelemay
CC-MAIN-2021-10
refinedweb
244
56.96
I am attempting to make a program in Python that copies the files on my flash drive (letter D:) to a folder on my hard drive but am getting a PermissionError: [Errno 13] Permission denied: 'D:'. The problematic part of my code is as follows: # Copy files to folder in current directory def copy(): source = getsource() if source != "failure": copyfile(source, createfolder()) wait("Successfully backup up drive" "\nPress 'Enter' to exit the program") else: wait("No USB drive was detected" "\nPress 'Enter' to exit") # Create a folder in current directory w/ date and time def createfolder(): name = strftime("%a, %b %d, %Y, %H.%M.%S", gmtime()) dir_path = os.path.dirname(os.path.realpath(__file__)) new_folder = dir_path + "\\" + name os.makedirs(new_folder) return new_folder As I stated in my comment above, it seems as if you're trying to open the directory, D:, as if it was a file, and that's not going to work because it's not a file, it's a directory. What you can do is use os.listdir() to list all of the files within your desired directory, and then use shutil.copy() to copy the files as you please. Here is the documentation for each of those: os.listdir() (You will be passing the full file path to this function) shutil.copy() (You will be passing each file to this function) Essentially you would store all of the files in the directory in a variable, such as all_the_files = os.listdir(/path/to/file), then loop through all_the_files by doing something like for each_file in all_the_files: and then use shutil.copy() to copy them as you please.
https://codedump.io/share/jL1w9ii1lLFu/1/python---errno-13-permission-denied-when-trying-to-copy-files
CC-MAIN-2017-47
refinedweb
271
62.27
import "github.com/mewkiz84/bytesx" Package bytesx implements highly optimized byte functions which extends the bytes package in the standard library (Currently x86 64-bit only) func EqualThreshold(a, b []byte, t uint8) bool EqualThreshold returns true if b does not differ in value more than t from the corresponding byte in a. t may take any value from 0 to 255 where 0 is exact match and 255 will match any string. If t is 1 and a is "MNO" and b is "LNP" than EqualThreshold will return true while it will return false if b is "LNQ" or "KNO". The equality check is only made untill the shortest of a and b. func IndexNotEqual(a, b []byte) int IndexNotEqual returns the index of the first non matching byte between a and b, or -1 if a and b are equal untill the shortest of the two. Updated 2013-11-07. Refresh now. Tools for package owners.
http://godoc.org/github.com/mewkiz84/bytesx
CC-MAIN-2014-42
refinedweb
158
63.02
No, it doesn't compile. Zeus is confused between C++ and C. Your code is correct, although using ++ is more usual. Passing a pointer to the first element is essentially passing the whole array... No, it doesn't compile. Zeus is confused between C++ and C. Your code is correct, although using ++ is more usual. Passing a pointer to the first element is essentially passing the whole array... Please post actual code that you've ran then copy/pasted, not something you just typed up. :tongue: What is inbuf? What is newline? (Presumably inbuffer and n.) And you have a semicolon in one... Look at all three posts by this weirdo, this post and the following two, all posted at about the same time. They are all meaningless garbage and remind me of the kind of useless add-on comments that... Sure, post the GitHub link and the other stuff. @rstanley, Large multi-file programs are probably best posted as a link. It struck me as an old-fashioned style. Maybe you're using an old book. Or have an old teacher. Whatever. :p It's the arbitrary actions of UB stemming from the uninitialized "top" pointer in "rev". It needs to be initialized to NULL. You've been given more than enough information in your thread on the other site: how read the GIF and JPG image size? - C++ Forum And from the code you've shown you clearly don't know what you... It's pretty obvious you didn't write that code. It says that unsigned integers are supposed to function the same across all implementations. It doesn't say anything about "testing for overflow of unsigned integers". In fact, you might say that... No. If curr could just be a single-level pointer I would've wrote it that way since it would be simpler. The reason you need the second level of indirection is that we don't want curr to hold the... The recursive version is better written like this: ListNode *merge2(ListNode *a, ListNode *b ) { if (!a) return b; if (!b) return a; if (a->data <= b->data) { typedef struct listnode { char data; struct listnode *next; } ListNode; ListNode *merge(ListNode *a, ListNode *b) { The format specs that read ints and floats and the format spec "%s" all skip initial whitespace so there's no difference in functionality. Maybe your version is more readable, though. We usually handle this kind of thing by first reading the entire line as a string, and then using sscanf to "scan" the numbers from the string. All the scanf functions return a count of the number of... The format spec for long long is "%lld". You have "%ld", which is for long. If long long is actually bigger than long on your machine and your machine is little endian, then a 0 output for a... Don't just say "and the second problem is that it does not work". Of course it "works". Post your broken code that you actually ran so we can show you your error. :mad: What does that mean? Do you want to know how to retrieve the hdd SN? Do you want to know how to "embed" the hdd SN in an exe? What does "embed" mean? Why do you want to do this? Maybe... You're just inventing how strcmp works. Where did you read it returns a count of matching characters? It's return value is 0 if ALL characters match. It returns a negative (but otherwise... With Fortran's implicit typing, variables i,j,k,l,m,n are integers; others are real. Variables do not need to be declared (will equal 0 on first use ... I assume). The loops include their ending... You can allocate more memory than you have physical RAM. The memory that is allocated is "virtual memory" and can in fact exist mostly on disk. This can then be very slow to use, of course, but... #include <stdio.h> #include <stdbool.h> bool calc() { int a, b, c = 0; char o; printf("> "); if (scanf("%d %c %d", &a, &o, &b) != 3) return false; switch (o) The code you've shown can be rewritten as shown below. Instead of a bunch of numbered variables (code1, code2, etc.) use an array; but remember that array indices start at 0 and go to one-less-than... Here is a clean-up of your code. 'fin' only has space for one address (and it has a global doppleganger for some reason). So once count is incremented past 0 it will be an out-of-bounds access. I... #include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *next; } Node; Node *AddNode(int data, Node *prev) #include <stdio.h> #include <stdlib.h> // Print array a of size n on a single line. void print(int* a, int n) { for (int i = 0; i < n; i++) printf("%d ", a[i]); ...
https://cboard.cprogramming.com/search.php?s=4b05897a9172b428daa268890a6d937b&searchid=3578798
CC-MAIN-2020-16
refinedweb
821
85.69
oh ok I see now. Thanks KevinWorkman. oh ok I see now. Thanks KevinWorkman. Thank you so much JavaPF!! ..especially the example you provided. , you mean Scanner can read the specified line from a file? If so, then how to do that? :) Hi guys Can Scanner read the specified line from user's input? For example, I want Scanner to find the 50th line of input and read it only, not from the first line, how to do that? Many... Thank you guys. I got a piece of sample code here for shortest path, it is working. But I don't understand vertexQueue.remove(v), my understanding is "after executing Vertex u =... ok, what about there are many lines of statements under for(int i = 0; i <= 5; ++i), EG.: for(int i = 0; i <= 5; ++i) System.out.println(i); // statements A ........................;... :) I see....Thanks a lot for the explanation. so is still a kind of loop, but doesn't statement need to be wrapped inside a pair of {}? (otherwise how could it know which statement is the thing... Hi guys I have a question for how many ways to use FOR statement? I thought FOR is only used in starting a loop, like below two forms: for (initialization; termination; increment) or For each... Hi Helloworld922 Thanks for your advice. ..If I really want to try those "ready-to-use" methods, do I just need to put "import org.graphstream.algorithm.Dijkstra" at the top? like import things... Hi Guys Can anyone tell me - What is the difference between and ? (They all seem to provide methods of Classes) Thanks heaps I found these two mehtods getShortestPath() and treeWeight() provided in Class Dijkstra in below link: Any idea... Thank you for your advice. :) Ok, will have two classes. If the cities are a number of vertexs, and put them into an arraylist, but how to show the connections between them? Thanks heaps ok, the english rule for a raod descriorion is: <roadName> <cityA> <AB distance> <cityB> [<BC distance> <cityC> […]] But how to write just one pattern in java that can represent above? Thanks... Thanks KevinWorkman, I didn't express my question well, I mean how to write a general pattern for a given string with string variables. For example: Here are some strings, each string represent one... Thank you helloworld! Dijkstra on Wikipedia gives below Pseudocode, I am surprised you said their pseudo-code can be used verbatim, it still looks far too simple to me. :o After reading the... ok, I have read class Dijkstra, I think the mehtods getShortestPath() and treeWeight() sounds useful, but I don't know how to use them. :) Any chance you could continue to tell me a bit more about... Hi guys I got a CHALLENGE here, below question is From the ACM South Pacific Regional Programming Contest 2009. It is a bit long reading, :) hope you have some patience. Will anyone be able to tell... Hi guys Firstly Happy new year to you soon,:) can someone please tell me this: I understand how to write a pattern with single character of regular-expression (eg. [a-zA-Z]), but how to define... oh, my god! It finally did it! =D> Thank u a lot copeg!!! :) Wow, it does have some magic! Now mouseClick part works, selectedOctagon can get selected. But something odd happened: As soon as I start to drag selectedOctagon, it moves very very quickly to... great, that souds promising, :) here is Octagon Class: import java.awt.*; import java.util.Random; public class Octagon extends Polygon { private int[] x; private int[] y; ... ok, after I tidied up the code to new one below, I think I have found out a big error here: selectedOctagon never got selected in the methods private Octagon hitTest(MouseEvent e) and public void... In fact I don't know what exact I should print to analyse; then I tried to put System.out.println(xtrans + " " + ytrans);inside mousedragged method, is that right thing to print? but it print out... Hi guys, don't give up here yet, the problem is still not solved yet. :-w Thanks copeg, but it didn't work out for me, I still don't know how to fix it. :o Is there any way yo point out the error inside the code? Thanks heaps How could System.out.println help it? It just simply print text out, I still don't know what is going on. As for debugger, I am hopeless on that. :o Is there other ways to tell whic part of code is...
http://www.javaprogrammingforums.com/search.php?s=3e682ba0d93ddcee960ed3e1b91fcd7d&searchid=1028413
CC-MAIN-2014-35
refinedweb
763
84.98
27 December 2010 11:30 [Source: ICIS news] By Linda Naylor ?xml:namespace> At the end of 2009, imports were about to flood the market, the economic outlook was gloomy and the fallout from the spectacular fourth quarter of 2008 was still fresh in some players’ minds. While the eurozone is still under pressure and expected to remain weak, and possibly weaken further, PE players are now more confident of a strong year to come than they were 12 months ago. “Buyers have been disappointed with Middle Eastern suppliers and they are coming back to us with strong volumes requests for 2011,” said a major producer. “I think we will see a strong 2011, supported by demand from January was expected to start with a bang in the European polyolefins market. Spot prices, particularly in the PE sector, were already soaring at the end of December due to expectations of a strong hike in the new January ethylene contract price, which settled up by €105/tonne ($138/tonne) at €1,110/tonne. One major producer, who had been expecting this increase, was aiming to hike PE by this amount and more. The propylene contract also rose, by €110/tonne, and polypropylene prices were expected to follow in its wake. The mood in the low density polyethylene (LDPE) market was for a strong 2011 following several permanent capacity closures in 2009, but sources’ opinions differed over the rest of the PE market. High density polyethylene (HDPE) and linear low density polyethylene (LLDPE) were looking firm for January, but the future was unclear for these grades, as it was HDPE and LLDPE that would be most affected by imports. Sentiment in the PP market was less bullish than in PE, but PP producers were also confident, predicting a tight monomer situation due to reduced refinery runs and cracker output. There was hesitation from many sources, both buyers and sellers, when considering 2011 after getting the prognosis so wrong for 2010. “There are so many different elements to consider that it is particularly difficult to read the coming year,” said another producer. There was no sign of erosion in crude oil and naphtha markets, and monomer was also looking strong. The threat of polymer imports still loomed, but now most sources did not expect much to arrive in “Material from the Buyers did expect to be able to get hold of imports in 2011, however, particularly during the second half of the year. Not only was the Middle East producing fresh quantities of polyolefins, but new plants were also coming on stream in Many of the potential exporters from the “These guys also want a return on their investment,” said another market source. “Their plants cost far more than they had originally budgeted. They won’t dump product into European producers had placed themselves strategically away from commodities in recent years, in a move to avoid a head-on clash with importers as plants exported material. “We are no longer in commodities,” said another producer. “Anything that finds its way into Some players added a note of caution, however, and not all felt that they could escape the tide of new capacities coming on stream in low-cost regions. “We do expect the Asian market to soak up Middle Eastern capacity, and that we’ll have a balanced 2011. New plants won’t run at their designed capacity but sooner or later it will have an impact. It can go from sunshine to rain very quickly.” ($1 = €0.76) For more on poly
http://www.icis.com/Articles/2010/12/27/9420253/outlook-11-europe-polyolefins-players-expect-strong-start-to-2011.html
CC-MAIN-2014-41
refinedweb
590
55.58
You're viewing Apigee Edge documentation. View Apigee X documentation. On Monday, September 19, 2016, we released a new version of Apigee Edge for Private Cloud. Since the previous Edge for Private Cloud Feature Release, the following releases have occurred and are included in this Feature Release: - Cloud: 16.04.13 (UI), 16.04.13 (monetization), 16.04.20 (UI), 16.04.27 (monetization), 16.04.27 (UI), 16.05.04 (UI), 16.05.11 (UI), 16.05.11 (monetization), 16.05.18 (UI), 16.05.25 (monetization), 16.06.08 (monetization), 16.06.15 (UI), 16.06.22 (monetization), 16.06.29 (UI), 16.07.06 (monetization), 16.07.06.02 (monetization), 16.07.13 (UI), 16.07.20.01 (monetization), 16.07.27 (UI), 16.08.17 See About release numbering to understand how you can figure out whether a specific cloud release is included in your version of Edge for Private Cloud. Release overview In this release, the classic API proxy editor has been removed, replaced by the new proxy editor that was available for use alongside the classic editor. Other notable enhancements include improved behavior of API product resource paths, improved handling of JSON payloads defined in Assign Message and Raise Fault policies, enhancements to XML-to-JSON conversions, improved resource validation, the ability to set timeouts on individual API proxies, updated generation of SOAP proxies in the API proxy wizard, and a high-performance Crypto object for JavaScript. Monetization enhancements include new notification features with a notification rate plan, an API that migrates developers to monetization, and the ability to make rate plans public or private. The remainder of this topic contains details on all the new features, updates, and bug fixes contained in the release. Deprecated API Services Classic Proxy Editor removed (Cloud 16.04.20 UI) The following deprecated features have been removed and are no longer supported: - Setting limits - Sending limit notifications As an alternative, you can set up notifications, as described in the following sections: (DEVRT-2742) New features and updates Following are the new features and enhancements in this release. In addition to the following enhancements, this release also contains multiple usability, performance, security, and stability enhancements. For further details and instructions, see the Edge for Private Cloud documentation. Private Cloud Postres upgrade to version 9.4 This release includes an upgrade to Postgres 9.4. For instructions on updating your system, see Update Apigee Edge to 4.16.09. GeoMap support in the Edge UI Geo aggregations lets you collect analytics data for API calls based on geographical attributes such as region, continent, country, and city. From this analytics data, you can view a GeoMap in the Edge UI that shows the location of API requests. For more information, see Enabling Geo Aggregation and Geo Maps. API BaaS Added documentation on: - How to configure API BaaS to use TLS. For more information, see Configuring TLS for API BaaS. - How to configure all API BaaS Stack nodes to use shared storage so that all assets are available to all API BaaS Stack nodes. For more information, see Uploading assets. - How to encrypted Cassandra password when configuring BaaS Stack nodes. For more information, see Resetting Edge Passwords. Beta release of the Monitoring Tool and Dashboard Included in this release is an Beta with the Edge 4.16.09 doc at Version 4.18.01. However, before you can install and use the dashboard, you must complete the Apigee Evaluation Agreement, also available at Version 4.18.01, and return it to Apigee by emailing it to orders@apigee.com. Beta release of the analytics collector tool All Edge for Private Cloud customers are required to submit to Apigee statistics about API proxy traffic. Apigee recommends that customers upload that information once a day, possibly by creating a cron job. To assist in uploading this data, Apigee provides the Beta release of the apigee-analytics-collector command-line utility. This utility sends the API call volume report back to Apigee. Every Edge for the Private Cloud installation can use this utility to retrieve and report traffic data to Apigee. For more information, see Uploading API Traffic Data to Apigee - Beta Release. API Services JSON payloads in Assign Message and Raise Fault (Cloud 16.08.17) (Cloud 16.08.17) (Cloud 16.08.17) (Cloud 16.08.17) (Cloud 16.08.17) (Cloud 16.08.17) (Cloud 16.08.17)setting) SOAP proxy behavior when using the proxy wizard (Cloud 16.07.27 UI) When creating a SOAP-based proxy from a WSDL using the proxy wizard, there are two options for proxy creation: - Pass-Through SOAP, where the proxy simply passes through a SOAP request payload as is. - REST to SOAP to REST, where the proxy converts an incoming payload such as JSON to a SOAP payload, then converts the SOAP response back to the format the caller expects. This release includes the following updates to how these options behave. The differences between the old and new behavior are in the policies and configurations that are automatically generated by the proxy wizard. Pass-Through SOAP All WSDL operations are now sent to the proxy base path "/" rather than to proxy resources (such as "/cityforecastbyzip"). Operation names are passed through to the target SOAP service. This behavior matches the SOAP specification. - The generated proxy no longer supports JSON in the request. It supports only XML. The proxy ensures SOAP requests have an Envelope, Body, and a namespace. REST to SOAP to REST - WSDL 2.0 is not supported. - The new behavior hasn't been tested with WS-Policy. - The proxy lets you POST JSON data instead of FormParams. - When you add CORS (Cross-origin resource sharing) support to the proxy using the proxy builder, you'll see the following enhancements: - Access-Control-Allow-Headers header: In addition to Origin, x-requested-with, and Acceptheaders, the Access-Control-Allow-Headers header also includes Content-Type, Accept-Encoding, Accept-Language, Host, Pragma, Referrer, User-Agent, and Cache-Control. - Access-Control-Allow-Methods header: In addition to GET, PUT, DELETE, this header also includes the PATCHand OPTIONSverbs. - When generating an API proxy for a WSDL, Edge reads any ComplexTypes that are defined as abstract in the WSDL and properly recognizes any instance types that are based on the abstract types. wsdl2apigee open source command-line utility Apigee also provides an open source command-line utility to generate passthrough or rest-to-soap API proxies from WSDLs. See. (EDGEUI-614) Expiry/refresh default in Key Value Map Operations policy (Cloud 16.06.15 UI) They Key Value Map Operations policy lets you determine how long values are persisted before being refreshed. The refresh interval is set with the <ExpiryTimeInSecs> element. If a GET operation is executed and the expiry interval has been exceeded, the value is refreshed and the policy gets the updated value. When you add this policy to an API proxy, the default expiry time is now 300 seconds. (The previous default was -1, which means values are never refreshed.) (EDGEUI-579) Monetization Adjustable notification rate plan (Cloud 16.04.20 UI, Cloud 16.04.13 monetization), DEVRT-2370) Webhook notifications for adjustable notification rate plans (Cloud 16.04.27 monetization) For adjustable notification rate plans, you can create webhooks that send notifications to the URL you specify. You can also control notifications to occur at specific intervals (percentages) up until the transaction limit is reached. Webhook notifications give you a flexible alternative to using the existing notification templates. See Set up notifications using webhooks. (DEVRT-2393, DEVRT-2394) Adjustable Notification with Custom Attribute rate plan (Cloud 16.05.18 UI) In Edge monetization, a new "Adjustable Notification with Custom Attribute" rate plan lets you add to a developer's transaction count using the value of a custom attribute. With the standard Adjustable Notification rate plan, each successful API call adds 1 to a developer's transaction count. But with the Adjustable Notification with Custom Attribute rate plan, the value of the custom attribute is added to the developer's transaction count. For example, if custom attribute "small" has a value of 0.1 in the response, the transaction count is incremented by 0.1; or if custom attribute "addressTotal" has a value of 50, the count is incremented by 50. For more information, see Specify rate plan with custom attribute details. (DEVRT-2504) Set up notifications based on combined transaction totals for a company and its developers (Cloud 16.06.22 monetization) Typically, transaction totals are tracked for all developers in a company automatically when the developers use the company app to access APIs. What if you have developers that are actively using their own developer apps to access APIs, and you need to track their combined transaction totals without any disruption in traffic? You can add the developers to a company and set up notifications to be sent when thresholds are reached that are based on combined transaction totals for the company and its developers. For more information, see Set up notifications based on combined transaction totals for a company and its developers. (DEVRT-2643) View and reprocess notifications (Cloud 16.06.08 monetization) As part of the monetization test suite, you can view and reprocess notifications previously sent using the management API. For more information, see Viewing and reprocessing notifications. (DEVRT-2643) Test Monetization (Cloud 16.05.25 monetization) Monetization provides a set of APIs that you can use to test the execution of webhooks to ensure notifications are being sent. For details, see Test notification setup. (DEVRT-2625) Migrating developers to monetization (Cloud 16.05.11 monetization) A new API is available to facilitate the migration of developers to monetization. You can transfer transaction usage and charge customized setup and recurring fees. In addition, when accepting a published rate plan, you can waive setup fees in case they have already been charged. For more information, see Migrating developers to monetization. (DEVRT-2446) Public and Private rate plans for the developer portal (Cloud 16.04.27 monetization) You can set rate plans to be "Public" or "Private". Public rate plans appear in the developer portal; Private rate plans do not. The default for a rate plan is Public. For more information, see. (DEVRT-2445) Unsuspend developers (Cloud 16.06.08 monetization) Monetization provides a set of APIs that you can use to unsuspend a developer that was previously suspended. A developer might be suspended if a configured limit is reached. For example, the number of transactions has reached its maximum limit or a prepaid account balance has been depleted. For information, see Unsuspend developers. (DEVRT-2641) View the status of transactions (Cloud 16.06.08 monetization) As part of the monetization test suite, you can view the status of transactions that have occurred during a specified time range using the management API. For more information, see Viewing the status of transactions. (DEVRT-2640) Including developer custom attributes in revenue reports (Cloud 16.05.25 monetization) For revenue reports only, you can include custom attributes in the report, if the custom attribute is defined for the developer. For more information, see Including developer custom attributes in revenue reports using the API. (DEVRT-2447) Transaction Recording Policy and API product resource consistency (Cloud 16.05.18 UI) If the resource paths in a monetization Transaction Recording Policy don't match the resources paths defined in its API product (for example, if you change the API product resource paths), the Transaction Recording Policy icon on the Products page shows a warning symbol. When you click the icon to view the Transaction Recording Policy, a warning appears at the top of the page. When you fix the resource paths in the Transaction Recording Policy, the warning indicators disappear. (DEVRT-2240) Bugs fixed The following bugs are fixed in this release. This list is primarily for users checking to see if their support tickets have been fixed. It's not designed to provide detailed information for all users. Edge for Private Cloud 16.08.17 16.07.27 (UI) 16.07.20.01 (monetization) This release includes minor DB shema changes There are no other software updates in this release. 16.07.13 (UI) 16.07.06.02 (monetization) 16.07.06 (monetization) 16.06.29 (UI) 16.06.22 (monetization) None 16.06.15 (UI) 16.06.08 (monetization) None 16.05.25 (monetization) 16.05.18 (UI) 16.05.11 (monetization) 16.05.11 (UI) 16.05.04 (UI) 16.04.27 (UI) 16.04.27 (monetization) None 16.04.20 (UI) 16.04.13 (monetization) None 16.04.13 (UI) Known Issues This release has the following known issues:
https://docs.apigee.com/release/notes/41609-edge-private-cloud-release-notes?hl=ja
CC-MAIN-2021-39
refinedweb
2,115
50.84
Standard MBeans How Do Standard MBeans Work? In this section, we will learn how to instrument a Java class as a standard MBean. We will first look at how to describe the management interface according to the JMX design patterns for standard MBeans. Then we will look at how to implement the MBean interface on the Queue class touched on earlier in this chapter. Many examples will be provided. It is here that we will examine all of the classes that make up the application, showing inheritance patterns and other cool standard MBean miscellany. We will also look at the Controller class's main() routine, which is what drives the application, and we will discuss how to register MBeans with the MBean server, how to register and use the HTML Adaptor server, and how to build and run the example. Describing the Management Interface JMX provides us with a set of patterns to follow when instrumenting our application resources as standard MBeans. If we follow these patterns exactly as they are set out in the specification, our standard MBeans are said to be compliant. If we don't correctly follow the patterns, the MBean server (part of the reference implementation; we'll discuss the MBean server later in this chapter) will declare our MBean as non-compliant by throwing a javax.management.NotCompliantMBeanException at the agent that attempts to register the MBean. However, it is possible for us to correctly follow the patterns but still not expose the correct management interface on our standard MBean. We will also look at that case in this section. - The management interface of the resource must have the same name as the resource's Java class, followed by "MBean"; it must be defined as a Java interface; and it must be implemented by the resource to be managed using the implements keyword. - The implementing class must contain at least one public constructor. - Getters and setters for attributes on the management interface must follow strict naming conventions. Each of these patterns is discussed in detail in this section. Pattern #1: Defining, naming, and implementing the MBean interfaceThe management interface must be defined using the Java interface keyword, it must have public visibility, and it must be strictly named. Earlier in this chapter, we looked at the thought process we might go through to define a management interface for a queue. Suppose the name of this class is Queue. Its standard MBean management interface must be defined as: public interface QueueMBean { //management interface goes here. . . } The Queue class, in turn, must implement the QueueMBean interface using the Java implements keyword: public class Queue implements QueueMBean { //implementation of QueueMBean //and other stuff here. . . } The name of the MBean interface is case-sensitive. For example, QueueMbean is not the same as QueueMBean. Of course, the compiler will help you if you "fat-finger"the spelling of the interface in either the interface definition or the implementation. However, if you use the same misspelling in both, the compiler will chug merrily along and produce perfectly runnable bytecode. Only when you attempt to register your MBean will you receive a NotCompliantMBeanException exception! The management interface is contained in its own .java file and must have the same name as its corresponding interface. Thus, every standard MBean requires at least two source code files:one for the interface and one for the class that implements the interface. Another example from the application we use throughout this book is the Worker class. Its management interface is defined as: public interface WorkerMBean { //. . . } The Worker class, in turn, implements this interface as: public class Worker implements WorkerMBean { //. . . } Pattern #2: Provide at least one public constructor The class that implements the MBean interface must have at least one constructor declared with public visibility. This class may have any number of public constructors, but it must have at least one. If you do not provide a constructor, the compiler will generate a no-argument constructor with public visibility. This will work fine for your MBeans, but I recommend that you explicitly declare a no-argument constructor for these cases, as your code will follow the rule and be more readable as well. Continuing with the code snippets from earlier, then, our Queue class would look like: public class Queue implements QueueMBean { public Queue(){ //do something here. . . } //other class methods and management interface //implementation. . . } However, the Queue class might not have a no-argument constructor at all: public class Queue implements QueueMBean { //no no-arg constructor provided, that's okay. . . public Queue(int queueSize){ //do something custom here. . . } //other class methods and management interface //implementation. . . } and still be a compliant MBean, because it provides a public constructor. Pattern #3: Attributes and how to name their getters and setters When defining an attribute on the management interface, you must follow strict naming standards. If the attribute is readable, it must be declared on the interface (and subsequently implemented) as getAttributeName(), where AttributeName is the name of the attribute you want to expose, and take no parameters. This method is called a getter. Table 2-1 showed some of the attributes we plan to expose on the Queue class. As an example, we would define the Add Wait Time attribute on the management interface as: public interface QueueMBean { public long getAddWaitTime(); //. . . } For boolean values, preceding the attribute name with "is"is a common idiom and one that is acceptable according to the JMX standard MBean design patterns. From Table 2-1, notice that we have a boolean attribute called Suspended. We would define this attribute on the management interface as: public interface QueueMBean { public long getAddWaitTime(); //. . . public boolean isSuspended(); //. . . } If an attribute is writable, the naming pattern is similar to that for readable attributes, only the word "get"is replaced with "set," and the attribute takes a single parameter whose type is that of the attribute to be set. This method is called a setter. For example, Table 2-1 shows a readable and writable attribute called QueueSize. We would define this attribute on the management interface as: public interface QueueMBean { public long getAddWaitTime(); //. . . public boolean isSuspended(); //. . . public int getQueueSize(); public void setQueueSize(int value); //. . . } There are two rules about setters: - The setter can take only a single parameter. If you unintentionally provide a second parameter to what you thought you were coding as a setter, the MBean server will expose your "setter" as an operation. - The parameter types must be the same for read/write attributes, or your management interface will not be what you expect. In fact, if you have a read/write attribute where the getter returns a different data type than the setter takes as a parameter, the setter controls. For example, suppose that I mistakenly coded the setter for QueueSize to take a short data type. My management interface would then look like: public interface QueueMBean { public long getAddWaitTime(); //. . . public boolean isSuspended(); //. . . public int getQueueSize(); public void setQueueSize(short value); //. . . }Strangely enough, what I have actually exposed is a single write-only attribute called QueueSize, of type short! Clearly, that is not what I intended. Of course, remember that with standard MBeans, the Java compiler can catch some of these mistakes for you. Let's say that I made this particular mistake on the interface definition, but on the implementing class I used the proper int type on my setter. The compiler would tell me that I should declare the implementing class abstract, because it doesn't define the setter that takes the short! That is one advantage of standard MBeans over other MBean types—the compiler can help you find mistakes before they turn into nasty bugs. Using the information from Tables 2-1 and 2-2, the management interface is shown in Example 2-1. Example 2-1. The QueueMBean interface public interface QueueMBean { //attributes public long getAddWaitTime(); public long getRemoveWaitTime(); public int getQueueSize(); public void setQueueSize(int value); public long getNumberOfItemsProcessed(); public boolean isQueueFull(); public boolean isQueueEmpty(); public boolean isSuspended(); public int getNumberOfSuppliers(); public int getNumberOfConsumers(); //operations public void reset(); public void suspend(); public void resume(); public void enableTracing(); public void disableTracing(); } A word about introspection Introspection literally means to "look inside" and is performed by the MBean server to ensure compliance on the part of your MBeans when they are registered. Because it is possible to write Java code that cleanly compiles and executes but does not follow the standard MBean design patterns we discussed earlier, the MBean server looks inside your MBean to make sure you followed the patterns correctly. When your MBean is registered by the agent, the MBean server uses Java's reflection API to crawl around inside the MBean and make sure that the three design patterns we discussed earlier were followed. If they were, your MBean is compliant and its registration proceeds. If not, the MBean server throws an exception at the agent. Introspection takes place only when your MBean is registered by the agent. Depending on the code paths your application takes when instantiating your MBean classes, the notification (via an exception) that one of your MBeans is not compliant will appear only when the MBean is registered. Page 2 of 7
https://www.developer.com/java/other/article.php/10936_2212031_2/Standard-MBeans.htm
CC-MAIN-2017-47
refinedweb
1,528
52.8
Keywords as Element Names in Code Any program element — such as a variable, class, or member — can have the same name as a restricted keyword. For example, you can create a variable named Loop. However, to refer to your version of it — which has the same name as the restricted Loop keyword — you must either qualify it by preceding it with its full namespace, or enclose it in square brackets ([ ]), as in the following examples: If you do not, Visual Basic assumes use of the intrinsic Loop keyword and produces an error, as in the following example:, it is recommended that you not use restricted keywords as the names of program elements. However, if a future version of Visual Basic defines a new keyword that conflicts with an existing form or control name, you can use this technique when updating your code to work with the new version. Note Your program also may include element names provided by other referenced assemblies. If these names conflict with restricted keywords, placing square brackets around them forces Visual Basic to accept them. See Also Visual Basic Naming Conventions | Program Structure and Code Conventions | Keywords
https://msdn.microsoft.com/en-us/library/hwx24eb6(v=vs.71).aspx
CC-MAIN-2016-40
refinedweb
191
52.23
How to use ecj compiler in Netbeans If you have read my post about why sometimes Eclipse ECJ compiler does not work nicely with other compilers then you maybe also need some cure for that issue. Few days later I’ve found some, maybe not very nice, solution to get ECJ working with Netbeans IDE. Had no spare time to write about it, but i have few free minutes now and maybe someone needs that stuff also. I’ve downloaded sources for Netbeans launcher C code (thanks God for Open Source) and modified it so it launches ECJ main class. Then added one line in main project build.xml file: <property name="platform.javac" value="<path_to>/ecjexec.exe"/> (just change <path_to> to where you have saved your launcher) This will make ant (default Netbeans build system) use ecjexec (thus ECJ) instead of javac. Oh, you need to do one more thing: add ecj.jar to your system CLASSPATH variable. Here is some quick’n’dirty C code you can add to Netbeans launcher to make it launch ECJ instead (sorry, no way i can attach exec here): #include <stdlib.h> #include <iostream> #include "jvmlauncher.h" /* * */ int main(int argc, char** argv) { std::list<std::string> progArgs; std::list<std::string> opts; for (int i = 1; i < argc; i++) { char* arg = argv[i]; progArgs.push_back(arg); } //opts.push_back("-classpath d:/Libs/ecj/ecj.jar"); JvmLauncher launcher; launcher.initialize("1.5"); std::string javapath; bool java_exists = launcher.getJavaPath(javapath); std::cout << "Java: " << java_exists << " " << javapath << std::endl; launcher.start("org.eclipse.jdt.internal.compiler.batch.Main", progArgs, opts, true, 0); return (0); } You can get original code here: (use platf_launcher, looks like it’s the same code I’ve downloaded few months ago) Hope it help’s you in some way. Just remember to open/edit launcher in Netbeans 🙂 Pingback: JavaPins
https://jdevel.wordpress.com/2010/07/02/how-to-use-ecj-compiler-in-netbeans/
CC-MAIN-2017-43
refinedweb
308
64.51
Contents tagged with CAB Learning the Model View Presenter Pattern The guys over at Patterns and Practices got it right. They've put together a package (available via a CodePlex project here) on learning and understanding the Model View Presenter Pattern (MVP). It's kind of a "mini-guidance" package and not the big behemoth you normally see from these guys that: - Provides guidance on how MVP to promotes testability and separation of concerns within the UI - Illustrates how to implement MVP with standard ASP.NET - Illustrates how to implement MVP with ASP.NET and the Composite Web Application Block The package contains full documentation on the pattern, unit tests, and source code (for both WinForms and CAB) demonstrating it. Very nice and very easy to digest! Check it out here if you're just getting started and want to see what MVP is about. Taming the ActionCatalog in SCSF The Smart Client Software Factory provides additional capbility above and beyond what CAB (the Composite Application UI Block) has. A little known gem is the ActionCatalog which can ease your pain in security trimming your application. For example suppose you have a system where you want to hide a menu item from people that don't have access to it. This is pretty typical and generally ends up in having to scatter your code with if(User.IsInRole("Administrator")) statements, which can get pretty ugly real quick. The ActionCatalog system in SCSF helps you avoid this. Here's a typical example. I've created a new Business Module and in the ModuleController I'm extending the menu by adding items to it: public class ModuleController : WorkItemController { public override void Run() { ExtendMenu(); } private void ExtendMenu() { ToolStripMenuItem conditionalMenu = new ToolStripMenuItem("Conditional Code"); if (canManageUsers()) { conditionalMenu.DropDownItems.Add(new ToolStripMenuItem("Manage Users")); } if (canManageAdministrators()) { conditionalMenu.DropDownItems.Add(new ToolStripMenuItem("Manage Administrators")); } WorkItem.UIExtensionSites[UIExtensionSiteNames.MainMenu].Add(conditionalMenu); } private bool canManageAdministrators() { string userName = Thread.CurrentPrincipal.Identity.Name; return Thread.CurrentPrincipal.Identity.IsAuthenticated && userName.ToLower().Equals("domain\admin"); } private bool canManageUsers() { string userName = Thread.CurrentPrincipal.Identity.Name; return Thread.CurrentPrincipal.Identity.IsAuthenticated && userName.ToLower().Equals("domain\joeuser"); } } For each menu item I want to add I make a call to a method to check if the user has access or not. In the example above I'm checking two conditions. First the user has to be authenticated to the domain, then for each specific menu item I'm checking to see another condition (in this case comparing the user name, however I could do something like check to see if they're in a domain group or not). Despite the fact that I could do a little bit of refactoring here, it's still ugly. I could for example extract the duplicate code on checking to see if the user is authenticated then do my specific compares. Another thing I could do is call out to a security service (say something that wraps AzMan or maybe the ASP.NET Membership Provider) to get back a conditional true/false on the users access. However with this approach I'm still stuck with these conditional statements and no matter what I do, my code smells. Enter the ActionCatalog. A set of a few classes inside of SCSF that makes security trimming easy and makes your code more maintainable. To use the ActionCatalog there are a few steps you have to do: - Create a class to hold your actions - Register the class with a WorkItem - Add conditions for allowing actions to be executed - Execute the actions Setting up the Catalog Let's start with the changes to the ModuleController. You'll add some new methods to setup your actions, conditions, and then execute the actions. In this case the actions are directly manipulating the UI by adding menu items to it, but actions can be anything (invoked or tied to CommandHandlers) so you decide where the most appropriate split is. Here's the modified ModuleController: public class ModuleController : WorkItemController { private ToolStripMenuItem rootMenuItem; public override void Run() { ExtendMenu(); RegisterActionCatalog(); RegisterActionConditions(); ExecuteActions(); } private void ExtendMenu() { _rootMenuItem = new ToolStripMenuItem("Action Catalog"); WorkItem.UIExtensionSites[UIExtensionSiteNames.MainMenu].Add(rootMenuItem); } private void ExecuteActions() { ActionCatalogService.Execute(ActionNames.ShowUserManagementMenu, WorkItem, this, _rootMenuItem); ActionCatalogService.Execute(ActionNames.ShowAdministratorManagementMenu, WorkItem, this, _rootMenuItem); } private void RegisterActionConditions() { ActionCatalogService.RegisterGeneralCondition(new AuthenticatedUsersCondition()); ActionCatalogService.RegisterSpecificCondition(ActionNames.ShowUserManagementMenu, new UserCondition()); ActionCatalogService.RegisterSpecificCondition(ActionNames.ShowAdministratorManagementMenu, new AdministratorCondition()); } private void RegisterActionCatalog() { WorkItem.Items.AddNew<ModuleActions>(); } Here we've added an RegisterActionCatalog(), RegisterActionConditions(), and ExecuteActions() method (I could have put these into one method but I felt the act of registering actions, conditions and executing them voilated SRP so they're split out here). Action Conditions ActionNames is just a series of constants that I'll use to tag my action methods later using the Action attribute. The conditions are where the security checks are performed. Here's the general condition first which ensures any action is performed by an authenticated user: class AuthenticatedUsersCondition : IActionCondition { public bool CanExecute(string action, WorkItem context, object caller, object target) { return Thread.CurrentPrincipal.Identity.IsAuthenticated; } } Next are specific conditions for each action. As you saw from the AuthenticatedUsersCondition you do get the action passed into to the CanExecute call so you could either pass this off to a security service or check for each action in a common method. I've just created separate classes to handle specific actions but again, how you organize things is up to you. class UserCondition : IActionCondition { public bool CanExecute(string action, WorkItem context, object caller, object target) { string userName = Thread.CurrentPrincipal.Identity.Name; return userName.ToLower().Equals("domain\joeuser"); } } class AdministratorCondition : IActionCondition { public bool CanExecute(string action, WorkItem context, object caller, object target) { string userName = Thread.CurrentPrincipal.Identity.Name; return userName.ToLower().Equals("domain\admin"); } } Both conditions contain the same code as before but are separated now and easier to maintain. Finally we call the Execute method on the actions themselves. Execute will pass in a work item (in this case the root workitem but it could be a child work item if you wanted), the caller and a target. In this case I want to add menu items to the UI so I'm passing in a ToolStripMenuItem object. The ModuleActions class contains our actions with each one tagged with the Action attribute. This keeps our code separate for each action but still lets us access the WorkItem and whatever objects we decide to pass into the actions. The Action Catalog Itself public class ModuleActions { private WorkItem _workItem; [ServiceDependency] public WorkItem WorkItem { set { _workItem = value; } get { return _workItem; } } [Action(ActionNames.ShowUserManagementMenu)] public void ShowUserManagementMenu(object caller, object target) { ToolStripMenuItem conditionalMenu = (ToolStripMenuItem) target; conditionalMenu.DropDownItems.Add(new ToolStripMenuItem("Manage Users")); } [Action(ActionNames.ShowAdministratorManagementMenu)] public void ShowAdministratorManagementMenu(object caller, object target) { ToolStripMenuItem conditionalMenu = (ToolStripMenuItem)target; conditionalMenu.DropDownItems.Add(new ToolStripMenuItem("Manage Administrators")); } } Registering The Action Strategy Calling ActionCatalogService.Execute isn't enough to invoke the action. In order for your Action to be registered (and called) the ActionStrategy has to be added to the builder chain. The ActionStrategy isn't added by default to an SCSF solution (even though you can resolve the IActionCatalogService since services and strategies are separate). Without the strategy in the builder chain, when it constructs the object it doesn't take into account the Action attribute. So you need to add this to a stock SCSF project to get the action registered: protected override void AddBuilderStrategies(Builder builder) { base.AddBuilderStrategies(builder); builder.Strategies.AddNew<ActionStrategy>(BuilderStage.Initialization); } Once you've done this your action is registered and called when you invoke the catalog.Execute() method. A few things about actions: - You don't have to call catalog.CanExecute for your actions. Just call catalog.Execute(). The Execute method makes a call to CanExecute to check if the action is allowed - You have to register an implementation of IActionCondition with the catalog in order to do checks via CanExecute. If you don't register a condition, any action is allowed Alternative Approach There are lots of ways to use the ActionCatalogService, this is just one of them. For example in your ModuleController you can set everything up, disable all commands, then execute your ActionCatalog which will enable menu items based on roles and security. The ActionCatalog lets you keep your execution code separate from permissions management and who can access what. This is a simple example but with little effort you can have this call out to say a claims based WCF service, retrieve users and roles from something like an ASP.NET Membership Provider, and make applying feature level security (including UI trimming) to your Smart Client a breeze! Hope that helps understand the ActionCatalog in SCSF! It's a pretty cool tool and can be leveraged quite easily in your apps. Acropolis, CAB, WPF, and the future "Acropolis, the future of Smart Client" So sayeth Glenn Block, product lead for the Smart Client Software Factory and CAB. Glenn's a good friend and he's just doing his job, but I felt a little shafted when Acropolis popped up on the scene. I mean, after the last few weeks of CAB is complex and CAB is this and CAB is that, the last thing we need is a CAB replacement but here it comes and it's called Acropolis. There were many requests to ship a WPF version of SCSF/CAB and well, we're actually doing it now with the SCSFContrib project up on CodePlex. Is Acropolis a WPF version of CAB? We'll see but Glenn says "Acropolis takes the concepts of CAB to levels that folks in p&p might have never dreamed". From the initial reaction I'm seeing from people like Chris Holmes and Oren, Acropolis doesn't look all that impressive. Another wrapper on top of WPF, a little orchestration thrown in to "wire up components and dependencies" and the promise of building apps without writing or generating any code. I've heard this story before with CASE and like Oren, I see ugly XAML (or XML or XML-like) code being behind all this which doesn't give me a warm and fuzzy. I have yet to setup Acropolis and take it for a real test drive so I have to act like the movie reviewer who's never seen the movie but heard other reviews and has some initial reactions from the trailer. If CAB wasn't on the scene, this would be a great. It's hard enough to get deep into XAML as it is, so layering more complexity on top of that requires something that will help a developer, not hinder him. True, you can still (and will) rip open the XAML to figure out what's going on and make those adjustments but at least it's not that complex right now with POWPF (plain old WPF if there is such a thing). It's 2007 and we've evolved (almost) to the point where we can trust designers and editors. I still have to tweak the .designer generated files [sometimes] to get the right objects parenting in a WinForm app, but I consider that part of the territory. However when I look at what is behind the Acropolis XAML it makes me shudder. There was a quote from another blog that really disturbed me "Probably the best suggestion I can give to my customers, as I always do, is to take inspiration from all of these solutions and to build his own one". Wow. Last option I would ever say to someone especially if there's something out there to do the heavy lifting for you. What bothers me about this whole thing is the MS statement of "we currently have no further plans for SCSF releases". I bought into Software Factories and thought the implementation Microsoft chose (the GAT and GAX) was a good option. Building my own factories or modifying others isn't that difficult and I can express what I really intend in a factory quite easily. With no future releases it means not only CAB is stopped in its tracks, so is SCSF. We just launched the SCSFContrib project which was basically a way to extend the core without touching it, however that restriction now becomes a bit of a roadblock, and we haven't really even got rolling on the project yet. Maybe we need to go one step further and allow the core of CAB to be modified/rewritten/extended and let the community evolve it. Is that something that would be useful? I mean, after the debate that raged on and Jeremy Miller banging out his own "roll your own CAB framework" maybe we need to open the heart of the beast and give it an implant that will let it live past the Acropolis phase. Some of us have invested already in one framework and I don't think there's a cost benefit to shift to another one, although that seems like the path we're being pushed down. Maybe the SCSFContrib project needs to be modified to support core changes and really divorce CAB from it's over architected implementation. A CAB where the guts are abstractions might help support a more popular community driven adoption and get it past the dependency on using MS tools. How about a CAB where you can use log4net, or Windsor, or pico? If Oren can build his own Event Broker in hours and Jeremy can instruct people on building your own CAB over a dozen blog posts I don't see why this isn't possible given some help from the world around us. Efficiency vs. Effectiveness, the CAB debate continues There's been two great posts on the CAB debate recently that were interesting. Jeremy Miller had an excellent post over the brouhaha, citing that he really isn't going to be building a better CAB but supports the new project we recently launched, SCSFContrib. I think Jeremy's excellent "Roll your own CAB" series is good, but you need to take it in context and not look at it as "how to replace CAB" but rather "how to learn what it takes to build CAB". Chris Holmes posted a response called Tools Are Not Evil from Oren's blog entry about CAB and EJB (in response to Glenn Block's enty, yeah you really do need a roadmap to follow this series of blog posts). Oren's response to Chris Holmes post got me to write this entry. In it he made a statement that bugged me: "you require SCSF to be effective with CAB" Since this morning, it looks like he might have updated the entry saying he stands corrected on that statement but I wanted to highlight the difference between being efficient with a tool, and being effective with the technology the tool is supporting. Long before SCSF appeared, I was groking CAB as I wanted to see if it was useful for my application or not and what it was all about. That took some time (as any new API does) and there were some concepts that were alien but after some pain and suffering I got through it. Then SCSF came along and it enabled me to be more efficient with CAB in that I no longer had to write my own controller, or implement an MVP pattern myself. This could be done by running a single recipe. Event the entire solution could be started for me with a short wizard, saving me a few hours I would have taken otherwise. Did it create things I don't need? Probably. There are a lot of services there that I simply don't use however I'm not stoked about it and ignore them (sometimes just deleteting them from the project afterwards). The point is that SCSF made me more efficient in how I could leveage CAB, just like ReSharper makes me a more efficient developer when I do refactorings. Does it teach me why I need to extract an interface from a class? No, but it does it in less time than it would take manually. When I mentor people on refactoring, I teach them why we do the refactoring (using the old school manual approach, going step by step much like how the refactorings are documented in Martin Fowlers book). We talk about why we do it and what we're doing each step of the way. After doing a few this way, they're comfortable with what they're doing then we yank out ReSharper and accomplish 10 minutes of coding in 10 seconds and a few keystrokes. Had the person not known why they're doing the refactoring (and what it is) just right-clicking and selecting Refactor from the menu would mean nothing. ReSharper (and other tools) make me a more efficient developer, but you still need to know the what and why behind the scenes in order to use the tools. I compare it to race car driving. You can give someone the best car on the planet, but if they just floor it they'll burn the engine out and any good driver worth his salt in any vehicle could drive circles around you. Same as development. I can code circles around guys that use wizards when they don't know what the wizard produces or why. Knowing what is happening behind the scenes and the reason behind it, makes using tools like ReSharper that much more value-added. SCSF does for CAB what ReSharper does for C# in my world and I'll take anyone that knows what they're doing over guys with a big toolbox and no clue why they're using them anyday. SC). Reusability vs. RYO Every so often, a topic brushes by my RSS feeds that I have to jump into and comment on. The latest foray is a conversation between Chris Holmes, Jeremy Miller, and Oren Eini. It started with Oren and a post about not particularly caring for what the Microsoft Patterns & Practices guys are producing (EntLib, CAB, SCSF, etc.) and ballooned here, here, and here. Oren started down the path that CAB (and other components produced by P&P) was overly complex and unnecessary. I'll focus on CAB but there are other smatterings of things from EntLib here. The main points Oren was getting across (if I read him correctly) was lack of real world applications backing what P&P is producing and overly complex solutions for simple(r) problems. Oren put together his version of the policy injection block (a recent addition to EntLib) in 40 minutes. Last night I was reading Jeremy Millers response and needed to chime in as I'm very passionate about a few things, namely Agile software development and CAB.. Adding a splash screen to a CAB application Been awhile since I blogged as I've been sort of out of it missing the MVP Summit and all. Here's a simple way to add a splash screen to your Composite UI Application Block (CAB) based applications. It's pretty simple to implement a splash screen. This is a basic form that will popup with a logo or whatever of your choosing while the application loads. The code below is based on applications generated with the June 2006 version of the Smart Client Software Factory, but the idea is the same and can be applied to any CAB application. First, create the splash screen. This will just be a simple Winform you add to your Shell project. Call it ShellForm and give it a splash image to display. it helps if you change a few properties to make it more "splashy": - Change the StartPosition property to CenterScreen - Change the ShowInTaskbar property to False - Change the FormBorderStyle property to None Now drop a picture box on the form and load up your image. Any image will do, but you'll probably want to size the splash screen to match the size of the image (otherwise some shearing might occur). Now we need to modify two files. ShellApplication.cs and SmartClientApplication.cs. In ShellApplication.cs all you need to do is change the call to the base class of SmartClientApplication to accept your ShellForm. Change the declaration from this: 22 class ShellApplication : SmartClientApplication<WorkItem, ShellForm> to this: 22 class ShellApplication : SmartClientApplication<WorkItem, ShellForm, SplashForm> SplashForm is the name of the class you created for the new form. Finally we get down to the meat of the splash screen. In SmartClientApplication.cs we need to do two things, recognize the new parameter being passed into the class and get the splash screen going. First add a generic to the declaration of the SmartClientApplication class as TSplash: 25 public abstract class SmartClientApplication<TWorkItem, TShell, TSplash> : FormShellApplication<TWorkItem, TShell> Then initialize it like the WorkItem: 25 public abstract class SmartClientApplication<TWorkItem, TShell, TSplash> : FormShellApplication<TWorkItem, TShell> 26 where TWorkItem : WorkItem, new() 27 where TShell : Form 28 where TSplash : Form, new() Add a private member variable to hold the splash screen (using the generic type "TSplash"): 30 private TSplash splash; Create the object in the constructor: 35 public SmartClientApplication() 36 { 37 splash = new TSplash(); 38 splash.Show(); 39 splash.Update(); 40 } After the shell gets created, we want to kill off the splash screen. We'll do this in the AfterShellCreated method of the SmartClientApplication class by adding an event handler when the Shell gets activated. Change your AfterShellCreated method to look like this: 46 protected override void AfterShellCreated() 47 { 48 base.AfterShellCreated(); 49 Shell.Activated += new EventHandler(ShellActivated); 50 } And create the event handler. The handler will remove the Shell.Activated event and dispose of the Splash form: 57 private void ShellActivated(object sender, EventArgs e) 58 { 59 Shell.Activated -= new EventHandler(ShellActivated); 60 splash.Hide(); 61 splash.Dispose(); 62 splash = null; 63 } That's it! A cool looking splash screen for your CAB application in about 10 minutes. Note: There was a long thread here on the GDN forums (moved to CodePlex) on doing this. That technique works as well, and gives you the ability to intercept the "loading" of the application as it goes through it's paces. We're using it for one app, but the technique above is a more simple approach that just gets the job done so you might find it easier to implement. Using Dependency Injection with CAB I was working through a problem tonight regarding dependency injection and CAB. CAB provides a facility to inject services and whatnot into other class using ObjectBuilder, Microsoft's DI framework. ObjectBuilder isn't the same as a DI/IOC container like Windsor Container or Spring.NET (or Jeremy Millers excellent StructureMap) but more like a framework for building containers. However in CAB it serves the purpose we need. Let's say I have a service that performs lookups and returns me lists of items from some backend system. I would like to use this LookupService in various modules but I don't want the modules responsible for creating the service (especially since I only want one of them and don't want to deal with singletons) and I want an easy way to ensure the service is loaded and ready to go when I need it. Here's where CAB will help you with this. First let's look at our service implementation: public class LookupService : ILookupService { public List<KeyValuePair<int, string>> Items { get { List<KeyValuePair<int, string>> items = new List<KeyValuePair<int, string>>(); items.Add(new KeyValuePair<int, string>(1, "Item 1")); items.Add(new KeyValuePair<int, string>(1, "Item 2")); return items; } } } This is a straight forward service that returns a generic List<> of KeyValuePairs<>. I might use this in my UI in a combo box or whatever, but it's just a lookup of items. The implementation here is hard coded, but you could just as easily have this call out to a database, do an asynchronous web service call, whatever you need. To share the service, I'll use the Infrastructure.Module project in my SCSF generated solution. This module gets loaded first and using SCSF I have it set to be a dependency so whenever the system loads any module I'll load this one first, ensuring my service is there. Here's my ProfileCatalog.xml that shows the dependency. <SolutionProfile xmlns=""> <Section Name="Services"> <Modules> <ModuleInfo AssemblyFile="Infrastructure.Module.dll" /> </Modules> </Section> <Section Name="Apps"> <Dependencies> <Dependency Name="Services" /> </Dependencies> <Modules> <ModuleInfo AssemblyFile="Project.dll" /> </Modules> </Section> </SolutionProfile> The module dependency is part of SCSF so it won't exist if you're just using CAB. In my profile catalog, the moment the Project.dll module loads, it will first load it's dependency module(s) from the Services section of the XML file. You can have as many services as you want here and they'll load in reverse order that they're listed in the file. To instantiate the service and make it available, I have to load it up and add it to the RootWorkItem and it's list of services. This is done in the ModuleController.cs in the Infrastructure.Module project: public class ModuleController : WorkItemController { public override void Run() { AddServices(); ExtendMenu(); ExtendToolStrip(); AddViews(); } private void AddServices() { WorkItem.RootWorkItem.Services.AddNew<LookupService, ILookupService>(); } private void ExtendMenu() { } private void ExtendToolStrip() { } private void AddViews() { } } If I were to load it up like a regular WorkItem and only use this code: private void AddServices() { WorkItem.Services.AddNew<LookupService, ILookupService>(); } Then I would be loading it into the services for this module only, which is great, but I want this for all modules to use so I add it to my RootWorkItem. RootWorkItem is a property of any WorkItem that refers to the one and only root item created by the Shell. This way I know there's only one and I can access it from any module anywhere. Once it's been added to the WorkItems list of Services, I can inject it into any module I need. I'll inject it into my presenter class as that's where I'll use it. The presenter will call the service to get it's values, and set the View with those values to update some GUI element (implementation of the View isn't shown but it just takes the values and binds them to a listbox or whatever you would use them for). I can inject it into the Presenter class two different ways. First, I can use the [ServiceDependency] tag in a parameter passed to the constructor of the Presenter: public class ProjectListViewPresenter : Presenter<IProjectListView> { private ILookupService _lookupService; public ProjectListViewPresenter([ServiceDependency] ILookupService lookupService) { _lookupService = lookupService; } } Not that nowhere do I have to call the constructor, this is done with the AddViews method in the ModuleController and it knows that it needs a type of ILookupService to inject during construction. The constructor sets a private member variable of type ILookupService to the value passed in. ObjectBuilder knows it needs to get an object of that type and will find it using the ServiceLocator service, which is constructed by the Shell. The second way is I can set a property and decorate it using the [ServiceDependency] tag like so: public class ProjectListViewPresenter : Presenter<IProjectListView> { private ILookupService _lookupService; [ServiceDependency] public ILookupService LookupService { get { return _lookupService; } set { _lookupService = value; } } } This is the same effect and is done whenever the object is created. Use one technique, not both as they'll both be called. Even though it's the same service object, it's just a waste to do it twice. Finally I just use the service in a method in my presenter when it's ready to update the view: public class ProjectListViewPresenter : Presenter<IProjectListView> { private ILookupService _lookupService; [ServiceDependency] public ILookupService LookupService { get { return _lookupService; } set { _lookupService = value; } } public override void OnViewReady() { View.Items = LookupService.Items; base.OnViewReady(); } } The end result is that I have a loosely coupled service that's injected into my presenter and provides my view with the services it needs. You can use either technique to set the service in the presenter and the great thing is that using something like Rhino mocks, you don't need to create the implementation of the service so writing presenter tests is a breeze with this technique, as you can setup whatever conditions you want for your tests. Using MSBuild with Smart Client Software Factories The Smart Client Software Factory (SCSF) is an awesome tool. It comes in the form as a guidance package from the patterns and practices guys and kicks off your initial Smart Client app with various services, several projects, and a shell application all built on top of the Composite Application UI Block (CAB). I have found one problem with the current version of SCSF and that's when you generate the initial solution and try to build it using MSBuild. Create a solution using the factory and try building the .sln file with MSBuild. You'll get a host of errors about projects referencing projects that don't exist. Here's some sample output: SmartClientSolution1.sln : Solution file warning MSB4051: Project {90BC9A2E-DF32-4D50-AB7A-2967B8F5D8D9} is referencing a project with GUID {BE39A9ED-D4C6-42E7-91D6-63D9B1D185C6}, but a project with this GUID was not found in the .SLN file. I believe this might be because the .csproj/.sln file is generated before the GUIDs are. It doesn't have a problem in the IDE because it references projects by relative file path, but when you try to build a solution using MSBuild (like via an automated build server) the build fails. Just to clarify this. The GUIDs in the solution file and csproj files are correct however where each project references another in the csproj file it contains both a reference location and a GUID. It's that GUID that's incorrect. Here's the section in each .csproj I'm referring to: <ItemGroup> <ProjectReference Include="..\Infrastructure.Interface\Infrastructure.Interface.csproj"> <Project>{C0143C3B-2D43-4CC3-B593-236D4097F23F}</Project> <Name>Infrastructure.Interface</Name> </ProjectReference> <ProjectReference Include="..\Infrastructure.Library\Infrastructure.Library.csproj"> <Project>{90BC9A2E-DF32-4D50-AB7A-2967B8F5D8D9}</Project> <Name>Infrastructure.Library</Name> </ProjectReference> </ItemGroup> You can fix this without a problem. To do so just open up the .csproj file and in the ItemGroup section, paste in the correct GUIDs for each project it's referring to from the original .sln file. The references that need to be fixed are: - Infrastructure.Library referencing Infrastructure.Interface - Infrastructure.Module referencing Infrastructure.Interface - Shell referencing Infrastructure.Interface - Shell referencing Infrastructure.Library Once you've updated the GUIDs in the .csproj files, you'll be good to go for automated builds of your CAB projects. I've logged this as an issue here on the new CodePlex site so hopefully they'll get to fixing this as it was a real pain to find.?
http://weblogs.asp.net/bsimser/Tags/CAB
CC-MAIN-2014-49
refinedweb
5,138
52.49
Taslak DXF Description Draft DXF is a software module used by the Std Open, Std Import and Std Export commands to handle the DXF file format. Qcad drawing exported to DXF, which is subsequently opened in FreeCAD Importing Two importers are available, which one is used can be specified under Edit → Preferences... → Import-Export → DXF. One is built-in, C++-based and fast, the other is legacy, coded in Python, slower, and requires the installation of an add-on, but can handle some entities better and can create more refined FreeCAD objects. Both support all DXF versions starting from R12. 3D solids inside a DXF file are stored under a binary ACIS/SAT blob, which at the moment cannot be read by FreeCAD. C++ importer This importer can import the following DXF objects: - lines - polylines (and lwpolylines) - arcs - circles - ellipses - splines - points - texts and mtexts - dimensions - leaders - blocks (only geometry, texts, dimensions and attributes inside blocks are skipped) - layers - paper space objects Legacy importer This importer can import the following DXF objects: - lines - polylines (and lwpolylines) - arcs - circles - ellipses - splines - 3D faces - texts and mtexts - leaders - layers Exporting There are also two exporters. The legacy exporter exports to the R12 DXF format, the C++ exporter to the R14 DXF format. Both formats can be handled by many applications. C++ exporter Some of the features and limitations of this exporter are: - All FreeCAD 2D geometry is exported, except Draft CubicBezCurves, Draft BezCurves and Draft Points. - Straight edges from faces of 3D objects are exported, but curved edges only if they are on a plane parallel to the XY plane of the global coordinate system. Note that a DXF created from 3D objects will contain duplicate lines. - Texts and dimensions are not exported. - Colors are ignored. - Layers are mapped from object names. Legacy exporter Some of the features and limitations of this exporter are: - All FreeCAD 2D geometry is exported, except Draft Points. But ellipses, B-splines and Bézier curves are not exported properly. - 3D objects are exported as flattened 2D views. - Compound objects are exported as blocks. - Texts and dimensions are exported. - The colors in the DXF are based on the line color of objects. Black is mapped to "ByBlock", other colors are mapped using AutoCAD Color Index (ACI) colors. - Layers are mapped from layer and group names. When groups are nested, the deepest group gives the layer name. Installing For licensing reasons, the required DXF import/export libraries needed by the legacy version of the importer are not part of the FreeCAD source code. For more information see: FreeCAD and DXF Import. Preferences See Import Export Preferences. DWG Because the DWG format is a proprietary, closed and undocumented format it is hard for open-source projects like FreeCAD to support it. That is why FreeCAD relies on external converters to read and write DWG files. To import a DWG file a converter is used to create a DXF first, which can then be processed by the FreeCAD DXF importer. When exporting to DWG the opposite conversion happens: the DXF created by the FreeCAD DXF exporter is turned into a DWG. Note that the DXF format allows a 1:1 conversion of the DWG format. All applications that can read and write DWG files can do the same with DXF files, with no data loss. So asking for DXF files instead of DWG files, and supplying DXF files in turn, should not cause any problems. There is built-in support for the following DWG converters: - LibreDWG (open-source, lacks support for some DWG entities). - ODA File Converter (free). - QCAD pro (commercial). introduced in version 0.20 See Import Export Preferences and FreeCAD and DWG Import for more information. Scripting See also: Autogenerated API documentation and FreeCAD Scripting Basics. To export objects to DXF use the export method of the importDXF module. importDXF.export(objectslist, filename, nospline=False, lwPoly=False) - For the Windows OS: use a / (forward slash) as the path separator in filename. Example: import FreeCAD as App import Draft import importDXF doc = App.newDocument() polygon1 = Draft.make_polygon(3, radius=500) polygon2 = Draft.make_polygon(5, radius=1500) doc.recompute() objects = [polygon1, polygon2] importDXF.export(objects, "/home/user/Pictures/myfile.dxf") -
https://wiki.freecadweb.org/Draft_DXF/tr
CC-MAIN-2021-49
refinedweb
699
65.22
Reddit Survey: Introduction to Pandas The data set used here is part of a project from UD651 course on udacity by Facebook. The data from the project corresponds to a survey from reddit.com. You can load the data through the following command. We will first look at the different attributes of this data using the summary() and describe() pandas methods. import pandas as pd import numpy as np #Read csv file reddit = pd.read_csv("").astype(object) #summarize data reddit.describe(include='all', percentiles=[]).T.replace(np.nan,' ', regex=True) The describe() method helped us get an overview of all the data available to us. We also ensured that all the data read was a categorical data. Let us look at the age.range variable in more detail. We can look at the different levels of this variables using the cat.categories property of a Pandas Series. reddit["age.range"].astype('category').cat.categories Index(['18-24', '25-34', '35-44', '45-54', '55-64', '65 or Above', 'Under 18'], dtype='object') This shows there are 7 possible values of this variable and some where no data is available (NA). A more pictorial view of this can be seen using a histogram plot of this. import matplotlib.pyplot as plt import seaborn as sns sns.set(style="darkgrid") %matplotlib inline newOrder = ["Under 18", "18-24", "25-34", "35-44", "45-54", "55-64", "65 or Above"] ax = sns.countplot(x="age.range", data=reddit, order=newOrder) Similarly, we can also plot a distribution of income range. ax = sns.countplot(x="income.range", data=reddit) locs, labels = plt.xticks() ax = plt.setp(labels, rotation=90) One problem with the above plots is that the different levels are not ordered. This can be fixed using ordered Factors, instead of regular factor type variables. Additionally, We need to use a more reasonable x-label for plotting income.range. newLevels = ["100K", ">150K", "20K","30K", "40K", "50K", "70K", "<20K"] reddit["income.range"] = reddit["income.range"].astype('category') reddit["income.range"] = reddit["income.range"].cat.rename_categories(newLevels) newOrder = ["<20K", "20K","30K", "40K", "50K", "70K", "100K", ">150K"] ax = sns.countplot(x="income.range", data=reddit, order=newOrder)
https://sadanand-singh.github.io/posts/pandasintroreddit/
CC-MAIN-2018-30
refinedweb
360
51.44
gMSA for Windows Container — concept Reminder: this article contains technique terms of Microsoft Active Directory, Docker, Kubernetes. Before start I believe most of Windows user who knows Microsoft Active Directory (abbreviation below: AD) service. I use to heard Novell people who said: Microsoft broadcast Directory concept to the Worldwide corp. As core product of Microsoft, a lot of product authentication and authorization around AD, e.g. NTLM in IIS, Windows Desktop login, MSSQL authentication, Windows Cluster, Exchange (there is story…), ADFS (note 1)…etc. By the way. Due to gMSA for my Kubernetes Windows node, therefore our team should be most used gMSA user since last year. Additionally, gMSA implementation that needs AD knowledge. I use to be AD admin for a long time, and have Kubernetes experience. Therefore, I could smoothly implement gMSA for Windows container. Why gMSA Generally, Windows platform programmer usually build AP as Windows service and leverage Domain computer for AD account authentication. This kind of practice that encountered big impact since early stage of container world. Due to container cannot join AD, even you put credential to access DB resource. You still cannot solve user AD authentication issue because of container is not authorized computer. Maybe you can consider LDAP. But that means you need to re-write your code. If you put your domain service account inside the configuration file that decreases security. How to gMSA Once gMSA ready, You just need to declare gMSA into your deployment YAML file. You pod will be like joined domain computer immediately. Tranditionally, system admin needs to perform the following action for domain joining. - Create computer object on Domain controller (you can skip this action). - Perform domain joining to create trust relationship between AD and computer. - Reboot computer to complete domain joining. Regarding above action, it is impossible to perform them inside container because of container lifecycle that is different concept. Even you implemented in the Docker. However, you cannot perform the same action on Windows Pod. I would say that Microsoft realized this issue, therefore we saw the gMSA in recent years. Ideally, gMSA is to allow domain computer to use AD account. There are the following features. In the AD - You need enable gMSA in the AD domain - gMSA name is end with “$”. It is similar computer object. - When setup permission, you need to choose service account object type, e.g. MSSQL DB permission assignment. - The account authorization binds at domain computer tier. Therefore, Windows node needs to join AD domain. - Password is managed by AD domain controller. That is to say, you don’t need to change password any more. - Due to no password in the connection string OR configuration file. You don’t need to worry about password leak issue because of no one know password. It is more secure. - Due to AD can assign to a group, therefore you just need to ensure your Windows nodes are member of this AD group. Regarding this requirement, you might need to plan automation well. - A domain computer can be assigned to multiple gMSA. - If you need Windows node auto scaling, please request an delegated OU with computer object creation/removal permission. Arrage a well talk meeting with AD admin. :) In the Docker - All containers on the machine joining the domain that can get gMSA permission. - Docker host admin cannot limit docker container to use particular gMSA only. In the Kubernetes - A Kubernetes cluster can configure multiple gMSA. All of Windows node need to join AD domain. - Kubernetes Cluster admin leverages CRD (custom resource definition) to manage which one service account of namespace to get which one gMSA permission. Please have relationship overview, otherwise you might get unexpected result. - When RestfulSet (or Job) declares gMSA, it will call a Kubernetes inside web service for authorization. If RestfulSet (or Job) does not have permission, Cluster won’t allow your pod creation. - Currently, gMSA web service only can run on the Linux node. - Till 2020/12, Linux pod cannot use gMSA because of it is not on Windows node. Maybe Microsoft will allow Linux Pod in the future. :P From my experience, Kubernetes admin needs to plan infra well. Especially, Windows node auto scaling with domain joining. Once infra ready, cluster admin need to manage gMSA assignment. From my point of view, I would say Microsoft is trying to leverage to gMSA for AD plus Windows container. I believe they want more market share. At the end. This article focus on concept. I will share “How to” in the next article. Appendix note 1: ADFS is a Microsoft modern authentication solution.
https://aaronsssya.medium.com/gmsa-for-windows-container-concept-17d620168215?source=user_profile---------3----------------------------
CC-MAIN-2021-39
refinedweb
764
59.7
namespace "." See SQL::Translator::Producer::XML::SQLFairy for details of this format. You do not need to specify every attribute of the Schema objects as any missing from the XML will be set to their default values. e.g. A field could be written using only; <sqlf:field Instead of the full; <sqlf:field <sqlf:comments></sqlf:comments> </sqlf:field> If you do not explicitly set the order of items using order attributes on the tags then the order the tags appear in the XML will be used. the the schema objects to be written as either xml attributes or as data elements, in any combination. While this allows for lots of flexibility in writing the XML the result is a great many possible XML formats, not so good for DTD writing, XPathing etc! So we have moved to a fixed version described in SQL::Translator::Producer::XML::SQLFairy. This version of the parser will still parse the old formats>
http://search.cpan.org/~frew/SQL-Translator-0.11015/lib/SQL/Translator/Parser/XML/SQLFairy.pm
CC-MAIN-2015-11
refinedweb
160
58.92
iOS-Swift User Profile Download a sample project. You will need to login for the sample to be preconfigured. Before Starting You should be familiar with previous tutorials. This tutorial assumes: - You're using the Lock library for handling login. Make sure you've integrated this library into your project and you're familiar with it. If you're not sure, check out the login tutorial first. - You're using the Auth0.swift and SimpleKeychain dependencies. It's recommended that you take a look at the session handling tutorial first. Fetch the User Profile The first step is to fetch the user profile. To do so, you need a valid idToken first. Check out the session handling tutorial if you're not sure about the idToken. You need to call a function from the Lock module that allows you to fetch the user profile given an idToken: import Lock let client = A0Lock.sharedLock().apiClient() client.fetchUserProfileWithIdToken(idToken, success: { profile in // You've got the user profile here! // You might want to store it in a safe place. You can use SimpleKeychain: let keychain = A0SimpleKeychain(service: "Auth0") let profileData = NSKeyedArchiver.archivedDataWithRootObject(profile) keychain.setData(profileData, forKey: "profile") }, failure: { error in // check the session handling tutorial for hints on what to do in case of a failure }) Show User Profile's Data i. Default info Showing the information contained in the user profile is pretty simple. You only have to access its properties, for instance: let name = profile.name let email = profile.email let avatarURL = profile.picture Check out the A0UserProfile class documentation to learn more about its fields. ii. Additional info Besides the defaults, you can handle more information that is contained within any of the following dictionaries: a. User Metadata The userMetadata dictionary contains fields related to the user profile that can be added from client-side (e.g. when editing the profile). This is the one we're going to work with in this tutorial. You can access its fields as follows: let firstName = profile.userMetadata["first_name"] as? String let lastName = profile.userMetadata["last_name"] as? String let country = profile.userMetadata["country"] as? String let isActive = profile.userMetadata["active"] as? Bool The strings you use for subscripting the userMetadatadictionary, and the variable types you handle, are up to you. b. App Metadata The appMetadata dictionary contains fields that are usually added via a rule, which is read-only for the native platform. c. Extra Info The extraInfo dictionary contains any other extra information stored in Auth0. That information is read-only for the native platform. For further information on metadata, see the full documentation. Update the User Profile You can only update the user metadata. In order to do so, you need to perform a patch: import Auth0 import Lock let idToken = ... // the idToken you obtained before let profile = ... // the A0Profile instance you obtained before Auth0 .users(token: idToken) .patch(profile.userId, userMetadata: ["first_name": "John", "last_name": "Appleseed", "country": "Canada"] .start { result in switch result { case .Success: // deal with success case .Failure(let error): // deal with failure } }
https://auth0.com/docs/quickstart/native/ios-swift/04-user-profile
CC-MAIN-2016-44
refinedweb
506
52.05
01 July 2011 17:46 [Source: ICIS news] LONDON (ICIS)--The first ?xml:namespace> “[It reflects] Asian parity and the market supply/demand balance in general, in Other producers are targeting increases for July contracts and their proposals include hikes to €1,090/tonne or around €1,100/tonne. A lower price was also recorded as being on the table. While producers stress the importance of Asian parity and supply/demand, buyers refuse to omit the significant drop in ethylene from discussions. “It was clear that the price should increase despite the big decrease in the ethylene price,” the buyer involved in the first settlement said. Earlier on Friday, customers said they were unwilling to accept anything other than a rollover or even a decrease. Reports did filter through, however, of some customers accepting the idea of an increase, just not up to the levels producers are targeting. The price was concluded on a free delivered (FD) northwest Europe (NWE) basis. ($1 = €0.69) For more on MEG,
http://www.icis.com/Articles/2011/07/01/9474562/initial-europe-july-meg-settles-up-29tonne-at-1044tonne.html
CC-MAIN-2014-52
refinedweb
168
53.61
The main memcached header holding commonly used data structures and function prototypes. More... #include <pthread.h> #include <config_static.h> #include <memcached/protocol_binary.h> #include <memcached/engine.h> #include <memcached/extension.h> #include "cache.h" #include "topkeys.h" #include "sasl_defs.h" #include "stats.h" #include "trace.h" #include "hash.h" #include <memcached/util.h> Go to the source code of this file. The main memcached header holding commonly used data structures and function prototypes. Append an indexed stat with a stat name (with format), value format and value. Common APPEND_NUM_FMT_STAT format. Append a simple stat with a stat name, value format and value. Size of an incr buf. Initial size of the sendmsg() scatter/gather array. Initial size of list of items being returned by "get". Maximum length of a key. Initial number of sendmsg() argument structures to allocate. High water marks for buffer shrinking. Initial size of list of CAS suffixes appended to "gets" lines. Ship tap log to the other end. This state differs with all other states in the way that it support full duplex dialog. We're listening to both read and write events from libevent most of the time. If a read event occurs we switch to the conn_read state to read and execute the input message (that would be an ack message from the other side). If a write event occurs we continue to send tap log to the other end. Convert a state name to a human readable form. exported globals
https://dev.mysql.com/doc/dev/mysql-server/latest/memcached_8h.html
CC-MAIN-2020-24
refinedweb
247
72.22
William R. Dieter and James E. Lumpp, Jr. Department of Electrical and Computer Engineering University of Kentucky Lexington, KY 40506, USA {dieter,jel}@dcs.uky.edu, The checkpointing library is simple to use, flexible, and efficient. Virtually all of the overhead of the checkpointing system comes from saving the checkpoint to disk. The checkpointing library added no measurable overhead to tested application programs when they took no checkpoints. Checkpoint file size is approximately the same size as the checkpointed process's address space. On the current implementation WATER-SPATIAL from the SPLASH2 benchmark suite saved a 2.8 MB checkpoint in about 0.18 seconds for local disk or about 21.55 seconds for an NFS mounted disk. The overhead of saving state to disk can be minimized through various techniques including varying the checkpoint interval and excluding regions of the address space from checkpoints. Computer systems are prone to hardware and software failures and the probability that a machine will crash before a process finishes running grows in proportion to the process's run time. A process can save its state in a checkpoint to help tolerate system downtime. A multithreaded process has both private state and shared state. A thread's private state includes its program counter, stack pointer, and registers. Its shared state includes everything common to all threads in the process, such as the address space and open file state. A multithreaded checkpointing library must save and recover the process's shared state and each thread's private state. User-level thread libraries are implemented outside the kernel using timers to preempt threads when their time slice is over. Implementing a checkpointing library for a user-level threads package is a straightforward extension of a single-threaded checkpointing library because a user-level multithreaded process is no different from a single-threaded process from the operating system's point of view. User-level threads cannot take advantage of a symmetric multiprocessor (SMP), however, because the kernel is not aware of the threads. Thus it cannot schedule them to run concurrently on separate processors. With kernel-level threads, like LinuxThreads in Linux or lightweight processes in Solaris, the kernel schedules threads and keeps track of their state. Not only must the checkpointing library save and restore the address space of the process to recover the thread state, but it must also call the kernel to restart threads during recovery. Hybrid thread libraries like the one found in Solaris, use both kernel-level and user-level threads. User-level threads are scheduled to run inside several kernel-level threads, called light-weight processes (LWP) in Solaris. The library usually starts with one LWP per processor. If a user-level thread makes a blocking call and there are more runnable threads, the thread library starts a new LWP so the whole process does not need to block. A hybrid thread library cannot be checkpointed like a user-threads library because it uses kernel-level threads. We have tested our checkpointing library on several programs in the SPLASH-2 benchmark suite in addition to some simple test programs. The WATER-SPATIAL application ran with no noticeable overhead other than the time to save a checkpoint. It saved a 2.8 MB checkpoint to local disk in about 0.18 seconds and to an NFS mounted disk in about 21.55 seconds. The time to save a checkpoint to disk is about the same as the time required to copy a file of the same size as the checkpoint with the cp command. The rest of the paper is organized as follows. Section 2 discusses related work and section 3 describes how programmers and users use the checkpointing library. Section 4 presents the design and implementation of such a library. Section 5 describes restrictions on programs using the checkpointing library. Finally, section 6 shows experimental results and performance. Checkpointing is a popular way of providing fault-tolerance for computer systems. Both user-level and kernel-level checkpointing systems have been developed for single threaded processes, however, ours is the first to provide support for multithreaded programs. In addition, our system provides this functionality in the form of a user-level library which makes it easier to use and the design is still efficient. Several other user-level checkpointing libraries for single processes run on multiple versions of Unix [12,14,16]. libckpt has many features including asynchronous (forked) checkpointing, incremental checkpointing, memory exclusion and user-directed checkpointing [12]. It has been ported to many different versions of Unix. However, libckpt does not handle multithreaded processes or dynamically linked executables. Condor is a process migration system designed to use idle cycles in the network [14]. When the system decides to migrate a process it checkpoints the process on one machine then restarts it on another. Condor runs on a number of operating systems including Solaris and Linux. It neither supports multithreaded programs nor does it have freely available source code. libckp was developed at AT&T Bell Laboratories to checkpoint Unix processes [16]. In contrast with libckpt, Condor and our own checkpointing library, libckp saves files along with the checkpoint to guarantee they will be the same when the program recovers from a checkpoint. Saving copies of all open files guarantees all the files will exist during recovery and allows libckp to handle arbitrary file I/O access patterns, but it can make the checkpoint much bigger. Many scientific programs do not need the extra guarantees if the user is willing to retain the input and output files and the application only writes to files in sequential order. libckp also does not support multithreaded programs. Process hijacking uses dynamic executable rewriting to add checkpointing to programs that were not compiled with checkpointing support [19]. Process hijacking does not support multithreaded processes. MOSIX and epckpt provide kernel-level checkpointing solutions. MOSIX is a set of kernel extensions which have been ported to BSD and Linux [4,3]. MOSIX uses a kernel module to provide transparent load balancing and process migration. epckpt is a Linux kernel patch that adds support for processes and process groups [1]. It is in an early stage of development and requires patching, recompiling, and installing a new kernel. Neither MOSIX nor epckpt work for multithreaded programs. Process migration in general [11,18] is related to checkpointing. Several process migration facilities, like Condor and MOSIX, use checkpointing to provide process migration. In the case of process migration a process is transported through space to another machine. In checkpointing the process is transported to a later time on the same or a different machine. The difference is that a process may recover from a checkpoint at a later time when the environment has changed. Resources the original process was using may be unavailable when it recovers. Checkpointing for distributed message passing systems has been heavily studied [8]. Most message passing algorithms work to reduce synchronization overhead and handle in-transit messages. Synchronization overhead and in-transit messages are not issues for multithreaded processes. The LinuxHA project [2] is bringing support for high availability to Linux. LinuxHA's failure detection mechanisms could be used with our library to automatically restart programs. Most of the LinuxHA work is focused on replicating processes on different machines for fault-tolerance. Replication can offer better guaranteed bounds on recovery time, but usually requires a duplicate machines to take over for each replicated process when a machine fails. Checkpointing only needs extra machines when a machine fails, and then only enough to replace the failed machines. The program can wait until the the failed machines are repaired if no machines are available and the application can tolerate the delay. The IEEE Portable Application Services Committee (PASC) 1003.1m Checkpointing Restart working group has been developing a standard API for checkpointing [5]. The checkpointing library we introduce here allows, for the first time, LinuxThreads programs to automatically be checkpointed. In addition to checkpointing multithreaded programs our checkpointing library provides features that help meet our goals of being simple to use, flexible, and efficient. Adding checkpointing support to a C program is straightforward with our checkpointing library. The application programmer only needs to add one line to include the checkpoint header file: #include "checkpoint.h"and one line to call checkpoint initialization in main. checkpoint_init(&argc, argv, NULL);checkpoint_init initializes data structures the checkpointing library uses to track thread and file state. Passing argc and argv to checkpoint_init allows the checkpointing library to read options from the command line. The user can control the checkpoint period by passing optional command line arguments to the checkpointing library. The checkpointing library reads all the arguments after the ``-'' argument. For example, % prog - -t periodruns the prog program with a checkpoint period of period seconds. A checkpoint period of 0 disables checkpointing. The user can also pass options to the checkpointing library by putting the options in the CHKPTOPTS environment variable. The programmer can set checkpointing options directly using third argument to checkpoint_init. Checkpoints are automatically stored in prog.chkpt.n where prog is the name of the program and n is the checkpoint number. The user can change the default checkpoint base name with the -b option. To recover from a checkpoint, the user runs the program with the recovery option and specifies a checkpoint file. For example, % prog - -r prog.chkpt.nruns the prog program, loading the state from the checkpointing file prog.chkpt.n. An application program can install callback functions to save any state not saved by the checkpointing library. For example, we have used callback functions to help add checkpointing to the Unify distributed shared memory system [9]. Unify processes communicate through UDP sockets, but the checkpointing library does not save their state. To make checkpointing work, Unify makes sure checkpoints are consistent and uses a recovery callback function to reopen the UDP sockets when it recovers from a failure. A process can install callback functions that will be called before a checkpoint, after a checkpoint, and after recovering from a checkpoint. chkpt_callback_push installs three functions: a pre-checkpoint callback called before each checkpoint, but after all application threads have been stopped, a post-checkpoint callback called after the checkpoint, but before any application thread has been restarted, and a post-recovery callback called after recovering from a checkpoint. Pushing a new set of callback functions does not remove any of the old ones. Instead they are pushed onto a stack. The most recently pushed pre-checkpoint callback function is called last. The most recently pushed post-checkpoint and post-recovery callback functions are called first. The program can remove callback functions in any order using the ID returned by chkpt_callback_push. The pushing and popping mechanism simplifies installing and removing callbacks to handle different kinds of state as a program enters different phases. Our checkpointing library provides memory exclusion similar to that provided by libckpt [12]. Memory exclusion allows the application to specify regions of memory that need not be saved in the checkpoint. Excluding large areas of memory that the application does not need reduces the size of the checkpoint. The difficulty of checkpointing multithreaded programs comes from making sure that the thread library is in a useful state after recovering from a checkpoint. Threads must be carefully restarted in the correct order to match the way they were originally created. The basic idea behind our checkpointing library is simple. During initialization the main thread, the only thread that exists when the program starts, starts the checkpoint thread. After initializing itself, the checkpoint thread blocks with a timed wait on a condition variable. When the timer expires or when another thread calls checkpoint_now the checkpoint thread starts a checkpoint. The checkpoint thread is also responsible for running application callback functions. To take a checkpoint, the checkpointing library blocks all threads, except the main thread, to prevent any threads from changing the process's state while it is being saved. The main thread then saves the process's state and unblocks all the remaining threads. To recover from a checkpoint, the checkpointing library restarts the threads that were running at the time of the checkpoint. The restarted threads block while the main thread loads the process's state from a checkpoint. Then the main thread unblocks the other threads and they continue running from the checkpoint. Section 4.1 and Section 4.2 describe the algorithm in more detail. The difficulty comes from doing everything in the correct order, making sure threads do not try to change the address space while it is being saved, and making sure the process's idea of its state matches the operating system's idea of the state. For example the thread library keeps track of the process IDs of all the threads. The checkpointing library must be able to update the thread library's copies of the thread process IDs. The process state saved in a checkpoint includes the address space, thread registers, thread library state, signal handlers, and open file descriptors. The checkpointing library cannot save every part of the program's state. The unsaved parts lead to the restrictions described in Section 5. A process's address space is made up of several segments. These segments include the code segment, data segment, heap, stack segment, code and data segments for each of the shared libraries linked with the program, and thread stacks. The checkpointing library uses the /proc(4) file system interface to find the segments that are mapped into memory. Figure 1 shows how the checkpointing library takes a checkpoint. Send a signal to application threads. To start a checkpoint, the checkpoint thread sends a signal to each of the application threads. Unlike Solaris, when a thread in Linux receives a signal it enters the signal handler for the signal regardless of the state of the mutex associated with the condition variable [7]. Call pre-checkpoint callbacks. The checkpoint thread calls the pre-checkpoint callbacks. Send a signal to the checkpoint thread. For symmetry the checkpoint thread sends a signal to itself to force itself into its signal handler like all the other threads. Block signals and wait. Once in the signal handler every thread blocks all signals and waits at a barrier for the rest of the threads to enter the signal handler. Save private thread state. When all threads have entered the signal handler, each thread, except the main thread (and the manager thread), saves its context to memory by calling sigsetjmp(3). Each thread, except the main thread, then blocks at another barrier. Save signal handlers. The main thread saves the process's signal handlers using sigaction(2). Wait for other threads. The main thread waits until all the other threads have called sigsetjmp(3) and reached the barrier. Stop the manger thread. The checkpoint thread cannot send a signal to the manager thread when it is signalling all the other threads in step 2 because the manager thread has no thread ID. Instead the main thread sends a message to the pipe the manager thread normally uses to communicate with other threads. When the manager thread receives the message it blocks until the main thread unblocks it. Save main thread stack environment.The main thread calls sigsetjmp(3) to save its stack environment. Save file state Once the other threads have reached the barrier the main thread saves the current file pointer for all open regular files. Save address space. The main thread saves the entire address space to the checkpoint file. Unblock Manager Thread. The main thread unblocks the manager thread. Wait at barrier. The main thread waits at the same barrier as the other threads causing all threads to continue. Wait at barrier. After leaving the barrier all threads except the checkpoint thread and manager. When a program recovers from a checkpoint it starts out as a single threaded program. During initialization, the checkpoint library restores the program's state as shown in Figure 2. Restore thread stacks. The main thread waits while the child threads restore their stack pointers. Each thread restores its stack by calling siglongjmp(3) which causes the thread to return from the sigsetjmp(3) call it made when it saved its state in the checkpoint. The threads move their stack pointers before the main thread loads the address space because the act of moving them needs to use local variables, which would corrupt the stacks if they were loaded first. Wait for the main thread. The child threads wait at a barrier for the main thread to finish restoring the program's state. Get thread ID to process ID mapping. After starting all the threads, the main thread calls pthread_chkpt_restart to get the new thread ID to process ID mapping. The main thread copies the mapping into an area of memory that will not be overwritten when the main thread restores the address space. pthread_chkpt_restart also sends a message to the manager thread telling it to call siglongjmp(3) and block so it will be prepared for its stack to be restored. Load main thread stack. Once all of the child threads and the manager thread have blocked, the main thread restores its own stack pointer. The main thread stack is not necessarily as large as it was when the the program saved the checkpoint. Therefore the main thread recursively calls a function until the its stack is as large as it was when it saved the checkpoint. The main thread can tell when its stack is large enough by comparing the address of a local variable to the address of a local variable when it saved its state. Remap the process's address space The main thread then maps every segment except the main thread stack into the program's address space from the checkpoint file using mmap(2) similar to the method Condor uses [10]. The checkpointing library uses mmap(2) to remap segments because mmap(2) does not cause the data to be loaded immediately. The operating system demand loads the contents of the segments when the program accesses them. Restore signal handlers. The main thread restores the signal handlers with sigaction(2). Restore main thread stack pointer The main thread calls siglongjmp(3) to continue execution where the program was when it saved the checkpoint. Restore file state The main thread opens all the files that were open during the checkpoint and moves the file pointer to its position at the time of the checkpoint. Restore thread ID to process ID mapping. Next the main thread restores the thread ID to process ID mapping and unblocks the manager thread by calling pthread_chkpt_postrestart. Wait at barrier. The main thread waits at the same barrier as the other threads causing all threads to continue. Wait at barrier. After leaving the barrier all threads except the checkpoint. The checkpointing library takes advantage of dynamic linking to intercept some library function calls and system calls so it can track the program's state. The checkpointing library intercepts library functions by providing an intercepting function with the same name as the library function. The checkpointing library calls dlsym(3) with the RTLD_NEXT option during initialization to get the addresses of all the intercepted library functions so the intercepting function can call the system version of the function. This method works for system calls as well as library functions because the code to setup and make system calls is part of the C library. For example, when the application calls pthread_create(3), it gets the checkpointing library's version. The checkpointing library records the parameters passed to pthread_create(3) so it can use them during recovery. Then it calls the system pthread_create(3) using the address it got from dlsym(3) during initialization. If the pthread_create(3) call is successful, the checkpointing library updates the number of running threads and returns. Otherwise, it cleans up its thread table and passes the error on to the application program. The checkpointing library uses an array that mirrors the kernel's file descriptor table to save the state of open files in each checkpoint. To re-open the files during recovery the checkpointing library needs the filename, mode, and current offset into each open file. When the process opens a file with open(2) the checkpointing library adds an entry in its table for that file descriptor with the filename and mode. If the process calls dup(2) or dup2(2) the checkpointing library links the new file descriptor information to the old file descriptor information. When the process closes the file descriptor its entry is removed from the checkpointing library's file descriptor table. The read(2) and write(2) system calls are not intercepted. When the process takes a checkpoint the checkpointing library saves the current file pointer of every regular file. When the process recovers from a checkpoint it uses the information in the checkpointing library's file descriptor table to re-open files and seek the file pointer to the position at the time of the checkpoint. The checkpointing library intercepts the popen(2) call to keep track of pipes that are open. During recovery the checkpointing library reopens pipes to replace those that existed at the time of the checkpoint. However, the checkpointing library does not keep track of data read from or written to the pipe, so data buffered in the kernel may be lost. It also does not handle processes outside the main process. The pipe support is only useful if two threads in the same process share a pipe. Implementing checkpointing for LinuxThreads programs is simpler than for Solaris because LinuxThreads is simpler than the Solaris pthread library. The Solaris kernel treats threads, lightweight processes (LWPs), and processes as different entities. Handling the interactions between threads and LWPs in Solaris is complex. In addition Solaris adds some rules about when a process can handle a signal that complicate the checkpointing library [6]. The Linux kernel is less complex than Solaris because the Linux kernel does not distinguish between threads and processes. LinuxThreads creates threads with clone(2) a generalized version of fork(2). Like fork(2), clone(2) creates a new process, but clone(2) allows the caller to specify which resources the new process shares with its parent and which resources the new process copies from its parent. Thus threads in a LinuxThreads program are separate processes that happen to share an address space and file descriptors with all other threads. We had to modify the LinuxThreads library to handle two different problems. First, the thread library stores a mapping from thread IDs to process IDs in its data segment. When the checkpointing library reloads the process's address space from a checkpoint, the thread ID to process ID mapping is restored to the mapping at the time of the checkpoint, which is out of date for the restored process. To handle this problem the checkpointing library must make sure reloading address space from the checkpoint does not wipe out the thread ID to process ID mapping. After it restarts threads but before it restores the address space, the checkpointing library saves the thread ID to process ID mapping in a region of memory that will not be reloaded from the checkpoint. The checkpointing library corrects the thread ID to process ID mapping after it restores the process's address space. Second, the thread library uses a manager thread to create processes. When a thread creates a new thread it sends a message to the manager thread through a pipe and the manager thread creates the new thread. The checkpointing library coordinates with the manager thread during checkpoints to save the manager thread's private state. The checkpointing library adds four functions to the thread library to handle its interactions with the thread library. The checkpointing library calls pthread_chkpt_precreate before it saves the process's address space. pthread_chkpt_precreate sends the manager thread a message telling it a checkpoint is beginning. The manager thread saves its environment by calling sigsetjmp(3) and blocks. The checkpointing library unblocks the manager thread by calling pthread_chkpt_postcreate after saving the checkpoint. When restoring a process from a checkpoint, the checkpointing library calls pthread_chkpt_prerestart to get a copy of the thread ID to process ID mapping and to send a message to the manager thread telling it to call siglongjmp(3) and block. The thread library saves the thread ID to process ID mapping in memory that will not be overwritten when the address space is restored. After restoring the address space, the checkpointing library calls pthread_chkpt_postrestart to restore the thread ID to process ID mapping and unblocks the manager thread. The pthread_chkpt_ calls are the only added entry points to the thread library. Our checkpointing library supports programs that access regular files sequentially or use signal handlers for signals. At least one signal must be available for the checkpointing library. The checkpointing library cannot restore process IDs and it does not support programs that randomly access files or communicate with other processes. In most cases, however, the application programmer can add recovery code in callback functions to recover the file or communication state. For example, we are using the checkpointing library to add checkpointing to the Unify distributed shared memory system [9]. Random access reads do not present a problem as long as the program never writes to the file. General random access files are difficult to handle because the checkpointing library must be able to roll the file back during recovery to the state it was in during the checkpoint. One simple way to do this is to save the entire file with the checkpoint [16]. Saving could increase the checkpoint size a lot if the program uses a lot of large files. The checkpointing library could avoid some of the overhead by not saving files opened with mode O_RDONLY. Assuming the files do not change between when they are opened and when the program finishes using them. The other alternative for handling random access files would be to log each change made to the file. During recovery the checkpointing library could undo all changes made since the last checkpoint. The disadvantage of logging changes is that it adds overhead to log every write operation and the log grows with each write between checkpoints. We did not want to add this overhead when our applications want to use sequential access files. We could reduce overhead by only logging files that are open with mode O_RDWR. In our current implementation, an application writer who wants to save random access files with a checkpoint could write a callback routine to manually save the desired files during a checkpoint. POSIX threads (and LinuxThreads) do not provide a way to create a thread with a particular thread ID. The checkpointing library assumes that the thread library always assigns thread IDs in the same order. As long as that assumption is true, the checkpointing library can guarantee each thread has the same thread ID after recovering by creating threads in the order in which they were originally created. Currently our checkpointing library does not handle programs with threads that exit before the end of the program. If a thread exits early, the thread created immediately after the thread that exited early will get the exited thread's ID during recovery. This problem could be fixed during recovery by creating a thread that exits immediately in place of the exited thread to use up the exited thread's ID. Alternatively we could modify the thread library to allow programs to request particular thread IDs, but we wanted to minimize the changes to the thread library to make it easier to work with different versions of the thread library. The applications we work with create all the threads they need at the start and the threads keep running until the program exits so it was not a problem for our applications. During recovery, described in section 4.2, the checkpointing library restarts all the threads and restores the process's entire address space from a checkpoint, including the thread library data segment. The checkpointing library assumes that the thread library will function correctly with the newly created threads and the thread data structures from before the checkpoint. This assumption is not entirely true in Linux and thus the thread library must be modified as described in section 4.5. The checkpointing library interrupts each thread with a signal to start a checkpoint. When the checkpointing library installs its signal handler, it passes SA_RESTART flag to sigaction(2) to tell the Linux kernel to restart interrupted system calls if possible. The application code must restart system calls that the Linux kernel cannot restart. We added nothing extra to support thread cancellation functions. The problem with thread cancellation is recreating the threads with the correct thread IDs as described above. Otherwise the checkpointing library would just need minor adjustments to cleanup the canceled thread after its last cancellation handler is called. We also did nothing special to support thread scheduling priorities. Handling thread scheduling priorities would be a matter of logging the calls to the thread scheduling priority calls and reissuing them to restore scheduling priorities during recovery. Support may be added if there is demand. The checkpointing library does not handle interprocess communication, but it does reopen pipes open at the time of a checkpoint. It cannot make another process use either end of the pipe it opens, and it does not save any data buffered in the kernel. Thus pipes will only be restored if they are used between threads in the same process and no data is buffered in the pipe at the time of the checkpoint. Handling IPC, either between processes on the same machine or on different machines, is difficult in general. Both processes must agree on when they take checkpoints or make assumptions about how deterministic they are to avoid inconsistent checkpoints. Otherwise one process could fail and recover from a checkpoint that rolls it back to a state in which it has not sent a message on which another process depends. At that point the program is in a state which it could not have reached without a failure. The second process is in a state that causally depends on a state that never happened, as far as the first process is concerned. In that case the two processes are said to be inconsistent. Issues of consistency have been well studied and are beyond the scope of this paper [8]. Extending our checkpointing library to work for a general case with multiple processes communicating with pipes or TCP sockets would be non-trivial. The checkpointing library does not intercept or modify time related system calls in any way. A program that uses absolute time values may behave strangely after recovering from a checkpoint. For example, assume a thread blocks using pthread_cond_timedwait(3) to wait for several seconds and the process checkpoints while the thread is blocked. The process is killed and restarts from the checkpoint several minutes later. After recovery, the thread will immediately unblock because the timer has expired. Strictly speaking this behavior is correct because the current time is later than the time for which the thread was waiting. Applications that have time based events, however, might get a flood of expired timers when recovering from a checkpoint. We could intercept all calls that have anything to do with absolute time and adjust the time they see after recovering from a checkpoint, but some programs need to know what the absolute time really is. Instead we leave it up to the application programmer to write a callback function to adjust any time values that need to be adjusted after recovering from a checkpoint. The checkpointing library adds overhead due to intercepting calls, overhead due to the checkpointing thread, and overhead due to saving checkpoints. The checkpointing library only intercepts thread creation, file open, and file close calls. Unless the program opens and closes files often or creates and destroys threads often that overhead will be low. The checkpointing thread does not add much overhead because it is blocked except during checkpointing. To verify that checkpointing adds little overhead when it is not writing a checkpoint, we ran several applications from the SPLASH2 [17] benchmark suite. SPLASH2 is a set of benchmarks designed to test the performance parallel shared memory machines. The benchmarks are based on applications and kernels commonly used in scientific computing. We present the results of running the BARNES and WATER-SPATIAL benchmarks below. The other SPLASH2 benchmarks we ran gave similar results. BARNES simulates the gravitational effects of a number of bodies in space using the Barnes-Hut algorithm. It uses a tree to represent the locations of the bodies in space. WATER-SPATIAL simulates the the interaction of water particles using a 3 dimensional grid. We increased the problem sizes of both applications from the size used in the original SPLASH2 paper [17] to increase the running time of the benchmarks. For WATER-SPATIAL we increased the number of particles to 8000 instead of 512. For BARNES we used 65536 particles instead of 16384. The test machine was a two processor 500 MHz Pentium III SMP machine with 512 KB L2 cache and 128 MB of main memory running Linux kernel version 2.2.10 with NFS v2 and glibc2. The file systems mounted for the NFS tests were served by an UltraSPARC-10 running Solaris 5.7. The network over which the NFS disk was mounted was a moderately used 100 Mb/s switched Ethernet connected by a Cisco Catalyst 2924 XL auto-sensing 10/100 Mb/s switch. None of the machines used in the test shared a port on the switch with any other machine. Table 1 compares running each of the benchmarks with and without checkpointing linked for one and two processors. With checkpointing linked, the program called the checkpoint initialization code, but did not take any checkpoints. This test shows how much overhead checkpointing adds not including the time to save the checkpoint to disk. Table 1 shows that the checkpointing library does not add much overhead when the program is not checkpointing. This overhead is important because the program will spend most of its time running, not checkpointing. In some cases, code with checkpointing linked but not used runs faster than without checkpointing. Changes in the program's memory layout cause this speedup. Linking the benchmark with unused code gave the same effect as linking with the checkpointing library. Table 2 shows the amount of time BARNES and WATER-SPATIAL spend taking a checkpoint using a local disk or an NFS mounted disk. Most of the time is spent saving the checkpoint to a file. These numbers are intended to give a feel for how long it takes for application programs to checkpoint and how the checkpointing time is spent. In both the local disk and the NFS disk cases the amount of time spent synchronizing threads before and after the checkpoint is several orders of magnitude smaller than the amount of time spent saving the checkpoint to disk. Saving the checkpoint to disk is the largest overhead of checkpointing. The size of the checkpoint file is directly proportional to the size of the process's address space. Most of the overhead of taking a checkpoint comes from writing the address space to disk. Figure 3 gives an idea how long a program will take to save a checkpoint depending the size of the checkpoint and whether it is saving to a local disk or an NFS mounted disk. The amount of time required to save the checkpoint depends on the file system to which it is saved. The figure shows times for local disk and NFS. Writing a checkpoint to an NFS mounted disk2 takes much longer than writing to a local disk. The figure also shows that the amount of time required to save a checkpoint is directly proportional to the size of the checkpoint. In this case, the time required to save a checkpoint to the NFS mounted disk can be approximated by the equation for checkpoints larger than about 1.3 MB, where is the size of checkpoint in MB. The user can use to decide which checkpoint interval to use. A simple method is to calculate the maximum percentage of execution time taken by checkpointing given and the maximum address space size (checkpoint size) of the program. More sophisticated methods can determine the checkpoint interval that will minimize the program's expected run time given and a particular failure rate [13,15]. Our checkpointing library provides checkpointing for multithreaded Linux programs. It adds little overhead except when taking a checkpoint. The overhead that it does add is directly proportional to the size of the address space. Saving the checkpoint to local disk is much faster than saving it to an NFS mounted disk. Our checkpointing library combines simplicity for many programs that meet its restrictions, but enough flexibility that other programs can use it without too much extra work. Callback function provide flexibility for applications that have special needs. Features like memory exclusion and user directed checkpointing can reduce overhead when taking a checkpoint. We are considering adding incremental and asynchronous checkpointing to further reduce the overhead of saving a checkpoint. The latest version of the checkpointing library is available through our web site at:
http://static.usenix.org/event/usenix01/freenix01/full_papers/dieter/dieter_html/paper.html
crawl-003
refinedweb
6,243
62.68
15 June 2012 13:31 [Source: ICIS news] LONDON (ICIS)--?xml:namespace> “We've conducted numerous interviews and meetings with shareholders [and] we can see that many of them need additional time to make a decision, so we've opted to extend the duration of the share call,” said vice president of Acron Vladimir Kantor. On Thursday, Acron criticised the Polish treasury ministry, which has a controlling holding of 32% in ZAT, for recommending shareholders refuse its offer, amounting to (Zl) Zl 1.5bn ($441m, €349m) for 66% of ZAT, as too low. The offer was a response to The ministry has stated it believes Acron ownership could disrupt the growth strategy of ZAT, a producer of nitrogen and multi-component fertilizers, caprolactam (capro), polyamide 6, oxo-alcohols, plasticisers and titanium dioxide (TiO2). The question now is whether a counter-offer from a “white knight” bidder might be submitted and on what price terms, said Wood & Company investment bank analyst Piotr Drozd. “At this point, with the strategy argument in hand, it seems that the political impact, and not the price, will be the state treasury’s key focus,” said Drozd. “Without the treasury’s consent, and with counter-bids expected, it should be difficult for Acron, if not impossible, to achieve the targeted 50% (+1 share) minimum threshold [for a successful bid], even assuming a tender price hike to the current stock price level,” he added. ($1 = €0.79) ($1 = Zl 3.40, €1 = Zl 4
http://www.icis.com/Articles/2012/06/15/9570185/acron-extends-zat-bid-deadline-possible-counter-bid.html
CC-MAIN-2015-22
refinedweb
247
56.29
I'm trying to write a progam that; Contains a function called sumN() which takes an int n as an argument and returns an int which is the sum of all integers between 1 and n. In the main() asks the user: How many values (s)he wants to enter (maximum 50); Asks for the values and stores them into an array int a[]. Prints to the console sumN(a) for all the elements of a[] that have been entered by the user. I've gotten this far and when I try to run it, it doesn't work it just says; in function 'int main()': error: invalid types 'double[int]' for array subscript. (on line 29) Here's my code; #include <iostream> using namespace std; int main() { double array, set[50]; int size, t,]; double SumN(double *array, int size);{ double total = 0; int i; for(i = 0; i < size; ++i) total += *array[i]; return total;} cout << "Here are your values:\n"; for (t=0; t<size; t++) cout << set[t] << "\n"; return 0; } Could someone please tell me where i'm going wrong as soon as possible? Thanks :)
https://www.daniweb.com/programming/software-development/threads/326040/can-someone-help-me-asap-s
CC-MAIN-2018-13
refinedweb
190
61.53
#include <wx/dcclient.h> A wxWindowDC must be constructed if an application wishes to paint on the whole area of a window (client and decorations). This should normally be constructed as a temporary stack object; don't store a wxWindowDC object. To draw on a window from inside an EVT_PAINT() handler, construct a wxPaintDC object instead. To draw on the client area of a window from outside an EVT_PAINT() handler, construct a wxClientDC object. A wxWindowDC object is initialized to use the same font and colours as the window it is associated with. Constructor. Pass a pointer to the window on which you wish to paint.
http://docs.wxwidgets.org/3.0/classwx_window_d_c.html
CC-MAIN-2018-34
refinedweb
106
62.48
A wrapper for Python's re library for advanced regex pattern management Project description A wrapper for the regex library for advanced pattern management Installation pip install replus or clone this repo git@github.com:raptored01/replus.git and then run python setup.py install Basic usage The Engine loads Regular Expression pattern templates written in *.json files from the provided directory, builds and compiles them in the following fashion: example of template models/dates.json: { "day": [ "3[01]", "[12][0-9]", "0?[1-9]" ], "month": [ "0?[1-9]", "1[012]" ], "year": [ "\\d{4}" ], "date": [ "{{day}}/{{month}}/{{year}}", "{{year}}-{{month}}-{{day}}" ], "patterns": [ "{{date}}" ] } will result in the following regex: (?P<date_0>(?P<day_0>[12][0-9]|0?[1-9]|3[01])/(?P<month_0>0?[1-9]|1[012])/(?P<year_0>\d{4})|(?P<year_1>\d{4})-(?P<month_1>0?[1-9]|1[012])-(?P<day_1>[12][0-9]|0?[1-9]|3[01])) You can put more patterns into patterns, as it will become a list that will be looped over. Querying It is possible to query as follows: from replus import Engine engine = Engine('models') for match in engine.parse("Look at this date: 2012-20-10"): print(match) # <[Match date] span(19, 29): 2012-12-10> date = match.group('date') print(date) # <[Group date_0] span(19, 29): 2012-12-10> day = date.group('day') print(day) # <[Group day_1] span(27, 29): 10> month = date.group('month') print(month) # <[Group month_1] span(24, 26): 12> year = date.group('year') print(year) # [Group year_1] span(19, 23): 2012> Filtering it is possible to filter regexes by type, being the type given by the json’s filename filters = ["dates", "cities"] for match in engine.parse(my_string, *filters): # do stuff Match and Group objects Match objects have the following attributes: - type: the type of match (e.g. “dates”); - match: the re.match object; - re: the regex pattern; - all_group_names: the name of all the children groups; Both Match and Group objects have the following attributes: - value: the string value of the match/group - start: the beginning of the match/group relative to the input string - end: the end of the group relative to the input string - span: (start, end) the span of the match/group object relative to the input string - offset: {"start": start, "end": end} similar to span - length: end-start - first(): get the first matching group - last(): get the last matching group Group objects have the following attributes: - name: the actual group name (e.g. date_1); - key: the group key (e.g. date); - spans: [(start, end), ...] the spans of the repeated matches relative to the input string - starts: the beginnings of the match/group relative to the input string - ends: the ends of the group relative to the input string - offsets: [{"start": start, "end": end}, ...] Both Match and Group objects can be serialized in dicts with the serialize() method and to a json string with the json attribute Secondary features There are two useful secondary features: - non-capturing groups: these are specified by using the “?:” prefix in the group name or key - atomic groups: these are specified by using the “?>” prefix in the group name or key - dynamic backreferences: use # to reference a previous group and @<n> to specify how many groups behind template: { "?:number": [ "\\d" ], "abg": [ "alpha", "beta", "gamma" ], "spam": [ "spam" ], "eggs": [ "eggs" ], "patterns": [ "This is an unnamed number group: {{number}}.", "I can match {{abg}} and {{abg}}, and then re-match the last {{#abg}} or the second last {{#abg@2}}", "Here is some {{?:spam}} and some {{?>eggs}}" ] } It will generate the following regexs: This is an unnamed number group: (?:\d). I can match (?P<abg_0>alpha|beta|gamma) and (?P<abg_1>alpha|beta|gamma), and then re-match the last (?P=abg_1) or the second last (?P=abg_0) Here is some (?:spam) and some (?>eggs) N.B.: in order to obtain an escape char, such as \d, in the pattern’s model it must be double escaped: \\d Current limitations None known Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/replus/
CC-MAIN-2020-05
refinedweb
685
71.55
I needed to write a random number generator in C which will generate random numbers from Normal Distribution (Gaussian Distribution). Without this component I couldn’t proceed to finish writing a C code for Heuristic Kalman Algorithm by Lyonnet and Toscano for some experiments. I selected the Marsaglia and Bray method also known as the Polar method to generate Normal random variables. Here is how it is done. I am just writing the algorithm - Generate and - Generate until - Generate and Here is the Uniform Distribution with range [-1,+1] Now and are normal random variables with mean 0 and standard deviation 1. To generate normal random variable from mean and standard deviation we need to do the following simple transform. Where and In each iteration two normal random variables are generated. Therefore we can generate two random variables in one iteration send one, and on the next call we will execute the algorithm and instead we will return the second generated value from the previous call. The implementation is pretty easy, the only thing we need is a uniform random number generator within the range [-1,+1]. We can use the uniform random number generator available in stblib, the rand function. Sourcecode Here is the code #include <math.h> #include <stdlib.h> double randn (double mu, double sigma) { double U1, U2, W, mult; static double X1, X2; static int call = 0; if (call == 1) { call = !call; return (mu + sigma * (double) X2); } do { U1 = -1 + ((double) rand () / RAND_MAX) * 2; U2 = -1 + ((double) rand () / RAND_MAX) * 2; W = pow (U1, 2) + pow (U2, 2); } while (W >= 1 || W == 0); mult = sqrt ((-2 * log (W)) / W); X1 = U1 * mult; X2 = U2 * mult; call = !call; return (mu + sigma * (double) X1); } The rand () call returns a random number uniformly distributed within 0 to RAND_MAX. To generate uniform random numbers within range [0,1] we just need to divide the returned number with RAND_MAX. Here we need to explicitly typecast any of the operand to double to make the division floating point. Not doing it will result in an integer division which will always evaluate to 0 (and 1 if returned value is RAND_MAX). We need the uniform random number to be in range [-1,+1]. To scale a number in a range [low,high] we need the following transform, where x is scaled to range [low,high] and the scaled value is y y = -low + x * (high - low) Using the above transformation the statement -1 + ((double) rand () / RAND_MAX) * 2; generates uniform distribution in range [-1,+1]. X1 is normally distributed with mean 0 and standard deviation 1. We thus make the necessary transformation (mu + sigma * (double) X1) before returning the random variable, as in . The check for if W is 0, while (W >= 1 || W == 0) in the loop is done to avoid division by zero. The loop will keep on generating U1 and U2 as in the algorithm. The variables X1 and X2 are made static so that it can hold the values from the previous call. Note that the value of X1 is not required to be held across iteration, but still is defined as static. The flag call determines if the call to the function randn is even or odd. If call = 0 then we generate two random numbers from normal distribution with mean 0 and standard deviation 1 using the Polar method, and then transform the generated random variable to make it have a mean mu and standard deviation sigma then return X1. If call = 1 then we do not compute anything and return the second normal random number (after mu sigma transformation) X2 generated in the previous call. So that was all. Next I will post a simple fun code to plot histograms in terminal for this normal distribution (or any distribution or data set). 7 thoughts on “Generating random numbers from Normal distribution in C” Generating random numbers with Gaussian (Normal) distribution in Visual Basic 6.0 (VB6) by Roberto Mior: Very useful for statistical analysis. Thank you very much indeed. thanks a lot to Phoxis for help please i need the simulation of normal distribution using monte carlo method can you help me in C or C++ The values generated are always the same, how to solve? Sorry for my english! Can you show me the code and how you are calling the function. I guess you are initialising the random number generator before each call.
https://phoxis.org/2013/05/04/generating-random-numbers-from-normal-distribution-in-c/?replytocom=10051
CC-MAIN-2020-29
refinedweb
737
60.55
The problem “Iterative Preorder Traversal” states that you are given a binary tree and now you need to find the preorder traversal of the tree. We are required to find the preorder traversal using iterative method and not the recursive approach. Example 5 7 9 6 1 4 3 Approach to print The problem statement asks us to print the preorder traversal of the given binary tree using the iterative method. Generally, we use the recursive method because that is easier. But sometimes it is asked to solve the problem using iteration. Thus we are required here to perform an iterative preorder traversal of the tree. Previously we were using recursion to print the traversal. So to replace the recursion, we have to use a stack data structure. So we will be using a stack data structure to store the nodes which will be required afterward. In preorder traversal first, we print the root then recursively print the left subtree, and in the end, recursively print the right subtree. Here in this algorithm we will run a loop that will run until our current node is not null. And then we will keep on storing the right child in stack if the right child exists. Then we move to the left child. If the left child is null, we remove the elements from the stack and assign them as current node. This way in the end we would have traversed the tree in preorder manner. Code C++ code to print Iterative Preorder Traversal #include<bits/stdc++.h> using namespace std; struct node { int data; node *left, *right; }; node* create(int data){ node* tmp = new node(); tmp->data = data; tmp->left = tmp->right = NULL; return tmp; } void preorder(node* root){ // create a stack stack<node*> s; while(root){ // print the current node cout<<root->data<<" "; // if current node has right sub-tree // then store it and use it afterwards if(root->right) s.push(root->right); // now move to left child of current node // if the left child does not exists // then in the next condition we will move up in the tree // and assign the right children which // we have been storing the stack root = root->left; if(!root && !s.empty()){ root = s.top(), s.pop(); } } } int main() { node* root = create(5); root->left = create(7); root->right = create(3); root->left->left = create(9); root->left->right = create(6); root->left->right->left = create(1); root->left->right->right = create(4); preorder(root); } 5 7 9 6 1 4 3 Java code to print Iterative Preorder Traversal import java.util.*; class node{ int data; node left, right; } class Main{ static node create(int data){ node tmp = new node(); tmp.data = data; tmp.left = tmp.right = null; return tmp; } static void preorder(node root){ // create a stack Stack<node> s = new Stack<node>(); while(root != null){ // print the current node System.out.print(root.data+" "); // if current node has right sub-tree // then store it and use it afterwards if(root.right != null) s.add(root.right); // now move to left child of current node // if the left child does not exists // then in the next condition we will move up in the tree // and assign the right children which // we have been storing the stack root = root.left; if(root == null && !s.empty()){ root = s.peek(); s.pop(); } } } public static void main(String[] args) { node root = create(5); root.left = create(7); root.right = create(3); root.left.left = create(9); root.left.right = create(6); root.left.right.left = create(1); root.left.right.right = create(4); preorder(root); } } 5 7 9 6 1 4 3 Complexity Analysis Time Complexity O(N), since we have traversed all the elements of the tree. Thus the time complexity is linear. Space Complexity O(H), in the worst-case each of the nodes can have the right child. Because we are storing the right child of each node in the path to the left child. Thus we can store at max O(H) nodes in the stack.
https://www.tutorialcup.com/interview/tree/iterative-preorder-traversal.htm
CC-MAIN-2021-49
refinedweb
676
73.17
Contents - 1 Introduction - 2 1. Data Annotation - 3 2. Environment Setup - 4 3. Creating Configuration Files - 5 4. Training Our Custom Object Detector Model - 6 5. Inference using Custom YOLOv5 Object Detector - 7 Conclusion Introduction In this article, we will go through the tutorial on how to use YOLOv5 for custom object detection in the Colab notebook. We will show you how to annotate our custom dataset, and set up your Google Colab environment for the training purpose. We have already covered the basic introduction to YOLOv5 and how to use it in the following article that you may like to see to build the basics – Tutorial Plan Our tutorial to train custom YOLOv5 model for object detection will be divided into four main sections as below – - Annotate the images using LabelImg software - Environment Setup - Create training and data config files - Train our custom YOLOv5 object detector on the cloud - Inferencing our trained YOLOv5 custom object detection model 1. Data Annotation In order to annotate our dataset, we will be using the LabelImg software. You can download it using this link for your machine. Steps to Annotate: - Open LabelImg and select the ‘Open Dir’ option here, go to the directory where you have saved your images. LabelImg - Next, select the ‘Change Save Dir’ and move to a directory where you want to save the annotations (text files). You can leave it just as it is and the images and text files will be saved in the same folder. 3. Change the pascalVOC format to YOLO by clicking on it. 4. Now click the ‘Create Rectbox’ button and create a bounding a bounding box around the objects you want to detect. Next, add the name of the class the object belongs to. This will create a classes.txt file which you have to delete. We delete it because the names of the classes will be defined in a separate file later. 5. Click on ‘save'(in the sidebar) to save the annotation. 6. Click on ‘next’ to open the next image for annotation. Do this for all the images in the dataset. 7. Divide the dataset into two parts i.e. images and text documents separate. Further, divide them into train and validation sets. Look at the next section for more insight. You should have a minimum of 250 images per class to reach a reasonable accuracy. The training and validation split can be 7:3(175:75). I personally collected and used 500 images and divided them into 400 training and 100 validation images. 2. Environment Setup Uploading Data to Personal Drive Create a data directory named ‘data’. The annotated data is supposed to be divided in such a way that the images and the annotations (text files) are separate. Further, each type of data is to be divided into two parts namely ‘train’ and ‘valid’ (which stands for training and validation data) Your dataset directory should look something like this: Setting Up Google Colab Google Colab is an online environment similar to Jupiter notebook where you can train deep learning models on GPU. The free plan of Google Colab allows you to train the deep learning model for up to 12 hrs before the runtime disconnects. Setting GPU By visiting the runtime section change the hardware accelerator to GPU. Mounting Our Personal Drive In order to use the dataset that we uploaded to the drive, we will mount our drive using the below code. (It will ask you to enter the authorization code that you can by clicking the link that will appear below) from google.colab import drive drive.mount('/content/drive') Go to this URL in a browser: Enter your authorization code: ·········· Mounted at /content/gdrive Cloning The YOLOv5 repository We will now clone the YOLOv5 repository provided by Ultralytics in our Colab environment. !git clone Output: Cloning into 'yolov5'... remote: Enumerating objects: 7207, done. remote: Counting objects: 100% (313/313), done. remote: Compressing objects: 100% (194/194), done. remote: Total 7207 (delta 191), reused 212 (delta 119), pack-reused 6894 Receiving objects: 100% (7207/7207), 9.18 MiB | 20.71 MiB/s, done. Resolving deltas: 100% (4929/4929), done. Installing Requirements Install the required dependencies and libraries required to use YOLOv5. !pip install -r yolov5/requirements.txt 3. Creating Configuration Files i) Model Architecture Configuration File The model architecture file contains info about the no. of classes the dataset and original model was trained on 80 classes. Thus we will be creating the model architecture file directly using python and changing the ‘nc’ parameter to the no. of classes in our custom dataset. The rest of the architecture is the same as the YOLOv5 S version. Most importantly the file also holds the value of pre-computed anchors (that help us to detect objects) along with the architecture of the backbone and neck of our model. Other parameters like the structure of layers, no of layers, values of hyperparameters, and filters are also defined in these files. You can look at it here or use this file. with open('new_train_yaml', 'w+') as file: file.write( """ # parameters nc: 1 #, BottleneckCSP, [128]], [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 [-1, 9, BottleneckCSP, [256]], [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 [-1, 9, BottleneckCSP, [512]], [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 [-1, 1, SPP, [1024, [5, 9, 13]]], [-1, 3, BottleneckCSP, [1024, False]], # 9 ] # YOLOv5 head head: [[-1, 1, Conv, [512, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], [[-1, 6], 1, Concat, [1]], # cat backbone P4 [-1, 3, BottleneckCSP, [512, False]], # 13 [-1, 1, Conv, [256, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], [[-1, 4], 1, Concat, [1]], # cat backbone P3 [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small) [-1, 1, Conv, [256, 3, 2]], [[-1, 14], 1, Concat, [1]], # cat head P4 [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium) [-1, 1, Conv, [512, 3, 2]], [[-1, 10], 1, Concat, [1]], # cat head P5 [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large) [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) ] """ ) ii) Training Configuration File Similar to the last section we will now create a training configuration file. Like the name suggests it provides the path to training and validation datasets. The ‘train’ and ‘val’ param provide the path to datasets while ‘nc’ represents the no. of classes and ‘names’ represents the class names associated with the class values (according to zero index). with open('new_data_yaml', 'w+') as file: file.write( """ train: /content/drive/MyDrive/data/images/train val: /content/drive/MyDrive/data/images/valid nc: 1 names: ['Lamborghini'] """ ) 4. Training Our Custom Object Detector Model i) Training Command We will start the training process by running the following command that invokes ‘train.py’ file. !python /content/yolov5/train.py --img 416 --batch 16 --epochs 500 --data /content/new_data_yaml --cfg /content/new_train_yaml Parameters: - –data: Path to the data configuration file - –cfg: Path to the model architecture configuration file - –img: Input image size - –batch: Size of a batch (model weights are updated with each batch if you are on a personal machine use more no of batches so that PC doesn’t run out of memory). - –epochs: No of epochs. Output: Results.png: You may wonder why there is nothing in the classification graphs, it is because we only had one class thus classification was not required. In the case of multiple classes classification loss is also considered along with localization loss. ii) Accessing the Custom Model Output Directory The very first time when the YOLOv5 model is called a folder called ‘runs’ is created that holds the outputs and info of each and every run. Each run is called an experiment and is created and saved in the following manner:(exp0, exp1, exp2, and so on). In case of inference ‘detection’ folder will be created whereas for training ‘train’ folder is created. !ls /content/runs/train exp !ls /content/runs/train/exp iii) Process and Data Visualization iv) Weights Directory !ls /content/runs/train/exp/weights best.pt last.pt 5. Inference using Custom YOLOv5 Object Detector i) Inference Command - –source: The path to the image to perform inference on. - –weights: Weights file of the trained model. - –img: The image will be resized to this value and then sent for detection. - –conf: Minimum confidence value to consider a prediction as good. - –save-txt: Flag parameters enables saving of text files containing the coordinates of bounding boxes. !python /content/yolov5/detect.py --source testImage.jpg --weights '/conten/runs/train/exp/weights/last.pt' --img 416 --conf 0.5 --save-txt Output: Fusing layers... Model Summary: 232 layers, 7246518 parameters, 0 gradients, 16.8 GFLOPs image 1/1 testImage.jpg: 320x416 Done. (0.009s) Results saved to runs/detect/exp labels saved to runs/detect/exp/labels Done. (0.015s) ii) Inference Results !ls /runs/detect/exp testImage.jpg labels Conclusion Coming to the end of this tutorial, hope you now know how to use YOLOv5 for custom object detection in Colab. Mind you custom training is the easiest part, the difficult part is the annotation of our custom dataset.
https://machinelearningknowledge.ai/tutorial-yolov5-custom-object-detection-in-colab/
CC-MAIN-2022-33
refinedweb
1,526
55.84
Why does this print wtf? Does pattern matching not work on structural types? "hello" match { case s: { def doesNotExist(i: Int, x: List[_]): Double } => println("wtf?") case _ => println("okie dokie") } Running this example in the Scala interpreter with unchecked warnings on ( scala -unchecked) produces the following warning: warning: refinement AnyRef{def doesNotExist(Int,List[_]): Double} in type pattern is unchecked since it is eliminated by erasure. Unfortunately, a generic type like this cannot be checked at runtime as the JVM doesn't have reified generics. All that the JVM sees in this pattern match is: "hello" match { case s: Object => ... case annon: Object => ... } EDIT: In response to your comments, I have been thinking about a solution but didn't have the time to post it yesterday. Unfortunately, even if it should work, the compiler fails to inject the proper Manifest. The problem you want to solve is to compare if an object is of a given structural type. Here's some code I've been thinking of (Scala 2.8-r20019, as Scala 2.7.6.final crashed on me a couple of times while playing with similar ideas) type Foo = AnyRef { def doesNotExist(i: Int, x: List[_]): Double } def getManifest[T](implicit m: Manifest[T]) = m def isFoo[T](x: T)(implicit mt: Manifest[T]) = mt == getManifest[Foo] Method isFoo basically compares the manifests of the class x of Foo. In an ideal world, the manifest of a structural type should be equal to the manifest of any type containing the required methods. At least that's my train of thought. Unfortunately this fails to compile, as the compiler injects a Manifest[AnyRef] instead of a Manifest[Foo] when calling getManifest[Foo]. Interestingly enough, if you don't use a structural type (for example, type Foo = String), this code compiles and works as expected. I'll post a question at some point to see why this fails with structural types -- is it a design decision, or it is just a problem of the experimental reflection API. Failing that, you could always use Java reflection to see if an object contains a method. def containsMethod(x: AnyRef, name: String, params: java.lang.Class[_]*) = { try { x.getClass.getMethod(name, params: _*) true } catch { case _ => false } } which works as expected: containsMethod("foo", "concat", classOf[String]) // true containsMethod("foo", "bar", classOf[List[Int]]) // false ... but it's not very nice. Also, note that the structure of a structural type is not available at runtime. If you have a method def foo(x: {def foo: Int}) = x.foo, after erasure you get def foo(x: Object) = [some reflection invoking foo on x], the type information being lost. That's why reflection is used in the first place, as you have to invoke a method on an Object and the JVM doesn't know if the Object has that method.
https://codedump.io/share/jS6IuduBa90R/1/pattern-matching-structural-types-in-scala
CC-MAIN-2016-50
refinedweb
481
63.8
In this article, we will implement two menu commands from our Windows Forms application: Why? A way for me to be more mobile. At night, I want to be able to solve my backup problem easily from within my main business app just by selecting "Backup" or even "Save" in my menu. And the next day, I might be travelling, so from my notebook, I want to be able to open the latest version and keep working. Since it took a few seconds to run it with my 30 MB database, I chose to use a BackgroundWorker thread to do the work and report the progress back to a textbox in the GUI to avoid a totally frozen GUI. BackgroundWorker I have set some goals for the infrastructure of my business for this year. Moving from MS SQL Server to MySQL is one of them; trying to find a more lightweight IDE alternative is another - with the main intention of getting more mobile. So, while the tasks I outlined in the beginning that we're about to implement here is no rocket science, and can typically be solved with a few minutes of scripting, I found it pretty neat to have it all inside my main business app. We need VS2008 Express and C# 2.0. We are developing a Windows Forms app here, with two buttons: one for restore and one for backup. The backups are always stored in <path>\backups. I only allow for one generation (files are deleted). All settings are done in the app.config file. No overriding is done in the GUI etc. The filename of the backup in this example is testfile.sql, and depending on the compression method, it might be testfile.sql.gz or testfile.sql.tar. The last parameter "BackupFTPDirectory" can be a subdirectory on the FTP server, say "/mybackups". <!-- 'Internal' (gz) or 'path to winrar\rar.exe'. BackupFTPDirectory How do we compress the .sql file before FTP? As I said, I really didn't feel like waiting for my 30 MB backup file to be downloaded/uploaded so I wanted some compression. Either internal (GZip) or a path to the rar.exe is supported right now. In the /backups directory, you will find two cmd files. Backmysql.cmd: "C:\xampp\mysql\bin\mysqldump.exe" --no-create-db --routines --host localhost --user root --password=enterpwhere %1 > "%2" You need to change the path to mysqldump and enter the the correct username and password, of course. The app will call this cmd file for executing the database backup. My first idea was to use the internal GZipStream (available in the namespace System.IO.Compression). Good enough for me I thought, and no dependencies at all. GZipStream System.IO.Compression 33 MB only got compressed to over 9 MB, and when I ran WinRar against it, I got under it 7.5 MB. 2.5 MB is a big deal when FTPing, so I had to implement a better compression method. Of course, there is the ISharpCode zip library, but I didn't feel like dragging in an over 200K library dependency into my app. However, since it's my app and my boxes, I can depend on WinRar being installed on all boxes (that's the compression app I have chosen to use). So I whipped up an ugly fix for it. if (oParams.CompressionMethod == "Internal") { ..old gz } else { System.Diagnostics.Process.Start d:\program\winrar\rar.exe a filename.sql.rar filename.sql } I know there are a lot of existing FTP libraries out there, free and commercial. I took FTPFactory.cs from Jaimon Mathew's single file, really easy to use. FTPFactory oFTP = new FTPFactory(); o; o; o; o; if (oParams.FTPDir.Length > 0) o; o; o; As I said, the whole operation takes a few seconds with my 6 MB RAR file. Waiting for it is no big deal since I do it once in the morning and once at night, but. WorkerParams a time and report the progress back to; } } This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
http://www.codeproject.com/Articles/34339/MySQL-Backup-compress-and-FTP-from-WinForms
crawl-003
refinedweb
691
73.17
First time here? Check out the FAQ! I found the answer and case closed. I use a Matlab tool box: GML Adaboost solve this problem. I transferred my csv files into .mat, and the dataset is compressed into a 2GB .Mat file from a 60 GB .csv. The model can be trained by this toolbox and export as a txt file. This model can be used in my C++ program by using a parser which provided by GML Adaboost . Hi all, I am trying to train my dataset (over 15G). Obviously, it is not possible to load entire data set into memory at once. Therefore, I am considering to load my data separately, and it worked fine on my own implementation of adaboost. Now, I would like to train this dataset by OpenCV. I found the training data is store into a smart pointer Ptr<ml::TrainData> I need to load all my data, because training process on OpenCV can only input one set of TrainData according to the following OpenCV 3 source code boost.cpp: boost.cpp bool train( const Ptr<TrainData>& trainData, int flags ) { startTraining(trainData, flags); int treeidx, ntrees = bparams.weakCount >= 0 ? bparams.weakCount : 10000; vector<int> sidx = w->sidx; for( treeidx = 0; treeidx < ntrees; treeidx++ ) { int root = addTree( sidx ); if( root < 0 ) return false; updateWeightsAndTrim( treeidx, sidx ); } endTraining(); return true; } Is there any other function can make me divide my dataset into several chunks and put into training process? If not, does anyone know other adaboost library can handle huge size of data? I had tried both .ptr<float> and .ptr<int> and still got exact same result. .ptr<float> .ptr<int> Hi all, I am trying to train my own boosting model, but I encountered Assertion failed on trainning stage. My program is trying to read a CSV file into cv::Mat and use cv::Mat to be the input of trainning process. Following is my code: int main(int argc, char *argv[]){ int rows = 10; int cols = 4; string pixel; Mat img(Size(cols,rows),CV_32F); Mat response(Size(1,rows),CV_32F); ifstream file("D:/testFile2/test.csv", ifstream::in); for(int i=0; i<rows; i++){ float* data = (float*)img.ptr<ushort>(i); float* data2 = (float*)response.ptr<ushort>(i); for(int j=0; j<cols+1; j++){ if(j==0){ getline(file, pixel, ','); data2[j] = (float)atof(pixel.c_str()); } else if(j == cols){ getline(file, pixel, '\n'); data[j-1] = (float)atof(pixel.c_str()); } else{ getline(file, pixel, ','); data[j-1] = (float)atof(pixel.c_str()); } } } printf("Data Read\n"); Ptr<ml::TrainData> dataset = ml::TrainData::create(img,ml::SampleTypes::ROW_SAMPLE,response); Ptr<ml::Boost> boost = ml::Boost::create(); boost->setBoostType(ml::Boost::REAL); boost->setWeakCount(10); boost->setMaxDepth(2); boost->setWeightTrimRate(0.95); cout<<"Training data: "<<endl <<"getSamples\n"<<dataset->getSamples()<<endl <<"getResponse\n"<<dataset->getResponses()<<endl <<endl; cout<<"Boostiing Model Trainning..."<<endl; boost = ml::Boost::train<ml::Boost>(dataset,0); cout<<"Finished Boosting Trainning!!!"<<endl; printf("Finished\n"); return 0; } And I got this As you can see, the input data is pretty simple, just a four dimensions data. Alternatively, if I used: Ptr<ml::TrainData> dataset = ml::TrainData::loadFromCSV("D:/testFile2/test.csv",0,0); Then, everything is fine, no assertion failed occured. Does anyone have idea about this? Thanks Ok, thanks for your help. I will keep working on this, and post my answer here if I got one. Hi Steven, thanks for your reply. I did build OpenCV3 with OpenCL enable. In the other way, I think OpenCL on Odroid is supported by OpenCL, because I can derived devices information by OpenCV API. Am I correct or not? Hi all, I am trying to use OpenCV3.0 OpenCL API on my Odroid XU3. Unfortunately, I am encountering some real weird problems. The following is my devices information which is derived by OpenCL 1.1: PlatformCount: 1 1. Device: Mali-T628 1.1 Hardware version: OpenCL 1.1 1.2 Software version: 1.1 1.3 OpenCL C version: OpenCL C 1.1 1.4 Parallel compute units: 4 2. Device: Mali-T628 2.1 Hardware version: OpenCL 1.1 2.2 Software version: 1.1 2.3 OpenCL C version: OpenCL C 1.1 2.4 Parallel compute units: 2 I tried to using do some performance test on Odroid by OpenCV3.0 OpenCL API, so I wrote following code: #include <iostream> #include <string> #include <iterator> #include <opencv2/opencv.hpp> #include <opencv2/core/ocl.hpp> using namespace std; int main(){ if (!cv::ocl::haveOpenCL()) { cout << "OpenCL is not avaiable..." << endl; return 0; } cv::ocl::Context context; if (!context.create(cv::ocl::Device::TYPE_GPU)) { cout << "Failed creating the context..." << endl; return 0; } // In OpenCV 3.0.0 beta, only a single device is detected. cout << context.ndevices() << " GPU devices are detected." << endl; for (int i = 0; i < context.ndevices(); i++) { cv::ocl::Device device = context.device(i); cout << "name : " << device.name() << endl; cout << "available : " << device.available() << endl; cout << "imageSupport : " << device.imageSupport() << endl; cout << "OpenCL_C_Version : " << device.OpenCL_C_Version() << endl; cout << endl; break; } double tic, toc; cv::Mat mat_src = cv::imread("img_1.png", 0); cv::Mat mat_dst; cv::UMat umat_src = mat_src.getUMat(cv::ACCESS_READ, cv::USAGE_ALLOCATE_DEVICE_MEMORY); cv::UMat umat_dst; tic = (double)cv::getTickCount(); for(int i = 0 ; i<1000; i++){ cv::Canny(umat_src, umat_dst, 0, 50); } toc = (double)cv::getTickCount(); cout<<"UMat X Canny Time: "<<(double)((toc-tic)/cv::getTickFrequency())<<endl; tic = (double)cv::getTickCount(); for(int i = 0 ; i<1000; i++){ cv::Canny(mat_src, mat_dst, 0, 50); } toc = (double)cv::getTickCount(); cout<<"Mat X Canny Time: "<<(double)((toc-tic)/cv::getTickFrequency())<<endl; return 0; } and I got following results on my Odroid: 1 GPU devices are detected. name : Mali-T628 available : 1 imageSupport : 1 OpenCL_C_Version : OpenCL C 1.1 UMat X Canny Time: 44.6943 Mat X Canny Time: 44.0222 As you can see, the results are merely no differences whether use UMat or not. To ensure UMat really did some effect to performance, I try the exactly same code on my PC, and I got following results: 1 GPU devices are detected. name : Intel(R) HD Graphics 4600 available : 1 imageSupport : 1 OpenCL_C_Version : OpenCL C 1.2 UMat X Canny Time: 4.8207 Mat X Canny Time: 11.6929 The result showed that performance was dramatically improved by OpenCL. So, why OpenCL API not work on Odroid? Is it related to the version of OpenCL?
https://answers.opencv.org/users/23343/jessech/?sort=recent
CC-MAIN-2019-39
refinedweb
1,066
61.22
Agenda See also: IRC log, previous 2008-12-18 <ShaneM> we do not use that namespac <ShaneM> it is pointed to from the xhtml namespace document Ralph: It is up there, somewhere - the XHTML namespace document points to it. ... Where is used? ShaneM: It shouldn't be circulating, nothing should point to it. <ShaneM> <benadida> <benadida> (2 days younger) <benadida> ShaneM: Ralph/Steven or I will fix this. ... The contents of both those documents should be exactly the same. <ShaneM> ACTION: fix the .htaccess for the XHTML namespace [recorded in] <benadida> action items --> ACTION: Mark to review reasoning on setting explicit about="" on HEAD and BODY [recorded in] [CONTINUES] ACTION: Ben to add public-rdfa examples to wiki and think of slightly improved top-level organization [recorded in] [CONTINUES] ACTION: Ben to put up information on "how to write RDFa" with screencast possibly and instructions on bookmarklet. [recorded in] [CONTINUES] ACTION: Jeremy to demonstrate GRDDL with XHTML/RDFa once the NS URI is set up. [recorded in] [CONTINUES] ACTION: Manu talk with Jamie McCarthy about an AskSlashdot piece [recorded in] [CONTINUES] ACTION: Manu to write summary for Semantic Web Use Cases for Ivan. [recorded in] [CONTINUES] ACTION: Manu write the perl code for Slashdot. [recorded in] [CONTINUES] ACTION: Mark create base wizard suitable for cloning [recorded in] [CONTINUES] ACTION: Mark to send Ben ubiquity related wizard stuff [recorded in] [CONTINUES] ACTION: Mark write foaf examples for wiki [recorded in] [CONTINUES] ACTION: Michael to create 'RDFa for uF users' on RDFa Wiki [recorded in] [CONTINUES] <mhausenblas> Manu:2 parts ... part 2 is "If I've already setup my page to use hCard, how do I switch to RDFa?" Michael: split it into two parts (how and differences) Manu: Perhaps we need something that shows general differences between uF and RDFa, and then gives specific examples. ACTION: Ralph think about RSS+RDFa [recorded in] [CONTINUES] <msporny> public-rdf-in-xhtml-tf/2009Jan/0016.html Test Case #121: "[prefix:]" CURIE format is valid Manu: the issue tested here is with suffix-less CURIEs, e.g. "example:" ... CURIE still expands, empty-string as suffix. <Ralph> +1 <mhausenblas> +1 <ShaneM> +1 RESOLUTION: test case 121 suffix-less CURIE approved <msporny> Test Case #122: "[:]" CURIE format is valid <mhausenblas> +1 <Ralph> +1 <benadida> +1 <ShaneM> +1 <markbirbeck> +1 <msporny> +1 RESOLUTION: test case 122 prefix and suffix-less CURIE [:] approved <msporny> public-rdf-in-xhtml-tf/2009Jan/0018.html Test Case #123: "[]" is a valid safe CURIE <mhausenblas> public-rdf-in-xhtml-tf/2009Jan/0026.html <msporny> about="[foo]" Manu: the current consensus is that the subject is <msporny> about="[]" Manu: "[foo]" is an invalid CURIE, therefore so should be the empty string ... as neither is in the reserved (XHTML) list <msporny> # the mapping to use when there is no prefix is not defined, which effectively prohibits the use of CURIEs that do not contain a colon; Ben: did we define CURIES to require a prefix in RDFa? Mark: yes ... wasn't my preference, but it was a long discussion Ben: considering consistency w.r.t. reserved words ... this is the first instance where an invalid value actually changes the structure Mark: and Ivan pointed out the same thing occurs with @about="[foo]" Shane: right; @about="[foo]" should not change the subject Ben: but the presence of @rel alters the graph structure even if the CURIE is not valid ... however in this case it's acting as if @about was not present ... however, since @about just changes the subject and doesn't by itself generates triples, maybe this is OK Mark: it's clear that this is the current spec. We could discuss whether this is the most desireable choice. Ben: so if it's not a valid CURIE value, the behavior is as if @about were not there Mark: the alternative discussed was to assume the invalid CURIE was in the local document namespace ... and we liked that less Ben: the discussion is about the subject; some triple has to be generated, and the spec is clear Mark: however, as you note @rel="[foo]" does do some work Ben: rephrasing, what is the alternative when an invalid CURIE is found? ... it would seem wrong to drop the triple entirely ... whereas it's more reasonable to drop the triple in @rel="[foo]" ... so I don't see a better alternative for @about="[foo]" without major changes to CURIE ... I'm satisfied with this conclusion Mark: the test case seems to be unnecessarily nested Manu: yeah, probably; it went through several iterations Mark: the middle DIV could probably be dropped ... you only need the first one Manu: yeah, it appears the <div about=""> could be dropped ... the correct SPARQL should be ...> ""> <msporny> <html xmlns="" <msporny> xmlns: <msporny> <head> <msporny> <title>Test Case 0123</title> <msporny> </head> <msporny> <body> <msporny> <p about=""> > <> <msporny> <> <msporny> "Test Case 0123" . <msporny> <> <msporny> <> ] ACTION: Manu to look at [recorded in]
http://www.w3.org/2009/01/08-rdfa-minutes.html
CC-MAIN-2014-23
refinedweb
818
57.81
When I created this statically generated blog, I decided to not integrate comments. Mainly because there was no solution which suited my needs: self hosted, small, easy to use, nice look. For my personal website I used Juvia, but for my needs its too big and it seems that there is no development going on anymore. Here comes the solution: ISSO - "Ich schrei sonst" - A disqus alternative. It's written in Python and very lightweight. Some features: - Disqus import - Small SQLite backend (because comments are not big data, says the website) - Lightweight backend, most work is done on the client (JS) - Up and Downvoting - Threaded answers - Possibility to edit or delete own comment during 15 minutes - Comment moderation The documentation is already very well. Just follow the installation docs. I wanted to run an ISSO instance per domain under /isso/, mainly to avoid troubles with CORS or some browser security plugins. And as I run all websites with TLS, it is the best choice to run such applications under the same URL. But I had some troubles getting it to run with mod_wsgi, running on a subfolder (not subdomain), as I'm really not a specialist on running Python applications. Here are some steps to get ISSO up and running with mod_wsgi on Apache: Apache with mod_wsgi You need mod_wsgi installed and enabled. On Ubuntu/Debian: apt-get install libapache2-mod-wsgi && a2enmod wsgi && service apache reload The needed Apache configuration is very simple, just add it to the VHost definition: WSGIScriptAlias /isso /var/www/yoursite.com/isso/isso.wsgi WSGIDaemonProcess isso-yoursite user=www-data group=www-data threads=5 This tells the WSGI process to run under the configured user/group. Make sure that this user has read/write permission on /var/www/yoursite.com/isso. This is very important, because SQLite (which runs under this user) needs permission on this folder to create and remove its lockfile. I had the strange behaviour that the SQLite DB file was not created as this defined user (I don't use www-data!) but instead as the user running the Apache webserver (normally www-data). So if you have troubles with file access, just re-check the permissions on this folder. If you want to run ISSO per domain, as I do, choose a unique WSGIDaemonProcess name (like isso-yoursite). Now create the WSGI file /var/www/yoursite.com/isso/isso.wsgi, the following content is sufficient: import os from isso import make_app from isso.core import Config application = make_app(Config.load("/var/www/yoursite.com/isso/isso.cfg")) And of course, the config file /var/www/yoursite.com/isso/isso.cfg needs to be created too: [general] ; cat /dev/urandom | strings | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n' session-key = <output from above> dbpath = /var/www/yoursite.com/isso/isso.db host = The database is created on the first time the application is accessed. Integration into Jekyll It depends on the Jekyll templates used. As a starting point, here are some snippets I used to integrate it into the minimal-mistakes theme. Jekyll site config: _config.yml: isso: data_isso: /isso/ script_src: /isso/js/embed.min.js Template: f.e. _layouts/post.html {% raw %} {% if site.isso.script_src %} <script data-</script> <section id="isso-thread"></section> {% endif %} {% endraw %} Bonus: Tweet link for comments I announce most of my posts on Twitter. So I added a new field to the front-matter tweet_url and enhanced the template _layouts/post.html a bit: {% raw %} <p class="byline">JavaScript deactivated? Want to send a comment? Write it here: <a href="{% if page.tweet_url %}{{ page.tweet_url }}{% else %} site.owner.twitter }}{% endif %}">@{{ site.owner.twitter }}</a> {% endraw %} As soon as the post is written and the Tweet is made, I copy the URL of the Tweet to the front-matter and commit this changes. This is a nice feature for users who have JavaScript deactivated, but want to comment on the post. Now I'm looking forward to many helpfull comments.
https://tobru.ch/comments-for-a-static-website-with-isso/
CC-MAIN-2022-21
refinedweb
668
57.06
The Q3SqlSelectCursor class provides browsing of general SQL SELECT statements. More... #include <Q3SqlSelectCursor> This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information. Inherits Q3SqlCursor. The Q3SqlSelectCursor class provides browsing of general SQL SELECT statements. Q3SqlSelectCursor is a convenience class that makes it possible to display result sets from general SQL SELECT statements in data-aware Qt widgets. Q3SqlSelectCursor is read-only and does not support INSERT, UPDATE or DELETE operations. Pass the query in at construction time, or use the Q3SqlSelectCursor::exec() function. Example: ... Q3SqlSelectCursor* cur = new Q3SqlSelectCursor("SELECT id, firstname, lastname FROM author"); Q3DataTable* table = new Q3DataTable(this); table->setSqlCursor(cur, true, true); table->refresh(); ... cur->exec("SELECT * FROM books"); table->refresh(); ... Constructs a read only cursor on database db using the query query. Constructs a copy of other Destroys the object and frees any allocated resources This is an overloaded function. Updates the database with the current contents of the cursor edit buffer using the specified filter. Returns the number of records which were updated. For error information, use lastError(). Only records which meet the filter criteria are updated, otherwise all records in the table are updated. If invalidate is true (the default), the cursor can no longer be navigated. A new select() call must be made before you can move to a valid record. Reimplemented from Q3SqlCursor. See also Q3SqlCursor::update(), primeUpdate(), setMode(), and lastError().
http://doc.trolltech.com/4.5-snapshot/q3sqlselectcursor.html
crawl-003
refinedweb
255
51.24
Syntax Error: Not a Chance I tried executed the following code in the python IDLE from __future__ import braces And I got the following error: SyntaxError: not a chance What does the above error mean? You have found an easter egg in Python. It is a joke. It means that delimiting blocks by braces instead of indentation will never be implemented. Normally , imports from the special __future__ module enable features that are backwards-incompatible, such as the print() function, or true division. So the line from __future__ import braces is taken to mean you want to enable the 'create blocks with braces' feature, and the exception tells you your chances of that ever happening are nil. You can add that to the long list of in-jokes included in Python, just like import __hello__, import this and import antigravity. The Python developers have a well-developed sense of humour! ★ Back to homepage or read more recommendations:★ Back to homepage or read more recommendations: From: stackoverflow.com/q/17811855
https://python-decompiler.com/article/2013-07/syntax-error-not-a-chance
CC-MAIN-2019-35
refinedweb
168
61.67
Organizing your Project¶ Introduction¶ Morepath does not put any requirements on how your Python code is organized. You can organize your Python project as you see fit and put app classes, paths, views, etc, anywhere you like. A single Python package (or even module) may define a single Morepath app, but could also define multiple apps. In this Morepath is like Python itself; the Python language does not restrict you in how you organize functions and classes. While this leaves you free to organize your code as you see fit, that doesn’t mean that your code shouldn’t be organized. Here are some guidelines on how you may want to organize things in your own project. But remember: these are guidelines to break when you see the need. Sounds Like a Lot of Work¶ You’re in luck. If you want to skip this chapter and just get started, you can use the Morepath cookiecutter template, which follows the guidelines layed out in this chapter: If you want to find out more about the why and the how, you can always keep on reading of course. Python project¶ It is recommended you organize your code in a Python project with a setup.py where you declare the dependency on Morepath. If you’re unfamiliar with how this works, you can check out this tutorial. Doing this is good Python practice and makes it easy for you to install and distribute your project using common tools like pip, buildout and PyPI. In addition Morepath itself can also load its code more easily. Project layout¶ Here’s a quick overview of the files and directories of Morepath project that follows the guidelines in this document: myproject setup.py myproject __init__.py app.py model.py [collection.py] path.py run.py view.py Project setup¶ Here is an example of your project’s setup.py with only those things relevant to Morepath shown and everything else cut out: from setuptools import setup, find_packages setup(name='myproject', packages=find_packages(), install_requires=[ 'morepath' ], entry_points={ 'console_scripts': [ 'myproject-start = myproject.run:run' ] }) This setup.py assumes you also have a myproject subdirectory in your project directory that is a Python package, i.e. it contains an __init__.py. This is the directory where you put your code. The find_packages() call finds it for you. The install_requires section declares the dependency on Morepath. Doing this makes everybody who installs your project automatically also pull in a release of Morepath and its own dependencies. In addition, it lets this package be found and configured when you use morepath.autoscan(). Finally there is an entry_points section that declares a console script (something you can run on the command-prompt of your operating system). When you install this project, a myproject-start script is automatically generated that you can use to start up the web server. It calls the run() function in the myproject.run module. Let’s create this next. You now need to install this project. If you want to install this project for development purposes you can use python setup.py develop, or pip install -e . from within a virtualenv. See also the setuptools documentation. Project naming¶ Its possible to name your project differently than you name your Python package; you could for instance have the name ThisProject in setup.py, and then have your Python package be still called myproject. We recommend naming the project the same as the Python package to avoid confusion. Namespace packages¶ Sometimes you have projects that are grouped in some way: they are all created by the same organization or they are part of the same larger project. In that case you can use Python namespace packages to make this relationship clear. Let’s say you have a larger project called myproject. The namespace package itself may not contain any code, so unlike the example everywhere else in this document the myproject directory is always empty but for a __init__.py. Different sub-projects could then be called myproject.core, myproject.wiki, etc. Let’s examine the files and directories of myproject.core: myproject.core setup.py myproject __init__.py core __init__.py app.py model.py [collection.py] path.py run.py view.py The change is the namespace package directory myproject that contains a single file, __init__.py, that contains the following code to declare it is a namespace package: __import__('pkg_resources').declare_namespace(__name__) Inside is the normal package called core. setup.py is modified too to include a declaration in namespace_packages, and we’ve changed the entry point: setup(name='myproject.core', packages=find_packages(), namespace_packages=['myproject'], install_requires=[ 'morepath' ], entry_points={ 'console_scripts': [ 'myproject.core-start = myproject.core.run:run' ] }) See also the namespace packages documentation. App Module¶ The app.py module is where we define our Morepath app. Here’s a sketch of app.py: import morepath class App(morepath.App): pass Run Module¶ In the run.py module we define how our application should be served. We take the App class defined in app.py, then have a run() function that is going to be called by the myproject-start entry point we defined in setup.py: from .app import App def run(): morepath.autoscan() App.commit() morepath.run(App()) This run function does the following: - Use morepath.autoscan()to recursively import your own package plus any dependencies that are installed. - Commit the Appclass so that its configuration is ready. You can omit this step and in this case the configuration is committed when Morepath processes the first request. But if you want to see configuration errors at startup, use an explicit commit. - start a WSGI server for the Appinstance on port localhost, port 5000. This uses the standard library wsgiref WSGI server. Note that this should only used for testing purposes, not production! For production, use an external WSGI server. The run module is also a good place to do other general configuration for the application, such as setting up a database connection. Upgrading your project to a newer version of Morepath¶ See Upgrading to a new Morepath version. Debugging scanning problems¶ If you for some reason get 404 Not Found errors where you expect some content, something may have gone wrong with scanning the configuration of your project. Here’s a checklist: Check whether your project has a setup.pywith an install_requiresthat depends on morepath(possibly indirectly through another dependency). You need to declare your code as a project so that autoscancan find it. Check whether your project is installed in a virtualenv using pip install -e .or in a buildout. Morepath needs to be able to find your project in order to scan it. Be sure that you have your modules in an actual sub-directory to the project with its own __init__.py. Modules in the top-level of a project won’t be scanned as a package Try manually scanning a package and see whether it works then: import mysterious_package morepath.scan(mysterious_package) If this fixes things, the package is somehow not being picked up for automatic scanning. Check the package’s setup.py. Try manually importing the modules before doing a morepath.autoscan()and see whether it works then: import mysterious_module morepath.autoscan() If this fixes things, then your own package is not being picked up as a Morepath package for some reason. Try moving Morepath directives into the module that also runs the application. If this works, your own package is not recognized as a proper Morepath package. Variation: automatic restart¶ During development it can be very helpful to have the WSGI server restart the Morepath app whenever a file is changed. Morepath’s built in development server does not offer this feature, but you can accomplish it with Werkzeug’s server. First install the Werkzeug package into your project. Then modify your run module to look like this: import morepath from werkzeug.serving import run_simple from .app import App def run(): morepath.autoscan() App.commit() run_simple('localhost', 8080, App(), use_reloader=True) Using this runner changes to Python code in your package trigger a restart of the WSGI server. Variation: no or multiple entry points¶ Not all packages have an entry point to start it up: a framework app that isn’t intended to be run directly may not define one. Some packages may define multiple apps and multiple entry points. Variation: waitress¶ Instead of using Morepath’s simple built-in WSGI server you can use another WSGI server. The built-in WSGI server is only meant for testing, so we strongly recommend doing so in production. Here’s how you’d use Waitress. First we adjust setup.py so we also require waitress: ... install_requires=[ 'morepath', 'waitress' ], ... Then we modify run.py to use waitress: import waitress ... def run(): ... waitress.serve(App()) Variation: command-line WSGI servers¶ You could also do away with the entry point and instead use waitress-serve on the command line directly. For this we need to first create a factory function that returns the fully configured WSGI app: def wsgi_factory(): morepath.autoscan() App.commit() return App() $ waitress-serve --call myproject.run:wsgi_factory This uses waitress’s --call functionality to invoke a WSGI factory instead of a WSGI function. If you want to use a WSGI function directly we have to create one using the wsgi_factory function we just defined. To avoid circular dependencies you should do it in a separate module that is only used for this purpose, say wsgi.py: prepared_app = wsgi_factory() You can then do: $ waitress-serve myproject.wsgi:prepared_app You can also use gunicorn this way: $ gunicorn -w 4 myproject.wsgi:prepared_app Model module¶ The model.py module is where we define the models relevant to the web application. They may integrate with some kind of database system, for instance the SQLAlchemy ORM. Note that your model code is completely independent from Morepath and there is no reason to import anything Morepath related into this module. Here is an example model.py that just uses plain Python classes: class Document(object): def __init__(self, id, title, content): self.id = id self.title = title self.content = content Variation: models elsewhere¶ Sometimes you don’t want to include model definitions in the same codebase that also implements a web application, as you would like to reuse them outside of the web context without any dependencies on Morepath. Your model classes are independent from Morepath, so this is easy to do: just put them in a separate project and depend on it from your web project. You can also have a project that reuses models defined by another Morepath project. Each Morepath app is isolated from the others by default, so you could remix its models into a whole new web application. Variation: collection module¶ An application tends to contain two kinds of models: - content object models, i.e. a Document. If you use an ORM like SQLAlchemy these would typically be backed by a table. - collection models, i.e. a collection of documents. This typically let you browse content models, search/filter for them, and let you add or remove them. Since collection models tend to not be backed by a database directly but are often application-specific classes, it can make sense to maintain them in a separate collection.py module. This module, like model.py also does not have any dependencies on Morepath. Path module¶ Now that we have models, we need to publish them on the web. First we need to define their paths. We do this in a path.py module: from .app import App from . import model @App.path(model=model.Document, path='documents/{id}') def get_document(id): if id != 'foo': return None # not found return Document('foo', 'Foo document', 'FOO!') In the functions decorated by App.path() we do whatever query is necessary to retrieve the model instance from a database, or return None if the model cannot be found. Morepath allows you to scatter @App.path decorators throughout your codebase, but by putting them all together in a single module it becomes really easy to inspect and adjust the URL structure of your application, and to see exactly what is done to query or construct the model instances. Once it becomes really big you can always split a single path module into multiple ones, though at that point you may want to consider splitting off a separate project with its own application instead. View module¶ We have models and they’re published on a path. Now we need to represent them as actual web resources. We do this in the view.py module: from .app import App from . import model @App.json(model=model.Document) def document_default(self, request): return {'id': self.id, 'title': self.title, 'content': self.content } Here we use App.view(), App.json() and App.html() directives to declare views. By putting them all in a view module it becomes easy to inspect and adjust how models are represented, but of course if this becomes large it’s easy to split it into multiple modules.
https://morepath.readthedocs.io/en/0.15/organizing_your_project.html
CC-MAIN-2018-51
refinedweb
2,169
58.69
Let m=nums1.size(), and n=nums2.size() Solution 1: hashtable (using unordered_map). - time complexity: max(O(m), O(n)) - space complexity: choose one O(m) or O(n) <--- So choose the smaller one if you can vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { if(nums1.size() > nums2.size()) return intersect(nums2, nums1); vector<int> ret; unordered_map<int,int> map1; for(int num:nums1) map1[num]++; for(int num:nums2) { if(map1.find(num)!=map1.end() && map1[num]>0) { ret.push_back(num); map1[num]--; } } return ret; } Solution 2: sort + binary search - time complexity: max(O(mlgm), O(nlgn), O(mlgn)) or max(O(mlgm), O(nlgn), O(nlgm)) - O(mlgm) <-- sort first array - O(nlgn) <--- sort second array - O(mlgn) <--- for each element in nums1, do binary search in nums2 - O(nlgm) <--- for each element in nums2, do binary search in nums1 - space complexity: depends on the space complexity used in your sorting algorithm, bounded by max(O(m), O(n)) vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> ret; if(nums1.empty() || nums2.empty()) return ret; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int j=0; for(int i=0; i<nums1.size(); ) { int index = lower_bound(nums2, nums1[i]); int count2 = 0; while(index<nums2.size() && nums2[index]==nums1[i]) { count2++; index++; } int count1 = 0; while(nums1[j]==nums1[i]) { count1++; j++; } ret.insert(ret.end(),min(count1,count2),nums1[i]); i=j; } return ret; } int lower_bound(const vector<int>& nums, int target) { int l=0, r=nums.size()-1; while(l<r) { int m=l+(r-l)/2; if(nums[m]<target) {l=m+1;} else {r=m;} } return r; } So if two arrays are already sorted, and say m is much smaller than n, we should choose the algorithm that for each element in nums1, do binary search in nums2, so that the complexity is O(mlgn). In this case, if memory is limited and nums2 is stored in disk, partition it and send portions of nums2 piece by piece. keep a pointer for nums1 indicating the current position, and it should be working fine~ Nice solution! I tried to sort only one array and search each element of other unordered arrays, but it does not work. I assume the nums2 on disks are not sorted. So I would prefer make nums1 a hashmap, then read chunks of nums2, query nums1's hashmap, when meet a same value, reduce 1 record in nums1's hashmap. @morrischen2008 if Both of array are sorted, the space complexity could be constant, time complexity is O(m+n). Just use two pointers, one for each array, and do pingpong operation. @hualiang2 Agree, with you, there is no need to cost O(mlogn) or O(nlogm) to search the element from the one from the other among the two arrays. Once both of them are sorted, usingtwo pointers to iterate through the two array become a more obvious solution. below is my solution of quick sort (used built sort), and two pointers: public class Solution { public int[] intersect(int[] nums1, int[] nums2) { ArrayList<Integer> in_sec = new ArrayList<Integer>(); int n1_p = 0; int n2_p = 0; int n1_len = nums1.length; int n2_len = nums2.length; int[] in_sec_arr; int idx = 0; Arrays.sort(nums1); Arrays.sort(nums2); while(n1_p<n1_len && n2_p < n2_len){ while(n1_p<n1_len && n2_p < n2_len && nums1[n1_p] < nums2[n2_p]){ n1_p++; } while(n1_p<n1_len && n2_p < n2_len && nums2[n2_p] < nums1[n1_p]){ n2_p++; } while(n1_p<n1_len && n2_p < n2_len && nums1[n1_p] == nums2[n2_p]){ in_sec.add(nums1[n1_p]); n1_p++; n2_p++; } } in_sec_arr = new int[in_sec.size()]; for (int val: in_sec){ in_sec_arr[idx] = val; idx++; } return in_sec_arr; } } @xuehaohu And some thoughts on the follow up questions: if two arrays are sorted, usingg two pointers, become easy. ( which would help skip sort steps ,and directly get into the two pointers to find intersection) if num1/s size is smaller than nums2 size. First, Hashmap solution is time of O(m) (n is the length of the array which was used to do the count, lets say first one: nums1, and m is the length of the other, which is longer) and space of O(3n) (since the first array us smaller) . and Sort and two pointers solution, are time of max(O(mlogm), O(m+n) ,O(n) ) (as O(mlogm > nlogn since m>n)). and space of O(2n) (arraylist:O(n) and finally constructing the int array O(n) ) So in terms of time: it is a comparsion between: O(m)and max( O(mlogm) , O(m+n) , +O(n) ), and obviously first solution is better, which is using hashmap to do element count for the shorter array. And in terms of space complexity, it is a comparsion between: O(3n) and O(2n) , so the second solution is slightly better as both of them are in same magnitude, there is no much difference. So based on the two comparison above, the first solution is better. - if the longer array cannot be loaded into memory all at one time, it is easy to handle it by first solution, which is find the intersection of the first array with each chunk of the second array loaded into memory, then finally the intersection is still right because: nums1 ∩ nums2 = nums1 ∩ nums2_chunk1 ∩ nums2_chunk2 ∩ nums2_chunk3 ... where nums2 = nums2_chunk1 U nums2_chunk2 U nums2_chunk3 ... @morrischen2008 your solution is fantastic. quick question. why the hash table solution is not complexity O(m+n) ? My intuitive guess was that making up one table takes m insert operations and looking up the element takes n operations. Please kindly suggest your answer. Thanks! Using a unordered_multiset, hope it helps! vector<int> intersectFirst(vector<int>& nums1, vector<int>& nums2) { unordered_multiset<int> hash(nums1.begin(), nums1.end()); vector<int> result; int n2 = nums2.size(); for(int i = 0; i < n2; ++i) { auto iter = hash.find(nums2[i]); if(iter != hash.end()) { result.push_back(nums2[i]); hash.erase(iter); } } return result; } Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/45986/two-c-solutions-hashtable-sort-binary-search-time-space-complexity-analyzed
CC-MAIN-2017-47
refinedweb
1,002
52.7
Sub-builds (antcall, subant) load a task each time the task is defined, but do not release it when the sub-build project completes. It would be best if the sub-build would recognize the task is already loaded, just like it does when the task is loaded within the same project using loaderref. If it is not feasible to re-use the task in this scenario, then it should be released to avoid sucking up all the available memory very quickly. I think this is only a problem with recent (> 1.5.8) releases of Groovy, since it requires so much PermGen. You can't give it enough anymore. The attached script runs out of memory in about 34 iterations of defining the groovy task within an antcall. It can be run as follows, where 3rdparty_libdir is the folder that contains the jars needed for the groovy task: ant -f GroovyMem.xml -Diterations=100 -D3rdparty_libdir=\3rdPartyJars\lib Note: The script uses AntContrib to iterate. Created attachment 25209 [details] Analysis Script Demonstrates memory bug with: ant -f GroovyMem.xml -Diterations=100 -D3rdparty_libdir=\3rdPartyJars\lib I ran into a similar problem. It appears that <taskdef> creates a new classloader every time (makes sense), but uses the J2EE delegation model and doesn't tie that classloader to the task/project that created it (doesn't make sense to me, but there might be a reason). So the classes never get GC'd. A longer writeup is on blog.kdgregory.com, today's date. There is a work-around: use Groovy via antlib, just like you're already doing with ant-contrib. Change your <project> element like this: <project name="GroovyMem" default="all" xmlns:antc="antlib:net.sf.antcontrib" xmlns: Then delete all of the <taskdef>s, and refer to the Groovy tasks using the namespace prefix: <target name="run_groovy"> <groovy:groovy> // do nothing </groovy:groovy> </target> Note that you will have to add Groovy to Ant's runtime classpath. My preferred way to do this is with the "-lib" command-line option.
https://bz.apache.org/bugzilla/show_bug.cgi?id=49021
CC-MAIN-2021-25
refinedweb
340
63.8
Section 5.5 More Details of Classes ALTHOUGH THE BASIC IDEAS of object-oriented programming are reasonably simple and clear, they are subtle, and they take time to get used to. And unfortunately, beyond the basic ideas there are a lot of details. This section covers more of those annoying details. You should not necessarily master everything in this section the first time through, but you should read it to be aware of what is possible. (This doesn't apply to the first subsection, below, which you definitely need to master.) For the most part, when I need to use material from this section later in the text, I will explain it again briefly, or I will refer you back to this section. Extending Existing Classes The previous section discussed subclasses, including information about how to program with subclasses in Java. However, that section dealt mostly with the theory. In this section, I want to emphasize the practical matter of Java syntax by giving anclass subclass-name extends existing-class-name { . . // Changes and additions. . } (Of course, the class can optionally be declared to be public.) As an example, suppose you want to write a program that plays the card game, Blackjack. You can use the Card, Hand, and Deck classes developed in Section { public int getBlackjackValue() { // Returns the value of this hand for the // game of Blackjack. int val; // The value computed for the hand. boolean ace; // This will be set to true if the // hand contains an ace. int cards; // Number of cards in the hand. val = 0; ace = false; cards = getCardCount(); getBlackjackValue(). For example, if bHand is a variable of type BlackjackHand, then the following are all legal method calls: bHand.getCardCount(), bHand.removeCard(0), and bHand.getBlackjackValue(). Inherited variables and methods from the Hand class can also be used in the definition of BlackjackHand (except for any that are declared to be private). The statement "cards = getCardCount();" in the above definition of getBlackjackValue() calls the instance method getCardCount(), which was defined in the Hand class. Extending existing classes is an easy way to build on previous work. We'll see that many standard classes have been written specifically to be used as the basis for making subclasses. Interfaces Some object-oriented programming languages, such as C++, allow a class to extend two or more superclasses. This is called multiple inheritance. In the illustration below, for example, class E is shown as having both class A and class B as direct superclasses, while class F has three direct superclasses. Such multiple inheritance is not allowed in Java. The designers of Java wanted to keep the language reasonably simple, and felt that the benefits of multiple inheritance were not worth the cost in increased complexity. However, Java does have a feature that can be used to accomplish many of the same goals as multiple inheritance: interfaces. We've encountered the term "interface" before, in connection with black boxes in general and subroutines in particular. The interface of a subroutine consists of the name of the subroutine, its return type, and the number and types of its parameters. This is the information you need to know if you want to call the subroutine. A subroutine also has an implementation: the block of code which defines it and which is executed when the subroutine is called. In Java, interface is a reserved word with an additional meaning. An "interface" in Java consists of a set of subroutine interfaces, without any associated implementations. A class can implement an interface by providing an implementation for each of the subroutines specified by the interface. Here is an example of a very simple Java interface:public interface Drawable { public void draw(); } This looks much like a class definition, except that the implementation of the method draw() is omitted. A class that implements the interface, Drawable, must provide an implementation for this method. Of course, the class objects, but can be used as a basis for building other classes. The subroutines in an interface are abstract methods, which must be implemented in any concrete class that implements the interface. And as with abstract classes, even though you can't construct an object from an interface, you can declare a variable whose type is given by the interface. For example, if Drawable is an interface, and if Line and FilledCircle are classes that implement Drawable, then you could say:Drawable figure; // Declare a variable of type Drawable. It can // refer to any object that implements the // Drawable interface. figure = new Line(); // figure now refers to an object of class Line has a draw() method. Note that a type is something that can be used to declare variables. A type can also be used to specify the type of a parameter in a subroutine, or the return type of a function. In Java, a type can be either a class, an interface, or one of the eight built-in primitive types. These are the only possibilities.. You'll learn about some of these standard interfaces in the next few chapters. The Special Variables this and super that can be used inside the class where the variable or method is defined. But a class does not actually contain instance variables or methods, only their source code. Actual instance variables and methods are contained in objects. To get at an instance variable or method from outside the class definition, you need a variable that refers to the object. Then the full name is of the form variable-name.simple-name. But suppose you are writing a class definition, and you want to refer to the object that contains the instance method you are writing? Suppose you want to use a full name for an instance variable, because its simple name is hidden by a local variable? Java provides a special, predefined variable named "this" that you can use for these purposes. The variable, this, can be used in the source code of an instance method to refer to the object that contains the method. If x is an instance variable, then this.x can be used as a full name for that variable. Whenever the computer executes an instance method, it is another common use method should change the values of the dice, the squares it visits become a brighter red. The result looks interesting, but I think it would be prettier if the pattern were symmetric. A symmetric version of the applet is shown at the bottom of this page.. This class uses features of Java that you won't learn about for a while yet, but the actual task of brightening a square is done by a single at the bottom of this page., which was introduced in the previous subsection.. More about Access Modifiers A class can be declared to be public. A public class can be accessed from anywhere. Certain classes have to be public. A class that defines a stand-alone application must be public, so that the system will be able to get at its main() routine. A class that defines an applet must be public so that it can be used by a Web browser. If a class is not declared to be public, then it can only be used by other classes in the same "package" as the class. Packages are discussed in Section 4.5. Classes that are not explicitly declared to be in any package are put into something called the default package. All the examples in this textbook are in the default package, so they are all accessible to one another whether or not they are declared public. So, except for applications and applets, which must be public, it makes no practical difference whether our classes are declared to be public or not. However, once you start writing packages, it does make a difference. A package should contain a set of related classes. Some of those classes are meant to be public, for access from outside the package. Others can be part of the internal workings of the package, and they should not be made public. A package is a kind of black box. The public classes in the package are the interface. (More exactly, the public variables and subroutines in the public classes are the interface). The non-public classes are part of the non-public implementation. Of course, all the classes in the package have unrestricted access to one another. Following this model, I will tend to declare a class public if it seems like it might have some general applicability. If it is written just to play some sort of auxiliary role in a larger project, I am more likely not to make it public. A member variable or subroutine in a class can also be declared to be public, which means that it is accessible from anywhere. It can be declared to be private, which means that it accessible only from inside the class where it is defined. Making a variable private gives you complete control over that variable. The only code that will ever manipulate it is the code you write in your class. This is an important kind of protection. If no access modifier is specified for a variable or subroutine, then it is accessible from any class in the same package as the class. As with classes, in this textbook there is no practical difference between declaring a member public and using no access modifier at all. However, there might be stylistic reasons for preferring one over the other. And a real difference does arise once you start writing your own packages. There is a third access modifier that can be applied to a member variable or subroutine. If it is declared to be protected, then it can be used in the class where it is defined and in any subclass of that class. This is obviously less restrictive than private and more restrictive than public. Classes that are written specifically to be used as a basis for making subclasses often have protected members. The protected members are there to provide a foundation for the subclasses to build on. But they are still invisible to the public at large. Mixing Static and Non-static Classes, as I've said, have two very distinct purposes. A class can be used to group together a set of static member variables and static member subroutines. Or it can be used as a factory for making objects. The non-static variables and subroutine definintions in the class specify the instance variables and methods of the objects. In most cases, a class performs one or the other of these roles, not both. Sometimes, however, static and non-static members are mixed in a single class. In this case, the class plays a dual role. Sometimes, these roles are completely separate. It is also possible for the static and non-static parts of a class to interact. This happens when instance methods use static member variables or call static member subroutines. An instance method belongs to an object, not to the class itself, and there can be many objects with their own versions of the instance method. But there is only one copy of a static member variable. So, effectively, we have many objects sharing that one variable. As an example, let's rewrite the Student class that was used in the Section 2. I've added an ID for each student and a static member called nextUniqueID. Although there is an ID variable in each student object, there is only one nextUniqueID variable.public class Student { private String name; // Student's name. private int ID; // Unique ID number for this student. public double test1, test2, test3; // Grades on three tests. private static int nextUniqueID = 0; // keep track of next available unique ID number Student(String theName) { // Constructor for Student objects; // provides a name for the Student, // and assigns the student a unique // ID number. name = theName; nextUniqueID++; ID = nextUniqueID; } public String getName() { // Accessor method for reading value of private // instance variable, name. return name; } public int getID() { // Accessor method for reading value of ID. return ID; } public double getAverage() { // Compute average test grade. return (test1 + test2 + test3) / 3; } } // end of class Student The initialization "nextUniqueID = 0" is done only once, when the class is first loaded. Whenever a Student object is constructed and the constructor says "nextUniqueID++;", it's always the same static member variable that is being incremented. When the very first Student object is created, nextUniqueID becomes 1. When the second object is created, nextUniqueID becomes 2. After the third object, it becomes 3. And so on. The constructor stores the new value of nextUniqueID in the ID variable of the object that is being created. Of course, ID is an instance variable, so every object has its own individual ID variable. The class is constructed so that each student will automatically get a different value for its ID variable. Furthermore, the ID variable is private, so there is no way for this variable to be tampered with after the object has been created. You are guaranteed, just by the way the class is designed, that every student object will have its own permanent, unique identification number. Which is kind of cool if you think about it. End of Chapter 5 [ Next Chapter | Previous Section | Chapter Index | Main Index ]
http://math.hws.edu/eck/cs124/javanotes3/c5/s5.html
crawl-002
refinedweb
2,224
63.7
KDECore #include <k3resolver.h> Detailed Description Name and service resolution class. This class provides support for doing name-to-binary resolution for nodenames and service ports. You should use this class if you need specific resolution techniques when creating a socket or if you want to inspect the results before calling the socket functions. You can either create an object and set the options you want in it or you can simply call the static member functions, which will create standard Resolver objects and dispatch the resolution for you. Normally, the static functions will be used, except in cases where specific options must be set. A Resolver object defaults to the following: - address family: any address family - socket type: streaming socket - protocol: implementation-defined. Generally, TCP - host and service: unset - Deprecated: - Use KSocketFactory or KLocalSocket instead Definition at line 312 of file k3resolver.h. Member Enumeration Documentation Error codes. These are the possible error values that objects of this class may return. See errorString() for getting a string representation for these errors. - AddrFamily: Address family for the given nodename is not supported. - TryAgain: Temporary failure in name resolution. You should try again. - NonRecoverable: Non-recoverable failure in name resolution. - BadFlags: Invalid flags were given. - Memory: Memory allocation failure. - NoName: The specified name or service doesn't exist. - UnsupportedFamily: The requested socket family is not supported. - UnsupportedService: The requested service is not supported for this socket type (i.e., a datagram service in a streaming socket). - UnsupportedSocketType: The requested socket type is not supported. - UnknownError: An unknown, unexpected error occurred. - SystemError: A system error occurred. See systemError(). - Canceled: This request was canceled by the user. Definition at line 397 of file k3resolver.h. Flags for the resolution. These flags are used for setting the resolution behaviour for this object: - Passive: resolve to a passive socket (i.e., one that can be used for binding to a local interface) - CanonName: request that the canonical name for the given nodename be found and recorded - NoResolve: request that no external resolution be performed. The given nodename and servicename will be resolved locally only. - NoSrv: don't try to use SRV-based name-resolution. - Multiport: the port/service argument is a list of port numbers and ranges. (future extension) - Note - SRV-based lookup and Multiport are not implemented yet. Definition at line 367 of file k3resolver.h. Address family selection types. These values can be OR-ed together to form a composite family selection. - UnknownFamily: a family that is unknown to the current implementation - KnownFamily: a family that is known to the implementation (the exact opposite of UnknownFamily) - AnyFamilies: any address family is acceptable - InternetFamily: an address for connecting to the Internet - InetFamily: alias for InternetFamily - IPv6Family: an IPv6 address only - IPv4Family: an IPv4 address only - UnixFamily: an address for the local Unix namespace (i.e., Unix sockets) - LocalFamily: alias for UnixFamily Definition at line 334 of file k3resolver.h. Status codes. These are the possible status for a Resolver object. A value greater than zero indicates normal behaviour, while negative values either indicate failure or error. - Idle: resolution has not yet been started. - Queued: resolution is queued but not yet in progress. - InProgress: resolution is in progress. - PostProcessing: resolution is in progress. - Success: resolution is done; you can retrieve the results. - Canceled: request canceled by the user. - Failed: resolution is done, but failed. Note: the status Canceled and the error code Canceled are the same. Note 2: the status Queued and InProgress might not be distinguishable. Some implementations might not differentiate one from the other. Definition at line 435 of file k3resolver.h. Constructor & Destructor Documentation Default constructor. Creates an empty Resolver object. You should set the wanted names and flags using the member functions before starting the name resolution. - Parameters - Definition at line 275 of file k3resolver.cpp. Constructor with host and service names. Creates a Resolver object with the given host and service names. Flags are initialised to 0 and any address family will be accepted. - Parameters - Definition at line 281 of file k3resolver.cpp. Destructor. When this object is deleted, it'll destroy all associated resources. If the resolution is still in progress, it will be canceled and the signal will not be emitted. Definition at line 288 of file k3resolver.cpp. Member Function Documentation Cancels a running request. This function will cancel a running request. If the request is not currently running or queued, this function does nothing. Note: if you tell the signal to be emitted, be aware that it might or might not be emitted before this function returns. - Parameters - Definition at line 496 of file k3resolver.cpp. Returns the domain name in an ASCII Compatible Encoding form, suitable for DNS lookups. This is the base for International Domain Name support over the Internet. Note this function may fail, in which case it'll return a null QByteArray. Reasons for failure include use of unknown code points (Unicode characters). Note that the encoding is illegible and, thus, should not be presented to the user, except if requested. - Parameters - - Returns - the ACE-encoded suitable for DNS queries if successful, a null QByteArray if failure. Definition at line 1026 of file k3resolver.cpp. Does the inverse of domainToAscii() and return an Unicode domain name from the given ACE-encoded domain. This function may fail if the given domain cannot be successfully converted back to Unicode. Reasons for failure include a malformed domain name or good ones whose reencoding back to ACE don't match the form given here (e.g., ACE-encoding of an already ASCII-compatible domain). It is, however, guaranteed that domains returned by domainToAscii() will work. - Parameters - - Returns - the Unicode representation of the given domain name if successful, the original string if not - Note - ACE = ASCII-Compatible Encoding, i.e., 7-bit Definition at line 1032 of file k3resolver.cpp. The same as above, but taking a QString argument. - Parameters - - Returns - the Unicode representation of the given domain name if successful, QString() if not. Definition at line 1038 of file k3resolver.cpp. Retrieve the error code in this object. This function will return NoError if we are not in an error condition. See status() and StatusCodes to find out what the current status is. - See also - errorString for getting a textual representation of this error Definition at line 301 of file k3resolver.cpp. Returns the textual representation of the error in this object. Definition at line 312 of file k3resolver.cpp. Returns the string representation of this error code. - Parameters - - Returns - the string representation. This is already i18n'ed. Definition at line 540 of file k3resolver.cpp. Handles events. Reimplemented from QObject. This function handles the events generated by the manager indicating that this object has finished processing. Do not post events to this object. Definition at line 516 of file k3resolver.cpp. This signal is emitted whenever the resolution is finished, one way or another (success or failure). The results parameter will contain the resolved data. Note: if you are doing multiple resolutions, you can use the QObject::sender() function to distinguish one Resolver object from another. - Parameters - - Note - This signal is always delivered in the GUI event thread, even for resolutions that were started in secondary threads. Retrieves the flags set for the resolution. Definition at line 367 of file k3resolver.cpp. Returns true if this object is currently running. Definition at line 318 of file k3resolver.cpp. Returns this machine's local hostname. - Returns - this machine's local hostname Definition at line 961 of file k3resolver.cpp. The nodename to which the resolution was/is to be performed. Definition at line 324 of file k3resolver.cpp. Normalise a domain name. In order to prevent simple mistakes in International Domain Names (IDN), it has been decided that certain code points (characters in Unicode) would be instead converted to others. This includes turning them all to lower case, as well certain other specific operations, as specified in the documents. For instance, the German 'ß' will be changed into 'ss', while the micro symbol 'µ' will be changed to the Greek mu 'μ'. Two equivalent domains have the same normalised form. And the normalised form of a normalised domain is itself (i.e., if d is normalised, the following is true: d == normalizeDomain(d) ) This operation is equivalent to encoding and the decoding a Unicode hostname. - Parameters - - Returns - the normalised domain, or QString() if the domain is invalid. Definition at line 1046 of file k3resolver.cpp. Resolves a protocol number to its names. Note: the returned QStrList operates on deep-copies. - Parameters - - Returns - all the protocol names in a list. The first is the "proper" name. Definition at line 608 of file k3resolver.cpp. Finds all aliases for a given protocol name. - Parameters - - Returns - all the protocol names in a list. The first is the "proper" name. Definition at line 668 of file k3resolver.cpp. Resolves a protocol name to its number. - Parameters - - Returns - the protocol number or -1 if we couldn't locate it Definition at line 728 of file k3resolver.cpp. Resolve the nodename and service name synchronously. This static function is provided as convenience for simplifying name resolution. It resolves the given host and service names synchronously and returns the results it found. It is equivalent to the following code: - Parameters - - Returns - a KResolverResults object containing the results - See also - KResolverResults for information on how to obtain the error code Definition at line 582 of file k3resolver.cpp. Start an asynchronous name resolution. This function is provided as a convenience to simplify the resolution process. It creates an internal KResolver object, connects the finished() signal to the given slot and starts the resolution asynchronously. It is more or less equivalent to the following code: Note: this function may trigger the signal before it returns, so your code must be prepared for this situation. You should use it like this in your code: - Parameters - - Returns - true if the queuing was successful, false if not - See also - KResolverResults for information on how to obtain the error code Definition at line 594 of file k3resolver.cpp. Retrieves the results of this resolution. Use this function to retrieve the results of the resolution. If no data was resolved (yet) or if we failed, this function will return an empty object. - Returns - the resolved data Definition at line 504 of file k3resolver.cpp. The service name to which the resolution was/is to be performed. Definition at line 330 of file k3resolver.cpp. Finds all the aliases for a given service name. Note: the returned QList<QByteArray> operates on deep-copies. - Parameters - - Returns - all the service names in a list. The first is the "proper" name. Definition at line 841 of file k3resolver.cpp. Resolves a port number to its names. Note: the returned QList<QByteArray> operates on deep copies. - Parameters - - Returns - all the service names in a list. The first is the "proper" name. Definition at line 901 of file k3resolver.cpp. Resolves a service name to its port number. - Parameters - - Returns - the port number in host byte-order or -1 in case of error Definition at line 785 of file k3resolver.cpp. Sets both the host and the service names. Setting either value to QString() will unset them. - Parameters - Definition at line 360 of file k3resolver.cpp. Sets the error codes. Sets the allowed socket families. - Parameters - - See also - SocketFamilies for possible values Definition at line 385 of file k3resolver.cpp. Sets the flags. - Parameters - - Returns - the old flags Definition at line 373 of file k3resolver.cpp. Sets the nodename for the resolution. Set the nodename to QString() to unset it. - Parameters - Definition at line 336 of file k3resolver.cpp. Sets the protocol we want. Protocols are dependent on the selected address family, so you should know what you are doing if you use this function. Besides, protocols generally are either stream-based or datagram-based, so the value of the socket type is also important. The resolution will fail if these values don't match. When using an Internet socket, the values for the protocol are the IPPROTO_* constants, defined in <netinet/in.h>. You may choose to set the protocol either by its number or by its name, or by both. If you set: - the number and the name: both values will be stored internally; you may set the name to an empty value, if wanted - the number only (name = NULL): the name will be searched in the protocols database - the name only (number = 0): the number will be searched in the database - neither name nor number: reset to default behaviour - Parameters - Definition at line 405 of file k3resolver.cpp. Sets the service name to be resolved. Set it to QString() to unset it. - Parameters - Definition at line 348 of file k3resolver.cpp. Sets the socket type we want. The values for the type parameter are the SOCK_* constants, defined in <sys/socket.h>. The most common values are: - SOCK_STREAM streaming socket (= reliable, sequenced, connection-based) - SOCK_DGRAM datagram socket (= unreliable, connectionless) - SOCK_RAW raw socket, with direct access to the container protocol (such as IP) These three are the only values to which it is guaranteed that resolution will work. Some systems may define other constants (such as SOCK_RDM for reliable datagrams), but support is implementation-defined. - Parameters - Definition at line 395 of file k3resolver.cpp. Starts the name resolution asynchronously. This function will queue this object for resolution and will return immediately. The status upon exit will either be Queued or InProgress or Failed. This function does nothing if the object is already queued. But if it had already succeeded or failed, this function will re-start it. Note: if both the nodename and the servicename are unset, this function will not queue, but will set a success state and emit the signal. Also note that in this case and maybe others, the signal finished() might be emitted before this function returns. - Returns - true if this request was successfully queued for asynchronous resolution Definition at line 426 of file k3resolver.cpp. Retrieve the current status of this object. - See also - StatusCodes for the possible status codes. Definition at line 295 of file k3resolver.cpp. Retrieve the associated system error code in this object. Many resolution operations may generate an extra error code as given by the C errno variable. That value is stored in the object and can be retrieved by this function. Definition at line 307 of file k3resolver.cpp. Standard hack to add virtuals later. Definition at line 1051 of file k3resolver.cpp. Waits for a request to finish resolving. This function will wait on a running request for its termination. The status upon exit will either be Success or Failed or Canceled. This function may be called from any thread, even one that is not the GUI thread or the one that started the resolution process. But note this function is not thread-safe nor reentrant: i.e., only one thread can be waiting on one given object. Also note that this function ensures that the finished() signal is emitted before it returns. That means that, as a side-effect, whenever wait() is called, the signal is emitted on the thread calling wait(). - Parameters - - Returns - true if the resolution has finished processing, even when it failed or was canceled. False means the wait timed out and the resolution is still running. Definition at line 445 of file k3resolver.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2014 The KDE developers. Generated on Tue Oct 14 2014 22:47:12 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/4.12-api/kdelibs-apidocs/kdecore/html/classKNetwork_1_1KResolver.html
CC-MAIN-2019-47
refinedweb
2,613
51.14
In this post, we will explore a dataset using Python. The dataset we will use is the Ghouls, Goblins, and Ghost (GGG) dataset available at the kaggle website. The analysis will not be anything complex we will simply do the following. - Data preparation - Data visualization - Descriptive statistics - Regression analysis Data Preparation The GGG dataset is fictitious data on the characteristics of spirits. Below are the modules we will use for our analysis. import pandas as pd import statsmodels.regression.linear_model as sm import numpy as np Once you download the dataset to your computer you need to load it into Python using the pd.read.csv function. Below is the code. df=pd.read_csv('FILE LOCATION HERE') We store the data as “df” in the example above. Next, we will take a peek at the first few rows of data to see what we are working with. Using the print function and accessing the first five rows reveals. It appears the first five columns are continuous data and the last two columns are categorical. The ‘id’ variable is useless for our purposes so we will remove it with the code below. df=df.drop(['id'],axis=1) The code above uses the drop function to remove the variable ‘id’. This is all saved into the object ‘df’. In other words, we wrote over are original ‘df’. Data Visualization We will start with our categorical variables for the data visualization. Below is a table and a graph of the ‘color’ and ‘type’ variables. First, we make an object called ‘spirits’ using the groupby function to organize the table by the ‘type’ variable. Below we make a graph of the data above using the .plot function. A professional wouldn’t make this plot but we are just practicing how to code. We now know how many ghosts, goblins and, ghouls there are in the dataset. We will now do a breakdown of ‘type’ by ‘color’ using the .crosstab function from pandas. We will now make bar graphs of both of the categorical variables using the .plot function. We will now turn our attention to the continuous variables. We will simply make histograms and calculate the correlation between them. First the histograms The code is simply subset the variable you want in the brackets and then type .plot.hist() to access the histogram function. It appears that all of our data is normally distributed. Now for the correlation Using the .corr() function has shown that there are now high correlations among the continuous variables. We will now do an analysis in which we combine the continuous and categorical variables through making boxplots The code is redundant. We use the .boxplot() function and tell python the column which is continuous and the ‘by’ which is the categorical variable. Descriptive Stats We are simply going to calcualte the mean and standard deviation of the continuous variables. df["bone_length"].mean() Out[65]: 0.43415996604821117 np.std(df["bone_length"]) Out[66]: 0.13265391313941383 df["hair_length"].mean() Out[67]: 0.5291143100058727 np.std(df["hair_length"]) Out[68]: 0.16967268504935665 df["has_soul"].mean() Out[69]: 0.47139203219259107 np.std(df["has_soul"]) Out[70]: 0.17589180837106724 The mean is calcualted with the .mean(). Standard deviation is calculated using the .std() function from the numpy package. Multiple Regression Our final trick is we want to explain the variable “has_soul” using the other continuous variables that are available. Below is the code X = df[["bone_length", "rotting_flesh","hair_length"]] y = df["has_soul"] model = sm.OLS(y, X).fit() In the code above we crate to new list. X contains are independent variables and y contains the dependent variable. Then we create an object called model and use the OLS() function. We place the y and X inside the parenthesis and we then use the .fit() function as well. Below is the summary of the analysis There is obviously a lot of information in the output. The r-square is 0.91 which is surprisingly high given that there were not high correlations in the matrix. The coefficiencies for the three independent variables are listed and all are significant. The AIC and BIC are for model comparison and do not mean much in isolation. The JB stat indicates that are distribution is not normal. Durbin watson test indicates negative autocorrelation which is important in time-series analysis. Conclusion Data exploration can be an insightful experience. Using Python, we found mant different patterns and ways to describe the data.
https://educationalresearchtechniques.com/2018/10/05/data-exploration-with-python/
CC-MAIN-2021-10
refinedweb
743
59.9
How To Send Airtime Using Africa's Talking Airtime API with Nodejs(Express). This is a step by step tutorial on how to implement Africa's Talking airtime API to your Node.js(express) application. Check out the whole project from GitHub. Africa's Talking (AT) is a unified API platform for software developers in Africa building SMS, USSD, Voice, Payments and Airtime applications. AT is here to ensure that the developer community in Africa is successful at creating, growing and sustaining great businesses, using their solutions. Prerequisite - Visual Studio Code or IDE of your choice. - Basic knowledge of Node.js. Account Setup and Launch Simulator Let's jump right in and login to our AT accounts. If you don't have an account go ahead and create one here. First, let's launch our sandbox environment. Sandbox is a free test environment that mirrors how users would interact with your application and the API. To learn more about the Sandbox, visit here. When you login to your account, your dashboard should look like this; Navigate to the "Go To Sandbox APP", you will be redirected to this page; Click on launch simulator. Select the country you are developing from and make sure to type in your correct phone number to get accurate results then click on launch. Generate API key We'll go back to our dashboard and click on settings. Then click on API key as shown in the image below. You will be redirected to a page where you'll have to key in your AT account password. Make sure you copy and store the API key safely. Sending Airtime Let's get started. - We'll open our project; you can use your favourite Integrated Development Environment (IDE). Create a new file and name it .env . This is where we will store our environment variables. In this case the apikey, usernameand port. Make sure you use the current generated apikey, use sandbox as the apps username. Use "sandbox" for development in the test environment. - Initialize node using npm initor yarn init. - Let's add some dependencies. Copy either of the two commands to the console in your root directory. npm install express africastalking body-parser dotenvor yarn add express africastalking body-parser dotenv. To handle HTTP POST request in express.js version 4 and above we install body-parsermiddleware. body-parserextracts the entire body portion of an incoming request stream and exposes it on req.body. dotenvloads environment variables from the .env file. - In this tutorial we will be using ES6+ syntax and therefore we will have to add babel. To learn more about babel click here. npm i @babel/core babel-cli @babel/preset-env babel-watch --save-devor yarn add @babel/core babel-cli @babel/preset-env babel-watch --dev. - Now let's create a file in the root directory and name it index.js. Add the following code to the index.js file. import express from "express"; import dotenv from "dotenv"; const router = express.Router(); dotenv.config(); // Set your app credentials const credentials = { apiKey: process.env.apiKey, username: process.env.username } // Initialize the SDK const AfricasTalking = require("africastalking")(credentials) // Get airtime service const airtime = AfricasTalking.AIRTIME // Sending airtime route router.post("/",(req,res) => { const options = { recipients: [{ phoneNumber: req.body.phoneNumber, currencyCode: req.body.currencyCode, amount: req.body.amount }] }; airtime.send(options) .then(response => { console.log(response); res.json(response); }).catch(error => { console.log(error); res.json(error.toString()); }); }) export default router; dotenv.config() method reads the environment variables. const credentials authenticates our application. The airtime route sends a request(req) to the AT airtime 6. Create another file and name it app.js in the same directory(root directory). Copy the following code to this file; import express from "express"; import 'babel-polyfill'; import router from "./index"; import dotenv from "dotenv"; import bodyParser, { json } from "body-parser"; dotenv.config(); const app = express(); const port = process.env.port || 3000; app.listen(port, ()=> console.log(`Listening from ${port}`)); app.use(bodyParser.json()); app.use("/v1", router); Here we set our live server to run on the port set on the .env file or port 3000. Our application listens from the AT API passing the whole body through bodyParser.json() 7. To run our application we will have to modify our package.json file to look like this; { "name": "send_airtime", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "babel app.js --out-dir build", "start": "babel-watch app.js" }, "author": "Cynthia", "license": "ISC", "dependencies": { "africastalking": "^0.5.2", "body-parser": "^1.19.0", "dotenv": "^8.2.0", "express": "^4.17.1", "nodemon": "^2.0.4", "save": "^2.4.0" }, "devDependencies": { "@babel/core": "^7.11.6", "@babel/preset-env": "^7.11.5", "babel-cli": "^6.26.0", "babel-watch": "^7.0.0", "make-runnable": "^1.3.8" } } Notice that in the script tag we have added "build" and "start" .The script build, builds our application with babel which converts the ES6 syntax to (pre 2015 JS) which the environment understands. In the "start" script we have added babel-watch so that when we edit code it will restart upon new changes. 8. Let's run the application using npm start. You should be able to see in your console Listening from port ${your Port}. 9. Open postman, fill in the body as you can see below and run your application. You should receive airtime notification in your sandbox environment. Note, no notification will be sent to your mobile phone. A message will be sent to your sandbox test environment once the transaction is successful. You can track your transactions from the AT Airtime transactions dashboards as shown below. It gives you status updates like successful and failed transactions making it easy to manage your application. That's how you send airtime using the Africa's Talking airtime API. Here is the link to the GitHub repository. Happy Coding!!!
https://developers.decoded.africa/send-airtime-using-africas-talking-airtime-api/
CC-MAIN-2020-50
refinedweb
990
61.63
Hi all In this tutorial I will show you how to get an image from your phone gallery and show it in an imageview. Here we use intents to open up the image gallery and get the image URI. Here I am setting the image type as “image” to get only the images. And on onActivityResult if the result is OK, then get the data using getData() function and converting the imageURI to the stringPath. Then show the image in the imageview using setImageURI. package pack.GetImage; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class GetImageActivity extends Activity { private static final int SELECT_PICTURE = 1; private String selectedImagePath; private ImageView img; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); img = (ImageView)findViewById(R.id.ImageView01); ((Button) findViewById(R.id.Button01)) .setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); System.out.println("Image Path : " + selectedImagePath); img.setImageURI(selectedImageUri); } } }); } } Here is the main.xml file <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <TextView android: <Button android: </Button> <ImageView android: </ImageView> </LinearLayout> Please leave your valuable comments if you found this post useful. Link to this post! Thank u , it works in my application successfully. thank you, above code works in my application. thank you very much for this tuto…:))) but I have a problem with the size of the imageView. It does not take the space I have reserved in xml file. can u help me please… Can’ t really understand the question. I think the problem may be because your image resolution is too small to fit in the provided xml size. Exactly. it is a problem of my image resolution..Thank u James for your help… You’re the man! I’ve spent hours trying to figure out why I could not open file based on value returned by data.getPath(). This is in fact because it is not the real file path and I was missing all of the projection & cursor stuff. Thanks a lot. Remy Pingback: android: cannot load external pictures [solved] « Willing wheels Code works perfect, however after selecting a photo if i click my add photo button again and select a different photo the app force closes . Any way to make this work? Hey dabious please check the Logcat what is the reason for Force Close. Code works great but I am running into this issue.. external allocation too large for this process. Any tutorials on how to implement a down sampling to the images that works with your code above? images store in sd card and open gallary if click on picture then give message(unfortunately camera has stopped) When your code is run then give same message un fortunately camera has stopped. please help me Please reply as soon as possible Hey vineet, please check the logcat and paste here the reason for this problem. then only I can help, because this is a perfectly working code. Thanks a lot. This example is exactly what am i looking. Hi, this works perfectly. But, how if i want to save it into database? can you show me the codes? i’ve spent days on this problems. Thanks in advance. Appreciate. Don’t save the image to the database, but save it to the SDCARD or the application sandbox and save the corresponding path in the database. Hey this code is pretty cool But the only problem I have is “The images I take from camera of my application does not display by this image picker” Can you help me here? Thanx in advance hi.i have got error in this two line 1.import android.provider.MediaStore; 2. private static final int SELECT_PICTURE = 1; please help me… Hi, this works perfectly, bt i want to show the selected image into the next layout.. plz help me.. You will get the path of the image just pass it with putExtra to the next activity and show it in the same way. that’s all. Hi, From API 11 the “managedQuery()” method is depricated so does any one have any isea as how the same program can be done for API 11 and above Eclipse adiced to use CursorLoader but i dont know how to use it thanks for nice info. Ngg.. I’m a student and start learn android, I tried to use this code to take two different picture from gallery and display it into two different imageview. But it can’t work. I just success to display first image, but not for the second. Do you know why is it? Are you setting in the imageview correctly. check once more. it should work with any image.please check your pic request id also. gracias, Saludos from mexico , thanks. thanks …………… Works perfect ! import android.widget.Button; showing error Hi, I have used this code to upload a picture in the header of list view in the Side Menu Navigation. It works fine but, when I close the application, the image disappears. Is there any solution for that? Hi Sri, Didn’t get u.. Image Path value is showing null in it. when you sysout in your program Hey there, i am having the same prob, which say the process has stopped. Cn i check if the ” Cursor cursor = managedQuery(uri, projection, null, null, null);” needs to be deprecated? Thank you for this tuto, , it works successfully, but i need the same work for an xml file. I mean i want to open and read an xml file. the problem is that i can’t see my file in the galery. Have you any suggestion ?? Gallery is for images and videos only, not for other types of files. Install a file explorer app like ES file explorer and there going to right path you can see the XML file. I think your question is “you want to select an xml file by opening a file explorer” Isn’t it? Then you have to make a file browser or Check in Google for Libraries like that. I am sure You will find more than one. Thanks The problem is that when i click to the button to browse my phone contents, i can see only: galerie, contacts, photos and the MP3 player, so how can i access to the other folders. Thinks Thank you James. I installed the explorer, and now i can see all files.
http://www.coderzheaven.com/2012/04/20/select-an-image-from-gallery-in-android-and-show-it-in-an-imageview/
CC-MAIN-2015-06
refinedweb
1,139
67.86
How to solve the Cannot use import statement outside a module In this tutorial, we are going to learn about how to solve the cannot use import statement outside of a module error in browser. When we use an es6 import statement to import one JavaScript file inside another, we might see this following error in our browser console. main.js import { add } from './math.js'; console.log(add(1, 2)); console Uncaught SyntaxError: Cannot use import statement outside a module To fix this error, we need to add the type="module" attribute to our main entry JavaScript file like this. <script type="module" src="main.js"></script> This tells the browser to treat this main.js file as a module instead of a normal script file. If you are getting this error inside the node.js, you can check out my previous tutorial on how to use es6 imports in Node.js.
https://reactgo.com/cant-use-import-statement/
CC-MAIN-2021-17
refinedweb
153
64.1
18/11/2010 at 12:42, xxxxxxxx wrote: User Information: Cinema 4D Version: 11 Platform: Windows ; Mac OSX ; Language(s) : C++ ; --------- Hey all, Well, my plugin is finally released, so no more "tip-toeing" around;) Quick description: Use HID devices for realtime animation/recording in c4d (cross-platform and fully scriptable). I'm already hard at work on the next update to it, in which I'm trying to add proper 3DConnexion and Wiimote tracker support. For this I'm using a library called VRPN. It's basically a server/client based approach to device interfaces; though I'm only really looking to use it on a local basis. So, the basic premise is to create a server that recognizes devices and sends their data to a client that processes the data as one of several Remote types (analog, button, tracker, etc.). This works fine in simple command line executables, but when I add the same working code to my plugin it doesn't work. I'm testing with a 3DConnexion Space Navigator. The really odd thing is when I was first testing I tried a simple client in my c4d plugin (in a scenehook with message that ticked by 30 times per second to ensure the mainloops were being called often enough) and a separate command line server. Initially it didn't work (though it did successfully establish a connection to the server program when c4d launched). It was supposed to output to the console (simple GePrint test message). When I switch to some other window, move the device around, and then go back to c4d, a series of my prints output to the console. When I contacted the developer of VRPN about this, this was the response I got:? So my question is: Is there some limitation in c4d that prevents it from responding to this TCP data correctly, or am I just approaching this wrong? here's an example of a simple client from VRPN #include <stdlib.h> #include <stdio.h> #include <vrpn_Button.h> #include "vrpn_Analog.h" #define PHANTOM_SERVER "[email protected]" /***************************************************************************** * Callback handler * *****************************************************************************/ void VRPN_CALLBACK handle_tracker_change(void *userdata, const vrpn_ANALOGCB a) { printf("Received %d analog output channels (first is %lf)\n", a.channel[1]); } void VRPN_CALLBACK handle_button_change(void *userdata, const vrpn_BUTTONCB b) { static int buttonstate = 1; if (b.state != buttonstate) { printf("button #%d is in state %d\n", b.button, b.state); buttonstate = b.state; } *(int * )userdata = buttonstate; } int main(int argc, char *argv[]) { int done = 0; vrpn_Analog_Remote *tracker; vrpn_Button_Remote *button; /* initialize the tracker */ tracker = new vrpn_Analog_Remote(PHANTOM_SERVER); tracker->register_change_handler(NULL, handle_tracker_change); /* initialize the button */ button = new vrpn_Button_Remote(PHANTOM_SERVER); button->register_change_handler(NULL, handle_button_change); // main loop while (! done ) { // Let tracker receive position information from remote tracker tracker->mainloop(); // Let button receive button status from remote button button->mainloop(); } } /* main */ In my plugin, the mainloops are being called in the Message member of the scenehook, triggered by a MessageData class that ticks by 30 times per second. The variables are declared as private class variables and filled in the Init member. Thanks in advance:) -kvb On 19/11/2010 at 04:24, xxxxxxxx wrote: UPDATE: Ok, I don't think my methodology or approach is the flaw here (I know, right?!? I can't believe it either ). I think I found a bug in the 3DConnexion driver for OSX... or at least how it interacts with c4d. I originally noticed this when working with SDL (3DConnexion support is in place on mac, but not on pc). I found that with the 3DC driver installed and a Space Navigator as the active device in Control4D (my plugin) you had to actually have the system prefs window as the currently active window (not c4d). That was the only way a 3DC device would send data to my plugin. I wrote it off as a problem with SDL; since the 3DC support was just a patch and only for Mac... I assumed it was somewhat "thrown together"... or, well, lets just say I had a more faith in 3DConnexion than I did with just some random person who submitted a patch:D So, on a whim, I decided to uninstall the 3DC driver. Now I can get space nav axis output to the console without having to put focus on another, outside window And I think the display lag was due to the number of prints that were being generated (30/sec*6=180 GePrints/sec). This is sort of good news... as I didn't want to have to get into the IP functions of c4d (which is something I was worried about, since VRPN is designed for large network VR type setups). But then again, I'm still not sure if the fix for the 3DC/c4d thing I've found falls on 3DC or Maxon... I'm hoping it's just a bug in the 3DC driver. I'll pop over to their forum and issue a report. Oh, and I "uninstalled" the spacemouse plugin from c4d early in my testing to make sure that wasn't the problem. Luckily, both SDL and VRPN allow the use of such devices without the 3DC driver installed; but I don't want to have to ask my users to uninstall it to get support. I'll have to do some tests on windows to confirm, of course. If I encounter any other problems at least I have a thread all set up for it, but for the time being I think it's out of my hands and for the moment I'm in pretty good shape. -kvb
https://plugincafe.maxon.net/topic/5343/5345_vrpncan-this-work
CC-MAIN-2021-49
refinedweb
927
60.04
- 0shares - Facebook0 - Twitter0 - Google+0 - Pinterest0 - LinkedIn0 Command Line Argument A command line argument is considered as an argument that is passed to the program when the program is invoked. Command line argument is used in C programming language when we have to control the program from outside. The command line argument is passed to the main () function of the program. The following is the syntax of using the command line argument: SYNTAX: int main ( int argc, char *argv []) In the above syntax argc is used to count the arguments on command line and argv [] is a pointer which is used to hold all the pointers of character type that point to the arguments passed to program. Example for command line argument: Consider the following example for command line argument: CODE: #include <stdio. h> #include <conio. h> int main ( int argc, char *argv [] ) { int x; if ( argc > = 2 ) { printf (“Number of arguments\n”); for (x = 1; x < argc; x++) { printf (“%s\t”, argv [x]); } } else { printf (“List of arguments is empty\n”); } getch (); return 0; } It should be noted here that argv [0] is used to hold the name of the program and argv [1] is used to point to the first command line argument, in this way argv [n] points to the last argument. If we do not provide an argument then “argc” will be one.
http://www.tutorialology.com/c-language/command-line-argument/
CC-MAIN-2017-43
refinedweb
227
60.08
Working with zip files in Python This article explains how one can perform various operations on a zip file using a simple python program. What is a zip file? ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together. Why do we need zip files? - To reduce storage requirements. - To improve transfer speed over standard connections. To work on zip files using python, we will use an inbuilt python module called zipfile. 1. Extracting a zip file The above program extracts a zip file named “my_python_files.zip” in the same directory as of this python script. The output of above program may look like this: Let us try to understand the above code in pieces: from zipfile import ZipFile ZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module. with ZipFile(file_name, 'r') as zip: Here, a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in READ mode and name it as zip. zip.printdir() printdir() method prints a table of contents for the archive. zip.extractall() extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file. For example: zip.extract('python_files/python_wiki.txt') This will extract only the specified file. If you want to read some specific file, you can go like this: data = zip.read(name_of_file_to_read) 2. Writing to a zip file Consider a directory (folder) with such a format: Here, we will need to crawl whole directory and its sub-directories in order to get a list of all file-paths before writing them to a zip file. The following program does this by crawling the directory to be zipped: The output of above program looks like this: Let us try to understand above code by dividing into fragments: def get_all_file_paths(directory): file_paths = [] for root, directories, files in os.walk(directory): for filename in files: filepath = os.path.join(root, filename) file_paths.append(filepath) return file_paths First of all, to get all file paths in our directory, we have created this function which uses the os.walk() method. In each iteration, all files present in that directory are appended to a list called file_paths. In the end, we return all the file paths. file_paths = get_all_file_paths(directory) Here we pass the directory to be zipped to the get_all_file_paths() function and obtain a list containing all file paths. with ZipFile('my_python_files.zip','w') as zip: Here, we create a ZipFile object in WRITE mode this time. for file in file_paths: zip.write(file) Here, we write all the files to the zip file one by one using write method. 3. Getting all information about a zip file The output of above program may look like this: for info in zip.infolist(): Here, infolist() method creates an instance of ZipInfo class which contains all the information about the zip file. We can access all information like last modification date of files, file names, system on which files were created, Zip version, size of files in compressed and uncompressed form,: - Working with csv files in Python - Working with PDF files in Python - Working with excel files using Pandas - Internal working of Set in Python - Internal working of Python - Working with the Python Debugger - Working with Images in Python - Python | Working with Pandas and XlsxWriter | Set – 3 - Internal Working of the len() Function in Python - Python | Working with Pandas and XlsxWriter | Set - 1 - Internal working of list in Python - Python | Working with PNG Images using Matplotlib - Working with Images in Python using Matplotlib - Working with Binary Data in Python - Working With JSON Data in Python - Python | Working with Pandas and XlsxWriter | Set – 2 - Python | Working with buttons in Kivy - Upload files in Python - Interact with files in Python - Reading CSV files in Python
https://www.geeksforgeeks.org/working-zip-files-python/
CC-MAIN-2020-29
refinedweb
710
60.14
in reply to Re^2: XS cannot properly handle typemap with namespace (use XSpp)in thread XS cannot properly handle typemap with namespace It seems XSpp is another system that is completely different with XS. So I'll have to suffer another painful learning...... I hope not, it should be quite simple. See / XS++ - bonding Perl and C++ with minimal pain Object/WithIntAndString.pm XSpp/Example.pm See also Re: Interfacing Perl with C++, using XS, with external files, and using the STL as parameters and return values. Math::ThinPlateSpline / Re: C tutorial for Perl programmers? (hard lint strict warnings bondage perlxspp) SOso-0.01.patch.txt It's indeed painful for me. T_T There are two examples in the XSpp's package, and none of them fully used the XSpp's features. I spent a whole day to realize that xspp typemap should be generated to xs typemap via tools such as Module::Build::WithXSpp, otherwise you cannot use mapped types (like the "Object-WithIntAndString" example in XSpp package which used ExtUtils::MakeMaker). I also downloaded several perl packages which use XSpp, and non of them use the feature neither. Now I nearly make my code correctly compile, but I still don't understand how some errors were fixed and disappeared. And I still don't fully know the difference between "{parsed}{%precall_code %output_code}" and "{simple}{%xs_input_code %xs_output_code}". It seems the first solution don't work properly in my code. Moreover, the xspp lacks error reports. Some errors are not reported by xspp, and will just continue running silently and create malfunction xs code. You have to take hours to find clues about your bug from the final C file, and deduce the corresponding part of the xsp.
http://www.perlmonks.org/?node_id=1069106
CC-MAIN-2016-40
refinedweb
289
64.1
JavaScript modules allow us to divide code into small pieces. They also let us keep some code private while exposing other pieces of code that can be imported into another module. In this article, we’ll look at how to define and use modules. Named exports start with the export keyword – they expose items from inside a module to the outside. Then, we can import them somewhere else. There can be multiple named exports in one module. For instance, we can write: export const foo = 1; export let bar = 1; Then, we can import them into another module as follows: import { foo, bar } from "./module"; const baz = foo + bar; We can also import the whole module with the * sign as follows: import * as module from "./module"; const baz = module.foo + module.bar; import { foo, bar } from "./module"; const baz = foo + bar; // priting console.log(baz) Try out the second method. We can export one default export using the export default keywords. For instance, we can write: export default 1; Then, import it as follows: import foo from "./bar"; const baz = foo; We can also export functions and class as follows: export default () => {}; Or: export default class {} We don’t need a semicolon at the end of the class export. Also, we can define default exports with the following code: const foo = 1; export { foo as default }; In browsers, scripts are denoted by the script tag. Modules are the same, but it’s denoted by the type attribute with the value module. Scripts are not in strict mode by default, but modules are. Top-level variables are global in scripts, but they are local to the module in modules. The top-level value of this is window in scripts and undefined in modules. Scripts are run synchronously, while modules are run asynchronously. There are no import statements in scripts, but we can selectively import module members in modules. We can programmatically import both scripts and modules using promise-based APIs. An ES6 module can be statically analyzed for static checking, optimization, and more. It has a declarative syntax for importing and exporting. Imports are hoisted to the top so that they can be referenced anywhere in the module. For instance, if we have: export const foo = 1; Then, we can import it as follows: import { foo } from "./bar"; const baz = foo; Also, they must be at the top-level. Therefore, we can’t have something like this: const baz = foo; import { foo } from "./bar"; ES6 imports are read-only views on export entities. Connections to variables inside the module that imported the export remain live. For instance, if we have: export const foo = 1; Then, if we have the following: import { foo } from "./bar"; foo = 1; Then, we’ll get a read-only error. Let’s see this in the code snippet below: import { foo } from "./bar"; foo = 1; We get the same result if we change the constto let. If module A and B import members from each other, then we call it a cyclic dependency. This is supported with ES6 modules. For instance, if we have: index.js: import { foo } from "./bar"; export const baz = 2; bar.js: import { baz } from "./index"; export let foo = 1; Then, the modules are cyclic dependencies since we can import a member from bar in index, and import a member from index in bar. This works because imports just refer to the original data, so it doesn’t matter when they come from. We can import JavaScript modules in various ways. One way is the default import, which is how we import members from a module. For instance, we can write: bar.js: let foo = 1; export default foo; Then, we can import it as follows: import foo from "./bar"; Named imports can be imported as follows (given the following named exports): export let foo = 1; Then, we can import it as follows: import { foo } from "./bar"; We can rename named exports by using the as keyword as follows: import { foo as baz } from "./bar"; We can also rename default exports as follows: import { default as foo } from "./bar"; We can also have empty where we don’t import anything. Instead, we run what’s included in the module. For instance, if we have the following in bar.js: console.log("bar"); Then, we can run the code in bar.js as follows: import "./bar"; Therefore, we should see 'bar' logged in the console log. ES6 modules are a great way to divide code into small chunks. We can export module members and import them in another file. Imported members are read-only. Modules are in strict mode by default, which allows us to avoid a lot of the issues that come with non-strict mode. RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/introduction-to-javascript-modules
CC-MAIN-2022-33
refinedweb
799
75.61
Hi, I am needing to take a vector and search it for a certain integer. The goal: To search a vector and confirm or deny if a certain integer is there. The problem: I am having problems searching the vector. Here is what I have been trying to use to search the "bag" of numbers. I have this part of my code below commented out so that the code will compile and run.I have this part of my code below commented out so that the code will compile and run.Code:search (bag.begin(), bag.end(), match1); So could somebody show me how to use this command for a vector? Or is this even the right command to be using or should I go about it a different way? Code:#include <iostream> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; class Bag { protected: vector<int> bag; public: Bag() {}; bool isEmpty() { if (bag.empty()) { cout << "Bag D is empty" << endl; } else { cout << "Fail" << endl; } return 0; }; bool isElement(int x) { cout << "Enter a number to see if it's in the bag." << endl; cin >> x; vector<int>::iterator it; //int match1 = x; //it = search (bag.begin(), bag.end(), match1); if (it!=bag.end()) { cout << "match1 found at position " << int(it-bag.begin()) << endl; } else { cout << "match1 not found" << endl; } return 0; }; void add(int x) { int y; cout << "How many items would you like to put in the bag?" << endl; cin >> y; bag.resize(y); cout << "Enter in " << y << " intergers." << endl; for (int i=0; i<y; i++) cin >> bag[i]; }; void list() { cout << "Here's what's in the bag:" << endl; for (int i=0; i< bag.size(); i++) cout << bag[i] << endl; }; void remove() { }; }; int main() { int x; Bag D; D.isEmpty(); D.add(x); D.list(); return 0; }
https://cboard.cprogramming.com/cplusplus-programming/126029-searching-int-vector.html
CC-MAIN-2017-09
refinedweb
302
82.54
Week 12 - Output Devices I made a second version of my input devices board, with a simplified design, and a header set up for I2C communication with an OLED display. Improving my input devices board After my experience with the previous board, I decided to fix some of its shortcomings: 1) I wanted to get rid of the external pull-up resistors on my 20 pin header. According to the data sheet, pins on ports B, C, D and E all have internal pull-up resistors, which can be turned on by adding a line like this in your Arduino code: void setup() { /* INPUT_PULLUP enables the Arduino Internal Pull-Up Resistor */ pinMode(12, INPUT_PULLUP); } On this header, the first 2 switches are connected to port F pins, which do not seem to have internal pullups. However, I was able to shift my pins around to make use of pins 21 and 22 on this 20-pin header instead, which are both port D pins. I was then able to remove all these pull-up resistors from the board, and also the GND trace that ran all the way over to that side of the board adding more size and complexity. 2) I swapped out my 16MHz crystal for one with the correct footprint, and rearranged the components around it to fit better. 3) The D+ and D- lines from my USB port to the ATMega32U4 have to travel underneath a capacitor. The narrow gap is forcing my traces to be very thin, and possibly causing problems with signal from the USB port. Looking at Luiz’ original board - from which mine is derived, I noticed that: - there are 22Ohm resistors on each of these traces, which I have omitted from my board - he has bridged different GND and VCC pins on the ATMega32U4, meaning he doesn’t need to have these two traces running underneath a decoupling capacitor. 4) Sorting out my decoupling capacitors: I have 8 decoupling capacitors in my original design, however, there are only 5 GND pins (including UGND) and 6 VCC pins (VCC x 2, AVCC x 2, VBUS and UVCC) So I should be able to simplify things here. An explanation of each of these pins: The 2 AVCC are used to power the Analog circuitry, and not connecting them, and not filtering it, would mean shitty analog to digital or digital to analog conversions. If you don’t need the ADC or DAC features it’s not mandatory. The VCC powers the digital circuitry. You should connect both. YMMV if you don’t. Drawing too much power cab cause issues then. The UVCC is for powering the USB circuitry. Again if you don’t use it… VBUS is actually an input that connects to USB power, for sensing when a usb cable is connected. I see I have one capacitor not connected to any VCC net, and another capacitor connected to AREF. Both of these can be removed. 5) I have to rearrange my spare pin headers now that I have swapped around the pins on the main 20x header. I now have 3 spare pins on the bottom side of the chip (18, 19, and 20) and 7 on the top (L-R: 42, AREF, 41, 40, 39, 38, 37, 36), plus up to 2 GND pins I could expose on headers. I could also expose pin 1 on the top left corner of the chip to a header along the top. New header pin tables These are my new header configurations Header A: 20 pins, to right of chip, reading top-bottom Each alternating odd-numbered pin (1, 3, 5, 7, 9, 11, 13, 15, 17, 19) connects to VCC Header B: 10 pins, above chip, reading L-R Header C: 5 pins, below chip, reading L-R Milling and soldering the board I was able to mill the board and solder the parts without too many problems Testing After failing to burn the bootloader using my FabISP, I checked the board for problems and found a couple: two GND pins on the chip were not connected, and a piece of stray copper was shorting the RST and VCC pins on the ISP header. After fixing these, I was able to burn the bootloader, remove the IFabISP, and upload a blink sketch over USB to blink the onboard LED I put on pin PC7 / D13. I was also able to verify that my reset button works. OLED Hello World Then I set about getting my OLED panel to work. I followed these instructions. I had set up my small 5-pin header specifically to enable easy connection of an OLED display, as follows: Display pins -> Header pins 1) VCC -> Header pin 5 2) GND -> Header pin 1 3) SCL -> Header pin 2 4) SDA -> Header pin 3 I then installed the Adafruit Arduino libraries for controlling these SSD1306 displays I configured the SSD1306 driver for my display, as per the instructions:. Comment out #define SSD1306_128_32 and uncomment #define SSD1306_128_64 so that the code in this section looks as follows. /*========================================================================= // #define SSD1306_128_32 // #define SSD1306_96_16 /*=========================================================================*/ I uploaded a basic Hello World Sketch to verify my board and OLED panel worked. Reading an array of buttons and displaying the result Now I was ready to prototype my input and output problem: to read the state of an array of buttons simultaneously, convert that state to a human-readable number, and display the result on a screen. This is one step towards having a media card reader that can identify which card has been inserted and choose the right media to play as a result. I had 5 buttons available, one of which I reserved as an ‘initiate read’ button. That left me 4 buttons, letting me generate a 4 byte binary number (e.g. 0010, 1111, 1001, etc), which would translate to decimal values 0-15. I looked up the maths I would need to convert binary number to decimal, which is of this form: 1011 = (1 × 2³) + (0 × 2²) + (1 × 2¹) + (1 × 2⁰) = 11 So I knew I would need to loop through an array of the values of each button, do some maths on each value, and add up the individual results to store in a running total. Once I’d been through the array, I could print this total to the OLED screen. My Arduino code: // set up array int arrayTest[] = {0, 0, 0, 0}; // an array of pin numbers to which LEDs are attached int arrayCount = 4; // size of array, ie number of buttons I have available int tempTotal = 0; // a number to hold total value in int pushButton1 = 5; // a button to initiate the loop through the array - modified for my Output Devices board // set up array population buttons // I only have 4 buttons, so it will have to be a 4 byte number (ie values 0-15). // int arrayValueButton1 = 12; // pins which each button is connected to, reading left to right int arrayValueButton2 = 6; int arrayValueButton3 = 8; int arrayValueButton4 = 9; // set up defaults for array values int arrayValue1 = 0; int arrayValue2 = 0; int arrayValue3 = 0; int arrayValue4 = 0; // Set up OLED display // Based on // On Arduino Uno, SCL pin is A5, SDA is A4 #include <Wire.h> #include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> #define OLED_ADDR 0x3C // OLED display TWI address Adafruit_SSD1306 display(-1); #if (SSD1306_LCDHEIGHT != 64) #error("Height incorrect, please fix Adafruit_SSD1306.h!"); #endif //End OLED void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // set up buttons to use internal pullup resistors, which menas that thier on/off values are swapped pinMode(pushButton1, INPUT_PULLUP); pinMode(arrayValueButton1, INPUT_PULLUP); pinMode(arrayValueButton2, INPUT_PULLUP); pinMode(arrayValueButton3, INPUT_PULLUP); pinMode(arrayValueButton4, INPUT_PULLUP); // initialize and clear display display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR); display.clearDisplay(); display.display(); // display a pixel in each corner of the screen display.drawPixel(0, 0, WHITE); display.drawPixel(127, 0, WHITE); display.drawPixel(0, 63, WHITE); display.drawPixel(127, 63, WHITE); // update display with all of the above graphics display.display(); } void loop() { // read the value of the 'start' button int buttonState1 = ! digitalRead(pushButton1); // use ! to invert button state if (buttonState1 == 1) { // only read the array if the button has been pressed // reset the total in case we read it previously tempTotal = 0; // read the array value buttons: int arrayValue1 = ! digitalRead(arrayValueButton1); // use ! to invert button state int arrayValue2 = ! digitalRead(arrayValueButton2); int arrayValue3 = ! digitalRead(arrayValueButton3); int arrayValue4 = ! digitalRead(arrayValueButton4); // stick them into an array int arrayTest[] = {arrayValue1, arrayValue2, arrayValue3, arrayValue4}; // loop through that array to read them for (int thisArrayMember = 0; thisArrayMember < arrayCount; thisArrayMember++) { // which member of the array (0, 1, 2, 3... up to max number of members), reading left to right // note, later on this will be reversed - when counting, numbers to the left have a higher value, so it's more useful to have a scale that reads L-R: 3, 2, 1, 0) Serial.print("Member: ");Serial.print(thisArrayMember); // what's the value of that member (0 or 1) Serial.print(" | Value: ");Serial.print(arrayTest[thisArrayMember]); // what's 2 to the power of the position of the member // use ceil() to ensure numbers are rounded correctly // reverse position numbers (arrayCount - thisArrayMember) so numbers to the left are multiplied more // reduce thisArrayMember by 1: to correct for error introduced because arrayCount ranges 1-4, thisArrayMember ranges 0-3 Serial.print(" | 2 to power of position of member: ");Serial.print(ceil(pow(2, (arrayCount - thisArrayMember - 1)))); // Multiply that value by the value of the button (1 or 0) Serial.print(" | Value x 2 to power of position: "); Serial.print(int(arrayTest[thisArrayMember] * ceil(pow(2, (arrayCount - thisArrayMember - 1))))); // and print the running total of all these values added up Serial.print(" | Running total: "); tempTotal = (tempTotal + arrayTest[thisArrayMember] * ceil(pow(2, (arrayCount - thisArrayMember - 1)))); Serial.println(tempTotal); tempTotal = (tempTotal + arrayTest[thisArrayMember] * ceil(pow(2, (arrayCount - thisArrayMember - 1)))); } // end array loop // display final result on OLED display display.setTextSize(2); display.setTextColor(WHITE); display.setCursor(7,3); // line 1 display.print("Number: "); display.setCursor(7,40); // line 2 display.print(tempTotal); display.display(); // update display with all of the above graphics display.clearDisplay(); // clears the buffer so it can be rewritten with new values when they arrive - doesn't clear the screen } } After many hours of breaking down the problem, and squashing bugs, it finally worked: Some questions and problems While I get this far, the process has led to new questions, and revealed some problems with my board For my large 20 pin header, I intended to leave each alternate pin accesible for all the connected buttons. I wired all these pins to VCC. Actually, given that the ATMega32U4 has internal pullup resistors, I should have connected them to GND. So in this case, I didn’t use them, and instead, made use of one of the other GND pins I had exposed to a pin (as recommended by Luiz. It makes me think that actually, having 10 identical pins available, even if they are wired up correctly is probably not much use. The OLED display uses I2C communication. I don’t know if i will also need to use this for some other parts of my final project, and if so, will there be a conflict. When testing on my board, and also on a commercial Arduino board, I noticed some memory alerts. On the Arduino, with all my serial debugging code, the programme above uses 79% of program memory. With the serial code commented out it uses 64%. And on my homebrew Leonardo board, it uses 57$% (again, without debugging code). Maybe this will cause problems later on. I noticed that not all of the pins on my dedicated ‘button header’ (the 20 pin header) worked. When I have access to more button hardware, and when I’m ready to connect up other parts of my system, such as the MP3/SD card reader, and playback controls, I need to verify that I can get all these to work. I could also try using a PISO shift register to reduce the number of pins needed for this part of the system. From an earlier code test, these were the pins that worked/didn’t work: int pushButton = HWB; // header pin 2- DOESNT WORK int pushButton = 5; // header pin 4 - WORKS int pushButton = 6; // header pin 6 - DOESNT WORK int pushButton = 9; // header pin 8 - WORKS int pushButton = 8; // header pin 10 - WORKS int pushButton = 6; // header pin 12 - WORKS int pushButton = 12; // header pin 14 - WORKS int pushButton = 4; // header pin 16 - DOESNT WORK int pushButton = 17; // TXLED // header pin 18 - DOESNT WORK int pushButton = 1; // header pin 20 - WORKS Group assignment We used an oscilloscope to measure the power consumption of an output device - a motor. Files Eagle files for my board Arduino test files
http://fab.academany.org/2018/labs/fablabbrighton/students/andrew-sleigh/assignments/2018/04/15/wk12-output-devices.html
CC-MAIN-2018-34
refinedweb
2,130
56.69
Jay Garcia @ModusJesus || Modus Create co-founder Ext JS in Action author Sencha Touch in Action author Get in touch for Ext JS & Sencha Touch Touch Training hi sorry for putting this up in the forum. but i don't know how to proceed. i am a beginner in javascript and completely new to ext-js. in my error console i can see the error is in ext-base.js line9. but the file is not easily readable. i am getting the error, even after i reduced my code to Ext.ux.ProgressColumn = Ext.extend(Ext.grid.Column, { }); how can i proceed debugging from here? thanks Use ext-base-debug.js and ext-all-debug.js for debugging! Jay Garcia @ModusJesus || Modus Create co-founder Ext JS in Action author Sencha Touch in Action author Get in touch for Ext JS & Sencha Touch Touch Training For my use i added a new attribute: and changed the colored-part to this:and changed the colored-part to this:PHP Code: /** * @cfg {boolean} invertedColor if timespan is used */ invertedColor : false So it demonstrates better the time that approachs.So it demonstrates better the time that approachs.PHP Code: if (this.colored == true) { if(this.invertedColor == true) { if (v > 66) style = '-red'; if (v < 67 && v > 33) style = '-orange'; if (v < 34) style = '-green'; } else { if (v <= 100 && v > 66) style = '-green'; if (v < 67 && v > 33) style = '-orange'; if (v < 34) style = '-red'; } } i.e. 99% of the time between now and endtime of a project is critical -> red ! great extension indeed.. Thank u so much Animal.. I just want to ask is it compatible with Grouping Grid? I tried to use, but I wasn't able to see any changes in the cell? I'll be happy if someone helps me.. Thanks in advance.. "People will never forget how you made them feel." linkedin.com/in/talhakabakus Hi, Thank you for this good extension. In my project I need to choose the color of the progress bar in function of an other column, to do this I have changed the initial code, it seems to me to be good to integrate this update in the original version: My little modifications are in bold. Bye and again thank you for this pluginBye and again thank you for this pluginCode:getBarClass: function(fraction, value, meta, record, rowIndex, colIndex, store) { return (fraction > 0.98) ? 'high' : (fraction > 0.75) ? 'medium' : 'low'; } // private renderer: function(value, meta, record, rowIndex, colIndex, store) { var fraction = this.getFraction.apply(this, arguments), pct = fraction * 100, displayVal; Array.prototype.push.call(arguments, pct); displayVal = this.baseRenderer.apply(this, arguments); if (record) { meta.css += ' x-grid3-td-progress-cell'; return this.tpl.apply({ align: this.align || 'left', value: displayVal, pct: fraction * 100, qtip: this.getQtip.apply(this, arguments), cls: this.getBarClass(fraction, value, meta, record, rowIndex, colIndex, store) }); } else { return displayVal; } } Cyberal Hi!...this is error when integrate whit grouping and summay p is null line 148 display bar good in grid but not in summary row. Any suguestions? sorry my bad inglish. Anyone have this plugin working with 4.1.0? - Joe
https://www.sencha.com/forum/showthread.php?80465-Ext.ux.ProgressColumn-a-Column-subclass-to-display-progress-bars-in-grid-cells./page4
CC-MAIN-2017-26
refinedweb
521
68.06
Passing an array of values conforming to the schema of the data source to the add function adds data to the data source: $find(<GRID_CLIENT_ID>).get_rows().add(<NEW_VALUES_ARRAY>); To remove a row, the remove function is used: $find(<GRID_CLIENT_ID>).get_rows().remove(<ROW_INSTANCE>,false); Updates to data in the grid are persisted by wrapping the WebDataGrid in an UpdatePanel and initiating a post back to the server. The WebDataGrid provides a rich API for conducting CRUD operations on the server, but many customers are not aware of the client-side API available for adding, modifying and removing rows from the data source. The key to executing these operations on the client is being aware of a few lines of JavaScript. This tutorial demonstrates how to insert, update and delete data in the grid entirely from the client.. Consider a page that has a grid and a few other controls available to the user: The WebDataGrid is responsible for displaying data in the standard manner. Deleting a row from the grid (and subsequently the data source) is a simple matter of clicking on the row selector and pressing the Delete button. Updates to the grid’s data are made in-line in the grid and are not instantly saved. The grid allows you to edit as many fields as you wish and changes are persisted by clicking the Update button. Finally, data is added to the data source by entering the required data and then clicking the Add button.. Be sure to download the code here to step through the code on your own. The markup for this sample includes a number of different controls which are discussed in sections. The first group of controls on the page are the WebDataGrid and UpdatePanel. The markup for this sample begins with the traditional inclusion of the ScriptManager and the WebDataGrid. A small twist to this sample is the use of an UpdatePanel that surrounds the grid and a few button controls. The WebDataGrid features a pay-to-play model where the scripts and other resources required by the grid for it’s rich features are only served to the client if the behaviors are enabled. Therefore examine the below screenshot of the behaviors editor to get an idea of the behaviors required to execute client CRUD. Enabling Cell Editing, Row Adding and Row Deleting ensures the script files needed to enable these behaviors on the grid are served to the client. The Row Selectors behaviors is enabled to provide a place to the user to select an entire row, which is required to remove a row. Finally, the Selection behavior is needed to format how the row selection is conducted. In this case when a cell or the row selector is clicked, the entire row is selected. Selecting the whole row is necessary so the grid will fire the RowSelectionChanged event, which in this case is handled by the onRowSelectionChanged function. This function provides the hooks needed to programmatically locate selected row. To see how all these settings translate into markup, here is the UpdatePanel and grid markup for the page: <asp:UpdatePanel <ContentTemplate> <ig:WebDataGrid <Columns> <ig:BoundDataField <ig:BoundDataField </Columns> <Behaviors> <ig:EditingCore> <Behaviors> <ig:CellEditing /> <ig:RowAdding /> <ig:RowDeleting /> </Behaviors> </ig:EditingCore> <ig:Selection <SelectionClientEvents RowSelectionChanged="onRowSelectionChanged" /> </ig:Selection> <ig:RowSelectors> </ig:RowSelectors> </Behaviors> </ig:WebDataGrid> <input type="button" value="Delete" onclick="del();" /> <asp:Button </ContentTemplate> </asp:UpdatePanel> An ASP.NET data source control is required to provide an interface for the WebDataGrid to access the application’s persistence mechanisms. This sample uses the ObjectDataSource, but you may use any other data source control for your purposes. The data source control points to the matching methods off a class named PersonRepository to delegate the work of persisting changes: <asp:ObjectDataSource <DeleteParameters> <asp:Parameter </DeleteParameters> </asp:ObjectDataSource> Notice the event handler for onobjectcreating. This event handler is used in order to provide the data source control with a single instance of the PersonRepository class, rather than a new instance being created upon each operation of the data source control. There are a few lines of code in the code behind in order to provide the control with it’s object instance: using System; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { private WebStateRepository<personrepository> _repository = new WebStateRepository<personrepository>(); protected void ods_ObjectCreating(object sender, ObjectDataSourceEventArgs e) { e.ObjectInstance = this._repository.Instance; } protected void Page_PreRender(object sender, EventArgs e) { if (this.Page.IsPostBack) { this._repository.Persist(); } } } The important part of this code listing is in the body of the ods_ObjectCreating method. This is where you give the ObjectDataSource control the instance of the object you want to use. Note: The WebStateRepository class is a utility class used in this sample to store the object collection in session state. In your implementation, you will simply point the data source control to an instance of your real repository class. Note: The WebStateRepository class is a utility class used in this sample to store the object collection in session state. In your implementation, you will simply point the data source control to an instance of your real repository class. The listing below demonstrates the markup required to render the text boxes which give the user a place to enter the new person’s first and last name. When the Add button is clicked, a JavaScript function named add is run on the page. <div> <input type="text" id="firstName" name="firstName" /> <input type="text" id="lastName" name="lastName" /> <input type="button" value="Add" onclick="add();" /> </div> Up to this point all the code in this article should be relatively familiar to you. The last step required is to wire up the client-side messages to add and delete data. (Remember updates are sent to the server in a batch by changing data in-line in the grid and initiating a post back to the server inside an UpdatePanel) function add() { var grid = $find("<%= wdg.ClientID %>"); var rows = grid.get_rows(); var newPerson = [$get("firstName").value, $get("lastName").value]; rows.add(newPerson); } To send the insert request to the server all that is required is to pass an array of the new values to the add function off the rows collection. This function uses the ASP.NET Ajax selectors to find the firstName and lastName controls on the page and create a new array based on the values in the controls. To commit the insert, the array is passed to the add function. Deleting data is a two step process. First the user must select which row is marked for deletion. Once the selected row is located, then the row may be removed. To handle the selection process the RowSelectionChanged event calls the onRowSelectionChanged function: var selectedDataKey = ""; function onRowSelectionChanged(sender, eventArgs) { var rows = eventArgs.getSelectedRows(); var selectedRow = rows.getItem(0); selectedDataKey = selectedRow.get_dataKey(); } First the selectedDataKey variable is created to store the selected key found when the row selection is changed. The onRowSelectionChanged function interrogates the eventArgs for the selected rows. Earlier the grid was configured to only allow single selection of rows, so the selectedRow variable gets its values safely by calling row.getItem(0). Finally the value for the selectedDataKey comes from calling the get_dataKey() function of the selectedRow instance. Now that the selected key is a known value the key is used to commit a delete to the data source: function del() { if (selectedDataKey != "") { var grid = $find("<%= wdg.ClientID %>"); var rows = grid.get_rows(); var row = rows.get_rowFromKey(selectedDataKey); rows.remove(row, false); } else { alert("Please select a row to remove."); } } From an instance of the grid’s rows collection the get_rowFromKey method will find the single row selected earlier by the user. Passing the row instance to the row collection’s remove function sends a delete message to the server. The second argument of the remove method is a bit unintuitive. The argument name is noncommitting: Therefore if you want to commit the change to the data source, you must pass in a false to the function.
https://www.infragistics.com/community/product_platforms/aspnet/w/aspnet-wiki/51/webdatagrid-client-side-crud
CC-MAIN-2020-45
refinedweb
1,337
53.21
LinuxQuestions.org ( /questions/ ) - Linux - Distributions ( ) - - F***ed my gentoo. ( ) jollyjoice 06-08-2006 01:12 PM F***ed my gentoo. Ok, Trying to upgrade to the new xorg 7.0 and it's all gone tits up. I now have no X, and can't log in, and now python has died. Tried to reinstall old 6.9.0rsomething and now X fails to load. Login prompt, enter user name and hit enter, no "password:" prompt, or anything at all, ctrl+c gets me back to login prompt but no user can login. Booting ubuntu live cd to get 64bit environ, can chroot into system, however python has now thrown it's toys out the pram. Quote: Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] !!! Failed to complete python imports. These are internal modules for !!! python and failure here indicates that you have a problem wit h python !!! itself and thus portage is not able to continue processing. !!! You might consider starting python with verbose flags to see what has !!! gone wrong. Here is the information we got for this exception : No module named fcntl Traceback (most recent call last): File "/usr/sbin/env-update", line 28, in ? import portage File "/usr/lib/portage/pym/portage.py", line 20, in ? import os,string,types,signal,fcntl,errno ImportError: No module named fcntl Any help very welcome. Thanks! oneandoneis2 06-08-2006 02:04 PM Tried logging in to the single-user, non-graphical runlevel? jollyjoice 06-08-2006 02:34 PM nope, I'm missing any login software it seems, i need shadow, but python isn't playing nice so I can't use portage to install it... Trying to get portage working again 1st, work from there I think. Wolfgang Dobler 06-30-2006 11:55 PM I just had a similar Quote: Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] problem after trying to upgrade to x11-7.0 on x86_64 (and 7.0 is now marked as stable -- most likely by accident...). The reason was that something (some component of x11, I guess) screwed up /usr/lib64. This should be a link to /usr/lib, Quote: /usr/lib64 -> lib but after the failed installation it was pointing to /lib64. 40 minutes later... It was actually x11-base/xorg-x11-6.8.2-r8 that screwed up the link, just before being done with the installation. I am currently installing x11-base/xorg-x11-6.8.2-r7 to see whether that is better. Another hour later... That did not make a difference. I have no clue why 6.8.2 would now try to do something stupid and choke on it if it installed perfectly fine the last time. So I am now going for a binary package from another machine (as I was too stupid to make one on this computer). Three minutes later... This did the job. jollyjoice 09-05-2006 12:13 PM Hey, nice to see you got it working. I gave up in the end and tried that fancy new gui installer :D All times are GMT -5. The time now is 04:53 PM .
http://www.linuxquestions.org/questions/linux-distributions-5/f***ed-my-gentoo-452888-print/
CC-MAIN-2016-44
refinedweb
533
77.13
I have a repeating structure in my Java class and wanted to present the data as follows: Peter Black John Red public class Test { public static void main(String[] args) { List<Person> persons = new ArrayList<>(); String[] names= {"Peter", "John"}; String[] colors= {"Black", "Red"}; for (String name: names) { Person d = new Person(); d.setName(name); for (String color: colors) { d.setColor(color); } persons.add(d); } for (Person a : persons) { System.out.println(a.getName() + "-" + a.getColor()); } } } Peter-Red John-Red Instead of using a nested for loop, which is not what you are trying to accomplish, loop through both arrays at the same time. if (names.length != colors.length) { // error! not a 1:1 relationship return; } for (int i = 0; i < names.length && i < colors.length; i++) { String name = names[i], color = colors[i]; Person d = new Person(); d.setName(name); d.setColor(color); persons.add(d); } I could just do i < names.length, however that will break if both arrays are different sizes, so i < names.length && i < colors.length will make sure i never exceeds either of the two arrays' lengths. Edit: I think the real problem here is how you are storing your info. Why are you using two string arrays, instead of a collection containing Person objects?
https://codedump.io/share/BR9ZkvsIDqI3/1/print-on-the-screen-a-repeat-loop
CC-MAIN-2017-13
refinedweb
210
65.93
Journal tools | Personal search form | My account | Bookmark | Search: ...drop out cross millefiori pendant unoka things fall apart washington state mega millions cock craving info remember az moon nursery phoenix valley evening morning star republican elephant picture drama job teacher washington dc mba programs apartment country hills how to tell what video card you have xanadu hotel gold coast 1997 direction ford mechanical pump... ... robot the rogues david niven german speakers worldwide 1997 jaguar xj8 couple massage picture cheese cream jalapeno deal las nevada vegas texas high school baseball forum illinois ... where the mind is without fear health insurance complaints florida silver dollar city picture lincoln center walter or reade or theater mimosa golf and country club champagne+... ...mobile phone networks old green day videos cold sore.com stop catch mays willie catch a call reviews granular activated carbon suppliers terry cloth hooded robe...arkansas funeral home hot springs golf cart picture call sabc trauma war eagle duck ... control clarksburg winery appomattox court house picture fort pierce florida funeral home hartsville ... ... quotes dream stealers oglesby and butler caspian publishing grand rapids boat show civic h22 install turbo carbon fiber reinforced polymer year review 2000 butter pan peanut peter picture gree house effect parts for e. ingraham series 33 electric motor daughter to father poems australian travel visa david quote wolf power ranger games download effects ... ... calendar january online program anastasia picture montana or wyoming nursing jobs... phone services 2007 3 mazda picture 2005 dress formal iv winter...broker in 1993 chevy cavalier picture coral draw 12 activation code...construction management degree paul klee picture incidence of uk childhood obesity...2.8 2006 balikatan baseball mays willie trinity life center broadband... ...turner valley golf and country club cheese.com n steak cabinet custom kitchen picture alaskan cooking crab king kansas senate bill compare isa rates deep mysterys air ... officers letter nhs dreamcast emulator games woodlake market sonyericsson p800i energy ipo verasun picture of compound microscope part causing dangerous death driving intel 82371abeb pci to ... ...splash baby video 2000 from upgrade window window xp film hand stretch qwest kyocera kx1 ringtones willie mays led zepplin video peters friends movie n sync video encoding video for phones doberman pinscher puppy... song collin import video games from asia the world map picture big intervideo windvd free download new quarter york ati driver ... ... renfrew center philadelphia peugeot 307 photos willie mays jessica simpson father quote nsithenqplm...ky lexington school gallery hot naked picture wife moorestown mall movie theatre silent...video mpeg lolita preteen galleries friend picture send american tale movie poor credit...release date nsithenqplm nude a poppin picture cinchers waist polevaulting video arabic song... ...biggest ever info penis recorded remember veterinarian picture with animal military summer camp texas illinois...jokes disneychannel asia.com.my baby fall picture mastress eden medication used to treat depression...hyundai s coupe 1992 west virginia beef jerky english dubbed anime joke mays willie 1993 hit for pinky and perky westside honda tn golden labrador puppy... ... valley animal hospital 2003 nissan murano pricing picture on strawberry shortcake and her friends united ... arte tv france club fight trailer asian black fucking man woman joke mays willie autocad 2005 keygen.exe brunello di montalcino castello banfi 1999 southern bank...art modern online mountain lion paw print picture nissan pick up 1993 custom european student... Billie Mays Pictures Of Willie Mays Willie Mays Daughter Billie Mays Step Daughter Of Willie Billie Mays Willie Mays Chilly Willy Free Willy Picture Of Willy Mays Johnny Depp Willy Wonka Willie Mays Picture Of Catch Johnny Depp Willy Wonka Picture Willie Mays Rc Willy Willie Mays Biography Tim Burton Willy Wonka Picture Tarbell Willie Willy Picture Pretty Willie Willy Chirino Picture Of Louisa May Alcott Result Page: 1 2 for Picture Of Willie Mays
http://www.ljseek.com/Picture-Of-Willie-Mays_s4Zp1.html
crawl-002
refinedweb
627
52.7
This is a weird one. See my reply below for my thoughts. In short, the answer is no because forte is screaming about the double declaration of mutex - which seems to be a valid error. The mutex in include/multithread.h really needs to be namespace-protected. Original message here: -- justin --- posting-system@google.com wrote: > From: posting-system@google.com > Date: Thu, 20 Sep 2001 00:52:14 -0700 > Reply-to: posting-system@google.com > To: jerenk@yahoo.com > Subject: Re: Is building Apache 1.3.20 with Solaris > CC 6.0 or 5.0 possible? > > From: jerenk@yahoo.com (Justin Erenkrantz) > Newsgroups: comp.infosystems. > Subject: Re: Is building Apache 1.3.20 with Solaris > CC 6.0 or 5.0 possible? > References: > <d1efd44f.0109190840.24ca4739@posting.google.com> > NNTP-Posting-Host: 24.13.179.162 > Message-ID: > <d68343be.0109192352.4117400f@posting.google.com> > > nick@macaw.demon.co.uk (Nick Lindridge) wrote in > news:<d1efd44f.0109190840.24ca4739@posting.google.com>... > > Hi, > > > > The answer is of of course yes, but has anyone actually built Apache > > with Forte or CC 5 recently for Solaris 7 or 8? Trying regular CC, > > compat 5 and compat 4 all give up for the same reasons, and I wondered > > if there are any config options that I've missed to get past the > > obvious problems. An example build gets a little way and then the > > output below. > > > > Not sure which is going to be the least pain at this point - > > installing gcc or fixing up the includes. > > Wow. It's broken. I'll take a look at it in a few days. > In the meantime, I'd suggest gcc. sunfreeware.com has > pre-built binaries you can download. > > Odd that we haven't caught this before... > > /usr/include/sys/mutex.h is getting included which defines a > structure called mutex. I wonder why gcc isn't complaining > about it. I wonder if it defines _ASM. For the complete > path, sys/mutex.h is included from sys/t_lock.h which is > included from sys/file.h which is included from ap_config.h. > The only way to work around this might be to define _ASM > before ap_config.h includes sys/file.h. That's a hack > though. > > Otherwise, it looks like we may need to go on a type-rename > hunt in Apache 1.3. This won't be fixed until 1.3.21 (at the > very least). > > I'm going to CC this to dev@httpd.apache.org. Feel free to > keep an eye on the progress there. > > Justin Erenkrantz ----- End forwarded message -----
http://mail-archives.apache.org/mod_mbox/httpd-dev/200109.mbox/%3C20010920011014.V12417@ebuilt.com%3E
CC-MAIN-2014-41
refinedweb
427
71.92
i know java, ive had two classes in it but ive only written it in notepad.. lol so here im trying to make an applet in netbeans and implement an action listener.. why do i get an error at my first line here: import java.awt.event.*; import java.awt.*; public class applet1 extends java.applet.Applet implements java.awt.event.ActionListener i.e this line: public class applet1 extends java.applet.Applet implements java.awt.event.ActionListener heres the error message i recieve: applet1 is not abstract and does not override abstract method actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener what can i do to fix this? is netbeans doing something for me to where i dont have to write this? or do i have to use a frame? thanks
https://www.daniweb.com/programming/software-development/threads/25620/netbeans-4-0-help
CC-MAIN-2018-22
refinedweb
134
61.93
MantisBT 2.0 Developers Guide ================ Reference for developers and community members ---------------------------------------------- [IMAGE] MantisBT Development Team mantisbt-dev@lists.sourceforge.net ------------------------------------------------------------------------ Legal Notice ============ Copyright © 2016 MantisBT team. This material may only be distributed subject to the terms and conditions set forth in the GNU Free Documentation License (GFDL), V1.2 or later (the latest version is presently available at). Abstract This book is targeted at MantisBT developers, contributors and plugin authors. It documents the development process and provides reference information regarding the MantisBT core, including the database schema as well as the plugin system including an events reference. ------------------------------------------------------------------------ 2. Database Schema Management 2.1. The MantisBT schema 2.2. Schema Definition 2.3. Installation / Upgrade Process 3. Event System 3.1. General Concepts 3.2. API Usage 3.3. Event Types 4. Plugin System 4.1. General Concepts 4.2. Building a Plugin 4.2.1. Plugin Structure 4.2.2. Properties 4.2.3. Pages and Files 4.2.4. Events 4.2.5. Configuration 4.2.6. Language and Localization 4.3. Example Plugin Source Listing 4.3.1. Example/Example.php 4.3.2. Example/files/foo.css 4.3.3. Example/lang/strings_english.txt 4.3.4. Example/page/config_page.php 4.3.5. Example/pages/config_update.php 4.3.6. Example/page/foo.php 4.4. API Usage 5. 6. Integrating with MantisBT 6.1. Java integration 6.1.1. Prebuilt SOAP stubs using Axis 6.1.2. Usage in OSGi environments 6.2. Compatibility between releases 6.3. Support 7. Appendix 7.1. Git References A. Revision History Chapter 1 MantisBT source code is managed with Git. If you are new to this version control system, you can find some good resources for learning and installing it in Section 7.1, âGit Referencesâ. 1.1. Initial Setup ------------------- There are a few steps the MantisBT team requires of contributors configure Git to use terminal colors when displaying file diffs and other information, and also alias certain Git actions to shorter phrases to reduce typing: git config --global color.diff "auto" git config --global color.status "auto" git config --global color.branch "auto" git config --global alias.st "status" git config --global alias.di "diff" git config --global alias.co "checkout" git config --global alias.ci "commit" 1.2. Cloning the Repository ---------------------------- The official MantisBT source code repository is hosted at GitHub. This document assumes that you have already signed up for and setup a GitHub account. 1.2.1. Determining the Clone URL Which URL you will use to clone the repository before you start developing depends on your situation. MantisBT Core Team Developers MantisBT developers have push access to the official repository. Benefitting from this access requires a special URL that uses your SSH key to handle access permissions: git@github.com:mantisbt/mantisbt.git. Alternatively, an HTTPS link can be used as well, in which case you will have to provide your GitHub User ID and password when Git requests it:. Note ---- Pushes will fail if you do not have access or your public SSH key is not set up correctly in your GitHub profile. Contributors For other people, the MantisBT repository and the related clone URLs git://github.com/mantisbt/mantisbt.git (SSH) or (HTTPS) will always be read-only. It is therefore strongly advised to create your own fork of MantisBT where you will be able to push your changes, and then use the fork's URL instead to clone, which will look like this: git@github.com:MyGithubId/mantisbt.git or 1.2.2. Initializing the Clone To clone the repository, execute the following command from your target workspace: git clone YourCloneURL After performing the cloning operation, you should end up with a new directory in your workspace, mantisbt/, containing the MantisBT repository with a remote named origin pointing to your Clone URL. MantisBT uses Composer to pull libraries and components from Packagist and Github. Install Composer and run the following command: composer install Warning ------- Failure to execute the submodule initialization commands will result in critical components being missing from /vendor folder, which will then cause errors when running MantisBT. 1.2.3. Adding remotes If you are planning to use your own fork to push and maintain your changes, then we recommend setting up an upstream remote for MantisBT's official repository, which will make it easier to keep your repository up-to-date. git remote add --tags upstream git://github.com/mantisbt/mantisbt.git 1.2.4. Checking out branches By default, the new clone will only track code from the primary remote branch, master, which is the latest development version of MantisBT. If you are planning to work with stable release or other development branches, you will need to set up local tracking branches in your repository. The following command will set up a tracking branch for the current stable branch, master-1.3.x. git checkout -b master-1.3.x origin/master-1.3.x Note ---- With the introduction of submodules for some of the third-party libraries, you may encounter issues when switching to an older branch which still has code from those libraries in a subdirectory of /library rather than a submodule: $ git checkout old_branch error: The following untracked working tree files would be overwritten by checkout (list of files) Aborting To resolve this, you first have to get rid of the submodules directories before you can checkout the branch. The command below will move all submodules to /tmp: sed -rn "s/^.*path\s*=\s*(.*)$/\1/p" .gitmodules |xargs -I{} mv -v {} /tmp git checkout old_branch Alernatively, if you don't care about keeping the changes in the submodules directories, you can simply execute git checkout -f old_branch git clean -df When switching back from the older branch, the submodules directories will be empty. At that point you can either * Update the submodules to reclone them git submodule update * Restore the directories previously moved to /tmp back into the empty directories, e.g. sed -rn "s/^.*path\s*=\s*(.*)$/\1/p" .gitmodules |xargs -n 1 basename |xargs -I{} mv -v /tmp/{} library For further reference: Pro Git book 1.3. Maintaining Tracking Branches ----------------------------------- In order to keep your local repository up-to-date with the official one, there are a few simple commands needed for any tracking branches that you may have, including master and master-1.3.x. First, you'll need to get the latest information from the remote repository: git fetch origin Note ---- If you cloned from your personal GitHub fork instead of the official MantisBT repository as explained in Section 1.2.3, âAdding remotesâ, then you should instead execute: git fetch upstream Then for each tracking branch you have, enter the following commands: git checkout BranchName git rebase Alternatively, you may combine the fetch and rebase operations described above into a single pull command (for each remote tracking branch): git checkout master git pull --rebase 1.4. Preparing Feature Branches -------------------------------- For each local or shared feature branch that you are working on, you will need to keep it up to date with the appropriate master branch. There are multiple methods for doing this, each better suited to a different type of feature branch. Both methods assume that you have already performed the previous step, to update your local tracking branches (see Section 1.3, âMaintaining Tracking Branchesâ). 1.4.1. Private Branches If the topic branch in question is a local, private branch, that you are not sharing with other developers, the simplest and easiest method to stay up to date with master is to use the rebase command. This will append all of your feature branch commits into a linear history after the last commit on the master branch. git rebase master feature Note ---- Rebasing changes the ID for each commit in your feature branch, which will cause trouble for anyone sharing and/or following your branch. The resulting conflict can be fixed by rebasing their copy of your branch onto your branch: git checkout feature git fetch remote/feature git rebase remote/feature 1.4.2. Public Branches For any publicly-shared branches, where other users may be watching your feature branches, or cloning them locally for development work, you'll need to take a different approach to keeping it up to date with master. To bring public branch up to date, you'll need to merge the current master branch, which will create a special "merge commit" in the branch history, causing a logical "split" in commit history where your branch started and joining at the merge. These merge commits are generally disliked, because they can crowd commit history, and because the history is no longer linear. They will be dealt with during the submission process (see Section 1.5, âRunning PHPUnit testsâ). git checkout feature git merge master At this point, you can push the branch to your public repository, and anyone following the branch can then pull the changes directly into their local branch, either with another merge, or with a rebase, as necessitated by the public or private status of their own changes. 1.5. Running PHPUnit tests --------------------------- MantisBT has a suite of PHPUnit tests found in the tests directory. You are encouraged to add your own tests for the patches you are submitting, but please remember that your changes must not break existing tests. In order to run the tests, you will need to have the PHP Soap extension, PHPUnit 3.4 or newer and Phing 2.4 or newer installed. The tests are configured using a bootstrap.php file. The boostrap.php.sample file contains the settings you will need to adjust to run all the tests. Running the unit tests is done from root directory using the following command: phing test 1.5.1. Running the SOAP tests MantisBT ships with a suite of SOAP tests which require an initial set up to be executed. The required steps are: * Install MantisBT locally and configure a project and a category. * Adjust the bootstrap.php file to point to your local installation. * Customize the config_inc.php to enable all the features tested using the SOAP tests. The simplest way to do that is to run all the tests once and adjust it based on the skipped tests. 1.6. Submitting Changes ------------------------ This section describes what you should do to submit a set of changes to MantisBT, allowing the project developers to review and test, your code, and ultimately commit it to the MantisBT repository. The actual submission can be done using several methods, described later in this section: * Recommended: Github Pull Requests (see Section 1.6.2, âSubmission Via Github Pull Requestsâ) * Other public Git repository Pull Requests (see Section 1.6.4, âSubmission Via Public Repositoryâ) * Git Formatted patches (see Section 1.6.3, âSubmission Via Formatted Patchesâ) 1.6.1. Before you submit Before submitting your contribution, you should make sure that 1. Your code follows the MantisBT coding guidelines 2. You have tested your changes locally (see Section 1.5, âRunning PHPUnit testsâ) 3. Your local branch has been rebased on top of the current Master branch, as described in Section 1.4.1, âPrivate Branchesâ. 1.6.2. Submission Via Github Pull Requests Since the official MantisBT repository is hosted there, using GitHub is the recommended (and easiest) way to submit your contributions. With this method, you can keep your changesets up-to-date with the official development repository, and likewise let anyone stay up to date with your repository, without needing to constantly upload and download new formatted patches whenever you change anything. The process below describes a simple workflow that can help you make your submission if you are not familiar with Git; note that it is by no means the only way to do this. Note ---- We'll assume that you have already forked MantisBT, cloned it locally as described in Section 1.2, âCloning the Repositoryâ (remote upstream being the official MantisBT repository and origin your personal fork), and created a new feature branch (see Section 1.4, âPreparing Feature Branchesâ) for your contribution, which we'll call MyBranch. 1. Make sure that the MyBranch feature branch is up-to-date with the master branch by rebasing it, resolving any conflicts if necessary. git fetch upstream git rebase upstream/master MyBranch 2. Push the branch to your Github fork git push origin MyBranch 3. Go to your Fork on Github () 4. Initiate a Pull Request from your feature branch, following the guidelines provided in Github Help. Please make sure you provide a detailed description of the changes you are submitting, including the reason for it and if possible a reference (link) to an existing issue on our bugtracker. The team will usually review your changes and provide feedback within 7 days (but your mileage may vary). 1.6.3. Submission Via Formatted Patches Formatted patches are very similar to file diffs generated by other tools or source control systems, but contain far more information, including your name and email address, and for every commit in the set, the commit's timestamp, message, author, and more. They allow anyone to import the enclosed changesets directly into Git, where all of the commit information is preserved. Assuming that you have an existing local that you've kept up to date with master as described in Section 1.4, âPreparing Feature Branchesâ currently checked out, 1.6.4. Submission Via Public Repository If you are not able or not willing to make use of a fork of the official GitHub repository but have another publicly available one to host your changes, for example on a free hosting for public repository such as * Bitbucket * Gitorious you can still use it to submit a patch in a similar fashion to the Github method described above, although the process is slightly more complicated. We'll assume you've already set up a publicly accessible repository at URL git@githosting.com:contrib.git, kept it up-to-date with MantisBT's official repository, and that you have pushed your feature branch MyBranch to it. 1. Generate the Pull Request This will list information about your changes and how to access them. The process will attempt to verify that you've pushed the correct data to the public repository, and will generate a summary of changes. git request-pull origin/master git@githosting.com:contrib.git MyBranch 2. Paste the output of the above command into a bug report or an email to the developer mailing list Once your pull request has been posted, developers and other users can add your public repository as a remote, and track your feature branch in their own working repository using the following commands, replacing the remote name and local branch name as appropriate: git remote add feature git@githosting.com:contrib.git git checkout -b MyBranch feature/MyBranch If the feature is approved for entry into MantisBT core, then the branch should first be rebased onto the latest HEAD so that Git can remove any unnecessary merge commits, and create a linear history. Once that's completed, the feature branch can be merged into master: git rebase master feature git checkout master git merge --no-ff feature Chapter 2. Database Schema Management --------------------------------------- 2.1. The MantisBT schema 2.2. Schema Definition 2.3. Installation / Upgrade Process 2.1. The MantisBT schema ------------------------- The MantisBT database schema (excluding plugins) is described in the Entity-Relationship diagram (ERD) below. There is also a PDF version available for download. MantisBT Entity-Relationship Diagram Figure 2.1. MantisBT Entity-Relationship Diagram 2.2. Schema Definition ----------------------- TODO: Discuss the ADODB datadict formats and the format MantisBT expects for schema definitions. 2.3. Installation / Upgrade Process ------------------------------------ TODO: Discuss how MantisBT handles a database installation / upgrade, including the use of the config system and schema definitions. Chapter 3. Event System ------------------------- 3.1. General Concepts 3.2. API Usage 3.3. Event Types 3.1. General Concepts ----------------------. 3.2. API Usage --------------- perusing Chapter 5, Events Reference is recommended for determining the unique needs of each event when signalling and hooking them. 3.3. Event Types ----------------- perusing Chapter 5, Events Reference is recommended immediately sent to the output buffer via 'echo'. Another parameter $format can be used to model how the results are printed. This parameter can be either: * null, or omitted: The returned values are printed without further processing *.Â.Â. API Usage --------------- This is a general overview of the plugin API. For more detailed analysis, you may reference the file core/plugin_api.php in the codebase. Chapter 5. 5.1. Introduction ------------------ In this chapter, an attempt will be made to list all events used (or planned for later use) in the MantisBT event system. Each listed event will include details for the event type, when the event is called, and the expected parameters and return values for event callbacks. Here we show an example event definition. For each event, the event identifier will be listed along with the event types (see Section 3.3, âEvent Typesâ) in parentheses. Below that should be a concise but thorough description of how the event is called and how to use it. Following that should be a list of event parameters (if any), as well as the expected return value (if any). EVENT_EXAMPLE (Default) This is an example event description. Parameters *
http://mantisbt.org/docs/master/en-US/Developers_Guide/Developers_Guide.txt
CC-MAIN-2017-39
refinedweb
2,924
55.13
Check if a given key already exists in a dictionary and increment it You are looking for collections.defaultdict (available for Python 2.5+). This from collections import defaultdictmy_dict = defaultdict(int)my_dict[key] += 1 will do what you want. For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use if key in my_dict: my_dict[key] += 1else: my_dict[key] = 1 I prefer to do this in one line of code. my_dict = {}my_dict[some_key] = my_dict.get(some_key, 0) + 1 Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the key doesn't exist in this one line of code, not everywhere. I personally like using setdefault() my_dict = {}my_dict.setdefault(some_key, 0)my_dict[some_key] += 1
https://codehunter.cc/a/python/check-if-a-given-key-already-exists-in-a-dictionary-and-increment-it
CC-MAIN-2022-21
refinedweb
173
64
- Padding. - Viewing Profile: Reputation: Zoner ZonerMember Since 13 Apr 2009 Offline Last Active Oct 29 2012 04:01 AM Community Stats - Group Members - Active Posts 231 - Profile Views 2,039 - Member Title Member - Age Age Unknown - Birthday Birthday Unknown - Gender Not Telling User Tools Contacts Zoner hasn't added any contacts yet. #4958584 CSM (based on nvidia's paper) swimming Posted by Zoner on 12 July 2012 - 05:25 PM #4937519 Number of arrays CPU can prefetch on Posted by Zoner on 04 May 2012 - 07:18 PM. #4923514 releasing a game built with old DirectX SDK's Posted by Zoner on 19 March 2012 - 09:14 PM #4909984 C++ SIMD/SSE optimization Posted by Zoner on 05 February 2012 - 06:11 PM The MSDN docs are a jumbled mess (and in multiple 'docs', SSE, SSE2, SSE4, some AVX are fairly separate doc-wise). #include <mmintrin.h> // MMX #include <xmmintrin.h> // SSE1 #include <emmintrin.h> // SSE2 #if (MATH_LEVEL & MATH_LEVEL_SSE3) #include <pmmintrin.h> // Intel SSE3 #endif #if (MATH_LEVEL & MATH_LEVEL_SSSE3) #include <tmmintrin.h> // Intel SSSE3 (the extra S is not a typo) #endif #if (MATH_LEVEL & MATH_LEVEL_SSE4_1) #include <smmintrin.h> // Intel SSE4.1 #endif #if (MATH_LEVEL & MATH_LEVEL_SSE4_2) #include <nmmintrin.h> // Intel SSE4.2 #endif #if (MATH_LEVEL & MATH_LEVEL_AES) #include <wmmintrin.h> // Intel AES instructions #endif #if (MATH_LEVEL & (MATH_LEVEL_AVX_128|MATH_LEVEL_AVX_256)) #include <immintrin.h> // Intel AVX instructions #endif //#include <intrin.h> // Includes all MSVC intrinsics, all of the above plus the crt and win32/win64 platform intrinsics #4908266 If developers hate Boost, what do they use? Posted by Zoner on 31 January 2012 - 08:43 PM I've never met anyone that admitted to even using C++ iostreams, let alone liking them or using them for anything beyond stuff in an academic environment (i.e. homework). STL and Boost pretty much require exception handling to be enabled. This is a dealbreaker for a lot of people, especially with codebases older than modern C++ codebases that are exception-safe. You are more or less forced to be 'C with Classes, type traits, and the STL/Boost templates and that don't allocate memory'. RAII design more or less requires exception handling for anything useful, as you can't put any interesting code in the constructors without being able to unwind (i.e. two phase initialization is required). The cleanup-on-scope aspect is useful though without exception handling, since the destructors aren't supposed to throw anyway. STL containers have poor to non-existant control over their memory management strategies. You can replace the 'allocator' for a container but it is near useless when the nodes linked list are forced to use the same allocator as the data they are pointing to, ruling out fixed size allocators for those objects etc. This is a lot of the motivation behind EASTL, having actual control, as the libraries are 'too generic'. And memory management ties heavily into threading: We use Unreal Engine here which approaches the 'ridiulous' side of the spectrum on the amount of dynamic memory allocation it does at runtime. The best weapon to fight this (as we cannot redesign the engine) is to break up the memory management into lots of heaps and fixed size allocators, so that any given allocation is unlikely or not at all going to contend with a lock from other threads. Stack based allocators are also a big help, but are very not-C++-like. My rule of thumb for using these libraries is if doesn't allocate memory, it is probably ok to use: algorithms for std::sort is quite useful even without proper STL containers, and outperforms qsort by quite a lot due to being able to inline everything. Type traits (either MS extensions, TR1, or Boost) can make your own templates quite a bit easier to write I've also never seen the need for thread libraries, the code just isn't that interesting or difficult to write (and libraries tend to do things like making the stack size hard to set, or everyone uses the library in their own code and you end up with 22 thread pools and 400 threads etc) #4907800 C++ SIMD/SSE optimization Posted by Zoner on 30 January 2012 - 04:57 PM Awesome, this works right out of the box! This code is around 30% faster than the native c++ code. Thanks for the fast response Zoner? The loop will likely need to be unrolled 2-4 more times as to pipeline better (i.e. use more registers until it starts spilling over onto the stack) If the data is aligned, the load and store can use the aligned 'non-u' versions instead. SIMD intrinics can only be audited by looking at optimized code (unoptimized SIMD code is pretty horrific), basically when an algorithm gets too complicated it has to spill various XMM registers onto the stack. So you have to build the code, check out the asm in a debugger and see if it is doing that or not. This is much less of a problem with 64 bit code as there are twice as many registers to work with. Re-using the same variables should work for a lot of code, although making the pointers use __restrict will probably be necessary so it can schedule the code more aggressively. If the restrict is helping the resulting asm should look something like: read A do work A read B do work B store A do more work on B read C store B do work C store C vs read A do work A store A read B do work B store B read C do work C store C #4907781 C++ SIMD/SSE optimization Posted by Zoner on 30 January 2012 - 03:56 PM static const __m128i GAlphaMask = _mm_set_epi32(0xFF000000,0xFF000000,0xFF000000,0xFF000000); // make this a global not in the function void foo() { unsigned int* f = (unsigned int*)frame; unsigned int* k = (unsigned int*)alphaKey; size_t numitems = mFrameHeight * mFrameWidth; size_t numloops = numitems / 4; size_t remainder = numitems - numloops * 4; for (size_t index=0;index<numloops; ++index) { __m128i val = _mm_loadu_si128((__m128i*)f); __m128i valmasked = _mm_and_si128(val, GAlphaMask); __m128i shiftA = _mm_srli_epi32(valmasked , 8); __m128i shiftB = _mm_srli_epi32(valmasked , 16); __m128i shiftC = _mm_srli_epi32(valmasked , 24); __m128i result = _mm_or_si128(_mm_or_si128(shiftA, shiftB), _mm_or_si128(shiftC, GAlphaMask)); _mm_storeu_si128((__m128i*)k, result); f += 4; k += 4; } // TODO - finish remainder with non-simd code } The loop will likely need to be unrolled 2-4 more times as to pipeline better (i.e. use more registers until it starts spilling over onto the stack) If the data is aligned, the load and store can use the aligned 'non-u' versions instead. #4905182 Forcing Alignment of SSE Intrinsics Types onto the Heap with Class Hierachies Posted by Zoner on 22 January 2012 - 02:03 PM This is ultimately windows code, as they have an aligned heap available out of the box (_aligned_malloc) mDEFAULT_ALIGNMENT is 16 in my codebase, ideally you would pass in the alignof the type here but the C++ ABI only passes in size to new (and you don't have the ability to get the type information either). void* mAlloc(zSIZE size, zSIZE alignment) { void* pointer = _aligned_malloc(size, alignment); if (pointer == null) { throw std::bad_alloc(); } return pointer; } void mFree(void* pointer) { _aligned_free(pointer); } void* operator new(zSIZE allocationSize) { return mAlloc(allocationSize, mDEFAULT_ALIGNMENT); } void* operator new[](zSIZE allocationSize) { return mAlloc(allocationSize, mDEFAULT_ALIGNMENT); } void operator delete(void* pointer) { mFree(pointer); } void operator delete[](void* pointer) { mFree(pointer); } #4905180 Forcing Alignment of SSE Intrinsics Types onto the Heap with Class Hierachies Posted by Zoner on 22 January 2012 - 02:01 PM A combination of an aligned allocator and compiler-specific alignment attributes should suffice. For Visual C++, look at __declspec(align). For GCC, look at __attribute__((aligned)). My intrinsic wrappers assert the alignment in the constructors and copy constructors. It can be useful to leave these asserts enabled in release builds for a while, as on the Windows it seems allocations from the debug heap are aligned sufficiently for SSE2. The SSE types __m128 and friends already have declspec align 16 applied to them for you. Placing them as a member in a struct will promote the structs alignment. Looking at the original data structures from the first post, the compiler should be generating 12 bytes of padding before the worldMatrix member in struct Transform, and also padding 4 bytes between the struct and the base class (as their alignments are different) struct TestA { zBYTE bytey; }; struct TestB : public TestA { vfloat vecy; }; zSIZE sizeA = sizeof(TestA); zSIZE alignA = alignof(TestA); zSIZE sizeB = sizeof(TestB); zSIZE alignB = alignof(TestB); zSIZE offset_bytey = offsetof(TestB, bytey); zSIZE offset_vecy = offsetof(TestB, vecy); watch window: sizeA=1 alignA=1 sizeB=32 alignB=16 offset_bytey=0 offset_vecy=16 #4833576 Return Values Posted by Zoner on 10 July 2011 - 09:50 PM Wow, thanks for being so thourough! I'm perplexed as to why so many heavyweight math libraries seem to worry about this! D3DX being one of them. EDIT: Ok, so it's probably still better to use:Vector3DAdd (a, b, dest); than:dest = a + b; Right? To avoid temp objects? Also, I hear that if the return value is named, it will have to construct/destruct it regardless. I'm trying to see the assembly myself but the compiler optimizes out all my test code EDIT2: Also, just to get this out of the way, yes, the profiler is telling me that vector math could go to be faster since my physics engine is choking atm. I've written a few math libraries, and the temporaries are rarely a problem, provided you keep the structs containing the objects pod-like. The last big complication I've seen is that sometimes SIMD wrapper classes don't interoperate well with exception handling being enabled. Not a problem, exceptions can be turned off! D3DX is structured the way it is for a few reasons: - It is C like on purpose, D3D has had a history of being supported for C to some degree, as you can still find all those wonderfully ugly macros in the headers to call the COM functions from C. - The D3DX dll is designed to be able to run on a wide variety of hardware (aka real old), most applications pick a minspec for the CPU instruction set and use that. SSE2 is a pretty solid choice these days (and is also the guaranteed minimum for x64). However if you write the math using D3DX and 'plain C/C++' it will work on all platforms. - The x86 ABI can't pass SSE instructions by value in the x86 ABI, so pointers (or references) are used instead. - The x64's ABI can pass SSE datatypes by value at the code level, but on the backend they are always passed by pointer, so only inlined code can keep the values in registers. With this restriction you might as well explicitly use pointers or references in the code, so you can see the 'cost' better, and also to cross-compile back in 32 bit. - A lot of 'basic' SIMD math operations take more than two arguments, which don't fit into existing C++ operators. This basically causes you to structure the lowest level of a math library in terms of C-like function primitives, of which the operator overloads can use as needed to provide syntactic sugar. - Some functions return more than one value, which also gets to be rather annoying without wrapper it in a struct, some tuple container, so a lot of times its easier to just have multiple out arguments. For example: A function that computes sin and cos simultaneous, frequently can be done at the same or similar cost as either sin or cos on quite a bit of hardware. Another example: Matrix inversion functions can also return the determinant as they have to compute it anyway as part of their inversion. Microsoft did take the time to do some runtime patchups to the function calls to call CPU specific functions (SSE, SSE2 etc), so you basically end up with this mix of 'better than plain C code' and 'worse than pure SIMD code'. #4833250 Mip maps..... no understanding Posted by Zoner on 09 July 2011 - 11:22 PM The lower the resolution of the mipmap, the better it maps to the cache on the GPU, which speeds things up (quite a lot actually). The hardware normally automatically picks which mipmap level to display quite well, except when working in screen space style effects. The filtering modes work in three 'dimensions': mag filter - filter applied when the image is up-resed (typically when you are already rendering the largest mip level and there isn't another one to switch to) min filter - filter applied when the image is down-resed mip filter - filter applied between mip levels (on, off, linear) When the mip filter is set to linear, the hardware picks a blend of of two mipmap levels to display, so the effect looks more seamless. The UV you feed into the fetch causes the hardware to fetch the color from two miplevels, and it automatically crossfades them together. If you set the mipfilter to nearest, it will only fetch one mip, and this will typically generate seams in the world you render, where the resolution of the texture jumps (as the hardware selects them automatically in most cases). This is faster however since it only has to do half the work. When the mag filter is set to linear, the hardware fetches a 2x2 block of pixels from a single mip level, and crossfades them together with a biliinear filter. If the filter is set to anisotropic, it uses a proprietary multi-sample kernel to sample multiple sets of pixels from the image in various patterns. The number of samples corresponds to the anisotropic setting (from 2 to 16), at a substantial cost to performance in most cases. However it helps maintain the image quality when the polygons are nearly parallel to the camera, and this can be pretty important for text on signs, stripes on roads, and other objects that tend to mip to transparent values too fast (chain link fences). You can set the hardware in quite a few configurations, as these settings are more or less mutually exclusive with each other. #4832710 First person weapon with different FOV in deferred engine Posted by Zoner on 08 July 2011 - 04:00 AM First off, the good news: Provided the near and far planes are the same for the projections, the depth values will be equivalent. What is different is the FOV is different so the screen space XY positions of the pixels will come out different, which generally only matters when de-projecting a screen pixel back into the world. For most effects that do this, the depth is usable as-is for depth based fog, and whatnot. This only requires making your artists cope with the same near plane as the world (and they will beg and scream for a closer plane for scopes and things that get right up on the near plane, but you have to say NO!, you get the custom FOV but you get it with this limitation). And the bad news: The depths are quite literally equivalent, which means the weapon will draw 'in the world' and have the rather annoying behavior of poking through walls you walk up to. So the fix is to render the gun several times, primarily for depth-only or stencil rendering. One possibility (and the one we use) is to render the gun with a viewport set to a range of 0/0.0000001 in order to get the gun to occlude the world. This is good for performance reasons, but bad if you have post process effects that absolutely must be able to to sample pixels from 'behind the gun'. This is a trade off someone has to sign off on. Performance usually wins that argument though, so we have opted to have the guns occlude everything (including hardware occlusion queries!). Another possibility is to render a pass to create a stencil mask of the weapon and occlude with that, but there are some complications that need to be understood, which I will talk about down near the bottom of this post. Forward renderers can just draw the gun later in the frame at their leisure for the most part, after clearing depth (another thing I need to explain later) and drawing the gun. Deferred rendering doesn't have it as easy, as you need the gun to exist properly in the GBuffers when doing lighting passes, for both performance reasons, and to accept and real-time shadowmaps properly along with the world. More good news: Aside from the case of the gun or the player needing to cast shaders, the weapon will generally look just fine lit (and shadowed!) with the not-quite correct de-projected world space position. The depth will be completely correct from the view-origin's point of view, and the gun itself wont be too far from a correct XY screen position so it will just light and shadow just fine. UNLESS you attach a tiny light directly to the gun, at which point the light needs its position adjusted to be in the guns coordinate system instead of the world, so the gun looks correct when lit by the light. Muzzle flash sprites and whatnot have a similar problem, but in reverse, in that the sprite needs to be placed in the world correctly relative to the gun's barrel. More bad news: Getting the gun into the GBuffer properly and without breaking performance can be a bit tricky. We store a version of the scene depth's W coordinate in the alpha channel of the framebuffer (which is also the same buffer that is the the GBuffer's emissive buffer when it is generated). This is true of the PC and PS3. Rendering is basically Clear Depth, Render Gun Depth to the super-tight viewport, Render Depth, Render Scene GBuffer, Clear Z, Render Gun to GBuffer, perform lighting, translucency, post process etc. We can clear Z in this setup because the rest of the engine reads the alpha channel version of the depth for everything. The XBOX version read's the Z-buffer directly, so we have to preserve world depth values, so instead of 'Clear Z' we render the GUN twice, once a depth-always write and the second with the traditional less-equal test. This is necessary because the viewport clamped depths are not something you want the game to be using. This particular method is an extremely bad idea for PC DX9 hardware in general (NVIDIA's in particular). The hardware is going to fight you: You might be tempted to use oDepth in a shader. This is a bad idea, in that it disables the early depth & stencil reject feature of the hardware when the pixel shader outputs a custom depth. It is also not necessary for getting guns showing up correctly with a custom FOV. It is also a bad idea because you will also need to run a pixel shader when doing depth-only rendering, and it is extremely slow to do this (hardware LOVES rendering depth-only no-pixel-shader setups!). This is also the same reason why you should limit allowing masked textures to be used in shadowmap rendering, as they are significantly slower to render into the shadowmap (somewhere between 4 and 20x slower, its kind of insane how big of a difference it can be). Getting it visually correct is not the real challenge. The real challenges lie in how many ways the hardware can break and performance can go off a cliff. The early-depth and early-stencil reject behaviors of the hardware are particularlly finiky, which gets progressively worse the older the hardware is. NVIDIA's name for these culls are called ZCull and SCull. ATI(AMD whatever) calls it Hi-Z and Hi-Stencil. These early-rejects can be disabled both by some combinations of render states, as well as changing your depth test direction in the middle of the frame. When these early-rejects are not working your pixel shaders will execute for all pixels, even if depth or stencil tests kill the pixels. The result will be visually correct, but the official location for these depth and stencil tests is after the pixel shader. Writing depth or stencil while testing depth or stencil will disable the early-reject for the draw calls doing this. This is sometimes unavoidable, but luckily only affects the specific draw calls that are setup this way. On a lot of NVIDIA hardware, if you change the depth write direction (like I mentioned doing a pass of 'always' before 'lessequal' in order to the fix the Z-buffer on the XBOX), the zcull and scull will be disabled UNTIL THE NEXT DEPTH & STENCIL CLEAR. I expect this to be better or a non-problem with Geforce 280 series and newer, but haven't looked into it for sure. This also means you should always clear both at least at the start of the frame (and use the API's to do it, and not render a quad). This also makes the alternating depth lessequal/greaterequal every other frame trick to try and avoid depth clears a colossally bad idea. The early-stencil test is very limited. On most hardware It pretty much caches the result of a group of stencil tests on some block size number of pixels and compresses it down to a a few bits. This means that using the stencil buffer for storing anything other than 0 and 'non-zero' pretty much worthless. And if you test for anything other than ==0 or !=0, the early stencil reject is not likely to work for you. It also means sharing the stencil buffer with a second mask is extremely difficult if you care about performance, and I definitely don't recommend trying it unless you can afford a second depth buffer with its own stencil buffer. #4826787 Write BITMAPINFOHEADER image data to IDirect3DTexture9 Posted by Zoner on 23 June 2011 - 08:11 AM The pBits pointer from the lock is the address of the upper left corner of the texture. The lock structure contains how many bytes to advance the pointer to get to the next row (it might be padded!). A general texture copy loop that doesn't require format conversion (ARGB to BGRA swizzling etc) can use memcpy, but needs to be written correctly: const BYTE* src = bitmapinfo.pointer.whatever; size_t numBytesPerRowSrc = bitmapinfo.width * (bitmapinfo.bitsperpixel/8); // warning: pseudocode BYTE* dst = lock.pBits; size_t numBytesPerRowDst = lock.pitch; size_t numBytesToCopyPerRow = min(numBytesPerRowSrc, numBytesPerRowDst); for (y=0; y<numRows; ++y) { memcpy(dst, src, numBytesToCopyPerRow); src += numBytesPerRowSrc; dst += numBytesPerRowDst; } As an optimimzation you can test if (numBytesPerRowSrc==numBytesPerRowDst) and do it with a single memcpy instead of with a loop. You are most likely to run into pitch being padded with non-power of two textures, and other special cases (a 1x2 U8V8 textures that is 2 bytes, will likely yield a pitch of at least 4 bytes for instance). If you need to do format conversion its easiest to cast the two pointers to a struct mapped to the pixel layout, and replace the memcpy with custom code. #4823820 Depth of Field Posted by Zoner on 15 June 2011 - 04:05 PM Typically a pipeline looks something like this: depth pass opaque pass (possibly with forward lighting) opaque lighting pass (either deferred or additional passes for multiple lights) opaque post processing (screen space depth fog) translucency pass (glass, particles, etc) post processing (dof, bloom, distortion, color correction, etc) final post processing (gamma correction) SSAO ideally is part of the lighting pass (and even better if it can be made to only affect diffuse lighting) Screen space fog is easy to do for opaque values (as they have easy to access depth information) but then you need to solve fog for translucency. In Unreal, DOF and Bloom are frequently combined into the same operation, though this restricts the bloom kernel quite a bit, but it is fast. So to answer the question: if it is wrong, change it. Screen space algorithms are pretty easy to swap or merge, especially compared to rendering a normal scene. A natural order should fall out pretty quickly. #4818883 For being good game programmer ,good to use SDL? Posted by Zoner on 02 June 2011 - 04:41 PM - It probably has the wrong open source license (its unusable as-is on platforms that don't have dll support), and for the platform's you would need the commercial license won't come with code to run on that platform (PS3, XBOX, etc) anyway, which more or less makes me wonder why the commercial license of SDL costs money. - You still have to deal with shaders (GLSL, Cg, HLSL), which arguably is where a huge portion of the code is going to live. Supporting more than one flavor is a huge amount of work, which can be mitigated with a language neutral shader generator (editor etc), which is also a huge amount of work to create. - Graphics API's in the grand scheme of things aren't all that complicated since the hardware does all of the work, using the APIs raw or even making a basic wrapper for one is a pretty trivial thing to do. - For C++ the real time consuming things end up being things like serialization, proper localization support and string handling, and memory management (multiple heaps, streaming textures etc)
http://www.gamedev.net/user/153524-zoner/?tab=reputation
CC-MAIN-2013-20
refinedweb
4,277
53.34
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards #include <boost/math/special_functions/bessel.hpp> template <class T1, class T2> calculated-result-type cyl_bessel_i(T1 v, T2 x); template <class T1, class T2, class Policy> calculated-result-type cyl_bessel_i(T1 v, T2 x, const Policy&); template <class T1, class T2> calculated-result-type cyl_bessel_k(T1 v, T2 x); template <class T1, class T2, class Policy> calculated-result-type cyl_bessel_k(T1 v, T2 x, const Policy&); The functions cyl_bessel_i and cyl_bessel_k return the result of the modified Bessel functions of the first and second kind respectively: cyl_bessel_i(v, x) = Iv(x) cyl_bessel_k(v, x) = exponential behaviour of Iv. The following graph illustrates the exponential decay of Kv. a comparison to the GSL-1.9 library. Note that only results for the widest floating-point type on the system are given, as narrower types have effectively zero error. All values are relative errors in units of epsilon. The following are handled as special cases first: When computing Iv for x < 0, then ν must be an integer or a domain error occurs. If ν is an integer, then the function is odd if ν is odd and even if ν is even, and we can reflect to x > 0. For Iv with v equal to 0, 1 or 0.5 are handled as special cases. The 0 and 1 cases use minimax rational approximations on finite and infinite intervals. The coefficients are from: While the 0.5 case is a simple trigonometric function: I0.5(x) = sqrt(2 / πx) * sinh(x) For Kv with v an integer, the result is calculated using the recurrence relation: starting from K0 and K1 which are calculated using rational the approximations above. These rational approximations are accurate to around 19 digits, and are therefore only used when T has no more than 64 binary digits of precision. When x is small compared to v, Ivx is best computed directly from the series: In the general case, we first normalize ν to [ 0, [inf]) with the help of the reflection formulae: Let μ = ν - floor(ν + 1/2), then μ is the fractional part of ν such that |μ| <= 1/2 (we need this for convergence later). The idea is to calculate Kμ(x) and Kμ+1(x), and use them to obtain Iν(x) and Kν(x). The algorithm is proposed by Temme in N.M. Temme, On the numerical evaluation of the modified bessel function of the third kind, Journal of Computational Physics, vol 19, 324 (1975), which needs two continued fractions as well as the Wronskian:). Kμ and Kμ+1 can be calculated by where S is also a series that is summed along with CF2, see I.J. Thompson and A.R. Barnett, Modified Bessel functions I_v and K_v of real order and complex argument to selected accuracy, Computer Physics Communications, vol 47, 245 (1987). When x is small (x <= 2), CF2 convergence may fail (but CF1 works very well). The solution here is Temme's series: where fk and hk are also computed by recursions (involving gamma functions), but the formulas are a little complicated, readers are referred to N.M. Temme, On the numerical evaluation of the modified Bessel function of the third kind, Journal of Computational Physics, vol 19, 324 (1975). Note: Temme's series converge only for |μ| <= 1/2. Kν(x) is then calculated from the forward recurrence, as is Kν+1(x). With these two values and fν, the Wronskian yields Iν(x) directly.
http://www.boost.org/doc/libs/1_54_0_beta1/libs/math/doc/html/math_toolkit/bessel/mbessel.html
CC-MAIN-2014-42
refinedweb
601
60.55
In the past when using stl classes in my program I've just done a using namespace::std; to get it correctly. I've been doing some reading, and I guess this isn't a good practice. The following is an example of where I cannot figure out how to get stl to compile without a using namespace::std: The above code works if I throw in a using namespace::std;.The above code works if I throw in a using namespace::std;.Code: #include <list> using std::list; using std::iterator; int main() { list< list<char>* > lines_list; list< list<char>* >::iterator lines_itr = lines_list.begin(); return 0; } It's not a major problem, but I would like to understand the proper way. Chad
https://cboard.cprogramming.com/cplusplus-programming/19535-stl-namespaces-printable-thread.html
CC-MAIN-2017-43
refinedweb
123
61.67
ASP: - An entry on the Web.config file, on the httpHandlers section; - An instance returned from a Handler Factory; - A route handler, like in MVC or Dynamic Data; - Explicitly requested by the URL, in the case of ASHX generic handlers. The httpHandlers section can specify both a handler or a handler factory for a specific URL pattern (say, for example, /images/*.png), which may be slightly confusing. I have already discussed handler factories in another post, have a look at it if you haven’t already. A simple registration would be: 1: <httpHandlers> 2: <add verb="*" path="Image.axd" type="MyNamespace.MyHandler, MyAssembly"/> 3: </httpHandlers> Another option is through a route. The IRouteHandler interface defines a method GetHttpHandler which returns the route handler that will handle the request. You can register a IRouteHandler instance for a specific route by setting the RouteHandler property inside the Route class. Finally, there’s another kind of handler that doesn’t need registering and that is called explicitly: generic handlers. These are .ASHX markup files without any user interface elements that merely reference a code-behind class, which must implement IHttpHandler (you can also place code in the .ASHX file, inside a <script runat=”server”> declaration). Here’s an example: 1: <%@ WebHandler Language="C#" Class="Handler" %> 2: <script runat="server" language="C#">1:2: public class Handler : System.Web.IHttpHandler3: {4: //...5: }6:</script> Having said that, what is a handler good for? The IHttpHandler interface only defines one method, ProcessRequest, and a property, IsReusable. As you can tell, this is considerably more simple than, for example, the Page class, with its myriad of virtual methods and events, which, of course, is also an implementation of IHttpHandler. Because of that, it is much more useful for handling requests that do not need a complex lifecycle. Some scenarios: - Downloading a file; - Uploading a file; - Streaming; - Redirecting; - Returning values for consumption by JavaScript, in AJAX style; - Tracing and monitoring, like ELMAH or the Trace handler; - Generating content dynamically, such as images. The IsReusable indicates to the ASP.NET infrastructure if the hander’s instance can be reused for different identical requests or if a new instance needs to be created. If you don’t store state on the handler’s class, it is safe to return true. As for the ProcessRequest method, a simple implementation might be: 1: public class ImageHandler : IHttpHandler 2: { 3: public void ProcessRequest(HttpContext context) 4: { 5: Bitmap bmp = new Bitmap(400, 300); 6: 7: Graphics g = Graphics.FromImage(bmp); 8: g.DrawRectangle(new Pen(new SolidBrush(Color.Green)), 10, 10, 300, 200); 9: g.DrawString(context.Request.Url.Query, new Font("Arial", 30), new SolidBrush(Color.Yellow), new PointF(10f, 10f)); 10: 11: context.Response.ContentType = "image/gif"; 12: 13: bmp.Save(context.Response.OutputStream, ImageFormat.Gif); 14: } 15: 16: public Boolean IsReusable 17: { 18: get 19: { 20: return (true); 21: } 22: } 23: } This will create an image with a text string that is obtained from the query string, that is, anything in the URL after the ? symbol. Don’t forget to always return the appropriate content type, because the browser won’t know how to handle the content you send without it. One final note: from an handler you normally don't have access to the session - the Session property is null. If you need to use it, you must declare that your handler implements IRequiresSessionState or IReadOnlySessionState, the later for read-only access. That's basically what ASP.NET does when, on your page's markup, you place a EnableSessionState attribute.
http://weblogs.asp.net/ricardoperes/asp-net-web-forms-extensibility-handlers
CC-MAIN-2014-42
refinedweb
592
55.54
A repeating choice that we have to make in databases is to trade off performance for scale. In other words, in order to process more requests per time frame, we need to increase the time it takes to process a single request. Let's see how this works with the case of transaction commits. In the simplest model, a transaction does its work, prepares itself to be committed, writes itself to the journal, and then notifies the client that it has successfully committed. Note that the most important part of the process is writing to the journal, which is how the transaction maintains durability. It also tends to be, by far, the most expensive part of the operation. This leads to a lot of attempts to try and change the equation. I talked about one such option when we talked about the details of the transaction journal, having a journal actor responsible for writing the transaction changes as they happen, and amortize the cost of writing them over time and many transactions. This is something that quite a few databases do, but that does have certain assumptions. To start with, it assumes that transactions are relatively long, and spend a lot of their time waiting for network I/O. In other words, this is a common model in the SQL world, where you have to open a connection, make a query, then make another query based on the results of that, etc. The idea is that you parallelize the cost of writing the changes to the journal along with the time it takes to read/write from the network. But other databases do not use this model. Most NoSQL databases use the concept of a single command (which may aggregate commands), but they don’t have the notion of a long conversation with the client. So there isn’t that much of a chance to spread the cost of writing to the journal on the network. Instead, a common trick is transaction merging. Transaction merging relies on the observation that I/O costs are no actually linear to the amount of I/O that you use. Oh, sure, writing 1KB is going to be faster than writing 10 MB. But it isn’t going to be two orders of magnitude faster. In fact, it is actually more efficient to make a single 10MB write than 1024 writes on 1 KB. If this makes no sense, consider buying groceries and driving back to your house. The weight of the groceries has an impact on the fuel efficiency of the car, but the length of the drive is of much higher importance in terms of how much fuel is consumed. If you buy 200 KG of groceries (you are probably planning a hell of a party) and drive 10 KB home, you are going to waste a lot less fuel than if you make 4 trips with 50 KG in the trunk. So what is transaction merging? Put simply, instead of calling the journal directly, we queue the operation we want to make, and let a separate thread run through all the concurrent operations. Here is the code: def MergeTransactionThreadProc(): buffer = Buffer() while true: buffer.Clear() result = DequeueOperation() if result.Success is false: WaitForAdditionalOperations() continue buffer.Write(result.Operation, result.Notification) max = time.time() + 1 while time.time() < max: result = DequeueOperation() if result.Success is false: break buffer.Write(result.Operation, result.Notification) journal.SyncBuffer(buffer) buffer.NotifyAllOperationsAboutSuccessfulJournalSync() The secret here is that if we have a load on the system, by the time we read from the queue, there are going to be more items in there. This means that when we write to the journal file, we’ll write not just a single operation (a trip back and forth to the grocery store), but we’ll be able to pack a lot of those operations immediately (one single trip). The idea is that we buffer all of the operations, up to a limit (in the code above, we use time, but typically you would also consider space), and then flush them to the journal as a single unit. After doing this, we can notify all of the operations that they have been successfully completed, at which point they can go and notify their callers. We traded off the performance of a single operation (because we now need to be more complex and pay more I/O) in favor of being able to scale to a much higher number of operations. If your platform support async, you can also give up the thread (and let some other request run) while you are waiting for the I/O to complete. The number of I/O requests you are going to make is lower, and the overall throughput is higher. Just to give you an example, in one of our tests, this single change moved us from doing 200 requests/second (roughly the maximum number of fsync()/sec that the machine could support) to supporting 4,000 requests per second (20x performance increase)! {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/the-guts-n-glory-of-database-internals-merging-tra
CC-MAIN-2017-34
refinedweb
852
59.33
This bug was filed from the Socorro interface and is report bp-e5104f83-9047-4a65-b1ca-2f9912130908. Appears to be regression in TB24. #1 crash so far ============================================================= "I tried to subscribe to another newsgroup and typed "comp" as the start of the name. Then I noticed that was incorrect, and used backspace to erase all those characters. It got down to "c" remaining, then crashed." Robert 0 plc4.dll PL_strncasecmp nsprpub/lib/libc/src/strcase.c 1 xul.dll nsCaseInsensitiveCStringComparator::operator()(char const *,char const *,unsigned int,unsigned int) xpcom/string/src/nsStringComparator.cpp 2 xul.dll Compare(nsACString_internal const &,nsACString_internal const &,nsCStringComparator const &) xpcom/string/src/nsTStringComparator.cpp 3 xul.dll nsCStringLowerCaseComparator::LessThan(nsCString const &,nsCString const &) mailnews/news/src/nsNntpIncomingServer.cpp 4 xul.dll nsTArray_Impl<nsCString,nsTArrayInfallibleAllocator>::Compare<nsCStringLowerCaseComparator>(void const *,void const *,void *) objdir-tb/mozilla/dist/include/nsTArray.h 5 xul.dll med3 objdir-tb/mozilla/xpcom/build/nsQuickSort.cpp 6 xul.dll NS_QuickSort objdir-tb/mozilla/xpcom/build/nsQuickSort.cpp 7 xul.dll NS_QuickSort objdir-tb/mozilla/xpcom/build/nsQuickSort.cpp 8 xul.dll NS_QuickSort objdir-tb/mozilla/xpcom/build/nsQuickSort.cpp 9 xul.dll NS_QuickSort objdir-tb/mozilla/xpcom/build/nsQuickSort.cpp 10 xul.dll NS_QuickSort objdir-tb/mozilla/xpcom/build/nsQuickSort.cpp bp-d3ea40bb-d71b-4805-a174-ae3212130918 another user, if we need someone to reproduce #6 crash for Tb25 aurora stack size of windows is 1MB, but Linux is 8MB.... Crashes also on Seamonkey 2.21 See crash report: ID: f1922010-b159-4398-bed1-9a1ed2130919 Signature: PL_strncasecmp | nsCaseInsensitiveCStringComparator::operator()(char const*, char const*, unsigned int, unsigned int) *** Bug 918346 has been marked as a duplicate of this bug. *** Created attachment 808284 [details] News subscribe dialog TB 17.0.8 with filter Already in version 17.0.8 was ns_quicksort incorrect. The first element is out of place. Created attachment 808285 [details] News subscribe dialog TB 24.0 with filter In version TB 24.0 ns_quicksort is totally broken. The elements are completely messed up. The recursion depth is thus obviously much too high. With many results (~16000) that causes the stack overflow. I suspect Bug 872497 ( O(n^2) performance in NS_QuickSort) (In reply to Philip Chee from comment #7) > I suspect Bug 872497 ( O(n^2) performance in NS_QuickSort) > Yes, I can confirm that. Without that patch the result looks like the TB17.0.8 result. :-) And no crash! (In reply to Alfred Peters from comment #5) > The first element is out of place. (In reply to Alfred Peters from comment #6) > The elements are completely messed up. QuickSort is non-stable sort. Patch of Bug 872497 simply removed "do nothing if data is already sorted in ascending order" part only, in order to resolve severe performance problem of NSQuickSort() when (a) first half of data is sorted in descending order and (b) second half of data is also sorted in descending order, and when (a) < (b). Because of "(a) < (b)", swap won't occur, then insertion sort was executed for entire data which is never sorted in ascending order(each half of data is already sorted in descending order). If reason of crash is non-stable sort, it's simply bug of caller of NS_QuickSort(), isn't it? Or sort result is incorrect after patch of Bug 872497? If so, it's problem since initial of NS_QuickSort()? Or incorrect sort result due to stack over flow after patch of Bug 872497? (In reply to Alfred Peters from comment #6) > The recursion depth is thus obviously much too high. After patch of Bug 872497, NS_QuickSort() merely applies same sort algorythm for random data to "already sorted data in ascending order" and to "already sorted data in descending order". If big random data, NS_QuickSort() can always produce such deep recursion depth. Why Tb still doesn't use std::stable_sort() or std::sort() of C++? Does problem occur with std::stable_sort() or std::sort() of C++? (In reply to Alfred Peters from comment #5) > Created attachment 808284 [details] > News subscribe dialog TB 17.0.8 with filter > Already in version 17.0.8 was ns_quicksort incorrect. The first element is out of place. How many news groups is sorted? Only 27 newsgroups which are seen in the screen shot? Is newsgroup name already sorted in ascending order when newsgroup names is passed from news server? Incorrect position is not first element only. alabama.test, which should be first element if ascending order, is also placed at wrong position. If sort key is newsgroup name, this is never due to non-stable sort. Phenomenon is perhaps next. de.mein.test3 is chosen as pivot, then alabama.test at position 0 and de.mein.test3 at mid are swapped. After it, NS_QuickSort() does do sorting of first half(smaller than pivot), de.mein.test3, alaba..., ..., de.mein..., alabama.test, then NS_QuickSort() does do sorting of second half(larger than pivot), de.mein.test3 to netgame.test. Because of bug in logic of NS_QuickSort() since initial of NS_QuickSort(), sort result is incorrect. (when N == 2**n +/- 1, forget to move/swap data at pivot?) (when N == 2**n +/- 1, infinite recursive call after patch of Bug 872497?) Is there any reason to continue using NS_QuickSort() which can surely produce wrong sort result? If no crash by backout of Bug 872497, wrong sort result is preferable for Tb or acceptable for Tb? (In reply to Alfred Peters from comment #5) > Already in version 17.0.8 was ns_quicksort incorrect. The first element is out of place. Another question. Sorting of newsgroup name is based on hiearchy of newsgroup name, and order/structure is correctly shown as expected if "filter"(Show items that contain) is not requested. Is newsgroup names sorted by newsgroup name using NS_QuickSort() after picking up filtered newsgroups when "filter"(Show items that contain) is requested at subscribe of news account? If yes, is comparison function correctly passed to NS_QuickSort()? If no, it's "sort entire newsgroups in ascending order" then "pickup filtered newsgroup"? If so, how many newsgroups are defined at the news server? (In reply to Alfred Peters from comment #6) > With many results (~16000) that causes the stack overflow. If many newsgroups is sorted, and if data is already fully sorted in ascending order, difference of "recursive call depth" between "before patch" and "afer patch" can be explained. Before patch : Insertion sort is applied to long element part at early stage of NS_QuickSort() process, then recursive call depth is 1 at most. After parch : Insertion sort is not applied unles elments length is less than 7. This is same algorithm/logic as one for "fully random data", and is always applied to "fully pre-sorted data in ascending order or descending order" too after the patch. So, "split to two parts then do recursive call for a half part" is repeated until element part length reaches "less than 7". If crash is due to stack overflow by "too deep recursive call", such stack overflow should always occur also in sorting of fully random data of same element number by NS_QuickSort(). Does problem like "infinte recursive call" occur in NS_Quicksort()? Crash occurs in StringComparator. Crash caused by fully broken sort result, instead of stack overflow? (In reply to WADA from comment #12) > Crash occurs in StringComparator. > Crash caused by fully broken sort result, instead of stack overflow? No, the stacks on crash-stacks say EXCEPTION_STACK_OVERFLOW Created attachment 811557 [details] [diff] [review] Correction of the comparison function LessThen () in class nsCStringLowerCaseComparator The incorrect comparison function causes the worst case of the quicksort algorithm, which caused the stack overflow. Comment on attachment 811557 [details] [diff] [review] Correction of the comparison function LessThen () in class nsCStringLowerCaseComparator Review of attachment 811557 [details] [diff] [review]: ----------------------------------------------------------------- ::: mailnews/news/src/nsNntpIncomingServer.cpp @@ +73,5 @@ > } > > bool LessThan(const nsCString &a, const nsCString &b) const > { > + return (Compare(a, b, nsCaseInsensitiveCStringComparator()) < 0); nit: Extraneous parentheses. Created attachment 812134 [details] [diff] [review] Correction of the comparison function LessThen() in class nsCStringLowerCaseComparator > > + return (Compare(a, b, nsCaseInsensitiveCStringComparator()) < 0); > > nit: Extraneous parentheses. OK, corrected. (In reply to Alfred Peters from comment #16) > Created attachment 812134 [details] [diff] [review] > > nit: Extraneous parentheses. > OK, corrected. I'm not the real reviewer. Could this be a problem? If not, could someone set the checkin-needed keyword. I do not have sufficient rights to do so. That's ok. Especially when carrying a review forward like that for nits fixed, it's good to add the reviewer also in the hg commit message. Like r=jcranmer. When is Thunderbird 27.0 scheduled for release to end users? This is a critical bug. TB27 will never be released to end users. But this should go into TB24.0.1 that will go soon. Comment on attachment 812134 [details] [diff] [review] Correction of the comparison function LessThen() in class nsCStringLowerCaseComparator [Triage Comment] We want to take this onto esr for 24.0.1 to get it fixed there.
https://bugzilla.mozilla.org/show_bug.cgi?id=917955
CC-MAIN-2016-30
refinedweb
1,486
51.65
No new comments. View All Comments No new messages. View All Messages No new notifications. View All Notifications * * Login using Answers In Focus LEARN: Introduction to Entity Framework LEARN: Getting Started with SQL Server 2016 C# Corner Annual Conference 2017 Announced Forums - C# Corner C# Corner Home Technologies Monthly Leaders ASK A QUESTION C# Programming Multi-threading IoT Coffee, Chai Lounge HTML, JavaScript, CSS .NET General Office Interoperability Microsoft Surface Community Services iPhone, iPad Active Directory Printing ReFS Current Affairs Java ADO.NET & Database Project Management Silverlight 5 Fun and Jokes JQuery AJAX & Atlas Remoting WCF Job Opportunities JSP Algorithms & AI Reporting Windows 8 Leadership Multimedia, Graphics, Flash Arrays & Collections Robotics and Hardware Windows Azure Mac for Windows Node.js ASP.NET & Web Development Security & Cryptography Windows Store Apps Microsoft Feedback PHP C# Language Setup & Deployment Workflow Foundation Open Source Projects Social Networking C# References Sharepoint WPF Operating Systems TypeScript CLR & .NET Internals Speech & Voice Recognition XAML Language Paid Projects Web Hosting COM Interoperability Tablet PC Site and Forums Feedback Prizes, Awards, MVP Website Management Custom Controls Testing and QA Announcements Students & Beginner Projects Windows Phone 7 Design and Architecture Visual Basic .NET Author Guidelines Test Category Database Embedded Development Visual C++ Bugs and Problems Training & Certification Database General Enterprise Development Visual Studio 11 Forums Feedback Web Development Oracle Games, DirectX, and XNA Visual Studio 2010 Site Feedback & Suggestions Advertising, Marketing, SEO SQL GDI+ and DirectX Web Services Site Spams Android SQL Server General Windows Forms Miscellaneous AngularJS Products LINQ Windows Services .NET Books Cloud Computing Office 2013 Migrating to .NET Cutting-Edge Ask the Author Expression Tools Products Mobile Development .NET 5.0 Career Advice HTML 5 SharePoint 2013 Forum guidelines C# Language C# .net Fundamental Answers Needed for 25 MCQ Mohammad Arif 1.4k 3 39.7k C# .net Fundamental Answers Needed for 25 MCQ Nov 23 2010 8:57 PM CAN ANYONE SOLVE MY 25 MCQ??? 1. Question: The global assembly cache: a. Can store two dll files with the same name b. Can store two dll files with the same name, but different version c. Can store two dll files with the same name and same version d. Can not store dll files with the same name 2. Question: Which of the following statements is correct with regard to .NET framework managed web pages? a. They interact directly with the runtime b. They do not execute in the native code language c. They are interpreted and scripted d. All of the above 3. Question: A banking application is online. As soon as Martin finished his session, Lisa logged on and did some banking. The connection string created for each of them is as follows: String ConnStr= "Server=BankServer;Database=BankDB;User=Martin;Password=gilbo123;" String ConnStr= "Server=BankServer;Database=BankDB;User=Lisa;Password=kari75;" Which of the following statements will be correct in case the connection pooling is also switched on? a. There is a possibility of Lisa using the same connection object as created for Martin from the connection pool b. Lisa can not use someone else's connection from the connection pool c. Lisa can pick any other ideal connection from the connection pool d. None of the above 4. Question: What are the core components of the .Net framework data provider model? a. DataAdapter and DataReader b. Connection and Command c. DataAdapter, Connection, and Command d. DataAdapter, DataReader, Connection, and Command 5. Question: Dot Net Framework consists of : a. Common language runtime b. Set of class libraries c. Common language runtime and set of class libraries 6. Question: _____________ helped overcome the DLL conflict (faced by the versions prior to .NET). a. CLR b. JIT c. CTS d. GAC e. Satellite Assemblies f. All of the above 7. Question: Which of the following types of cursors is available with ADO.NET DataReader object? a. server-side, forward-only, and read-write cursor b. server-side, forward-only, and read-only cursor c. server-side, backward-only, and read-write cursor d. server-side, bidirectional, and read-only cursor 8. Question: Which of the following does not constitute the benefits of CLR? a. Ability to use components developed in different language b. Garbage collection c. IDL (Interface Definition Language) use is promoted by restricting self describing objects d. Ability to compile once, and run on any CPU 9. Question: Can you overload a function with the same number and types of arguments (parameters) but with a different return type? a. Yes b. No c. Yes, but only if function is static d. Yes, but only if function is virtual 10. Question: Which of the following are true about constructors and member functions? a. A constructor can return values, but a member function cannot b. A member function can declare and define values, but a constructor cannot c. A member function can return values, but a constructor cannot d. All of the above 11. Question: Which of the following are true about operator overloading? a. *operator can be overloaded to perform division b. **can be overloaded to perform ''to the power of'' c. If == (equality operator) is overloaded then C# rules enforce that!= (inequality operator ) also be overloaded d. If the + operator is overloaded then += works automatically e. In a class named MyClass the following syntax is correct to overload equality: public static bool operator ==(MyClass obj) 12A. Question: Which of the following statements are correct with regard to Polymorphism? a. Polymorphism is a process by which a class can exist in multiple forms b. Polymorphism is a process by which a class can exist in only two forms c. Polymorphism is a process by which objects of a reference type can display different behavior d. Polymorphism is a process by which different instances of the same class display different behavior e. Polymorphism allows old code in a class library to call new code written by a programmer that derives a class from a class in the class library 12B. Question: ___________ namespace is not defined in the .NET class library. a. System b. System.CodeDom c. System.IO d. System.Thread e. System.Text 13. Question: How can an abstract function be declared? a. By equating it to 1 b. By equating it to zero c. By using the virtual keyword d. By using the abstract keyword 14. Question: Which object oriented concept is related to the derivation of a class based on another class? a. Encapsulation b. Polymorphism c. Data Hiding d. Inheritance e. Overloading 15. Question: Which of the following help increase the code safety and stability? a. Inheritance b. Polymorphism c. Abstraction d. Encapsulation 16. Question: Which of the following are not C# value types? a. long b. bool c. struct d. class e. string 17. Question: What happens when the below code is executed? abstract class Shape { public abstract void draw(); } class Rectangle: Shape { public override void draw(); //Some more member functions..... } class CCheck { public static void Main() { Shape objShape; } } a. The code will compile and run. b. Compile error for draw method will be encountered first c. Defining the body of the draw() method in class Rectangle would let the class compile. d. None of the above 18. Question: You created a stored procedure to retrieve the following details for the given customer: CustomerName, Address, PhoneNumber Which of the following is an ideal choice to get the best performance? a. Return the result as dataset using data adapter b. Return the result as dataset using command object c. Return the result as three out parameters and command object d. All of the above 19. Question: In C#, exception handling should be used......... a. to handle the occurrence of unusual or unanticipated program events b. to redirect the programs normal flow of control c. in cases of potential logic or user input errors d. in case of overflow of an array boundary 20. Question: Which of the following has the lowest precedence? a. Bitwise operators b. Multiplication and Division c. Assignment operators d. Logical operators 21. Question: Which of the following is capable of returning multiple rows and multiple columns from the database? a. ExecuteReader b. ExecuteXmlReader c. DataAdapter d. All of the above 22. Question: Which of the following command types are provided by an oledb and sql provider? a. StoredProcedure,Text,Table b. StoredProcedure,Query,Table c. Procedure,Text,Table,Query d. Procedure,Query,Table 23. Question: Which access specifier will you use to make base class members accessible in the derived class and not accessible for the rest of the program? a. public access specifier b. private access specifier c. protected access specifier d. static access specifier 24. Question: Which of the following define the rules for .Net Languages? a. GAC b. CLS c. CLI d. CTS e. CLR f. JIT 25. Question: Which of the following are true? a. Function overloading is an example of static polymorphism b. Operator overloading is an example of static polymorphism c. Function overloading is an example of dynamic polymorphism d. Operator overloading is an example of dynamic polymorphism e. Overriding virtual functions of the parent class in a derived class is an example of static polymorphism f. Overriding virtual functions of the parent class in a derived class is an example of dynamic polymorphism Reply Answers ( 5 ) Is there a between operator in C#? Where are cookies stored on my PC? Follow @twitterapi File APIs for .NET Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!
http://www.c-sharpcorner.com/forums/c-sharp-net-fundamental-answers-needed-for-mcq
CC-MAIN-2017-13
refinedweb
1,593
59.5
Adding Links in the Navbar Now that we have our first route set up, let’s add a couple of links to the navbar of our app. These will direct users to login or signup for our app when they first visit it. Replace the render method in src/App.js with the following. render() { return ( <div className="App container"> <Navbar fluid collapseOnSelect> <Navbar.Header> <Navbar.Brand> <Link to="/">Scratch</Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav pullRight> <NavItem href="/signup">Signup</NavItem> <NavItem href="/login">Login</NavItem> </Nav> </Navbar.Collapse> </Navbar> <Routes /> </div> ); } This adds two links to our navbar using the NavItem Bootstrap component. The Navbar.Collapse component ensures that on mobile devices the two links will be collapsed. And let’s include the necessary components in the header. Replace the react-router-dom and react-bootstrap import in src/App.js with this. import { Link } from "react-router-dom"; import { Nav, Navbar, NavItem } from "react-bootstrap"; Now if you flip over to your browser, you should see the two links in our navbar. Unfortunately, when you click on them they refresh your browser while redirecting to the link. We need it to route it to the new link without refreshing the page since we are building a single page app. To fix this we need a component that works with React Router and React Bootstrap called React Router Bootstrap. It can wrap around your Navbar links and use the React Router to route your app to the required link without refreshing the browser. Run the following command in your working directory. $ npm install react-router-bootstrap --save And include it at the top of your src/App.js. import { LinkContainer } from "react-router-bootstrap"; We will now wrap our links with the LinkContainer. Replace the render method in your src/App.js with this. render() { return ( <div className="App container"> <Navbar fluid collapseOnSelect> <Navbar.Header> <Navbar.Brand> <Link to="/">Scratch</Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav pullRight> <LinkContainer to="/signup"> <NavItem>Signup</NavItem> </LinkContainer> <LinkContainer to="/login"> <NavItem>Login</NavItem> </LinkContainer> </Nav> </Navbar.Collapse> </Navbar> <Routes /> </div> ); } And that’s it! Now if you flip over to your browser and click on the login link, you should see the link highlighted in the navbar. Also, it doesn’t refresh the page while redirecting. You’ll notice that we are not rendering anything on the page because we don’t have a login page currently. We should handle the case when a requested page is not found. Next let’s look at how to tackle handling 404s with our router. If you liked this post, please subscribe to our newsletter, give us a star on GitHub, and check out our sponsors. For help and discussionComments on this chapter
https://branchv21--serverless-stack.netlify.app/chapters/adding-links-in-the-navbar.html
CC-MAIN-2022-33
refinedweb
467
67.35
I wrote some articles about AWS Cloud Developer Kit earlier this year. I was attracted to CDK immediately upon hearing of it due to the ability to write infrastructure as code in TypeScript. I really like writing code in TypeScript and CDK seemed almost too good to be true. Table of Contents - A Missed Opportunity? - Lamba in CDK - aws-lambda-nodejs - Parcel - Refactoring #1 - Refactoring #2 - Next Steps A Missed Opportunity? CDK is a new technology and that means that it doesn't necessarily cover every use case yet. What I found as I worked through official examples was that somebody had written CDK code in TypeScript but the accompanying Lambda code was written in JavaScript! This struck me as a missed opportunity. It turns out it wasn't a missed opportunity but one that just hadn't landed yet. Lambda in CDK To explain a bit better for those who aren't really in the transpilation game, TypeScript code is usually transpiled into JavaScript before being shipped into a runtime, be that runtime a web server, NodeJS or Lambda. That's because (leaving deno aside for now), there's no TypeScript execution environment. I say usually because there is actually a pretty cool project called ts-node that lets you execute TypeScript code in NodeJS without transpiling the code ahead of time. ts-node is a great tool to save developers a step in development flows. It's debatable whether you should use it in production or not (I don't). That said, it's totally appropriate to use ts-node with CDK. This lets you shorten the code=>build=>deploy cycle to code=>deploy. That's great! But this doesn't work with Lambda Functions. CDK turns my TypeScript infrastructure constructs into CloudFormation. It doesn't do anything special with my Lambda code - or at least it didn't until the aws-lambda-nodejs module landed in CDK. aws-lambda-nodejs The aws-lambda-nodejs module is an extension of aws-lambda. Really the only thing it adds is an automatic transpilation step using Parcel. Whenever you run a cdk deploy or cdk synth, this module will bundle your Lambda functions and stick the result in special .cache and .build directories (which you will probably want to gitignore). Then the deploy process will stage the bundles in S3 and provide them to Lambda - all with no extra config required. It's quite impressive! An interesting thing about this module is it actually does your Parcel build in Docker, which will let you build for a different runtime (NodeJS version) than you are running locally. You could even have multiple functions with different runtimes if you needed to for some reason. This does mean you need to have Docker installed to use the module which might give you grief if you're running CDK in some CD pipeline that doesn't have Docker available. Parcel I actually haven't used Parcel before. I remember it arriving on the scene a couple of years back, but I have already paid the "Webpack tax" (meaning I have spent enough time with Webpack that I can be productive without creating a complete mess) so I never got around to looking at Parcel. This is pretty cool. I my have to rethink my approach to SAM. Refactoring #1 Okay, so let's update my projects to use aws-lambda-nodejs! I'll start with my Step Functions example:. This should be pretty simple since the functions are incredibly basic with no dependencies. First I update all my dependencies. No reason to be working with old versions. In fact when I wrote this code back in December 2019, the latest version of CDK was 1.19.0 and aws-lambda-nodejs didn't exist yet. Today, May 29, 2020, the latest version of CDK is 1.41.0. You get a lot of advantages by staying current which is why my repo is set up with dependabot and github actions. Anyway, I'm current so now I can npm i @aws-cdk/aws-lambda-nodejs and then modify some code! My old code using the aws-lambda function looked like this: import { AssetCode, Function, Runtime } from '@aws-cdk/aws-lambda'; const lambdaPath = `${__dirname}/lambda`; const assignCaseLambda = new Function(this, 'assignCaseFunction', { code: new AssetCode(lambdaPath), handler: 'assign-case.handler', runtime: Runtime.NODEJS_12_X, }); The assumption here is that some other process (in my case just simple tsc) will drop the transpiled lambda code (assign-case.js) in the right place. Here's my refactor: import { Runtime } from '@aws-cdk/aws-lambda'; import { NodejsFunction } from '@aws-cdk/aws-lambda-nodejs'; const lambdaPath = `${__dirname}/lambda`; const assignCaseLambda = new NodejsFunction(this, 'assignCaseFunction', { entry: `${lambdaPath}/assign-case.ts`, handler: 'handler', runtime: Runtime.NODEJS_12_X, }); I'm now using the entry key to specify the TypeScript file that has my function handler. I'm still specifying the runtime, but maybe I don't have to. I kind of like being really explicit about my runtime. Will maybe play around with having that derived later on. That's basically it! Everything else in my PR is either a dependency update or removing the unneeded build system. I deployed this and it works just fine. I checked out the code in the Lambda console and it looks good too. Check out my PR diff for this refactor. Refactoring #2 My other CDK example has dependencies in aws-cli (DynamoDB) and the faker library. Let's see how Parcel handles those. The code change required is trivial. Here's my PR diff. Now let's see how Parcel handled bundling my function. It produced an index.js file weighing in at 11.6 MB. That seems kind of big, considering this is a sample project. Inspecting the file, it seems that Parcel brought in all of aws-sdk. It doesn't look like proper tree-shaking is happening here and there's no way to declare aws-sdk as an external module in Parcel 1. Well, that's a weakness for sure. Fortunately there is a config option for minify. Let's try that and see if it helps. const initDBLambda = new NodejsFunction(this, 'initDBFunction', { entry: `${lambdaPath}/init-db.ts`, handler: 'handler', memorySize: 3000, minify: true, runtime: Runtime.NODEJS_12_X, timeout: Duration.minutes(15), }); The minified build is now 6.3 MB. That's a good reduction in size, but if we could remove the non-DynamoDB dependencies from aws-sdk, it would be a heck of a lot smaller. It doesn't look like Parcel 1 allows that unfortunately. Parcel 2 should add some more of these quality of life issues and will definitely be worth a look. I recommend watching this issue to see that unfold. To be clear, if your million dollar app has a 6 MB Lambda in it, you are probably quite happy. This isn't a fatal flaw by any means, but it's certainly an area for improvement. Next Steps I should mention that at the time of this writing, this module is marked experimental, which means the API could change at some point in the near future. I'm sure the CDK team will want to switch to Parcel 2 when that's available and this module will improve. Whether or not to use this for production will depend on the workload. Given the rate CDK is moving, I would consider using this module for an active development situation where the tooling can evolve, but it's maybe not ideal for a case where we want to ship something and expect stability. Cover: The Beagle Laid Ashore drawn by Conrad Martens (1834) and engraved by Thomas Landseer (1838) Posted on May 12 by: Matt Morgan TypeScript, Lambda, Serverless, IoC, Cloud Native, make it faster! Discussion
https://dev.to/elthrasher/aws-cdk-aws-lambda-nodejs-module-9ic
CC-MAIN-2020-29
refinedweb
1,297
65.73
Hey I am trying to make a smal random number game just for practice and have 2 questions. First I'm wondering if im generating the random number (between 1 and 100) the correct way. Second I am wondering how to loop this program (preferably with a for loop) so it will ask more than 1 time and then produce the answer, if the answer isnt correct then I obviously want it to ask then answer again. I am not sure you can use a for with the if-else? Anyways any help will be appreciated, thanks. Code: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main () { int guess; double random; int i; cout << " I'm guessing of a number between 1 and 100 can you guess it?\n"; cin >> guess; srand(time(NULL)); random = rand() % (100 + 1); if (random > guess) cout << "Guess was too big\n"; else if (random < guess) cout << "Guess was too small\n"; else if (random == guess) cout << "You got it!\n"; system ("pause"); return 0; }
http://cboard.cprogramming.com/cplusplus-programming/123181-couple-questions-very-small-random-number-program-printable-thread.html
CC-MAIN-2016-18
refinedweb
172
76.15
Python Musings #7: Simulating FSAs in lieu of real postal code data. Want to share your content on python-bloggers? click here. Disclaimer The following is the same content that I have posted in my other blog on this topic in R, but written in Python. While I actually first wrote the code for doing this in Python, I’ll be posting the similar verbiage from that blog here. Introduction Often when scraping data, websites will ask a user to enter a postal code to get the locations near it. If you are interested in collecting data on locations in Canada for an entire Province or the entire province from a site, it might be hard to find a list of all postal codes or FSAs in Canada or in a given province which is easy to use. Information on how FSAs work can be found here. In this blog, I’m going to share a brief snippet of code that you can use to generate Canadian FSAs. While some FSAs generated may not actually exist, if we follow the rules about Canadian postal codes, it serves as a good substitute in lieu of an actual list. The Code is essentially 3 nested for-loops. While many programmers would not advise writing nested for-loops, I find that for this case it is easier to understand and write. import string fsa_list =[] alphabet = list(string.ascii_uppercase) province_alphabet = ["A","B","C","E","G","H","J","K","L","M","N","P","R","S","T","V","X","Y"] nonLetters=["D", "F", "I", "O", "Q", "U"] second_letter= list(set(string.ascii_uppercase)-set(nonLetters)) for letter1 in province_alphabet: for number in [0,1,2,3,4,5,6,7,8,9]: for letter2 in alphabet: fsa_list.append(letter1+str(number)+letter2) We now have our simulated FSAs! import random random.sample(fsa_list,10) ['A0I', 'S7H', 'R5O', 'V4T', 'R9G', 'B6W', 'T6D', 'B9O', 'M0B', 'Y7H'] Want to see more of my content? Be sure to subscribe and never miss an update! Want to share your content on python-bloggers? click here.
https://python-bloggers.com/2021/10/python-musings-7-simulating-fsas-in-lieu-of-real-postal-code-data/
CC-MAIN-2022-40
refinedweb
343
64.2
MQTT Publish Subscribe - 7.10 firmware or later with Python Demo Procedure - Start the MQTT scripts after the device boots up - Logon to the cloud website and monitor the traffic - Turn the switch on the first device to "on" or "off" position - The LED on the second device should turn "on" or "off" Sample Code Please note that this sample code uses the Lantronix APIs for hardware access that are present in firmware versions 7.10 and above. To import the APIs, add this to your Python script: from ltrxlib import * Device #1 This code snippet polls the state of the digital input and publishes a message whenever the state changes. The code invokes the methods in the Lantronix Device Abstraction class (LtrxDsal) available inside the "ltrxlib" module. ###) Device #2 This code snippet parses the received message from the MQTT subscription and set the relay state based on the command. The code invokes the methods in the Lantronix Device Abstraction class (LtrxDsal) available inside the "ltrxlib" module. ###...'
http://wiki.lantronix.com/developer/MQTT_Publish_Subscribe
CC-MAIN-2019-09
refinedweb
167
64.44
Test Run - Super-Simple Mutation Testing By James McCaffrey | May 2011 Most testers I know have heard of mutation testing, but few have actually performed it. Mutation testing has the reputation of being difficult and requiring expensive third-party software tools. However, in this month’s column, I’ll show you how to create a super-simple (fewer than two pages of code and four hours of time) mutation testing system using C# and Visual Studio. By keeping the mutation testing system simple, you can get most of the benefits of a full-fledged mutation system at a fraction of the time and effort. Mutation testing is a way to measure the effectiveness of a set of test cases. The idea is simple. Suppose you start with 100 test cases and your system under test (SUT) passes all 100 tests. If you mutate the SUT—for example, by changing a “>” to a “<” or by changing a “+” to a “-”—you presumably introduce a bug into the SUT. Now if you rerun your 100 test cases, you’d expect at least one test case failure indicating that one of your test cases caught the faulty code. But if you see no test failures, then it’s quite likely that your set of test cases missed the faulty code and didn’t thoroughly exercise the SUT. The best way for you to see where I’m headed is by looking at Figure 1. Figure 1 Mutation Testing Demo Run The SUT in this example is a library named MathLib.dll. The technique I present here can be used to test most Microsoft .NET Framework systems including DLLs, WinForms applications, ASP.NET Web applications and so on. The mutation system begins by scanning the original source code for the SUT, looking for candidate code to mutate. My super-simple system looks only for “<” and “>” operators. The test system is set to create and evaluate two mutants. In a production scenario, you’d likely create hundreds or even thousands of mutants. The first mutant randomly selects an operator to mutate, in this case a “>” operator at character position 189 in the SUT source code, and mutates the token to “<”. Next, the mutant DLL source code is built to create a mutant MathLb.dll library. Then the mutation system calls a suite of test cases on the mutant SUT, logging results to a file. The second iteration creates and tests a second mutant in the same way. The result of the log file is: ============= Number failures = 0 Number test case failures = 0 indicates possible weak test suite! ============= Number failures = 3 This is good. ============= The first mutant didn’t generate any test case failures, which means you should examine the source code at position 189 and determine why none of your test cases exercise that code. The SUT My super-simple mutation testing demo consists of three Visual Studio projects. The first project holds the SUT, and in this case is a C# class library named MathLib. The second project is a test harness executable, in this case a C# console application named TestMutation. The third project creates and builds the mutants, in this case a C# console application named Mutation. For convenience I placed all three projects in a single directory named MutationTesting. With mutation testing there are a lot of files and folders to keep track of and you shouldn’t underestimate the challenge of keeping them organized. For this demo I used Visual Studio 2008 (but any Visual Studio version will work) to create a dummy MathLib class library. The entire source code for the dummy SUT is shown in Figure 2. Notice I retained the default class name of Class1. The class contains a single static method, TriMin, which returns the smallest of three type double parameters. Also note the SUT is deliberately incorrect. For example, if x = 2.0, y = 3.0 and z = 1.0, the TriMin method returns 2.0 instead of the correct 1.0 value. However, it’s important to note that mutation testing does notdirectly measure the correctness of the SUT; mutation testing measures the effectiveness of a set of test cases. After building the SUT, the next step is to save a baseline copy of the source file, Class1.cs, to the root directory of the mutation testing system. The idea is that each mutant is a single modification of the original source code of the SUT and so a copy of the original SUT source must be maintained. In this example I saved the original source as Class1-Original.cs in directory C:\MutationTesting\Mutation. The Test Harness In some testing situations, you may have an existing set of test-case data, and in some situations you have an existing test harness. For this super-simple mutation testing system, I created a C# console application test harness named TestMutation. After creating the project in Visual Studio, I added a Reference to the SUT: MathLib.dll located at C:\MutationTesting\MathLib\bin\Debug. The entire source code for the test harness project is presented in Figure 3. using System; using System.IO; namespace TestMutation { class Program { static void Main(string[] args) { string[] testCaseData = new string[] { "1.0, 2.0, 3.0, 1.0", "4.0, 5.0, 6.0, 4.0", "7.0, 8.0, 9.0, 7.0"}; int numFail = 0; for (int i = 0; i < testCaseData.Length; ++i) { string[] tokens = testCaseData[i].Split(','); double x = double.Parse(tokens[0]); double y = double.Parse(tokens[1]); double z = double.Parse(tokens[2]); double expected = double.Parse(tokens[3]); double actual = MathLib.Class1.TriMin(x, y, z); if (actual != expected) ++numFail; } FileStream ofs = new FileStream("..\\..\\logFile.txt", FileMode.Append); StreamWriter sw = new StreamWriter(ofs); sw.WriteLine("============="); sw.WriteLine("Number failures = " + numFail); if (numFail == 0) sw.WriteLine( "Number test case failures = " + "0 indicates possible weak test suite!"); else if (numFail > 0) sw.WriteLine("This is good."); sw.Close(); ofs.Close(); } } } Observe that the test harness has three hardcoded test cases. In a production environment, you’d likely have many hundreds of test cases stored in a text file and you could pass the filename in to Main as args[0]. The first test case, “1.0, 2.0, 3.0, 1.0,” represents the x, y and z parameters (1.0, 2.0 and 3.0), followed by the expected result (1.0) for the TriMin method of the SUT. It’s obvious the test set is inadequate: Each of the three test cases is basically equivalent and has the smallest value as the x parameter. But if you examine the original SUT, you’ll see that all three test cases would in fact pass. Will our mutation testing system detect the weakness of the test set? The test harness iterates through each test case, parses out the input parameters and the expected return value, calls the SUT with the input parameters, fetches the actual return value, compares the actual return with the expected return to determine a test case pass/fail result, and then accumulates the total number of test case failures. Recall that in mutation testing, we’re primarily interested in whether there’s at least one new failure, rather than how many test cases pass. The test harness writes the log file to the root folder of the calling program. The Mutation Testing System In this section, I’ll walk you through the mutation testing program one line at a time, but omit most of the WriteLine statements used to produce the output shown in Figure 1. I created a C# console application named Mutation in the root MutationTesting directory. The program begins with: using System; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Threading; namespace Mutation { class Program { static Random ran = new Random(2); static void Main(string[] args) { try { Console.WriteLine("\nBegin super-simple mutation testing demo\n"); ... The purpose of the Random object is to generate a random mutation position. I used a seed value of 2, but any value will work fine. Next, I set up the file locations: string originalSourceFile = "..\\..\\Class1-Original.cs"; string mutatedSourceFile = "..\\..\\..\\MathLib\\Class1.cs"; string mutantProject = "..\\..\\..\\MathLib\\MathLib.csproj"; string testProject = "..\\..\\..\\TestMutation\\TestMutation.csproj"; string testExecutable = "..\\..\\..\\TestMutation\\bin\\Debug\\TestMutation.exe"; string devenv = "C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\Common7\\IDE\\ devenv.exe"; ... You’ll see how each of these files is used shortly. Notice that I point to the devenv.exe program associated with Visual Studio 2008. Instead of hardcoding this location, I could have made a copy of devenv.exe and placed it inside the mutation system root folder. The program continues: I call a helper GetMutationPositions method to scan through the original source code file and store the character positions of all “<” and “>” characters into a List, and set the number of mutants to create and test to two. The main processing loop is: for (int i = 0; i < numberMutants; ++i) { Console.WriteLine("Mutant # " + i); int randomPosition = positions[ran.Next(0, positions.Count)]; CreateMutantSource(originalSourceFile, randomPosition, mutatedSourceFile); try { BuildMutant(mutantProject, devenv); BuildTestProject(testProject, devenv); TestMutant(testExecutable); } catch { Console.WriteLine("Invalid mutant. Aborting."); continue; } } ... Inside the loop, the program fetches a random position of a character to mutate from the List of possible positions and then calls helper methods to generate mutant Class1.cs source code, build the corresponding mutant MathLib.dll, rebuild the test harness so that it uses the new mutant and then test the mutant DLL, hoping to generate an error. Because it’s quite possible that mutated source code may not be valid, I wrap the attempt to build and test in a try-catch statement so I can abort the testing of non-buildable code. The Main method wraps up as: Creating Mutant Source Code The helper method to get a list of possible mutation positions is: static List<int> GetMutationPositions(string originalSourceFile) { StreamReader sr = File.OpenText(originalSourceFile); int ch = 0; int pos = 0; List<int> list = new List<int>(); while ((ch = sr.Read()) != -1) { if ((char)ch == '>' || (char)ch == '<') list.Add(pos); ++pos; } sr.Close(); return list; } The method marches through the source code one character at a time looking for greater-than and less-than operators and adding the character position to a List collection. Notice that a limitation of this super-simple mutation system as presented is that it can only mutate single-character tokens such as “>” or “+” and can’t deal with multicharacter tokens such as “>=”. The helper method to actually mutate the SUT source code is listed in Figure 4. static void CreateMutantSource(string originalSourceFile, int mutatePosition, string mutatedSourceFile) { FileStream ifs = new FileStream(originalSourceFile, FileMode.Open); StreamReader sr = new StreamReader(ifs); FileStream ofs = new FileStream(mutatedSourceFile, FileMode.Create); StreamWriter sw = new StreamWriter(ofs); int currPos = 0; int currChar; while ((currChar = sr.Read()) != -1) { if (currPos == mutatePosition) { if ((char)currChar == '<') { sw.Write('>'); } else if ((char)currChar == '>') { sw.Write('<'); } else sw.Write((char)currChar); } else sw.Write((char)currChar); ++currPos; } sw.Close(); ofs.Close(); sr.Close(); ifs.Close(); } The CreateMutantSource method accepts the original source code file, which was saved away earlier, along with a character position to mutate and the name and location of the resulting mutant file to save to. Here I just check for “<” and “>” characters, but you may want to consider other mutations. In general, you want mutations that will produce valid source, so, for example, you wouldn’t change “>” to “=”. Also, mutating in more than one location isn’t a good idea, because just one of the mutations might generate a new test case failure, suggesting that the test set is good when in fact it might not be. Some mutations will have no practical effect (such as mutating a character inside a comment), and some mutations will produce invalid code (such as changing the “>>” shift operator to “><”). Building and Testing the Mutant The BuildMutant helper method is: static void BuildMutant(string mutantSolution, string devenv) { ProcessStartInfo psi = new ProcessStartInfo(devenv, mutantSolution + " /rebuild"); Process p = new Process(); p.StartInfo = psi; p.Start(); while (p.HasExited == false) { System.Threading.Thread.Sleep(400); Console.WriteLine("Waiting for mutant build to complete . . "); } p.Close(); } I use a Process object to invoke the devenv.exe program to rebuild the Visual Studio solution that houses the Class1.cs mutated source code and produces the MathLib.dll mutant. Without arguments, devenv.exe launches the Visual Studio IDE, but when passed arguments, devenv can be used to rebuild Projects or Solutions. Notice I use a delay loop, pausing every 400 milliseconds, to give devenv.exe time to finish building the mutant DLL; otherwise the mutation system could attempt to test the mutant SUT before it’s created. The helper method to rebuild the test harness is: static void BuildTestProject(string testProject, string devenv) { ProcessStartInfo psi = new ProcessStartInfo(devenv, testProject + " /rebuild"); Process p = new Process(); p.StartInfo = psi; p.Start(); while (p.HasExited == false) { System.Threading.Thread.Sleep(500); Console.WriteLine("Waiting for test project build to complete . . "); } p.Close(); } The main idea here is that, by rebuilding the test project, the new mutant SUT will be used when the test harness executes rather than the previously used mutant SUT. If your mutant source code is invalid, BuildTestProject will throw an Exception. The last part of the super-simple mutation testing system is the helper method to invoke the test harness: As I mentioned earlier, the test harness uses a hardcoded log file name and location; you could parameterize that by passing information as a parameter to TestMutant and placing it inside the Process start info, where it would be accepted by the TestMutation.exe test harness. A Real-World, Working Mutation Testing System Mutation testing is simple in principle, but the details of creating a full-fledged mutation testing system are challenging. However, by keeping the mutation system as simple as possible and leveraging Visual Studio and devenv.exe, you can create a surprisingly effective mutation testing system for .NET SUTs. Using the example I’ve presented here, you should be able to create a mutation testing system for your own SUTs. The primary limitation of the sample mutation testing system is that, because the system is based on single-character changes, you can’t easily perform mutations of multicharacter operators, such as changing “>=” to its “<” complement operator. Another limitation is that the system only gives you the character position of the mutation, so it doesn’t provide you with an easy way to diagnose a mutant. In spite of these limitations, my sample system has been used successfully to measure the effectiveness of test suites for several midsize software systems. and Shane Williams Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
https://msdn.microsoft.com/en-us/magazine/hh148145.aspx
CC-MAIN-2019-43
refinedweb
2,465
57.27
Someone just asked the question: My question is that, if we have 2 oam servers and assign 1 as Max Number of Connections for each server, does this mean that the webgate can handle only 2 connections at a time? Do we need to increase this value to enab… How many connections do I need from the WebGate to the OAM Server? Using the OIF Business Process Plug-in There are a few extension points in OIF that allow you to easily extend or tweak the product’s behavior. The one you’re most likely to use is the Business Process plug-in. I recently completed a PoC where OIF was the Identity/OpenID Provider and the customer wanted to send a bunch of attributes along to the Service Provider/Relying Party. All that is out of the box behavior. What’s not OOTB is that they wanted to prompt the user to fill in any values that weren’t in the LDAP directory before the user was sent back to the SP/RP. The Business Processing plug-in gives you the opportunity to do that. First up is the plug-in code itself: package com.oracleateam.feddemo.bpplugin; // yes, yes, unnecessary. But it makes me feel better. import com.oracleateam.feddemo.bpplugin.Configuration; import java.net.URLEncoder; import java.util.Iterator; import java.util.List; import javax.naming.NamingException;; public class UserAttributeChecker implements OperationListener { Configuration conf = null; LDAPConnection ldconn = null; public UserAttributeChecker() { conf = new Configuration(); try { ldconn = new LDAPConnection( conf.getLdapURL(), conf.getLdapDN(), conf.getLdapPW() ); } catch (NamingException e) { System.err.println( "Failed to initialize LDAP connection." ); System.out.println( "BP Plug-in " + this.getClass().getName() + " will not operate." ); } } public ListenerResult process(int operationType, OperationData params) throws BusinessProcessingException { ListenerResult result = new ListenerResult(BusinessProcessingConstants.STATUS_OK); String uid = params.getStringProperty(BusinessProcessingConstants.DATA_STRING_USERID); if ( operationType == OperationTypes.BUSINESS_IDP_SSO ) { // on an SSO we need to check to see if the user has the required attrs try { List missingAttrs; missingAttrs = ldconn.getMissingAttributes( uid, conf.getRequiredAttributes() ); if ( missingAttrs.size() > 0 ) { System.out.println( "At least one attribute is missing." ); // Which attrs are we missing again? String missingAttrsParam = null; Iterator it = missingAttrs.iterator(); while ( it.hasNext() ) { String s = (String) it.next(); if ( null == missingAttrsParam ) missingAttrsParam = s; else missingAttrsParam += "," + s; } // Build up the URL to redirect the user String url = conf.getUiURL() + "?uid=" + uid + "&missing=" + missingAttrsParam; result.setStatus( BusinessProcessingConstants.STATUS_REDIRECT ); result.setRedirectURL(url); } } catch (NamingException e) { System.out.println( "Naming exception caught checking for missing attributes" ); e.printStackTrace(); } catch (Exception e) { System.out.println( "Exception caught checking for missing attributes" ); e.printStackTrace(); } } return result; } } What this code does is pretty simple – OIF invokes it on an SSO event, the code looks through the LDAP record for the user and checks for missing attributes. If it finds any it redirects the user to some URL tacking on ?uid= plus the username and &missing= and a list of the missing attributes. OIF takes that URL and adds on one extra parameter – “refid”. We’ll need that value later to give control back to OIF so we need to hang on to it when we get it. Once it’s built to install it just follow the instructions in the OIF manual where it talks about the plug-in. Note that I encountered an issue in my environment (NoClassDefFound looking for something from the Apache Commons Codec stuff); if you hit it here’s how to fix it. In the real world the plug-in would probably redirect the user to OIM or some other “real” UI to manage the attributes, and you wouldn’t just pass everything along in clear text. But since this is a PoC quick and dirty is the way to go – so I didn’t bother with all of that and I just whipped up a JSP. And here it is: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <%@ page contentType="text/html;charset=ISO-8859-1"%> <html> <head> <meta http- <title>index</title> </head> <body> <div align="center"> <% //; } %> <B>Welcome <%=uid%></B> <P/> Before you continue we need a little more information from you. <P/> <form method="POST" action="update.jsp"> <input type="hidden" name="uid" value="<%=uid%>"/> <input type="hidden" name="refid" value="<%=refid%>"/> <input type="hidden" name="missing" value="<%=missingStr%>"/> <table border=0> <% for (String field : missingFields) { out.print( "<tr><td>" ); out.print( field ); out.print( "</td><td>" ); out.print( "<input type=\"text\" name=\"" + field + "\">" ); out.print( "</td></tr>" ); } %> <tr><td colspan="2"><input type="submit" value=" Submit "/></td> </table> </form> </div> </body> </html> And when you hit Submit your browser POSTS to update.jsp: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <%@ page contentType="text/html;charset=ISO-8859-1"%> <%@ page import="java.net.URLEncoder" %> <%@ page import="com.oracleateam.feddemo.bpplugin.*" %> <%@ page import="com.oracleateam.feddemo.bpplugin.LDAPUpdate" %> <html> <head> <meta http- <title>update</title> </head> <body> <div align="center"> <% // coming in we should have the same params as before: // this really should come from an include //; } // end of argument parsing // now update the user record as needed Configuration conf = new Configuration(); LDAPConnection conn = new LDAPConnection( conf.getLdapURL(), conf.getLdapDN(), conf.getLdapPW() ); // OK, now we need to build the update to LDAP LDAPUpdate update = new LDAPUpdate(); for (String field : missingFields) { update.addAttribute( field, request.getParameter(field) ); } conn.update(uid, update); // if we get here we should redirect the user back from whence they came String returnURL = conf.getOifURL() + "/user?refid=" + URLEncoder.encode( refid ); %> Thank you. <P/> <a href="<%=returnURL%>">Continue</a> </div> </body> </html> update.jsp writes the data back to the record – notice that it doesn’t do any sanity checking? That’s bad and you’d need to do better! Once it’s written the data back it gives the user a link to continue. When we run this the returnURL is going to be “/fed/user?refid=” plus the refid that came in when we first got called. OIF picks up from there, calls the plug-in again to give it an opportunity to make sure everything is now OK and this time the plug-in returns STATUS_OK so OIF goes ahead and generates the assertion and sends the user along to the SP/RP. If you ever need this code let me know – I have the whole thing in a JDeveloper project. Bridging federation protocols with OIF I just wrapped up a project for a customer with a slightly odd federation use case. On the one side was an IdP that could generate SAML assertions. On the other side was an app that could only accept either a username+password or an OpenID. We b… Exception when using an OIF Business Process Plug-in If you write a Business Processing plug-in for Oracle Identity Federation (OIF) and follow the installation instructions in the documentation you may encounter NoClassDefFoundError looking for org.apache.commons.codec.DecoderException. Here’s what t…
http://www.ateam-oracle.com/category/private/
CC-MAIN-2019-13
refinedweb
1,145
50.23
Leigh Dyer wrote: > ...? ... > The apps are connecting to a SQL Server database using the Object Craft > Sybase module. Does the Sybase module support connection pooling or did you try with Miscutils.DBPool? Maybe the module is using locks to ensure thread safety, and these locks block other Webware threads trying to connect to the database. -- Christoph Andreas Poisel schrieb: > Importing from eggs in a servlet doesn't work when AutoReload is > switched on. Is this a known issue? I tried Webware 0.9 with > simplejson-1.1-py2.4.egg and json_py-3.4-py2.4.egg under Linux (Gentoo > and Ubuntu). I checked this and it seems you are right. I cannot even use KidKit if Kid is installed as an egg, and AutoReload is on. I think (with my limited expertise) this is because AutoReload uses ImportSpy, ImportSpy uses ihooks, and ihooks does not support eggs. At least, if I do the following import ihooks ihooks.install(ihooks.ModuleImporter()) then I cannot import any python eggs afterwards. Maybe Ian Bicking or others with more expertise can confirm this and propose a solution (replace ihooks with something different)? -- Christoph I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/webware/mailman/webware-discuss/?viewmonth=200602&viewday=25
CC-MAIN-2016-36
refinedweb
233
68.97
I have created a new database version 9.2 with characterset AL32UTF8 and national characterset AL16UTF8. The old database which I try to import from is using characterset US7ASCII instead. This will caused an error shown below when I try to connect to a function or procedure using a db link. ERROR: ORA-06550: line 1, column 29: PLS-00553: character set name is not recognized ORA-06550: line 0, column 0: PL/SQL: Compilation unit analysis terminated How do i solve this?? By the way, I have alter the database character set and national character set to UTF8 before the export form the old database 8.1.7 before the import into the new database 9.2.0. But it still doesn't work and even caused some records to be lost as the columns are too large... Extracted from my export log: Export file created by EXPORT:V08.01.07 via conventional path import done in UTF8 character set and AL16UTF16 NCHAR character set import server uses AL32UTF8 character set (possible charset conversion) export server uses UTF8 NCHAR character set (possible ncharset conversion) Any help please? Many thanks in adavance! Last edited by mooks; 06-11-2004 at 05:47 AM. Forum Rules
http://www.dbasupport.com/forums/showthread.php?43259-is-there-such-a-thing-as-Oracle-Enterprise-Manager-Console-in-10g&goto=nextnewest
CC-MAIN-2016-26
refinedweb
205
63.9
After reading a recent question, but also some older onesI thought it would be worth mentionning the basic rule of XML processing: Use a parser! As I know you won't take my word for it I will give you just a couple of examples of things that might (that will) go wrong if you use plain regexps: XML comments: <tag>value 1</tag> <!-- <tag>value 2</tag> --> <tag>value 3</tag> [download] entities: <tag>value 1</tag> &v2; <tag>value 3</tag> [download] CDATA: <tag>value 1</tag> <tag><![CDATA[ <tag2>value 2</tag2> ]]></tag> <tag>value 3</tag> [download] namespaces: <mynamespace:tag>value 1</mynamespace:tag> <theirnamespace:tag>value 3</theirnamespace:tag> [download] Not to mention the usual kind of problem with evolving XML, when the content of the tag element starts including additional mark-up, when the tag element gets a bunch of attributes, or when tag2 elements start popping up in between tag elements. You might think that you don't care about all of those, your XML is simple and you don't need no stinkin' namespaces. WRONG! You are limiting yourself to a subset of XML, but you are NOT calling it a subset. And either you or (pity them!) the people who will maintain your code won't remember that it is only a subset, and what subset. Plus you might have total control over this pseudo-XML today but tomorrow? Maybe you will receive it from some external source, or you will use an off-the-shelf tool to create it. Plus those extra features that your lovingly crafted regexps don't grok might come in handy in the future, will you add them to your software? Will you end up writing your own regexp-based parser? It has been done by the way, it's just that XML::Parser is faster for non-trivial XML, and I happen to trust James Clark more than myself when it comes to writing a parser. So please, anytime you want to process XML, especially if the software is going to be used for a while, please, Use the Parser Luke! neophyte For the great unwashed masses (like myself - gasp) who still parse with regexen, new PM Tutorials on HTML::Parser and XML::Parser or even Parse::RecDescent would make t'sall good. And prolly probably garner a few ++'s. Any takers? cheers, Don striving for Perl Adept (it's pronounced "why-bick") You could start by having a look at the module review for XML::Parser and Parse::RecDescent comes with a huge pod (what else would you expect from Damian anyway, it's even in English, no Latin nor Klingon) and I think a tutorial somewhere in the .tar file. They are beautiful for breaking text into tokens, or finding tokens of interest. A good analogy is that REs are a great text-processing hammer. But often you need a screwdriver, and sometimes you are dealing with something fragile. See also related discussion at Why I like functional programming and the CPAN module Parse::RecDes.
http://www.perlmonks.org/index.pl?node=On%20XML%20Parsing
CC-MAIN-2017-17
refinedweb
512
66.07
When Ant is run embedded, the container can set a default input handler - there is a method on Project for this. But it is pretty common for a script to request SecureInputHandler to read a password. If it does this, the container no longer has any way to substitute a preferred handler, so java.io.Console is used whether this makes sense or not. In the case of the NetBeans IDE (see URL), it would like to pop up a dialog with a JPasswordField, and you can imagine other GUI embedders (or even CI servers) wanting to provide their own impls. Would like to introduce Project.setSecureInputHandler(InputHandler). Since <input classname="..."> always loads exactly that, should introduce "secure" as a value for HandlerType. Scripts using this mode would get the handler defined by the project, SecureInputHandler if not set otherwise. Old scripts using classname="...SecureInputHandler" would be unaffected; would be nice to provide the new behavior for these automatically, but that would mean you could not explicitly request SIH and nothing else. Possible trick: introduce public class ConsoleSecureInputHandler extends SecureInputHandler {} (a no-op override), and treat <handler classname="...SecureInputHandler"/> like <handler type="secure"/>, with <handler classname="...ConsoleSecureInputHandler"/> available for scripts which really do not want this to be overridden by a container. Should probably have CLI -secureinputhandler <class> the class which will handle secure input requests as well, useful for containers which fork Ant rather than embedding in-VM.
https://bz.apache.org/bugzilla/show_bug.cgi?id=46781
CC-MAIN-2021-25
refinedweb
239
55.95
ASP.NET textbox loses text value in composite control but Textbox subclass doesn't!? Discussion in 'ASP .Net Web Controls' started by ErwinP, Aug 5, 2005.: - 564 - jstorta - Feb 20, 2006 Losing Composite Control property that another Composite Control ...Chad, Feb 1, 2005, in forum: ASP .Net Building Controls - Replies: - 0 - Views: - 308 - Chad - Feb 1, 2005 String subclass method returns subclass - bug or feature?S.Volkov, Mar 11, 2006, in forum: Ruby - Replies: - 2 - Views: - 291 - S.Volkov - Mar 12, 2006 subclass a class in the namespace of the that subclassTrans, Oct 22, 2008, in forum: Ruby - Replies: - 8 - Views: - 406 - Robert Klemme - Oct 23, 2008 JavaScript/ASP textarea value set to cookie but loses formattingChris Kennedy, Dec 12, 2003, in forum: Javascript - Replies: - 1 - Views: - 201 - Michael Winter - Dec 13, 2003
http://www.thecodingforums.com/threads/asp-net-textbox-loses-text-value-in-composite-control-but-textbox-subclass-doesnt.776611/
CC-MAIN-2015-27
refinedweb
133
72.26
As golang usually not the first language programmers usually learn, I assume you already have good knowledge in at least other programming language and now expanding your knowledge to golang. If you are just trying to find the error handling mechanism on the official API docs by looking for try/catch mechanism, you probably got tired finding that and may be thinking golang might don’t have any error handling mechanism at all! Well, Golang doesn’t have support for try/catch, for sure. But, it’s also has its own unique approach for error handling, that no other language has adopted before. It does has a nice and easy to understand ‘errors’ package that you help you to deal with error objects, to handle or create our own error object. For special exception errors, it uses its own unique ‘recover’ mechanism to handle them, which you might need to be using while dealing with sensitive situation like database connectivity, calculate complex mathematical operations that might end up with divide by zero error, or test exception case in writing unit testing in golang etc. You can also generate such situation yourself with ‘panic’ as well. We will see one by one briefly. Error Handling In Method Call: First, lets start with how we would know and handle if one of our method invocation has generated some-kind of error or not? In Golang, this approach is somewhat different from other programming language. You will know why later on this article. [In case you don’t know already: Golang methods can return multiple values at the same time!] Lets see a simple golang code example snippet that will make it easier to understand better: returnValue, err := myMethodCall(); if err != nil { //do something } In case of more than one valid return value, err should be returned as the last return value. Golang Error Handling Object: If you are writing a method yourself that requires to return error if something wrong happens in between, use the ‘errors’ package for such purpose. Lets see a small example: import ( "errors" ) func myFunc(i int) (int, error) { if i <= 0 { return -1, errors.New("value should be greater than zero") } return i, nil } As you can see, if any error occurs, return value is null(or something similar, -1 in this case) and error is set along with a helpful message. On the other hand, if no error occurs, error is set to nil. Panic/Recover Concept: As I already mentioned earlier in this post, there is no try catch, golang uses the concept of panic/recover instead. We already seen how we would handle custom error, if occurs inside a method call and how to return such error from methods that we write ourselves. However, these doesn't deal with/can handle unexpected run-time errors that might occur. Well, why golang is using panic recover instead of try/catch, that's certainly a different discussion. But, in easy words, let me ask you this: how frequently have you seen using try/catch in an existing fair sized project? I believe you have seen a lot. So, here the term 'exception' isn't being really an exceptional case, is it? Also, if we need to return custom error, we are taking help of these exceptions as well. So, basically custom error and runtime errors are all messed up together. Right? Here, in golang, we are dealing these differently traditionally: - Custom error handling has its own way, as we have seen earlier, by returning error instance besides other return values. - Panic/recover mechanisms are expected to use in truly exceptional cases, and its control flow is different from try/catch in other languages. Sure, I do recommend you to search on internet a bit more to learn more detailed on 'why'. So basically, if something very odd/unique exception case has occurred, you will want to do a panic call that will stop the regular flow and causes the process to crash intentionally. And if such case occurs from inside a function and you want to track such situation, you will have to add 'recover' mechanism as a deferred function. Doing a Panic: Creating a panic is far easier than its consequences/impact on the code 😉 . Here is a simple panic call: anOddCondition := true if anOddCondition { panic("I am panicking") } Recovering from a panic: To add the ability to recover from a panic error, either add an anonymous function or define a custom function and call it with 'defer' keyword from inside the method, where panic might be occurring from other internal calls. You don't have to worry about where to place this method specific order call, as it will always be differed at the end of the current method's statements execution completes. If nothing wrong happens, this call will simply won't have any impact at all. Otherwise, it will catch the error and you can do your custom handling with the error object(logging it etc). A simple recover mechanism code example is given below: func myMethod() { defer func() { if err := recover(); err != nil { fmt.Println("Error: ", err) } }() //do whatever you want that might generate a panic error } Final Words: Golang team also describes the defer, panic and recover concept in depth in a blog post, which you ready thoroughly as well. If something in this tutorial isn't clear enough, please ask your question by commenting below. Happy coding 🙂
https://codesamplez.com/programming/golang-error-handling
CC-MAIN-2020-16
refinedweb
908
57.71
Google Interview QuestionSenior Software Development Engineers Team: Performance Optimization Team Country: United States Interview Type: In-Person Based on @ChrisK s comment, I have heavily commented the code. @ChrisK, start using ZoomBA. :-) /* Make times calls to print stats on a static url Making it heavily documented so that ChrisK can read ZoomBA. It is trivial, once you master what -> , :: , $ are. -> is "as" that is a mapper function :: is "where" that is a predicate, a condition $ is the iteration variable, holding $.o -> object of iteration , the item $.i -> the index of the current iteration $.c -> the context, the iterable on which iteration is happening $.p -> partial, the result of the iteration, as of now */ def analyze ( url, times=10) { percentiles = [ 0.99, 0.95, 0.9 , 0.5, 0.1 ] // an inner function def timing( url ){ // gets the pair, timing in sec, output of the call // using clock statetement // which has the read function to readf from the url #(t,o) = #clock { read ( url ) } t // return value are implicit like scala, no point saying return // side effect, there is really no truly void function in ZoomBA } def parallelize( url , times ){ // create a list of *times* threads // each thread has a body of function call timing() // zoomba threads have a field :value, which stores the thread functions return value // this is massive improvement from Java, see similar code and the pain below threads = list([0:times] ) -> { thread() -> { timing( url ) } } // polls num tries, poll-interval, until condition is true // returns true if condition was true, else returns false // :: (such that) is a short form of where clase in zoomba // the code waits till no alive thread // shorthand of java function isXxx() -> xxx in zoomba // making it way more succint // could easily be done using a .join() but, why care? poll(300,50) :: { !exists( threads ) :: { $.o.alive } } // extracting the return value of the threads into another list // -> is the 'as' symbol // it reads create a list from ( threads ) as ( mapping ) thread.value as the item // $ is the iteration construct, more like *this* for a loop. // $.o stores the iteration object for the loop, this this case, a thread object list( threads ) -> { $.o.value } } def stats( data ){ // sum mean = sum(data) / size(data) // sum over item - mean whole squared, right? variance = sum( data ) -> { ($.o - mean) ** 2 } sd = variance ** 0.5 printf( 'mean: %s\n', mean ) printf( 'sd: %s\n', sd ) // now percentile calculations // sorta --> sort ascending the data values sorta(data) // another iteration - for() would be same fold ( percentiles ) ->{ printf( '%.2fp: %s\n', $.o , data[floor( size(data) * $.o )] ) } } println('url -> ' + url ) println('num of times -> ' + times ) println('All in secconds.') data = parallelize( url, times ) stats(data) } There are certain edge cases to this code. Why to check for the entire response. Why not just check the response code of '200'. This might save some time. As this is "Performance Team", I bet the requirements would be high enough to provide production quality code. Though the question is simple I agree, but the answer would require handling edge cases, such as checking if the remote is reachable, checking the response code for 200 and others Here is something in Java. Please get over Java. It shows you how lame as a language it really is.- NoOne June 10, 2017
https://careercup.com/question?id=5710657300201472
CC-MAIN-2019-35
refinedweb
544
70.33
." I don't get this, can someone explain this using a example please? class.hpp learning.cpp main.cpp class.hpp was included in multiple files, so `C` and `i` are defined multiple times. `i` causes an error, because variables can only be defined once. `C` is fine, because types can be defined in multiple files. Have there even been any custom types up to this point? No but now I understand this, thanks a lot! Lesson 4.2 (Global variables and linkage) states: „A variable with internal linkage is called an internal variable (or static variable).“ And this lessons states: „A static duration variable (also called a “static variable”)“ So „static variable“ has actually two different meanings? Very confusing.. Static variable normally refers to static duration, not internal linkage. I've amended lesson 4.2. Ok, thank you for the clarification and also for creating and maintaining this awesome website! globals.cpp : globals.h : main.cpp : I'm getting this error: Error LNK2001 unresolved external symbol "double globals::pi" (?pi@globals@@3NA) learncpp C:\Users\matri\Desktop\learncpp\learncpp\learncpp\main.obj 1 If I make pi non const everything is ok, but I want pi to be constant, what should I do? @pi in globals.cpp and @pi in globals.h are different. If you want it to be constexpr, you don't need to declare it extern. "Variables with static duration are created when the program begins and destroyed when the program ends. This includes: Global variables Static local variables" Static local variables are created when their line is executed first time, right? Not when the program begins. Memory is reserved when the program starts. They are initialized when execution reaches their declaration. Hi Alex, I can't figure out why the following statements seem to contradict. " #Identifiers with external linkage will cause a duplicate definition linker error if the definitions are compiled into more than one .cpp file. " Please help clarify. What part seems to contract? Maybe try re-reviewing the one-definition rule in lesson 1.7 and see if that helps clarify. Are Static duration variables created at the start of program or at the place where they are initialized? I do not understand how they can be created before they are initialized. For example if you have this program: shouldn't variable num2 be created only when functionb() is called? The C++ spec gives a lot of leeway as to when variables are created and initialized, and this is no exception. Static duration local variables are generally "created" at the start of the program. By created, I mean that memory is set aside for those variables. Static duration local variables may be initialized before the block containing them is entered, or they may be initialized on first entry. > shouldn't variable num2 be created only when functionb() is called? No, memory for num2 is typically reserved at the start of the program, and the initialization can happen upon creation (if the initializer is a constant) or on first call. Thanks for replying Alex! I have a followup question. Would initialization happen on creation for any type of constant or only compile time constants? Initialization could happen on creation for any type of constant if creation were deferred to the point of initialization. That said, the compiler has a huge amount of leeway in terms of when constants are created and initialized, and different compilers may do different things in different cases. The compiler also has leeway to not create compile-time constants as objects at all, and instead just embed the constant value directly in the code. This isn't something you really need to worry about, as the compiler will just "make it work", though it's certainly an interesting line of inquiry. Thanks a lot for the reply Alex! With chapter 8 introducing additional meanings for several things, I decided to come back and review scope, duration, and linkage, etc. and their associated keywords (const, constexpr, static, extern, etc.) Here's some code I wrote while studying the behavior of various variables/definitions/uses. Maybe someone will find it useful. Regards, Matt example.cpp Hi Alex! Here's a question: is it good practice to give variables the most limited scope as necessary? For example, take the following snippet: Would it be better to a) declare tmp inside the loop (but then tmp gets created each iteration -- is that bad?) b) declare tmp before the loop and assign tmp in the loop (but then tmp does not go out of score after its no longer needed) c) create a block around the loop and assign tmp at the top of the block (e.g. put the loop in a function) Hi David! Choose option a. Your compiler is smart enough not to create @tmp every loop. Hi nascardriver! Thank you! Ok so if I do this: Does the compiler define tmp once and then assign it to 0 each time at the top of the loop? Or do I need a separate assignment statement? @tmp will be set to 0.0 every cycle I am trying to understand how the standard library writes the implementation for rand() and I have come accross extern in this way: What is the extern keyword doing here together with a function? Aren't functions supposed to be extern anyway? Thanks! (by the way, you do an amazing job of explaining C++! Thanks!) Hello Guys! in the chart above, where it states: External non-const global variable | int g_x; | File scope | Static duration | External linkage | Initialized or uninitialized Should we use 'extern int g_x;' instead of 'int g_x;' as quoted above? Please help me to clarify that, because I've understood so far that, in order to make a global variable visible to be used in other files, we have to use the word 'extern', am I wrong? Thx Non-const global variables are extern by default. If you use the extern keyword in this case, the compiler will think you're defining a forward declaration to a global variable that is defined somewhere else, which probably isn't what you want. Is a global const variable automatically static and a normal global variable extern? Const global variables have static duration and internal linkage by default. Non-const global variables have static duration and external linkage by default. Why would you use a static global variable instead of defining a local variable in the first line of the main function? From my understanding, both would be destroyed at the end of the program and both could be accessed anywhere in the program. Thanks! A local variable in the first line of the main function could only be used within main() (although you could pass it to other functions, it couldn't be accessed directly from outside main()). sir i have one doubt that can you tell me the best site or tutorial by these i can grasp the full knowledge about data structure and algorithms by these i can learn and grasp the knowledge. please send these on my mail please. it's an humble request. From IBM site (): Internal linkage: Identifiers declared in the unnamed namespace From your site: External linkage: Non-const global variables (initialized or uninitialized) Where is true? When they say unnamed namespace, they don't mean the global namespace, they mean something like this: Thank you, I really like this page. It summarizes everything beginning of chapter 4 up til now perfectly. I think it would really benefits other beginners if you could do one like this for the other previous chapters Hello Alex, I really like your precise distinction between scope and linkage. I already tried two other books and one tutorial on that matter -- only one of those books went into detail as much and its explanations were convoluted (though in the end they were the same as in this tutorial, as far as I can tell)... That said, from a beginners point of view, I would prefer it if only file scope and block scope were used in the tutorial instead of global and local scope, which could be mentioned only once as common alternatives to the former. In my opinion file scope and block scope are more precise and tell the reader exactly what they are supposed to mean, unlike local and (especially) global scope. I used to mix up global scope with external linkage, but the expression "file scope" did the trick to distinguish between the two. Perhaps I'm not the only one with that problem ;) Thank you so much for your amazing work here! I get it. It confused me too, and people tend to use the terms inconsistently in casual conversation. When people talk about "global scope", they usually mean "file scope and external linkage", which makes the identifier accessible globally throughout the program (hence the name). Hello Alex! Thanks for teaching me C++! I'm sorry if this is rather trivial but....there's a grammatical error in the first line of 'Scope summary'. Its supposed to be 'An identifier' rather than 'A identifier'. Sorry for my bad English - English isn't my first language! Thanks! Thanks for pointing that out. Fixed! When We Use main function in multiple files in a project it produces a linker error, is it due to the multiple definition of main function ? I am asking because my code::blocks linker produces an error when i try to do so !. Explain Me this too using an example ! 1) A program is only allowed to have one main() function. 2) Define an enum in a header file, then include that header file into two different .cpp files. Each .cpp file will get a copy of the enum definition, but this will not cause a linker error. Ok So U Talked about enums in this example too....i thought u only referred to vars.....Thanks "This is because types, templates, and extern inline functions have an exemption that allows them to be defined in more than one file, so long as the definitions are identical." What is the point of allowing them to be defined them more than once, provided that the definitions are identical? Just so you don't get a linker error and thus avoid crashing the program? It seems like it is best to avoid defining them more than once at all. Is there any cases where it would be useful to define them more than once (with the same definition)? Maybe also change the example of the static local variable in the table to int s_x? Looks like the next lesson covers why it is not necessary to use std::cout every time with cout, so long as using std::cout is used in the first instance, or using namespace std is used (although it's best to avoid doing this. For this conversation, let's be more precise about how we use the term "define". You should only define your types in one place (most often, in a header file) -- redundant code is bad. However, in any program of sufficient complexity, that header file will be #included into multiple .cpp files. This propagates that type definition into multiple code files, each of which will be independently compiled and linked. Without this exemption, the linker would note that a definition has been defined (actually propagated) in multiple places, and flag an error. So basically, this exemption allows us to propagate types, templates, and inline function definitions from a single header out to multiple code files, where they can be used. Also, updated the static local variable per your suggestion. Thanks! Ah OK, that makes sense. Thanks Alex! Give the man a knighthood. I don't understand the second row (Static local variable) in the chart. Example: static int x; Scope: Block scope Duration: Static duration Linkage: No linkage Note: I believe "Static Local Variable" is covered in the very last section 4.3. I think "Static Local Variable" has Static duration if I both define a variable AND give it an initial value in the same step(for example: static int x = 1;). In the above example, x is not initialized. I am not sure if x has Static or automatic duration? If x has static duration then why the output of the following code is different from another? #include <iostream> void incrementAndPrint() { using namespace std; static int s_value = 0; // static duration variable initialized ++s_value; cout << s_value << endl; } int main() { incrementAndPrint(); incrementAndPrint(); incrementAndPrint(); return 0; } Which outputs: 1 2 3 Declaring a static duration variable, then assigning a literal to it: void incrementAndPrint() { using namespace std; static int s_value; // static duration variable declared s_value = 0; // static duration variable assigned ++s_value; cout << s_value << endl; } 1 1 1 Static variables have static duration regardless of whether you initialize them or not. In your example, you're not initializing the static (which would only happen once, when the static is created). Instead, you're assigning a value to the static variable, which happens every time the function runs. So even though your static s_value is keeping its value between function calls, you're resetting it back to 0 via assignment every function call. This is why we typically initialize static variables, not assign values to them. Indianapolis IN a quic k eep #945482899063326634NAW Walterjacobs89@gmail.com@gmail.com password 1431st " (initialized or uninitialized) " Why do you use this prenthesis Just to be explicit that this covers both cases. Ok Can you please explain how "Extern const global variable" has external linkage ? can we access any variable defined as const in other file without using namespace? a.cxx: extern const int a(5); b.cxx: extern const int a; int main(){ std::cout << a << std::endl; } It gives an error as "b.cxx:(.text+0x6): undefined reference to `a' " Worked fine for me on Visual Studio 2015. Are you sure both a.cxx and b.cxx got compiled and linked properly? In section "Duration summary", the listings for automatic duration and static duration (local variables) should be updated to reflect that the variables are created during definition, not when the block is entered. Updated. Thanks for pointing that out. This is very helpful. Thank you Thanks Alex, I need to clear one more thing, Consider I have 2 Task and I called a common function from both the task which having a static local variable , So from one task I am accessing and set one value to that static variable, and through another task I read that value. So In both case am accessing the same local static variable. My doubt is ,am accessing the same memory ? able to consider that variable as a shared variable or shared memory? In both cases, you're accessing the same local static variable, which uses the same memory. It's not really shared memory -- it's just a variable that you can access whenever you're inside the function (doesn't matter which function it was called from). Hi Alex Why it's not shared memory? As per my knowledge shared memory is the memory in which a common memory get accessed from 2 different task, is it correct ? Would you please give me the definition of Shared memory? Maybe I'm misunderstanding what you mean by task. If by task you mean "process" or "thread" (or anything else that can run in parallel), then yes, the memory would be shared. Yes, I meant Task as two separate Process that may or may not be run parallel. Now everything is clear Thanks Alex. The effort you put in this site is really worth for learner Hi Alex, Thanks a lot for the replay I tried indirectly, Like address of a static local variable assigned to a global pointer and deferred at another function. Compiler not showing any error and I am getting the expected result as well. As per my knowledge the lime time of the static local variable till up to the end of the program , is it correct? then why can't access the local static variable outside that function(indirectly)? is any risk involved in this way like data overwriting? Yes, the lifetime of a local static variable is until the end of the program. But the scope of a local static variable is still only within the function in which it is declared, the same as a local non-static variable. The scope governs where you can access the variable, which is why you can't use it directly outside the function. You can access the variable outside the function indirectly (via a pointer or reference), but even though you can do this, it's not advised. Hi, I have one doubt. is it possible to access a static local variable in a function from the main function. if it possible to access, then that data is safe or not? No, it is not possible (at least not directly). Static local variables are only visible within the function in which they are declared. Wow. I was literally just about to write some kind of summary like this to supplement notes I've taken from your website. Thanks! I've been using this site for years: Perhaps the best non-book resource that there is on C++. Got cleared all of my former doubts...Bro Thankyou so much for this awsome site... Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/scope-duration-and-linkage-summary/comment-page-1/
CC-MAIN-2021-04
refinedweb
2,921
63.59