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
Example code streaming RPC To test client-side logic without the overhead of connecting to a real server. Mocking enables users to write light-weight unit tests to check functionalities on client-side without invoking RPC calls to a server. We use Gomock to mock the client interface (in the generated code) and programmatically set its methods to expect and return pre-determined values. This enables users to write tests around the client logic and use this mocked stub while making RPC calls. Documentation on Gomock can be found here. A quick reading of the documentation should enable users to follow the code below. Consider a gRPC service based on following proto file: //helloworld.proto package helloworld; message HelloRequest { string name = 1; } message HelloReply { string name = 1; } service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } The generated file helloworld.pb.go will have a client interface for each service defined in the proto file. This interface will have methods corresponding to each rpc inside that service. type GreeterClient interface { SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) } The generated code also contains a struct that implements this interface. type greeterClient struct { cc *grpc.ClientConn } func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error){ // ... // gRPC specific code here // ... } Along with this the generated code has a method to create an instance of this struct. func NewGreeterClient(cc *grpc.ClientConn) GreeterClient The user code uses this function to create an instance of the struct greeterClient which then can be used to make rpc calls to the server. We will mock this interface GreeterClient and use an instance of that mock to make rpc calls. These calls instead of going to server will return pre-determined values. To create a mock we’ll use mockgen. From the directory examples/helloworld/ run mockgen google.golang.org/grpc/examples/helloworld/helloworld GreeterClient > mock_helloworld/hw_mock.go Notice that in the above command we specify GreeterClient as the interface to be mocked. The user test code can import the package generated by mockgen along with library package gomock to write unit tests around client-side logic. import "github.com/golang/mock/gomock" import hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld" An instance of the mocked interface can be created as: mockGreeterClient := hwmock.NewMockGreeterClient(ctrl) This mocked object can be programmed to expect calls to its methods and return pre-determined values. For instance, we can program mockGreeterClient to expect a call to its method SayHello and return a HelloReply with message “Mocked RPC”. mockGreeterClient.EXPECT().SayHello( gomock.Any(), // expect any value for first parameter gomock.Any(), // expect any value for second parameter ).Return(&helloworld.HelloReply{Message: “Mocked RPC”}, nil) gomock.Any() indicates that the parameter can have any value or type. We can indicate specific values for built-in types with gomock.Eq(). However, if the test code needs to specify the parameter to have a proto message type, we can replace gomock.Any() with an instance of a struct that implements gomock.Matcher interface. type rpcMsg struct { msg proto.Message } func (r *rpcMsg) Matches(msg interface{}) bool { m, ok := msg.(proto.Message) if !ok { return false } return proto.Equal(m, r.msg) } func (r *rpcMsg) String() string { return fmt.Sprintf("is %s", r.msg) } ... req := &helloworld.HelloRequest{Name: "unit_test"} mockGreeterClient.EXPECT().SayHello( gomock.Any(), &rpcMsg{msg: req}, ).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil) For our example we consider the case of bi-directional streaming RPCs. Concretely, we'll write a test for RouteChat function from the route guide example to demonstrate how to write mocks for streams. RouteChat is a bi-directional streaming RPC, which means calling RouteChat returns a stream that can Send and Recv messages to and from the server, respectively. We‘ll start by creating a mock of this stream interface returned by RouteChat and then we’ll mock the client interface and set expectation on the method RouteChat to return our mocked stream. Like before we'll use mockgen. From the examples/route_guide directory run: mockgen google.golang.org/grpc/examples/route_guide/routeguide RouteGuideClient,RouteGuide_RouteChatClient > mock_route_guide/rg_mock.go Notice that we are mocking both client( RouteGuideClient) and stream( RouteGuide_RouteChatClient) interfaces here. This will create a file rg_mock.go under directory mock_route_guide. This file contins all the mocking code we need to write our test. In our test code, like before, we import the this mocking code along with the generated code import ( rgmock "google.golang.org/grpc/examples/route_guide/mock_routeguide" rgpb "google.golang.org/grpc/examples/route_guide/routeguide" ) Now conside a test that takes the RouteGuide client object as a parameter, makes a RouteChat rpc call and sends a message on the resulting stream. Furthermore, this test expects to see the same message to be received on the stream. var msg = ... // Creates a RouteChat call and sends msg on it. // Checks if the received message was equal to msg. func testRouteChat(client rgb.RouteChatClient) error{ ... } We can inject our mock in here by simply passing it as an argument to the method. Creating mock for stream interface: stream := rgmock.NewMockRouteGuide_RouteChatClient(ctrl) } Setting Expectations: stream.EXPECT().Send(gomock.Any()).Return(nil) stream.EXPECT().Recv().Return(msg, nil) Creating mock for client interface: rgclient := rgmock.NewMockRouteGuideClient(ctrl) Setting Expectations: rgclient.EXPECT().RouteChat(gomock.Any()).Return(stream, nil)
https://fuchsia.googlesource.com/third_party/grpc/grpc-go/+/refs/heads/upstream/v1.13.x/Documentation/gomock-example.md
CC-MAIN-2020-29
refinedweb
882
51.85
I am trying to create a program to calculate the Fantasy performances of my players, but I am comming across some problems. Here is my Code so far. The bolded portion gives me the error "no matching function to call RunningBack::GetRush(int)"The bolded portion gives me the error "no matching function to call RunningBack::GetRush(int)"Code:#include <iostream> using namespace std; class RunningBack { public: int GetRush(int); void SetRush(int rush); private: int itsRush; }; int RunningBack::GetRush(int rush) { cin >> rush; return itsRush; } void RunningBack::SetRush(int rush) { itsRush = rush; } int main() { RunningBack Back1; cout<< "Back number 1 ran for " ; cout << Back1.GetRush() << " yards today\n"; cin.get(); return 0; } I can't get it to display the yards that you input. Also how do I convert these yards to points. The points work like this: for every 20 yards you get 1 point. So if the user inputs 97 it should round off to 4 points.
http://cboard.cprogramming.com/cplusplus-programming/83382-fantasy-calculator.html
CC-MAIN-2014-35
refinedweb
160
70.23
Is This Content Helpful? How can we make this better? Please provide as much detail as possible. Contact our Support Team Why must arcpy.sa functions be assigned to a variable? The arcpy.sa functions are temporary, therefore, the arcpy.sa function must be assigned to a variable. Otherwise, the output does not persist, and is unusable in scripts. A variable holds references to data. In this example, the raster object created with an arcpy.sa function is stored in a variable named Solar. Code: import arcpy; from arcpy.sa import *; arcpy.CheckoutExtension ("Spatial"); #Code used to check the extension in ArcMap Solar = arcpy.sa.AreaSolarRadiation (inRaster, latitude, time); # the code segment uses the arcpy.sa
https://support.esri.com/en/technical-article/000012410
CC-MAIN-2019-35
refinedweb
116
55.81
If you happened to land on this page and missed PART ONE, I would advise you go back and read that section first. You may get lost coming in half way through the story. This is what you'll find in part one. - Downloading and setting up the Android SDK - Downloading the Processing IDE - Setting up and preparing the Android device - Running through a couple of Processing/Android sketches on an Andoid phone. ToastMaster - the master of all Toasts I will now introduce you to Toast. What does "Toast" have to do with programming ? Toast is used by Android to quietly display little messages on the screen. Have a look here for a a quick introduction to Toast, otherwise have a look at the Android Developers Toast information. I will be creating my own method that relies on Toast to make the process of displaying messages easier. I have named this method: "ToastMaster". A word of warning. Calling ToastMaster from within setup() will cause errors in the DiscoverBluetooth sketch (further down this page). This will not happen in every sketch, but the Discoverbluetooth sketch has subActivities which may cause some sort of conflict.. I did warn you. Here is a quick look at my ToastMaster method (no need to compile this code): Here is a breakdown of what this is doing: - Toast.makeText() - is used to construct the message to be displayed. - getApplicationContext() - gets a handle on the Application - textToDisplay - is obvious, this is the text you want to display. - Toast.LENGTH_LONG - is how long you want the message to displayed for. (or LENGTH_SHORT) - setGravity() - sets the message position on the screen, in this case I have chosen to center the text. - show() - is used to actually show the message. Broadcast Receivers : Looking out for Bluetooth devices To listen/look out for any Bluetooth devices that are within range, we need to create and register a Broadcast receiver. When registering a BroadcastReceiver, you will need to tell the program what it is you are looking / listening out for. In our case we want to listen out for occasions whereby a Bluetooth device is FOUND. This is represented by: - BluetoothDevice.ACTION_FOUND - this is sent or broadcast when a Bluetooth device is found (when in discovery mode). Here are the relevant components: Discovering Bluetooth devices: putting it all together You will notice that in the following sketch, we have to import a whole lot more. Which is why I have tried to break it down into bite size chunks, to help you digest it all. Now we will put it all together into a sketch which will - ask to turn Bluetooth ON if it happens to be disabled. - If you don't turn on Bluetooth, it will tell you that you need to turn it on. - If you turn on bluetooth (or if it was already on), it will try to discover any bluetooth devices in range. These devices need to be made "discoverable" before running this sketch. - If the phone finds a bluetooth device, it will display the name of the device and will change the background screen colour to GREEN. Upgrading the Broadcast Receiver : More Device info Ok, we have the device name. But what other information can we collect from the device? You can call - intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); - .getAddress() = Returns the hardware address of the BluetoothDevice. eg. "00:11:22:AA:BB:CC" - .getBondState() = Returns an integer which describes the BondState of the BluetoothDevice - BOND_NONE = 10 - BOND_BONDING = 11 - BOND_BONDED = 12 If you replace the old version of myOwnBroadcastReceiver with this one, you will know a little bit more about the devices discovered. Connecting to the Bluetooth Device: While we now have more information about the Bluetooth device, we don't really need it, and we will get rid of it by the end of the tutorial, however we will keep it here for the time being. In the next updated sketch we will be making a connection to the discovered device, and turning the background purple when the connection is made. In order to do this we will need to - Create a boolean variable to hold the connection status - Create and register a new BroadcastReceiver to notify us when a connection broadcast action has been received. - Create a new thread to handle the connection - Change the background screen colour when a successful connection has been made - boolean BTisConnected=false; Next we will create and register a new BroadcastReceiver, it is created using this: - BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver(); action with the BroadcastReceiver in the following way - registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED)); - String action=intent.getAction(); Now that we can be notified about the connection made to the Bluetooth Device, lets go through the code required to make the connection. We will only connect if we have actually discovered a device, so we will put this code within the FOUND section of myOwnBroadcastReceiver. We use the discoveredDeviceName variable to specifically target the Bluetooth device we wish to connect to. We then unregister the myDiscoverer BroadcastReceiver because we are going to stop discovering before we connect to the Bluetooth Device, plus if you don't, it will generate an error. We then pass our discovered device to a new Thread to connect to that device in the background. The class used to handle the connection is the "ConnectToBluetooth" class as displayed below: We will cancelDiscovery() on the bluetooth Adapter to prevent a slow connection. Also we will need to use a specific UUID as per below: - private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); Before you can connect to the Bluetooth shield you need to use the UUID to create a BluetoothSocket. - mySocket = btShield.createRfcommSocketToServiceRecord(uuid); - mySocket.connect(); The major structure of this code was made possible using the following site: And the following sites were also useful in getting some of the information I needed: While I have described all the major components required to connect to the Bluetooth Device, I will now put it all together in a new and updated version of the "DiscoverBluetooth" Android/Processing sketch and call it "ConnectBluetooth". There is some additional code in this sketch which I did not specifically go through, for example, the code used to turn the background to purple in the draw() method. Look out for that one. Anyway, read through the following code, and make sure that you understand what each section is doing. Android/Processing Sketch 5: ConnectBluetooth The Arduino Sketch Most of the Android/Processing code used so far has depended on a Bluetooth Device being discoverable. Our ultimate aim it to connect to a Bluetooth Shield on an Arduino UNO or compatible board such as the Freetronics Eleven. The following sketch was essentially taken from one of my previous posts (here), however, I have stripped it down to the bear essentials so that it will only be discoverable, and will not send or receive data. I will provide this functionality later. I just wanted to show you the essential bits to establish the connection to the Shield. ARDUINO Sketch 1: Bluetooth Pair and Connect Please make sure to setup the Bluetooth jumpers as per the picture below, otherwise you will not have much luck with the sketch above. Well that brings us to the end of part TWO. PART THREE In part three we will attempt to actually send some data from the Android phone to the Arduino via Bluetooth, and vice versa. This will be when the real fun starts. or GO BACK Click on the link if you missed PART ONE Hi man! First of all, congratulation for your blog! Secondly, sorry for my english, but i'm french :) I'm following your tutorial, it learn me a lot. I'm at the part 2, but i'm stuck. About "to know more about material" (name, MAC adresse etc...) At this point, when I compile, Android apps get's automatically closed... Hi Ginizi Have a look at part three of the tutorial. I explain briefly how to debug your code using adb.exe. Find this program on your hard drive and then create a shortcut to this adb.exe program on your desktop. Right click the newly created shortcut and select properties. Change the target to "c:\......\Android\android-sdk\platform-tools\adb.exe" logcat *:E. Once you get your shortcut working. You can doubleclick on the shortcut immediately after getting an Error from running your Android/Processing program. This may help identify where the program is failing Hi Scott, thanks for your answer, I will check soon as possible. I'm very impressive about your work, really. I want know, how old are you, what is your studies's level? You told "Basic Arduino", I think it's not basic at all... To understand all you mean, we need know "C", JAVA and to finish some basics of android. I work actually on a project, a robotic turret, i create an App on my computer that controls. I use processing IDE, and it work great! Recently, I thought about migrate Apps on android to control it with my phone with bluetooth. I was fall on your blog yesterday. In real, I just want send some datas on my arduino to control my turret, is for you the good way to follow? Thanks for the advice and good information, very specific in your instruction. I have another question about that, what its the way if I want to use in a device with Android 2.3, because we try and doesnt sync, just with the ver 4.0 All my examples have worked with Android v2.3.4 on my Samsung Galaxy SII. So not sure why you are not getting connectivity. See if you can successfully connect using this tutorial (yes/no), and then come back to this one and identify using the methods I described for Ginizi (above), where the program is going wrong for you. Regards Scott Friend thanks for your help, the connection with Bluetooth SPP app is successful, I see that not every app has no connection, I see that sending data from my pc and get my smarthphone, but I can not do otherwise, appears sent but on the screen of my pc does not show the data sent from the smartphone, which I can do? my smarthphones is SONY XPERIA PLAY whit android 2.3.4 Hi LUIS, Which specific sketch are you having problems with? And did you get any of the other sketches to work as expected? This tutorial is progressive so it will help to know where it started to go wrong for you. Also what kind of Arduino board/Bluetooth shield are you using? It sounds strange that you can send data from the Arduino to the Android device but not the other way around. Scott Hi; thanks a lot about your excellent tutorial, I'm trying to make my own home automation in my house using Android.. when trying to make test sketch 5 received" error from inside the android tools,check the console." taskdef class com.android.ant.setuptask cannt be found note: my phone samsung galaxy y pro Hi Khalil, Was sketch 5 the first sketch you tried to run, or have you started from the beginning? Which version of ADK are you using? I have also heard that sometimes the location of the JAVA classpath may cause some issues, but not 100% sure. And have you tried the troubleshooting tips that I provided for Ginizi (above) ? And make sure that you are not trying to do this in the Emulator, because the Emulator does not have Bluetooth. Scott Scott C, Thank you very much from this tutorial, this is very helpful! I just want to verify some things. I noticed something, could you please elaborate on this. The thing is, I noticed that when you started running the sketch when your bluetooth was off, the sketch will request that you turn it on. The problem is upon turning on or pressing yes, nothing happened. It doesn't seem to discover any device, but when I close the sketch and run it again (not turning the bluetooth back off), it does discover other devices. This is fine though technically, I could just do that again, but I feel like cheating that way. I tried to gawk for a second, then I tried putting the registerReceiver() and bluetooth.startDiscovery() inside the if(resultCode==RESULT_OK) clause, and it does remedied my concern. I just want to ask, after calling the overridden method onActivityResult() when does it continue execution? does it continue on the point where startForActivity() method finished? Or does it start running setup again? Or it starts running the draw() method? according to the Activity Life Cycle on the android developers documentation, activities are being stacked on top of another when a new activity was called. when a new activity is called, the recent activity prior to new activity will be stopped (or paused? it does also say on the documentation that if the new activity don't occupy the whole screen, it just pauses, like what the request for bluetooth is doing, Im guessing in this particular situation, paused?) then the onActivityResult() will be executed when that foreground activity closes. When does it return execution? Could you correct me if i am wrong? I'm kind of new to this android and reading documentations, massive documentations. Thank you, I just can't sleep without knowing, I may doubt myself in the future if I just continued this without my questions being answered. Thank you very much. More power. Sorry for the long post. yev Hi Yev - sorry for the delayed reply. Hope you didn't lose too much sleep in the mean-time. I am new to this android/arduino thing aswell, and I think this question is best put to the forums... I don't enough time at the moment - and I don't want you to lose more sleep. Really sorry - but when I get more time - I might come back to your question and see if I can provide you with an answer. Good luck Hey yev, are you also working on the android <-> BLE project? I got some problems here... I am trying to build an Android App(4.3) that can communicate with UNO+BLE Shield via bluetooth. A demo of UNO+BLE <=> IOS App is officially provided (). The code on UNO+BLE also provided on that page. Yet I am trapped in searching device. My app can discover BT from tablet or other phones. But it cant find UNO+BLE. I tried your arduino sketch too(). But still doesnt work...I'm a little bit confused now. I don't really understand how you setup bluetooth on BLE in your sketch1. It seems you use the SoftwareSerial file. Yet does the serial refer to the com with PC via USB cable? How does it relate to the bt on BLE? My Email is sctracy03@gmail.com......Really need your help here. Hi, i think this tutorial is brilliant and is the best i come across so far for arduino <> andriod. I have followed all the tutorial and attempted all the sketches and have had no problems until sketch 5 (connect bluetooth) where i got a "application stopped unexpectedly" error on the android device and the following output on the processing console when trying it in the emulator: FATAL EXCEPTION: Animation Thread java.lang.NullPointerException at processing.test.discoverbluetooth3.DiscoverBluetooth3.setup(DiscoverBluetooth3.java:94) at processing.core.PApplet.handleDraw(Unknown Source) at processing.core.PGraphicsAndroid2D.requestDraw(Unknown Source) at processing.core.PApplet.run(Unknown Source) at java.lang.Thread.run(Thread.java:1019) smartphone is huawei X3 with android 2.3.3 bluetooth shield is same as that in tutorial Any help is much appreciated. Cheers, Richard. Hi Richard, not sure how you managed to get so far in the emulator. Last time I looked, the emulator did not support Bluetooth at all. These projects should be run on the Bluetooth device. By Bluetooth device I meant to say, android phone. Hi Scott, Yes i run them on the android phone and the initial ones all worked until sketch 5 so i then ran it in the emulator becos when i do that i get error message in the console of the processing IDE. Anyway do you have any idea what the error relates to? Any help is much appreciated. Cheers, Richard. Hi Richard, You cannot use the emulator to debug your Bluetooth issues because the emulator will generate errors that are not applicable to your phone. The emulator does not support Bluetooth. Having said that, there are a couple of ways to hunt down the problem. You can use logcat which is described in Bluetooth tutorial 3, or you can comment out sections of code to see if that restores functionality. The error you posted is pointing to setup. May be worth investigating your variables in there. I also made a warning about Toastmaster in this article. Make sure you read about that too. Hope that helps. Will this software run on a Nexus7 tablet? Not sure - never tried - only blogged about my experience with a Samsung as described. Running beautifully on my Nexus 7. Great tutorial and well documented. Had been using Eclipse but Processing 2.0 is so much easier. Tried 2.1 but had Java compile errors. Thanks for the fine presentation. Great to hear thanks +stan what is cli(); error ? I don't know ?? It's "Clear Interrupts". An AVR GCC command to disable global interrupts. Thanks Michael. You learn something new every day. Very much appreciated. hi men . I need your help, look I get this error. the method run() of type connectTobluetooth must override a superclass method Did you use the @Override statement ? Did you copy this tutorial as above ? I get the same error when attempting to use the @Override statement. It appears to be a java compiler level issue (1.5 vs 1.6?) but I haven't figured out how to fix it yet. Same with me. So close... All the other code samples worked up to this point and now I'm stuck with " run() of type connectTobluetooth must override a superclass method" Does anyone have any pointers? Are you all using the Processing IDE ? Version ? Also check Capitalization consistency throughout your code. My code has this : ConnectToBluetooth Your error has this: connectTobluetooth So I am guessing you are either adapting my code, or re-typing ??? Make sure your variables are consistent throughout your code. As there are now a few of you who have the same issue. It may be worth asking for help in the Processing forums. They have a section dedicated to Android programming: Feel free to come back a report the solution (for any others that may fall into the same boat). Hi,I've solved the problem simply removing the @Override statement... This is a great tutorial that explains things well. I have something to add about the UUID. The UUID is the unique identifier that the android app will use to tell the HC-05/06 what service it's performing. In the case of the HC-05/06 it need to be a "Serial Port Profile" which is identified by the UUID's second nibble being "1101". So if you get the standards base UUID. "00000000-0000-1000-8000-00805F9B34FB" and insert your service identifier so the HC-05/06 will let you pair. You get your tutorials basic identifier, the SPP UUID "00001101-0000-1000-8000-00805F9B34FB" Thanks Michael, Do you know if this UUID number can be changed in any way? Or does it have to be that specific code described above ? Short answer: I don't think it can be changed. Long answer: From my limited understanding the UUID is to uniquely identify APPLICATIONS not devices. So for the SPP I would say it can't be changed as this is the unique UUID to specify that you want to use the serial port profile. The reason UUID generators exist is so you can generate your own unique UUID for your own unique application that doesn't currently exist. To put it simply It's a unique identifier for the syntax of your communication. You can define your own UUID just like making up your own language or use one that already exists to speak to all devices that speak that same language. Hence changing the UUID would change the name of your language even if the syntax is technically the same and so the device would reject your connection. Hello Scott or Anyone. I am getting the following error after I copied in your final Android sketch. public class ConnectToBluetooth implements Runnable{ ^^^^^^^^^^^^^^^^^^ The type ConnectBlueTooth.ConnectToBluetooth must implement the inherited abstract method Runnable.run() I am just starting to learn Android programming (actually I know nothing about it except for what I have learned here, and also I am learning the Arduino UNO at the same time. Any help with the error would be wonderful, Thank you, Steve Hi Steve, It appears that something has broken with a software version upgrade. A few people have reported this problem. As suggested in previous comments, it might be worth asking for help in the forums until I can work out where the problem exists. Also, if you manage to figure it out, please let me know. This tutorial works best with Processing version 2.0 Higher versions seems to generate errors. Hello. I am new to this stuff. Great tutorial by the way. I keep getting this error: import java.io.InputStream; ^^^^^^^^^^^^^^^^^^^ The import java.io.InputStream is never used ---------- I googled, but couldn't find clear solution. It's probably really simple, but like I said, I'm new. Thanks! Just remove that line from the code. Hey Scott, First thanks for a great tutorial. My Sketch 5 does'nt work, though I hav tried the different things you have answered the others in there comments. The adb says "E/Parcel < 378>: Reading a NULL string not supported here." Hi Thor, I am not sure why there would be a NULL string error. Perhaps you will need to systematically comment out various sections of the code to see when the error disappears. At least then you can focus your attention on the problem area. Hi all, Thanks to Scott for a great tutorial. I'm having some trouble with Sketch 4. The reason for this trouble is that I'm running Processing 3, API 15. Can't set the target to API 10. I'm getting compile errors on lines 57 and 93 stating: The function "registerRevceiver(BroadcastReceiver, IntentFilter)" does not exist The function "getApplicationContext()" does not exist Does anyone have any ideas as to how to get this code example to work with Processing 3 for API 15? I suspect it's an issue to do with the API level and some library mismatching of sorts. Any help would be greatly appreciated! I had some similar errors with the earlier sketches in part 1, but managed to fix them with a bit of messing around and also referring to the comments. I realize that this tutorial is out of date by this point, but it would be great to try and get it working, as it's the best one I've found thus far and most suitable to my application! Thanks, Jono Hello, Thanks for the great tutorial. I have the same problem as Jono above, any pointers on how we could solve it? Thanks Hey Jono, You might find your answer here: Cheers
https://arduinobasics.blogspot.com/2013/03/bluetooth-android-processing-2.html
CC-MAIN-2018-22
refinedweb
3,955
65.32
import xml into mysql Bütçe $240-2000 HKD. Bu iş için 51 freelancer ortalamada $1370 teklif veriyor Hello. I have rich experience with xml to sql. I am a serious bidder. As a web expert, I have strong skills for 7 more than years. I hope to work with you because my skill set is suitable for your project. Will wait pa Daha Fazla Hi, How r u? I can import xml into mysql I am experienced website developer having 7+ years of experience. Kindly check my recent work: FOR WEB : [login to view URL] Regards, Shw Daha Fazla Hello. I am a professional programmer and have rich experiences in mysql, php,xml, etc.... So I can make sql from your xml files surely. Please send message so that we can start now. i am ready for your project now. Gr Daha Fazla Hi, I understood 2 points that i need to integrate/import XML into your DB and then make a search option to show results but what about 3rd point? Can you please share that XML file so that i can check and provide yo Daha Fazla Hello sir. I have good skills and experiences as you requested on your project. You can see my results as follow. I am very interested in your project. If you hire me, Daha Fazla Hi there, I can convert xml file in the wordpress database. I am expert in Worpdress/Woocommere customization and I have completed 150+ projects with 5 star ratings. I have more than 10 years of experience in Wordp Daha Fazla Dear Client , We are Really interested to do work with you , We are Web & Software development company having more than 6 year experience in Software development we totally committed to quality service, Transparency, Daha Fazla Hello? Nice to meet you. I am excited to work with you on this project. I am ready to start work immediately. I have good skills in those. So I think I can help you if you want. Thank you. Best Regards. hello sir i am expert in wordpress,php and mysql i am able to do this work you will satisfy with my work i can do this work asap thank you I will create for you this admin plugin, to import xml files and add a new page for show the items list. Hi there, I have read your project description and its clear to me. I am ready to start the job right now. lets discuss. I am a professional individual developer having experienced in PHP, MySQL, Javascript, XML, Boo Daha Fazla Hi Nice to meet you. I have enough experience in python script. Below the libraries are I used in past project. selenium, pandas, matplotlib, lxml, beautifulsoup, scipy, and other useful libraries. I can import xml fil Daha Fazla Hello, I've gone through project description thoroughly and ready to design website on WordPress platform. I'm an SKILLED WORDPRESS WEB DEVELOPER having 6+ years of successful Track Record of Projects. And would like Hello Hope you are doing well. I have 7 years of experience in Wordpress, xml and MySQL DB management. I can handle this project. Regards VishnuLal* Hello, how are you? I am a creditist and xml, wp, php expert. I am very happy to have an opportunity of bidding your project. I have carefully read your posting and understood clearly what you want. My rich development Daha Fazla Hello. Nice to meet you. I have read your requirements carefully and I think I am the most porper person for you and your project. As a senior Web Developer, I have enough experiences of Web Development over 7 years. A. I have good experience with xml and wordpress. I have checked your description in detail. I can convert xml to mysql database and display on wp website. I can do it as well and asap. I want to discuss with you.
https://www.tr.freelancer.com/projects/php/import-xml-into-mysql-20839168/
CC-MAIN-2019-39
refinedweb
656
75.5
simonmar 2005/02/28 04:03:14 PST Modified files: ghc/compiler/basicTypes OccName.lhs ghc/compiler/prelude TysPrim.lhs Log: The type variables in the types of wired-in entities were built using mkVarOcc, which gives a variable name rather than a type variable name. Normally the compiler doesn't care, but when tidying types for output to the user the tidier would consider a VarName as distinct from a TvName, and not give them different print names. This fix makes puts all the type variables in the TvName namespace. Revision Changes Path 1.61 +4 -1 fptools/ghc/compiler/basicTypes/OccName.lhs 1.50 +2 -2 fptools/ghc/compiler/prelude/TysPrim.lhs
http://www.haskell.org/pipermail/cvs-ghc/2005-February/023610.html
CC-MAIN-2013-20
refinedweb
114
51.55
Join devRant Pipeless API From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple APILearn More Search - "next" - Rant Why do shithead clients think they can walk away without paying us once we deliver the project !!! So, here goes nothing.. Got an online gig to create a dashboard. Since i had to deal with a lot of shitheads in the past, I told them my rules were simple, 20% advance, 40% on 50% completion and 40% after i complete and send them proof of completion. Once i receive the payment in full, only then i will hand over the code. They said it was fine and paid 20%. I got the next 40% also without any effort but they said they also needed me to deploy the code on their AWS account, and they were ready to pay extra for it, so i agreed. I complete the whole project and sent them the screenshots, asking for the remaining 40% payment. They rejected the request saying my work was not complete as i had not deployed on AWS yet. After a couple of more such exchanges, i agreed to setup their account before the payment. But i could sense something fishy, so i did everything on their AWS account, except registered the domain from my account and set up everything. Once i inform them that its done and ask for the remaining payment. The reply i got was LOL. I tried to login to the AWS account, only to find password had been changed. Database access revoked. Even my admin account on the app had been removed. Thinking that they have been successful, they even published ads about thier NEW dashboard to their customers. I sent them a final mail with warning ending with a middle finger emoji. 24 hours later, I created a github page with the text " This website has been siezed by the government as the owner is found accused in fraud" and redirected the domain to it. Got an apology mail from them 2 hours later begging me to restore the website. i asked for an extra 10% penalty apart from the remaining payment. After i got paid, set an auto-reply of LOL to thier emails and chilled for a week before restoring the domain back to normal. Dev : 1 Shithead Client: 025 - What is the point of having a progress bar if .. beginning 0 % after ~2hrs 0% next minute: ~~~~~~~~~~~~~~ 100 % installation complete ??7 - - Manager: Everyone will be required to switch to Mac in the next couple of months. Dev: Um, why? Manager: Macs are more professional and developer focused than windows machines, I read it in an article. Plus they look way nicer. Dev: Half of the applications we use don’t have a version that works on iOS. Manager: What? How do you know? Dev: I have a Mac for occasionally doing some work on the iOS app we support. I ran into that when I was setting it up as a development environment. Manager: You have a Mac? Dev: Yes Manager: Why? How come you don’t use it for development? Dev: …17 - My bosses, bosses, boss asked to call me up unexpectedly: BBBoss:" Just wanted to say we are really happy with your performance, especially in these tough circumstances, ... " Me thinking: "Ah, great I am getting laid off." BBBoss: " ... which is why we decided to give you and extra 1000$ in you next paycheck." Me: "??? ... for real." BBBoss: "yes, thank you for your hard work." Me: "I am still employed?" BBBoss (laughs) :"Yes, we are happy to have you."7 - Dev: What do you think of the new version of the app? Client: It’s great! We just have a couple notes of feedback we are working on compiling. We should have those to you by next week. *Next week* Client: We need another week to compile all of this feed back we are generating *Another week goes by* Client: Still working on it, it’s going to be a really thorough review when you get it though. No stone will be left unturned! *2 weeks later* Client: Here it is! Attached: A word document with a single line of text “can’t nobody log in” next to a picture of the login screen with a red circle drawn around the login button Client: Can you hurry up and action our feedback? We want to go live next week Dev: …9 -: …20 - Friends Pandemic December proposal: "We should all get on Zoom every weekend, play Christmas trivia games and do shots" Family ideal Pandemic December: "Lets send each other Secret Santa presents throughout the whole month, and get on Zoom and unpack them" Me: Chilled out on a reclining seat next to a freshly slaughtered green fir tree, burning hearth fire, warm wool sweater, faux fur slippers, big mug of liquored up hot chocolate, keyboard on my lap, writing a Rust library on big screen TV. Sorry friends & family, y'all are doing holidays wrong. Happy holidays. -- signed, Grandpa Bittersweet.12 - Manager: Alright, we've decided we're gonna just going to accept PayPal and also credit card checkout through PayPal in the next two days! Dev: ... Manager: We can achieve this timeline, right? Dev: ... Manager: Alright, awesome to see your motivation! Let's do it! Dev: YOU ANSWER PHONE CALLS, TALK TO PEOPLE AND 'STRATEGIZE' ALL DAY. YOU DON'T HAVE TO RELY ON THOUSANDS OF PEOPLE USING THE APP WITHOUT ERROR. THAT'S ON ME, NOT YOU, SO JUST SHUT THE FUCK UP!!! Manager: ... Dev: ...8 -.19 - - Told some guy who was parking next to the emergency exit to move his car. He was like "uhm, well, you're not going to have an emergency anyway.." *fire alarm starts* Perfect timing ^^5 - Oh boy, the startup managers are writing a roadmap today. Can't wait. 5 mIlLiOn DaIlY aCtIvE uSeRs By EnD oF Q1! (2022!!!) 1 MiLlIoN dAiLy ReVeNuE bY tOmOrRoW! zErO bUgS aNd KnOwN iSsUeS iN sYsTeM bY 5Pm ToDaY! tHoUsAnDs Of NeW cUsToMeRs WiThIn ThE nExT hOuR!6 - **at daily standup Dev: and along with a push to production that is what I’ll be doing today Manager: Good good, alright, nice….. ok who else hasn’t gone yet? Dev how about you go next Dev: …I literally just went Manager: What? Well what did you say then? Hey when is that push to prod happening? I feel like there should be one happening sometime soon. Dev: …8 - - Up for a rollercoaster? I had a super motivated day where i could focus and wanted to get my work done. My stupid work lappy instead kept throwing tantrums and totally prevented me from working. (Everything caused disk thrashing, took multiple minutes instead of seconds, etc.) Total shit day, but I felt great. Next morning, I woke up all achy and cold. Ignored it and went to work. I was able to fix everything, and got my benchmarks running smoothly in all of fifteen minutes. Got good results, too! Left work and got married at the courthouse. :) Went to a restaurant afterward, and two jolly fat guys (Off-duty Santa?!) bought us lunch. Got home and… started feeling really awful. A little while later, I had a 102*f fever. Collapsed on the floor with an electric blanket and was absolutely miserable. Just kind of stared for hours, aching everywhere. Eventually went to bed, and my wife (!) made me all warm and comfy. And then I proceeded to be completely unable to sleep. Or move. Or think. Laid there for four hours unable to move, and shaking violently at any touch of cold air. Now it’s 1am and I’m here at the freezing kitchen table writing this. I am miserable. Absolutely miserable. But still happy, too! 🥶👰♀️💍👰🏻♀️19 - - During a company wide status meeting where all product managers, architects and directors assemble: Me: *A product architect leading a team of devs* Directors: So are there any issues or risks you see in delivering the next build in target time for Client 1? Me: There are too many changes in feature requirements. First they said we can use a shared NFS for storage. Now they are asking to switch over to SFTP pull mode.. blah blah.. Directors: Oh I see.. well we can support both solutions then. Me: But the deadlin.. Directors: *ignores what I say* Will be a good marketing point for future. Me: But there are too many regressions in integra.. Directors: *ignores what I say* We should also meet deadlines. That is the most important thing. Me: Its not as easy as 1+1=2.. The team needs more time to.. Directors: *ignores what I say* Ok lets move on to the next point. What about Client 2? Me:4 - Long long ago there was a man who discovered if he scratched certain patterns onto a rock he could use them to remind him about things he would otherwise forgot. Over time the scratching were refined and this great secret of eternal memory were taught to his children, and they taught it to their children. Soon mankind had discovered a way to preserve through the ages his thoughts and memories and further discovered that if he wrote down these symbols he could transfer information over distances by simply recording these symbols in a portable medium. Writing exploded it allowed a genius in one place to communicate the information he had recorded across time and space. Thousands of years passed, writing continued to be refined and more and more vital. Eventually a humble man by the name of Johannes Gutenberg seeking to make the divine word of God accessible to the people created the printing press allowing the written word to be copied and circulated with great ease expanding vastly the works available to mankind and the number of people who could understand this arcane art of writing. But mankind never satiated in his desire to know all there is to know demanded more information, demanded it faster, demanded it better. So the greatest minds of 200 years, Marconi, Maxwell, Bohr, Von Nueman, Turing and a host of others working with each other, standing on the shoulders of their brobdinangian predecessors, brought forth a way to send these signals, transfer this writing upon beams of light, by manipulating the very fabric of the cosmos, mankind had reach the ultimate limits of transmission of information. Man has conquered time, and space itself in preserving and transmitting information, we are as the gods! My point is this, that your insistence upon having a meeting to ask a question, with 10 people that could've been answered with a 2 sentence email, is not only an affront to me for wasting my time, but also serves as an affront to the greatest minds of the 19th and 20th centuries, it is an insult to your ancestors who first sacrificed and labored to master the art of writing, it is in fact offensive to all of humanity up to this point. In short by requiring a meeting to be held, not only are you ensuring the information is delayed because we all now need to find a time that all of us are available, not only are you now eliminating the ability to have a first hand permanent record of what need to be communicated, you are actively working against progress, you are dragging humanity collectively backwards. You join the esteemed ranks of organizations such as the oppressive Catholic church that sought to silence Galialio and Copernicus, you are among the august crowd that burned witches at Salem, the Soviet secret police that silenced "bourgeoisie" science, you join the side of thousands of years of daft ignorance. If it were not for you people we would have flying cars, we would have nanobots capable of building things on a whim, we would all be programming in lisp. But because of you and people like you we are trapped in this world, where the greatest minds are trapped in meetings that never end, where mistruth and ignorance run rampant, a world where JavaScript is the de facto language of choice every where because it runs everywhere, and ruins everywhere. So please remember, next time you want to have a meeting ask yourself first. "Could this be an email?" "Do I enjoy burning witches?" if you do this you might make the world a little bit of a less terrible place to be.6 - So, I applied for a job lately and the first interview via Zoom went pretty good. Then I got an invitation for a second interview at the company. I got there, was guided into a conference room and the two head of departments along with an HR woman joined. After a bit if chit-chat HR rep said I should tell them in the next couple of days if I'm still interested. HR left, the other two gave me a tour of the complex, lasting about an hour. then we got back to the conference room, waited for HR rep and when she arrived she told me something along the lines of "Yeah, we got an impression of you now and you don't need to contact us anymore if your are interested...." me to myself: "wait what? that sucks...." HR: "We are impressed enough of you that we want to hire you immediately. Here is the contract!" me (completely speechless): "oh... OH... THANKS, but... OHHHH" (having a stupid perplexed grin on my face) I mean... I got the job and pay is good, but PLEASE don't trick me like that!!! I nearly got a heart attack!!!8 - Manager: Messages not visible! bug ticket!!!! Dev: oh fuck, there's an issue with our chat system, not good! _inspects ticket_ oh, it's just a display issue that actually is according to the previous spec, yawn... Dev: please describe the bug better next time, I though we had a major outage, this is simply a small design issue... Manager: ... Dev: ... I think I'm quitting soon guys. I literally do not get paid enough to deal with these incompetent idiots each day. Meanwhile: Management: forget your shitty salary, take one for the team, you get 3% of the shares in the company!!!! Dev: what fucking shares, you haven't even converted to a corporation yet, THERE ARE NO SHARES Management: ... Dev: ... Oh yeah and they called me at 6:30 PM today: "so i guess you are winding down for the day" fuck outta here i haven't been working since 5 you fucks jesus i swear some people need to screw their fucking head on straight, so far gone into the hUsTlE CuLtUrE they don't even know what reality is anymore - First I wanna say how grateful I am that devRant exists, because my friends either don’t understand this vocab or don’t care lol. Last week I worked on a pretty large ticket, opened a PR with 54 file changes. Just to follow standards I set the PR milestone to a future release version, but the truth is I didn’t care which version this work ended up in— I just needed it to go into the develop branch asap. Since it was a large PR there was some expected discussion that prolonged its merging, but in the meantime I started a second branch that depended on some of the work from this branch. I set the new branch’s upstream to develop, fully expecting my PR to merge into develop, since that’s what I set the PR base to. I completed all the work I could in the new branch, and got two colleagues to approve the initial PR so it would be merged into develop, I could add the finishing touch and get this work done seamlessly before the week was over. They approved, it got merged, I pulled develop, and… my work wasn’t there. I went to look at my PR and someone had changed the base branch to a release branch. It was my boss, who thought he was helping. (Our bosses don’t actually work on the same team as us, so he didn’t know. it’s weird. We have leads that keep track of our work instead.) I messaged him and told him I really needed this in develop, knowing our release branch won’t be in develop for probably another week. I was very annoyed but didn’t wanna make him feel too bad so I said I’d just merge the release branch into my new branch. So many conflicts I couldn’t see straight. His response was “yeah and you’ll probably have a bunch of package manager conflicts too because that’s in that release.” He was right— I have so many package manager conflicts that I can’t even see how many compiler conflicts there are. I considered cherry picking my changes, but the whole reason I set develop as my upstream was to avoid having any conflicts since I’m working in the same functions, and this would create more. So I could spend the next (?) days making educated guesses on possibly a thousand conflict resolutions, or I can revert my release branch merge and quietly step back and wait for the release branch to be merged into develop. I’m sure cherry picking is the best option here but I’m genuinely too annoyed lol, and fortunately my team does not care to notice if I step back and work on something else to kill time until it’s fixed automatically. But I’m still in dire need of a rant because my entire plan was ruined by a well-meaning person who messed with my PR without asking, so here is that rant and I thank you for your time.8 - - - Dammit, just put the date somewhere next to the title when writing an article. It's amazing how much context might be missing if there's no date when dealing with software issues.9 - - Fuck Reddit admins. Fuck them in ass with a rusted iron rod. Then pour in some liquid steel and dehydrate them to death. Bloody fucks. Remember the toxic girl who stalked and harassed me? She did that on Reddit. After multiple reports to faggot admins, no action was taken against her multiple accounts. I ended up creating few alt accounts for my mental well-being. I have been contributing fairly well from all my accounts earning community trust and reputation, even behind the mask of anonymity. Now, day before yesterday, a teen started abusing me for no reason on a local sub. I ended up ignoring. Next morning I am notified that admins banned my account permanently. What the fuck! I did not violate any policy and yet I was kicked out. I raised an appeal for those fags to look into this and uplift the ban. Fuckers banned all my accounts permanently without giving any reason. Instead of taking action against retards who harass people, these bhenchods ban people who contribute in a good way. I truly wish, that the person who made this decision rots to death while feeling the pain of regret. I am soooo fucking annoyed. I have been using Reddit for many good reasons and have found it really helpful in various areas of my life.12 - - - New client: can we go live next month? Me: do you think you are our only client, or do you want to pay an extra priority fee? New client: what? Me: what? *Crickets"4 - People/companies talking about ooh we want gender diversity we want more female software developers, IT professionals etc You talk the talk, do you know how to walk the walk?? Do you know how to deal with female engineers? I am a hardcore engineer worked and studied majorly with men for years. I lead, managed teams had my own company worked as a consultant for years. Then I got into the IT industry as developer later. I was completely against the idea of being female would make any difference or you would be treated differently. Finally I had my own enlightenment and stopped resisting that idea. Some treatments made me think what are these guys doing? Don’t treat me like your sister. I am not your sister. Don’t see the femininity or looks. I am not a Merrilyn Monroe to say oooh you are great you know soo much. I am not paid for that act, I do my job! It’s same as yours mate. Don’t underestimate me or try to preach me as if I am a cute little girl. Don’t show off and boost your ego next to other guys. Now I regretfully I agree the ladies ranting about male dominance and getting different treatment in IT. I am literally trying to avoid red nail polishes or red lipstick god forbid. Maybe I should put some fake beard and a belly, loose jeans with an energy drink in hand. Here comes the expert IT professional, already ticking a box. Honestly you are not taken seriously most of the time. If you are a guy then they are all ears..And those guys talk about they want gender diversity blah blah You feel like a ghost when you express your opinion. You are not taken into account even when you have a comment or suggestion. Even humiliated by a guy giving me a speech about how to be a good developer next to a manager. Look buddy I am not a yesterday’s child. I am at your age. I haven’t come to this position by jumping around picking flowers in a field. If I was a man, would you dare saying those to me? There could be a street fight coming. LinkedIn selfie takers with body show offs putting ooh I am an IT recruiter as a female I got into IT. You can do it too. (don’t get me wrong I respect that achievement that’s good) but those girls get thousands of likes and applauses, you are working in IT for years people say they are seeking for. Your technical post doesn’t even get 20 likes. Your encouraging comment on a guy’s post isn’t even acknowledged. You are not even taken into account. Am I a ghost or something? Honestly I don’t understand. What do you mean by gender diversity? What do you want here? Leave this gender bullshit. Look at the knowledge you don’t even know what equality means. It’s not having even numbers of genders. It is respecting knowledge and hard work regardless. Listening and acknowledging without judgement. Looking beyond male, female or others Companies that say we want to have more females, you don’t come and knock on my door either. You are already stating a difference there. Attract with indifference don’t come and tell me you are a female we want more females here. I’m telling you this sector is not getting proper gender equality for 25 years. Talk is there but mentality is not yet there. I am super pissed off and discouraged today. I don’t even get discouraged that easily. Now I understand some women in IT talking about insecurities. I am on the edge of having one, such a shame. Don’t come at me now I would bite! This is my generalisation yes. Exceptions apply and how good it would have been if those exceptions were dominant.35 -: ...4 - My annoying 19-yo nephew wants to drop out of CompSci to "create the next billion-dollar startup". I told him I would give him 10 rupees (USD 0.10) for 0.000000001% percent of his "pass me the butter at the diner table" company. He accepted. Thus, his "heritage protein logistics startup" had an series-A valuation of a billion American dollars! Hopefully he will stay in college now.2 - My dev colleagues, the ceo, a external designer and me (dev) are sitting in the meeting room and we discuss the result from the designer. He designed a complete relaunch of a small CRM for the logistics sector. The designer is a designer as you know him, big beart, small macbook, chai late and he designed nothing, he hired a freelancer from romania. My boss studied software development in the 80s but didn't really developed a software for about 20 years, but he thinks he knows all and everything. My boss is constantly complaining about the colors in the design and he would like a iOS approach. Our system should complete copy the styles from iOS. The really funny thing happend in just 1 minute. My boss is complaining again about the colors and told the blue color is way to dark and the designer meant thats not possible the blue color very bright. My boss sat next to the designer and looked not on the wall where the picture was thrown from a projector, instead he looks from the side in the macbook screen of the macbook which was in front of the designer. Then the designer says "Oh my god, the color changes if I look from the side or from the top of the macbook." The Designer was blown away. My boss couldn't believe it and did the same movements with his head and said. "Wow, you are right the color changes". We all other people couldn't believe that they are so dumb and thought this must be a joke. But that wasn't a joke. After the meetin my boss told everyone in our company his results regarding the screen. I wrote every story in a document, and I'm planning to create a book with dumb shit like this.2 - A couple of weeks ago, I got to the second stage of a recruitment process with a relatively big fintech in the crypto space (I know) - all went well and although I did not think much of it at first, with all the information I had gathered I came to realize this might as well be the best opportunity I've had in my pursuit of finding a new job (i.e looking for high technical challenges, unsure of where I see myself in 5 years, wanting to give full-remote work a try, etc.). Cue to the end of the interview; "That's great! I really enjoyed speaking with you, your technical background seems excellent so we would like to move to the next stage which is a take-home test to do in your free time.", said the interviewer. "Wow! Much amaze, well of course! What's it gonna be?", said the naive interviewee. "I'm sending you the details via email, please send it back in 48 hours, buhbye now", she hangs up. ... "48 hours?? Right, this should be easy then, probably some online leetcoding platform, as usual.", thought the naive interviewee, who evidently went through this sh*t numerous times already. A day later I receive the email: this was the whole deal. The take-home test supreme with bacon and cheese. A full-blown project, with tests, a project structure, a docker image, testing and bullet points for bonus points! The assessment was poorly written with lots of typos and overall ambiguity, a few datasets were also provided but bloated with inconsistent comments and trailing whitespace. What the actual fck??? Am I supposed to sleep deprive myself to death while also working my day job? What are you trying to assess? How much of my life I'm willing to sacrifice for your stupid useless coding challenge? You are not all Google, have some respect, jeez. I did not get the job.2 - - Recruiter story.. hilarious stuff.. I have an interview in next fifteen minutes and was setting up for it. Recruiter calls me to remind me of the same. I ask her to tell me who the interviewer would be, because she did not mention in the invite and also did not respond when I asked her over the email. Her response: sure, wait a minute... Actually we are not allowed to disclose interviewer. LMAO WTF!!7 - - The Mac Studio with 128 GB integrated memory looks very interesting, I could finally run a third Electron app next to Slack and Spotify.6 - !rant Today was a lot. I heard water outside and some shouting, come to find out the upstairs neighbor’s pipe burst. Spent the next hour or two collecting as much water as possible in the coolers we have to try to move it to the storm drain and protect the downstairs neighbor’s apartment. You'd be amazed how much water can fish out of a broken pipe. Spent a nice hour or two chatting with the downstairs neighbor after they asked what happened (having just realized the water was shut off and having missed all the activity). Was just settling down from that when I heard a kid screaming for help and panicked shouting. Come to find out my favorite neighbor is unresponsive and can't breathe and her kids are all panicked and waiting for the ambulance. The 911 operator is trying to give them instructions but they're too panicked to listen. I get them to move her onto the floor, then finally get the oldest to do chest compressions until the ambulance shows up. The paramedics managed to get her back, she was breathing on her own and talking, and take her to the hospital but it took a long time to get there. Hugged the heck out of everyone who seemed like they needed it and tried to say comforting shit that it seemed like they needed to hear. I haven't felt this emotionally tapped out in a long-ass time.7 - - Ok, so our team is responsible for writing an app that consumes an API written by the client's team (I refuse to call it a "REST" API, despite their claims). On one of the clarification meetings we are discussing an endpoint that accepts a (logically) unique field multiple times, even though an entity is already registered in the system with that unique identifier. Our proposal would be that this API of theirs should not happily accept duplicates as many times as there are bits on a 4TB hard drive, rather it should signal an error. The response we got is this: Due to the Separation of Concerns principle they thought that it should be our app's responsibility to not send a request if an entity with said field is already in the system. Thus there's no need for the backend to validate this. I didn't hear the next part, because I had to collect my headphones from the other side of the room where they were flung in rage.11 - I quit my job… it got so exhausting, it had become all about last minute work and ETAs. The more I worked the sicker I felt. It started directly impacting my physical health which ended up affecting mentally too. I feel good that I got out of something very toxic but at the same time not working kinda makes me sad when I look at others working. I have consciously taken a break to clear my mind but it affects me that I don’t know what next.2 - - Be me - Been in a new job for 2 months - Was excited because of 50% salary increase and better position - Have a new team of 6 devs including me. All new guy - Market crash - Top management demands a trim down to all divisions - Will be left to 3 devs next month - All the while being asked to - Deliver a shopify like marketplace from end to end - Deliver integration with partners for data inventory tracking - All within 2 months - Furious when target is not met - Demands a micro management to every single person on the team on what their day to day schedule - Demands everybody to live by hustle culture and ready to work non stop even nights or weekend - Be me - Been working non stop for at least a month - Sacrificed weekends and holidays Beginning to think that maybe the money and position isn't worth the hassle6 - - I am back with some more emotional shit. So tomorrow is my last working day at my second employer where essentially I'll just walk into the 10 seater serviced office to drop my laptop in a cupboard because no one else is here. So today, an hour ago, they had a virtual farewell for me and everyone spoke of me highly with specific examples. Well that's not what this post is about, but the emphasis is that I am still in dual mind of whether I made the right decision to quit my second employer so soon (in just 10 months)? If I had stayed for two months more: 1. I'd gotten a hike this week 2. More RSUs in that hike along with cash 3. Joining RSUs would have vested for the cliff period of 1 year 4. Tenure would be at least a year 5. Would have found a better job with higher pay (on the new hiked salary). I surprisingly got the grip of the product and that's when I decided to quit. The reason I quit is I wanted to optimise for WLB and timezone with better team culture. While the next job is surely a company I wanted for a long time and that too in B2C space, I really lost my affection for that role and that's where it came to me upfront and I rejected them initially before picking up the offer again. My second employer is a very global and one of the largest brands. Really wanted to stick around and never got to enjoy the benefits which others did. Only time can tell, because when I chased something I never got it, when I stopped, it came to me. And what I am chasing now is something I am unable to achieve. Why is life so fucked. Seems like I am about to lose one of my biggest and only life and career dream. Maybe I fucked up this decision. Maybe not. Only time can tell.12 - So I've got my first sort of proper gig. I'm tasked with writing... A goddamn minecraft plugin in java. Well, it's actually rather fun strangely enough. My ideas of payment were not declined but rather accepted, the other devs are nice and everything is going well for now. Also: Do expect a mental breakdown post next week or so8 - "Writing good code is a charity". ( - saves time, effort, mental-health, & career of next developer) - - - I fucking got scammed. Scenario 1: Had literally no experience in B2C, no experience in experimentation, 0% fitment. Verdict: got hired in just one round in a top domestic brand which is a profit making startup. Scenario 2: A friend from ex-org got referred in a global brand for an international location. Hadn't interviewed for 4+ years. Created his resume in 15 minutes, got shortlisted, screened, interviewed, and hired in less than 2 weeks. (This guy is a good friend I am incredibly happy for him and that he scored the gig and in now way I wish bad for his outcome). Scenario 3: I also got a strong refferal for the same brand and location. I have been interviewing for past 6 months, resume is super polished where companies like FAANG spoke to me. Got rejected in shortlisting. The referral guy got me in the pool because it was his team In screening round, I was a good fit, answered everything well. Yes, I wasn't concise as much (and that's the feedback I kept getting and I was working on it). Verdict: rejected. They didn't ask me relevant questions and rejected me on the basis of not having the required experience. Seems like the hiring manager didn't want me to clear so came up with reasons. And now it feels that, if the HM wants you, they'll hire you irrespective of anything and if they don't they'll kick you out for lamest of the reason. My life is split in two part, the first three decades were surely shit and this was my last chance of making sure the next three are worth remembering on the death bed. I failed. Miserably. For the factors outside of my control. Not that I haven't failed in past. Not that I didn't try again. But man, I am doing persisting. The game is rigged. One cannot win without extreme luck. Millions of dreams shattered. A shitty day, is now a shitty life. Being born in third nation is a fucking curse.5 - Team estimated a huge feature with 60 days. Made a prototype in a day, implemented it in the project the next day. Code looks a lot cleaner than a previous similar solution. Now it’s 90% done. Should have worked with 2 other people. Oh well, sorry not sorry for that teamwork.3 - Me: “here’s a demo of the backend functionality you requested. We’ve got more work to do to make this production ready. Let me know your thoughts or if we need to make any changes, otherwise I’ll hand this off to the UX team, we’ll be ready to go live next month after other they deliver the front end” PM: *telling stakeholders* “The new thing is done and ready for go live” Me: *privately to PM* “who told you that the thing was ready for go live?” PM: “You did” Me: “I suggest you go read what I wrote a little more closely”5 - This tree was the loneliest tree on Earth. The next tree was 400 kilometres away. In 1973, it was knocked down by a truck driver.4 - PSA: Next time you plan on changing all your model names from "xxxxx" to "xxxxxModel", under a minor version bump so that everyones CI breaks, in order to deliver no benefit whatsoever ..... don't10 - - - Fuuuuck!!! In 2017 I had a reeeeally sweet offer for a Java-gig. Equity, quarterly evaluations with potential raises, exciting products, world class experts as colleagues and all. The catch was relocating across the entire country, and due to some family health stuff, I was forced to decline. Today I learned that the company is valued at about $150M. The equity alone would have been worth around 1.5M today, and thats not all. One of the founders are giving away about 15% of the shares to the employees, landing them about 100K in equity each. And here I sit, wondering about what the next electric bill will be...10 - - - EoS1: This is the continuation of my previous rant, "The Ballad of The Six Witchers and The Undocumented Java Tool". Catch the first part here:... The Undocumented Java Tool, created by Those Who Came Before to fight the great battles of the past, is a swift beast. It reaches systems unknown and impacts many processes, unbeknownst even to said processes' masters. All from within it's lair, a foggy Windows Server swamp of moldy data streams and boggy flows. One of The Six Witchers, the Wild One, scouted ahead to map the input and output data streams of the Unmapped Data Swamp. Accompanied only by his animal familiars, NetCat and WireShark. Two others, bold and adventurous, raised their decompiling blades against the Undocumented Java Tool beast itself, to uncover it's data processing secrets. Another of the witchers, of dark complexion and smooth speak, followed the data upstream to find where the fuck the limited excel sheets that feeds The Beast comes from, since it's handlers only know that "every other day a new one appears on this shared active directory location". WTF do people often have NPC-levels of unawareness about their own fucking jobs?!?! The other witchers left to tend to the Burn-Rate Bonfire, for The Sprint is dark and full of terrors, and some bigwigs always manage to shoehorn their whims/unrelated stories into a otherwise lean sprint. At the dawn of the new year, the witchers reconvened. "The Beast breathes a currency conversion API" - said The Wild One - "And it's claws and fangs strike mostly at two independent JIRA clusters, sometimes upserting issues. It uses a company-deprecated API to send emails. We're in deep shit." "I've found The Source of Fucking Excel Sheets" - said the smooth witcher - "It is The Temple of Cash-Flow, where the priests weave the Tapestry of Transactions. Our Fucking Excel Sheets are but a snapshot of the latest updates on the balance of some billing accounts. I spoke with one of the priestesses, and she told me that The Oracle (DB) would be able to provide us with The Data directly, if we were to learn the way of the ODBC and the Query" "We stroke at the beast" - said the bold and adventurous witchers, now deserving of the bragging rights to be called The Butchers of Jarfile - "It is actually fewer than twenty classes and modules. Most are API-drivers. And less than 40% of the code is ever even fucking used! We found fucking JIRA API tokens and URIs hard-coded. And it is all synchronous and monolithic - no wonder it takes almost 20 hours to run a single fucking excel sheet". Together, the witchers figured out that each new billing account were morphed by The Beast into a new JIRA issue, if none was open yet for it. Transactions were used to update the outstanding balance on the issues regarding the billing accounts. The currency conversion API was used too often, and it's purpose was only to give a rough estimate of the total balance in each Jira issue in USD, since each issue could have transactions in several currencies. The Beast would consume the Excel sheet, do some cryptic transformations on it, and for each resulting line access the currency API and upsert a JIRA issue. The secrets of those transformations were still hidden from the witchers. When and why would The Beast send emails, was still a mistery. As the Witchers Council approached an end and all were armed with knowledge and information, they decided on the next steps. The Wild Witcher, known in every tavern in the land and by the sea, would create a connector to The Red Port of Redis, where every currency conversion is already updated by other processes and can be quickly retrieved inside the VPC. The Greenhorn Witcher is to follow him and build an offline process to update balances in JIRA issues. The Butchers of Jarfile were to build The Juggler, an automation that should be able to receive a parquet file with an insertion plan and asynchronously update the JIRA API with scores of concurrent requests. The Smooth Witcher, proud of his new lead, was to build The Oracle Watch, an order that would guard the Oracle (DB) at the Temple of Cash-Flow and report every qualifying transaction to parquet files in AWS S3. The Data would then be pushed to cross The Event Bridge into The Cluster of Sparks and Storms. This Witcher Who Writes is to ride the Elephant of Hadoop into The Cluster of Sparks an Storms, to weave the signs of Map and Reduce and with speed and precision transform The Data into The Insertion Plan. However, how exactly is The Data to be transformed is not yet known. Will the Witchers be able to build The Data's New Path? Will they figure out the mysterious transformation? Will they discover the Undocumented Java Tool's secrets on notifying customers and aggregating data? This story is still afoot. Only the future will tell, and I will keep you posted - Regarding my last rant: I have all my 3 Raspberrys set up for seti@home now, reporting to twitter and my own "surveillance" system for them. The system is still ugly, the code is ugly but that's getting improved next!4 - - I like like my boss and my coworkers and the place I work but for the love of goat cheese this org has the attention span of a toddler on meth. Seriously, it's like this is your #1 priority, next week, wait we have a different emergency you have a new super critical urgent thing, then "hey team Y has a vendor coming in next month to integrate these two pieces and they need you to have half of it wired up by then so make sure you get that done." Like SERIOUSLY SERIOUSLY HERE"S SOME LIFE ADVICE IT DOESN'T MATTER WHAT YOU PLAN OR SCHEDULE OR PRIORITIZE IF YOU END UP CHANGING ALL OF IT EVERY WEEK! It's like painting a mural of a field, and then 10 minutes in you decide you'd rather paint a space ship, then you realize you don't like the space ship so instead you decide to change your painting to Elvis with a mullet, and you keep doing this. The end result is not beauty it's the mad deranged scribbles of a man past the point of sanity. But for the love of Haliburton if they ask me why X or Y wasn't done I'll probably end up going full BOFH on somebody.3 - - this client couldn't figure out pagination. and whenever items moved to next page he could not find it. He would create a new one.1 - Apartment management: Hey folks. Elevator #4 is getting a software upgrade so it will not be in service for a few weeks. While we’re doing the upgrade, the elevator call button next to elevator #1 will only call that elevator. The other call button will call elevators 2 and 3. Please press only one button. If you press both, you’re requesting two elevators to come to you and this slows elevator arrival time for other residents. Thank you. 99% of residents: Ah ha! You told us the secret. We’re going to press both call buttons because we choose chaos 😈4 - - So the next O’rly book I can imagine for this project is: How did I ended in this microservices nightmare?2 - - HTML quick maffs If you want to have a placeholder for native <select> element, just do the following: <option value="" selected disabled hidden>Choose...</option> It will make a native placeholder that: - is accessible and readable by screen reader - doesn't show up in options list - allows native validation with "required" attribute (note the empty value attribute in the placeholder option). It's unfortunate that we don't have it the way we have placeholder in inputs, but this is the next best thing.3 - I am feeling little fucked up. I talked to one of the female employees from my new company, I'll be joining next month. She asked manager to hire a girl in the team, I know she casually asked but after knowing this, I know my interviews were surprisingly easy, I mean I know already that no one asked me to optimize anything... did the fucking hired me for diversity, pay is good, people are good, work is good but seriously if I'm getting hired for the fucking diversity my manager is going to have a good speech from me and I'll move from his team for sure.21 - an interview with a CEO and product owner next week for the position of principal developer. The job ad which got me here stated 'Any additional skills you have will be viewed favorably'. I've had my ass burned by that crap at least once before. When they ask about private projects, I'm just going to say "I love my job so much, I do it in my free time too!"3 - Follow up to:.... 1- The attacker just copy pasted its JWT session token and jammed requests on the buy gift cards route 2- The endpoint returns the gift card to continue the payment process, but the gift card is already valid 3- Clients wants only to force passwords to have strong combinations 4- Talk about a FIREWALL? Only next month 5- Reduce the token expiration from 3 HOURS to 10 minutes? Implement strong passwords first 6- And then start using refresh tokens BONUS: Clearly someone from inside that worked for them, the API and database password are the same for years. And the route isn't used directly by the application, although it exists and has rules that the attacker kows. And multiple accounts from legit users are being used, so the person clearly has access to some internal shit7 - !rant It's funny to consider that my previous rant (...) before I stopped checking this platform as regularly was about what the perfect job would look like to me … Because I just landed it today, people! Signed with a very chill, medium sized, local dev company that appreciates me as much as I do appreciate them. Starting next month I won't be just a random intern (although they never treated me as such anyway) anymore but a professional developer, with even a slightly more important pay than what you (at least I)'d expect for a junior Adios annoying courses and mediocre marks, now the fun begins - My First !Experience : Disappointment with a computer My mum kept tons of floppies but we didnt have a computer at home. Went to my friends house, who had one, and had Encarta 95 (its like a fun wikipedia for kids). When I mentioned I had floppies, he asked for one, since he didnt have one. We copied Encarta to that floppy hoping we would cheat in the next computer science test. We even tested it. After we were certain that all works (you should know we were surprised that it could fit in one floppy), we got to school, put the disk in and voila we had copied a shortcut :)4 - I find it weird that for C floats, -0<+0 is not true. Had to write a little bit of extra code to enforce this. -0 could represent an incrementally small number below zero but greater than the next lower quantisation level.5 - Company: people are not taking holidays, let's have after work party midweek so they have to take a day off. Employees: (next day after late night party) I'm calling in sick2 - Why on gods green earth, would anybody look at a file with 20k lines, which clearly was made by something called WEBPACK and decide it's the right place to implement their changes for the next few years?!?3 - Almond: "This isn't right, we need to use <blah> instead" Phil: <Marks as resolved> Almond: "This still doesn't look to be resolved" Phil: "IT IS RESOLVED IT WILL BE PUBLISHED AS PART OF MY NEXT COMMIT WHICH I WILL PUSH ON SCHEDULE LATER TODAY" 🙄 ...yeah, that makes sense...4 - sprint started two weeks ago, it's due today. yesterday, most tasks for the sprint were done, but was still waiting that whole two weeks for updates on two new tickets, guess they'll be in the next sprint... project leaders yesterday: oh here are those updates for the sprint! (not to mention the meeting was at 5 PM yesterday, not even the BEGINNING of the work day) project leaders today: what's the status of the sprint?! ...it's a joke, right? do you think I'm a fucking magician? its always the same no matter where you go, slowly starting to realize... tl;dr; adding new feature requests the day before a sprint ends and then having the nerve of asking the "status" of the sprint the following day: - Why use google calendar? Get you a micromanager! Always the same with these f**** 🤡🤡🤡s Congratulations, you've earned yourself a spot in the STOP category on next week's retrospective! 🖕4 - Imagine you work in a mechanic’s shop. You just got trained today on a new part install, including all the task-specific tools it takes to install it. Some are standard tools, like a screwdriver, that most people know how to use. Others are complicated, single-purpose tools that only work to install this one part. It takes you a couple of hours compared to other techs who learned quicker than you and can do it in 20 minutes. You go to bed that night thinking “I’ve got this. I’ll remember how this works tomorrow and I’ll be twice as fast tomorrow as I was today.” The next morning, you wake up retaining a working, useful memory of only about 5% on how to use the specialized tools and installation of the part. You retrain that day as a review, but your install time still suffers in comparison. You again feel confident by the end of the day that you understand and go to bed thinking you’ll at least get within 10-20 minutes of the faster techs in your install. The next morning, you wake up retaining a working, useful memory of only 10% on how to use the specialized tools. Repeat until you reach 100% mastery and match the other techs in speed and efficiency. Oops! Scratch that! We are no longer using those tools or that part. We’re switching to this other thing that somehow everyone already knows or understands quickly. Start over. This has been my entire development career. I’m so tired.2 - - Once again I am done with World of Warcraft. The game is developed by incompetent morons who completely lost the narrative and a company that solely focused on profits. Loved the game through 2005-2010, but nowadays it's just a toxic cesspool of egoistic people that play like they're on their way to the next MDI championship. Zero tolerance for mistakes, pointing fingers and calling people out and overall horrible attitude. And who can blame them? Most of us are 30+ something people who have 9-5 jobs and families, so the little time we have to play has to be perfect and not ruined by someone, making me feel like I've wasted my time. I've also noticed I've turned more egoistic while I used to be more of an altruist. Not in the game, but in real life. Over the past year I've almost spent more time focusing on the game than the world around me. I haven't been slacking off in my responsibilities, but I've been chasing that periodic dopamine rush you get from achieving something in the game. That stops now. Uninstall. Purge files. Just the thought of readjusting my addons makes me shiver, so that's going to be a nice deterrent. Fuck that community. Time to get back to those personal projects that I never finished. (Instead of talking to a psychiatrist, I just vent here.? : - This is the third part of my ongoing series "The Ballad of the Six Witchers and the Undocumented Java Tool". In this part, we have the massive Battle of Sparks and Storms. The first part is here:... The second part is here:... Over the last couple sprints and then some, The Witcher Who Writes and the Butchers of Jarfile had studied the decompiled guts of the Undocumented Java Beast and finally derived (most of) the process by which the data was transformed. They even built a model to replicate the results in small scale. But when such process was presented to the Priests of Accounting at the Temple of Cash-Flow, chaos ensued. This cannot be! - cried the priests - You must be wrong! Wrong, the Witchers were not. In every single test case the Priests of Accounting threw at the Witchers, their model predicted perfectly what would be registered by the Undocumented Java Tool at the very end. It was not the Witchers. The process was corrupted at its essence. The Witchers reconvened at their fortress of Sprint. In the dark room of Standup, the leader of their order, wise beyond his years (and there were plenty of those), in a deep and solemn voice, there declared: "Guys, we must not fuck this up." (actual quote) For the leader of the witchers had just returned from a war council at the capitol of the province. There, heading a table boarding the Archpriest of Accounting, the Augur of Economics, the Marketing Spymaster and Admiral of the Fleet, was the Ciefoh Seat himself. They had heard rumors about the Order of the Witchers' battles and operations. They wanted to know more. It was quiet that night in the flat and cloudy plains of Cluster of Sparks and Storms. The Ciefoh Seat had ordered the thunder to stay silent, so that the forces of whole cluster would be available for the Witchers. The cluster had solid ground for Hive and Parquet turf, and extended from the Connection River to farther than the horizon. The Witcher Who Writes, seated high atop his war-elephant, looked at the massive battle formations behind. The frontline were all war-elephants of Hadoop, their mahouts the Witchers themselves. For the right flank, the Red Port of Redis had sent their best connectors - currency conversions would happen by the hundreds, instantly and always updated. The left flank had the first and second army of Coroutine Jugglers, trained by the Witchers. Their swift catapults would be able to move data to and from the JIRA cities. No data point will be left behind. At the center were thousands of Sparks mounting their RDD warhorses. Organized in formations designed by the Witchers and the Priestesses of Accounting, those armoured and strong units were native to this cloudy landscape. This was their home, and they were ready to defend it. For the enemy could be seen in the horizon. There were terabytes of data crossing the Stony Event Bridge. Hundreds of millions of datapoints, eager to flood the memory of every system and devour the processing time of every node on sight. For the Ciefoh Seat, in his fury about the wrong calculations of the processes of the past, had ruled that the Witchers would not simply reshape the data from now on. The Witchers were to process the entire historical ledger of transactions. And be done before the end of the month. The metrics rumbled under the weight of terabytes of data crossing the Event Bridge. With fire in their eyes, the war-elephants in the frontline advanced. Hundreds of data points would be impaled by their tusks and trampled by their feet, pressed into the parquet and hive grounds. But hundreds more would take their place. There were too many data points for the Hadoop war-elephants alone. But the dawn will come. When the night seemed darker, the Witchers heard a thunder, and the skies turned red. The Sparks were on the move. Riding into the parquet and hive turf, impaling scores of data points with their long SIMD lances and chopping data off with their Scala swords, the Sparks burned through the enemy like fire. The second line of the sparks would pick data off to be sent by the Coroutine Jugglers to JIRA. That would provoke even more data to cross the Event Bridge, but the third line of Sparks were ready for it - those data would be pierced by the rounds provided by the Red Port of Redis, and sent back to JIRA - for good. They fought for six days and six nights, taking turns so that the battles would not stop. And then, silence. The day was won, all the data crushed into hive and parquet. Short-lived was the relief. The Witchers knew that the enemy in combat is but a shadow of the troubles that approach. Politics and greed and grudge are all next in line. Are the Witchers heroes or marauders? The aftermath is to come, and I will keep you posted.4 - Why is it most companies think being “agile” simply means “let’s say we do work in two week blocks” but without planning or showcases or reviews, without estimations, with ad-hoc tasks inserted continually, priorities changing, tasks moving to the next “sprint” over and over … But yes, these companies proclaim they are “agile” and do “two week sprints” when it is nothing more than chaos and rhetoric.6 - So... I'm pretty much dead inside. But today I laughed in a meeting. Nearly died of laughter. We're currently understaffed for various reasons, especially the ongoing migrations etc. So a lot of projects are currently in "maintenance" mode (e.g. no new features) - cause we lack the necessary man power. The meeting was more or less: Team: We had an ongoing discussion in the team regarding logging and possibilities of tracing and XY suggested we implement OpenTelemetry in *all* projects in the next weeks, can we do that?" Sometimes I'm not sure If I'm in a sitcom for torture experts.3 - In some malls here in russia we casually have home depot stuff vending machines, right next to usual snack ones.1 - so... not really a rant because i'm happy to be in the long-term zenlike state where i don't really give a fuck about anything anymore, but... so today's my birthday (thanks in advance for all the semi-mandatory "cheers" reactions and such) the agency i do temp jobs through sends money weekly (for the one week back) (which is the main and only reason i use them). they arrive at friday 12:25, so that's when i know to go "check" by withdrawing it, and it's also awesome because it's the best time to provide funds to reward myself (by booze/weed) at the end of the week. last week, nothing came in. i called them and learned it was due to the contact person in the company i did job in being too late on sending the agency list of people who showed up at the work, i was told it's gonna arrive one week later together with the proper payment for the week-1,so effectively i was one week without any money (literally), but on the next week double was going to arrive, which is nice. that next week of double was now. i found out that no double arrived, only single-value payment. i called them to ask why. i was told that what arrived was the late payment, and the dude in company was again late with sending the presence list, so the other payment, for the proper week's work, will be a week late again. so... that kinda ruined my financial planning tor tge week that's going to happen. i guess my point (if i have any) is... funny how when someone fucks up, there's nobody for me to be angry at and hold responsible in any way, but when i have delays in my work due to delays upstream, nobody gives a shit about my excuses and it's my fault and i should have compensated, it was my responsibility and duty, and me not doing it (to my own detriment, for someone else) is me failing. funny how the subjective dynamics of the world always somehow works out in a way where everyone else fucks up and i either have to suck it up and be okay with it otherwise i'm a selfish unreliable entitled asshole, or suck it up and extinguish their fire for them, otherwise i'm a selfish unreliable entitled asshole XD anyone else noticed this in their life? how does it work? what is the factor that decides whether you're in the "suck it up" class or the "fuck it, someone else will suck it up" class? doesn't seem to (just) be the money(flow), i've seen this thing happen even in situations where the money/client dynamics were flowing the opposite way to what would be natural for the shit fall direction.4 - - Since roughly 1 year ago I have been making "leftoff" comments in my code, whenever a work day ended or so, with a few notes on what I was doing and what I was about to work on next. And I recommend it, I think that's good practice. Because I forgot to do it on friday and I have no GOD DAMN CLUE what I was working on : - Got some detailed feedback from Booking.com, upon asking. I answered all the questions right. But they said I am not ready for a Sr PM role (which might be true). Here are three points that I captured from the feedback: 1. Focus on details 2. Clear and better reasoning for WHY 3. Realistic over idealistic scenarios While it makes me feel low that I didn't make it but this feedback will surely help me overcome the challenges and clear interviews in future. On to the next one now. Let's see what comes my way.. One thing for sure, there is lots and lots to learn for me yet. One thing I surely lack is articulating my thoughts and keeping things crisp while conveying the information aptly. Anyone has any tips/resources on how to improve in this area?14 - The company I'm working for now (fortunately as a consultant) is now rebuilding its data structure. To do so they chose to use YANG :) What next breakthrough technology should we go for, coffescript?3 - Started new job at startup and finished all the development environment setup started development it was going smooth for one week.all the created API were working fine on the next day morning without any changes API's were giving cors error.asked my senior what must be the problem he said bypass cors and figure out the problem after trying for 1hrs i couldn't figure out what was the problem but API's were back to normal without any changes. then after sometime same day in zoom call i asked what was the problem he said show me the error but I couldn't reproduced the same cors error he then lectured me for 1 hrs and after that he said that learn to solve by your own dont come with silly mistake like this to me. I don't know what was the problem he even refused me show to what the problem was.6 - Not necessarily a DEV rant, but a rant nonetheless. This day sucks. So first, my bus got late 25 minutes, because entire city decided that it will take a car - because it was raining horizontally. At some point I was doing 1 km in 10 minutes. Then my train got delayed by 5 minutes. So l had to do a little bit of cardio and ran to the next bus from station to school. When I finally made it - surprisingly 5 minutes before the start of the exam, it turned out that I wasn't even on the list of participants. Which was surprising to both me and teachers, because I was clearly registered on the portal. Well, they hand added me in and let me in. Then I open my laptop, I start it up I try to start the exam. But it said that I don't even have the examination program - even tho I did install it yesterday. So I had to quickly download it and reinstall it. Then I could finally write the Project Management exam. Thankfully the exam went fine, I feel confident about the results, but it’s like everything tried to make sure I am not gonna make it - Right to repair by Corsair My mouse has double click glitch... To disassemble the mouse, first skates need to be peeled off and destroyed in order to get to mounting screws... I was unable to find those skates online, so I reached directly the Corsair to check if they sold them. Of course they don't sell them... Next I tried to find professional shop. I found one willing to replace switch for 50$ while brand new mouse costs 60$. FUCK YOU CORSAIR7 - - Company Emails that tell you who they are what believe in. How they were the market leaders since the stone age. what their values are what their holistic approach to life is. How they are diversifying inclusiveness to include diversity. And how all of this bull shit ties into you being a ideal employee of the organisation Just to get you to fill a damn form. Makes me wish the next attempt at human extinction succeeds.4 - Our school had for an open source way of dealing with home schooling and managing the school network and so on. Now the government forced a "proprietary" system on our school and everyone hates it. The teachers didn't want it the pupils didn't want it but who cares "what we do is the best". Btw the proprietary system costs a fuck load of money even though they just mixed many open source projects and made it their own proprietary thing. And this company now get's loads of money for their shitty system that never really worked once since we got it. They blocked so many ip's that we can't even access google and it's services on the school wifi and the bandwith dropped severely with the new system. Oh and many random ip's e.g. one of my vps is accessible but the other one not. Discord is blocked. Web whatsapp. And so on... Now.... I need to learn for tests next week and need to access that stuff on the portal but... Now they decided to switch the LDAP server to the new system and since a few hours i can't access this fucking thing. It seems like the platform now contacts the new server which isn't even up and running.... Never change a fucking running system.... Oh and we got smart boards and it runs on android and they didn't block adb. Now i installed clash of clans on one of those things. Haha whoops. These boards cost 7000€ and have security patches from 2 years ago....and Android 87 - Tip: Write `throw new Error("problem: <your task for next Monday, and your last thoughts about that>") at the end of your test-file. Then you come back to work after the weekend and know exactly where you left off! Thank me later, as I thank my Friday-4pm-me1 -:... - - As expected, I take a single day of PTO and I get a whole bunch of emails about stakeholders needing help and requests for website improvements. I have 14 days of PTO that I have to use in the next two months, so stakeholders gonna get a rude surprise when they see my out of office response almost every other day.1 - - Worst: Realizing there were crippling and horrible bugs in software that got shipped to customers. Also realizing that we truly don't know the amount of technical debt that contributed to these bugs. My most terrifying comment from a colleague: That software was written on a weekend and the dev was getting 3 hours a sleep a night. One of the bugs I found I was fighting for almost a year to even find what was causing the bug. Best: Finding those bugs and eradicating them. Having confidence that the bugs we know about are truly dead and gone. Til we meet again...next...3 - - -- Best -- > Submitted my notice of termination for my current job > Found a new job starting next year > Can switch from Windows to Linux/MacOS in new job > Got more time to work on personal projects due to the pandemic -- Worst -- > Huge amount of software restrictions (current job) almost got several projects at work canceled. Maybe its important to say that the core business of my current workplace is auditing so there are a lot of law regulations which then apply in the softwaredevelopment process. > New managers that do not have the slightest clue of what they're doing > Online Teambuilding events > Absurd amount of segmentation of tools and also different coding guidelines that are used at work. E.g. one team uses jira, another trello, another github issue tracker and so on. - !dev There are two weeks left until the PhD application results are published. But I'm having such awful nervous breakdowns. I don't even know, if it's anxiety or if I'm literally dying inside from something else. From an almost-heart-attack today when I got a trivial and unrelated bad-news email, to keep having weird dreams about things like end of the world and post-apocalyptic life, or being jumpy all the time. ... And it's not like it's life or death, I know that. I know that I can do other things if this doesn't stick. I know things will workout the way they should; I know all of those. But there's just something destroying my physical and mental health right now, and I don't even know if it's just the anxiety for the next big step in my career, or something else, or how I should deal with it. ... Anyways, amannoyed - I've read some posts about how bad Windows is lately and I'm just wondering how some can break their installations so bad.. I mean like multiple BSODs just for installing updates, or just don't get their windows to work at all. I've been using win next to Linux(Debian/Ubuntu) for quite some time now and never had those kind of problems, also on pure Windows 7/10 PCs.2 - Had a fine day, but all of a sudden existential dread kicked in. Then I noticed a bug right next to me, got a sheet of paper and let it out. Thanks for lifting my spirits2 - - Hey guys, i joined a new company a week ago. In the offer letter they mentioned the working hours from 9:30pm to 6:30pm but today an HR told me to be online till 7:30pm. I refused. Guys i really cant sit for so long in front of the computer. 9:30 to 6:30 is a good time, but i cant sit for more than that. Also after 6:30 i meet my friends everyday. I dont know what to say to them the next time they ask me to sit for so long. If they want employees to sit for so long then why dont they mention it on offer letter?8 - - I - I gave a technical interview today and here is summary how it went . interviewer asked me to login to leetcode account then . Interviewer :- "Open this problem( he gave link) and open submission section". Me :- "Yes sir" I opened it and I have solved that in past . Interviewer :- "okay so you have solved this one so let's move to next question(2nd)". I opened it and again I have already solved that in past. Then he gave 3rd and it was also solved by me already . Then he said " Okay now I will share with you this problem which you have not solved and I am sure ". He gave me a hard problem which I actually haven't solved . I would have solved the first 3 , the 4th one was actually hard and I was not able to optimise my code on time . sometimes life is really tough 😪. he could have asked anyone of them 😕.7 - If you ask any sane person "hey, do you want to get some disease with fever, headache and potential risk of dying?", I doubt anyone will say "yes". But if there exist a way to prevent it with a proven efficacy from both evidence-based medicine and science, why not get it today? I'm not even talking about covid. Why people are not getting their flu shots? How's that logic works? You mean you don't want disease, but you also don't want to take any measures to prevent it? Every time in late autumn people get cold. For a sane person, one such case with themselves is enough to say "hey, I don't want this to happen again the next autumn". Yet people do nothing. I can't understand this. And this is only a flu. Hepatitis will destroy your liver and potentially will destroy your whole life, so why avoid vaccination?10 - - We kinda feel the feature you lead was messy because even though you brought up valid use cases and we decided to postpone the development of those till the next release, the user wanted them and we pressured you to get it done in a couple of days…which lead to a slightly buggy less than perfect release…so yeah, even tho you saved our asses for secretly starting development of those extra use cases beforehand we won’t showcase it as a successful release. - Management1 - - - - I officially gave up on this semester of college! ✨🍻🎉 I'm coming back next year, but until then, I'm glad to disappoint my family3 - Normal colleagues pick the right slack channel and post a message there. My colleague picks a random channel that has no relation to dev at all and posts a question/request there. He must be using a random script to pick the next channel name :D - Confession: I don't feel like working. At all. I'm so in need of a vacation. I spend 3/5 days gaming at home and do my sprint assignments in the last two, because I'm so fucking good at what I do. Been working like this for weeks now. Last summer vacation I really had was fucked up by a PO calling me about the project expectations wanting me to really explain the technical decisions to stakeholders, because the schedule kept getting shorter and that caused me huge amounts of anxiety. I left the company next year. They even contacted me later asking if I had any interest coming back. No fucking chance. Didnt have any vacation days for last summer. Now I'm in a really nice position where I don't have to really give a shit about the project I'm working on so I can just ignore work completely during my vacation. Gonna delete my email from my phone and disconnect Slack. Fuck work - Why the fuck is gradle so horrible. I literally have no idea why anyone would ever use this thing (other than being forced too because somehow the rest of the world is using it). Every plugin has an arbitrary DSL that you have to magically know by piecing together enough snippets. At that point, no one is actually intuiting anything based on the beauty of the DSL, every build is a frankenstein of different snippets that were pasted from different versions of gradle blog posts or SO posts. And if you do get it o work then the DSL changes, or it isn't compatible with another plugin. I just want to write a fucking integration test in Kotlin. Can I just add an `integrationTest` task in `tasks` right next to `tasks.test`? No, obviously it goes in the `kotlin jvm() compilations` section, DUH. The first thing anyone in the universe should have asked is "how is this better than literally hand writing a makefile"? At least then I would be able to see the commands that it ran. Now I'm googling how to make the new jvm-test-suite plugin work when you're using the Kotlin plugin but every single result on Google for `jvm-test-suite kotlin` just returns the docs for jvm-test-suite (whose snippets obviously didn't work in my project) because those doc pages have "Kotlin" written above each of the gradle snippets. Please just end this. Oh and dev rant sucks too. It thinks anything separated by dots in a url.2 - I'm having a break from coding for the next hour. So, please tell me....what's the best bread maker to buy?5 - I gave a rant yesterday about this. But I have to say it again because it's so gratifying. It went like this Me: "you should patch the module instead of using it for your python unit test." Them: "You keep telling me this, but maybe there is a better way" Me: "there is, I'm telling it to you" Next day, Code review. Me: "You need to change this" ... silent on the issue ... On a call... Me: "You need to patch the module. Don't mess up the namespace." Them: "I don't think so, X did the work" (In my head: then what did you do) Me: "We can grab whoever you like Y, X. Let's see if X is busy" ... X isnt busy, hops on call 45 seconds later. Me: "we're using the module, we should patch this' X: Muses the thought for 2-3 seconds. X: "yeah... Yeah we probably should patch that" Moral of the story, don't take shit personally unless your right... Then relish in. But if your right and X says otherwise, you can always + a rant. - was wondering how many years will I get for killing muggles who approach me with ideas about the "Next Facebook Idea" after hearing I am a programmer?! Would be possible to be freed of all charges?2 - I'm wondering if devs would still play that russian roulette in linux if the one drawing the short straw gets it's GPU fried up 🤔 Or at least somethibg like that.2 - Spends months on a clearly laid out project. Finally gets to the end. "Great stuff, well done - now let's start the next section of it" "...the what now?"2 - - - Greetings, fellow JS devs What change do you want on the next breaking version of JS? I would say use square bracket instead of curly bracket for object. What do you think?30 - Steve Jobs talking about gigabit internet, cloud and SaSS in ‘97... watching old Jobs videos from 90s when Steve was at Next and just after back to Apple with great ideas and fresh mind, damn he saw that all in 90s - Me: "But what if I fuck it up?" Him: "Well, don't fuck it up". When asking about what the user should do next in case they make a mistake and wanted to correct it. It was a turning point in my dev life.1 - Do you ever meet peopao awesome that you literally have to stop and process it through.. Just met one such guy at my new workplace and as soon as he opened his mouth, I could sense that dude is fucking next level personality.4 - Kids these days and their ultrasonic scalpels. Back in _my_ day, we were doing sugreries with _real_ scalpels made of bare metal. Who cares that ultrasonic ones are way less invasive and it heals faster! If you’re using an ultrasonic scalpel, you’re not even a real surgeon. What’s next? Computer does a surgery for you while you wiggling around the controllers? WHAT DO YOU MEAN ITS ALREADY BEING DONE!? What happened to this country!4 - I've recently done 2 interviews in the past 2 weeks, I did 3 stages for the first one and failed the last stage. I felt devastated. I did the 2nd one Which had written and oral, I feel like I failed oral,results are yet to come out. I have 2 interviews next week and I have no energy to prepare. I feel lost and tired of preparation - How to reproduce: - have a single login form for admins and ordinary users - add a second button right next to 'login' which reads 'login as admin' in order to have a separate login for them - release a new version of software with this change solely and changelog informing about it - have customers admin tell you everybody is complaining about not being able to login with thwor admin accounts5 - Client breaks website and i’m the one trying to fix things. For two unplanned hours i’ve been trying to help and instead of a thank you i get a thanks for nothing message. I’m not responding to this client next time. Fuckn bitch2 - Please give us back the simple linefeed. There is a huge difference between just starting the next sentence on a new line and having it seperated by an empty line.1 - - When you bust your ass developing a site for a client, bend over backwards with changes - pushing the rest of your extremely large queue further and further behind, just to come in to a cancellation request from someone else at said company. 😡 We had really good rapport and the site looked amazing, and all they give me is "we're going in another direction". 😡 Why do people so this when the site is already finished?!? So rude! Before you comment telling me to charge upfront next time or whatever I work for a huge company so none of that is in my control. - - every day my boss says he'll review the requirements for our product. every day he forgets to do so. every day he asks where the update for the next stage is. every day i remind him. every day he forg ---2 - - Best typescript - I needed to learn it for a project and I like it, I know java and javascript and it is something in between of those two that makes writing enterprise web applications easier, it’s nice that you can debug it directly in chrome, it makes things easier Worst docker, Dockerfiles - devops tools - amount of shell commands inside them and mangled && to make everything running in one file layer makes those unreadable mess that you need to think twice to understand, there is no debugger for it, you do everything with try and see what happens, there is actually no real dev toolset for devops and that sucks, since you got builder images that makes things more mangled than before, it’s clearly missing some external officially approved scripting language or at least FUNCTION and WITH LAYER and indentation / parentheses syntax and they still trying to make it flat, why are you doing that ? as a result next to Dockerfile cause you can’t import multiple ones you get bunch bash scripts with mangled syntax and other crap that is glued together to make a monster - and this runs most of current software on this planet2 -. - I chose my next milestone as a dev. I’m gonna ask a question on stackoverflow. I just need a question 🤔10 - -... - My last night : - Had nothing much to work on - Opened an anime site to spend sometime. - Clicked on some really good shows. - Realized full screen isn't working on that page. - Fired up JS Console , spent next 30 minutes trying to get the video part full screen. Failed!! - Opened up Google & navigated through stackoverflow looking for the fix. Still couldn't do it. - Cursed the website for having a bad design. - Left the site.8 - -. - This is more of an advice seeking rant. I've recently been promoted to Team Leader of my team but mostly because of circumstances. The previous team leader left for a start-up and I've been somehow the acting Scrum Master of the team for the past months (although our company sucks at Scrum generally speaking) and also having the most time in the company. However I'm still the youngest I'm my team so managing the actual team feels a bit weird and also I do not consider myself experienced enough to be a Technical lead but we don't have a different position for that. Below actions happen in the course of 2-3 months. With all the things above considered I find myself in a dire situation, a couple of months ago there were several Blocker bugs opened from the Clients side / production env related to one feature, however after spending about a month or so on trying to investigate the issues we've come to the conclusion that it needs to be refactorised as it's way too bad and it can't be solved (as a side note this issue has also been raised by a former dev who left the company). Although it was not part of the initial upcoming version release it was "forcefully" introduced in the plan and we took out of the scope other things but was still flagged as a potential risk. But wait..there's more, this feature was part of a Java microservice (the whole microservice basically) and our team is mostly made of JS, just one guy who actually works as a Java dev (I've only done one Java course during uni but never felt attracted to it). I've not been involved in the initial planning of this EPIC, my former TL was an the Java guy. Now during this the company decides that me and my TL were needed for a side project, so both of us got "pulled out" of the team and move there but we've also had to "manage" the team at the same time. In the end it's decided that since my TL will leave and I will take leadership of the team, I get "released" from the side project to manage the team. I'm left with about 3 weeks to slam dunk the feature.. but, I'm not a great leader for my team nor do I have the knowledge to help me teammate into fixing this Java MS, I do go about the normal schedule about asking him in the daily what is he working on and if he needs any help, but I don't really get into much details as I'm neither too much in sync with the feature nor with the technical part of Java. And here we are now in the last week, I've had several calls with PSO from the clients trying to push me into giving them a deadline on when will it be fixed that it's very important for the client to get this working in the next release and so on, however I do not hold an answer to that. I've been trying to explain to them that this was flagged as a risk and I can't guarantee them anything but that didn't seem to make them any happier. On the other side I feel like this team member has been slacking it a lot, his work this week would barely sum up a couple of hours from my point of view as I've asked him to push the branch he's been working on and checked his code changes. I'm a bit anxious to confront him however as I feel I haven't been on top of his situation either, not saying I was uninvolved but I definetly could have been a better manager for him and go into more details about his daily work and so on. All in all there has been mistakes on all levels(maybe not on PSO as they can't really be held accountable for R&D inability to deliver stuff, but they should be a little more understandable at the very least) and it got us into a shitty situation which stresses me out and makes me feel like I've started my new position with a wrong step. I'm just wondering if anyone has been in similar situations and has any tips or words of wisdom to share. Or how do you guys feel about the whole situation, am I just over stressing it? Did I get a good analysis, was there anything I could have done better? I'm open for any kind of feedback.2 - My job search is so frustrating. Despite having a job for two years and my Bachelor’s degree being almost complete (less than a year left) over half of the jobs give me an instant rejection because I don’t have a college degree (yet). The worst part is knowing that if I apply next year they would probably invite me to an interview.4 - Even though my coding bootcamp was pretty shitty, I did make friends with the person seated next to me on the first day. We were assigned seats next to each other. We bonded over our thoughts of “we’re adults wtf is up with assigned seats” and “I would never sit at the back of the classroom.” She really helped me out when I didn’t understand some things in class. I helped her with notes on days when she was absent. Even though we don’t socialize much after bootcamp, I still consider her a great friend.1 -. - My mind is so clear when I stop caring about my work. I was clearly stating the problems I have been facing, I was clear for the next steps, I was clear what's been blocking us. :) - Up all damn night making the script work. Wrote a non-sieve prime generator. Thing kept outputting one or two numbers that weren't prime, related to something called carmichael numbers. Any case got it to work, god damn was it a slog though. Generates next and previous primes pretty reliably regardless of the size of the number (haven't gone over 31 bit because I haven't had a chance to implement decimal for this). Don't know if the sieve is the only reliable way to do it. This seems to do it without a hitch, and doesn't seem to use a lot of memory. Don't have to constantly return to a lookup table of small factors or their multiple either. Technically it generates the primes out of the integers, and not the other way around. Things 0.01-0.02th of a second per prime up to around the 100 million mark, and then it gets into the 0.15-1second range per generation. At around primes of a couple billion, its averaging about 1 second per bit to calculate 1. whether the number is prime or not, 2. what the next or last immediate prime is. Although I'm sure theres some optimization or improvement here. Seems reliable but obviously I don't have the resources to check it beyond the first 20k primes I confirmed. From what I can see it didn't drop any primes, and it didn't include any errant non-primes. Codes here: Your gotos should be nextPrime(), lastPrime(), isPrime, genPrimes(up to but not including some N), and genNPrimes(), which generates x amount of primes for you. Speed limit definitely seems to top out at 1 second per bit for a prime once the code is in the billions, but I don't know if thats the ceiling, again, because decimal needs implemented. I think the core method, in calcY (terrible name, I know) could probably be optimized in some clever way if its given an adjacent prime, and what parameters were used. Theres probably some pattern I'm not seeing, but eh. I'm also wondering if I can't use those fancy aberrations, 'carmichael numbers' or whatever the hell they are, to calculate some sort of offset, and by doing so, figure out a given primes index. And all my brain says is "sleep" But family wants me to hang out, and I have to go talk a manager at home depot into an interview, because wanting to program for a living, and actually getting someone to give you the time of day are two different things.1 - - me. - Does anyone even use AWS CDK? I saw something about CDKv2 getting released and immediately made up my mind about it and just want to validate my opinion. I'm having a hard time thinking of a case where I would need to use yet another layer of bullshit to deploy cloud infra. It's bad enough with terraform(which I far prefer over cloud formation). But now you can use python or node? What's next, deploying with XSLT? I'm partially ranting, because I know someone on my team is going to show this as the "new thing" and I'll be stuck maintaining my code...as code--and that really pisses me off. I'm also legitimately curious on how many of you have run across this being used successfully and for what problem did it solve?10 - It's seriously fucked up how you just suddenly realize that you're getting old just with what you eat and drink. I never drank alcohol, but instead I sometimes drink sodas. The fucked up thing is that now I've noticed if I down a 1.5L bottle of soda with sugar in it, my motivation is gone the next day. I'm down, I'm irritated, tired, I just can't bring myself to work at all. The moment I open my IDE and start writing a function I just feel incredibly frustrated and wanna smash the keyboard and close the computer. I just want to lie on the couch and watch Netflix or game all day. That's so fucked up. Now I gotta stop drinking sodas so I can stay mentaly healthy?! Aargh? - "Just let me know when you're done (today) with that handful of JIRA tickets that are not reproducible, have no description, and include no error information. We need to get them into the next release." Yeah. Yeah, I'll let you know real soon. - - hey devs, hope you all are doing good.. I was frustated by my salary.. I mean in this job I am good but I didn't got the expected growth.. So I find a job .. but before resigning because I know my boss is cool atleast he will listen .. so I leave him a message that I wanted to do more.. and got the other offers.. He said no worries.. we will match your package.. but now you can be associate TL and handle the team also.. I took the offer.. atleast I am satisified. The thing is new team is mostly are dumbo :( Will see how long I can pull.. or I am hoping my next rants will be something like.. I will join as junior dev pr same salary.. just take me out from this fucking TL role.. because I know what team is going to do.. someone stuck.. ask TL.. someone have internet issue ask TL.. don;t know css.. ask TL.. dont know logic.. ask TL. its look like I have to be google for team Anyways will see how it goes.. I wish me luck Ohh yeah if you are in TL roles.. could you share your experience please2 - So I've just been proposed by my (now ex) team leader to be the next team leader. I'm scared to death because this is something completely new to me. What are your views on the move from development to team leader? How did you handle the transition?4 - Do I waste a couple of hours to write a re-usable tool to make this setup process less of a slog Or do I slog through it to make sure it's done on time then make the tool to make next month easier/faster Decisions decisions 😮💨🤔 - I need to help out my manager to interview angular developer candidate which I don't have any experience on Angular development. I was darn nervous interviewing those people, relying on some reading on angular documentation, articles and tutorials but after few interviews. I manage to get into the momentum to conduct interview smoothly. After two weeks of doing it, now I'm kinda understand Angular thanks to some great candidate explaining those concept clearly ( hope you get hired on the next round of interview).2 - - Why the fuck isnt pythons tabbed loop thing something that's configurable? So many things to like about python, but is there someone on this planet who actually likes this feature? Trying to use it in Jupyter notebook (browser) is a nightmare, because tab will focus on next ui element. Or am i missing something?13 - UUUUUUUUSELES PRODUCT OWNER! "Backlog refinement" .. let's do planning! Who does what next sprint?! What about this epic, how is it coming along?! LOOK AT THE FUCKING BACKLOG! USELESS CUNT!4 - - I finally got the clarity on my relationship. Atleast I think I did. I am officially done with Microsoft. I mean the only useful and sensible products left are Outlook and Excel. Funnily both the products have hit their maturity stage and now MS is trying to bloat them. But still to a reasonable extent. What other MS products are worth touching? Wait.. I legit can't think of any now. Next on tagret, Google and Apple. Lol Perhaps only Apple product I ever want to interact with will be (future tense) Apple Music (well because lossless and the fact that that the product is the reason for existence of the company). NGL Steve had the right vision on Music. They tagged things right in their iTunes catalogue. But then MTV happened. And now Spotify is the new MTV. Fuck me in ass someone. So only Google? Well I have already sold my soul to them. What's more remaining?8 - - - - This is a rant about the passion of programming and building in the business world (AKA corporate/startup world) I speak for myself and I believe many programmers out there who set out on their journey into the world of programming by a certain interest kindled some time when they first wrote their first line of code. We innocently eager, and dream of working for large fancy companies and start making money while doing the thing we love doing the most. And then... reality hits. We find that most companies are basically just the same thing. Our supposedly creative and mind-challenging passion is now turned into mundane boring repetitive tasks and dealing with all kinds of bazaar demands and requirements. You suddenly go from wanting to change the world to "please move this to left by 10 px". And from experience that drives people to the extent of hating their jobs, and hating the very thing they were once so very infatuated with. One narrative I see being pushed down the throats of developers (especially fresh young eager developers with no experience) mostly by business people/owners is "WORK FOR PASSION!". I personally heard one CEO say things like "It's not just about a salary at the end of the month. IT IS ABOUT A MISSION. IT IS ABOUT A VISION"...bla...bla...bla. Or "We don't work for money we work for passion". Yeah good luck keeping your business afloat on passion. What irritates me the most about this, is that it is working. People today are convinced that doing shit jobs for these people are all about passion. But no one wants to stop for a second and think that maybe if people are passionate about something, even if that thing is in the field in which they work, they're not passionate about working for someone else doing something they hate? If I am really working for "passion" why don't I just quit and go work on something that I am ACTUALLY passionate about? Something that brings me joy not dread? It's a simple question but it's baffling to me why no one thinks about it. To me personally, jobs are just that; jobs. It's something to make a living and that's it. I don't give a fuck if you think you're building the next "innovative", "disruptive", "shitluptive" thing :D. Unfortunately that is viewed as "negative limited mentality". I am quite passionate about programming and making things, but I am not so passionate about building your stupid app/website with a glue code everywhere - Looking through a staffing website’s photos of recruiters. They all literally look the same from a distance. Like NPCs generated by the game’s AI. “Which character would you like to pick to ruin the next stage of your professional development?” Can someone smarter than me make a game that actually hilariously simulates job searches? I’d play that for the mere catharsis and entertainment value - So... I've been looking for a week on why my machine was braking tools on every piece... Found out yesterday, it was machining without water.... Told the engenheir (my direct boss)... Started working at midnight and was the same... Decided to fix it, besides the fact that I'm a temp and shouldn't be doing his job... Can't fix it... To many broken pieces.... Well a few metal pipes like straws and some rubber bands and its fixed for now... I really can't understand why a engenheir gets 10x more money and can't bother to fix the machines.... Well I know why... He's not the one paying for new ones when these brake. Next: other machine Is working without oil... And no, I'm not messing with that... In a few months they will just have to buy a new one - I feel bad for bootcampers. Their schools tell them to apply for a job even if they don’t have all the qualifications because they will learn on the job. That’s fine if you’re applying for an upgrade in the same career path. But when you’re changing careers, a lot of jobs don’t necessarily have time to invest in you like that. I do have respect for those who DM me on Slack and ask if the job is open to new bootcamp grads. At least they are taking the initiative to ask and not sulking that they’re not good enough. I tell them “this role requires experience in x. If you have that, then apply” because I don’t actually know they’re not qualified. I was like them before. It’s hard to get the first job and sometimes it’s a lot of luck. But the first job will make getting the next one easier. At least they’re not recruiters trying to convince me to pay them to fill the role -. - Friday is always such a significant day because you know what's up next? WEEKEND BABY but I am up since 4am after four hours of sleep (it's 5am now), because well life sometimes sucks like that, and the only thing keeping my brain from going gaga is work so I am working since 4am to probably 7,8pm Fml and wish me luck8 - - - Somebody: (whinwy) we need something to log into nonprivileged technical accounts without our rootssh proxy. We want this pammodule pam_X.so me: this stuff is old (-2013) and i can't find any source for it. How about using SSSD with libsss_sudo? Its an modern solution which would allow this with an advantage of using the existing infrastructure. somebody: NO I WANT THIS MODULE. me: ok i have it packaged under this name. Could you please test it by manipulating the pam config? Somebody: WHAT WHY DO I NEED TO MANIPULATE THE PAMCONFIG? me: because another package on our servers already manipulates the config and i don't want to create trouble by manipulate it. Somebody: why are we discussing this. I said clearly what we need and we need it NOW. we have an package that changes the pam config to our needs, we are starting to roll out the config via ansible, but we still use configuration packages on many servers For authentication as root we use cyberark for logging the ssh sessions. The older solution allowed additionally the login into non-rootaccounts, but it is shut down in the next few weeks after over half an year of both systems active and over half an year with the information that the login into non-privileged accounts will be no more.7 - I recently built an automated payout functionality for bank-to-bank transfers, and we initially looked at using the pain.001 XML schema to do it. Luckily, we ended up finding a service that has a simple REST API to do this instead. (Thank god we didn't go with the XML method, I know how much of a headache that could become, I can imagine the treasure trove of memes with naming an XML schema with the name PAIN) Anyway, for one of our big-brained product managers, this will forever be the infamous "XML Task" that he continues to ask about and bring up. I've already clarified a few times that we have long chosen a solution process that has nothing to do with XML, but to no avail, it will forever be his "XML Task". Wonder what name he'll pick next time we need XML in a solution? "Second XML Task?" Let's just keep the mental overhead idiot train going!3 - I'm planning to switch from ownCloud to Nextcloud in the next weeks. Does anyone have experience with that or maybe some advice? Aside from creating Backups.7 - - Living abroad during corona times is shit. Trying to visit the family back home... 2019: it's too risky, I won't chance it 2020: still too risky, I won't chance it, even though technically I can now 2021 - Jan to Oct: I can go now, but I can end up getting stuck at the other side. I'll wait just a bit longer 2021 - November - right, quick, I'll book just THREE short days to say hi to the family... BOOKED 2021 - days later: LOCKDOWN AGAIN MOTHERFUCKER! Your flights are GONE! Try again next time fool!2 - Programming at a job to me is no longer creating something fun and valuable; it's more like figuring out why shit doesn't work, con-stant-ly. It' s like coming in to your desk every morning, dreading the day because there's yesterday's shit to fix. "Hmm, what shall today be like? Oh yes, troubleshooting why my database model doesn't work, redesign it completely and break my mind over db details. The next day? Having to redesign my classes to implement new patterns because apparently the current design isn't good enough." Even if you work on new deliverables, that's just new problems in disguise anyway. Pleasant? Not really. lol.3 - - you know what's good to do in example code? ( ͡° ͜ʖ ͡°) just frickin struct { someshit1, someshit2} someshits then define 'someshit' as a standalone var after it and use them all next to each other constantly instead of just having them wrapped up or seaparated1 - My current work... 3 years of formation... 3 years of experience... And I didn't know the basics to operate the machines used here. Also I'm only getting minimum wage and I'm a temp so fuck it. I already knew to much for what I'm paid. Also... Extra formation for the next job :p - - I guess I just try to make a features list for "my next thing (now 3% smaller!)", instantly become a customer, demand way too many features, then get lost in the to-do list aand I'm writing another devRant. Nice. - Lets write the next big thing (tm)! Rules: one line per post in any language. I'll start: while(true){14 - !dev (feel free ignore my rambling) Fuck my piece of shit landlord that doesn't want me to provide a next tenant because they already have someone (without visiting, I believe they have some shady dealing since I noticed a pattern in regards to the last two flats that changed tenants) and doesn't give a shit about the kitchen I had built in / says "maybe you can leave it [for free] or maybeee the owner will take it but don't expect as much as 500 or 600€ and whatever the owner proposes is non negotiable [...] if you wanna take it out we'll buy a new one" (i.e. fuck you we rather pay 4k for a new one than give you the 2k it's worth) (╯° □°) ╯︵ ┻━┻ aaaaargh this certainly doesn't help my stress levels which are already 11/10 with the flat search1 - -. - So I got accepted into a Master’s programme for CS - which is kinda cool but hardly unexpected. Guess I should feel elated about it, but honestly, I don’t know how I feel about it. Really it only adds additional complexity into the next few years of my life: I feel a little gutted that I have to switch over to my plan B regarding the sporting side of my life (there’s no way I can work full-time, study AND train for IM simultaneously - there’s just not enough hours in a day…), but that’s okay. At least I had a plan B knowing I might get accepted to these studies now. What it really complicates is decisionmaking regarding this:... At my current workplace, I have officially 2hrs each week + an additional full work day a month to use for studying during work hours (in reality I tend to use more than that because I can, whenever there are no pressing matters need doing), and my gut is saying that’s unlikely to be possible in a consultancy position in a startup. Maybe it is, I don’t know. Need to ask. In life, very few things are ever straightforward, aren’t they? But hey, at least I get to do my Master’s and I get to do it in a quality university! - I had some fun times in college. Me: This book is too outdated, we need updated information for the video capture card presentation. I'd do it but this time I'm busy. Teammate: I'll do it. Me: oh wow really? Thanks! Next week... Teammate: here, take a look. I updated the information Me: Yeah, I can see that all of those 10+ year old models have some fresh google search information in them. Thanks. - - My in-laws seem allergic to keeping fruit on the fridge. In a 40° heat. No wonder half the fruit are spoiled by next morning. My algorithm for storing produce: Is it fresh produce? => (No) use another algo. (X) Is it potatoes or onions? => (Yes) put it in a bowl in a closet (X) ::: Put it all in the fridge, dammit. - Not too sure why I am required to be in the office when we all know the next code I will be writing is next year.2 - - Need advice: So this recruiter from AWS reached out to me for a SDE job. I said yes I’m interested and scheduled an interview. She didn’t show up. I politely said would you like to schedule another time 30 min after the empty session was over. She said yes. Then the day after she sends me a message saying they can’t hire students. (I’m 20 yo second year electrical engineering student but I have decent dev experience ~3-4 years) I tell her I’m not planning on continuing with my 3rd year next fall. She says no I’m hiring from the “industry only”. And I try to tell her I’ve never had an internship before and all of this work experience is all by myself and not university related….she stopped responding…..what am I supposed to do? It’s not the first time that this has happened. They see “graduating 2024” they immediately bounce. I tried hiding what year my university education starts/ends….didn’t work…5 - You know what I noticed about a lot of people is that they just can't abide when people make them uncomfortable or work off their natural guilt impulses to not do things they shouldn't do, so they can be happy content fucking monsters. really bothers them when you point out that they are in fact fucking monsters and no amount of warping the next or youngest generation into accepting horrific abuse or writing it off as a small thing, makes it so. it's like what is in fact the worst thing that can happen prior to reaching the point of brain damage and severed limbs is not so much reduced in severity from the perspective of their brainwashed underclass, but downplayed to the point where it is just endured, and then later replicated. thick glass wearing fucked up monsters !19 - On minute I'm on the track to success feeling all fly and so then the next mintue I'm losing myself like what the F - Anyone else using Algo in the Android app but can load the next other when they reach the end of the first?1 - - Microsoft Teams login says password is incorrect then and for a captcha I type it again but fails... I'm like wtf... Could it be the captcha... Which I entered in all lowercase It doesn't say the captcha is case sensitive though.. Next few times it gives me captchas with k... Teehee me like 5 tries to login Are we trying to verify passwords/humanness or whether I can somehow tell the difference between K and k?1 - What is ruby and why should i learn it. also whats the next step after learning fundamentals in Python?13 Top Tags
https://devrant.com/search?term=next
CC-MAIN-2022-27
refinedweb
19,762
71.34
These minutes have been approved by the Working Group and are now protected from editing. (See IRC log of approval discussion.) Note that some names appear in red on this page. That simply indicates that the name is linking to a wiki page which does not yet exist. Users should click on that link and create a page for themselves. If they already have a page, they can link from this 'canonical name' page to their existing page by making the page content be "#REDIRECT otherPage", where otherPage is the name of the other page. OWL WG Teleconference 10 Oct 2007 Attendees - Present - Achille Fokoue, Anne Cregan, Bernardo Cuenca Grau, Bijan Parsia, Carsten Lutz, Conrad Bock, Conrad Bock, Doug Lenat, Elisa Kendall, Evan Wallace, Giorgos Stoilos, Ian Horrocks, Ivan Herman, Jeff Pan, Joanne Luciano, Markus Krötzsch, Rinke Hoekstra, Sandro Hawke, Tommie Meyer, Uli Sattler, Vipul Kashyap, Alan Ruttenberg, Boris Motik, Peter Patel-Schneider - Regrets - Deborah McGuinness, James Hendler, Michael Sintek - Chairs - Alan Ruttenberg, Ian Horrocks - Scribe - Bijan Parsia Minutes ADMIN (20 min) Agenda: Ian Horrocks: Procedural preliminaries; everyone should get better at getting connected so as to not take up telecon time with us getting connected ... Please check the using zakim and the ettiquette page. ...and importantly, help the scribe! PROPOSED regular telecon time Wednesday 1300 East US Ian Horrocks: Anyone have a problem with this time? No, let's move on. Agenda amendments Ian Horrocks: no amendments Telecons and IRC Sandro Hawke: Normally irc logs are public. So we need to decide that Lots of agreement both on and off IRC. Scribe Alternation Ian Horrocks: For scribing, please check the list and let chairs know if you can't make your turn Regrets to be posted on meeting wiki Alan Ruttenberg: if someone doesn't want to use the wiki for regrets, send email *directly* to Alan Ruttenberg (not to the list) Peter Patel-Schneider: Problem with the wiki involving colons and usernames Markus Krötzsch: tools like showing all-contributions-of-user require using User: namespace discussion about names in wiki names Alan Ruttenberg: if you have issues with your wikiname, contact alanr or sandro *off list* Sandro Hawke: everyone should create a wiki account in the next few days Ian Horrocks: Accounts are important because much of the work of the group will be done via the wiki Alan Ruttenberg: Wiki authorship policy: Every page is editable by all users. If you want to protect a page from arbitrary edits *say so on the page*. Default is that all users are free to edit. Alan Ruttenberg: question about who gets write access (e.g., out side of group Sandro Hawke: If the edits are friendly, just do it. If you expect disputation, try the talk page first Alan Ruttenberg: alanr has ambitious plans for using the wiki; e.g., doing the specs there; test cases; etc. Alan Ruttenberg: keep an eye on the recent changes Peter Patel-Schneider: Is the wiki support full html? Charter review (scope, deliverables, timeline) Ian Horrocks: We're not going to do the charter review on the phone -- good homework. Participants shoudl read the charter very carefully and review the input documents for next week Ian Horrocks: and the issues list, etc. Alan Ruttenberg: we need to transistion the various issue lists Bijan:This was my question/point Ian Horrocks: The timeline is aggressive. Need first draft of the deliverables soon. So we need to identify potential land minds. Please review documents with an eye to these landmines. Vipul Kashyap: Combined issues list is a great idea, but many issues from the origianl list are closed. What should deal with it? Vipul Kashyap: Some closed issues weren't *accommodated* but deferred. How do we reopen? Ian Horrocks: Prefer to make a new issue for that general agreement Vipul Kashyap: Could the issue transfer person add all the resolutions and rationales? Ian Horrocks: prefer that the burden is on participants who want to champion an old closed issue should propose it fresh Sandro Hawke: Note about issues: chairs have discrestion about actually raising issues. Participants propose issues. Ian Horrocks: We must recall the timeline. So issues are better raised as early as possible. Sub-groups to work on deliverables Ian Horrocks: A proposal for organization: We should have subgroups for the deliverables. ... And we would use the wiki heavily for the collab document editing/authoring. ... Feedback? Vipul Kashyap: How to create the subgroups? Divide by technology or by application. Ian Horrocks: We'd divide by *documents*. Ian Horrocks: i.e., each subgroup is "in charge" of a corresponding document Ian Horrocks: That's a point. If you look at the owl, there's a lot of overlap. Might be good. Bijan Parsia: I meant more that e.g., syntax changes affect the semantics document Joanne Luciano: Useful for getting crosschecks Bijan Parsia: I agree, but this is orthogonal to my point that the *language* decisions are separate Vipul Kashyap: Can we have an overarching example or use case to drive the documents. Ian Horrocks: We do have a requirements document deliverable Ian Horrocks: but requirements can eat up a lot of time so we can't presume that the other documents can wait on them. ... any objections? Alan Ruttenberg: I agree with Ian that we have a clear set of goals for the language extensions (originally motivated from OWLED), but don't want to close off new use cases. Given the timeline, if you think there's something missing based on a use case Alan Ruttenberg: please bring it to group attention Bijan:Can we defer some of these discussion to the mailing list? Vipul Kashyap: Perhaps a table mapping constructs to use cases? I.e., how each cosntruct meet the use cases Alan Ruttenberg: A user guide could incorporate that. It would be a good idea to have this connectability in the guide. Bijan Parsia: Are subgroups "merely" editors or do they advance the technical work Ian Horrocks: function as traditional editors Bijan Parsia: So, we use the traditional proposal mechanism via email? Bijan Parsia: I think that only an hour is hopeless Relationships to other W3C groups Choose contact persons Ian Horrocks: There are a bunch of WG to coordinate with. People should look at the related groups in the charter and people should see if they are interested to be the contact person for select group Alan Ruttenberg: The role of the contact person is to monitor the target group activity for things which might affect owl and informing them about things from owl that might affect them. Review of the RIF document Alan Ruttenberg: Reviewing the RIF BLD should be an activity of owlwg. Peter would be a good person to do that. Sandro Hawke: Whenever we do a review as a group, we generally delegate but they can publish that individually or as a group. A group decision is needed for the latter Ian Horrocks: Everyone is personally welcome to review RIF Sandro Hawke: It's a lot of wg work to do a group review Ian Horrocks: but given the importance of the relationahip it's worth doing a group review RESOLVED there will be WG review of RIF BLD Sandro Hawke: publishing morotoriam meants that the BLD will not formally published for a few weeks Manchester F2F: Estimate attendance Manchester F2F: Outline objectives Ian Horrocks: Objectives of the f2f: Time is pressing (again). F2F can get a lot of work done. Alan Ruttenberg: Horrocks: People should feel free to ask questions on the mailing list, esp. if there's something they don't understand. Bijan Parsia: Are we aiming for FWD before the f2f or decide there? what's the publication schedule. Ian Horrocks: we'll take that up next week. I'll add it on the agenda. Ivan Herman: have the local arrangements page been updated? Ian Horrocks: Yes. There is a new la page linked from the wiki Summary of Action Items [NEW] ACTION: Alan to clean up User: prefix on wiki [recorded in] [NEW] ACTION: alanr to check for HTML support in mediawiki, esp. to support the semantics document [recorded in] [NEW] ACTION: Peter to Review the RIF BLD draft and report back to OWL-WG for discussion [recorded in] [End of minutes] Minutes formatted by David Booth's scribe.perl version 1.128 (CVS log) $Date: 2007/10/10 18:40:38 $ original html converted to wiki markup using with edits by AlanRuttenberg Further processing done to convert that wiki-text into template calls, and canonicalize user names to those used by tracker, in customer software by Sandro Hawke.
https://www.w3.org/2007/OWL/wiki/index.php?title=Teleconference.2007.10.10/Minutes&mobileaction=toggle_view_mobile
CC-MAIN-2015-27
refinedweb
1,436
60.55
The included source files will allow you to use the Office 2000 and VS.NET style file dialogs in your applications, which will appear on all versions of Windows 95/98/NT/Me, as well as 2000. To use the dialog, simply add the source files to your project and use the standard CFileDialog calling functions to show / manipulate it. For example, to load the dialog with an "Open" button, use the code below BXFileDialog dlg(TRUE); dlg.m_ofn.lpstrTitle = "Open Document"; dlg.DoModal(); To show the save button, use FALSE instead of TRUE when creating the dialog: BXFileDialog dlg(FALSE); dlg.m_ofn.lpstrTitle = "Save Document"; dlg.DoModal(); To show the bitmap preview panel, pass TRUE as the second parameter to the constructor: BXFileDialog dlg(FALSE, TRUE); dlg.m_ofn.lpstrTitle = "Save Document"; dlg.DoModal(); To allow the dialog to be resized, pass TRUE as the third parameter to the constructor: BXFileDialog dlg(TRUE, FALSE, TRUE); dlg.m_ofn.lpstrTitle = "Open Document"; dlg.DoModal(); To set up file type filters, add this before your call to DoModal() (this is optional):'; dlg.m_ofn.lpstrFilter = szFilter; Below I will attempt to explain using it instead of the default file 'open' / 'save as' dialogs. I will use a method that in my opinion is easier than using multiple versions of the same code for each of your documents' Open and Save As commands. To do this, define ( public) and add the following function to your CWinApp derived class (make sure you include the dialog header in this file). BOOL CMyApp::DoPromptFileName(CString &fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpen, BOOL bPreview, BOOL bSizing) { BXFileDialog dlg(bOpen, bPreview, bSizing);'; CString strTitle; strTitle.LoadString(nIDSTitle); dlg.m_ofn.lpstrFilter = szFilter ; dlg.m_ofn.lpstrTitle = strTitle; dlg.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH); dlg.m_ofn.hwndOwner = AfxGetMainWnd()->m_hWnd; if (dlg.DoModal() == IDOK) return TRUE; return FALSE; } Also make sure that in your app header, theApp is defined, to make it easier to access your class. Eg: extern CMyApp theApp; Now open your document source file. Make sure it includes the main app header (so you can use theApp), and unless you already have an override for OnOpenDocument(...), use the class wizard to insert one for you. Then modify as follows ( IDS_FILE_OPEN is a string ID for the dialog title): BOOL CMyDoc::OnOpenDocument(LPCTSTR lpszPathName) { if (!theApp.DoPromptFileName(lpszPathName, IDS_FILE_OPEN, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, TRUE, FALSE, TRUE)) return FALSE; return TRUE; } The override the documents' OnSaveDocument(...) function, as follows (again, IDS_FILE_SAVEAS is a string ID for the dialog title): BOOL CMyDoc::OnSaveDocument(LPCTSTR lpszPathName) { if (!theApp.DoPromptFileName(lpszPathName, IDS_FILE_SAVEAS, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, FALSE, FALSE, TRUE)) return FALSE; return TRUE; } That is all you need to add. If you have more than one CDocument derived class, simply repeat as necessary. If you want to display different commands in the OK button's drop-down menu, you can override the virtual void OnFileTypeChange(DWORD dwNewFilterIndex) function. This function is called whenever the user selects a new file type from the 'File Type' combo box. The dwNewFilterIndex parameter contains the index of the new file type in the array passed to the dialog in the OPENFILENAME structure you pass to the dialog before showing it. You can switch on this DWORD to load different commands depending on the file type, e.g.: // destroy the current menu (remove all items) m_btn.m_menu.DestroyMenu(); // recreate the popup menu m_btn.m_menu.CreatePopupMenu(); // add the new items, depending on the file type selected switch(dwNewFilterIndex) { case 0: m_btn.AddMenuItem(ID_START,"&Open",0); m_btn.AddMenuItem(ID_START+1,"Open with &Filter",0); break; case 1: m_btn.AddMenuItem(ID_START,"&Open",0); case 2: m_btn.AddMenuItem(ID_START,"&Open",0); m_btn.AddMenuItem(ID_START+1,"Open As &HTML",0); default: break; // do nothing } In order to make including the dialog in your existing projects as simple as possible, you will no longer need to copy the individual resources to your own project's resource file. To use the resources, follow these steps: #include "cmn.rc"before the final #endifstatement. You have just told the resource compiler to compile the separate resource script (named cmn.rc) when it compiles your project. The header defining the ID's in this script will automatically be made available to you. By default the initial size of the dialog will be that of the static control in the dialog template called IDC_SIZE_TEMPLATE. Changing this size will cause the dialog and all it's controls to be resized too. The width of the grey static control is used to calculate the width of the 'side bar'. You can change the #define CONTROL_GAP to change the default spacing between controls used when updating the dialog's layout. Microsoft Office uses a value of 3. The default for this code is 5, as it looks better (in my opinion). Sizing Support On Windows 98 and NT 5 and later, the default Windows file dialogs can be resized. To enable this dialog to be resized in this way, pass TRUE (or FALSE to disable it) as the third parameter to the dialog constructor. For an example, see the Quick Guide section above. By default, Windows can't display context help for the custom controls we add to the dialog (in this case the 'side bar'), as it is not meant to be there. In order to be able to display context help for the buttons in this bar (and to override any of the default controls), simple make sure you have the HtmlHelp header and library files in your projects include path (freely available from Microsoft - search for HtmlHelp Workshop on MSDN) and compile your project with _USE_HTMLHELP defined. The strings used to display the text in the context help windows is obtained from the string resource in cmn.rc. Refer to the source to see how the DoPopupHelp() function is implemented. Feel free to use this function elsewhere in your projects, without credit. You can now optionally display a 'preview panel' to the right of the listbox, in the same fashion as Office 2000 does. To show this panel, pass TRUE as the second parameter in the creation statement (shown in the examples above). This preview panel will display any images that your system will, using the IPicture interface. You can now make the sidebar buttons appear in the new VS.NET style (see screenshot at the top of this page). To do this, simply call SetAppearance(...) before calling DoModal(), and pass in APPEARANCE_VSDOTNET. E.g.: BXFileDialog dlg(); dlg.SetAppearance(BXFileDialog::eAppearance::APPEARANCE_VSDOTNET); dlg.DoModal(); Possible values to pass to SetAppearance(...) are: APPEARANCE_DEFAULT // Office 2000 APPEARANCE_VSDOTNET // VS.NET There can be many reasons for your project not compiling, but the most common related to the use of this dialog are: _USE_HTMLHELPin the project settings. AfxEnableControlContainer()from your CWinApp::InitInstance()function. You have to override the OnSaveDocument() function for each of your document types, and OnFileOpen() in your main CWinApp derived class, and use the new dialog in place of the old one. See the Using it in Your App section above for an example. Based on the original code by Norm Almond. Maintained by David Wulff. Contains some code by Joel Bernard, Anatoly Danekin, Wes Rogers, Tak^Shoran and Chris Maunder. And a special thank you to all of you who have posted bug reports and/or fixes, or have simply said "Hey, this would be cool...". This code is provided on an "AS-IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. You can use the code and any segments hereof, in any product, commercial or otherwise, provided that any copyright information contained in the source files remains unaltered and intact. If you contribute to the source in any way, regardless of whether you release said changes, you must comment them and identify them as your own to prevent confusion as to the author of said changes. Use of this code in any application gives me marital rights to your first-born daughter. (Okay, maybe not that last sentence...) I would appreciate a quick email [dwulff@battleaxesoftware.com] if you are going to use the code in a commercial application, purely out of interest. You are NOT required to do this, nor are you required to credit the original authors in your application or its documentation. CDN_TYPECHANGEmessage, so you can customise the OK button's drop-down menu. Article content updated to reflect new code. The debug build of the sample program will now General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/dialog/win2kfiledlg.aspx
crawl-002
refinedweb
1,408
56.15
Hi there, I'm trying to write a program which calculates the average mark of three tests but I can't figure out how to do the basic math, I know this sounds stupid but I can't seem to find any examples anywhere. It compiles and runs but when I enter for example 21 for french, 18 for german and 13 for spanish it displays the average 697034459.It compiles and runs but when I enter for example 21 for french, 18 for german and 13 for spanish it displays the average 697034459.Code:#include <iostream> using namespace std; int main() { int pass = 15; int french, german, spanish; int mark = (french+german+spanish)/3; cout<<"LANGUAGE COURSE\n"; cout<<"\n"; cout<<"Enter French mark."; // I don't need the cursor to move cin>> french; // down. cin.ignore(); cout<<"Enter German mark."; cin>> german; cin.ignore(); cout<<"Enter Spanish mark."; cin>> spanish; cin.ignore(); cout<<"Your percentage mark was "<< mark <<".\n"; cin.get(); } i have never done maths in c++ before and I can't find any relevant help anywhere so any links or other help will be very welcome. Calef13
http://cboard.cprogramming.com/cplusplus-programming/75084-problem-numerical-calculations.html
CC-MAIN-2014-52
refinedweb
191
72.76
Define: Static Extension A static extension allows pseudo-extending existing types without modifying their source. In Haxe this is achieved by declaring a static method with a first argument of the extending type and then bringing the defining class into context through using. Static extensions can be a powerful tool which allows augmenting types without actually changing them. The following example demonstrates the usage: using Main.IntExtender; class IntExtender { static public function triple(i:Int) { return i * 3; } } class Main { static public function main() { trace(12.triple()); } } Clearly, Int does not natively provide a triple method, yet this program compiles and outputs 36 as expected. This is because the call to 12.triple() is transformed into IntExtender.triple(12). There are three requirements for this: 12and the first argument of tripleare known to be of type Int. IntExtenderis brought into context through using Main.IntExtender. Intdoes not have a triplefield by itself (if it had, that field would take priority over the static extension). Static extensions are usually considered syntactic sugar and indeed they are, but it is worth noting that they can have a dramatic effect on code readability: Instead of nested calls in the form of f1(f2(f3(f4(x)))), chained calls in the form of x.f4().f3().f2().f1() can be used. Following the rules previously described in Resolution Order, multiple using expressions are checked from bottom to top, with the types within each module as well as the fields within each type being checked from top to bottom. Using a module (as opposed to a specific type of a module, see Modules and Paths) as static extension brings all its types into context.
https://haxe.org/manual/lf-static-extension.html
CC-MAIN-2018-43
refinedweb
279
53.81
Laravel Excel 3.0 Laravel Excel is a package by Maatwebsite that makes working with spreadsheets easy. It’s been out since 2013 and just recently released version 3.0 with some important breaking changes. In their lessons learned post they go through the history of the project and why they have decided to make v3.0 a major breaking change from previous releases: My goal for Laravel Excel 3.0 is to cater our own needs first and only add convenience methods that we need and would use ourselves, instead of re-inventing the PhpSpreadsheet “wheel”. The less code to solve the problem, the easier it should be to maintain. The post is worth checking out specifically to look at opensource from the maintainer’s point of view and how it’s easy to let people change your goals to suit them. This quote is so perfect: Laravel Excel used to be an opinionated PHPExcel but became an un-opinionated Excel for Laravel. Laravel Excel 3.0 is now released and this version mainly focuses on exports and making it as simple as possible and is a complete break from previous versions. Here are some of the highlights from this release: - Easily export collections to Excel - Export queries with automatic chunking for better performance - Queue exports for better performance - Easily export Blade views to Excel To give you an example of exporting in 3.0, take a look at this quick example taken from their documentation. First, create an InvoicesExport class: namespace App\Exports; class InvoicesExport implements FromCollection { public function collection() { return Invoice::all(); } } Next, from your controller initialize the download: public function export() { return Excel::download(new InvoicesExport, 'invoices.xlsx'); } Or get fancy and store it to S3: public function storeExcel() { return Excel::store(new InvoicesExport, 'invoices.xlsx', 's3'); } Of course, these examples just scratch the surface. Check out the Github repo and official docs for more information. As mentioned above, v3.0 focuses on exporting and v3.1 will focus on imports, but as of this time, there isn’t a planned release date yet. Newsletter Join the weekly newsletter and never miss out on new tips, tutorials, and more. Uploading Avatar Images with Spatie’s Media Library By default, the Laravel registration form comes with the name, email, and password fields, but often it’s usefu… Getting Started with Signed Routes in Laravel Laravel includes the ability to create signed URLs and in this article, we’ll work on enabling signed URLs in a…
https://laravel-news.com/laravel-excel-3-0
CC-MAIN-2018-34
refinedweb
418
54.12
>> Flow control in try catch finally in Java programming. Get your Java dream job! Beginners interview preparation 85 Lectures 6 hours Core Java bootcamp program with Hands on practice 99 Lectures 17 hours An exception is an issue (run time error) that occurred during the execution of a program. Some exceptions are prompted at compile time these are known at compile-time exceptions or checked exceptions. If an exception occurs the program terminates abruptly at the line that caused exception, leaving the remaining part of the program unexecuted. To prevent this, you need to handle exceptions. Try, catch, finally blocks To handle exceptions Java provides a try-catch block mechanism. The try block − A try block is placed around the code that might generate an exception. Code within a try/catch block is referred to as a protected code. Syntax try { // Protected code } catch (ExceptionName e1) { // Catch block } The catch block − A catch block involves declaring the type of exception you are trying to catch. If an exception occurs in the try block, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. The finally block − The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of the occurrence of an Exception. Flow control in exceptions In exception handling, you can have try-catch, try-finally and, try-catch-finally blocks. In these, you might have the following scenarios − If Exception doesn’t occur − If no exception raised in the try block the code in the catch block (in try-catch or try-catch-finally) doesn’t get executed. Anyhow the finally block gets executed always (try-finally or, try-catch-finally) If Exception occurs in try-catch − When an exception raised inside a try block, instead of terminating the program JVM stores the exception details in the exception stack and proceeds to the catch block. If the type of exception that occurred is listed/handled in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter and, the code in the (respective) catch block is executed. Example"); } } } Output Given file path is not found If the occurred exception is not handled in the catch block and thrown using the throws keyword. The code in the final block gets executed and the exceptions occur at the run time. Example import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Test { public static void main(String args[]) throws FileNotFoundException{ System.out.println("Hello"); try{ File file =new File("my_file"); FileInputStream fis = new FileInputStream(file); } catch(ArrayIndexOutOfBoundsException e){ } finally{ System.out.println("finally block"); } } } Output Runtime Exception Hello finally block Exception in thread "main" java.io.FileNotFoundException: my_file (The system cannot find the file specified) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at sample.Test.main(Test.java:12) Exception occurs in try-catch-finally The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of the occurrence of an Exception. Therefore, if an exception occurs in a try-catch-finally block. The code in the catch block, as well as finally block, gets executed."); } } } Output Exception thrown : java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed - Related Questions & Answers - Flow control in a try catch finally in Java - Flow control in try catch finally in C# - Try-Catch-Finally in C# - What are try, catch, finally blocks in Java? - Try/catch/finally/throw keywords in C# - Explain Try/Catch/Finally block in PowerShell - How do we use try...catch...finally statement in JavaScript? - Can we write any statements between try, catch and finally blocks in Java? - Why variables defined in try cannot be used in catch or finally in java? - Static Control Flow in Java - Can we declare a try catch block within another try catch block in Java? - Try, catch, throw and throws in Java - The try-finally Clause in Python - Can finally block be used without catch in Java? - Control flow alterations in Ruby
https://www.tutorialspoint.com/flow-control-in-try-catch-finally-in-java-programming
CC-MAIN-2022-40
refinedweb
732
56.25
Ticket #7001 (closed defect: duplicate) Export and then Import fails to install. Error suggests that the ovf file has wrong information Description Exporting an appliance from Windows and Importing to Linux fails now. It looks like the encoding of the OVF file has static information stored in it that will not allow it to be imported. The D:\Shared folder was setup on the guest, but that should not stop the install. It should continue and dis-allow the shared folder information as it has in the past. Now that I know I guess I can always delete the share folders before exporting but that seems like a step that should not be needed plus it makes it a major problem if this were at different locations. At the very least it should be a setting that I can uncheck on the Import screen. Attachments Change History Changed 5 years ago by Perryg - attachment Import-error.png added Changed 5 years ago by Perryg - attachment Windows-XPpro-Bridged.ovf added Changed 5 years ago by Perryg - attachment WrongPrimaryDrive.png added Changed 5 years ago by Perryg - attachment XPpro-Bridged.ovf added New OVF comment:1 Changed 5 years ago by Perryg Update: I removed the shared folder and exported again and Import failed. Seems the SATA on the XP on Windows made Linux mad. No worries I switched it back to IDE on both drives and exported again. Import succeeded but I was presented with found no bootable media. It seems that something in the export Import is broken. It Imported the drives backwards, Primary/Secondary were reversed, but one other thing. I looks like it exported the secondary drive and the Primary drive as one and the original (19GB) file is nowhere to be found. Attaching the Windows screen shot and the Linux import screen shot as well as the Log file from the Linux host of the imported XP guest. Also the new OVF file I did try to switch them around but neither will boot as I suspect the export/import has something bad wrong in it. Changed 5 years ago by Perryg - attachment export-error.jpg added WindowsXP-Original comment:2 Changed 5 years ago by umoeller - Owner set to umoeller - Status changed from new to assigned Thanks for the report. If I see this correctly, we fail because there are platform-specific settings in the OVF such as the shared folder path which doesn't exist on Linux. So the import code should probably issue a warning but not fail. We'll look into this. comment:3 Changed 5 years ago by whiochon I have the same problem. It occurs when there are multiple virtual disk images associated with the machine. Note in the .ovf files attached the UUID of all the images in the <StorageControllers> section at the bottom of the file is the same. They should match the UUIDs of the images listed in the <DiskSection> section at the top of the file, in the same order. I have been able to import the ovf by editing it first to fix the error, and removing the .mf file (otherwise VirtualBox complains as it has also calculated the wrong SHA key on export) comment:4 Changed 5 years ago by javaboyuk I have an export import issue too: export from a solaris host (but has a shared are "/datapool" import onto a windows host, gives error "/datapool" not absolute if you edit the .ovf file to add say c: to path you get a checksum eror on the file as you've edited it! not work arround comment:5 Changed 5 years ago by whiochon Checksum error can be avoided by removing the checksum file (*.mf) But it sounds like the shared folder issue is another issue altogether. comment:6 Changed 5 years ago by TheOtherPhilC My experience is same as whiochon. I have two SATA disks attached to one controller. UUIDs are correct in the DiskSection of the .ovf, but one UUID is listed twice in the VirtualSystem/vbox:Machine/StorageControllers/StorageController/AttachedDevice sections for the relevant controller. As with whiochon, I was able to get past it by renaming the .mf and editing the .ovf with the correct UUID. In my case, there are no shared folders to confuse the issue. The only possible anomaly I can find other than the UUID problem is that while the original VM has one IDE (PIIX4) controller with a single port having a DVD identified as "IDE Secondary Master", the OVF PIIX4 controller has a count of two ports with the DVD attached to port 1. Changed 4 years ago by wgregori - attachment ubuntuMaster.ovf added comment:7 follow-up: ↓ 8 Changed 4 years ago by wgregori I'm having the same problem with a linux export of a linux machine trying to import it to the same linux box. I have the same problem with a window's box. I've attached the ovf file. comment:8 in reply to: ↑ 7 Changed 4 years ago by wgregori comment:9 Changed 4 years ago by myersjj I have this same problem using the latest version 4.0.6. This is quite disturbing :( I'm running Windows 7 x64 with a Linux guest. comment:10 Changed #7941 comment:11 Changed 4 years ago by poetzsch - Status changed from assigned to closed - Resolution set to duplicate
https://www.virtualbox.org/ticket/7001
CC-MAIN-2015-14
refinedweb
899
71.34
Package profiler is a client for the Cloud Profiler service. Usage example: import "cloud.google.com/go/profiler" ... if err := profiler.Start(profiler.Config{Service: "my-service"}); err != nil { // TODO: Handle error. } Calling Start will start a goroutine to collect profiles and upload to the profiler server, at the rhythm specified by the server. The caller must provide the service string in the config, and may provide other information as well. See Config for details. Profiler has CPU, heap and goroutine profiling enabled by default. Mutex profiling can be enabled in the config. Note that goroutine and mutex profiles are shown as "threads" and "contention" profiles in the profiler UI. Functions func Start func Start(cfg Config, options ...option.ClientOption) error Start starts a goroutine to collect and upload profiles. The caller must provide the service string in the config. See Config for details. Start should only be called once. Any additional calls will be ignored. Example package main import ( "cloud.google.com/go/profiler" ) func main() { if err := profiler.Start(profiler.Config{Service: "my-service", ServiceVersion: "v1"}); err != nil { //TODO: Handle error. } } Config type Config struct { // Service must be provided to start the profiler. It specifies the name of // the service under which the profiled data will be recorded and exposed at // the Profiler UI for the project. You can specify an arbitrary string, but // see Deployment.target at // // for restrictions. If the parameter is not set, the agent will probe // GAE_SERVICE environment variable which is present in Google App Engine // environment. // NOTE: The string should be the same across different replicas of // your service so that the globally constant profiling rate is // maintained. Do not put things like PID or unique pod ID in the name. Service string // ServiceVersion is an optional field specifying the version of the // service. It can be an arbitrary string. Profiler profiles // once per minute for each version of each service in each zone. // ServiceVersion defaults to GAE_VERSION environment variable if that is // set, or to empty string otherwise. ServiceVersion string // DebugLogging enables detailed debug logging from profiler. It // defaults to false. DebugLogging bool // MutexProfiling enables mutex profiling. It defaults to false. // Note that mutex profiling is not supported by Go versions older // than Go 1.8. MutexProfiling bool // When true, collecting the CPU profiles is disabled. NoCPUProfiling bool // When true, collecting the allocation profiles is disabled. NoAllocProfiling bool // AllocForceGC forces garbage collection before the collection of each heap // profile collected to produce the allocation profile. This increases the // accuracy of allocation profiling. It defaults to false. AllocForceGC bool // When true, collecting the heap profiles is disabled. NoHeapProfiling bool // When true, collecting the goroutine profiles is disabled. NoGoroutineProfiling bool // When true, the agent sends all telemetries via OpenCensus exporter, which // can be viewed in Cloud Trace and Cloud Monitoring. // Default is false. EnableOCTelemetry bool // ProjectID is the Cloud Console project ID to use instead of the one set by // GOOGLE_CLOUD_PROJECT environment variable or read from the VM metadata // server. // // Set this if you are running the agent in your local environment // or anywhere else outside of Google Cloud Platform. ProjectID string // APIAddr is the HTTP endpoint to use to connect to the profiler // agent API. Defaults to the production environment, overridable // for testing. APIAddr string // Instance is the name. Instance string // Zone is the zone. Zone string // contains filtered or unexported fields } Config is the profiler configuration.
https://cloud.google.com/go/docs/reference/cloud.google.com/go/profiler/latest
CC-MAIN-2022-27
refinedweb
564
52.66
I'm trying to make a simple program that will calculate the area of a circle when I input the radius. When I input a number it works, but when I input something else I'd like it to say "That's not a number" and let me try again instead of giving me an error. I can't figure out why this is not working. from math import pi def get_area(r): area = pi * (r**2) print "A= %d" % area def is_number(number): try: float(number) return True except ValueError: return False loop = True while loop == True: radius = input("Enter circle radius:") if is_number(radius) == True: get_area(radius) loop = False else: print "That's not a number!" When you don't input a number, the error is thrown by input itself which is not in the scope of your try/except. You can simply discard the is_number function altogether which is quite redundant and put the except block: try: radius = input("Enter circle radius:") except (ValueError, NameError): print "That's not a number!" get_area(radius)
https://codedump.io/share/YrWE8Knsx19F/1/valueerror-exception-not-working-in-python
CC-MAIN-2017-09
refinedweb
176
61.5
Introduction: Freeform Arduino, 16 Mhz Resonator, 10K Resistor (Radio Shack #271-1335) 0.1uF Capacitors (Radio Shack #272-135) 3mm red LED(Radio Shack #276-026) 1K Resistor (Radio Shack #271-1321) 6-pin Male Header (as the connector to FTDI cable to upload the sketch) This are the minimum components to get Arduino up and running.). Step 4: How I'm Going to Upload the Sketch? Continue on from the step 3, I prepared to make FTDI connector, using one 0.1uF capacitor, 6-pin male connector, and some leftover hookup wire from other project. Step 5: What Is the Energy Source? According to the ATMega168-20PU datasheet, I knew that the microcontroller could use power 3.3V up to 5V. But I wonder if I could used the 12V Remote Control battery like the one that used in my car remote? I tried it out and found that it is OK, since the 5V Voltage Regulator IC- LM7805 can withstand up to 30 Volt. So, I decided to use 12V Type 23A size 'N' Alkaline Battery (Radio Shack #23-144B) and Size 'N' Battery Holder. I installed the battery holder at the bottom of the tube, approximately below the place that I would placed the microcontroller. The images below show how I installed the battery holder. Step 6: Eyes & Brain After the closer look at what had been done up to this point. It look so organic to me, the FTDI connector look like the mouth and the part of the tube before it was cut out look just like the head of an animal. So I decided to add two LEDs that would connected to pin D13 of ATMega168 to make it more like animal eyes. Some more idea came, I realized that 6 + 8 = 14, which also equal to the number of the pins of the microcontroller on each side. I should used two 6-pin Long Contact Legs Female Headers, and two 8-pin Long Contact Legs Female Headers, so I could reprogram the ATMega168, to use in any project After some trial, placing the microcontroller in place, etc. I decide to place those female connectors along the side, and glue them to the battery holder. And started to solder those legs of the female connectors to the microcontroller pins. Step 7: Is It Alive? Next, I connected 16Mhz Resonator to pins D9, D10 and Ground. And soldered 0.1uF pins to D7 and D8 of ATMega168. Now that I had Freeform Arduino, It's a good time to do a test to see if it alive, and had nothing wrong with it! I loaded the 'Blink.ino' from the Arduino IDE's basic example to check if everything woking. And it did work! But it did not look completed! Well, I had to think of something to make it complete! Step 8: What If, I Add Arms and Legs? Since the "Freeform" design turned toward the animal look, I thought It wolud be a good idea to complete the project by adding the arms and legs to it. But would be the suitable material for it? After another round of looking through the tools box and components case. I came across these 16 Gauge and 18 Guage stem wire, that my wife got them from the Art and craft store, the left over from her fake flowers project. I picked 16 Gauge since it is green color, but later I realized it was not the right decision! I tied two of the stem wires together with the masking tape and a tiny drop of super glue. Then bent those stems to the form of arms and legs. Note: the pictures below was reproduce to show wo I did it. I did not take the pictures while I worked on them. Step 9: Adds a Motor Skill? At this point, I thought, This is the animal which already has brain, and power, but it has nothing to make it moves like the animal. The idea came up, How about making it dance, just added the vibrating motor to the beast? So, I added a small motor, something like a small vibrating motor that is used in the pager. Below is the schematic that I sketched out at the time the idea came up. Following is the lists of the components that I used: BC337 (DigiKey #BC33740TACT-ND) or you could used TIP120 NPN Transistor (Radio Shack #276-2068) , but I found that this component is kind of too big for the project. 1K Resistor (Radio Shack #271-1321) Diode 1N4001 (Radio Shack #276-1101) Pager Vibrate Motor (Radio Shack #273-107) After tested the motor, I realized that the motor pulled a lot of voltage, I decided to add extra battery, CR1220, and Battery Holder (Radio Shack #270-0008). Later I learned that it a discontinue item, Step 10: IR Receiver Another problem rise! How could I control the motor? XBee? No, too big! Bluetooth? No, too expensive! What if I just use IR Receiver, only two buck! That's it! IR Receiver I decided. And here is the components I bought for this project. 38khz IR Receiver (Radio Shack #276-0143) IR LED (Radio Shack #276-640) - Not used in the project just got it for the test process. I used the Poraloid Remote to match with the IR Receiver. ( see Ken Shirriff's blog for the way to do so.) Sketch I used Ken Shirriff's IR Library, and I adapted one of the sample sketch, IRrecDemo.ino, in the library. I also use another example, IRsendDemo.ino, to decode my Polaroid IR remote, to get the value of the Enter button, so I can use the Enter button to turn on the motor. (See detail how to do this on Ken's blog on the mentioned link above.) /* * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv * An IR detector/demodulator must be connected to the input RECV_PIN. * Version 0.1 July, 2009 * */ #include <IRremote.h> #define motorPin 12 #define ledPin 13 int RECV_PIN = 9; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); pinMode(motorPin, OUTPUT); digitalWrite(motorPin, LOW); irrecv.enableIRIn(); // Start the receiver } void dance() { delay(200); digitalWrite(motorPin, HIGH); digitalWrite(ledPin, HIGH); delay(4000); digitalWrite(motorPin, LOW); digitalWrite(ledPin, LOW); } void loop() { if (irrecv.decode(&results)) { //Serial.println(results.value, HEX); // Polaroid RC-50 Remote: ENTER = 0x9C63AC04 if(results.value == 0x9C63AC04) { dance(); } irrecv.resume(); // Receive the next value } } Step 11: Conclusion The project was a success in term of hardware and appearance, it is a function "Freeform" Arduino. But in term of working properly, it was not! As I mentioned in step 8, the arms and legs are too big! (16 Gauge wire). It's too stiff for the small vibrating motor to handle. And I will have a new version, smaller wires as arms and legs, bigger motors. Here is a video. Video Recommendations We have a be nice policy. Please be positive and constructive. 8 Comments A super post. It is appreciated. can you share file for me :( niudiuhiu@gmail.com Interesting!! This is so cool! Thanks. can i use a p2n222ag transistor? instead of BC337 Pranav, you mean P2N2222A?? I never used P2N2222A before. I used either TIP120 or BC337. But I found this webpage that mentioned the P2N2222A as part of the kit to control toy motor. Take a look! Hope this help. thnxx for ur help
http://www.instructables.com/id/Freeform-Arduino/
CC-MAIN-2018-17
refinedweb
1,248
75
375 terms · rita pmp questions. One project manager wants to focus on the advantages of the matrix-type organization they all work in for their projects. Which of the following would he mention? A. Improved project manager control over resources B. More than one boss for project teams C. Communications are easier D. Reporting is easier Answer A Explanation Remember that if the question doesn't state what it is comparing to, it is comparing to a functional organization. Two project managers have just realized that they are in a weak matrix organization and that their power as project managers is quite limited. One figures out that he is really a project expediter and the other realizes Explanation D Explanation The main drawback of the projectized organization is that at the end of the project, the team is dispersed but they do not have a functional department (home) to which to return. Answer A Explanation In a functional organization, the project manager has the least support for the project and has little authority to assign resources. Choices C and D Explanation Because a project done in a matrix organization involves people from across the organization, communications are more complex. Answer B Explanation In a functional organization, the functional manager is the team member's boss and probably also the project manager's boss.. All of the following are parts of the team's stakeholder management effort EXCEPT: A. Giving stakeholders extras. B. Identifying stakeholders. C. Determining stakeholders' needs. D. Managing stakeholders' expectations. Answer A Explanation Giving stakeholders extras is known as gold plating. This is not effective stakeholder or quality Explanation This is an example of a project expediter position because you are not evaluating the change, looking for impacts, etc. You are merely implementing others' requests. In this case, you are acting as the project expediter. projects though the stakeholders are her friends. Answer C Explanation Some students historical. Management by objectives works only if: A. It is supported by management. B. The rules are written down. C. The project does not impact the objectives. D. The project includes the objectives in the project charter. Answer A Explanation The best answer is the need for management to support the objectives.. $100,000 would be considered projects and would involve project management. Answer C Explanation Because orders are numerous and of short duration, this situation is a process, not a project. The previous project manager for your project managed it without much project organization. There is a lack of management control and no clearly defined project deliverables. Which of the following would be the BEST choice for getting your project better organized? A. Adopt a life cycle approach to the project. B. Develop lessons learned for each phase. C. Develop specific work plans for each work package. D. Develop a description of the product of the project. Answer A Explanation Choice B would help improve subsequent phases, but would do nothing for control and deliverables. Choice C would help control each phase, but would not control the integration of the phases into a cohesive whole. Choice D would help, but not help both control and deliverables for each phase. Effective project management requires a life cycle approach to running the project. Choice A is the only answer that covers both control and deliverables.. Answer: B Explanation This work has entered the manufacturing stage. Manufacturing is generally considered a process, not a project, as it is not temporary. A project charter will not be appropriate here. One of your team members informs you that he does not know which of the many projects he is working on is the most important. Who should determine the priorities among projects in a company? A. The project manager B. The project management team C. The project management office D. The team Answer C Explanation Because the question talks about priorities among projects, this cannot be the role of the project manager (choice A), the project management team (choice B), or the project team (choice D). A market demand, a business need, and/or legal requirement are examples of: A. Reasons to hire a project manager. B. Reasons projects are initiated. C. Reasons people or businesses become stakeholders. D. Reasons to sponsor a project. Answer B Explanation These are all reasons projects are initiated. Answer A Explanation choice A. There are other tools that are better for accomplishing the things listed in the other choices. Lessons learned are BEST completed by: A. The project manager. B. The team. C. The sponsor. D. The stakeholders. Answer D Explanation The best answer is stakeholders, as their input is critical for collecting all the lessons learned on each project. The term stakeholders includes all the other groups. Consideration of ongoing operations and maintenance as part of a project. A project is temporary with a definite beginning and end. D. Be viewed as a separate project. Answer C Explanation Remember the definition of a project: temporary and unique. Operations and maintenance are considered on-going activities, not temporary. Therefore, such work is not considered a project or part of a project... Project Management Processes CHAPTER THREE The project team has just completed the initial project schedule and budget. The NEXT thing to do is: A. Identify risks. B. Begin iterations. C. Determine communications requirements. D. Create a bar (Gantt) chart. Answer C Explanation Communications requirements and quality standards are needed before risks (especially risks relating to communications and quality) can be determined (choice A). Iterations (choice B) cannot begin until the risks are identified, qualified, quantified, and responses developed. These then create the need to revise the WBS and other parts of the project management plan. A bar chart (choice D) would have been done during the creation of the schedule, so it cannot be the next thing. Of the choices listed, determine communications requirements (choice C) is the best. A detailed project schedule can be created only after creating the: A. Project budget. B. Work breakdown structure. C. Project management plan. D. Detailed risk assessment. Answer B Explanation In the project management process, the project budget (choice A), project management plan (choice C), and detailed risk assessment (choice D) come after the schedule. The only answer that could be an input is the WBS. Which of the following is NOT an input to the initiating process group? A. Company processes B. Company culture C. Historical WBSs D. Project scope statement Answer D Explanation Notice the question asks which is NOT an input to the initiating process group. Did you read it correctly? The project scope statement (choice D) is an output of the planning process group. Did you select choice A? Companies should have processes in place for hiring resources, reporting, and managing risks on projects (to name only a few). Does yours? The project sponsor has just signed the project charter. What is the NEXT thing to do? A. Begin to complete work packages. B. Verify Scope. C. Start integrated change control. D. Start to create management plans. Answer D Explanation The project charter is created during the initiating process group. Therefore the question is asking what is done next in either the initiating process group or the planning process group. For this type of question, you should look for the choice that occurs closest to the process group you are in. Choice A is done during the executing process group. Choices Band C are done during the monitoring and controlling process group. Choice D is the best choice, as it is part of the planning process group. experience of the sponsor (choice A) might sound like a good idea, the sponsor is a stakeholder and understanding the stakeholders. The only correct choice is the activity list (choice B). A project manager does not have much time to spend process, making choice C incorrect. Metrics are part of the quality management plan, making choice D incorrect. Choice B is best, as the activity list is created immediately before the network diagram. A project manager gets a call from a team member notifying him that there is a variance between the speed of a system on the project and the desired or planned speed. The project manager is surprised because that performance measurement was not identified in planning. If the project manager then evaluates whether the variance warrants a response, he is in what project management process? A. Initiating B. Executing C. Monitoring and controlling D. Closing Answer C Explanation Even though the measurement was not identified in planning, the project manager would still have to investigate the variance and determine if it is important. Therefore, the project manager is in the project monitoring and controlling process group. A team member notifies the project manager that the activities comprising a work package are no longer appropriate. It would be BEST for the project manager to be in what part of the project management process? A. Corrective action B. Integrated change control C. Monitoring and controlling D. Project closing Answer C Explanation If you chose another part of the project management process, you probably forgot that the situation needs to be evaluated by the project manager before recommending a change or entering integrated change control.. Closing B. Monitoring and controlling C. Executing D. Initiating Answer C Explanation This situation does not describe an actual measurement (a monitoring and controlling activity) but rather a meeting occurring during project executing talking about control issues. Which of the following would be the MOST appropriate thing to do during the initiating process group? A. Create a detailed description of the project deliverables. B. Get familiar with the company culture and structure as it relates to the project. C. Identify the root cause of problems. D. Ensure all project management processes are complete. Answer B Explanation Choice A occurs during the planning process group as part of creating the project scope statement. Since you must already have problems in order to determine their root cause, choice C must occur during the monitoring and controlling process group, not initiating. Choice D occurs during the closing process group. All of the following must be performed during project initiating EXCEPT: A. Identify and document business needs. B. Create a project scope statement. C. Divide large projects into phases. D. Accumulate and evaluate historical information. Answer B Explanation A project scope statement (choice B) is generally created in project planning. Closure includes all of the following EXCEPT: A. Determining performance measures. B. Turning over the product of the project. C. Documenting the degree to which each project phase was properly closed after its completion. D. Updating the company's organizational process assets. Answer A Explanation Performance measures are determined earlier in the project so they can be used to measure progress during the project, making choice A the only correct answer to this question. The first phase of your project has come to an end. What should you ensure is done BEFORE beginning the next phase? A. Verify that the resources are available for the next phase. B. Check the project's progress compared to its baselines. C. Confirm that the phase has reached its objectives, and have its deliverables formally accepted. D. Recommend corrective action to bring the project results in line with project expectations. Answer C Explanation A phase or project must be formally closed and accepted. In which process group does the team measure and analyze the work being done on the project? A. Initiating B. Executing C. Monitoring and controlling D. Closing Answer C Explanation During the monitoring and controlling process group, project performance is measured, and needed changes are identified and approved. Which process groups must be included in every project? A. Planning, executing, and closing B. Initiating, planning, and executing C. Initiating, planning, executing, monitoring and controlling, and closing D. Planning, executing, and monitoring and controlling Answer C Explanation All five process groups are addressed in each project. It is the responsibility of the project manager to determine the level of attention to give to each process group. Effective project integration usually requires an emphasis on: A. The personal careers of the team members. B. Timely updates to the project management plan. C. Effective communications at key interface points. D. Product control. Answer C Explanation This question is asking for the most important of the choices. Think about what is involved in integration: project management plan development, project management plan execution, and integrated change control. In order to integrate the project components into a cohesive whole, communication is key when one activity will interface with another, one team member will interface with another, and any other form of interfacing will occur. Choices Band D are parts of the monitoring and controlling process group, while integration includes more than control. Choice A falls under project management plan execution.). When it comes to changes, the project manager's attention is BEST given to: A. Making changes. B. Tracking and recording changes. C. Informing the sponsor of changes. D. Preventing unnecessary changes. Answer D Explanation Project managers should be proactive. The only proactive answer here is preventing unnecessary changes. A project manager has managed four projects for the company and is being considered to join the project management office team. The following is discovered during the evaluation of his performance. The project manager's first project had an ending cost variance of -500, used two critical resources, needed to rework the project charter during project executing and was ranked 14th in priority within the company. The second project finished with a schedule variance of +100, was completed with a vastly compressed schedule, and received a letter of recommendation from the sponsor, but the product of the project was not used. The third project had 23 percent more changes than expected, had an SPI of 0.90, and 25 open items in the issue log when the project was completed. Each of these projects had a cost budget of US $1,000 and 20 to 28 percent more changes than others of its size. The project management office decided not to add this project manager to the team. Which of the following BEST describes why this might have happened? A. The project manager has only managed low-priority projects, and he had to compress the schedule, showing that he does not have the skill to work in the project management office. B. Issue logs should not be used on projects of this size, showing that the project manager does not have the knowledge to work in a project management office. C. The project manager did not effectively involve the stakeholders, showing that he does not have the knowledge to work in the project management office. D. The project manger had two critical resources on his team and still needed to rework the project charter, showing that he does not have the discipline to work in the project management office. Answer C Explanation This is a very confusing question. Notice all the distracters that mayor may not be relevant? Since most project schedules are compressed by the project manager during project planning, choice A is not a logical reason and so cannot be the best choice. Issue logs can be used on smaller projects, which means choice B is not the best choice. The number of critical (or hard-to-get) resources noted in choice D has no bearing on the need to rework the project charter. Since it does not make logical sense, it cannot be the best choice. Take another look at the second and third projects. In the second project, the product of the project was not used. This implies many things, including the possibilities that either the project manager did not identify the requirements of all the stakeholders or that the business need of the project changed dramatically and the project manager did not notice. This indicates a major flaw in the project manager's abilities. In the third project, there were 25 concerns of the stakeholders that were not addressed before the project was completed. Again, this shows a major lack of project management knowledge. The needs of the stakeholders and not just the sponsor must be taken into account on all projects. This makes choice C the best choice. All of the following are parts of an effective change management plan EXCEPT: A. Procedures B. Standards for reports C. Meetings D. Lessons learned Answer D Explanation A change management plan includes the processes and procedures that allow smooth evaluation and tracking of changes. Lessons learned (choice D) are reviews of the processes and procedures to improve them; they are not part of the system. A work authorization system can be used to: A. Manage who does each activity. B. Manage what time and in what sequence work is done. C. Manage when each activity is done. D. Manage who does each activity and when it is done. Answer B Explanation Who does each activity (choices. A project is plagued by changes to the project charter. Who has the primary responsibility to decide if these changes are necessary? A. The project manager B. The project team C. The sponsor D. The stakeholders Answer C Explanation The sponsor issues the project charter and so he or she should help the project manager control changes to the charter. The primary responsibility lies with the sponsor.!) Double declining balance is a form of: A. Decelerated depreciation. B. Straight line depreciation. C. Accelerated depreciation. D. Life cycle costing. Answer C Explanation We need to know that double declining balance is a form of depreciation. That eliminates choice D. We also know that double declining balance is a form of accelerated depreciation, eliminating choices A and B. Therefore, C is the correct response. You are a new project manager who has never managed a project before. You have been asked to plan a new project. It would be BEST in this situation to rely on during planning in order. You are taking over a project and determine the following: Activity B has an early finish (EF) of day 3, a late finish (LF) of day 6, and an early start (ES) of day 2. Activity L is being done by a hard-to-get resource. The cost performance index (CPI) is 1.1, and the schedule performance index (SPI) is 0.8. Based on this information, what would you be more concerned about? A. Float B. Resources C. Cost D. Schedule Answer D Explanation You may not understand this question until you review the rest of the book. Come back to it. This question tries to integrate a lot of information and test your ability to discern what information is relevant to the question. Though some figures to calculate float are provided (choice A), there is no information to say that the float is a problem. Most projects have hard-to-get resources (choice B). The question does not give an indication that having hard-to-get resources is a problem. CPI (choice C) is greater than one, so cost is not something to worry about. SPI is less than one, so choice D is the best answer. A project management plan should be realistic in order to be used to manage the project. Which of the following is the BEST method to achieve a realistic project management plan? A. Sponsor creates the project management plan based on input from the project manager. B. Functional manager creates the project management plan based on input from the project manager. C. Project manager creates the project management plan based on input from senior management.. All of the following are parts of Direct and Manage Project Execution EXCEPT: A. Identifying changes. B. Using a work breakdown structure. C. Implementing corrective actions. D. Setting up a project control system. Answer D Explanation A project control system (choice D) is set up during the planning process group, not during project executing. Did choice B confuse you? A WBS is created in project planning, but can be used to help manage the project during project executing. The wording here was not creating the WBS but using the WBS:'. You have been assigned to manage the development of an organization's first Web site. The site will be highly complex and interactive, and neither your project team nor the client has much experience with Web site development. The timeline is extremely aggressive. Any delay will be costly for both your firm and the client. You have a project sponsor and have achieved agreement and Sign-off on both the project charter and the project management plan. Client personnel have been kept fully informed of the project's progress through status reports and regular meetings. The project is on schedule and within the budget, and a final perfunctory review has been scheduled. Suddenly you hear that the entire effort may be cancelled because the product developed is totally unacceptable. What is the MOST likely cause of this situation? A. A key stakeholder was not adequately involved in the project. B. The project charter and project management plan were not thoroughly explained or adequately reviewed by the client. C. Communications arrangements were inadequate and did not provide the required information to interested parties. D. The project sponsor failed to provide adequate support for the project. Answer A Explanation A single high-level executive can end an entire project if he or she is not satisfied with the results, even if that person has, by choice, been only tangentially involved in the project. It is critical to ensure that all of the final decision makers have been identified early in a project in order to ensure that their concerns are addressed. The project manager has just received a change from the customer that does not affect the project schedule and is easy to complete. What should the project manager do FIRST? A. Make the change happen as soon as possible. B. Contact the project sponsor for permission. C. Go to the change control board. D. Evaluate the impacts on other project constraints. Answer D Explanation The other impacts to the project should be evaluated first. Such impacts include scope, cost, quality, risk, resources, and customer satisfaction. Once these are evaluated, the change control board, if one exists, can approve or deny the change. Your company just won a major new project. It will begin in three months and is valued at US $2,000,000. Explanation As you work on a project, you need to constantly reevaluate the project objectives and how the project relates to other concurrent projects. Is your project still in line with corporate objectives? If the other project will impact yours, you need to be proactive and work on options now. You are a project manager who was just assigned to take over a project from another project manager who is leaving the company. The previous project manager tells you that the project is on schedule, but only because he has constantly pushed the team to perform. What is the FIRST thing you should do as the new project manager? A. Check risk status. B. Check cost performance. C. Determine a management strategy. D. Tell the team your objectives. Answer C Explanation Before you can do anything else, you have to know what YOU are going to do. Developing the management strategy will provide the framework for all the rest of the choices presented and the other activities that need to be done.-critical path activity? (Until the project float is in jeopardy means that there is float and, thus, it is not on the critical path.) So is the issue the non-critical defined in the change management plan (choice B). Because they weren't, the project manager will waste valuable work time trying to figure it out after the fact. a project manager do FIRST? A. Ask the team member how the need for? You are asked to prepare a budget for completing a project that was started last year and then shelved for six months. All the following would be included in the budget EXCEPT: A. Fixed costs. B. Sunk costs. C. Direct costs. D. Variable costs. Answer B Explanation Sunk costs (choice B) are expended costs. The rule is that they should not be considered when deciding whether to continue with a troubled project. This project is chartered to determine new ways to extend the product life of one of the company's medium-producing products. The project manager comes from the engineering department, and the team comes from product management and marketing departments. The project scope statement and project planning are completed when a stakeholder notifies the team that there is a better way to complete one of the work packages. They even supply a technical review letter from? A. Contact the department and complain again about their missing the deadline for submission of scope. B. Look for how this schedule change will impact the cost to complete the work package and the quality of the product of the work package. C. See if there is a way to change from a matrix environment to a functional organization so as to eliminate all the interference from other departments. D. Ask the department if they have any other changes. Answer B Explanation Choice A could be done, but notice that it is not proactive? It would be helpful to get to the root cause of why this department always comes up with such ideas or changes after the project begins. However, this is not the immediate problem, the change is, and therefore choice A is not best. The type of project organization described is a matrix organization. There is not anything inherently wrong with such an organization, nor is there anything wrong in this particular situation that would require it to be changed, so choice C cannot be best. The department's history makes choice D something that should definitely be done, but the proposed change needs more immediate attention. Only choice B begins integrated change control by looking at the impact of one change on other project constraints. Project A has an internal rate of return (IRR) of 21 percent. Project B has an IRR of 7 percent. Project C has an IRR of 31 percent. Project D has an IRR of 19 percent. Which of these would be the BEST project? A. Project A B. Project B C. Project C D. Project D Answer C Explanation Remember, the internal rate of return is similar to the interest rate you get from the bank. The higher the rate is, the better the return. An output of the Close Project or Phase process is the creation of: A. Project archives. B. A project charter. C. A project management plan. D. A risk analysis plan. Answer A Explanation The project charter (choice B) is created in initiating. The project management plan (choice C) is an output of the planning process group. You have not seen the term risk analysis plan (choice D) in this book, so it is unlikely to be the best answer. All of the following would occur during the Close Project or Phase process EXCEPT: A. Creating lessons learned. B. Formal acceptance. C. Reducing resource spending. D. Performing benefit cost analysis. Answer D Explanation Benefit cost analysis (choice D) is done earlier in the project to help select between alternatives. All the other choices are done during closing. Therefore choice D must be the best answer. Which of the following is included in a project charter? A. A risk management strategy B. Work package estimates C. Detailed resource estimates D. The business need the responsibility assignment matrix and other documents. Project history (choice D) is found in the lessons learned and other project documents.. The engineering department has uncovered a problem with the cost accounting system and has asked the systems department to analyze what is wrong and fix the problem. You are a project manager working with? A. Develop a project charter. B. Reestimate the project schedule with input from the engineering department. C. Verify the scope of the new work with the help of the stakeholders. D. Identify specific changes to the existing work. Answer A Explanation question is trying to imply that the new work is a self-contained unit of work, has no overlap with the existing work and needs a different skill set. Therefore, it is generally best to make it a new project. The first step to answering this question is to realize that the work should be a separate project. The second step is to look at the choices and see which relates to initiating a new project. Choice B sounds like the best choice, but only if you did not realize that the new work should be a separate project. Choice C is done during project monitoring and controlling. Choice D is done during project executing. The project charter is developed in the initiating process group. Band C) are done earlier in the project. The lessons learned (choice D) can only be completed after the work is completed. Your company can accept one of three possible projects. Project A has a net present value (NPV) of US $30,000 and will take six years to complete. Project B has an NPV of US $60,000 and will take three years to complete. Project C has an NPV of US $90,000 and will take four years to complete. Based on this information, which project would you pick? A. They all have the same value. B. Project A C. Project B D. Project C Answer D Explanation Remember, project length is incorporated when computing NPV. You would choose the project that provides the most value, in this case the project with the highest NPV. Scope Management CHAPTER FIVE Answer A work breakdown structure numbering system allows the project staff to: A. Systematically estimate costs of work breakdown structure elements. B. Provide project justification. C. Identify the level at which individual elements are found. D. Use it in project management software. Answer C Explanation The numbering system allows you to quickly identify the level in the work breakdown structure where the specific element is found. It also helps to locate the element in the WBS dictionary. The work breakdown structure can BEST be. A new project manager is being mentored by a more experienced certified project management professional (PMP). The new project manager is having difficulty finding enough time to manage the project because the product and project scope are being progressively elaborated. The PMP- certified project manager mentions that the basic tools was used to assist. The WBS helps ensure everyone understands the scope of the work. During a project team meeting, a team member suggests an enhancement to the scope that is beyond the scope of the project charter. The project manager points out that the team needs to concentrate on completing all the work and only the work required. This is an example of: A. Change management process. B. Scope management. C. Quality analysis. D. Scope decomposition. Answer B Explanation The team member is suggesting an enhancement that is outside the scope of the project charter. Scope management involves focusing on doing the work and only the work in the project management plan that meets the objectives of the project charter. The project manager is performing scope management. the change is (choice B) and then meet with the team (choice A), but only if their input is required. The project manager should not just say no (choice C) until he knows more about the possible change. He also should not go to management (choice D) without more information.. A new project manager has asked you for advice on creating a work breakdown structure. After you explain the process to her, she asks you what software she should use to create the WBS and what she should do with it when she. To manage a project effectively, work should be broken down into small pieces. Which of the following does NOT describe how far to decompose the work? A. Until it has a meaningful conclusion B. Until it cannot be logically subdivided further C. Until it can be done by one person D. Until it can be realistically estimated Answer C Explanation The lowest level of the WBS is a work package, which can be performed by more than one person.. A project manager has just been assigned to a new project and has been given the project charter. The FIRST thing the project manager must do is: A. Create a project scope statement. B. Confirm that all the stakeholders have had input into this book might draw you to conclude that the FIRST thing would be to start planning. Wouldn't it be smart to make sure what you have in the project charter is clear and complete before moving on? This is why choice B is the best choice. The construction phase of a new software product is near completion. The next phases are testing and implementation. The project is two weeks ahead of schedule. What should the project manager be MOST concerned with before moving on to the final phase? A. Verify Scope B. Control Quality C. Create Performance Reports D. Control Costs Answer A Explanation The Verify Scope process deals with acceptance by the customer. Without this acceptance, you will not be able to move into the next project phase. You are managing a six-month project and have held biweekly? A. Ask the stakeholder if there are any more changes expected. B. Complete integrated change control. C. Make sure the impact of the change is understood by the stakeholder. D. Find out the root cause of why the scope was not discovered during project planning. Answer B Explanation Notice that there are many things that the project manager could do listed in the choices. The question asks what is the BEST thing to do NEXT. Though they are great things to do, choices A, C, and D are not next. Management of the change is not complete when the Control Scope process is completed. It is important to look at the impact of the change on other parts of the project such as time and cost. Therefore, choice B is the best thing to do next, probably followed by C and then D and A.? A. The project manager did not get buy-in from the manager for the resources on the project. B. The project manager did not create an adequate reward system for team members to improve their cooperation. C. The project manager should have had a meeting with the team member's boss the first time the team member caused trouble. D. The project manager does not have work packages. Answer D Explanation Is this a hard question? The whole discussion of the team member and his actions is a distracter. The real problem is not that the team member is being uncooperative. He is asking a question that many team members want to ask in the real world. How can I tell you how things are going if I do not know what work I am being asked to do? The real problem is the lack of a WBS and work packages; otherwise the team member would not have to ask such a question. Choice A cannot be the answer because the project manager is not losing resources (what is implied by getting the manager's buy-in). Though a reward system (choice B) would help with cooperation, the real problem here is not cooperation. Choice C cannot be the answer because it does not solve the problem at hand (the team member not knowing what he is to do). It solves another problem. If you chose C, be very careful! You can get 10 to 20 questions wrong on the exam simply because you do not see the real problem!. Which of the following is an output of the Collect Requirements process? A. Requirements traceability matrix B. Project scope statement C. Work breakdown structure D. Change requests Answer A Explanation The project scope statement (choice B) is an output of the Define Scope process. The work breakdown structure (choice C) is an output of the Create WBS process. Change requests (choice D) are an output of the Verify Scope and Control Scope processes. A scope change has been suggested by one of the stakeholders on the project. After careful consideration and a lot of arguing, the change control board has decided to reject the change. What should the project manager do? A. Support the stakeholder by asking the board for the reason for the rejection. B. Suggest to the stakeholder that the next change they request will be approved. C. Record the change request and its result. D. Advise the change control board to make sure they create approval processes before the next change is proposed. Answer C Explanation One could do choice A, but there is no reason to think that the board's rejection would not contain an explanation already, since providing that information is commonly done. Suggesting a change process that circumvents the change control board's authority (choice B) is not ethical. There is no reason to think that approval processes are not already in place (choice D). A rejected change should be recorded for historical purposes, in case the idea is resurrected later, and for other reasons. A project manager's scope management efforts are being audited. The cost performance index (CPI) on the project is 1.13, and the benefit cost ratio (BCR)? A. Having to cut costs on the project and increase benefits B. Making sure the customer approved the project scope C. Not being able to measure completion of the product of the project D. Having to add resources to the project Answer C Explanation There are many pieces of data in this question that are distracters from the real issue. Though it is common to have to cut costs (choice A) and add resources to a project (choice D), nothing in the question should lead you to think these will be required in this situation. Customers do not generally approve the project scope (what you are going to do to complete their requirements); instead, they approve the product scope (their requirements), so choice B cannot be best. Since the requirements are a measure of the completion of the product of the project (choice C), not having completed requirements makes such measurement impossible. This is why choice C is the best choice.. Which of the following is CORRECT in regard to the Control Scope process? A. Effective scope definition can lead to a more complete project scope statement. B. The Control Scope process must be done before scope planning. C. The Scope Control process must be integrated with other control processes. D. Controlling the schedule is the most effective way of controlling scope. Answer C Explanation Though it is a correct statement, choice A cannot be the answer because it does not deal with control. Since scope planning occurs before the Control Scope process, choice B cannot be the answer. Since controlling the schedule is not the best way to control scope, choice D is not the best answer. The control processes do not act in isolation. A change to one will most likely affect the others. Therefore, choice C is the best answer. Which of the following BEST describes the Verify Scope process? A. It provides assurances that the deliverable meets the specifications, is an input to the project management plan, and. Which of the following BEST describes product analysis? A. Working with the customer to determine the product description B. Mathematically analyzing the quality desired for the project C. Gaining a better understanding of the product of the project in order to create the project scope statement D. Determining if the quality standard on the project can be met Answer C Explanation Since you need to have a product description before you can do product analysis, choice A cannot be best. Choice B is related to Plan Quality. Choice D is Perform Quality Assurance. Time Management CHAPTER SIX. A dependency requiring that design be completed before manufacturing can start is an example of a: A. Discretionary dependency. B. External dependency. C. Mandatory dependency. D. Scope dependency. Answer C Explanation Since the dependency is required, it could not be discretionary (choice A) and therefore must be mandatory. No mention is made that the dependency comes from a source outside the project, so external (choice B) is not correct. Scope dependency (choice D) is not a defined term. The key word in this question is requires:' The question defines a mandatory dependency.. Lag means: A. The amount of time an activity can be delayed without delaying the project finish date. B. The amount of time an activity can be delayed without delaying the early start date of its successor. C. Waiting time. D. The product of a forward and backward pass. Answer C Explanation Total float and free float (choices A and B) are the time an activity can be delayed without impacting the entire project or the next activity. Critical path method (choice D) is a network analysis technique, not waiting time. Choice C is the correct answer. Which of the following is the BEST project management tool to use to determine the longest time the project will take? A. WBS B. Network diagram C. Bar chart D. Project charter Answer B Explanation The bar chart (choice C) may show an end date, but it is not used to determine dates and show progress. The project charter (choice D) may include any required end dates, but not a logical determination of how long the project will take. The network diagram (choice B) takes the work packages from the work breakdown structure (choice A) and adds dependencies. The dependencies allow us to look at the various paths through the diagram. The longest duration path is the critical path. Choice B is the best answer. Which of the following is CORRECT? A. The critical path helps prove how long the project will take. B. There can be only one critical path. C. The network diagram will change every time the end date changes. D. A project can never have negative float. Answer A Explanation This question tests your knowledge about a number of topics. There can often be more than one critical path (choice B) but you might adjust to decrease risk and have only one critical path. Choice C uses the word will. The network diagram may change or it may not, depending on the amount of schedule reserve and the reason for the change to the schedule. You can have negative float (choice D) if you are behind schedule. Only choice A is correct.. Which of the following BEST describes the relationship between standard deviation and risk? A. Nothing B. Standard deviation tells you if the estimate is accurate. C. Standard deviation tells you how unsure the estimate is. D. Standard deviation tells you if the estimate includes a pad. Answer C Explanation Choice A is not best, as the standard deviation tells you the amount of uncertainty or risk involved in the estimate for the activity. An estimate can have a wide range (choice B) and still be accurate if the item estimated includes risks. Choice D cannot be the best answer since there is no such thing as a pad in proper project management. An estimate might be inflated, but it is because of risks, not padding. The float of an activity is determined by: A. Performing a Monte Carlo analysis. B. Determining the waiting time between activities. C. Determining lag. D. Determining the amount of time the activity can be delayed before it delays the critical path. Answer D Explanation This question does not specify what type of float. Total float is the amount of time an activity can be delayed without impacting the end date of the project. Free float is the amount of time an activity can be delayed without impacting the early start of the next activity. The only choice matching either of these definitions is choice D.. analysis and life cycle costs (choices A and D) do not directly deal with resources. Leveling (choice C) is the only choice that will definitely affect resources.. Which of the following is the BEST thing to do to try to complete a project two days earlier? A. Tell senior management that the project's critical path does not allow the project to be finished earlier. B. Tell your boss. C. Meet with the team and look for options for crashing or fast tracking the critical path. D. Work hard and see what the project status is next month. Answer C Explanation This is another question that asks about problem solving. Only choice C relates to evaluate:' Choices B and D do not try to solve the real problem. Choice A is just an untrue statement. In attempting to complete the project faster, the project manager looks at the cost associated with crashing each activity. The BEST approach to crashing would also include looking at the: A. Risk impact of crashing each activity. B. Customer's opinion of which activities to crash. C. Boss's opinion of which activities to crash and in which order. D. Project life cycle phase in which the activity is due to occur. Answer A Explanation You mayor may not need your customer's (choice B) or your boss's (choice C) input, but you will definitely need to include an analysis of risk. Choice A is broader than choice D and therefore is better. Which of the following processes includes asking team members about the time estimates for their activities and reaching agreement on the calendar date for each activity? A. Sequence Activities B. Develop Schedule C. Define Scope D. Develop Project Charter Answer B Explanation By the time this process is taking place, Sequence Activities (choice A), Define Scope (choice C), and Develop Project Charter (choice D) would be completed. so many other choices that could be selected first. Choice D could have the least negative effect on the project. During project planning, you estimate the time needed for each activity and then add the estimates to create the project estimate. You commit to completing the project by this date. What is wrong with this scenario? A. The team did not create the estimate, and estimating takes too long using that method. B. The team did not create the estimate, and a network diagram was not used. C. The estimate is too long and should be created by management. D. The project estimate should be the same as the customer's required completion date. Answer B Explanation Time estimates for the activities should be created by the team and should not be added. Some activities may take place concurrently. Therefore, choice B must be the correct answer.. You are a project manager on a US $5,000,000 software development project. While working with your project team to develop a network diagram, your data architects suggest that quality could be improved if the data model is approved by senior management before moving on to other design elements. They support this suggestion with an article from a leading software development journal. Which of the following BEST describes what this type of input is called? A. Mandatory dependency B. Discretionary dependency C. External dependency D. Heuristic Answer B Explanation The situation is neither mandatory (choice A), nor driven by an external source (choice C). A rule of thumb (choice D) is something that can be used consistently. This situation is a unique occurrence. The situation is a suggestion of a preferred method, so choice B is the best answer. Based on the following, if you needed to shorten the duration of the project, what activity would you try to shorten? Activity / Preceding Activity / Duration In Weeks Start ....... None ........ 0 A ............. Start ........ 1 B ............. Start ......... 2 C ............. Start ......... 6 D ............. A ............. 10 E ............. B,C ........... 1 F ............. C .............. 2 G ............ D .............. 3 H ............ E .............. 9 I ............. F .............. 1 End ........ G,H,I ......... 0 A. Activity B B. Activity D C. Activity H D. Activity C Answer D Explanation This is one of the two-stage questions you will find on the exam. First you need to draw the network diagram and find the critical path, and then make a decision. The network diagram would be: Paths Duration in Weeks Start, A, D, G, End 14 Start, B, E, H, End 12 Start, C, E, H, End 16 Start, C, F, I, End 9 Many people immediately look for the longest duration activity on the project to cut. Here activity D is the longest, at 10 weeks. However, that activity is not on the critical path, and cutting it would not shorten the project's duration. You must change the critical path. In this case, both activity C and activity H are on the critical path. If you have a choice, all things being equal, choose the earlier option. Therefore, activity C (choice D) is the best answer. You have a project with the following activities: Activity A takes 40 hours and can start after the project starts. Activity B takes 25 hours and should happen after the project starts. Activity C must happen after activity A and takes 35 hours. Activity D must happen after activities Band C and takes 30 hours. Activity E must take place after activity C and takes 10 hours. Activity F takes place after Activity E and takes 22 hours. Activities F and D are the last activities of the project. Which of the following is TRUE if activity B actually takes 37 hours? A. The critical path is 67 hours. B. The critical path changes to Start, B, D, End. C. The critical path is Start, A, C, E, F, End. D. The critical path increases by 12 hours. Answer C Explanation Did you notice how difficult this question was to read? Such wording is intentional, to prepare you for interpreting questions on the real exam. Looking at this situation, you see that there are three paths through the network. They are Start, A, C, E, F, End with a duration of 40 + 35 + 10 + 22 = 107; Start, A, C, D, End with a duration of 40 + 35 + 30 = 105; and Start, B, D, End with a duration of 25 + 30 = 55. If the duration of activity B changes from 25 to 37, the activity will take 12 hours longer. As the activity is only on the third path, it will only change the duration of that path from 55 to 55 + 12 = 67 hours. Since the duration of the critical path is 107 hours, the delay with activity B will have no impact on the project timeline or the current critical path. A project manager has received activity duration estimates from his team. Which of the following does he need in order to complete the Develop Schedule process? A. Change requests B. Schedule change control system C. Recommended corrective actions D. Reserves Answer D Explanation Develop Schedule includes all work and uses all inputs needed to come up with a finalized, realistic schedule. One would need time reserves (choice D) in order to complete a schedule. All of the other items are parts of Control Schedule and occur after Develop Schedule. A project manager is taking over a project from another project manager during the planning process group. If the new project manager wants to see what the previous project manager planned for managing changes to the schedule, it would be BEST to look at the: A. Communications management plan. B. Update management plan. C. Staffing management plan D. Schedule management plan. Answer D Explanation Answer D is the most correct answer. The schedule management plan is the repository for plans for schedule changes. Note that choice B is a made-up term. A project manager is using weighted average duration estimates to perform schedule network analysis. Which type of mathematical analysis is being used? A. Critical path method B. PERT C. Monte Carlo D. Resource leveling Answer B Explanation PERT uses a weighted average to compute activity durations. The WBS, estimates for each work package, and the network diagram are completed. Which of the following would be the NEXT thing for the project manager to do? A. Sequence the activities. B. Verify that they have the correct scope. C. Create a preliminary schedule and get the team's approval. D. Complete risk management. Answer C Explanation Choice A is the same thing as create a network diagram. Choice B is another name for Verify Scope, which is done during the monitoring and controlling process group, not during project planning. Since a schedule is an input to risk management, choice D comes after choice C and so it is not the next thing to do: The only remaining choice is C.. Duration compression (choice D) occurs before finalizing the schedule (choice C) and is, therefore, the best answer. You are a project manager for a new product development project that has four levels in the work breakdown structure. A network diagram has been created, the duration estimates have been compressed, and a schedule has been developed. What time management activity should you do NEXT? A. Begin Control Schedule. B. Estimate Activity Resources. C. Analogously estimate the schedule. D. Gain approval. Answer D Explanation Notice how this question and the previous one seem very similar. This is intended to prepare you for similar questions on the exam. Choices B and C should have already been completed. The situation described is within the Develop Schedule process of time management. Choice A is the next time management process after Develop Schedule, but the Develop Schedule process is not finished. Final approval (choice D) of the schedule by the stakeholders is needed before one has a project schedule. A team member from research and development tells you that her work is too creative to provide you with a fixed single estimate for the activity. You both decide to use the Explanation The activity described has float because there is a difference between the early start and late start. An activity that has float is probably not on the critical path. There is no information presented about lag (choice B) or progress (choice C), so choice D is the best answer. The project is calculated to be completed four days after the desired completion date. You do not have access to additional resources. The project is low risk, the benefit cost ratio (BCR) is expected to be 1.6, and the dependencies are preferential. Under these circumstances, what would be the BEST thing to do? A. Cut resources from an activity. B. Make more activities concurrent. C. Move resources from the preferential dependencies to the external dependencies. D. Remove an activity from the project. Answer B Explanation Cutting resources from an activity (choice A) would not save time, nor would moving resources in the way described (choice C). Removing an activity from the project (choice D) is a possibility, but since the dependencies are preferential and the risk is low, the best choice would be to make more activities concurrent (choice B), as this would have less impact on the project.? A. Project manager B. Senior management C. Project sponsor D. Manager of the project management office Answer A Explanation Did you get lost looking at all the numbers presented in this question? Notice that there are no calculations required, simply an understanding of what the problem is. This question describes schedule management, which is a responsibility of the project manager.. Rearranging resources so that a constant number of resources is used each month is called: A. Crashing. B. Floating. C. Leveling. D. Fast tracking. Answer C Explanation The key to this question is the phrase constant number used each month. Only leveling, choice C, has such an effect on the schedule. Which of the following is a benefit of an analogous project estimate? A. The estimate will be closer to what the work will actually require. B. It is based on a detailed understanding of what the work requires. C. It gives the project team an understanding of management's expectations. D. It helps the project manager determine if the project will meet the schedule. Answer C Explanation Remember for the exam that analogous estimates are considered to be top-down, high-level estimates, even though a high-level or even a definitive estimate can be estimated analogously. Therefore, choices A and B cannot be correct. The project manager needs more than an analogous (high-level) estimate to determine whether or not the project will meet the schedule (choice D). It is a benefit to know management's expectations of how much the project will cost so that any differences between the analogous estimate and the detailed bottom-up estimate can be reconciled in the planning processes. The best choice is C. During project executing, a large number of changes are made to the project. The project manager should: A. Wait until all changes are known and print out a new schedule. B. Make approved changes as needed, but retain the schedule baseline. C. Make only the changes approved by management. D. Talk to management before any changes are made. Answer B Explanation A project manager must be more in control of the project than choices C and D reflect. Choice A is a common error many project managers make. Instead, the project manager should be controlling the project throughout the completion of the project. Cost Management CHAPTER SEVEN. Estimate at completion (EAC) is a periodic evaluation of: A. The cost of work completed. B. The value of work performed. C. The anticipated total cost at project completion. D. What it will cost to finish the job. Answer C Explanation When you look at earned value, many of the terms have similar definitions. This could get you into trouble. Since the EAC means the estimate at completion, choice C is the best answer. Choice D is the definition of ETC, estimate to complete.. Analogous estimating: A. Uses bottom-up estimating techniques. B. Is used most frequently during the executing processes of the project. C. Uses top-down estimating techniques. D. Uses actual detailed historical costs. Answer C Explanation Analogous estimating is used most frequently during the planning processes, not the executing processes (choice B). You do not need to use historical costs (choice D) for an analogous estimate. Therefore, choice C is the correct answer. All of the following are outputs of the Estimate Costs process EXCEPT: A. An understanding of the cost risk in the work that has been estimated. B. The prevention of inappropriate changes from. The main focus of life cycle costing is to: A. Estimate installation costs. B. Estimate the cost of operations and maintenance. C. Consider installation costs when planning the project costs. D. Consider operations and maintenance costs in making project decisions. Answer D Explanation Life cycle costing looks at operations and maintenance costs and balances them with the project costs to try to reduce the cost across the entire life of the project. Cost performance measurement is BEST done through which of the following? A. Asking for a percent complete from each team member and reporting that in the monthly progress report B. Calculating earned value and using the indexes and other calculations to report past performance and forecast future performance C. Using the 50/50 rule and making sure the life cycle cost is less than the project cost D. Focusing on the amount expended last month and what will be expended the following month Answer B Explanation Asking percent complete (choice A) is not a best practice since it is usually a guess. Often the easiest work is done first on a project, throwing off any percentage calculations of work remaining. It may be a good thing to use the 50/50 rule, as in choice C. However, the 50/50 rule is not necessarily included in the progress report, and the second part of the sentence is incorrect. The life cycle cost cannot be lower than the project cost, as the life cycle cost includes the project cost. Choice D is often done by inexperienced project managers who know of nothing else. Not only does it provide little information, but also it cannot be used to predict the future. Choice B is the best answer since it looks at the past and uses this information to estimate future costs. the rate planned. D. The project is only getting 89 cents out of every dollar invested. Answer D Explanation The CPI is less than one, so the situation is bad. Choice D is the best answer. A schedule performance index (SPI) of 0.76 means: A. You are over budget. B. You are ahead of schedule. C. You are only progressing at 76 percent of the rate originally planned. D. You are only progressing at 24 percent of the rate originally planned. Answer C Explanation Earned value questions ask for a calculation or an interpretation of the results. See the tricks under this topic in this book.. Who has the cost risk in a fixed price (FP) contract? A. The team B. The buyer C. The seller D. Management Answer C Explanation If the costs are more than expected under a fixed price contract, the seller must pay those costs. As explained in the Procurement Management chapter,. Which of the following represents the estimated value of the work actually accomplished? A. Earned value (EV) B. Planned value (PV) C. Actual cost (AC) D. Cost variance (CV) Answer A Explanation It can be confusing to differentiate earned value terms from each other. The definition presented here is for EV or earned value, so choice A is the best choice. Which of the following are ALL items included in the cost management plan? A. The level of accuracy needed for estimates, rules for measuring cost performance, specifications for how duration estimates should be stated B. Specifications for how estimates should be stated, rules for measuring cost performance, the level of accuracy needed for estimates C. Rules for measuring team performance, the level of accuracy needed for estimates, specifications for how estimates should be stated D. Specifications for how estimates should be stated, the level of risk needed for estimates, rules for measuring cost performance Answer B Explanation Every item in choice B accurately describes a part of the cost management plan. Notice how one word in each of the other options makes the entire choice incorrect. Choice A refers to duration estimates, which are created during the time management process, choice C includes measuring team performance, a part of human resource management, and choice D includes risk. Your project has a medium amount of risk and is not very well defined. The sponsor hands you a project charter and asks you to confirm that the project can be completed within the project cost budget. What is the BEST method to handle this? A. Build the estimate in the form of a range of possible results. B. Ask the team members to help estimate the cost based on the project charter. C. Based on the information you have, calculate a parametric estimate. D. Provide an analogous estimate based on past history. Answer A Explanation Accuracy is always important, but since the project charter has just been received, the project has not yet been planned. Therefore, although some of the choices are not blatantly wrong, it is best to estimate in a range.. The seller tells you that your activities have resulted in an increase in their costs. You should: A. Recommend a change to the project costs. B. Have a meeting with management to find out what to do. C. Ask the seller for supporting information. D. Deny any wrongdoing. Answer C Explanation This is a professional and social responsibility/procurement/cost question. The situation described involves a claim. The best thing to do would be to get supporting information to find out what happened and take corrective action for the future. After choice C and negotiation, choice A would most likely occur. Choice D is unethical. Choice B is a meeting with YOUR management and should not occur until you have all the information. that would have the least negative impact in this situation. You would not need to meet with the sponsor to do choice B. Choices C and D always have negative effects. The choice with the least negative impact is Choice A. A new store development project requires the purchase of various equipment, machinery, and furniture. The department responsible for the development recently centralized its external purchasing process and standardized its new order system. In which document can these new procedures be found? A. Project scope statement B. WBS C. Staffing management plan D. Organizational policies Answer D Explanation Procedures for the rental and purchase of supplies and equipment are found in the organizational policies, part of organizational process assets.. You have just completed the initiating processes of a small project and are moving into the planning processes when a project stakeholder asks you for the project's budget and cost baseline. What should you tell her? A. The project budget can be found in the project's charter, which has just been completed. B. The project budget and baseline will not be finalized and accepted until the planning processes are completed. C. The project management plan will not contain the project's budget and baseline; this is a small project. D. It is impossible to complete an estimate before the project management plan is created. Answer B Explanation The overall project budget (choice A) may be included in the project charter but not the detailed costs. Even small projects (choice C) should have a budget and schedule. It is not impossible to create a project budget before the project management plan is created (choice D). It is just not wise, as the budget will not be accurate. The project manager is allocating overall cost estimates to individual activities to establish a baseline for measuring project performance. What process is this? A. Cost Management B. Estimate Costs C. Determine Budget D. Control Costs Answer C Explanation Choice A is too general. The estimates are already created in this example, so the answer is not choice B. The answer is not D, Control Costs, because the baseline has not yet been created. The correct answer is choice C. Monitoring cost expended to date in order to detect variances from the plan occurs during: A. The creation of the cost change management plan. B. Recommending corrective actions . C. Updating the cost baseline. D. Product performance reviews. Answer D Explanation Recommending corrective actions (choice B) and possible updates to the cost baseline (choice C) result from the activity described; they are not concurrent with it. Monitoring costs are part of change control, but not part of creating the change control system (choice A). is almost impossible to guess correctly.. estimate was completed. Which of the following describes what was missing? A. Estimated costs should be used to measure CPI. B. SPI should be used, not CPI. C. Bottom-up estimating should have been used. D. Past history was not taken into account. Answer C Explanation Actual costs are used to measure CPI, and there is no reason to use SPI in this situation, so choices A and B are not correct. Using past history (choice D) is another way of saying analogous. The best way to estimate is bottom-up (choice C). Such estimating would have improved the overall quality of the estimate. Earned value analysis is an example of: A. Performance reporting. B. Planning control. C. Ishikawa diagrams. D. Integrating the project components into a whole. Answer A Explanation Earned value analysis is a great reporting tool. With it, you can show where you stand on budget and schedule as well as provide forecasts for the rest of the project. You are about to take over a project from another project manager and find out the following information about the project. Activity Z has an early start (ES) of day 15 and a late start (LS) of day 20. Activity Z is a difficult activity. The cost performance index (CPI) is 1.1. The schedule performance index (SPI) is 0.8. There are 11 stakeholders on the project. Based on this information, which of the following would you be the MOST concerned about? A. Schedule B. Float C. Cost D. The number of available resources Answer A Explanation This is one of those questions that combines topics from various knowledge areas. Did you fall into the trap of calculating the float for Z? The amount of float for one activity and the number of stakeholders does not tell you anything in this case, so choices Band D cannot be the best answers. The CPI is greater than one and the SPI is less than one. Therefore, the thing to be most worried about would be schedule.. You provide a project cost estimate for the project to the project sponsor. He is unhappy with the estimate, because he thinks the price should be lower. He asks you to cut 15 percent off the project estimate. What should you do? A. Start the project and constantly look for cost savings. B. Tell all the team members to cut 15 percent from their estimates. C. Inform the sponsor of the activities to be cut. D. Add additional resources with low hourly rates. Answer C Explanation This question is full of choices that are not correct project management actions. If you picked the wrong answer, look again at the choices and try to determine what you are missing. Whatever it is, it will show up more than once on the real exam! To answer the question, you must first realize that it is never appropriate for a project manager to just cut estimates across the board (choice B). The project manager should have created an estimate with realistic work package estimates that do not include padding. Then, if costs must be decreased, the project manager can look to cut quality, decrease risk, cut scope, or use cheaper resources (and at the same time closely monitor the impact of changes on the project schedule). One of the worst things a project manager can do is to start a project while knowing that the time or cost for the project is unrealistic. Therefore, choice A cannot be best. Notice that choice D suggests adding resources. That would cost more. Choice C involves evaluating, looking for alternatives, and then going to the sponsor to tell him the impact of the cost cutting. Cost risk means: A. There are risks that will cost the project money. B. The project is too risky from a cost aspect. C. There is a risk that project costs could go higher than planned. D. There is a risk that the cost of the project will be lower than planned. Answer C Explanation Choice A is a correct statement but it is not the definition of cost risk. Choice B refers to the overall cost risk on the project, and assumes that the risk is too great to do the project. The opposite of choice D is correct. A project manager needs to analyze the project costs to find ways to decrease costs. It would be BEST if the project manager looks at: A. Variable costs and fixed costs. B. Fixed costs and indirect costs. C. Direct costs and variable costs. D. Indirect costs and direct costs. Answer C Explanation Choice C describes costs that are directly attributable to the project or that vary with the amount of work accomplished. Human Resource Management CHAPTER NINE All of the following are forms of power derived from the project manager's position EXCEPT: A. Formal. B. Reward. C. Penalty. D. Expert. Answer D Explanation When someone is given the job of project manager, they will have formal, reward, and penalty power. But just having the position does not make the project manager either a technical or project management expert. or she will also be a good project manager. The sponsor's role on a project is BEST described as: A. Helping to plan activities. B. Helping to prevent unnecessary changes to project objectives. C. Identifying unnecessary project constraints. D. Helping to put the project management plan together. Answer B Explanation Though the sponsor may help plan some of the activities (choice A) it is not the sponsor's exclusive duty. Some project constraints (choice C) come from the sponsor, but they should be considered necessary. The project management plan (choice D) is created by the team and approved by the sponsor and other management. Since the project objectives are stated in the project charter and it is the sponsor who issues the project charter, choice B is the correct answer. The MOST common causes of conflict on a project are schedules, project priorities, and: A. Personality. B. Resources. C. Cost. D. Management. Answer B Explanation Know the top four sources (schedule, project priorities, resources, and technical opinions) so you can answer questions such as this one. Don't be fooled because personality is on the list. It is last. What does a resource histogram show that a responsibility assignment matrix does not? A. Time B. Activity C. Interrelationships D. The person in charge of each activity Answer A Explanation Time is shown on a schedule or bar chart. The responsibility assignment matrix maps specific resources against the work packages from the WBS. On a resource histogram, the use of resources is shown individually or by groups over time. You have just been assigned as project manager for a large telecommunications project. This one- year project is about halfway done. The project team consists of 5 sellers and 20 of your company's employees. You want to understand who is responsible for doing what on the project. Where would you find such information? A. Responsibility assignment matrix B. Resource histogram C. Bar chart D. Project organization chart Answer A Explanation The responsibility assignment matrix maps who will do the work. The resource histogram (choice B) shows the number of resources used in each time period. In its pure form, a bar chart (choice C) shows only activity and calendar date. An organizational chart (choice D) shows who reports to whom. During project planning in a matrix organization, the project manager determines that additional human resources are needed. From whom would he request these resources? A. Project manager B. Functional manager C. Team D. Project sponsor Answer B Explanation Did you remember that in a matrix organization, the functional manager controls the resources? A project manager must publish a project schedule. Activities, start/end times, and resources are identified. What should the project manager do NEXT? A. Distribute the project schedule according to the communications management plan. B. Confirm the availability of the resources. C. Refine the project management plan to reflect more accurate costing information. D. Publish a bar chart illustrating the timeline. Answer B Explanation The project schedule remains preliminary until resource assignments are confirmed. types of project management power will likely be the MOST effective in this circumstance? A. Referent B. Expert C. Penalty D. Formal Answer B Explanation Reward and expert are the best sources of power. Reward is not listed as a choice. A team member is not performing well on the project because she is inexperienced in system development work. There is no one else available who is better qualified to do the work. What is the BEST solution for the project manager? A. Consult with the functional manager to determine project completion incentives for the team member. B. Obtain a new resource more skilled in development work. C. Arrange for the team member to get training. D. Allocate some of the project schedule reserve. Answer C Explanation The job of the project manager includes providing or obtaining project -specific training for team members. This kind of training is a direct cost of the project. have to give up something to solve this problem." What conflict resolution method is she using? A. Confrontation B. Compromise C. Smoothing D. Communicating Answer B Explanation The act of both parties giving something defines compromise. A project has several teams. Team C has repeatedly missed deadlines in the past. This has caused team D to have to crash the critical path several times. As the team leader for team D, you should meet with the: A. Manager of team D. B. Project manager alone. C. Project manager and management. D. Project manager and the leader of team C. Answer D Explanation Those having the problem should resolve the problem. Having had to crash the critical path several times implies that team D has already dealt with these problems. In this case, the two team leaders need to meet. The extent of this situation requires the project manager's involvement as well. opinions,. The project is just starting out and consists of people from 14 different departments. The project charter was signed by one person and contains over 30 major requirements that must be met on the project. The sponsor has informed the project manager that the SPI must be kept between 0.95 and 1.1. A few minutes of investigation resulted in the identification of 34 stakeholders, and the schedule objectives on the project are constrained. A project manager has just been hired. Which of the following types of project management power will BEST help the project manager gain the cooperation of others? A. Formal B. Referent C. Penalty D. Expert Answer A Explanation Generally, the best forms of power are reward or expert. The project manager has not had time to become a recognized expert in the company (choice D) and reward is not included as a choice here. This leaves formal power (choice A) as the only logical answer. happens. Answer D Explanation Choice D is an example of compromising. A project is in the middle of the executing processes manger to address these issues with? A. The team B. Senior management C. The customer D. The sponsor Answer D Explanation It is the sponsor's role to prevent unnecessary changes and to set priorities between projects. The situation described in this question implies that such work is not being done, and the project manager must therefore go to the root of the problem: the sponsor. What theory proposes that employees' efforts will lead to effective performance and the employees will be rewarded for accomplishments? A. Conditional reinforcement B. Malsow's hierarchy C. McGregor's D. Expectancy Answer D Explanation Employees who believe that their efforts will lead to effective performance and who expect to be rewarded for their accomplishments will stay productive as rewards meet their expectations. This is expectancy theory. The installation project has a CPI of 1.03 and an SPI of 1.0. There are 14 team members, and each team member had input into the final project management plan. The customer has accepted the three deliverables completed so far without complaint and the responsibility assignment matrix has not changed since the project began. The project is being completed in a matrix environment and there are no contracts needed for the project. Though the sponsor is happy with the status of the project, one of the team members is always complaining about how much time his project work is taking. Which of the following would be the BEST thing for the project manager to do? A. Review the reward system for the project. B. Try to improve schedule performance of the project. C. Meet with the customer to try to extend the schedule. D. Gain formal acceptance in writing from the customer. Answer A Explanation Improving schedule performance (choice B) relates to getting the project completed sooner. Though it would seem to always be a good idea to improve schedule performance, this project's performance is fine. The schedule has been approved as it is. It would be better for the project manager to spend more time controlling the project to make sure it finishes according to plan than to improve schedule performance. If you chose C, ask yourself why. There is nothing wrong with the schedule performance of the project that would require an extension. Did you think that the best way to deal with the complaining stakeholder was to give him more time? How do you know the team member's activities are on the critical path? It is always important to gain formal acceptance from the customer, as it provides an opportunity for the team to check if everything is going well. It is a good idea to get such acceptance in writing. Choice D could be done, but there is a more important problem that takes precedence here. Read on. The only thing glaringly wrong in this situation is that the team member is complaining. If you read the situation completely, you will notice that the team member was involved and approved the project management plan, including his own involvement in the project. Since the responsibility assignment matrix has not changed, the team member has not even been assigned different duties since the project began. There must be something else causing the team member to complain. The project manager should investigate and find out what part of the reward system is ineffective. The project has been challenging to manage. Everyone has been on edge due to pressure to complete the project on time. Unfortunately, the tension has grown to the point where team meetings have become shouting matches and little work is accomplished during the meetings. One team member asks to be excused from future team meetings, as all the shouting upsets him. Meanwhile, the sponsor has asked to attend team meetings in order to better understand how the project is going and the issues involved in completing the project, and the customer has started discussions about adding scope to the project. In this situation, it would be BEST for the project manager to: A. Ask the sponsor if the information needed could be sent in a report rather than have her attend the meeting. B. Inform the team member who asked to be excused from the meetings of the value of communication in such meetings. C. Create new ground rules for the meetings and introduce them to the team. D. Hold a team-building exercise that involves all the team members. Answer C Explanation Here is a situation where all four choices could be done. Choice A does not solve the root cause of the problem described. Choice B merely dismisses the concerns of the team member and might cause anger. A team building exercise (choice D) would take planning and so could not be done right away. Remember, the sponsor might be attending the next meeting and at least one team member might not attend because of past problems. The best thing to do would be to set up new ground rules for the team governing behavior (choice C) and then plan a team-building exercise (choice D).. Answer A Explanation Questions like this can drive you crazy on the exam because it is easy to get confused. The best thing to do is to look at the two terms used here (project performance appraisals and team performance assessment) and review in your mind what each means BEFORE looking at the choices. Choices B, C, and D list aspects of team performance assessments. Only choice A is correct. Project performance appraisals deal with how each team member is performing work, rather than how well the team is working together. A project manager had a complex problem to solve and made a decision about what needed to be done. A few months later, the problem resurfaced. What did the project manager MOST likely not do?. The project CPI is 1.02, the benefit cost ratio is 1.7, and the latest round of performance reviews identified few needed adjustments. The project team was co-located into a new building when the project started. Everyone commented on how excited they were to have all new facilities. The sponsor is providing adequate support for the project, and few unidentified risks have occurred. In an attempt to improve performance, the project manager spends part of the project budget on new chairs for the team members and adds the term senior to each team member's job title. Which of the following is the MOST correct thing that can be said of this project or the project manager? A. The project manager has misunderstood Herzberg's theory. B. The project is slowly spending more money than it should. The project manager should begin to watch cost more carefully. C. The performance review should be handled better to find more adjustments. D. The project manager should use good judgment to determine which variances are important. Answer A Explanation Choice B includes the concept of cost to trick you into selecting it if you are unsure of the real answer. There is no indication that the costs are trending in any particular direction. There is no reason to think that performance reviews should turn up more adjustments (choice C). The project manager should always use good judgment (choice D), but nothing in this question talks about judgment regarding variances, so this cannot be the best choice. In this situation, the project manager is making great working conditions better. According to Herzberg's theory, fixing bad working conditions will help you to motivate, but making good working conditions better will not improve motivation. You need to focus on the motivating agents and not the hygiene factors.. During the first half of the project, five team members left for other projects without being replaced, two team members went on vacation without informing you, and other team members expressed uncertainty about the work they were to complete. In this situation, it is BEST if you create a ______ for the second half of the project? A. Work breakdown structure B. Resource histogram C. Staffing management plan D. Responsibility assignment matrix Answer C Explanation The staffing management plan describes when resources will be brought onto and taken off the project.? A. Make sure functional managers have a copy of the resource histogram. B. Show the sponsor the data, and explain the project manager's concern. C. Determine metrics to use as an early warning sign that resources will not be available. D. Ask functional managers for their opinions. Answer A Explanation Sending data without pointing out the issue (choice A) does not mean the communication will be adequately decoded by the recipient. The other choices are more effective communication in this instance. A large project is underway when one of the team members reviews the project status report. He sees that the project is currently running late. As he looks at the report further, he notices that the delay will cause one of his activities to be scheduled during a time he will be out of the country and cannot work on the activity. This is of great concern because he is very committed to the project being successful and he does not want to be the cause of the project being further delayed. What is the BEST THING for him to do? A. Contact the project manager immediately to provide the project manager with his schedule. B. Include the information in his next report. C. Request that the issue be added to the project issue log. D. Recommend preventive action. Answer D Explanation Notice that this question talks about what the team member should do? It is important for the project manager to understand the team member's role and possibly even instruct team members on how to work on projects and what is expected of them. Choices A, B, and C have one thing in common. They involve the team member asking the project manager to do something. In reality, it may very well be the team member who will come up with a solution (such as decreasing the scope of the activity, fast tracking, or specific suggestions about changes to predecessor activities). Therefore, choice D is the best choice. But ask yourself how you run your projects? Which is better, your way or this way? Lastly, please note that recommended corrective or preventive actions can come from the team or stakeholders in addition to the project manager. There have been many work packages completed successfully on the project and the sponsor has made some recommendations for improvements. The project is on schedule to meet an aggressive deadline when the successor activity to a critical path activity suffers a major setback. The activity has 14 days of float and is being completed by four people. There are two other team members with the skill set to assist the troubled activity, if needed. The project manager receives a call that three other team members are attempting to be removed from the project because they do not feel the project can be successful. When the project manager pursues this, she discovers that those team members have issues that have not been addressed. Which of the following is the BEST thing to do to improve the project? A. Have the team members immediately assist the troubled activity. B. Investigate why the project schedule is aggressive. C. See who can replace the three team members. D. Create an issue log. Answer D Explanation Sometimes complex problems are caused by not doing simple things. The data in the first paragraph, once you read the choices, is completely extraneous. The troubled activity has float and so does not need immediate attention. Choice A may not be necessary if the amount of float will not be exceeded by the problem. None of the choices suggest investigating if the amount of float is enough to cover any delay caused by the trouble, whatever it is. Rather, the choices take you in different directions. Choice B should have already been done before the project began. Choice C cannot be best, as replacing team members does not solve the root cause of the problem. Could there be something that the project manager is doing wrong, or could be doing that she is not, that would solve the problem without losing resources? Wouldn't it be more effective to discover the root cause of those team members' concerns so that the problem does not surface again later? The creation of an issue log will let the troubled team members know that their concerns have been heard, are noted, and will be resolved. This might be enough to stop them from leaving and avoid project delays and confusion if new team members must be added. This makes choice D the best answer. Communications Management CHAPTER TEN Extensive use of ________ communication is most likely to aid in solving complex problems. A. Verbal B. Written C. Formal D. Nonverbal Answer B Explanation Written communication allows your words to be documented, and they will go to everyone in the same form. When there are complex problems, you want everyone to receive the same thing. The work breakdown structure can be an effective aid for communication in which situation(s)? A. Internal within the project team B. Internal within the organization C. External with the customer D. Internal and external to the project Answer D Explanation The work breakdown structure allows communication vertically and horizontally within the organization as well as outside the project. Communications are often enhanced when the sender the receiver. A. Speaks up to B. Uses more physical movements when talking to C. Talks slowly to D. Shows concern for the perspective of Answer D Explanation Understanding the receiver's perspective allows you to direct the communication to meet his needs. Formal written correspondence with the customer is required when: A. Defects are detected. B. The customer requests additional work not covered under contract. C. The project has a schedule slippage that includes changes to the critical path. D. The project has cost overruns. Answer B Explanation Everything that we do is more formal in a procurement environment than in other project activities. Because choice B deals with contracts, it is the best answer. A project manager has a problem with a team member's performance. What is BEST form of communication for addressing this problem? A. Formal written communication B. Formal verbal communication C. Informal written communication D. Informal verbal communication Answer D Explanation The best choice is D. If informal verbal communication does not solve the problem, choice A is the next best choice. This does not mean that you do not keep records of the problem, but this question is asking about communication between two parties. Communications under a contract should tend toward: A. Formal written communication. B. Formal verbal communication. C. Informal written communication. D. Informal verbal communication. Answer A Explanation When we talk about contracts, everything that we do is more formal than in other project activities. Records are also important, thus the need for written communication. The project status report is an example of which type of communication? A. Formal written communication B. Formal verbal communication C. Informal written communication D. Informal verbal communication Answer A Explanation The project status needs to be known by many people. Therefore, it is best to make this type of communication in writing so that it can be transmitted to many people. It is also formal in that it is an official report of the project. Therefore, choice A is the best answer. When a project manager is engaged in negotiations, nonverbal communication skills are of: A. Little importance. B. Major importance. C. Importance only when cost and schedule objectives are involved. D. Importance only to ensure you win the negotiation. Answer B Explanation Nonverbal communication carries 55 percent of the message you send. With this much at stake, nonverbal communication is of major importance. Answer D Explanation Although the information is found as a sub-plan to the project management plan (choice A), the communications management plan (choice D) is the best answer because it directly answers the question. Project information has been distributed according to the communications management plan. Some project deliverables have been changed in accordance with the project management plan. One stakeholder expressed surprise to the project manager upon hearing of a previously published. Answer C Explanation Choice A cannot be correct because the question states that all stakeholders received the information. Choices Band D do not address the root cause of the problem. The problem presented here shows that there is something missing in the communications management plan. The best answer is to review the communications management plan in order to prevent future problems and find any instances of similar problems. Communication is the key to the success of a project. As the project manager, you have three stakeholders with whom you need to communicate. As such, you have six channels of communication. A new stakeholder has been added that you also need to communicate with. How many communications channels do you have now? A. 7 B. 10 C. 12 D. 16 Answer B Explanation Did you realize that the project manager is part of the communication channels? Therefore, there are actually four stakeholders to begin with and six channels of communication. The question is asking how many total channels of communication you have with a team of five people. The formula is [N x (N-l)]12 or (5 x 4)/2 = 10. mannerisms and what is being said. D. The pitch and tone of the voices, and physical mannerisms. Answer D Explanation Choices C and D both include nonverbal communication, which represents 55 percent of communication. Choice D adds paralingual communication (pitch and tone) and is thus the best choice. Answer B Explanation Because of the differences in culture and the distance between team members, formal written communication is needed. The project status meeting is not going well. Everyone. Answer D Explanation Choice A is not a rule for effective meetings. Since there is no indication that the meeting was not scheduled in advance (choice B) or that there isn't a purpose (choice C), these cannot be the best answers. Discussed at random implies no agenda (choice D). If an agenda is issued beforehand, people will follow the outline and should not need random discussions.? A. Work status B. Progress C. Forecast D. Communications Answer B Explanation The key word is quickly. The status report (choice A) is too detailed for a quick look. The forecast report (choice C) only looks into the future. The progress report (choice B) will summarize project status.. Answer A Explanation Questions like this can drive one crazy. Although it asks for the most important thing, there are many choices that are reasonably correct. In questions like this, look for the most immediate need. In this case, the team member is in a manufacturing environment. That means that communications will most likely be blocked by noise. In order to have the issue at hand taken care of, the communication, it is BEST for the project manager to use choice A. A project manager overhears a conversation between two stakeholders who are talking about and then ask them to direct any questions to the project manager in writing. B. Make a presentation to all the stakeholders regarding the status of the project. C. Send both stakeholders a copy of the issue log and ask for additional comments. D. Arrange a meeting with both stakeholders to allow them to voice any concerns they may have. Answer D Explanation Here again is a question with more than one right answer. Would asking for something in writing be the best way to communicate? In this particular situation, asking for the concern to be in writing might alienate the stakeholders. Therefore, choice A cannot be best. The issue log (choice C) is where the issue should be listed, but the situation does not say if the project manager knows what the stakeholder's concern is. Therefore, C cannot be the best choice. Why not choice B? Notice the use of the words all stakeholders:' Why bother other stakeholders with this problem when the project manager already knows there may be some concern of stakeholders A and B to address, not all stakeholders. Choice B refers to making a presentation. Presentations are formal verbal. This problem would likely require informal verbal communication in order to discover the real problem. Choice D is therefore the best choice. mayor may not be. During the middle of the project, things have been going well. The work authorization system has allowed people to know when to start work, and the issue log has helped keep track of stakeholders' needs. The benefit cost ratio has been improving, and the sponsor has expressed his appreciation for the team members' efforts by hosting a milestone party for the team. The project manager gets a call from a team member saying that the results from the completion of their activity's predecessor. Answer B Explanation Since there is no information about the sponsor or his needs in this situation and nothing presented here relates to sponsors, choice A cannot be best. Choice C cannot be best, as it is not a correct statement. One watches both predecessor and successor activities. Choice D cannot be best, as the attendance at the party and the issue at hand are not related. Often forgotten in communications management plans are the bosses of team members (functional management, since of course you remember that we are assuming a matrix organization). Including the bosses of team members in communications planning, requirements gathering, risk management, and other areas of project management helps make the project better. In addition, it helps the boss manage his own resources effectively. If the functional manager of the team member assigned to the predecessor activity had been included, he would have known when the team member was needed to do work for the project and the impact, if any, of delay. The communications management plan might also have included a method to communicate potential delays. For these reasons, choice B is Answer D Explanation Working with people from different cultures, with different cultural values and beliefs, necessitates an understanding of both basic definitions and the areas of cultural impact. As project managers, we need to have good communication skills and a willingness to adapt to other cultures. The project has 13 team members and affects the project be. Answer B Explanation Many of these choices could be done, but ask yourself, What is the most effective thing to do? The party may well generate lessons learned, and recording them (choice A) would certainly be a good idea, but the question asked what to do first. There is a more immediate issue- the manager. Choice C could also be useful, but it would require taking time of all the stakeholders when there is only one stakeholder, the manager, who definitely has an issue. Besides, a good project manager would be holding regular meetings with the stakeholders already. Choice D might be a good idea, as the manager apparently is not communicating with the project manager. However, this would not absolutely make sure the manager does communicate. The manager is, in effect, saying that he is not getting the information he needs. His lack of needed information is causing him to suggest more meetings. Too many meetings are a problem on projects. The concept of information distribution (choice B) is to determine who needs what information and plan how to get it to them. A great project manager does not just add meetings, but solves the real problem in the best way. That might take the form of changing a report or sending existing reports to different people rather than adding meetings. For these reasons, choice B is best. The purpose of status meetings is to: A. Exchange information about the project. B. Have team members report on what they are doing C. Issue work authorizations D. Confirm the accuracy of the costs submitted by the team. Answer A Explanation Many people select choice B, but the question asks for the purpose of such meetings. Team members' reporting on what they are doing may best be done outside of meetings. The main purpose is choice A. The requirements of many stakeholders were not approved for inclusion in your project. Therefore, you had a difficult time receiving formal approval of the project management plan for this project. The stakeholders argued and held up the project while they held meeting after meeting back the requirements into the project. C. Maintain an issue log. D. Hold meetings with the stakeholders to go over the work that will not be added to the project. Answer D Explanation Why would choice D be the action not to take? Isn't it similar to choice A? Yes and no. This issue should be over, but since there were so many meetings and arguments about the requirements being removed, it is unlikely that the issue will be dropped by the stakeholders. However, since it has not come up again, and the project was started six months ago, spending time in a meeting is excessive. The other choices are easier and have less impact on the project and are therefore things that could be done. The project manager is expecting a deliverable to be submitted by e-mail from a team member today. At the end of the day, the project manager contacts the team member to notify him that it has not been received. The team member apologizes and says that he was not able to e-mail the deliverable, and it was sent through the mail instead. The team member goes on to explain that he notified the project manager that this would occur during a phone conversation they had while the project manager was traveling. Wasn't that the conversation we had when I told you I could not hear you well due to poor cell phone coverage? asks the project manager. Yes, replies the team member. What could have avoided this problem? A. Paralingual communication B. Adding to the issue log after the phone call C. Better attention to determining communications requirements D. Feedback during the communication Answer D Explanation The pitch and tone of voice (choice A) is not relevant here, as the project manager could not even hear what was being said. There were no issues recognized after the conversation, so none could be added to the issue log (choice B). This issue is not related to communications requirements, so choice C cannot be best. Saying, I am not sure I properly heard what you said during the conversation or asking for the message to be repeated back to the sender would have prevented this problem. This makes choice D the best option. When do stakeholders have the MOST influence on a project? A. At the beginning of the project B. In the middle of the project C. At the end of the project D. Throughout the project Answer A Explanation Stakeholders must be identified and involved at the beginning of the project, in order to determine their requirements and expectations. Remember that if this is not done early, the results may be expensive changes and/or dissatisfaction later in the project. The project has been going well, except for the number of changes being made. The project is being installed into seven different departments within the company and will greatly improve departmental performance when operational. There are 14 project management processes selected for use on. Answer D Explanation It is important here to look for the choice that would solve the real problem. There is no reason to think that training (choice A), management oversight (choice B), or a need for more processes (choice C) are factors contributing to the number of changes. The root cause would be that stakeholders were missed and therefore their requirements were not found. Those stakeholders are now causing changes to accommodate their needs. The best choice is D. Stakeholders can be identified in which project management process groups? A. Initiating, planning, executing, monitoring and controlling, and closing B. Initiating and planning C. Planning and monitoring and controlling D. Monitoring and controlling and closing Answer A Explanation Stakeholders can be identified throughout the project management process groups. However, the earlier stakeholders are identified, the better for the project. If all of the stakeholders' needs and requirements are taken into account before plans are finalized and project work is begun, fewer changes will be needed later in the project, when they will be more costly. If a project manager wants to report on the actual project results vs. planned results, she should use a: A. Trend report. B. Forecasting report. C. Status report. D. Variance report. Answer D Explanation This situation describes the need to "compare." A trend report (choice A) shows performance over time. A forecasting report (choice B) looks only to the future. A status report (choice C) is generally static (relating to a moment in time). The only choice that compares project results is a variance analysis (choice D).. Risk Management CHAPTER ELEVEN If a project has a 60 percent chance of a US $100,000 profit and a 40 percent chance of a US$100,000 loss, the expected monetary value for the project is: A. $100,000 profit. B. $60,000 loss. C. $20,000 profit. D. $40,000 loss. Answer C Explanation Assuming that the ends of a range of estimates are +/- 3 sigma from the mean, which of the following range estimates involves the LEAST risk? A. 30 days, plus or minus 5 days B. 22 - 30 days C. Optimistic = 26 days, most likely = 30 days, pessimistic = 33 days D. Mean of 28 days Answer C Explanation. Which of the following risk events is MOST likely to interfere with attaining a project's schedule objective? A. Delays in obtaining required approvals B. Substantial increases in the cost of purchased materials C. Contract disputes that generate claims for increased payments D. Slippage of the planned post-implementation review meeting Answer A Explanation Cost increases (choice B) and contract disputes (choice C) will not necessarily interfere with schedule. Notice the words post-implementation in choice D. It will not definitely interfere with the project schedule. Choice A is the only one that deals with a time delay. If a risk has a 20 percent chance of happening in a given month, and the project is expected to last five months, what is the probability that this risk event will occur during the fourth month of the project? A. Less than 1 percent B. 20 percent C. 60 percent D. 80 percent Answer B Explanation Don't feel too silly if you got this wrong. Many people miss this one. No calculation is needed. If there is a 20 percent chance in anyone month, the chance in the fourth month must therefore be 20 percent. If a risk event has a 90 percent chance of occurring, and the consequences will be US $10,000, what does US $9,000 represent? A. Risk value B. Present value C. Expected monetary value D. Contingency budget Answer C Explanation Expected monetary value is computed by multiplying the probability times the impact. In this case, EMV = 0.9 x $10,000 = $9,000. Risks will be identified during which risk management process(es)? A. Perform Quantitative Risk Analysis and Identify Risks B. Identify Risks and Monitor and Control Risks C. Perform Qualitative Risk Analysis and Monitor and Control Risks D. Identify Risks Answer B Explanation This is a tricky question. Risks are identified during the Identify Risk process, naturally, but newly emerging risks are identified in the Monitor and Control Risks process. Explanation Risks change throughout the project. You need to review risks at intervals during the project to ensure that non-critical risks have not become critical. All of the following are ALWAYS inputs to the risk management process EXCEPT: A. Historical information. B. Lessons learned. C. Work breakdown structure. D. Project status reports. Answer D Explanation Project status reports (choice D) can be an input to risk management. However, when completing risk management for the first time, you would not have project status reports. Therefore, project status reports are not always an input to risk management. Risk tolerances are determined in order to help: A. The team rank the project risks. B. The project manager estimate the project. C. The team schedule the project. D. Management know how other managers will act on the project. Answer A Explanation If you know the tolerances of the stakeholders, you can determine how they might react to different situations and risk events. You use this information to help assign levels of risk on each work package or activity. All of the following are common results of risk management EXCEPT: A. Contract terms and conditions are created. B. The project management plan is changed. C. The communications management plan is changed. D. The project charter is changed. Answer D Explanation. Purchasing insurance is BEST considered an example of risk: A. Mitigation. B. Transfer. C. Acceptance. D. Avoidance. Answer B Explanation. You are finding it difficult to evaluate the exact cost impact of risks. You should evaluate on a(n): A. Quantitative basis. B. Numerical basis. C. Qualitative basis. D. Econometric basis. Answer C Explanation If you cannot determine an exact cost impact to the event, use qualitative estimates such as Low, Medium, High, etc. Outputs of the Plan Risk Responses process include: A. Residual risks, fallback plans, and contingency reserves. B. Risk triggers, contracts, and a risk list. C. Secondary risks, process updates, and risk owners. D. Contingency plans, project management plan updates, and change requests. Answer A Explanation A risk list (choice B), process updates (choice C), and change requests (choice D) are not outputs of the Plan Risk Responses process. The items in choice A are all outputs of the Plan Risk Responses process, making choice A the correct answer. Workarounds are determined during which risk management process? A. Identify Risks B. Perform Quantitative Risk Analysis C. Plan Risk Responses D. Monitor and Control Risks Answer D Explanation A workaround refers to determining how to handle a risk that occurs but is not included in the risk register. The project must be in the Monitor and Control Risks process if risks have occurred. A project manager has just finished the risk response plan for a us $387,000 engineering project. Which of the following should he probably do NEXT? A. Determine the overall risk rating of the project. B. Begin to analyze the risks that show up in the project drawings. C. Add work packages to the project work breakdown structure. D. Hold a project risk reassessment. Answer C Explanation project manager asked various stakeholders to determine the probability and impact of a number of risks. He then analyzed assumptions. He is about to move to the next step of risk management. Based on this information, what has the project manager forgotten to do? A. Evaluate trends in risk analysis. B. Identify triggers. C. Provide a standardized risk rating matrix. D. Create a fallback plan. Answer C Explanation The activities of the Perform Qualitative Risk Analysis process are probability and impact definition, assumptions testing (data quality assessment), and probability and impact matrix development.? A. Simulation B. Risk mitigation C. Overall risk ranking for the project D. Involvement of other stakeholders Answer D Explanation The process they have used so far is fine, except the input of other stakeholders is needed in order to identify more risks. You are a project manager for the construction of a major new manufacturing plant that has never been done before. The project cost is estimated at US $30,000,000 and will make use of three sellers. Once begun, the project cannot be cancelled, as there will be a large expenditure on plant and equipment. As the project manager, it would be MOST important to carefully: A. Review all cost proposals from the sellers. B. Examine the budget reserves. C. Complete the project charter. D. Perform an identification of risks. Answer D. During the Plan Risk Management process, your team has come up with 434 risks and 16 major causes of those risks. The project is the last? A. Accept the risk. B. Continue to investigate ways to mitigate the risk. C. Look for ways to avoid the risk. D. Look for ways to transfer the risk. Answer A Explanation This question relates real-world situations to risk types. Did you realize that the entire first paragraph is extraneous? Based on the question, you cannot delete the work to avoid it, nor can you insure or outsource to transfer the risk. This leaves acceptance as the only correct choice. A project manager is quantifying risk for her project. Several of her experts are offsite, but wish to be included. How can this be done? A. Use Monte Carlo analysis using the Internet as a tool. B. Apply the critical path method. C. Determine options for recommended corrective action. D. Apply the Delphi technique. Answer D Explanation The Delphi technique is most commonly used to obtain expert opinions on technical issues, the necessary project or product scope, or the risks. An experienced project manager has just begun working for a large information technology integrator. Her manager provides her with a draft project charter and immediately asks her to provide an analysis of the risks on the project. Which of the following would BEST help in this effort? A. An article from PM Network Magazine B. Her project scope statement from the project planning process C. Her resource plan from the project planning process D. A conversation with a team member from a similar project that failed in the past Answer D Explanation Did you realize that this situation is taking place during the initiating process group? Choices Band C are created in the project planning process and so are not yet available. Therefore, we are left with deciding if choice A or choice D provides the greater value. Since the information gained in choice D is more specific to your company, it is the best choice. You have been appointed as the manager of a new, large, and complex project. Because this project is business-critical and very visible, senior management has told you to analyze the project's risks and prepare response strategies for them as soon as possible. The organization has risk management procedures that are seldom used or followed, and has had a history of handling risks badly. The project's first milestone is in two weeks. In preparing the risk response plan, input from which of the following is generally LEAST important? A. Project team members B. Project sponsor C. Individuals responsible for risk management policies and templates D. Key stakeholders Answer B Explanation of retrieving them. What should have been done to prevent this problem? A. Purchase insurance. B. Plan for a reserve fund. C. Monitor the weather and have a contingency plan. D. Schedule the installation outside of the hurricane season. Answer C Explanation system development project is nearing project closing when a previously unidentified risk is discovered. This could potentially affect the project's overall ability to deliver. What should be done NEXT? A. Alert the project sponsor of potential impacts to cost, scope, or schedule. B. Qualify the risk. C. Mitigate this risk by developing a risk response plan. D. Develop a workaround. Answer B Explanation. The cost performance index (CPI) of a project is 0.6 and the schedule performance index (SPI) is 0.71. The project has 625 work packages and is being completed over a four-year period. The team members are very inexperienced, and the project received little support for proper planning. Which of the following is the BEST thing to do? A. Update risk identification and analysis. B. Spend more time improving the cost estimates. C. Remove as many work packages as possible. D. Reorganize the responsibility assignment matrix. Answer A Explanation This project has deviated so far from the baseline that updated risk identification and risk analysis should be performed. While preparing your risk responses, you identify additional risks. What should you do?. Answer B Explanation. You have just been assigned as the project manager for a new telecommunications project that is entering the second phase of the project. There appear to be many risks on this project, but no one has evaluated them to assess the range of possible project outcomes. What needs to be done? A. Plan Risk Management B. Perform Quantitative Risk Analysis C. Plan Risk Responses D. Monitor and Control Risks Answer A Explanation Did you notice that this project has already begun? Risk management is a required element of project management. You must complete the risk management process, starting with the Plan Risk Management process, making choice A the correct choice. During project executing, Explanation First, you want to determine what the risk entails and the impact to the project, then determine what actions you will take regarding the risk. During project executing, a major problem occurs that was not included in the risk register. What should you do FIRST? A. Create a workaround. B. Reevaluate the Identify Risks process. C. Look for any unexpected effects of the problem. D. Tell management. Answer A Explanation Notice that this is a problem that has occurred, rather than a problem that has just been identified. Following the right process is part of professional and social responsibility. Because an unidentified problem or risk occurred, it is important to perform choices Band C. However, they are not your first choices. You might need to inform management (choice D) but this is reactive, not proactive, and not the first thing you should do. The customer requests a change to the project that would increase the project risk. Which of the following should you do before all the others? A. Include the expected monetary value of the risk in the new cost estimate. B. Talk to the customer about the impact of the change. C. Analyze the impacts of the change with the team. D. Change the risk management plan. Answer C Explanation This is a recurring theme. First, you should evaluate the impact of the change. Next, determine options. Then go to management and the customer. Which of the following is a chief characteristic of the Delphi technique? A. Extrapolation from historical records from previous projects B. Expert opinion C. Analytical hierarchy process D. Bottom-up approach Answer B Explanation The Delphi technique uses experts and builds to consensus; therefore, expert opinion is the chief characteristic. A project has had some problems, but now seems under control. In the last few months, almost all the reserve has been used up and most of the negative impacts of events that had been predicted have occurred. There are only four activities left, and two of them are on the critical path. Management now informs the project manager that it would be in the performing organization's. Answer B. Monte Carlo analysis is used to: A. Get an indication of the risk involved in the project. B. Estimate an activity's length. C. Simulate the order in which activities occur. D. Prove to management that extra staff is needed. Answer A Explanation Answer A Explanation This question essentially asks, What is an output of the Perform Qualitative Risk Analysis process? Only Choice A meets that criteria. Choices Band C are parts of the Plan Risk Responses process. Choice D occurs during the Perform Quantitative Risk Analysis process. A project manager is creating a risk response plan. However, every time a risk response is suggested, another risk is identified that is caused by the response. Which of the following is the BEST thing for the project manager to do? A. Document the new risks and continue the Plan Risk Responses process. B. Make sure the project work is better understood. C. Spend more time making sure the risk responses are clearly defined. D. Get more people involved in the Identify Risks process, since risks have been missed. Answer A Explanation Did you realize this question describes secondary risks? Identifying secondary risks is good and expected while completing the Plan Risk Responses process. With that in mind, the best thing to do is choice A. A watchlist is an output of which risk management process? A. Plan Risk Responses B. Perform Quantitative Risk Analysis C. Perform Qualitative Risk Analysis D. Plan Risk Management Answer C Explanation A watch list is made up of low priority risks that, in the Perform Qualitative Risk Analysis process, were determined to be of too low priority or low impact to move further in the risk process. During the Identify Risks process, a project manager made a long list of risks identified by all the stakeholders using various methods. He then made sure that all the risks were understood and that triggers had been identified. Later, in the Plan Risk Responses process, he took all the risks identified by the stakeholders and determined ways to mitigate them. What has he done wrong?. Answer B Explanation Stakeholders (choice A) are involved in the Identify Risks process. Workarounds (choice C) are created later in the risk process. Plan Risk Responses must include the involvement of all risk response owners and possibly others. This makes choice B the correct answer. Which of the following MUST be an agenda item at all team meetings? A. Discussion of project risks B. Status of current activities C. Identification of new activities D. Review of project problems Answer A Explanation Risk is so important that it must be discussed at all team meetings. Procurement Management CHAPTER TWELVE Once signed, a contract is legally binding unless: A. One party is unable to perform. B. One party is unable to finance its part of the work. C. It is in violation of applicable law. D. It is declared null and void by either party's legal counsel. Answer C Explanation Once signed, a contract is binding. Generally, the inability to perform, get financing, or one party's belief that the contract is null and void does not change the fact that the contract is binding. If, however, both sides agree to terminate the contract, the contract can move into closure. Once closure is completed, the project is considered completed. With a clear contract statement of work, a seller completes work as specified, but the buyer is not pleased with the results. The contract is considered to be: A. Null and void. B. Incomplete. C. Complete. D. Waived. Answer C Explanation If the seller completes the work specified in the procurement statement of work, the contract is considered complete. That does not mean the same thing as contract closed. The Close Procurements process must still occur. However, in this situation, the contract work is completed. Tricky! All of the following statements concerning procurement documents are incorrect EXCEPT: A. Well-designed procurement documents can simplify comparison of responses. B. Procurement documents must be rigorous with no flexibility to allow consideration of seller suggestions. C. In general, bid documents should not include evaluation criteria. D. Well-designed procurement documents do not include a procurement statement of work. Answer A Explanation Often the seller is required to inform the buyer of anything that is missing or unclear in the procurement documents (choice B). It is in the buyer's best interest to discover missing items, since it will save the buyer money and trouble to correct the problem early. Procurement documents must contain terms and conditions and evaluation criteria (choice C) as well as all the work that is to be done, including the procurement statement of work (choice D). This is so the seller can price the project and know what is most important to the buyer. Choice A is an important point for the real world and is the best answer. A project manager for the seller is told by her management that the project should do whatever possible to be awarded incentive money. The primary objective of incentive clauses in a contract is to: A. Reduce costs for the buyer. B. Help the seller control costs. C. Synchronize objectives. D. Reduce risk for the seller by shifting risk to the buyer. Answer C Explanation Incentives are meant to bring the objectives of the seller in line with those of the buyer. That way both are progressing toward the same objective. All the following statements about change control are incorrect EXCEPT: A. A fixed price contract will minimize the need for change control. B. Changes seldom provide real benefits to the project. C. Contracts should include procedures to accommodate changes. D. More detailed specifications eliminate the causes of changes. Answer C Explanation Since there can be changes in any form of contract, choice A is not the best answer. There are always good ideas (changes) that can add benefit to the project, so choice B cannot be the best answer. In choice D, the word eliminate implies that changes will not occur. As that is not true, this cannot be the best answer. A routine audit of a cost reimbursable (CR) contract determines that overcharges are being made. If the contract does not specify corrective action, the buyer should: A. Continue to make project payments. B. Halt payments until the problem is corrected. C. Void the contract and start legal action to recover overpayments. D. Change the contract to require more frequent audits. Answer A Explanation Notice that choice B is really saying halt ALL payments. Halting all payments would be a breach of contract on the buyer's part. Choice C is too severe and cannot be done unilaterally. Choice D does not solve the problem presented. A choice that said, Halt payments on the disputed amount would probably be the best answer, but it is not offered. The best answer is A. The primary objective of contract negotiations is to: A. Get the most from the other side. B. Protect the relationship. C. Get the highest monetary return. D. Define objectives and stick to them. Answer B Explanation As a project manager, you want to develop a relationship during negotiations that will last throughout the project. A seller is working on a cost reimbursable (CR) contract when the buyer decides he would like to expand the scope of services and change to a fixed price (FP) contract. All of the following are the seller's options EXCEPT: A. Completing the original work on a cost reimbursable basis and then negotiating a fixed price for the additional work. B. Completing the original work and rejecting the additional work. C. Negotiating a fixed price contract that includes all the work. D. Starting over with a new contract. Answer D Explanation The seller does not have the choice to start over. The contract that exists is binding. Both parties could agree to start over, but this is a drastic step. All of the following MUST be present to have a contract EXCEPT: A. Procurement statement of work B. Acceptance C. Address of the seller D. Buyers' signatures Answer C Explanation Many people miss the fact that a contract includes a procurement statement of work (choice A). To have a contract, you must also have acceptance (choice B). One set of signatures is not enough; you must have sign-off (i.e., acceptance) from both parties, so choice D is only partially correct. The address of the seller (choice C) is not required, and therefore is the exception. Which of the following BEST describes the project manager's role during the procurement process? A. The project manager has only minor involvement. B. The project manager should be the negotiator. C. The project manager should supply an understanding of the risks of the project. D. The project manager should tell the contract manager how the contracting process should be handled. Answer C Explanation As the project manager, you know what the project risks are. You need to make sure that provisions are included in the contract to address these risks. What is one of the KEY objectives during contract negotiations? A. Obtain a fair and reasonable price. B. Negotiate a price under the seller's estimate. C. Ensure that all project risks are thoroughly delineated. D. Ensure that an effective communications management plan is established. Answer A Explanation Choices C and D are good ideas, but not the key objective. Negotiations should be win/win, so choice B is not the best choice. A fair and equitable price (choice A) will create a good working atmosphere. Otherwise, you will pay later, on change orders. Which of the following activities occurs during the Plan Procurements process? A. Make-or-buy decisions B. Answering sellers' questions about the bid documents C. Advertising D. Proposal evaluation Answer A Explanation Answering sellers' questions (choice B), advertising (choice C), and proposal evaluation (choice D) occur during the Conduct Procurements process. Which of the following is the BEST thing for a project manager to do in the Conduct Procurements process of procurement management? A. Evaluate risks B. Select a contract type C. Update the project schedule D. Answer sellers' questions about bid documents Answer D Explanation During the Conduct Procurements process, you normally answer questions submitted by the sellers. The risk analysis processes (choice A) are done before the procurement process begins, as procurement is a risk mitigation and transference tool. Selecting a contract type (choice B) is part of Plan Procurements. Changes to the project schedule (choice C) may be an output of the Administer Procurements process. The sponsor is worried about the seller deriving extra profit on the cost plus fixed fee (CPFF) contract. Each month he requires the project manager to submit CPI calculations and an analysis of the cost to complete. The project manager explains to the sponsor that extra profits should NOT be a worry on this project because: A. The team is making sure the seller does not cut scope. B. All costs invoiced are being audited. C. There can only be a maximum 10 percent increase if there is an unexpected cost overrun. D. The fee is only received by the seller when the project is completed. Answer B Explanation Choice A cannot be best because cutting scope decreases profits on this type of contract. Choice C cannot be best, as CPFF contracts generally do not limit fee increases. Choice D cannot be best, as the fee in a CPFF contract is usually paid out on a continuous basis during the life of the project. One of the ways to change the profit in a cost plus fixed fee contract is to invoice for items not chargeable to the project (choice B). In a fixed price (FP) contract, the fee or profit is: A. Unknown. B. Part of the negotiation involved in paying every invoice. C. Applied as a line item to every invoice. D. Determined with the other party at the end of the project. Answer A Explanation To the seller, it is known, but this question is from the buyer's perspective. You do not know what profit the seller included in the contract. A project performed under a cost reimbursable contract has finally entered the Close Procurements process. What MUST the buyer remember to do? A. Decrease the risk rating of the project. B. Audit seller's cost submittals. C. Evaluate the fee he is paying. D. Make sure that the seller is not adding resources. Answer B Explanation Although a reserve might be decreased for the project overall when one of its contracts enters closure, the risk rating of the project (choice A) may not be affected. Choice C should have been done during the Conduct Procurements process. Although choice D may be a concern during the Administer Procurements process, it is not common during Close Procurements. Choice B, audit seller's cost submittals, is part of the procurement audit and is a required aspect of Close Procurements. The sponsor and the project manager are discussing what type of contract the project manager plans to use on the project. The buyer points out that the performing organization spent a lot of money hiring a design team to come up with the design. The project manager is concerned that the risk for the buyer be as small as possible. An advantage of a fixed price contract for the buyer is: A. Cost risk is lower. B. Cost risk is higher. C. There is little risk. D. Risk is shared by all parties. Answer A Explanation If you had trouble with this one, you need to remember that the questions are asked from the buyer's perspective unless otherwise noted. In this case, the seller has the most cost risk, and the buyer's risk is lower. As part of the records management system, you are trying to make sure that all records from the procurement are documented and indexed. Which of the following do you NOT have to worry about? A. Proposal B. Procurement statement of work C. Terms and conditions D. Negotiation process Answer D Explanation You will see long, wordy questions consisting of many paragraphs on the exam, but do not let them worry you. Sometimes the briefer questions are harder. To answer this question, you need to know what a records management system is and that it would not be used to keep track of negotiations. the negotiation process is not a document. You are in the middle of a complex negotiation when the other party says, "We need to finish in one hour because I have to catch my plane." That person is using which of the following negotiation strategies? A. Good guy, bad guy B. Delay C. Deadline D. Extreme demands Answer C Explanation Putting a time limit on the negotiation is an example of deadline. Which of the following is an advantage of centralized contracting? A. Increased expertise B. Easier access C. No home D. More loyalty to the project Answer A Explanation Centralized contracting usually means harder access and less loyalty. Therefore choices B and D are disadvantages. The fact that procurement managers have no home when they're not working on a project (choice C) is also a disadvantage. With which type of contract is the seller MOST concerned about project scope? A. Fixed price B. Cost plus fixed fee C. Time and material D. Purchase order Answer A Explanation In a fixed price contract, the seller has the cost risk and therefore wants to completely understand the procurement statement of work before bidding. Your company has an emergency and needs contracted work done as soon as possible. Under these circumstances, which of the following would be the MOST helpful to add to the contract? A. A clear procurement statement of work B. Requirements as to which subcontractors can be used C. Incentives D. A force majeure clause Answer C Explanation If you follow the proper project management process, you ALWAYS have good definition of scope (choice A). In this situation, you are in a time crunch. Both good scope definition and incentives are required to make it happen. Which provides the better answer? Along with good scope definition, you need the seller to feel your need for speed. Incentives bring the seller's objectives in line with the buyer's and thus would be the MOST helpful. Good cope definition alone does not ensure speed. The project team is arguing about the prospective sellers who have submitted proposals. One team member argues for a certain seller while another team member wants the project awarded to a different seller. What part of the procurement process is the team in? A. Plan Procurements B. Administer Procurements C. Negotiate Contract D. Conduct Procurements Answer D Explanation Selected sellers are an output of the Conduct Procurement process. The project team seems to like to argue; they have argued about everything. Luckily the project manager has set in place a reward system and team-building sessions that will help and encourage the team to cooperate more. The latest thing they are arguing about is whether they should complete a work package themselves or outsource the work to someone else. What part of the procurement process must they be in? A. Conduct Procurements B. Plan Procurements C. Administer Procurements D. Claims Administration Answer B Explanation Notice that much of this question is irrelevant? Did you also notice that the words make-or-buy decision were not used in the question? Instead, the question used the definition of make-or-buy. Watch out for this on the exam. A make-or-buy decision is needed before the rest of the procurement process can occur. Therefore, the situation must be taking place in one of the early steps of the procurement process. A project manager is in the middle of creating a request for proposal (RFP). What part of the procurement process is she in? A. Conduct Procurements B. Plan Procurements C. Administer Procurements D. Make-or- Buy Analysis Answer B Explanation In the Plan Procurements process, we create the procurement documents. The request for proposal is one of those) Answer D Explanation Of the options given, the only contract that limits fees for large projects with limited scope definition is cost plus fixed fee. Negotiations between two parties are becoming complex, so party A makes some notes that both parties sign. However, when the work is being done, party B claims that they are not required to provide an item they both agreed to during negotiations, because it was not included in the subsequent contract. In this case, party B is: A. Incorrect, because both parties must comply with what they agreed upon. B. Correct, because there was an offer. C. Generally correct, because both parties are only required to perform what is in the contract. D. Generally incorrect, because all agreements must be upheld. Answer C Explanation Party B is only required to deliver what is defined in the contract. Your project has just: A. Collusion between subcontractors. B. The subcontractor's qualifications. C. The subcontractor's evaluation criteria. D. Holding a bidder conference. Answer B Explanation Although you have used this contractor before, how can you be sure the company is qualified to do the new work, since it is not exactly like the previous work? This is the risk you are taking.: A. There is a lot of proprietary data. B. You have the expertise but you do not have the available manpower. C. You do not need control over the work. D. Your company resources are limited. Answer A Explanation It is generally better to do the work yourself if using an outside company means you have to turn over proprietary data to the other company. After much excitement and hard work, the procurement statement of work for the project is completed. Even after gaining agreement that the procurement statement of work is complete, the project manager is still concerned whether it actually addresses all the buyer's needs. The project manager is about to attend the bidder conference. He asks you for advice on what to do during the session. Which of the following is the BEST advice you can give him? A. You do not need to attend this session. The contract manager will hold it. B. Make sure you negotiate project scope. C. Make sure you give all the sellers enough time to ask questions. They may not want to ask questions while their competitors are in the room. D. Let the project sponsor handle the meeting so you can be the good guy in the negotiation session. Answer C Explanation The project manager should attend the bidder conference, so choice A is incorrect. Did you select choice B because the question referred to a concern about scope? Then read the choice again. It talks about negotiation, and negotiation occurs after the seller is selected, not during the bidder conference. The procurement manager usually holds the bidder conference, so choice D is incorrect. Choice C describes one of the many challenges of a bidder conference and is therefore the best answer. A seller is awarded a contract to build a pipeline. The contract terms and conditions require that a work plan be issued for the buyer's approval prior to commencing work, but the seller fails to provide one. Which of the following is the BEST thing for the buyer's project manager to do? A. File a letter of intent. B. Develop the work plan and issue it to the seller to move things along. C. Issue a default letter. D. Issue a stop work order to the seller until a work plan is prepared. Answer C Explanation Any time that a seller does not perform according to the contract, the project manager must take action. The preferred choice might be to contact the seller and ask what is going on, but that choice is not available here. Therefore, the best choice is to let him know he is in default (choice C). Close Procurements is different from Close Project or Phase in that Close Procurements: A. Occurs before Close Project or Phase. B. Is the only one to involve the customer. C. Includes the return of property. D. May be done more than once for each contract. Answer A Explanation Choice B cannot be correct since the customer may be involved in lessons learned and procurement audits and would certainly be involved in formal acceptance. Choice C cannot be correct since both Close Procurements and Close Project or Phase involve the return of property. Close Procurements is done only once for each contract, so choice D cannot be correct. Choice A is correct because contracts are closed out before the project is closed out with the Close Project or Phase process. You have just started administrating a contract when management decides to terminate the contract. What should you do FIRST? A. Go back to the Plan Procurements process. B. Go back to the Conduct Procurements process. C. Finish the Administer Procurements process. D. Go to the Close Procurements process. Answer D Explanation If the contract is terminated, the project needs to enter closure. You need those results for historical purposes.. Answer C Explanation The evaluation criteria are the primary tools for evaluating potential sellers and should be used by the entire team in order to make a selection. The performing organization is trying to decide whether to split the contracts department and assign procurement responsibilities to departments directly responsible for the projects. A procurement professional might not want this split to occur because they would lose __________ in a decentralized contracting environment. A. Standardized company project management practices B. Loyalty to the project C. Experience D. Access to others with similar expertise Answer D Explanation Choice A is incorrect, as the change would not impact the entire project management process, only procurement. Loyalty to the project (choice B) would be gained, not lost, in a decentralized environment. In a decentralized procurement situation, there is less focus on maintaining the skill or expertise of the contracting function, making choice D the best answer. During project executing, your project team member delivers a project deliverable to the buyer. However, the buyer refuses the deliverable, stating that it does not meet the requirement on page 300 of the technical specifications. You review the document and find that you agree. What is the BEST thing to do? A. Explain that the contract is wrong and should be changed. B. Issue a change order. C. Review the requirements and meet with the responsible team member to review the WBS dictionary. D. Call a meeting of the team to review the requirement on page 300. Answer C Explanation In choice A, the contract could be wrong, or the customer could be wrong, but this would have/should have been discovered earlier if proper project management was followed. If you picked choice B, you have forgotten that a seller cannot issue a change order (although he could request one). Did you select choice D? If so, remember that project management is not about making every decision with ALL the team members. Choice C involves meeting with the appropriate team member. If such a problem has arisen, it could mean something was wrong in the WBS dictionary or in how the team member completed the work. What type of contract do you NOT want to use if you do not have enough labor to audit invoices? A. Cost plus fixed fee (CPFF) B. Time & material (T&M) C. Fixed price (FP) D. Fixed price incentive fee (FPIF) Answer A Explanation If you got this question wrong, reread it. You need to audit invoices in all contract types, so how do you choose? Look for the answer that is BEST. In this case, it would be the choice that requires the greatest effort. A T&M contract (choice B) should be for small dollars and short duration (remember that a T&M contract has no incentive to finish), so it does not have a great risk. Choices C and D cannot be best because the risk to the buyer is limited-they are still only going to pay the contract price. In a CPFF contract, the buyer pays all costs. The seller could be charging the buyer for costs that should not be allocated to the buyer. Because of the size and dollar amount of these type of contracts and because the risk to the buyer is great, CPFF contracts need the most auditing. Since this question asked for which one you do not want to use, the answer must be choice A. A new project manager is about to begin creating the procurement statement of work. One stakeholder wants to add many items to the procurement statement of work. Another stakeholder only wants to describe the functional requirements. The project is important for the project manager's company, but a seller will do the work. How would you advise the project manager? A. The procurement statement of work should be general to allow the seller to make his own decisions. B. The procurement statement of work should be general to allow clarification later. C. The procurement statement of work should be detailed to allow clarification later. D. The procurement statement of work should be as detailed as necessary for the type of project. Answer D Explanation When the seller has more expertise than the buyer, the procurement statement of work should describe performance or function rather than a complete list of work. In any case, the procurement statement of work should be as detailed as possible. Professional and Social Responsibility CHAPTER THIRTEEN A project manager is being considered for a particular project that will deal exclusively with global virtual teams. He only has experience with local teams. What should he do when discussing the opportunity with the sponsor? A. Since he has led projects and teams, it does not make any difference that these are all global virtual teams, so he does not need to bring it up. B. He should avoid any conversation regarding the types of teams involved so the sponsor does not know he lacks experience in this area. C. The project manager should point out to the sponsor that he has not had experience with global virtual teams, but discuss why he thinks he is a good fit for the project anyway. D. The project manager should point out to the sponsor that he has not had experience with global virtual teams and therefore must decline the assignment. Answer C Explanation Choice A is incorrect because there are many issues that will be different in this project than those the project manager has experience with. Choice B is unethical and constitutes lying about his qualifications. Choice D is not right because the project manager may have so many skills that would benefit the project that this might not be a major problem. We must make sure sponsors know of any gaps in our qualifications when taking on assignments. A project manager gathered data to perform earned value calculations on his project. He used the results to report to management that the project is under budget and on schedule. After reporting this information, he discovered that the base figures he used in the calculations were incorrect, as they came from an old copy of the project file which had not been updated. What should he do now? A. He should contact management to make them aware of the error, give the correct information, and explain how he made the mistake. B. He should contact management and tell them to expect some changes in the next reporting period, and that things are starting to look gloomy. C. He should use the correct figures to calculate the information when it is time for the next report and ignore the fact the he reported incorrect information. D. He should tell management that the data he received from team members was incorrect and thus the report was not accurate. Answer A Explanation Choice B is not the truth of the matter. Although things may be gloomy, this is not a new development, since the report was based on old data. Choice C is not right since he is not admitting his mistake, the ethical thing to do, and choice D is blaming someone else for his own error. Choice A is correct since the ethical thing to do is to acknowledge and take responsibility for the error. A project manager is working with a vendor on a project when she learns that the vendor has bribed a subcontractor to work on this project instead of fulfilling previous commitments to other projects. What should the she do? A. She should report the offense to management and the project managers of the affected projects. B. She should not do anything because this is the vendor's problem. The project manager herself didn't do anything wrong. C. She should report this to other subcontractors so they know they could get more money from the vendor. D. She should resign from the project so as to remove herself from this type of activity, but keep it to herself rather than cause problems. Answer A Explanation Choices Band C do not inform management and the other project managers affected, so are not the best way to deal with this. Not reporting this knowledge (choice D) to the appropriate people is unethical. Choice A is correct because it is the responsibility of the project manager to report unethical behavior to management and those affected. You are in the middle of a new product development Band C hide it. Choice D ignores it. Only choice A deals with it. A decision has to be made regarding project selection. Several project managers have been asked to give their opinions to the executive committee. Each project manager has a personal interest because the project chosen will drive which project manager will be assigned. The project chosen will be high priority and high visibility, with substantial reward for success. How should the project managers make their recommendations? A. They should each explain why the project they would be in charge of would be the best to choose and provide documentation to substantiate it. B. They should recommend the project that would be best for the company in the long run, regardless of who is going to run it. C. They should make a chart that shows the pros and cons of each project making sure to list more pros for the one they would run and less cons to prove its value. D. They should not give an opinion since it would not be objective. Answer B Explanation Although choice D sounds like a good option, it is not the best, since the project managers have been asked for their input. Choices A and C are incorrect because the project managers would be promoting their own interests, rather than that of the organization. Choice B is best since it suggests being objective and making impartial recommendations in the best interest of the organization. When checking the calendar of a team member to schedule a meeting, you see she has scheduled a meeting with a key stakeholder that you were not informed of. The BEST approach would be to: A. Avoid mentioning it to the team member but continue to watch her activities. B. Notify your boss about the problem. C. Address the concern with the team member's boss. D. Address the concern with the team member. Answer D Explanation Always look for the choice that deals with and solves the problem. Choice A is withdrawal. Choices Band C would not be appropriate until you learn the root cause of the problem. Your employee is three days late with a report. Five minutes before the meeting where the topic of the report is to be discussed, she hands you the report. You notice some serious errors in it. What should you do? A. Cancel the meeting and reschedule when the report is fixed. B. Go to the meeting and tell the other attendees there are errors in the report. C. Force the employee to do the presentation and remain silent as the other attendees find the errors. D. Cancel the meeting and rewrite the report yourself. Answer A Explanation Choice C is penalizing the employee and making her lose face. Choices B, C, and D all involve decreasing the employee's morale. Therefore, the best choice, and the one that does not waste everyone's time, is to cancel the meeting, get to the root cause of the problem, and then fix it and reschedule the meeting (partially mentioned in choice A). and. fee for service paid to a government official and is therefore not a bribe.? You've been assigned to take over managing a project that should be half complete according to the schedule. After an extensive evaluation, you discover that the project is running far behind schedule, and that the project will probably take twice the time originally estimated by the previous project manager. However, the sponsor has been told that the project is on schedule. What is the BEST course of action? A. Try to restructure the schedule to meet the project deadline. B. Report your assessment to the sponsor. C. Turn the project back to the previous project manager. D. Move forward with the schedule as planned by the previous project manager and report at the first missed milestone. Answer B Explanation Choice C is not possible, as the previous project manager may have left the company or he may be busy with new projects. It is a form of withdrawal. Moving ahead (choice D) also withdraws from the problem, and withdrawal is not the best choice. There are two problems described here; the project is behind, and the sponsor does not know it. There seem to be two possible right answers, choices A and B. Which is the best thing to deal with? Certainly it would be to work to get the project on schedule, but look at what choice A says. It limits the effort to restructuring the schedule and does not consider other options, such as cutting scope, that might more effectively deal with the problem. Choice A is too limiting. What if the sponsor would agree to change the due date? The best choice in THIS situation is to inform the sponsor of the revised completion time estimate. You are halfway through a major network rollout. There are 300 locations in the United States with another another 20 in England. A software seller has just released a major software upgrade for some of the equipment being installed. The upgrade would provide the customer with functionality they requested that was not available at the time the project began. What is the BEST course of action under these circumstances? A. Continue as planned, your customer has not requested a change. B. Inform the customer of the upgrade and the impacts to the project's timeline and functionality if the upgrade is implemented. C. Implement the change and adjust the schedule as necessary because this supports the customer's original request. D. Implement the change to the remaining sites and continue with the schedule. Answer B Explanation Professional and social responsibility includes looking after the customer's best interests. Therefore, choice A cannot be best. In this case, the schedule and scope are already approved and all changes must go through the change control process. Therefore, choices C and D cannot be best. You are a project manager for one of many projects in a large and important program. At a high-level status meeting, you note that another project manager has reported her project on schedule. Looking back on your project over the last few weeks, you remember many deliverables from the other project that arrived late. What should you do? A. Meet with the program manager. B. Develop a risk control plan. C. Discuss the issue with your boss. D. Meet with the other project manager. Answer D Explanation Professional and social responsibility dictates that you should confront the situation first with the other project manager (choice D) to find out if the other project is really on schedule and thereby confirm or deny your information. Choice A or C would be the second step if choice D validates your concern. Choice B would be a more likely choice if it referred to an earlier step in risk management. But choice D remains the best answer. You have always been asked by your management to cut your project estimate by 10 percent after you have given it to them. The scope of your new project is unclear and there are over 30 stakeholders. Management expects a 25 percent reduction in downtime as a result of the project. Which of the following is the BEST course of action in this situation? A. Replan to achieve a 35 percent improvement in downtime. B. Reduce the estimates and note the changes in the risk response plan. C. Provide an accurate estimate of the actual costs and be able to support it. D. Meet with the team to identify where you can find 10 percent savings.'s looking for options related to the other project constraints. Choice A does not address costs, the issue at. You are in the middle of a project when you discover that a software seller for your project is having major difficulty keeping employees due to a labor dispute. Many other projects in your company are also using the company's services. What should you do? A. Attempt to keep the required people on your project. B. Tell the other project managers in your company about the labor problem. C. Contact the company and advise it that you will cancel its work on the project unless it settles its labor dispute. D. Cease doing business with the company. Answer B Explanation Choice A puts your interests over those of your company so it cannot be the best choice. There is no indication that the labor dispute has caused any problems, so there is no need to cancel its work (choice C) or cease doing business with the company (choice D). The best choice would be to inform others in your company. All of the following are the responsibility of a project manager EXCEPT: A. Maintain the confidentiality of customer confidential information. B. Determine the legality of company procedures. C. Ensure that a conflict of interest does not compromise the legitimate interest of the customer. D. Provide accurate and truthful representations in cost estimates. Answer B Explanation The project manager is neither empowered nor competent to determine the legality of company procedures. NOTE: There is an important distinction between practices and procedures. All unethical practices should be reported. For example, a project manager must report an act of fraud. Fraud is not a company procedure (normally). However, a project manager is not in a position to determine whether company procedures comply with existing law. In order to complete work on your projects, you have been provided confidential information from all of your clients. A university contacts you to help it in its research. Such assistance would require you to provide the university with some of the client data from your files. What should you do? A. Release the information, but remove all references to the clients' names. B. Provide high-level information only. C. Contact your clients and seek permission to disclose the information. D. Disclose the information. Answer C Explanation Confidential information should be respected (not disclosed to third parties without the express approval of the client). If you picked choice A, remember that the clients own the confidential information. See, not all professional and social responsibility questions are tough! out customer. You have just discovered an error in the implementation plan that will prevent you from meeting a milestone date. The BEST thing you can do is: A. Develop options to meet the milestone date. B. Change the milestone date. C. Remove any discussion about due dates in the project status report. D. Educate the team about the need to meet milestone dates. Answer A Explanation Only choice A solves the problem. Choice B is unethical. Choice C violates the rule to report honestly. While testing the strength of concrete poured on your project, you discover that over 35 percent of the concrete does not meet your company's quality standards. You feel certain the concrete will function as it is, and you don't think the concrete needs to meet the quality level specified. What should you do? A. Change the quality standards to meet the level achieved. B. List in your reports that the concrete simply meets our quality needs:' C. Ensure the remaining concrete meets the standard. D. Report the lesser quality level and try to find a solution. Answer D Explanation Can you explain why choices A and B are unethical? Choice C simply withdraws from the problem and is therefore not the best solution. The only possible choice is D. That choice would involve quality and other experts to find a resolution. of the project manager's communications. Answer C Explanation You should have noticed that only choices A and C involve more people than just the project manager. Since this is an issue involving everyone, everyone should be involved. Choice A may be a good idea in all cases; however, it does not specifically address cultural issues. Therefore, the answer must be C.. A certified PMP is contacted by PMI and asked to provide information regarding another project manager who has been reported to be involved in unethical activities. The PMP-certified project manager knows his information would support the accusations and the other project manager in question is a friend. He decides that the best thing to do would be to not respond, and therefore neither confirm nor deny the accusations. Would this be the right thing to do? A. Yes. It would be a safe thing to do to just ignore the request and stay out of it. B. No. If he knows something, he is required by the Code of Ethics and Professional Conduct conduct to cooperate. C. No. It would be better to deny the charges against his friend to maintain the relationship. D. Yes. It is expected that project managers will support each other in the field against outsiders. Answer B Explanation Choices A and D do not support PMI's request for information. Choice C would be lying. Choice B is correct, as PMI's Code of Ethics and Professional Conduct requires PMP-certified project managers to report unethical behavior and violations of the code. The PMP-certified project manager is obligated to cooperate with PMI in collecting information. A project manager discovers a defect in a deliverable due to the customer under contract today. The project manager knows the customer does not have the technical understanding to notice the defect. The deliverable meets the contract requirements, but it does not meet the project manager's quality standard. What should the project manager do in this situation? A. Issue the deliverable and get formal acceptance from the customer. B. Note the problem in the lessons learned so future projects do not encounter the same problem. C. Discuss the issue with the customer. D. Inform the customer that the deliverable will be late. Answer C Explanation Choice A does not follow the rule to protect the best interests of the customer. Choice B does not solve the problem. Choice D will cause a default of contract. Although the deliverable meets the contractual requirements, it is best to bring the problem to the customer's attention (choice C) so an option that does no harm can be found. Management tells a project manager to subcontract part of the project to a company that management has worked with many times. Under these circumstances, the project manager should be MOST concerned about: A. Making sure the company has the qualifications to complete the project. B. Meeting management expectations of time. C. The cost of the subcontracted work. D. The contract terms and conditions. Answer A Explanation The first thing that should come to mind is whether this is an ethical situation and whether it violates any company rules or laws. If it does not violate any of these, it would be best to check qualifications (choice A). There is no justification to rate choices B, C, or D higher than any other choice.? A. He should tell the students that they need to become familiar with the how things are done in this country and that they must play along. B. He should excuse the students from playing and arrange to discuss with them alternative activities that they would be more comfortable with. C. He should report the students to their functional manager and request they be removed from the project since their attitude will have a negative impact on the project. D. He should tell the students they are excused from the activities and to not attend any team building activities in the future. Answer B Explanation Choice A is forcing the team members to do something that is unacceptable in their culture. Choice C penalizes the team members for expressing their cultural preferences, which is not a valid reason to remove them from the team. Excluding them from all future team building (choice D) does not show respect for their culture, and would have a negative impact on the project. Choice B is best because it demonstrates respect for cultural ,differences. A project manager discovers an urgent need for outsourced resources on the project. He knows he has the money to cover the cost of these resources. He goes to the procurement manager and explains the situation, insisting a contract be drawn up today so he can obtain resources and circumvent the standard procedure. Is this the correct process to follow? A. Yes, of course. For urgent needs, it is not necessary to follow the organization's procedure regarding procurement. B. Yes. Urgent needs from projects should always be dealt with immediately as directed by the project manager. C. No. The procurement manager has a process to follow when creating contracts that helps protect the company and its projects. D. No. The procurement manager should be checking in with the project manager to see if he is in need of a contract, rather than making the project manager come and ask for one. Answer C Explanation Procrastination or a lack of planning on the part of the project manager does not create an emergency situation for the procurement manager. Circumventing the process (choice A) is not ethical. Choice B implies that projects always come first, and that the project manager has authority over the procurement manager. Choice D is not a common practice, nor is it logical. Choice C is the correct answer because it demonstrates respect for the procurement manager and the processes in place to protect the organization. The engineering department wants the project objective to be a 10 percent improvement in throughput. The information technology department wants no more than 5. You are finalizing the monthly project status report due now to your manager when you discover that several project team members are not reporting actual hours spent on project activities. This results in skewed project statistics. What is the MOST appropriate action to be taken? A. Discuss the impacts of these actions with team members. B. Report the team members' actions to their functional managers. C. Continue reporting information as presented to you. D. Provide accurate and truthful representations in all project reports. Answer D Explanation The project manager's responsibility is to provide truthful project information. The project manager should thereafter discuss the impacts of his or her actions with the team members. If that does not work, the next step is to report it to the functional managers.
http://quizlet.com/5004050/rita-pmp-questions-flash-cards/
CC-MAIN-2013-48
refinedweb
28,611
66.33
Name | Synopsis | Parameters | Description | Return Values | Examples | Attributes | See Also | Notes cc [ flag... ] file... -lsocket -lnsl [ library... ] ); Address family Various flags Name of host Error storage Address for lookup Length of address Pointer to hostent structure The getipnodebyname() function searches the ipnodes database from the beginning. The function finds the first h_name member that matches the hostname specified by name. The function takes an af argument that specifies the address family. The address family can be AF_INET for IPv4 addresses or AF_INET6 for IPv6 addresses. The flags argument determines what results are returned based on the value of flags. If the flags argument is set to 0 (zero), the default operation of the function is specified as follows: If the af argument is AF_INET, a query is made for an IPv4 address. If successful, IPv4 addresses are returned and the h_length member of the hostent structure is 4. Otherwise, the function returns a NULL pointer. If the af argument is AF_INET6, a query is made for an IPv6 address. If successful, IPv6 addresses are returned and the h_length member of the hostent structure is 16. Otherwise, the function returns a NULL pointer. The flags argument changes the default actions of the function. Set the flags argument with a logical OR operation on any of combination of the following values: AI_V4MAPPED AI_ALL AI_ADDRCONFIG The special flags value, AI_DEFAULT, should handle most applications. Porting simple applications to use IPv6 replaces the call hptr = gethostbyname(name); with hptr = getipnodebyname(name, AF_INET6, AI_DEFAULT, &error_num); The flags value 0 (zero) implies a strict interpretation of the af argument: If flags is 0 and af is AF_INET, the caller wants only IPv4 addresses. A query is made for A records. If successful, IPv4 addresses are returned and the h_length member of the hostent structure is 4. Otherwise, the function returns a NULL pointer. If flags is 0 and af is AF_INET6, the caller wants only IPv6 addresses. A query is made for AAAA records. If successful, IPv6 addresses are returned and the h_length member of the hostent structure is 16. Otherwise, the function returns a NULL pointer. Logically OR other constants into the flags argument to modify the behavior of the getipnodebyname() function. If the AI_V4MAPPED flag is specified with af set to AF_INET6, the caller can accept IPv4-mapped IPv6 addresses. If no AAAA records are found, a query is made for A records. Any A records found are returned as IPv4-mapped IPv6 addresses and the h_length is 16. The AI_V4MAPPED flag is ignored unless af equals AF_INET6. The AI_ALL flag is used in conjunction with the AI_V4MAPPED flag, exclusively with the IPv6 address family. When AI_ALL is logically ORed with AI_V4MAPPED flag, the caller wants all addresses: IPv6 and IPv4-mapped IPv6 addresses. A query is first made for AAAA records and, if successful, IPv6 addresses are returned. Another query is then made for A records. Any A records found are returned as IPv4-mapped IPv6 addresses and the h_length is 16. Only when both queries fail does the function return a NULL pointer. The AI_ALL flag is ignored unless af is set to AF_INET6. The AI_ADDRCONFIG flag specifies that a query for AAAA records should occur only when the node is configured with at least one IPv6 source address. A query for A records should occur only when the node is configured with at least one IPv4 source address. For example, if a node is configured with no IPv6 source addresses, af equals AF_INET6, and the node name queried has both AAAA and A records, then: A NULL pointer is returned when only the AI_ADDRCONFIG value is specified. The A records are returned as IPv4-mapped IPv6 addresses when the AI_ADDRCONFIG and AI_V4MAPPED values are specified. The special flags value, AI_DEFAULT, is defined as #define AI_DEFAULT (AI_V4MAPPED | AI_ADDRCONFIG) The getipnodebyname() function allows the name argument to be a node name or a literal address string: a dotted-decimal IPv4 address or an IPv6 hex address. Applications do not have to call inet_pton(3SOCKET) to handle literal address strings. Four scenarios arise based on the type of literal address string and the value of the af argument. The two simple cases occur when name is a dotted-decimal IPv4 address and af equals AF_INET and when name is an IPv6 hex address and af equals AF_INET6. The members of the returned hostent structure are: Pointer to a copy of the name argument NULL pointer. Copy of the af argument. 4 for AF_INET or 16 for AF_INET6. Array of pointers to 4-byte or 16-byte binary addresses. The array is terminated by a NULL pointer. Upon successful completion, getipnodebyname() and getipnodebyaddr() return a hostent structure. Otherwise they return NULL. The hostent structure does not change from the existing definition when used with gethostbyname(3NSL). For example, */ }; An error occurs when name is an IPv6 hex address and af equals AF_INET. The return value of the function is a NULL pointer and error_num equals HOST_NOT_FOUND. The getipnodebyaddr() function has the same arguments as the existing gethostbyaddr(3NSL) function, but adds an error number. As with getipnodebyname(), getipnodebyaddr() is thread-safe. The error_num value is returned to the caller with the appropriate error code to support thread-safe error code returns. The following error conditions can be returned for error_num: Host is unknown. No address is available for the name specified in the server request. This error is not a soft error. Another type of name server request might be successful. An unexpected server failure occurred, which is a non-recoverable error. This error is a soft error that indicates that the local server did not receive a response from an authoritative server. A retry at some later time might be successful. One possible source of confusion is the handling of IPv4-mapped IPv6 addresses and IPv4-compatible IPv6 addresses, but the following logic should apply:. If af is AF_INET, lookup the name for the given IPv4 address. If af is AF_INET6, lookup the name for the given IPv6 address. If the function is returning success, then the single address that is returned in the hostent structure is a copy of the first argument to the function with the same address family that was passed as an argument to this function. All four steps listed are performed in order. This structure, and the information pointed to by this structure, are dynamically allocated by getipnodebyname() and getipnodebyaddr(). The freehostent() function frees this memory. The following is a sample program that retrieves the canonical name, aliases, and all Internet IP addresses, both version 6 and version 4, for a given hostname. #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> main(int argc, const char **argv) { char abuf[INET6_ADDRSTRLEN]; int error_num; struct hostent *hp; char **p; if (argc != 2) { (void) printf("usage: %s hostname\ ", argv[0]); exit (1); } /* argv[1] can be a pointer to a hostname or literal IP address */ hp = getipnodebyname(argv[1], AF_INET6, AI_ALL | AI_ADDRCONFIG | AI_V4MAPPED, &error_num); if (hp == NULL) { if (error_num == TRY_AGAIN) { printf("%s: unknown host or invalid literal address " "(try again later)\ ", argv[1]); } else { printf("%s: unknown host or invalid literal address\ ", argv[1]); } exit (1); } for (p = hp->h_addr_list; *p != 0; p++) { struct in6_addr in6; char **q; bcopy(*p, (caddr_t)&in6, hp->h_length); (void) printf("%s\\t%s", inet_ntop(AF_INET6, (void *)&in6, abuf, sizeof(abuf)), hp->h_name); for (q = hp->h_aliases; *q != 0; q++) (void) printf(" %s", *q); (void) putchar('\ '); } freehostent(hp); exit (0); } See attributes(5) for descriptions of the following attributes: getaddrinfo(3SOCKET), gethostbyname(3NSL), htonl(3SOCKET), inet(3SOCKET), netdb.h(3HEAD), hosts(4), nsswitch.conf(4), attributes(5) No enumeration functions are provided for IPv6. Existing enumeration functions such as sethostent(3NSL) do not work in combination with the getipnodebyname() and getipnodebyaddr() functions. All the functions that return a struct hostent must always return the canonical make such as determination in different ways. If more than one alias and more than one address in hostent exist, no pairing is implied between the alias and address. The current implementations of these functions return or accept only addresses for the Internet address family (type AF_INET) or the Internet address family Version 6 (type AF_INET6). The form for an address of type AF_INET is a struct in_addr defined in <netinet/in.h>. The form for an address of type AF_INET6 is a struct in6_addr, also defined in <netinet/in.h>. The functions described in inet_ntop(3SOCKET) and inet_pton(3SOCKET) that are illustrated in the EXAMPLES section are helpful in constructing and manipulating addresses in either of these forms. Name | Synopsis | Parameters | Description | Return Values | Examples | Attributes | See Also | Notes
http://docs.oracle.com/cd/E19253-01/816-5170/6mbb5es8d/index.html
CC-MAIN-2015-40
refinedweb
1,455
56.05
Hi all, I used Python and Python plugin to build external mode Python program that interacts with SPSS I wanted to know if the same functionality I'm applying can work using the .Net Plugin instead, the functions are: 1- exporting viewer documents using OMS. 3- using spssaux module to create DatasetOutput. 4- using SpssClient module to set output options of results tables and exporting them to word document. I would appreciate any help. Thanks in advance, Sarah Answer by SystemAdmin (532) | Jan 06, 2010 at 01:21 AM The answer is yes and no. 1. You can run OMS commands from .NET just fine. spv format is supported in recent versions. 3. The spssaux module is Python only. You could, however, use the Dataset class with .NET as an alternative. The Dataset class was modeled in part on the functionality in spssaux.py and spssdata.py, but, of course, you will have to write different code. 4. When running in external mode, there is no spssclient. You can apply tableLooks with OMS when writing spv files, but otherwise you would have to save an spv file and then run another program in internal mode to manipulate the spv contents and do the export. Alternatively, export as Word via OMS and do the formatting in Word automation. Of course, you can still use COM automation via VB/VBA or any language that supports COM to drive the full SPSS client, which would allow the use of automation methods. Those would be different from the SpssClient module apis, however. HTH, Jon Peck Answer by SystemAdmin (532) | Jan 06, 2010 at 11:18 AM Hi Jon, thanks a lot for you help. I have tried to use OMS to export word before in Python but the large table where always wrapped, then the .Net see each part of the table as a separate one. I had to use the SpssClient to set the output option. I read on the .Net Plugin user guide that I can write python programs and submit it with .Net Processor.Submit function. I already have python script that take the spv file and do the export and some table formatting. Is there a way I can call it from inside .NET and provide good running time as I use this script many times ? I tried to use The COM to replace the SPSS client, I added a reference to the application and choose COM tab and selected spsswin 17.0 Type library component and added the reference and run the attached code but got the following exception :Retrieving the COM class factory for component with CLSID {9995B33E-E434-4879-80DC-8D8CB950AC6B} failed due to the following error: 80040154. Thanks again, Sarah using spsswinLib; using spsswin; public partial class Form1 : Form { public Form1() { InitializeComponent(); } public spsswinLib.Application16Class spssCom; private void button1_Click(object sender, EventArgs e) { spssCom = new spsswinLib.Application16Class(); string path = "/SPSSOutPut/output.spv"; ISpssOutputDoc outputDoc=spssCom.OpenOutputDoc(path); outputDoc.ExportDocument(SpssExportSubset.SpssAll, "/SPSSOutPut/output.doc",SpssExportFormat.SpssFormatDoc, false); } } Answer by SystemAdmin (532) | Jan 06, 2010 at 04:26 PM I don't know what that COM error code means. Are you sure that the libraries are registered correctly? There was a problem with one of the patches where there was a registration problem. You might run regsrvr on the libraries and see if that helps. Also, if you have multiple SPSS versions installed, make sure that the right one is registered. As a test, try running the equivalent code from the Basic editor within SPSS. You might also be able to run your Python script from within .NET(!) if that route is working by using the SCRIPT command. I haven't tried that myself, but in theory it would work if you have the client running. HTH, Jon Answer by SystemAdmin (532) | Jan 06, 2010 at 05:41 PM I'm running VS 2008 and I added the references for SPSS.BackendAPI.dll and SPSS.BackendAPI.Controller.dll. Then located the spssxd.dll location using the attached code, the location is different from the statistical explorer example may be because I'm running different version of SPSS. I was able to run the program without problem and The first Message shows that I'm running SPPS 17.0.2 and the second Message shows that The plugin version is 17.0.2.0. then on the first Submit or starting for the the SPSSP it throws an exceptions that says" An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)" and SPSSP.GetLastErrorMessage() shows that there is NO Error. Is there something I missing here. Is there a problem that I have the Python plugin installed on the same machine? Regarding the COM I did not register any libraries, should not the installation of SPSS perform this step. The same attached code worked on SPSS V 18 and using plugin 18 , the COM code is also working on version 18 . Thanks a lot, Sarah public void PlugIn() { // Locate SPSS and create a new instance of the Processor // Statistics and graphics will be created by the Processor for display in the application, // but the SPSS user interface will never appear string path=System.Windows.Forms.Application.StartupPath+ "\\SPSSOutPut\\data.sav"; string outpUtPath=System.Windows.Forms.Application.StartupPath+ "\\SPSSOutPut\\out.spv"; Microsoft.Win32.RegistryKey regiKey = Registry.LocalMachine.OpenSubKey( "SOFTWARE\\Wow6432Node\\SPSS\\SPSS-NET 17.0\\SPSS"); if (regiKey != null) { string SpssXdPath = regiKey.GetValue( "").ToString(); SPSSP = new Processor(SpssXdPath); MessageBox.Show( "SPSS version "+SPSSP.Version); MessageBox.Show( "the plugin version " + SPSSP.GetPlugInVersion()); string cmd = "GET FILE='" + path + "'."; MessageBox.Show(cmd); try { SPSSP.Submit( "SET UNICODE ON."); SPSSP.StartSPSS(outpUtPath); bool ready= SPSSP.IsBackendReady(); if (ready == true) { MessageBox.Show( "backend ready"); SPSSP.Submit(cmd); } else { MessageBox.Show( "backend is not ready"); } } catch { MessageBox.Show( SPSSP.GetLastErrorMessage()); } } else { SPSSP = new Processor(); } } Answer by SystemAdmin (532) | Jan 06, 2010 at 09:53 PM After installing another version of SPSS 17.0.2 on another machine and its corresponding plugin, both of the code worked. I think the problem might be on my machine or the OS as I'm using Vista and the other machines are XP. I will uninstall every thing and reinstall on my machine again and see. I noticed that the spssxd.dll location is the same on XP machine, only the version number change, it was "SOFTWARE\\SPSS\\SPSS-NET 17.0\\SPSS" and "SOFTWARE\\SPSS\\SPSS-NET 18.0\\SPSS" . But on the Vista it was "SOFTWARE\\Wow6432Node\\SPSS\\SPSS-NET 17.0\\SPSS". Will those location be fixed? Thanks, Sarah Answer by SystemAdmin (532) | Jan 07, 2010 at 12:56 AM I'm not sure where you are looking, but none of the locations look familiar to me.
https://developer.ibm.com/answers/questions/215402/converting-a-python-program-into-net-1.html
CC-MAIN-2019-43
refinedweb
1,127
67.65
01 July 2013 21:19 [Source: ICIS news] HOUSTON (ICIS)--Koch Pipeline has launched its first phase of a non-binding open season for its proposed Dakota Express Pipeline that would transport Bakken crude oil to two ?xml:namespace> The planned pipeline would take 250,000 bbl/day of crude oil from the The pipeline would begin service in 2016, the company said. Koch also said it is “actively exploring” a connection at the Patoka terminal to the Eastern Gulf Crude Access Pipeline, which then could take the Bakken crude to eastern Gulf Coast refineries. New and existing pipelines would be used in the planned project. About 600 miles of new line would be built, Koch said, while the company’s existing Wood River Pipeline and The Wood River Pipeline has been used to transport crude northward from The first phase of open season will close on 14 August. If sufficient interest is garnered, Koch could initiate the second phase, during which binding commitments would be
http://www.icis.com/Articles/2013/07/01/9683556/us-koch-launches-open-season-for-planned-bakken-pipeline.html
CC-MAIN-2014-35
refinedweb
166
61.5
Asked by: WCF Step by Step Question - Help!! I have the book, WCF Step by Step, by John Sharp, and I am still learning WCF. I really need some assistance with one particular implementation I am trying to do with a Postgresql database. Can someone Please direct me to the chapters / topics in the book discussing the methodologies by which my Client application, developed in Visual Studio 2012 and WPF, C#, can use WCF to obtain / update data from a postgresql database Server on my desktop machine, connected through localhost, 127.0.0.1? I am planning on also using Npgsql for data operations. Postgresql typically uses port 5432. Do I need to change that Postgres configuration to another port to allow message sharing or forwarding from, WCF? Thank you. All replies WCF is about SOA. WCF has nothing to do what any database. However you understand SoC, then you will resort to having a classlib project called a DAL, where WCF doesn't care what the database is about, which is the concern of the DAL that the WCF service has reference to the DAL. <copied> Layered designs in information systems are another embodiment of separation of concerns (e.g., presentation layer, business logic layer, data access layer, persistence layer. <end> You can forget about an ASP.NET WEB UI, because the UI can be about any UI -- desktop, ASP.NET or otherwise. Presentation tier, BLL, WCF and DAL projects have reference to a project called Entities that contain the DTO(s) and you send the DTO through the tiers. Forget about the datasets and datatables in the link below and learn how to use the DTO(s) objects and List<T>. You can use MVP with Windows forms UI in n-tier. Watch the show and learn how to use MVP. I think my question is more about the particular WCF configuration as there are many ideas out there on how to configure endpoints, proxies, behaviors, etc. For starters, is this app.config shown immediately below anything like what it should look like? This is from the WCF host module in my Prism Unity application. The WCF library is in another separate module/ assembly. Below the app.config is the WCFHostModule.cs, which is instantiated when the application starts. As shown, the OnStart method of the WCFHostModule instantiates MyDataService. Right now, that class just has a method that connects to the database. Later on I will add DAL, etc. <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="WcfLibraryModuleBehavior"> <serviceDebug includeExceptionDetailInFaults="true" /> <serviceMetadata /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="WcfLibraryModuleBehavior" name="WcfLibraryModule.MyDataService"> <endpoint binding="netTcpBinding" bindingConfiguration="" name="WcfLibraryModule.Endpoint" contract="WcfLibraryModule.IMyDataService" /> <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="WcfLibraryModuleEndpoint2" contract="IMetadataExchange" /> </service> </services> </system.serviceModel> </configuration> using System.ServiceProcess; using System.ServiceModel; using WcfLibraryModule; namespace WcfSvcHostModule { public partial class WcfHostService : ServiceBase { internal static ServiceHost myServiceHost = null; public WcfHostService() { InitializeComponent(); } protected override void OnStart(string[] args) { if (myServiceHost != null) { myServiceHost.Close(); } myServiceHost = new ServiceHost(typeof(MyDataService)); myServiceHost.Open(); } protected override void OnStop() { if (myServiceHost != null) { myServiceHost.Close(); myServiceHost = null; } } } } - Edited by Harpagornis Tuesday, July 28, 2015 4:12 AM code provided If you know all of this, then why are you here asking questions if you are this sharp? You should be able just to open up a WCF book and just put it altogether without being here asking questions. I know that's what I did back in year 2008 when I first used WCF for DoD and hooked it up together with using Windows Work Flow and WCF together all for the first time, just opened up the WCF and WF books and used MS SQL Server too all sitting behind the WCF services. There is no mystery about it. Any coding monkey can open up a book and write some code. But can you architecture a solution from the front-end to the back-end, and that may be what you are missing, because you should be able to do this with any DB sitting behind WCF. There is no secret sauce on WCF. It is just a SOA solution that allows communications between the WCF client and WCF Service client/server and that is it. Come on man...... Have you even tried to look at examples? There are plenty of them. And do you know about the programname.exe.config, right? .NET is only using an app.config in debug mode. At runtime, .NET is looking at programname.exe.config. You are talking about you can't get things to work, and I had to assume that you don't know what you are doing at all. Then what is the problem? You get any exceptions or what? You want help? You won't explain what the problem is about other than you can't get a database to work with WCF. That's not the purpose of WCF. And I'll make another suggestion to you. Get the database stuff into a DAL, use MS Unit Test harness with Nunit, a classlib project, a functional test project, against the DAL, and get all aspects of the DAL to work. Then you should set reference to the DAL from WCF project and call methods on the DAL with no problems. WCF should only be looked at in the aspects of communications only. One error message I got was that shown below. That occurs when I right click the WCFLibraryModule project and select Debug / Start New Instance. System.ServiceModel.AddressAlreadyInUseException: There is already a listener on IP endpoint 0.0.0.0:5432. My OS is Windows 7 and Postgresql is a Network service already "listening" on port 5432. When I got that error, this was the App.config for the WCFLibraryModule. <configuration> ="Npgsql" type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" /> </providers> </entityFramework> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="WcfLibraryModuleBehavior"> <serviceDebug includeExceptionDetailInFaults="true" /> <serviceMetadata /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="WcfLibraryModule.MyDataService"> <endpoint address="net.tcp://localhost:5432/MyDataSvc" binding="netTcpBinding" bindingConfiguration="" contract="WcfLibraryModule.IMyDataService" /> </service> </services> </system.serviceModel> </configuration> Well, you have to change the port number that the service is listening on, which is in conflict with another program that is already listening on the port that is running on the machine. You have to use a port that is not a well known port. You shouldn't use any low ports which are 0-1023, and you can't use any ports above 1023 that are high ports that are well known high ports. You have 66,635 ports to choose from pick one that is not a well known port that the service can listen on, or pick a port that doesn't have the potential or you know in fact that no program running on the machine is going to use the port. So, what you are saying is that I need to establish the connection to my Postgresql database as usual on port 5432, using Npgsql, and create the DAL and only THEN I can use WCF? No, what I am saying is Postgressql DB and your WCF service cannot be listening on the same inbound port. If the Postgressql DB is running on the computer using TCP 5432 a well-known TCP port number, then you can't have the WCF service running and listening on the same TCP port on the machine. It is a conflict the port is already in use by another program running on the machine that is/will cause your WCF service to be terminated due to it not being able to get exclusive control of the port. If MS SQL Server is running on the computer, MS SQL Server listens on TCP ports 1432 and 1433 well-known ports, then no other program running on the computer such as a WCF service can be listening on the port too. You have to pick another port for your WCF service to listen on for inbound traffic from the WCF client. You must understand that in client/service applications in communications with each other, it is the WCF client that must make the initial contact with the WCF service on the inbound port that the WCF service is listening on before communications will take place between the two. I gave you the link of the TCP and UDP ports that are well known throughout the IT industry, and you have to adhere to that list. This endpoint has to be changed to some other port that the inbound port the service is listening on, if nothing other program is running on the machine that is not already listening on the inbound port. Endpoint address="net.tcp://localhost:5432/MyDataSvc" binding="netTcpBinding" it has to be changed to some other port and you have to figure out how to tell the WCF service what port it is to listen on, and you tell the client through the endpoint were the WCF service is located and what port the WCF service is listening on. Capiche? You should still use a DAL, and I don't care how you do it use a console application to test the DAL or something and then set reference to the DAL in the WCF service. All issues with the DAL should be out of the way before you set reference to the DAL in the WCF service project to eliminate any issues with the DAL prior to using it with the WCF service. You should do some kind of Hello World thing with your WCF client and service to make sure you understand how client/server applications work before you proceed to do something with a DB in the solution. Small dives before big dives and stop going SPLAT into the pool's cement. :) I already did a simple Client app that connects to the Postgresql Server. From what you are telling me, WCF has no relevance in that Client / Server connection / messaging process. Yeah it WCF does it absolutely does between the WCF client and service that messages are sent between the two. <copy>: <end> It seems to me for whatever reasons, you are having a hard time about how communcations work on a network Intranet or Internet and with computers in general. net.tcp://localhost do you know what localhost means? How it works? How can you have two different programs the DB and the WCF client and service programs using the same TCP port number? You can is some situations but this is not one of those situations, which is a more advanced WCF topic. I suggest that you stop, use MS SQL Server Express and find out what you are suppose to be doing here. If you don't understand how to use WCF, then how can use it effectively? How can use WCF in any programming scenario if you don't really understand how to use it? But I wouldn't get into using WCF with datasets and datatables too much. WCF just comes into play after the data is sent by the Postgres Server? You know what a DAL is about. The DAL is the client of the database server any DB server it doesn't matter if the DB server is MS SQL Server, Oracle, Postgres, Access or whatever. It is the DAL's responsibility to work with the database for CRUD operations (Create, Read, Update and Delete) operations with the database. And I understand about Entities and DAL, repository pattern, etc. The above statement is yours. A DAL is a design pattern, repository pattern is a design pattern. A DAL can have a repository being used within it, it could be the Data Access Object pattern, or it could be the Unit Of Work pattern. DTO(s) Data Transfer Objects are created by the DAL and populated by DAL objects used to populate DTO(s) that are marked as DataContracts. The DTO(s) are sent from the DAL so that the WCF service can serialize them and send then to the WCF client, the messages in the form of XML serialize objects. The WCF client can make new DTO(s) or use the ones sent to the client by the service and manipulated them. The client then sends the DTO(s) back to the WCF services that in turn sends DTO(s) to the DAL so that objects in the DAL like repository, DAO or UoW objects, work with the data in the DTO(s) and the DAL objects persist the data to the database. The WCF service hosts the classlib project called the DAL. <copied> Data transfer object (DTO) is an object that carries data between processes. The motivation for its use has to do with the fact that communication between processes is usually done resorting to remote interfaces (e.g. web services), where each call is an expensive operation.<sup> </sup. <end> The two processes that are in play here are the WCF service and the WCF client. I have given you examples on how to do it, and it is up to you to figure it all out. 3-Tier / N-Tier Pattern and Practices based Architectures - Reference Application: ASP.NET MVC Patterns - Reference Application: ASP.NET Web Forms Patterns - Reference Application: Windows Forms Patterns - Reference Application: WPF Patterns Each one of the application front-ends with the source code are using WCF and a database on the backend you get the source code on all of it. They are using the same back-end with each front-end being interchangeable with the back end. And they are using everything that I have been talking about. You see it all in action when you run the solutions in VS Debug mode. You have to see someone else doing it and see the picture before you can take off and do your own thing. It's plain and simple. If you don't know how to architect then you are lost on all aspects of developing .NET solutions effectively. Good luck to you man as I am out of here on this. :) I will continue looking for an answer to my question about whether or not the WCF service can monitor the data transport to and from the Database Server, separate and apart from the DAL methods. Thank you for all your help. I assure you that I have done a lot of research on most if not all of the topics you mentioned. As you know, no matter how much reading and studying one does, there is no substitute for actually doing and trying. I also downloaded many related demo apps, but there are very few Postgres (or Access or MySql or whatever) demo apps out there, especially using all the architectural design methods discussed. I will continue looking for an answer to my question about whether or not the WCF service can monitor the data transport to and from the Database Server The answer is no. It is not the job of a WCF solution. What is SOA? SOA or Service oriented architecture is an architecture style for building business applications by means of services. Application comprises collection of services which communicate through messages.
https://social.msdn.microsoft.com/Forums/en-US/1bc0a047-317d-494d-bb45-4af84a97e97f/wcf-step-by-step?forum=wcf
CC-MAIN-2020-45
refinedweb
2,547
63.29
Doing a project in code academy related to package weights. The below code should output 35 for a package that weights 5, instead it prints 43.75 The code seems to work correctly for a package that weights 8.4 , it prints 53.6. I can’t figure out what’s happening. TIA! def ground_shipping(weight): if weight <= 2.0 and: return weight * 1.50 +20 elif weight < 2.0 and weight <= 6: return weight * 3 + 20 elif weight > 6 and weight <= 10: return weight * 4 + 20 else: return weight * 4.75 +20 #Check Ground Shipping print(ground_shipping(8.4)) print(ground_shipping(5))
https://discuss.codecademy.com/t/simple-question-on-if-and-elif-with-inequalities/419318
CC-MAIN-2020-40
refinedweb
103
87.92
Bob renders directory structure templates Project description Mister Bob the Builder creates directory skeletons. Documentation TODO - [medium] refactor Python API - [medium] gittip - [medium] add +var+ folder in template_sample - [medium] Check how one would implement multi-namespace python package with current mr.bob api - [low] Ability to configure what to ignore when copying templates in bobconfig (as a hook?) - [low] better format print questions output (keep order of questions -> use order information like for asking questions) - [low] document we don’t need local commands once answers are remembered (just issue another template on top of current) - [low] ability to specify variables/defaults to questions from cli - [maybe] ability to simulate rendering (dry-run) - [maybe] ability to update/patch templates Changelog 0.1a9 (2013-04-26) - regex to detect variable names when rendering file names was broken when directory path contains pluses. [Godefroid Chapelle] 0.1a8 (2013-03-11) - Depend on six>=1.2.0 [Domen Kožar] - Moved all exceptions to mrbob.exceptions module [Domen Kožar] - Fix loading of zip files [Domen Kožar] - #28: Remote loading of config files [Nejc Zupan] - #30: Keep newlines of rendered template [Domen Kožar] 0.1a7 (2013-01-23) - Don’t depend on argparse in python 2.7 and higher, since it’s already in stdlib [Domen Kožar] - #22: Prevent users from specifying target directory inside template dir [Domen Kožar] 0.1a6 (2013-01-02) - Use StrictUndefined with jinja2 renderer so that any missing key is reported as an error [Domen Kožar] - If a key in a namespace was missing while rendering, no error was raised [Domen Kožar] - Added hook mrbob.hooks.show_message [Domen Kožar] - mrbob.validators.boolean renamed to mrbob.hooks.to_boolean [Domen Kožar] - Renamed validators.py to hooks.py [Domen Kožar] - Removed validators and action settings from [questions] as it is superseded by hooks [Domen Kožar] - Added pre_ask_question and post_ask_question to [questions] section [Domen Kožar] - Added pre_render, post_render and post_render_msg options [Domen Kožar] - Added [defaults] section that will override template defaults. The only difference to [variables] is that variables provide default answers [Domen Kožar] - Moved renderer parameter to [template] section [Domen Kožar] - Added [template] section that is parsed only from .mrbob.ini inside a template directory. [Domen Kožar] - Correctly evaluate boolean of quiet and verbose settings [Domen Kožar] - Added non_interactive setting that will not prompt for any input and fail if any of required questions are not answered [Domen Kožar] - Added remember_answers setting that will create .mrbob.ini file inside rendered directory with all the answers written to [variables] section [Domen Kožar] - Include changelog in documentation [Domen Kožar] - Question does no longer raise error if unknown parameter is passed from a config file. Instead those parameters are saved to question.extra that can be later inspected and validated. This is first step to have advanced question types such as question with a set of predefined answers [Domen Kožar] - Rewrite all py.test stuff to nosetests, so we have unified testing now. This also fixes flake8 segfaults on pypy [Domen Kožar] 0.1a5 (2012-12-12) - #26: Variables were not correctly parsed from config files [Domen Kožar] 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/mr.bob/0.1a9/
CC-MAIN-2018-30
refinedweb
532
53.71
[EXPL] Rational Clearcase Exploit Code Released From: SecuriTeam (support_at_securiteam.com) Date: 09/14/03 - Previous message: SecuriTeam: "[NEWS] MyServer Buffer Overflow Vulnerability (math_sum.mscgi)" - Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ] To: list@securiteam.com Date: 14 Sep 2003 18:33:40 +0200 The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: - - promotion The SecuriTeam alerts list - Free, Accurate, Independent. Get your security news from a reliable source. - - - - - - - - - Rational Clearcase Exploit Code Released ------------------------------------------------------------------------ SUMMARY <> IBM Rational ClearCase "simplifies the process of change with a family of products that scales from small project workgroups to the distributed global enterprise". A locally exploitable stack overflow in the product's binaries allows gaining of elevated privileges. The following exploit code can be used to test your system for the mentioned vulnerability. DETAILS Exploit: /* ****** Another Proof Of Concept Code by c0ntex@hushmail.com ****** **** Rational Clearcase Clearance **** ********************** * ------------------------------------------------------------------------------------- The definition of Rational in the dictionary: Definition: [adj] having its source in or being guided by the intellect (distinguished from experience or emotion); "a rational analysis" [adj] of or associated with or requiring the use of the mind; "intellectual problems"; "the triumph of the rational over the animal side of man" ------------------------------------------------------------------------------------- There are so far, 10 seperate binaries, including the below that are vulnerable to some form of stack based attack. All architectures are vulnerable in some form too. It is also possible to own remote machines from the ClearCase binaries. Is it a bug or a feature? who cares, it's Friday :-) [-] Vuln Binary [-] Vuln Architectures [-]Serious? /usr/atria/bin/Perl Intel, Alpha, RISC, Possible SPARC Could be /usr/atria/bin/notify Intel, Alpha, RISC, Possible SPARC Not really /usr/atria/bin/cleartool Intel, Alpha, RISC, Possible SPARC Yeah /usr/atria/etc/scrubber Intel, Alpha, RISC, Possible SPARC Yeah /usr/atria/etc/mount_mvfs Intel, Alpha, RISC, Possible SPARC Yeah /usr/atria/etc/imsglog Intel, Alpha, RISC, Possible SPARC Could be /usr/atria/etc/Gzip Intel, Alpha, RISC, Possible SPARC Not really ... etc ... Still to come: ALBD and MVFS / NFS encapsulation analysis. You may find that MVFS causes your NFS daemon to, well, react in adverse ways. :) Await a testing environment. Anyone? ******************* BOYCOT ROOT GAINING EXPLOIT CODE SHARING ******************* ALL linux SetUID binaries have a little bug too :-) RUN Forest, RUN, you might find it too *lol* // Funny priv8 joke ahha // Want another funny priv8 joke? -> Symantec are a funny bunch, they want to make exploit and tool codes illegal. Ok sirs, may this humble hobbiest ask your good integrity driven self why you decide to purchase and fund a security related website that shares these same codes with the public socialist. You could perhaps also then answer why you also fund a security related website that is involved with people that have been known to `hack`, where the word hack is assumed to be in the same context used by the media monkey. -- bash> file core.* core.1230: ELF 32-bit LSB core file of 'su' (signal 11), Intel 80386, version 1 (SYSV), from 'su' core.1233: ELF 32-bit LSB core file of 'crontab' (signal 11), Intel 80386, version 1 (SYSV), from 'crontab' bash> su Segmentation fault (core dumped) bash> mount mount: error while loading shared libraries: O: cannot open shared object file: No such file or directory bash> PuTTY -bash: PuTTY: command not found bash> passwd Segmentation fault (core dumped) Still checking this out. ******************* Oracle, now there is an application, it also has some stack based bug that can be abused by underpaid and overworked computer hobbiest, some PoC might be shared. Then again, it might not :) Oracle and SNMP, what a lovely combination. Oracle on Microsoft system is funny too. **************** Speaking of Microsoft, another little bug noticed was an overflow in a widespread *exe* called rundll32. Only useful for virii or something stupid like that anyway, right? "!!ALERT!! No 0day patch for remote 0day XSS 0day" *LOL*, this is funny stuff man. --------- Let us go back about 1 1/2 months. Background: Being terribly bored with brain numbing talk on IRC I decided to play a great game called Counter Strike - have you played this game? I tell you, it is a very good game :) come play some time, it is not a buggy application *HONEST* You know what I mean right? "Description: The Windows Rundll32 Program is used to run DLLs as programs and is used by many programs to execute functions located in a DLL file." The part that has been left out: rundll32 has been coded in such a way that it does not check user supplied input with a means to preventing user controlled buffer overflows. rundll32.ex :) Faulting application rundll32.exe, version 5.1.2600.0, faulting module unknown, version 0.0.0.0, fault address 0x000a000d. Unicode EIP address = 00410041 = *LOL* <--// Nice site fella :) // You might say `who cares` about rundll32, he say "not he", but would be rude not to let you know why windows machines shut down or have new user account. After finding the bug I check google engine and find one post from a guy that noticed the same thing. Hi guy :-) ------------------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define VER "ClearCase Smack_Crack_And_Hack_Attack Version 1.0.1" #define NULL (void *)0 #define NOP 0x90 #define RET 0xbfffd838 #define BUFF 1300 char shellcode[] = "\x31\xc0\xfe\xc0\xcd\x80"; /* 8048091: 31 c0 xor %eax,%eax 8048093: fe c0 inc %al 8048095: cd 80 int $0x80 */ int main(int argc, char *argv[]) { char buffer[BUFF]; unsigned long int retaddr; unsigned short int offset = 0; unsigned short int i; if(argc > 1) { offset = atol(argv[1]); } retaddr = RET + offset; printf("\n\n*************************************************************\n" "*************************************************************\n"); printf("[-] %s\n", VER); printf("[-] Bug discovered and PoC developed by c0ntex@hushmail.com.\n" "[-] --------------------------------------------------------\n" "[-] with a little bit of copy & paste skill. Ok, Yes, it is\n" "[-] true, c0ntex also lazy perl scripter. :->\n" "[-] --------------------------------------------------------\n" "[-] If the added return address isn't working, brute force it.\n" "[-] Values from around -2000 -> +2000 should work quite well.\n" "[-] Or add a request to get current esp value and use that.\n" "[-] --------------------------------------------------------\n" "[-] Usage: %s offset_value\n", argv[0]); for(i = 0; i < BUFF; i += 4) *(long *) &buffer[i] = retaddr; for(i = 0; i < (BUFF - strlen(shellcode) - 100); ++i) *(buffer + i) = NOP; memcpy(buffer + i, shellcode, strlen(shellcode)); printf("[-] Using Return address 0x%lx\n", retaddr); printf("[-] Using offset value %d\n", offset); printf("*************************************************************\n" "*************************************************************\n\n"); execlp("/usr/atria/bin/Perl", "Perl", buffer, NULL); return 0; } ADDITIONAL INFORMATION The information has been provided by <mailto:c0ntex@hush] MyServer Buffer Overflow Vulnerability (math_sum.mscgi)" - Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ] Relevant Pages - ) - [EXPL] xMule AttachToAlreadyKnown Double Free Vulnerability Exploit Code ... The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: ... Remote Vulnerabilities> eMule / Lmule / xMule Multiple Remote ... a vulnerability in xMule allows remote attackers to cause ... int gai_errno = 0; ... (Securiteam) - [NT] SurgeMail 38k4 Format string and Buffer Overflow ... The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: ... SurgeMail 38k4 Format string and Buffer Overflow ... affected by a format string vulnerability in the function which builds the ... int putcc; ... (Securiteam) - [EXPL] Ethereal EIGRP Dissector Buffer Overflow Exploit ... The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: ... for the EIGRP Dissector buffer overflow is presented below. ... * This vulnerability was found by: ... static int ... (Securiteam) - [EXPL] Buffer Overflow in JOIN Command Leads to DoS ... The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: ... the vulnerability allows remote attackers to cause to server to no ... int sockopen ... struct hostent *he; ... (Securiteam)
http://www.derkeiler.com/Mailing-Lists/Securiteam/2003-09/0035.html
crawl-001
refinedweb
1,306
54.12
If this doesn't pique the interest of my fellow developers then I don't know what will: a problem that will take twenty billion years to solve (at an extremely optimistic estimate), unless we find an efficient algorithm. The problem in question is Project Euler Problem 67. We're given a triangle made up of one hundred rows of numbers, and asked to consider all routes from the top to the bottom, made by moving from one row to the next via adjacent cells. Over all such routes, we have to find the maximum sum. Can't picture it? Let me help: For the route that I've drawn, the sum is 5 + 15 + 29 + 45 = [train your brain and work it out yourself!]. If we only wanted to tackle the baby brother of this problem (Problem 18 - the same problem for a triangle with just 15 rows), we could get away with checking each of the routes. But it's not feasible to do that here because there are 299 possibilities: hence the need for an efficient algorithm. Any ideas? You could take a bath and wait for the Eureka moment. Or if you want to avoid the ensuing streaking, read on. An algorithm Suppose that for each cell in a row we know the maximum sum over all routes ending at that cell. From that it's easy to work out the same for each of the cells in the next row. Here's how you do it. If you've got a cell with value c, somewhere in the middle of the row, then you can only reach it from either of the two cells adjacent to it in the row above. We're assuming that we already know the maximum sum for routes ending at these cells: suppose it is a and b respectively. So the biggest possible sum we can get for routes ending at c is Max(c + a, c + b). For the two cells at either end of the row the calculation is even simpler: they can only be reached from the cell at the appropriate end of the row above them, so we just sum the cell value with the known maximum sum to the cell above. In this way, we can crunch through the rows, 'flattening' the triangle until we reach the last row, at which point we will know the maximum possible sum over all routes ending at each of the cells in that row. That's the middle of an algorithm. To solve the overall problem we just need to add a beginning and an end. The middle part starts by assuming that we already know the maximum sum for all routes ending at a particular row. So to get the algorithm rolling we need a row for which we do have that information, and the first row of the triangle is the obvious candidate: all routes start there, so the maximum up to that point is just the value of the cell in that row. How about the end of the algorithm? To solve the problem, we need to know the maximum sum from top to bottom through the triangle; we've calculated the maximum sum ending at each of the cells in the last row, so we just need to take the maximum over all these cells. Some code To code this, we'll reach once again into our Functional Programming toolbox. I think the Aggregate method is just the hammer to crack this particular nut. Do you see how? Ignore the input part for now, and assume we've got a sequence of List<int>, one List for each row of the triangle. Like this: {75} {95, 64} {17, 47, 82} {18, 35, 87, 10} ...In this layout, it's a little tricky to visualise which cells are adjacent to which: you need to look at the cell directly above, and the one above but to the left. For example, the 35 in row four is adjacent to 47 and 17 in the row above. We'll use Aggregate to 'flatten' the triangle represented by this sequence of Lists using the algorithm I described above: the aggregate that we'll be calculating is a List containing the maximum sum over all routes to each cell up to the last row we've processed. Remember that Aggregate needs a function that combines the aggregate so far with the next item in the series. We'll supply a function that takes the maximums so far and combines them with the cell values for the next row. The code looks like this:(); Notice that at line 7 we're processing the sequence nextRow (containing the cell values) using an overload of the Select method that gives us the index of each cell value in the sequence; we use this index to find the appropriate entries in the list currentMaxima containing the maximum sums to the cells in the row above. And with that, I believe we've solved the problem. It takes 2 milliseconds to solve the 100-row triangle problem on my computer - a satisfying improvement over 20 billion years. Here's the complete code. Note that in the source code project I have included two files containing the data for these problems. namespace ProjectEuler { [EulerProblem(18, Title = "Find the maximum sum travelling from the top of the triangle to the base.")] public class Problem18 { public long Solve() { var dataPath = @"ProblemData\Problem18Data.txt"; return MaximumSumThroughTriangleSolver.SolveFromFile(dataPath); } } [EulerProblem(67, Title = "Using an efficient algorithm find the maximal sum in the triangle?")] public class Problem67 { public long Solve() { var dataPath = @"ProblemData\Problem67Data.txt"; return MaximumSumThroughTriangleSolver.SolveFromFile(dataPath); } } public static class MaximumSumThroughTriangleSolver { public static int SolveFromFile(string dataFilePath) { string problemData = File.ReadAllText(dataFilePath); return Solve(problemData); } public static int Solve(string problemData) { var rows = problemData .Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) .Select(line => line.Split(' ') .Select(token => int.Parse(token)) .ToList() ) .ToList();(); } } } 24 comments: Your article has been included in the 42nd Carnival of Mathematics, just posted a few minutes ago. Hey! I believe you explained this as best you could but I still am not getting how to resolve this using your algorithm (maybe it's because I am not a c# guy or I am not that great with math) Could you give more examples or something? in your first illustration, the last row in the triangle has 5 elements....i think it should have 4. You're right about that. I made the same mistake in the second illustration too! I wonder how many other people spotted that but couldn't be bothered to tell me. Thanks. Your explanation was exactly what I needed to get past #67. #81 is similar, I think. a matrix for right and down. Rotate, deal with the edge cases and it's the same problem. Kylar, Glad I could help. It's interesting how my explanations suit some, but not others. I think you might right about 81: I hadn't looked at it before. Sam Thanks. it would have take me month to think of an useful idea. Your concept help me do my code in a jiffy The first illustration is very wrong. Picking 5-15-27-58 would yield 105 instead of 95, and that's clearly a greater sum. You're right that the route you've shown would give a greater sum. However in that picture, I was just trying to illustrate one possible route through the triangle, not necessarily the maximal one. I am trying to solve this problem using Mathematica any advice @Anonymous, I'm afraid I've never used Mathematica You're an exceptionally talented problem solver, Sameul. Thanks for sharing. But yes, the other comments are right about the problem with the graphics. Each row should increase by only a single item. A small flaw in an otherwise outstanding post. Peter, Glad you liked it. Thanks for reading! Sam I'm trying to solve this problem using an easy Dijktra's algorithm. Am I wrong or should it be easier this way? 5stars wouldn't it be simpler to do essentially the same as you did, but to start at the bottom and work ones way up the pyramid. E.g. represent the data as List numbers = new List>() { {15}, {23,1}, {56,33,5}, {5,11,9,33} }; and then just do: for (int i = numbers.Count-2; i >= 0; i--) { for (int j = 0; j < numbers[i].Count; j++) { numbers[i][j] += Math.Max(numbers[i + 1][j], numbers[i + 1][j + 1]); } } once your done, numbers[0][0] holds the result. works quite fast for me. cheers Just for yucks, here is an F# equivalent. let answer = System.IO.File.ReadLines(".\\triangle.txt") |> Seq.map(fun x -> x.Split(' ') |> Seq.map(fun y -> System.Int32.Parse(y))) |> Seq.fold(fun acc x -> let rowLen = Seq.length x x |> Seq.mapi(fun i y -> let current = fun () -> y+(Seq.nth i acc) let previous = fun () -> y+(Seq.nth (i-1) acc) if i=0 then current() elif i=rowLen-1 then previous() else System.Math.Max(current() , previous()) ) |> Seq.toList ) [0;] |> List.max Hi there, Thank you for your excellent linq tutorials! I noticed that the output of your code is the same when removing line 46. Is that line there for a specific reason? Excellent algorithm, which is easy to implement in other languages. This has a nice short and clear formulation in Haskell - the bottom up solution: eu_18_67 tri = head $ foldr1 (\xs ys-> zipWith (+) xs (zipWith max ys (tail ys))) tri Cheers, I know you've had this already but thanks again for this help. I just couldn't get the right start to this problem (I'm only doing 18) and this was great. I'll write my own code rather than use yours as I only have a basic knowledge but this method will help a lot I knew this problem could be solved from the top down but could not come up with solution. Very good explanation. This solution is a brute-force, but it would take a long time or a massive processing power .. since the problem size is 2^99
http://blog.functionalfun.net/2008/08/project-euler-problems-18-and-67.html?showComment=1229171520000
CC-MAIN-2019-35
refinedweb
1,708
72.66
Okay, I don't know what's going on here, but here's my code: n = "hello" def string_function(Hello): print "Hello" + "world" return "Helloworld" print string_function("Hello") You see, it's telling me I need to return a function called waynes in order to work, but it said in the directions all I needed to print was helloworld, and mentioned nothing about "waynesworld." And, when I do add it in, it tells me this: Oops, try again. string_function('Hello') returned 'Waynesworld' instead of 'Helloworld' I cannot for the life of me figure out why it's needing me to create "Waynes" and then contradicting itself with the other error message. Help!
https://discuss.codecademy.com/t/resolved/36490
CC-MAIN-2018-34
refinedweb
112
53.17
I've recently ported John Papa's popular Hot Towel Angular SPA Template to TypeScript. Why? Because it was there. If you'd like to read more about HotTowel-Angular then have a read of John Papa's post. You can find my port on GitHub here. What is this port you speak of? It is intentionally a "bare bones" port of the HotTowel-Angular JavaScript code across to TypeScript. It's essentially the same code as John's - just with added type annotations (and yes it is noImplicitAny compliant). You could, if you wanted to, go much further. You could start using a whole host of TypeScripts functionality: modules / classes / arrow functions... the whole shebang. But my port is deliberately not that; I didn't want to scare your horses... I wanted you to see how easy it is to move from JS to TS. And I'm standing on the shoulders of that great giant John Papa for that purpose. If you wanted an example of how you might go further in an Angular port to TypeScript then you could take a look at my previous post on the topic. What's in the repo? The repo contains the contents of HotTowel-Angular's app folder, with each JavaScript file converted over to TypeScript. The compiled JavaScript files are also included so that you can compare just how similar the compiled JavaScript is to John's original code. In fact there are only 2 differences in the end: 1. sidebar.js's getNavRoutes ...had the filtering changed from this: return r.config.settings && r.config.settings.nav;to this: return (r.config.settings && r.config.settings.nav) ? true : false; This was necessary as TypeScript insists that the array filter predicate returns a boolean. John's original method returns a number ( nav's value to be clear) which actually seems to work fine. My assumption is that JavaScript's filter method is happy with a truth-y / false-y test which John's implementation would satisfy. 2. common.js's $broadcast ...had to be given a rest parameter to satisfy the TS compiler. John's original method exposed no parameters as it just forwards on whatever arguments are passed to it. This means that $broadcast has a bit of unused code in the head of the generated method: var args = []; for (var _i = 0; _i < (arguments.length - 0); _i++) { args[_i] = arguments[_i + 0]; } If you want to use this Then simply follow the instructions for installing HotTowel-Angular and then drop this repo's app folder over the one just created when HotTowel-Angular was installed. If you're using Visual Studio then make sure that you include the new TS files into your project and give them the BuildAction of TypeScriptCompile. You'll need the following NuGet packages for the relevant DefinitelyTyped Typings: Install-Package angularjs.TypeScript.DefinitelyTyped Install-Package angular-ui-bootstrap.TypeScript.DefinitelyTyped Install-Package jquery.TypeScript.DefinitelyTyped Install-Package spin.TypeScript.DefinitelyTyped Install-Package toastr.TypeScript.DefinitelyTyped And you're good to go. If you're not using Visual Studio then you may need to add in some <reference path="angular.d.ts" /> etc. statements to the TypeScript files as well. If you're interested in the specific versions of the typings that I used then you can find them in the packages.config of the repo. Thanks To John Papa for creating HotTowel-Angular. Much love. And my mum too... Just because.
https://blog.johnnyreilly.com/2014/07/
CC-MAIN-2020-16
refinedweb
579
58.48
Profiling¶ This is considered an advanced topic mainly of interest to server developers. Introduction¶ Sometimes it can be useful to try to determine just how efficient a particular piece of code is, or to figure out if one could speed up things more than they are. There are many ways to test the performance of Python and the running server. Before digging into this section, remember Donald Knuth’s words of wisdom: […]about 97% of the time: Premature optimization is the root of all evil. That is, don’t start to try to optimize your code until you have actually identified a need to do so. This means your code must actually be working before you start to consider optimization. Optimization will also often make your code more complex and harder to read. Consider readability and maintainability and you may find that a small gain in speed is just not worth it. Simple timer tests¶ Python’s timeit module is very good for testing small things. For example, in order to test if it is faster to use a for loop or a list comprehension you could use the following code: import timeit # Time to do 1000000 for loops timeit.timeit("for i in range(100):\n a.append(i)", setup="a = []") <<< 10.70982813835144 # Time to do 1000000 list comprehensions timeit.timeit("a = [i for i in range(100)]") <<< 5.358283996582031 The setup keyword is used to set up things that should not be included in the time measurement, like a = [] in the first call. By default the timeit function will re-run the given test 1000000 times and returns the total time to do so (so not the average per test). A hint is to not use this default for testing something that includes database writes - for that you may want to use a lower number of repeats (say 100 or 1000) using the number=100 keyword. Using cProfile¶ Python comes with its own profiler, named cProfile (this is for cPython, no tests have been done with pypy at this point). Due to the way Evennia’s processes are handled, there is no point in using the normal way to start the profiler ( python -m cProfile evennia.py). Instead you start the profiler through the launcher: evennia --profiler start This will start Evennia with the Server component running (in daemon mode) under cProfile. You could instead try --profile with the portal argument to profile the Portal (you would then need to start the Server separately). Please note that while the profiler is running, your process will use a lot more memory than usual. Memory usage is even likely to climb over time. So don’t leave it running perpetually but monitor it carefully (for example using the top command on Linux or the Task Manager’s memory display on Windows). Once you have run the server for a while, you need to stop it so the profiler can give its report. Do not kill the program from your task manager or by sending it a kill signal - this will most likely also mess with the profiler. Instead either use evennia.py stop or (which may be even better), use @shutdown from inside the game. Once the server has fully shut down (this may be a lot slower than usual) you will find that profiler has created a new file mygame/server/logs/server.prof. Analyzing the profile¶ The server.prof file is a binary file. There are many ways to analyze and display its contents, all of which has only been tested in Linux (If you are a Windows/Mac user, let us know what works). pipwhereas KCacheGrind is something you need to get via your package manager or their homepage. How to analyze and interpret profiling data is not a trivial issue and depends on what you are profiling for. Evennia being an asynchronous server can also confuse profiling. Ask on the mailing list if you need help and be ready to be able to supply your server.prof file for comparison, along with the exact conditions under which it was obtained. The Dummyrunner¶ It is difficult to test “actual” game performance without having players in your game. For this reason Evennia comes with the Dummyrunner system. The Dummyrunner is a stress-testing system: a separate program that logs into your game with simulated players (aka “bots” or “dummies”). Once connected these dummies will semi-randomly perform various tasks from a list of possible actions. Use Ctrl-C to stop the Dummyrunner. Warning: You should not run the Dummyrunner on a production database. It will spawn many objects and also needs to run with general permissions. To launch the Dummyrunner, first start your server normally (with or without profiling, as above). Then start a new terminal/console window and active your virtualenv there too. In the new terminal, try to connect 10 dummy players: evennia --dummyrunner 10 The first time you do this you will most likely get a warning from Dummyrunner. It will tell you to copy an import string to the end of your settings file. Quit the Dummyrunner ( Ctrl-C) and follow the instructions. Restart Evennia and try evennia --dummyrunner 10 again. Make sure to remove that extra settings line when running a public server. The actions perform by the dummies is controlled by a settings file. The default Dummyrunner settings file is evennia/server/server/profiling/dummyrunner_settings.py but you shouldn’t modify this directly. Rather create/copy the default file to mygame/server/conf/ and modify it there. To make sure to use your file over the default, add the following line to your settings file: DUMMYRUNNER_SETTINGS_MODULE = "server/conf/dummyrunner_settings.py" Hint: Don’t start with too many dummies. The Dummyrunner defaults to taxing the server much more intensely than an equal number of human players. A good dummy number to start with is 10-100. Once you have the dummyrunner running, stop it with Ctrl-C. Generally, the dummyrunner system makes for a decent test of general performance; but it is of course hard to actually mimic human user behavior. For this, actual real-game testing is required.
http://evennia.readthedocs.io/en/latest/Profiling.html
CC-MAIN-2018-13
refinedweb
1,026
64
What happens when you use the asterisk in the function with the name Function(*number) The asterisk in a function parameter is often referred to as a splat. It tells Python that the variable may be a package of arguments that will need to be unpacked by the function. >>> def foo(*args): print (len(args)) >>> foo(1,2,3,4,5,6,7,8,9) 9 >>> So if you put a splat with the argument, your allowed to put multiple arguments in the function but if there is no splat, then you will get an error if you put multiple arguments in the function when a user input occurs? A single variable can only hold one object, be it a value, a list, or a dictionary. A splat variable can hold multiple objects. Style guides recommend against using them since they are difficult to debug. Explicit parameters are more clear. Python functions do not permit unnamed parameters, meaning the number of arguments needs to much the number of parameters. The special case would be where there may be zero, one, two, or three, etc. parameters in whch case they would be set with defaults. >>> def foo(a=1, b=2, c=3): return (a, b, c) >>> foo() (1, 2, 3) >>> foo(2,4,6,8) Traceback (most recent call last): File "<pyshell#210>", line 1, in <module> foo(2,4,6,8) TypeError: foo() takes from 0 to 3 positional arguments but 4 were given >>> def foo(): return "Foo" >>> foo('bar') Traceback (most recent call last): File "<pyshell#214>", line 1, in <module> foo('bar') TypeError: foo() takes 0 positional arguments but 1 was given >>> Notice that when we try to pass too many arguments it raises an exception? In the revised function that takes no arguments, the same error occurs if we try to pass one. There are always going be some cases where splat is a workable solution to an otherwise indeterminant scenario, but in a well designed program, this should rarely be necessary. Here is some silliness… >>> def foo(*args): print (len(args)) args_dict = {} args_keys = 'abcdefghijklmnopqrstuvwxyz' for i in range(len(args)): args_dict[args_keys[i]] = args[i] return args_dict >>> print (foo(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26)) 26 {'y': 25, 'k': 11, 'o': 15, 'x': 24, 'h': 8, 'm': 13, 'c': 3, 'u': 21, 't': 20, 'e': 5, 'l': 12, 'a': 1, 'w': 23, 'p': 16, 's': 19, 'r': 18, 'q': 17, 'i': 9, 'f': 6, 'n': 14, 'v': 22, 'j': 10, 'b': 2, 'd': 4, 'g': 7, 'z': 26} >>> Will this lesson be taught later in the Learn Python course because I find this hard to understand. It’s as expected, for the present. It should be hard to understand for a beginner; I’ve covered a lot of ground, even with the simple example. Forget about the silliness, although it does demonstrate the mechanics of a ridiculous number of packaged arguments. In this case we still had a determined number, but as mentioned earlier, there is no limit as long as Python has memory to work with. Does this come up in any lessons? Maybe, and if at all, only in one place. It is not something a beginner should be focusing upon. This is an advanced topic. Just for the fun of it, let’s look at a simpler example, but that is not to say it is a good practice. As mentioned earlier, this is not a best practice. >>> def triangle_check_angles(*angles): A, B, C = angles; angles_check = A + B + C == 180 return "Angles {}, {}, {} check out".format(A,B,C) if angles_check else False >>> triangle_check_angles(30, 50, 90) False >>> triangle_check_angles(30, 60, 90) 'Angles 30, 60, 90 check out' >>> def triangle_check_sides(*sides): a, b, c = sides sides_check = a + b > c and a + c > b and b + c > a return "Sides {}, {}, {} check out".format(a,b,c) if sides_check else False >>> triangle_check_sides(3, 4, 8) False >>> triangle_check_sides(3, 4, 7) False >>> triangle_check_sides(3, 4, 5) 'Sides 3, 4, 5 check out' >>>
https://discuss.codecademy.com/t/function-number/232854
CC-MAIN-2018-43
refinedweb
686
65.56
Created on 2008-02-12 20:50 by hauser, last changed 2012-04-17 23:18 by brett.cannon. This issue is now closed.. As you said,. And I plan to add a much simpler API to the imp module for people to use directly so that these abuses don't continue. There are quite a few projects that use this solution:.*%5C%5B%27%27%5C%5D . I would change it even if it is a hack, but I understand your point. Just for reference, the simplest workaround is to use: modname = "foo.bar.baz.baq" mod = __import__(modname, {}, {}, [modname.rsplit(".", 1)[-1]]) See also A pointer for people who keep referring to this bug -- after discussions, the following idiom was selected as the "official" way to import modules by name in 2.x (as seen in latest 2.x docs ). --- If you simply want to import a module (potentially within a package) by name, you can get it from sys.modules: >>> import sys >>>>> __import__(name) <module 'foo' from ...> >>> baz = sys.modules[name] >>> baz <module 'foo.bar.baz' from ...> And just some more info, Python 2.7/3.1 have gained the importlib module/package and its import_module function which gives a much saner API than __import__. Just bitten by this (through a 3rd party library that uses this pattern) and I'm wondering why it was closed as invalid. Passing a non-empty fromlist string also imports the tail module but without the side effect of double import, so it's not generally harmful. More surprisingly, a colleague discovered accidentally that the same behavior happens if you pass one or more slashes: __import__('pkg', fromlist=['', '/', '//']) imports 'pkg', 'pkg.', 'pkg./' and 'pkg.//' ! I'm not arguing that using fromlist to import the tail module is not a hack, but the behavior for empty strings and slashes (and whatever else causes multiple imports) is clearly a bug. Unless someone is actually relying on this double import behavior (very unlikely), I think it should be fixed. If you want a justification, think of it as undefined behavior. When you use an empty string in fromlist you are essentially simulating ``from pkg import`` which makes absolutely no sense, so no one has cared enough to try to fix this. It's such a hack that I don't think people need to worry about fixing it, especially with a more sanctioned way to do it and with importlib being available in PyPI and running in Python 2.3 and later. Now if someone bothers to submit a patch to fix the issue that is reasonable then it can be considered for fixing, but I view this as such a nonsensical call signature that I personally don't see the need to have someone burn some time on this unless they really care. As a compromise I have made this a "wont fix" bug, but I still don't see the need to open the bug again. I concur with Brett. For the most part, we don't care about implementation artifacts and undefined behaviors (as long as it doesn't segfault). Since ``from pkg import`` makes no sense, would it be okay if __import__ with an empty fromlist or slashes raised an error? On Thu, Apr 15, 2010 at 14:56, Éric Araujo <report@bugs.python.org> wrote: That's fine with me if someone wrote a patch that did that. Although now that I think about it, there is a slightly sticky situation of someone using '' or some name with a slash for a key in __dict__. The usage in fromlist would then be "reasonable", but the semantics would be somewhat odd as fromlist is really only needed to trigger other imports. It's probably safe to still make it an error, although it shouldn't be special-cased just for slashes and spaces but specifically the logic triggering the double import. > When you use an empty string in fromlist you are essentially simulating > ``from pkg import`` which makes absolutely no sense, so no one has > cared enough to try to fix this. ``from pkg import __bogus__, 123, @$%`` doesn't make sense either and yet the equivalent __import__ call doesn't cause multiple imports neither binds __name__ to bogus strings, it just imports and returns pkg. > Since ``from pkg import`` makes no sense, would it be okay if > __import__ with an empty fromlist or slashes raised an error? No, this would break lots of working code and would be inconsistent anyway with other invalid fromlist inputs. The backwards compatible solution would be to treat the empty string (and slashes) like every other input, i.e. prevent multiple imports. More fun findings: dots are special-cased too, but only if they don't appear consecutively (!); ~$ cat pkg/__init__.py print __name__ ~$ python -c "__import__('pkg', fromlist=['.'])" pkg pkg.. ~$ python -c "__import__('pkg', fromlist=['..'])" pkg ~$ python -c "__import__('pkg', fromlist=['...'])" pkg ~$ python -c "__import__('pkg', fromlist=['././//.'])" pkg pkg.././//. ~$ python -c "__import__('pkg', fromlist=['././../'])" pkg FWIW attached is a patch that allows only valid identifiers before calling import_submodule(), and returns silently otherwise (for backwards compatibility). For the record, the reason that empty strings and some combinations of slashes/dots caused the double import was that they were concatenated to the path, and if the final path was a valid directory and contained an __init__.py it was imported. E.g. __import__('pkg.subpkg', fromlist=['/../.']) ends up looking in "pkg/subpkg//../.". On the surface this seems like a potential directory traversal attack hole, although I couldn't get past 'pkg' by passing '../../../', so I guess there must be other checks before attempting the import. > On the surface this seems like a potential directory traversal attack > hole, although I couldn't get past 'pkg' by passing '../../../', so I > guess there must be other checks before attempting the import. I rushed to post; it turns out one *can* access packages in parent directories, so I think it's accurate to describe it as a directory traversal hole. Thanks for the patch, George. I will get it when I can. And this make me even more glad that we removed the file path import from 3.x. FWIW, I also get this behavior on 2.6.5 and there are claims that it occurs on 2.6.4 and 3.1.1. see I replied to the Stack Overflow question. I should also mention that importlib is on PyPI and compatible back to PYthon 2.3. I still plan to get to this some day, but I don't view this as a critical fix, just a nice thing to do for folks. Importlib does away with this issue.
https://bugs.python.org/issue2090
CC-MAIN-2018-05
refinedweb
1,111
63.9
This example demonstrates how to create an In-Ribbon Gallery at design time and runtime. It is assumed that the form already contains a RibbonControl, and ImageCollection objects (imageCollection1 and imageCollection2) that will provide images for gallery items. imageCollection1 contains regular images for gallery items, while imageCollection2 contains enlarged versions of these images, which will be displayed when a specific gallery item is hovered over. Open the Design view in Visual Studio. Right-click the RibbonPageGroup's client area and select Add RibbonGalleryBarItem. This creates a RibbonGalleryBarItem object designed to display an In-Ribbon Gallery. To access and customize the gallery settings using the Properties window, ensure that the created RibbonGalleryBarItem object is selected in the Design view. Once the RibbonGalleryBarItem is selected, expand the RibbonGalleryBarItem.Gallery property in the Properties window, and set the gallery settings as follows. The modified properties are marked in the following image. Before adding individual gallery items, first create a gallery item group, which is an immediate container of gallery items within the gallery. The gallery can contain multiple gallery item groups. In this tutorial, only one titleless group is created. Right-click the RibbonGalleryItem's client area and select Add Gallery Group. To create a gallery item, right-click the created group and choose Add Gallery Item. Add two more items in the same way. For each gallery item, regular and hover images need to be specified. In this tutorial, gallery item images are stored in ImageCollection objects. Thus, to assign individual images from these collections to items, the GalleryItem.ImageIndex and GalleryItem.HoverImageIndex properties are used. Select the first gallery item and click the item's smart tag, to open the Tasks pane. Set the ImageIndex and HoverImageIndex properties by selecting the proper images from the dropdown lists. If you are observing empty dropdown lists in your case, this means that the image collections assigned to the BaseGallery.Images and BaseGallery.HoverImages properties do not contain any images. Assign images to the other two gallery items in the same way. Run the project and move the mouse over the gallery items to see the hover images feature in action. The following code is equivalent to the design-time example above. using DevExpress.XtraBars; using DevExpress.XtraBars.Ribbon; // Create a bar item that represents an In-Ribbon gallery. RibbonGalleryBarItem galleryBarItem =. GalleryItemGroup itemGroup1 = new GalleryItemGroup(); galleryBarItem.Gallery.Groups.Add(itemGroup1); // Create gallery items and add them to the group. GalleryItem item1 = new GalleryItem(); item1.ImageIndex = item1.HoverImageIndex = 0; GalleryItem item2 = new GalleryItem(); item2.ImageIndex = item2.HoverImageIndex = 1; GalleryItem item3 = new GalleryItem(); item3.ImageIndex =); Imports DevExpress.XtraBars Imports DevExpress.XtraBars.Ribbon ' Create a bar item that represents an In-Ribbon gallery. Dim galleryBarItem As. Dim itemGroup1 As New GalleryItemGroup() galleryBarItem.Gallery.Groups.Add(itemGroup1) ' Create gallery items and add them to the group. Dim item1 As New GalleryItem() item1.ImageIndex = 0 item1.HoverImageIndex = 0 Dim item2 As New GalleryItem() item2.ImageIndex = 1 item2.HoverImageIndex = 1 Dim item3 As New GalleryItem() item3.ImageIndex = 2)
https://documentation.devexpress.com/WindowsForms/2667/Controls-and-Libraries/Ribbon-Bars-and-Menu/Examples/Ribbon/How-to-Create-an-In-Ribbon-Gallery
CC-MAIN-2017-39
refinedweb
498
61.63
Plug-in any Ruby/Rack based framework to GlassFish GlassFish gem as well asGlassFish v3 supportsRack. Rack provides an interface to plugin a Ruby web framework with a web sever. Similar to PythonWSGI. This means that any ruby based framework that can talk Rack can be simply deployed on GlassFish. Here is how you can do it on GlassFish gem: Insall JRuby Install JRuby fromhere. Setup JRUBY_HOME to the install location and add JRUBY_HOME/bin to your PATH. Install GlassFish gem $ gem install glassfish Now, lets write a trivial app and save it in file: myapp.rb class MyApp def self.Run "Hello World" end end Write a rack-up script and save it in myframework.ru Starting . GlassFish gem as well as GlassFish v3 server can auto-detect Rails, Merb and Sinatra applications. You can use the above mentioned technique to plugin other frameworks. For reference also see Jacob'sblog where he explains how Sintra application is plugged in to GlassFish. - Login or register to post comments - Printer-friendly version - vivekp's blog - 4432 reads by jamesbritt - 2009-07-19 12:15I've been tryig to get this working, but it fails right away with this: SEVERE: uninitialized constant Rack::VERSION Any idea why? jruby 1.4.0dev (ruby 1.8.6p287) (2009-07-13 6586) (Java HotSpot(TM) Client VM 1.6.0_07) [i386-java] glassfish (0.9.5), rack (1.0.0) by johnlloydjones - 2009-08-01 09:16OK, success. I added this line to the .ru file: require 'jruby/rack/grizzly_helper' (Oh and I still need to define Rack::VERSION as above.) by johnlloydjones - 2009-08-01 08:50OK, maybe not so simple. I added this to the top of my test.rb file: module Rack VERSION = '1.0' end Now I get this: SEVERE: uninitialized constant JRuby::Rack from :1 com.sun.grizzly.jruby.rack.RackInitializationException: uninitialized constant JRuby::Rack from :1 at com.sun.grizzly.jruby.rack.DefaultRackApplicationFactory.createApplication(DefaultRackApplicationFactory.ja va:169) at com.sun.grizzly.jruby.rack.DefaultRackApplicationFactory.newApplication(DefaultRackApplicationFactory.java: 69) Something is missing? by johnlloydjones - 2009-08-01 08:36I also get the uninitialized constant Rack::VERSION error. As far as I can see, this is because the jruby-rack.jar is not being found. Where should it be placed for the glassfish gem to use it?
https://weblogs.java.net/node/241980/atom/feed
CC-MAIN-2015-32
refinedweb
387
52.66
QTableView doesn't show any data - thinkpad20 I'm trying to figure out how to use tables in Qt and I'm using the Model/View tutorial from Nokia: Using the code in this tutorial for the first example (2.1 A Read-Only Table), I tried to add a table to a Qt GUI application I had been building. Although I pretty much followed the code to the letter, the table doesn't show anything when the program runs. I'm using the WYSIWYG editor for the project, so a lot of the code is hidden. But I think I included the necessary code. The model code is almost a straight copy from that tutorial, but I'll post it here: pointsmodel.h @#ifndef POINTSMODEL_H #define POINTSMODEL_H #include <QAbstractTableModel> class PointsModel : public QAbstractTableModel { Q_OBJECT public: PointsModel(QObject *parent); int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; }; #endif // POINTSMODEL_H @ pointsmodel.cpp @#include "pointsmodel.h" #include <QDebug> PointsModel::PointsModel(QObject *parent) :QAbstractTableModel(parent) { } int PointsModel::rowCount(const QModelIndex & /parent/) const { qDebug() << QString("call to rowCount"); return 5; } int PointsModel::columnCount(const QModelIndex & /parent/) const { qDebug() << QString("call to columnCount"); return 3; } QVariant PointsModel::data(const QModelIndex &index, int role) const { int row = index.row(); int col = index.column(); qDebug() << QString("call to data: row %1, col%2, role %3") .arg(row).arg(col).arg(role); if (role == Qt::DisplayRole) { return QString("Row%1, Column%2") .arg(index.row() + 1) .arg(index.column() +1); } return QVariant(); } @ And then in the constructor of my main window, after adding the qtableview widget to the layout in the WYSIWYG editor with the objectname pointsTableView: @ PointsModel pModel(0); ui->pointsTableView->setModel( &pModel );@ Having done this, it loads up blank. Any help? Thanks a ton! bq. I’m trying to figure out how to use tables in Qt There are two types of tables - views and item-based. QTableView based on model and represent view. QTableWidget based on items (QTableItem) Your main problem is with this snippet: @ PointsModel pModel(0); ui->pointsTableView->setModel( &pModel ); @ This is where your code deviates from that of the example, I bet. The problem is that you are creating the model on the stack. As soon as pModel goes out of scope, it is destroyed again. That is before it even could be displayed. Simply create the model on the heap (and choose a suitable parent object for it), and your code should work just fine. [quote author="tucnak" date="1341215352"]bq. I’m trying to figure out how to use tables in Qt There are two types of tables - views and item-based. QTableView based on model and represent view. QTableWidget based on items (QTableItem) [/quote] I fail to see how that is relevant to the question. The TS clearly was working with the model/view based version, as he defined his own model. - thinkpad20 I really appreciate it Andre! I followed your advice, changed some things around and now it's displaying. I can't say I'm 100% solid on stack/heap stuff and why it needed to be that way, but it gives me some reading to do. Thanks a ton!
https://forum.qt.io/topic/17971/qtableview-doesn-t-show-any-data
CC-MAIN-2018-34
refinedweb
539
55.34
>>IMAGE. Not a comment on the functionality this provides, but… Please, oh please, don’t tell people to import packages as “.”! It pollutes the name space (importing gingko and gomega this way imports almost 60 names into the global namespace) and makes it hard for people not entirely familiar with the code to know what’s locally defined and what’s external. It might seem like a convenience you can’t bear to sacrifice, but it is really best to avoid it. In the project I work on, we started off using gocheck in this style, but have moved towards using a short package identifier alias instead (“gc” in our case), which works pretty well. For example October 9, 2013 at 11:47 am Hey Roger, I’m happy to add a warning to that effect to the documentation. Yes, obviously, I’m encouraging people to merge Ginkgo and Gomega into the global namespace of their *tests*. And, yes this can be problematic should a name collision occur (which the compiler will immediately catch). But, pragmatically speaking, it is also phenomenally convenient and allows for very flexible and descriptive tests with better signal:noise. Practically speaking, I’ve been using Ginkgo and Gomega for over a month and have not once run into a conflict, but – of course – YMMV. For packages that conflict, a short identifier will suffice — but I’d rather that be the exception than the norm. It’s a nice way to write unit tests, but it misses the point of BDD, or better “specification by example” (excellent book:). Specification by example is about communication and collaboration with all stakeholders. BDD approaches like the ones in this article are no good way to communicate with non-technical persons. A Go implementation of Cucumber would be a lot more useful. With proper imports you can chose to read code breadth-first instead of depth-first. Usually it’s important to see how something is used before reading how something is implemented. Proper imports expose this information locally; it’s obvious which identifier is local to the package and which is not. I can defer reading about other package until I am satisfied I understood all the information I need about the local one. Proper scoped naming is important for other reasons as well. Packages expose (usually small) interfaces, and a scoped name carries semantic meaning which can become familiar and idiomatic. An io.Reader or fmt.Printf is the same everywhere. A Reader or a Printf loses its familiar character. Not only the reader has to do extra work to find out what those are, but he he burdened by new, idiosyncratic information relevant only to that particular piece of code. Readers can learn about how a particular interface is to be used by investigating how it’s used in other places. With scoped imports, this is one grep away. With dot imports, I need syntactic analysis; it fails the grep test. Authors are also interested in how their code is used. They are also hindered by improper package usage. Please don’t take this away. October 10, 2013 at 7:03 am @Christian: I agree that this is not BDD a-la Cucumber. I think that’s why we went with “BDD-style” for both Cedar and Jasmine. And, yes, the intent is not to communicate with non-technical stakeholders. The primary intent is to allow developers to write descriptive tests. @Roger: godocs are coming (in a few days). Godoc is optimized for API documentation not tutorial/narrative-style documentation. I wanted to get the latter out first. And as for the slippery-slope argument — let’s all take a deep breath. You don’t have to use “.” — I’ll add all sorts of warnings to the docs. I’ve found that the constant repetition of “ginkgo.” and “gomega.” (or “K.” and “M.”) in the tests adds unnecessary noise and stutter but that is a purely subjective statement and I’m not going to hold people to it! October 10, 2013 at 9:07 am @Onsi – Very nice work with Ginkgo. I’m one of the authors of GoConvey (github.com/smartystreets/goconvey), which is very similar. I agree with your stance on not following the Cucumber/Gherkin BDD school of thought. I admit that if I had found Ginkgo a few months ago I might not have written GoConvey, but I’m happy with what we’ve come up with. Best of luck with your development of Ginkgo.
http://pivotallabs.com/announcing-ginkgo-and-gomega-bdd-style-testing-for-golang/?tag=tdd
CC-MAIN-2015-18
refinedweb
752
64.91
PowerSwitch Tail AC control module The PowerSwitch Tail is a low-cost module designed to switch AC loads such as household lights and appliances using a digital logic control signal. Hello World Import programPowerSwitchTail Simple Demo of PowerSwitch Tail module used to control AC devices Library Import programPowerSwitchTail Simple Demo of PowerSwitch Tail module used to control AC devices Notes rather than building a high voltage AC circuit on a breadboard or even a small relay breakout board or SSR breakout board with a bare PCB without a case. It has an internal switch module and the high voltage connections are all enclosed in the case. Standard AC plugs are already attached. wires attached to screw terminals are the digital control signal and logic ground. It will operate off of a 3.3V or 5V logic output signal and it draws about the same current as a small LED. Several Power Switch Tail modules could be used using mbed's USB cable power without the need for an external DC power supply for mbed. The digital connections can be made without opening the safety case, but here is a view of the PCB inside. PowerSwitch Tail II with safety cover off to view PCB Safety Note on High Voltages Leave the cover on when using the module.. Breadboard contacts and small jumper wires only handle about one amp. For electrical isolation, when using a relay to control external AC devices, do not connect the grounds on the power supplies from the control side to the load side. Any digital out pin can be used to control the relay (connects to the input of the relay driver circuit). Here is an example program the turns the relay on and off every 4 seconds. #include "mbed.h" DigitalOut myled(LED1); DigitalOut Ctrl(p8); int main() { while(1) { Ctrl = 1; myled = 1; wait(2); Ctrl = 0; myled = 0; wait(2); } } The digital output control signal (mbed P8) and a logic ground (mbed gnd pin 1) are connected using a small screw terminal block built into the case of the PowerSwitch.
https://os.mbed.com/components/PowerSwitch-Tail-AC-control-module/
CC-MAIN-2020-05
refinedweb
347
57.1
#include <hallo.h> Erik Andersen wrote on Thu Apr 04, 2002 um 07:42:53PM: > Sorry about that. The package needed some immediate attention. > If I'd had the time, I'd have done it myself... As is.... Wish > it could have been otherwise, I changed a bit more since tonight, new upload on: If I do not hear from you today or tomorrow, I will move to incoming. cdrtools (4:1.10-2.5) unstable; urgency=medium . * New maintainer * forces use of SHM instead of MMAP, ignoring tests at build time which depend on the kernel version, closes: #127895, #131325, #136754, #138581 * blackout the build arguments and version info string in mkisofs, closes: #87043. Set NOPRIVACY environment to force the default behaviour. * cdda2wav's output channel problem is fixed by upstream, closes: #55695 * symlink mkhybrid and mkisofs, closes: #132479 * updated upstream's mail address, closes: #115496 * fixed formatting error in mkisofs.8, closes: #135385 * respect extension of filenames when creating Joilet info for filenames longer than 64 chars, closes: #80202 * fixed typo in templates, closes: #126870 Gruss/Regards, Eduard. -- Wer Freiheit aufgibt, um Sicherheit zu bekommen, verdient keins der beiden und bekommt meist auch keins. -- Benjamin Franklin, 1759 -- To UNSUBSCRIBE, email to debian-devel-request@lists.debian.org with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
https://lists.debian.org/debian-devel/2002/04/msg00282.html
CC-MAIN-2015-18
refinedweb
220
54.73
Hi folks, I’m new here, trying to get started with fmod in Unity. I’m looking for the best way to implement a master volume setting in my game, and I see in the C++ documentation that there is a function System::getMasterChannelGroup that looks useful. I don’t see it available in the C# Unity integration though. What would be the best way to control the master volume in Unity? Cheers, /Mikael - alpacasound asked 4 years ago - You must login to post comments I was struggling with this for a while as well. I figured it had to be something to do with the path because when I debug logged the returned GUID it was all zeroes. Turns out, when you export GUIDs from FMOD Studio the text file output contains all the paths that you need. From this, all bus paths must begin "bus:/". Similar to the event instance paths beginning with "event:/". If you do: [code:353v06o6]FMOD_StudioSystem.ERRCHECK(system.lookupID("bus:/", out guid));[/code:353v06o6] That should work =) - Trumkey answered 4 years ago Hi Mikael, You can retrieve the master bus using the API and control it’s volume directly. The path of the master bus is "/" so the code would look something like this: [code:3gu46xgq]using UnityEngine; using System.Collections; public class MasterVolume : MonoBehaviour { public float volume = 1.0f; FMOD.Studio.MixerStrip masterBus; void Start() { FMOD.GUID guid; FMOD.Studio.System system = FMOD_StudioSystem.instance.System; ERRCHECK( system.lookupBusID("/", out guid) ); ERRCHECK( system.getMixerStrip(guid, FMOD.Studio.LOADING_MODE.BEGIN_NOW, out masterBus) ); } void Update() { ERRCHECK( masterBus.setFaderLevel(volume) ); } void ERRCHECK(FMOD.RESULT result) { FMOD_StudioSystem.ERRCHECK(result); } } [/code:3gu46xgq] - Guest answered 4 years ago Thanks a lot! - alpacasound answered 4 years ago Seems the ERRCHECK method is private now? This code works for me, but doesn’t do error checking. [code:1u1rancx] public float volume = 1.0f; FMOD.Studio.MixerStrip masterBus; void Start() { FMOD.GUID guid; FMOD.Studio.System system = FMOD_StudioSystem.instance.System; system.lookupID("bus:/", out guid); system.getMixerStrip(guid, FMOD.Studio.LOADING_MODE.BEGIN_NOW, out masterBus); } void Update() { masterBus.setFaderLevel(volume); } [/code:1u1rancx] - Grieva answered 4 years ago Hi peter, That solution looks good but is it still current? I trying to use it with some minor modifications for the newer version and keep getting null pointers regarding the masterbus. In Start [code:rkv1vo9r]FMOD.GUID guid; FMOD.Studio.System system = FMOD_StudioSystem.instance.System; FMOD_StudioSystem.ERRCHECK(system.lookupID("/", out guid)); FMOD_StudioSystem.ERRCHECK(system.getMixerStrip(guid, FMOD.Studio.LOADING_MODE.BEGIN_NOW, out masterBus));[/code:rkv1vo9r] On Update: [code:rkv1vo9r]FMOD_StudioSystem.ERRCHECK(masterBus.setFaderLevel(volume));[/code:rkv1vo9r] I’m also fairly new to FMOD, and after a quick search I have been unable to find the API referenced in your comment. Is volume a limited between 0 and 1? - Troutmonkey answered 4 years ago
http://www.fmod.org/questions/question/forum-40089/
CC-MAIN-2018-13
refinedweb
466
53.37
The Data Science Lab Here's a hands-on tutorial from bona-fide data scientist Dr. James McCaffrey of Microsoft Research to get you up to speed with machine learning development using C#, complete with code listings and graphics. A working knowledge of machine learning (ML) is becoming an increasingly important part of many C# developers' skill sets. And virtually every significant ML technique uses vectors and matrices. In this article I get you up to speed with the fundamental knowledge you need to create and modify ML code written using the C# language. A good way to see where this article is headed is to take a look at the screenshot of a demo program in Figure 1. Informally, a vector is an array of numeric values. A matrix is conceptually a two-dimensional data structure of numeric values. The demo program begins by creating and displaying a vector with four cells, each initialized to 3.5. Next, the demo creates a 3x4 (3 rows, 4 columns) matrix. The demo program concludes by reading 12 values from a text file and storing them into a 4x3 matrix. This article assumes you have intermediate or better skill with C# but doesn't assume you know anything about vectors and matrices or about ML. The complete code for the demo program shown running in Figure 1 is presented in this article. The code is also available in the file download that accompanies this article. The Demo ProgramTo C# ML code in that environment. I entered "Matrices" as the Project Name, specified C:\VSM on my local machine as the Location (you can use any convenient directory), and checked the "Place solution and project in the same directory" entry. After the template code loaded into the Visual Studio editor, at the top of the editor window I removed all using statements to unneeded namespaces, leaving just the reference to the top-level System namespace. Next I added a using statement that references the System.IO namespace so the program can read data from a text file. In the Solution Explorer window, I renamed file Program.cs to the more descriptive MatricesProgram.cs and then in the editor window I renamed class Program to class MatricesProgram to match the file name. Next, in the Solution Explorer window, I right-clicked on the bold-font Matrices project name and selected Add | New Item | Text File and entered "dummy_data.tsv" in the Name field. After clicking on the Add button, I entered values 1.0 through 12.0, three per line, separated by tab characters, as shown in Figure 1. I also added a header line that begins with "//" characters, which specifies the file name. using System; using System.IO; namespace Matrices { class MatricesProgram { static void Main(string[] args) { Console.WriteLine("Begin vectors and matrices demo"); Console.WriteLine("Creating a vector with 4 cells"); double[] v = Utils.VecCreate(4, 3.5); Utils.VecShow(v, 3, 6); Console.WriteLine("Creating a 3x4 matrix"); double[][] m = Utils.MatCreate(3, 4); Utils.MatShow(m, 2, 6); Console.WriteLine("Loading 4x3 matrix from file"); string fn = "..\\..\\..\\dummy_data.tsv"; double[][] d = Utils.MatLoad(fn, 4, new int[] { 0,1,2 }, '\t'); Utils.MatShow(d, 1, 6); Console.WriteLine("End demo "); Console.ReadLine(); } // Main } // Program class public class Utils { public static double[] VecCreate(int n, double val = 0.0) { . . } public static void VecShow(double[] vec, int dec, int wid) { . . } public static double[][] MatCreate(int rows, int cols) { . . } public static void MatShow(double[][] mat, int dec, int wid) { . . } public static double[][] MatLoad(string fn, int nRows, int[] cols, char sep) { . . } } // Utils class } // ns The structure of the demo program, with a few minor edits to save space, is shown in Listing 1. All of the vector and matrix functionality is implemented by static functions in a class named Utils. Alternative design possibilities are to place the functions in a C# class library or to place the functions inside the Program class. VectorsThe simplest way to create a vector is with code like: double[] v = new double[4]; which would create an array with length of four cells, each holding a type double value initialized to 0.0 by default. Type int and type float vectors can be created using the same pattern. Most ML techniques use type int and 64-bit type double, except for neural networks which often use type int and 32-bit type float. It's possible to create vectors that are initialized to specific values with code like: double[] v = new double[] { 1.0, 2.0, 3.0 }; With this pattern you can omit the explicit length of 3 if you wish because the compiler will infer the length of the array from the number of values supplied. It's possible to create a vector programmatically. The demo program defines the following method to create a vector with n cells all initialized to a specific value: public static double[] VecCreate(int n, double val = 0.0) { double[] result = new double[n]; for (int i = 0; i < n; ++i) result[i] = val; return result; } The method can be called like: double[] v = Utils.VecCreate(4, 3.50); // 4 cells all 3.5 double[] w = Utils.VecCreate(5, 2.78); // 5 cells all 2.78 double[] t = Utils.VecCreate(6); // 6 cells all 0.0 The structure of the C# vector v is shown in the top part of Figure 2. Technically, the name of a vector is a reference to the first cell in the array. Conceptually, the name refers to the entire array. The demo program shows how to traverse a vector in method VecShow(): public static void VecShow(double[] vec, int dec, int wid) { for (int i = 0; i < vec.Length; ++i) Console.Write(vec[i].ToString("F" + dec).PadLeft(wid)); Console.WriteLine(""); } When using a for-loop to traverse a vector, the choice of using pre-increment (++i) or post-increment (i++) is purely a matter of style because the increment is a standalone statement. Notice that VecShow() assumes it is being called from a console application. The method can be called like so: Utils.VecShow(v, 4, 8); This call displays vector v with 4 decimals for each value and a total of 8 spaces per value (with blank space padding on the left, if necessary). A common source of errors is forgetting that vectors are reference objects rather than value objects. For example, consider these three statements: double[] v1 = new double[3] { 4.0, 5.0, 6.0 }; double[] v2 = v1; v2[0] = 9.0; The second statement creates a reference named v2 that points to the same location as v1. The third statement changes cell [0] of v2 to 9.0 but because both v1 and v2 point to the same object, the value of v1[0] has also changed. If you want to make an independent copy of a vector, you can do so with a function like this: static double[] Duplicate(double[] v) { int n = v.Length; double[] result = new double[n]; for (int i = 0; i < n; ++i) result[i] = v[i]; return result; } double[] v1 = new double[3] { 4.0, 5.0, 6.0 }; double[] v2 = Duplicate(v1); v2[0] = 9.0; // no effect on v1 A useful consequence of vectors being references is that a function can modify its array parameter. For example: static void TripleIt(double[] v) { for (int i = 0; i < v.Length; ++i) v[i] = 3 * v[i]; } double[] v = new double[] { 7.0, 9.0 }; TripleIt(v); // v is now (21.0, 27.0) Developers who prefer a functional style of programming can avoid using the reference mechanism to modify a vector and could write code like this: static double[] Triple(double[] v) { int n = v.Length; double[] result = new double[n]; for (int i = 0; i < n; ++i) result[i] = 3 * v[i]; return result; } double[] v = new double[] { 7.0, 9.0 }; v = Triple(v); // v is now (21.0, 27.0) Alternatively, the .NET System.Array class has an Array.Copy() method that you can use to make an independent copy of a vector. MatricesThe most common way to create a C# matrix is to use an array of arrays. For example: double[][] m = new double[4][]; // 4 rows for (int i = 0; i < 4; ++i) m[i] = new double[3]; // 3 columns per row Conceptually, the code creates a matrix named m that has four rows and three columns. Technically, the matrix is an array named m that has four cells, and each cell is a reference to an array with three cells. The anatomy of a 3x4 array-of-arrays style matrix named d is shown in the bottom part of Figure 2. The demo program defines a helper method in class Utils to create a matrix: public static double[][] MatCreate(int rows, int cols) { double[][] result = new double[rows][]; for (int i = 0; i < rows; ++i) result[i] = new double[cols]; return result; } The method can be called like so: double[][] m = Utils.MatCreate(4, 3); // 4x3 All cells of a matrix created in this way will be initialized by default to 0.0 values. Individual cells are referenced like so: m[0][1] = -1.2345; // row 0, col 1 m[3][2] = 9.99; // row 3, col 2 Note that unlike most languages, C# supports a true built-in matrix object. For example: double[,] m = new double[4,3]; // 4x3 m[0, 1] = -1.2345; // row 0, col 1 However, this technique is rarely used in ML scenarios. Another approach is to implement a matrix using a program-defined class along the lines of: class MyMatrix { private int rows; private int cols; private double[][] values; . . . This approach is quite common but in my opinion it's an example of OOP run amok and is unnecessarily complicated for most ML systems. The demo program defines a method MatShow() to display a matrix to a console shell. The code is shown in Listing 2. Notice that because a matrix is an array-of-arrays, the inner for-loop across column values could have been replaced by a call to VecShow() like so: for (int i = 0; i < nRows; ++i) Utils.VecShow(mat[i], dec, wid); In general I prefer to avoid method dependencies like this because then I can make a change to VecShow(), without there being an unintended side effect on MatShow(). Listing 2. Methods to Display and Load a Matrix public static void MatShow(double[][] mat, int dec, int wid) { int nRows = mat.Length; int nCols = mat[0].Length; for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { double x = mat[i][j]; Console.Write(x.ToString("F" + dec).PadLeft(wid)); } Console.WriteLine(""); } } public static double[][] MatLoad(string fn, int nRows, int[] cols, char sep) { int nCols = cols.Length; double[][] result = MatCreate(nRows, nCols); string line = ""; string[] tokens = null; FileStream ifs = new FileStream(fn, FileMode.Open); StreamReader sr = new StreamReader(ifs); int i = 0; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("//") == true) continue; tokens = line.Split(sep); for (int j = 0; j < nCols; ++j) { int k = cols[j]; // into tokens result[i][j] = double.Parse(tokens[k]); } ++i; } sr.Close(); ifs.Close(); return result; } Many ML techniques require you to read data from a text file into a matrix. The demo program defines a method MatLoad() to perform this operation. A call to MatLoad() looks like: string fn = "C:\\Somewhere\\some_file.tsv"; int numRows = 12; int[] cols = new int[] {0, 2, 4 }; char sep = '\t'; double[][] m = Utils.MatLoad(fn, numRows, cols, sep); The MatLoad() method requires you to specify the number of rows to read. It'd be possible for MatLoad() to perform a preliminary scan of the target text file to programmatically determine the number of rows. Such a helper function could be defined as: public static int NumLines(string fn) { int ct = 0; FileStream ifs = new FileStream(fn, FileMode.Open); StreamReader sr = new StreamReader(ifs); while (sr.ReadLine() != null) ++ct; sr.Close(); ifs.Close(); return ct; } Method MatLoad() allows you to specify which columns to use which is useful in situations where you only want a few of the columns. Similarly, method MatLoad() parameterizes the character that separates values on each line in the source text file. The most common separators are single blank space character, tab character, and comma character. Method MatLoad() is hard-coded to interpret any line in the source text file that starts with two forward slash characters as a comment line. You might want to parameterize this string value to make MatLoad() a bit more general. Wrapping UpIf you work with .NET technologies you have several options if you want to create a ML prediction system such as a naive Bayes classifier or a logistic regression classifier. At a low level of abstraction, you can create your ML system using raw C# with the .NET Core framework. At a high level of abstraction, you can use the new (it's still in preview mode as I write this) ML.NET library. Advantages of using the raw C# approach include having complete control over your system, avoiding any license issues, ease of customization, and simplified integration into existing .NET systems. The primary disadvantage of using the raw C# approach is that creating a working ML prediction system sometimes (but not always) takes a bit longer than using the ML.NET library. In many scenarios the decision to use raw C# or ML.NET is not Boolean -- you can use both approaches together. About the Author Dr. James McCaffrey works for Microsoft Research in Redmond, Wash. He has worked on several Microsoft products including Azure and Bing. James
https://visualstudiomagazine.com/articles/2019/11/07/charp-vectors-ml.aspx?utm_campaign=dotNET%20Weekly&utm_medium=email&utm_source=week-46_year-2019
CC-MAIN-2020-34
refinedweb
2,283
65.32
I’ve published a new build through the app store, but still not getting information passing from the link to the app. My app.json has the following: "ios": { "supportsTablet": false, "bundleIdentifier": "...", "infoPlist": { "NSLocationWhenInUseUsageDescription": "...", "NSLocationAlwaysUsageDescription": "...." }, "associatedDomains": [ "applinks:xxxx.app.link", "applinks:xxxx.test-app.link" ], "config": { "branch": { "apiKey": "key_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } }, And in my app I have the following: import { DangerZone } from 'expo'; let { Branch } = DangerZone; . . . componentDidMount() { Branch.subscribe(function(bundle) { if (bundle && bundle.params && !bundle.error) { handleLink(bundle.params); } }); } But no data; handleLink is never called. As far as I can tell my Branch settings are correct. I have ‘Universal Links’ enabled, my app ID and prefix come right out of the app id cert page in developer.apple.com, and “Associated Domains” is enabled on the distribution cert. Is there something I’m missing or have done incorrectly? Do you have any further advice for debugging? Thanks.
https://forums.expo.io/t/still-struggling-with-branch-io/17123
CC-MAIN-2019-22
refinedweb
147
50.02
Do not do pointless commenting. All of the below comments added no extra meaning to the source code and should have been left out. public class AuthorKeywords { /** The keywords. */ private String[] keywords; private int startYear = 1989; // assign 1989 to startYear private dataPath = null; // clear the value of dataPath : /** * getter for the startYear value */ public int getStartYear() { return startYear; } : A more useful set of comments for the same source code are listed below. Even if comments on simple code is missed, complex code should always have a comment at the beginning describing what the philosophy of the code is, what it is trying to accomplish. Source code that is doing a complex activity should be heavily commented. Source code that has an underlaying philosphy it follows should be commented. /** * This class represents a logical index by keyword of all books * written by an author we have in our database. * * Note that it is just a container for storing and reading * the book data but the contents are wrapped by useful * methods to make them easy to access. * * Author: MB */ public class AuthorKeywords { /** * These keywords are used to find the record when the * user searches for books by word associations */ private String[] keywords; private int startYear = 1989; // earliest possible data date private dataPath = null; // where this data came from /** * @return the earliest year that we found information */ public int getStartYear() { return startYear; } : This is further illustrated by another example. The following model class, Media.java had a small amount of Javadoc at the top of the file. Clearly, if a file was called Media.java and the classname was called Media, the file is designed to hold media information. But still the developer added a comment presumably to remove a Javadoc warning – a waste of effort. /** * Represents the Media */ public class Media implements BaseModel { : /** The storage folder. */ private String storageFolder; /** The queue. */ private Queue<Thumbnail> queue; Perhaps the Media class was so simple it did not require comments. But where is the Media class intended to be used? What are the restrictions on using it? How are the private variables intended to be used? The solution should have been to either remove the Javadoc build warning or to write more meaningful comments. The latter is easier and makes the developer a stand-out player on the team. /** * This is the Media model class, which represents the 'media' * table in the database, and contains most 1:1 attributes of a * media clip. * * It is the core entity in this application and describes a * physical binary video file. * * Refer to Media.hbm.xml for the column-to-property mappings. */ public class Media implements BaseModel { : /** * The root folder where all encoded videos for this * media get stored. */ private String storageFolder; /** * Queue of thumbnails yet to be generated for this media. */ private Queue<Thumbnail> queue; } In most cases a class has a reason to exist and it only takes a minute or two to write this down in a comment. Tip: Comment the philosophy of what you are trying to do AND any comment code that might be confusing to those who come along after you. You may be run over by a bus tomorrow, and you wouldn't want to inconvenience anyone, would you?
http://javagoodways.com/comment_useful_Comments_should_enlighten_the_reader_.html
CC-MAIN-2021-21
refinedweb
539
63.19
Pymakr: connected but cannot run script over serial Hi, just got the WiPy 2.0 board. I updated the firmware to the latest version and am running Pymakr 1.0.0.b8 version on Win7 64bit. I can successfully connect to the wipy using a serial connection. It says "connected" in the repl prompt and I can type stuff and get proper answers. I then wanted to run a script. So I type some code in a file that I named "main.py": from machine import I2C #configure the I2C bus i2c = I2C(0, I2C.MASTER, baudrate=100000) i2c.scan() # returns list of slave addresses and I also added a file named "boot.py" with the following code: from machine import UART import os uart = UART(0, 115200) os.dupterm(uart) I then tried to sync the projecto to the Wipy by pressing Sync but every time I do that it says: Syncing the project with the WiPy. Please wait... Syncing failed! Resetting doesn't help. To sum it up, I can use the REPL command but I cannot run a script over serial. Did I understand the usage of the boot.py and main.py file correctly? Do I always have to put my code inside "main.py" to run it? What am I doing wrong? It seems to work over WifI but not over serial...I'm lost and very new to this micropython stuff... Thanks for your help! Hi, thanks for your replies. Ok, I'll look into ftp for now and check back for new firmware versions. Thanks for your help! - Ralph Global Moderator last edited by The sync functionality has not been working properly since the last few firmware versions, due to issues on the available RAM. We're working hard to solve this, so keep an eye out for the next firmware releases. Sorry for the inconvenience! Until it is fixed, try to use FTP to upload your files, then rebooting the device (boot button) after which boot.py and main.py will automatically run. You can keep the serial connection open in pymakr (or other serial program like putty) during the process to see all the output. Regards, Ralph @Busta as i say previously i do not use pymakr try using e.g. putty or com port monitor - e.g. from Arduino IDE and connect by filezilla or other ftp client - for me it is fastest way to develop Ok, thanks for the info. Just tried it in Pymakr. Added a simple print statement to my "main.py" file as a test then ran: execfile("main.py") but nothing shows up in the repl prompt. Mmmm...I don't know what to do. Do I always have to put my code inside "main.py" to run it No you can write any file e.g. my.py and exec it like: execfile('my.py')in e.g. REPL or telnet especially i do not use pymakr i connect by ftp(filezilla) + COM port monitor by filezilla i edit and upload files by REPL i execute and test things
https://forum.pycom.io/topic/549/pymakr-connected-but-cannot-run-script-over-serial
CC-MAIN-2018-26
refinedweb
515
77.64
The root namespace for working with data in the .NET Framework is System.Data. This namespace provides the DataSet and DataTable objects you'll use to work with any type of data. In addition, the .NET Framework provides two specific namespaces that each provides objects for retrieving data that you'll learn about in this book: System.Data.OleDb. Used for working with any OLE DB data source, such as Jet, Oracle, and so on. This namespace supports existing unmanaged (that is, with code written outside the CLR) ADO providers. This namespace includes the OleDbConnection, OleDbCommand, OleDbDataReader, and OleDbDataAdapter objects. System.Data.SqlClient. Provides direct support for SQL Server 6.5 and later, using a managed provider. If you know you'll be working only with SQL Server, you'll want to take advantage of the optimized behavior of this set of classes. This namespace includes the SqlConnection, SqlCommand, SqlDataReader, and SqlDataAdapter objects. You can be relatively sure that Microsoft (and other vendors) will release additional assemblies (and namespaces) containing ADO.NET objects. For example, before the Visual Studio .NET shipped, Microsoft had already released the System.Data.ODBC namespace, and by the time you read this, it's likely that an Oracle-specific namespace will be available as well. (The Oracle namespace wasn't available at the time we wrote this book.) We'll focus on the OleDb and SqlClient namespaces throughout the rest of this book. To get a copy of the System.Data.Odbc namespace, visit Microsoft's download site at. Search for odbc, and you'll find this useful addition to the .NET Framework. Visual Basic .NET adds an implicit Imports statement for System.Data to all your projects for you (unless you change this behavior in the Property Pages dialog box for your project). Although you could refer to ADO.NET objects like this, you can also abbreviate them, as the following code fragment shows: Dim da1 As System.Data.SqlClient.SqlDataAdapter ' This works fine, too Dim da2 As SqlClient.SqlDataAdapter If you're going to be using the System.Data.SqlClient namespace throughout your application, you might consider adding an Imports statement for the namespace at the top of each file that uses the objects, like this: ' Insert this at the top of a file: Imports System.Data.SqlClient ' Now this works, as well: Dim da3 As SqlDataAdapter You can use the same techniques when working with the System.Data.OleDb namespace as well.
https://flylib.com/books/en/3.93.1.78/1/
CC-MAIN-2019-43
refinedweb
410
67.25
If I was trying to create a VM Role for Azure and I got this error from my Hyper-V machine. After some tests I hit my head and got to a clear conclusion: Silly me how could have I missed it. The problem was I set up the VM with more memory that the available in Hyper-V, so I changed this setting and my VM just worked!! If I was not able to transfer any sense of sarcasm, I think that this is really hard to understand error message. you start moving applications to the Silverlight and the Cloud it wont belong for you to start wondering if you can move your applications to be able to work on mobile devices, and it is a natural thing to wonder. One of the best features of Artinsoft conversion tools from VB6 and other languages to .NET is that we generate very clean code, it is not a runtime as much as possible it is plain vanilla .NET code. And that allows us to easily move to other .NET platforms using our evolution framework. Moving a VB6 or Winforms applications will require some libraries not currently present in WP7, one of those libraries are the one to read from a Config file. If you are in need of this functionaly Alex Yakhnin has provided a good port of the Mobility Configuration block that will allow you to do something as simple as: / Get section ApplicationSettingsSection section = (ApplicationSettingsSection)ConfigurationManager.GetSection("ApplicationSettings"); // Display values this.textBlock1.Text = section.AppSettings["localServer"].Value; this.textBlock2.Text = section.AppSettings["remoteServer"].Value; Je. A Are. If!!! Windows Phone 7 (WP7) is out! and it’s a great platform for developing new Apps. After being involved with Silverlight for a while I am glad to have now the option to deploy apps to Windows Phone 7. But we have to recognize that there are tons of great Apps for iPhone already. You might even have some of them. So it’s porting time. Here at Artinsoft we love to upgrade/port application to all platforms. So I will provide here some basic thoughts to help you upgrade your code. For this post let’s discuss a little about applications written for XCode. XCode applications are written in Objetive-C.Let’s map some examples: In Objective-C your class will be usually #import <Foundation/NSObject.h> #import <Foundation/NSObject.h> @interface Fraction: NSObject { int numerator; int denominator; } -(void) print; -(void) setNumerator: (int) n; -(void) setDenominator: (int) d; -(int) numerator; -(int) denominator; @end How you should understand that? Well this is just the list of methods in your class something like: using System; public class Fraction { int _numerator; int _denominator; public void print() { /* TODO*/} public int numerator { get { /* TODO */ } set { /*TODO*/} } public int denominator { get { /* TODO */ } set { /*TODO*/} } } The code for these methods will be in the .m file. So that will complement your class implementation for something like: using System; public class Fraction { int _numerator; int _denominator; public void print() { Console.Write("{0}/{1}" ,numerator,denominator); } public int numerator { get { return _numerator; } set { _numerator = value; } } public int denominator { get { return _denominator; } set { _denominator = value; } } } Ok An now let’s look at the Objective-C main.m: #import <stdio.h> #import "Fraction.h" int main( int argc, const char *argv[] ) { // create a new instance Fraction *frac = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; // set the values [frac setNumerator: 1]; [frac setDenominator: 3]; // combined set [frac2 setNumerator: 1 andDenominator: 5]; // print it printf( "The fraction is: " ); [frac print]; printf( "\n" ); // print it printf( "Fraction 2 is: " ); [frac2 print]; printf( "\n" ); // free memory [frac release]; [frac2 release]; return 0; } Which can be rewritten in C# as: using System; static class ProgramMain{static int Main(string[] argv) { // create a new instance Fraction frac = new Fraction(); // set the values frac.Numerator = 1; frac.Denominator = 3; // print it Console.Write( "The fraction is: " ); frac.print(); Console.Write( "\n" ); // free memory frac = null; return 0; }} Well this is just for warming up. In following posts we will be looking at more Objective-C \ XCode concept mapping to C#. I recommend looking at the site that provides a lot about mapping iOS API.
http://blogs.artinsoft.net/author/Mrojas.aspx/?page=6
CC-MAIN-2017-47
refinedweb
699
53.51
I want to have one main class and inside it some variables that I want to call inside other classes. For example: class AwsS3Initalization attr_reader :resource, :client def initialize resource, client @resource = resource @client = client # Where do I define those variables below? I think this is not the right place to put them @resource = Aws::S3::Resource.new(region: 'region', access_key_id: 'my-key', secret_access_key: 'secret-key') @client = Aws::S3::Client.new(region: 'region', access_key_id: 'my-key', secret_access_key: 'secret-key') end end Best way would be to inherit other classes from AwsS3Initalization like: class Foo < AwsS3Initalization end class Bar < AwsS3Initalization end Then you will be able to access all the variables from parent class into subclasses. UPDATE class AwsS3Initialization ACCESS_KEY = <read-from-yml> SECRET_KEY = <read-from-yml> def self.resource Aws::S3::Resource.new(...) end def self.client Aws::S3::Client.new(...) end end
https://codedump.io/share/kPxuQTkBwSnS/1/share-variables-across-different-classes-ruby
CC-MAIN-2017-04
refinedweb
143
54.22
film_gyaan An unofficial dart SDK which will connect to for you. For details on API go to. This is an unofficial package for TheMovieDB. And I don't take any credit for the APIs related to TheMovieDB. Create an API Key at and use this in the package while initializing. Add film_gyaan: <version>to the project. Add import 'package:film_gyaan/film_gyaan.dart';to start accessing the SDK features. Initialize the FilmGyaan with the API key. var filmGyaan = FilmGyaan( credentials: Credentials( apiKey: '<API_KEY>', ), ); - Start using the package to get movie list, details and many more. Please add issues/improvements/feature requests on GitHub. Will try to solve or add them as soon as possible. Libraries - film_gyaan - - film_gyaan.core - Core is the library which will handle the core functionality related to the filmy gyaan SDK.
https://pub.dev/documentation/film_gyaan/latest/
CC-MAIN-2022-33
refinedweb
133
70.9
Up to [DragonFly] / src / sys / sys Request diff between arbitrary revisions Keyword substitution: kv Default branch: MAIN *. Bring uuidgen(3) into libc and implement the uuidgen() system call. Obtained-from: FreeBSD / Marcel Moolena). 1:1 Userland threading stage 4.8/4: Add syscalls lwp_gettid() and lwp_kill()... Move all the resource limit handling code into a new file, kern/kern_plimit.c. Add spinlocks for access, and mark getrlimit and setrlimit as being MPSAFE. Document how LWPs will have to be handled - basically we will have to unshare the resource structure once we start allowing multiple LWPs per process, but we can otherwise leave it in the proc structure. preadv() and pwritev() systems and regenerate. Submitted-by: Chuck Tuffli <ctuffli@gmail.com> Loosely-based-on: FreeBSD Pass the direction to kern_getdirentries, it will be used by the emulation layer soon without transfering the data to userland first. Add closefrom(2) syscall. It closes all file descriptors equal or greater than the given descriptor. This function does exit and return EINTR, when necessary. Other errors from close() are ignored. Uncomment the entry for kern_chrot in kern_syscall.h and change the implementation to take the namecache entry directly.. Improve seperation between kernel code and userland code by requiring that source files that #include kernel headers also #define _KERNEL or _KERNEL_STRUCTURES as appropriate. With-suggestions-from: joerg Still-todo: systimer.h, and clean up scsi_da.c Tested-by: cd /usr/src/nrelease && make installer_release Approved-by: dillon If-anything-breaks-yell-at: cpressey. Lots of bug fixes to the checkpointing code. The big fix is that you can now checkpoint a program that you have checkpoint-restored. i.e. you run program X, you checkpoint it, you checkpoint-restore X from the checkpoint, and then you checkpoint it again. The issue here is the when a checkpointed program is restored the checkpoint file is used to map portions of the image of the restored program. If you then tried to checkpoint the restored image the system would overwrite or destroy the original checkpoint file and the new checkpoint file would have references to the old file (now non-existant) file. Any attempt to restore the recursed checkpoint would result in a seg-fault. That is now fixed. * Remove the previous checkpoint file before saving the new one. If the program we are checkpointing happens to be a checkpoint restore from the same file then overwriting the file would wind up corrupting the image set we are trying to save. * When checkpointing a program that has been checkpoint-restored do not attempt to save the file handles for the vnode representing the checkpoint-restored program's own checkpoint file (which is a good chunk of its backing store), because this vnode is likely to be destroyed the moment we close the handle, since we are likely replacing the previous checkpoint file. Instead, the backing store representing the old checkpoint file is copied to the new one. * Re-checkpointing a program (hitting ^E multiple times) now properly replaces the checkpoint file. * Properly close any file descriptors from the checkpt(1) program itself when restoring a checkpointed program, properly replace any file descriptors that need replacing. * Properly replace p_comm[] when restoring a checkpoint file, so checkpointing again saves under the same program name. 'ps' output is still wrong, though. TODO LIST: * Add an iterator to the checkpoint file, accessible via kern.ckptfile, so successive checkpoints save to a blah.ckpt.1, blah.ckpt.2, etc, rather then always overwriting blah.ckpt (the iterator could be saved in the proc structure). * Add back as a 'feature' the ability for the new checkpoint file to reference the old one. That is, each new checkpoint file would represent a delta relative to the old one. This might be useful when checkpointing programs with ever growing data setse so as not to have to copy the entire contents of the program to the checkpoint file each time you want to make a new checkpoint. It would be hell on the VM system, but it would work. * Add an option to checkpt(1) so you can checkpoint-restore-enter-gdb all in one go, to be able to debug a checkpointed file more easily. Inspired by: Brook Davis's HPC presentation. He expressed an interest in possibly porting the checkpoint code so I figure I ought to fix it up. VFS messaging/interfacing work stage 9/99: VFS 'NEW' API WORK. NOTE: unionfs and nullfs are temporarily broken by this commit. * Remove the old namecache API. Remove vfs_cache_lookup(), cache_lookup(), cache_enter(), namei() and lookup() are all gone. VOP_LOOKUP() and VOP_CACHEDLOOKUP() have been collapsed into a single non-caching VOP_LOOKUP(). * Complete the new VFS CACHE (namecache) API. The new API is able to supply topological guarentees and is able to reserve namespaces, including negative cache spaces (whether the target name exists or not), which the new API uses to reserve namespace for things like NRENAME and NCREATE (and others). * Complete the new namecache API. VOP_NRESOLVE, NLOOKUPDOTDOT, NCREATE, NMKDIR, NMKNOD, NLINK, NSYMLINK, NWHITEOUT, NRENAME, NRMDIR, NREMOVE. These new calls take (typicaly locked) namecache pointers rather then combinations of directory vnodes, file vnodes, and name components. The new calls are *MUCH* simpler in concept and implementation. For example, VOP_RENAME() has 8 arguments while VOP_NRENAME() has only 3 arguments. The new namecache API uses the namecache to lock namespaces without having to lock the underlying vnodes. For example, this allows the kernel to reserve the target name of a create function trivially. Namecache records are maintained BY THE KERNEL for both positive and negative hits. Generally speaking, the kernel layer is now responsible for resolving path elements. NRESOLVE is called when an unresolved namecache record needs to be resolved. Unlike the old VOP_LOOKUP, NRESOLVE is simply responsible for associating a vnode to a namecache record (positive hit) or telling the system that it's a negative hit, and not responsible for handling symlinks or other special cases or doing any of the other path lookup work, much unlike the old VOP_LOOKUP. It should be particularly noted that the new namecache topology does not allow disconnected namecache records. In rare cases where a vnode must be converted to a namecache pointer for new API operation via a file handle (i.e. NFS), the cache_fromdvp() function is provided and a new API VOP, VOP_NLOOKUPDOTDOT() is provided to allow the namecache to resolve the topology leading up to the requested vnode. These and other topological guarentees greatly reduce the complexity of the new namecache API. The new namei() is called nlookup(). This function uses a combination of cache_n*() calls, VOP_NRESOLVE(), and standard VOP calls resolve the supplied path, deal with symlinks, and so forth, in a nice small compact compartmentalized procedure. * The old VFS code is no longer responsible for maintaining namecache records, a function which was mostly adhoc cache_purge()s occuring before the VFS actually knows whether an operation will succeed or not. The new VFS code is typically responsible for adjusting the state of locked namecache records passed into it. For example, if NCREATE succeeds it must call cache_setvp() to associate the passed namecache record with the vnode representing the successfully created file. The new requirements are much less complex then the old requirements. * Most VFSs still implement the old API calls, albeit somewhat modified and in particular the VOP_LOOKUP function is now *MUCH* simpler. However, the kernel now uses the new API calls almost exclusively and relies on compatibility code installed in the default ops (vop_compat_*()) to convert the new calls to the old calls. * All kernel system calls and related support functions which used to do complex and confusing namei() operations now do far less complex and far less confusing nlookup() operations. * SPECOPS shortcutting has been implemented. User reads and writes now go directly to supporting functions which talk to the device via fileops rather then having to be routed through VOP_READ or VOP_WRITE, saving significant overhead. Note, however, that these only really effect /dev/null and /dev/zero. Implementing this was fairly easy, we now simply pass an optional struct file pointer to VOP_OPEN() and let spec_open() handle the override. SPECIAL NOTES: It should be noted that we must still lock a directory vnode LK_EXCLUSIVE before issuing a VOP_LOOKUP(), even for simple lookups, because a number of VFS's (including UFS) store active directory scanning information in the directory vnode. The legacy NAMEI_LOOKUP cases can be changed to use LK_SHARED once these VFS cases are fixed. In particular, we are now organized well enough to actually be able to do record locking within a directory for handling NCREATE, NDELETE, and NRENAME situations, but it hasn't been done yet. Many thanks to all of the testers and in particular David Rhodus for finding a large number of panics and other issues. VFS messaging/interfacing work stage 7) Rearrange the kern_getcwd() procedure to return the base of the string rather then relocating the string. Also fix two bugs: (1) the original bcopy was copying data beyond the end of the buffer ([bp, bp+buflen] exceeds the buffer), and (2), the uap->buflen checks must be made in __getcwd(), before the kernel tries to malloc() space. Split the __getcwd syscall into a kernel and an userland part, so it can be used in the kernel as well. Pointers by: Matthew Dillon <dillon@apollo.backplane.com> Change sendfile() to send the header out coaleseced with the data. Inspired by Mike Silbersack's FreeBSD rev 1.171 to uipc_syscalls.c.@frenchfries.net> Additional-work-by: dillon Split mmap(). Move ovadvise(), ogetpagesize() and ommap() to new file 43bsd/43bsd_vm.c. Split mkfifo(). Trash the CHECKALT{CREAT,EXIST} macros and friends. Implement linux_copyin_path() and linux_free_path() for path translation without using the stackgap. Use the above and recently split syscalls to remove stackgap allocations from linux_creat(), linux_open(), linux_lseek(), linux_llseek(), linux_access(), linux_unlink(), linux_chdir(), linux_chmod(), linux_mkdir(), linux_rmdir(), linux_rename(), linux_symlink(), linux_readlink(), linux_truncate(), linux_link(), linux_chown(), linux_lchown(), linux_uselib(), linux_utime(), linux_mknod(), linux_newstat(), linux_newlstat(), linux_statfs(), linux_stat64(), linux_lstat64(), linux_chown16(), linux_lchown16(), linux_execve(). Split use split syscalls to reimplement linux_fstatfs(). Implement linux_translate_path() for use in exec_linux_imgact_try(). Split execve(). This required some interesting changes to the shell image activation code and the image_params structure. Userland pointers are no longer passed in the image_params structure. The exec_copyin_args() function now pulls the arguments, environment and filename of the target being execve()'d into a kernel space buffer before calling kern_execve(). The exec_shell_imgact() function does some magic to prepend the interpreter arguments. The last major syscall separation commit completely broke our lseek() as well as the linux emulated lseek(). It's sheer luck that the system works at all :-). Fix lseek's 64 bit return value. Split wait4(), setrlimit(), getrlimit(), statfs(), fstatfs(), chdir(), open(), mknod(), link(), symlink(), unlink(), lseek(), access(), stat(), lstat(), readlink(), chmod(), chown(), lchown(), utimes(), lutimes(), futimes(), truncate(), rename(), mkdir(), rmdir(), getdirentries(), getdents(). Trash the 4.3BSD numeric filesystem type support in mount(). Move ocreat(), olseek(), otruncate(), ostat(), olstat(), owait(), ogetrlimit(), and osetrlimit() to the 43bsd subtree and reimplement using split syscalls. Move ogetdirentries() to the subtree without change because it is such a mess. Convince linux_waitpid(), linux_wait(), linux_setrlimit(), linux_old_getrlimit(), and linux_getrlimit() to use split syscalls. The file kern/vfs_syscalls.c is now completely free of COMPAT_43 code. I believe that execve() is the only pending split before I can tackle stackgap usage in the linux emulator's CHECKALT{EXIST,CREAT}() macros.. Create the kern_fstat() and kern_ftruncate() in-kernel syscalls. Implement fstat(), nfstat() and ftruncate() using the in-kernel syscalls. Move ofstat() and oftruncate() to the 43bsd emulation tree and implement with in-kernel syscalls. Create the linux_ftruncate() syscall in the linux emulation layer. This replaces a direct use of oftruncate() in the linux syscall map. Rewrite linux_newfstat() and linux_fstat64() with the in-kernel syscalls. Create kern_readv() and kern_writev() and use them to split read(), pread(), readv(), write(), pwrite(), and writev(). Also, rewrite linux_pread() and linux_pwrite() using the in-kernel syscalls. Rename do_dup() to kern_dup() and pull in some changes from FreeBSD-CURRENT. Implement dup(), dup2() and fcntl(F_DUPFD) with kern_dup(). Split fcntl() into fcntl() and kern_fcntl(). Implement linux_fcntl() using kern_fcntl() and replace a call to fcntl() in linux_accept() with a call to kern_fcntl().. Modify kern_{send,recv}msg() to take struct uio's, not struct msghdr's. Fix up all syscalls which use these functions, including the 43bsd syscalls. Also, fix some spots where I forgot to pass the message flags in the emulation code. Split getsockopt() and setsockopt(). Separate all of the send{to,msg} and recv{from,msg} syscalls and create kern_sendmsg() and kern_recvmsg(). The functions sendit() and recvit() are now no more. Rewrite the related legacy syscalls and place them in the 43bsd emulation directory. Also move the definition of omsghdr to the emulation directory. Change the split syscall naming convention from syscall1() to kern_syscall() while moving the prototypes from sys/syscall1.h to sys/kern_syscall.h. Split the listen(), getsockname(), getpeername(), and socketpair() syscalls.
http://www.dragonflybsd.org/cvsweb/src/sys/sys/kern_syscall.h?f=h
CC-MAIN-2014-52
refinedweb
2,144
56.55
I set up wireless at home a couple of weeks ago and became interested in wireless tools. I wanted to know how AP scanner software works. I did a bit of research and it turned out that getting Wifi information is rather simple with the NDISUIO driver that is available on PocketPC 2003 and newer systems. So, I coded a simple scanner that has two view modes. The first is a colored list of all nearby APs. The other mode displays the signal strength of a selected AP with large numbers. This way it has an acceptable outdoor visibility and you can follow a single signal without having to see the APs of your neighbours flashing on your screen. I also included different custom MFC controls I coded before: a bitmapped slider, a tab control and buttons. I hope you find these classes useful, too. NDISUIO This article features the following classes: CWifiPeek CColoredDlg CCustomTabCtrl CCustomSlider CCustomButton PeekPocket is fairly simple to use. Just turn your WLAN on, run the application and see the APs listed. Secure APs are printed in red, while inactive ones are greyed out. An inactive AP is one that is not currently visible. If you tap an AP name, you can "go large," i.e. follow one signal without seeing any other APs. You can set the list font size and scanning speed on the Options tab. You can also set network type and security filters there. Your Wifi adapter should be displayed in the combo. If it is not, something's wrong. In such a case, you can try the following: If these do not help, sometimes a reset will. You can compile the application with Visual Studio 2005 and the PocketPC 2003 SDK. PeekPocket should run fine on WM5 and WM6 devices, too. If you add other SDKs to the demo project, you might need to change a couple of compiler/linker settings. The CWifiPeek class does all the Wifi query stuff. It can be used in non-MFC applications, too. You have to add CWifiPeek.h and CWifiPeek.cpp to your project. Don't forget to disable use of precompiled headers for this CPP file! The class uses the NDIS User mode I/O driver (NDISUIO) to perform AP scanning. The following structure will be used to return station info: struct BSSIDInfo { BYTE BSSID[6]; //MAC Address WCHAR SSID[32]; //Station name int RSSI; //Signal strength int Channel; //Used channel int Infastructure; //Type: AP or peer int Auth; //Open or secure? }; The class provides the following functions: bool GetAdapters(LPWSTR pDest, DWORD &dwBufSizeBytes); bool RefreshBSSIDs(LPWSTR pAdapter); bool GetBBSIDs(LPWSTR pAdapter, struct BSSIDInfo *pDest, DWORD &dwBufSizeBytes, DWORD &dwReturnedItems); The GetAdapters function can be used to query names of network adapters. It calls the built-in NDIS (not NDISUIO) driver. You have to pass the address of a WCHAR buffer and the buffer size. The function fills the buffer with adapter names separated by commas. It also sets the DWORD to the number of bytes returned. It filters out some adapter names, e.g. infrared, GPRS, ActiveSync connection. If the function returns true, but indicates that it copied zero bytes, something might be wrong. Your Wifi might be turned off or might not be operational. GetAdapters NDIS WCHAR DWORD true The function uses the <a href="">IOCTL_NDIS_GET_ADAPTER_NAMES</a> IOCTL call. Adapter names must be retrieved because the NDISUIO calls require this parameter. The RefreshBSSIDs function requests that the driver initiate an AP survey. It takes one parameter: an adapter name. Upon success, it returns true. This function is called frequently so that we have an up-to-date list. <a href="">IOCTL_NDIS_GET_ADAPTER_NAMES</a> RefreshBSSIDs The GetBBSIDs function returns the list of available stations, i.e. peers and Access Points. It takes an adapter name and a pointer to the destination buffer, along with the buffer size. If it succeeds, it returns true and fills dwReturnedItems with the number of returned structures, not bytes. These two methods use the <a href="">OID_802_11_BSSID_LIST_SCAN</a> and <a href="">OID_802_11_BSSID_LIST</a> wireless OIDs. Notes on the returned station data: GetBBSIDs dwReturnedItems <a href="">OID_802_11_BSSID_LIST_SCAN</a> <a href="">OID_802_11_BSSID_LIST</a> BSSID SSID RSSI Infrastructure <a href="">Ndis802_11IBSS</a> <a href="">Ndis802_11Infrastructure</a> Auth <a href="">Ndis802_11AuthModeOpen</a> The base class of all dialogs is CColoredDlg instead of CDialog. This class provides support for custom colors with an OnCtlColor handler. During the paint cycle of dialog controls, this handler is invoked and the parent dialog can set the background and foreground colors of the controls being drawn. This feature can be used to make the GUI look a bit different. However, it's very simple if you look at the code. You can use this class in a few simple steps: CDialog OnCtlColor #include "ColoredDlg.h" That's it! Colors should be set up in the OnInitDialog function with SetBkgColor and SetFrgColor calls. These take a COLORREF value that you can create with an RGB macro, for instance. A two-minute dialog with colored controls can be seen here: OnInitDialog SetBkgColor SetFrgColor COLORREF RGB You can draw different controls with different colors using an OnCtlColor handler. Controls don't have to be owner-drawn to have their colors changed. The Tab control in CustomTabCtrl.h and CustomTabCtrl.cpp is a WinCE / PocketPC compatible version of Andrzej Markowski's excellent Custom Tab Control. I've made it WinCE-compatible by removing everything Win32-specific, such as XP themes support, tooltips, etc. I've also made the tabs rectangular, as it was a lot simpler to draw these with WinCE GDI. Left and right orientations are present, but they are experimental and very slow, i.e. no PlgBlt on WinCE. In general, it's recommended to use the top and bottom orientations only. The class is still compatible with Win32 and can be used with Embedded Visual C++ 4, too. PlgBlt Have a look at Andrzej's article to see how to use this control in your applications. Just don't forget to disable use of precompiled headers for this version. The control can be created both dynamically and from a template. The control supports custom colors. To get and set these colors, use the following functions: void GetColors(TabItemColors *pColorsOut); void SetColors(TabItemColors *pColorsIn, BOOL fRedraw=FALSE); These calls use the following structure: struct TabItemColors { COLORREF crWndBkg; //window background color COLORREF crBkgInactive; //background color for inactive tab item COLORREF crBkgActive; // .. active tab item COLORREF crTxtInactive; //text color for active tab item COLORREF crTxtActive; // .. active tab item COLORREF crDarkLine; //darker line COLORREF crLightLine; //lighter line }; You can see which is which on this image: The "Scanner" tab is active and the "Options" tab is inactive. The lines around tabs are "dark lines." The crLightLine field is reserved for future use. The rectangular area on the right, marked with "1," is "window background." That is, a part of the control window where no tabs are drawn. It's a good idea to call GetColors first, update the colors you wish and then call SetColors. Have a look at the CPPDlg::OnInitDialog function. You can set the tab font too, just as with the original control. One thing to keep in mind is that if you use CFont, you should not declare it on OnInitDialog, but as a member variable in the dialog header. This way the font won't be freed until the dialog is closed. crLightLine GetColors SetColors CPPDlg::OnInitDialog CFont I've added something else to the control: the container mode. Andrzej's tab control is actually a bar with buttons. The bar sends various notifications to its parent when the user clicks something, but it's the application's task to show and hide child windows accordingly. A container, on the other hand, can host child dialogs and displays or hides them automatically. The container mode can be enabled by setting the CTCS_CONTAINER style This mode is supported by a derived class, CCustomTabContainer. New functions related to the container mode are: CTCS_CONTAINER CCustomTabContainer int GetTabsHeight(); void SetTabsHeight(int nHeight); void AdjustRect(BOOL bLarger, LPRECT lpRect); void AddDialog(int nIndex, CString strText, CDialog *pDlg); void RemoveDialog(int nIndex); When in container mode, the height of the entire tab control window is obviously larger than just the height of the tabs: Tabs' height can be set with the SetTabsHeight function. To get the current value, use the GetTabsHeight function. The control has an AdjustRect function that is similar to CTabCtrl::AdjustRect. To use the container in an application, proceed as follows: SetTabsHeight GetTabsHeight AdjustRect CTabCtrl::AdjustRect CScannerDlg COptionsDlg m_pScannerDlg m_pOptionsDlg AddDialog Note that the container calls delete on the dialogs automatically when either the container is destructed, the close button is tapped or when you call RemoveDialog. delete RemoveDialog This is a bitmapped slider control and is implemented as a CWnd-derived class. It can be used on WinCE / PocketPC and Win32 platforms, too. It has horizontal and vertical orientations, as well as a reversed mode: CWnd To use it in your application, proceed as follows: #include "CustomSlider.h" CustomSliderClass m_Slider.Create(_T("CustomSliderClass"), strTitle, strStyle, sliderRect, this, IDC_SLIDER) DDX_Control DoDataExchange As you probably know, a slider control has two distinct parts: the so-called thumb -- i.e. the object that actually slides -- and the channel, i.e. the area where the thumb moves. The following picture shows a channel, a thumb and the slider control they make: The slider has the following properties, which should be set up in OnInitDialog: BkgColor RangeMin RangeMax Pos Reverse You can use the following functions to get and set these properties: void GetRange(DWORD& dwMin, DWORD& dwMax); DWORD GetRangeMin(); DWORD GetRangeMax(); void SetRange(DWORD dwMin, DWORD dwMax); void SetRangeMin(DWORD dwMin); void SetRangeMax(DWORD dwMax); DWORD GetPos(); void SetPos(DWORD dwPos); void SetReverse(bool bRev); bool GetReverse(); void SetBkgColor(COLORREF crBkg); COLORREF GetBkgColor(); void SetBitmaps(HBITMAP hBmpChannel, HBITMAP hBmpThumbInactive, HBITMAP hBmpThumbActive = NULL); Notes: TBS_VERT SetBitmaps COptionsDlg::OnInitDialog Here's how to handle slider events. Add an OnHScroll or OnVScroll handler to your dialog class. The handler should look like this: void COptionsDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { if(pScrollBar != NULL && pScrollBar->IsKindOf( RUNTIME_CLASS(CCustomSlider))) { //which slider was it? switch(pScrollBar->GetDlgCtrlID()) { case IDC_SCANSPEED_SLIDER: { ... use nPos break; }//case scanspeed slider case IDC_FONTSIZE_SLIDER: { ... use nPos break; }//case fontsize slider } } } There are myriad owner-drawn buttons for Win32, but a lot less for WinCE. The <a href="">CCeButtonST</a> is an excellent control, but it does not support a couple of things I wanted. For example, it does not support setting different captions for active/inactive buttons or modifying group box and radio button behaviour. Activating a radio button unchecks all other radios in the same control group. The CCustomButton is an owner-drawn MFC button class that has the following characteristics: <a href="">CCeButtonST</a> To use it in your application, add CustomButton.h and CustomButton.cpp to your application. Guess what: just like the controls above, this one requires you to turn off precompiled headers for the CPP file, too. Add buttons to your dialogs and add member variables of type CCustomButton. There's no need to make your buttons owner-drawn. You can also create the control dynamically with its Create method. The following properties can be set for buttons, checkboxes and radios: Create Colors can be set with the following methods: void SetBkgIdleColor(COLORREF crBkgIdle); void SetBkgActiveColor(COLORREF crBkgActive); void SetFrgIdleColor(COLORREF crFrgIdle); void SetFrgActiveColor(COLORREF crFrgActive); Captions, font and used bitmaps can be changed with: void SetCaption(CString strCaption, CString strActiveCaption = _T("")); void SetFont(HFONT hFont); void SetBitmaps(HBITMAP hBmpInactive, HBITMAP hBmpActive = NULL); The font and bitmaps will be freed automatically. If you omit the second caption or bitmap parameter, the same text/bitmap will be used for active (pressed) and inactive states. As with the slider above, the black color in bitmaps will be treated as transparent. If you set a custom font, make sure it is not freed until the dialog is closed. So if you use CFont for font creation, declare the variable as a dialog class member var in the header file and not in OnInitDialog. You can set some additional properties with the SetFlags function. See the usable flags below. Whether you have a pushbutton or a checkbox depends on the utton styles (BS_XXX) used. These styles will be handled automatically if you add buttons, radios or checkboxes with the dialog editor. If you add controls manually, you should specify the following styles: SetFlags BS_XXX BS_RADIOBUTTON BS_AUTORADIOBUTTON BS_CHECKBOX BS_AUTOCHECKBOX BS_GROUPBOX The following styles are specific for pushbuttons: BS_FLAT BS_PUSHLIKE BS_BITMAP BS_LEFT BS_RIGHT BS_CENTER BS_VCENTER BS_BOTTOM BS_TOP BS_SINGLELINE BS_MULTILINE You can specify additional pushbutton properties with the SetFlags function: bfTextLeft bfTextRight bfTextTop bfTextBottom SetAlign bfHGradient SetGradientColors Here are two buttons with gradient background and custom font: The following styles can be used with checkboxes and radios: You can't specify BS_BITMAP with the dialog editor for these control types, so add it manually to the RC file if required. You can specify additional properties with the SetFlags function: The following checkboxes have the default bfTextRight alignment: The following styles can be used with group boxes: You can specify additional properties with the SetFlags function: The first two group boxes have a caption and demonstrate different text placement and alignment. The third box has no caption; it is nothing much more than a filled rectangle: It takes only three calls to set up a group box: SetFrgIdleColor SetFrameColor SetBkgIdleColor You can set a custom font for the group box, too. Note that because of the way WinCE draws controls, you should take care that the group box is after your grouped controls in the RC file. It does not matter what you see in the dialog editor; the dialog in the RC file should look like this: BEGIN CONTROL "Check1",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | BS_BITMAP,48,54,60,10 CONTROL "Check2",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | BS_BITMAP,48,72,60,10 PUSHBUTTON "Flat button",IDC_FLATBTN,35,27,90,19,BS_FLAT GROUPBOX "GroupBox",IDC_GB,7,7,142,101 END The group box is the last one. If you create controls dynamically, you should order them with SetWindowPos so that the group box does not cover other controls. Have fun! SetWindowPos Thanks to you eagle-eyed readers, I've fixed a number of smaller bugs in this project. I've also added some features, including a multilingual user interface beginning with 5 languages: English, French, Hungarian, Polish and Portuguese. If you wish to use any of the classes featured in this article, I kindly ask you to get the most recent sources.
https://www.codeproject.com/articles/19341/wifi-scanner-custom-mfc-controls?fid=431977&df=90&mpp=10&noise=1&prof=true&sort=position&view=expanded&spc=none
CC-MAIN-2017-04
refinedweb
2,430
54.63
This post shows how one can verify if a given IPv4/IPv6 address belongs to a given subnetwork represented in CIDR notation. The solution presented here works both on Python 2.x and 3.x, but users of Python 3.x can also use the netaddr module to achieve the same purpose (as described here). The key idea is very simple: since IP addresses can be directly interpreted as integers (IPv4 and IPv6 addresses are 32-bit and 128-bit integers respectively), and since a subnetwork is merely a contiguous range of IP addresses, we can determine the integer values of the lower and upper bounds of the address range defined by the given subnetwork and then check if the given IP address falls within this range or not. If is falls within the computed integer range, it is part of the given subnetwork; otherwise, it is outside of it. The ip_in_subnetwork function on the code below does what we just described. A detailed explanation of the most difficult parts of the code is given right after it. import socket import binascii def ip_in_subnetwork(ip_address, subnetwork): """ Returns True if the given IP address belongs to the subnetwork expressed in CIDR notation, otherwise False. Both parameters are strings. Both IPv4 addresses/subnetworks (e.g. "192.168.1.1" and "192.168.1.0/24") and IPv6 addresses/subnetworks (e.g. "2a02:a448:ddb0::" and "2a02:a448:ddb0::/44") are accepted. """ (ip_integer, version1) = ip_to_integer(ip_address) (ip_lower, ip_upper, version2) = subnetwork_to_ip_range(subnetwork) if version1 != version2: raise ValueError("incompatible IP versions") return (ip_lower <= ip_integer <= ip_upper) def ip_to_integer(ip_address): """ Converts an IP address expressed as a string to its representation as an integer value and returns a tuple (ip_integer, version), with version being the IP version (either 4 or 6). Both IPv4 addresses (e.g. "192.168.1.1") and IPv6 addresses (e.g. "2a02:a448:ddb0::") are accepted. """ # try parsing the IP address first as IPv4, then as IPv6 for version in (socket.AF_INET, socket.AF_INET6): try: ip_hex = socket.inet_pton(version, ip_address) ip_integer = int(binascii.hexlify(ip_hex), 16) return (ip_integer, 4 if version == socket.AF_INET else 6) except: pass raise ValueError("invalid IP address") def subnetwork_to_ip_range(subnetwork): """ Returns a tuple (ip_lower, ip_upper, version) containing the integer values of the lower and upper IP addresses respectively in a subnetwork expressed in CIDR notation (as a string), with version being the subnetwork IP version (either 4 or 6). Both IPv4 subnetworks (e.g. "192.168.1.0/24") and IPv6 subnetworks (e.g. "2a02:a448:ddb0::/44") are accepted. """ try: fragments = subnetwork.split('/') network_prefix = fragments[0] netmask_len = int(fragments[1]) # try parsing the subnetwork first as IPv4, then as IPv6 for version in (socket.AF_INET, socket.AF_INET6): ip_len = 32 if version == socket.AF_INET else 128 try: suffix_mask = (1 << (ip_len - netmask_len)) - 1 netmask = ((1 << ip_len) - 1) - suffix_mask ip_hex = socket.inet_pton(version, network_prefix) ip_lower = int(binascii.hexlify(ip_hex), 16) & netmask ip_upper = ip_lower + suffix_mask return (ip_lower, ip_upper, 4 if version == socket.AF_INET else 6) except: pass except: pass raise ValueError("invalid subnetwork") A few explanations may be necessary to make this code clear (assuming, of course, that you understand the CIDR notation). To start, notice that on subnetwork_to_ip_range, we compute a "suffix mask", which is a mask whose bits are equal to one if they are in the host part of an IP address and zero if they are part of the network prefix. This mask is the same as the netmask for the given subnetwork with all bits inverted. Since the lowest IP address in a given subnetwork has all bits in the host part equal to zero, it is identical to the network prefix. By summing the network prefix and the suffix mask, we get the largest IP address in the subnetwork. On both ip_to_integer and subnetwork_to_ip_range, the function socket.inet_pton is used to convert an IP address into its representation as a binary string (a 32-bit/4-byte string for IPv4 and a 128-bit/16-byte string for IPv6). As an example, "192.168.1.0" is converted to "\xc0\xa8\x01\x00", whose bytes represent the numbers 192 (0xc0), 168 (0xa8), 1 (0x01) and 0 (0x00) in hexadecimal notation respectively. This binary string (ip_hex) is then converted to an actual hexadecimal string by binascii.hexlify. For instance, "\xc0\xa8\x01\x00" is converted to the ASCII string "c0a80100" (the resulting string is therefore twice as long as the original one since each byte on the original string needs two characters to be represented in hexadecimal). This string is then passed to the int constructor to be converted to an integer value. The second parameter (16) which is passed to int indicates that the input string is an integer value represented in hexadecimal notation. Finally, notice that both ip_to_integer and subnetwork_to_ip_range try to process their input parameters first as IPv4 addresses/subnetworks, then as IPv6. An exception is thrown only if both attempts fail, but this will only happen if the input parameter does not represent a valid IP address/subnetwork.
https://diego.assencio.com/?index=85e407d6c771ba2bc5f02b17714241e2
CC-MAIN-2019-09
refinedweb
836
55.95
I have my gameServer.py script running remotely through PuTTy. gameServer.py looks like this: while True : (( listen for packets )) (( send all packets to all clients )) WHEN I execute the script normally: ./gameServer.py It works perfectly but the terminal is tied up. Naturally quitting PuTTy terminates my script. I want to be able to close PuTTY and just have this script run perpetually so I tried: ./gameServer.py & But that actually does not work and I don't understand why. First of all its not receiving or sending any packets when run in that & mode, second of all it will go "+ Stopped" whenever I type enter or ANYTHING into the console. & I don't see why it would be stopping, but try nohup ./gameServer.py & This should cause gameServer.py to ignore the hangup signal when you disconnect PuTTY Try putting it in the background with the command: bg user@rkt:~$ sleep 10 ^z [1]+ Stopped sleep 10 user@rkt:~$ bg [1]+ sleep 10 & user@rkt:~$ jobs [1]+ Running sleep 10 & You can change your process to be a daemon, then you can detouch your tty without having it killed: def become_daemon(): pid = os.fork () if pid != 0: # if pid is not child... sys.exit(0) os.setsid() # Create new session and sets process group. pid = os.fork () # Will have INIT (pid 1) as parent process... if pid != 0: # if pid is not child... sys.exit(0) and in your script simple invoke this function You can look at this ActiveState recipe for more about the double-fork mechanism and more precise implementation. Another way to log off and leave jobs running is with the "disown <jobid>" command. It allows you to unbind jobs from the current login session, so you can logoff. disown <jobid> This isn't aimed at answering your python problem, wouldn't have a clue where to start with that, but a temporary workaround / useful utility is called screen yum install screen or apt-get install screen if you're using either Debian/Ubuntu or Redhat/Centos/Fedora will install it. Screen provides you with a shell session that you can detach from and re-attach from without having to maintain a connection. I pretty much use it on any box I'm connected to because if I get disconnected I don't cut off potentially damaging work in it's flow. screen yum install screen apt-get install screen just run screen to spawn a new session, run your command and then press ctrl+a and then d (keep control held down for both letters) To reconnect, run screen -dr from the command line and your screen session will attach itself to your current connection. screen -dr By posting your answer, you agree to the privacy policy and terms of service. asked 5 years ago viewed 1444 times active
http://serverfault.com/questions/71376/why-doesnt-my-python-script-keep-running-when-i-use/71397
CC-MAIN-2015-40
refinedweb
475
70.43
by Matthew Ford 4th October 2018 (originally posted 10th Aug 2014) © Forward Computing and Control Pty. Ltd. NSW Australia Mechanical switches do not switch cleanly. The contacts bounce as they open and close. See “A Guide to Debouncing” for examples. This library, DebouncedSwitch V3.2 will debounce a switch connected from an Arduino digital input to GND. It has separate debounce timings for closing and opening. These are set initially to 50mS in the DebouncedSwitch.cpp file. Increase them if your switch needs it. The library adds about 350bytes of program and for each switch uses 6 bytes of RAM, so it is light weight. As well as giving a debounced switch status, the library also indicates when the switch changes state. See the example below. Download DebouncedSwitch.zip to your computer, move it to your desktop or some other folder you can easily find and then use Arduino 1.5.5 IDE menu option Sketch → Import Library → Add Library to install it.). The examples are included with the library. Here is a simple sketch that turns the LED on when the switch is DOWN and off when the switch is UP (not connected to GND) #include <DebouncedSwitch.h> int led = 13; int D4 = 4; // give the pin a name DebouncedSwitch sw(D4); // monitor a switch on input D4 void setup() { pinMode(led, OUTPUT); // initially low (OFF) } void loop() { sw.update(); // call this every loop to update switch state if (sw.isDown()) { // debounced switch is down digitalWrite(led, HIGH); } else { digitalWrite(led, LOW); } } Here is a simple sketch that toggles the LED when the normally open momentary push button is released. #include <DebouncedSwitch.h> int led = 13; int D4 = 4; // give the pin a name DebouncedSwitch sw(D4); // monitor a switch connected between input D4 and GND void setup() { pinMode(led, OUTPUT); // initially low (OFF) } void loop() { sw.update(); // call this every loop to update switch state if (sw.isChanged()) { // debounced switch changed state Up or Down // isChanged() is only true for one loop(), cleared when update() called again if (!sw.isDown()) { // switch was just released // toggle the led // read current value and set opposite one digitalWrite(led, !digitalRead(led)); } } } The update() method has to be called for each switch every loop to update the status. The isChanged() method only returns TRUE when the switch changes state from UP to DOWN or from DOWN to UP. The next call to update() clears the isChanged() flag so it is only TRUE for one loop when the switch changes state.
https://www.forward.com.au/pfod/ArduinoProgramming/DebouncedSwitch/DebouncedSwitch.html
CC-MAIN-2018-47
refinedweb
418
72.87
StepArea3DSeriesView Class A series view of the 3D Step Area type. Namespace: DevExpress.XtraCharts Assembly: DevExpress.XtraCharts.v19.1.dll Declaration public class StepArea3DSeriesView : Area3DSeriesView, IStepSeriesView Public Class StepArea3DSeriesView Inherits Area3DSeriesView Implements IStepSeriesView Remarks The StepArea3DSeriesView class provides the functionality of a series view of the 3D Step Area type within a chart control. In addition to the common area view settings inherited from the base Area3DSeriesView class, the StepArea3DSeriesView class declares a step area type specific setting, which allows you to control the manner in which step areas are drawn within the view (StepArea3DSeriesView.InvertedStep). Note that a particular view type can be defined for a series via its SeriesBase.View property. For more information on series views of the 3D step area type, please see the Step Area Chart topic.
https://docs.devexpress.com/CoreLibraries/DevExpress.XtraCharts.StepArea3DSeriesView?v=19.1
CC-MAIN-2021-21
refinedweb
132
50.36
Feature #7250 A mechanism to include at once both instance-level and class-level methods from a module Description =begin I have simply commented first on #7240, but i feel i need to start a ticket in order to not post off topic. This seems to be a big feature request, so i didn't feel confident to suggest, but when i read in #7240 that (({Module#included})) hook can become even more hooked, i've decided to express myself. === Proposal In my opinion, the most common use case for the "(({included}))" hook in modules is adding class methods. However, to me this looks hackish and hard to follow. I would have preferred if there was a way to define both instance-level and class-level behavior in a module and include both at once. Here is an API i would suggest: module M def foo 'Foo' end def base.bar # here a fictional private method Module#base is called 'Bar' end end class C include M end a = C.new a.foo # => 'Foo' C.bar # => 'Bar' This means that a module would need to store 2 method tables, one as usual, and a second one defined as singleton methods on some object returned by some private method, called for example (({Module#base})). Since ordinary objects have no method table, classes have one method table, why not to allow modules to have 2 method tables? === Relevant considerations Talking about method tables, maybe if objects were allowed to have one, there would be no need for meta-classes? (Then classes would have 2 method tables, modules would have 3, and in fact methods and method tables could be regarded as kinds of attributes.) It looks to me like meta-class is simply there to make up for the fact that objects are not allowed to keep their own methods. Allowing modules to have more method tables than classes may look like breaking the inheritance (({Class < Module})), but to me this inheritance does not look like a good idea anyway. For example, a module can be included, but a class cannot. To me, class looks like an object factory, but a module like a container of parts that can be unpacked and mounted onto a class. === Irrelevant considerations I think that from the point of view of English, the method name "(({included}))" is not consistent with the method name "(({extended}))" (the module is included, but the base is extended). I would have preferred if the word "(({extend}))" was used instead of "(({include}))" when "including" one module into another, as this operation seems somewhat different from including a module into a class. I understand that it makes no sense to discuss this now, when (({extend})) is already has its fixed meaning. =end History #1 Updated by Yusuke Endoh almost 3 years ago - Target version set to next minor #2 Updated by Alexey Muranov almost 3 years ago I have fantasized a bit more about an alternative Object Model for Ruby. Here is what i imagined: Objects are allowed to keep their methods more or less the same way as they keep attributes in instance variables. Methods are constant-like attributes, redefining a method generates a similar warning as assigning to a constant. (There is no real difference between methods and data, but there is a somewhat real difference between "constant" and "mutable" data.) Objects of Classclass, that is classes, have a constant INSTANCE_PROTOTYPEof class BasicObject, and the def's define methods on the object referenced by this constant. When a method is called on an object, the method is first looked up in the method table of this object, then in the method table of the INSTANCE_PROTOTYPEof the object's class, then in the method table of the INSTANCE_PROTOTYPEof the ancestor class, etc. (In some sense, object's methods are "shallow copies" of the methods of the instance prototype of the object's class, but they are copied not one-by-one, but by whole method tables, like environments.) Objects of Moduleclass, that is modules, have a constant EXTENSIONS_FORinitialized with Hash.new { |h, k| h[k] = BasicObject.new }, def's inside the module define methods on the object EXTENSIONS_FOR[:INSTANCE_PROTOTYPE], Module#basereturns EXTENSIONS_FOR[:self], so " def base.foo; ... end" defines a method fooon EXTENSIONS_FOR[:self], etc. Instead of inheriting Classfrom Module, both inherit from a new class Namespace. Edited 2014-02-26 Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/7250
CC-MAIN-2015-35
refinedweb
734
57.71
Servlets are one of the older APIs that is now part of Java Enterprise Edition (Java EE). Look at JSF, Struts, Tapestry, Velocity, Shale, or any of the other Java EE or Java based web frameworks and you will see servlets at the core. The servlet API has stood the test of time because it was designed good from the start and has evolved slowly. As part of Java EE 5.0 servlets will be undergoing a maintenance release. At the same time the servlet EG is starting to think about the direction to take the next major Servlet release in the future. Some suggestions we have had that we are looking into for the next major release of servlets include: The list above is not an exhaustive list but should give an idea as to the direction we see the Servlet API going. As the Servlet specification lead I would also like to invite suggestions from the community at large. How are you using Servlets? Where do you want them to go? Your second and third points are at cross-purposes. Enhanced cookie support, especially for registration and login, would just make it easier for programmers to develop insecure and broken systems. Look to HTTP authentication instead for login, and base logins on resources rather than sessions. In other words, make the servlet API more RESTful, not less. Cookie-based accounts are going in the wrong direction. Posted by: elharo on July 13, 2005 at 04:27 AM I've always wondered why http-servlets are the only kinds around. Posted by: tobega on July 13, 2005 at 06:20 AM There should be some way to get the host address and other related server information from the ServletContext - so we can retrieve it w/o a StartupListener. Posted by: rsanheim on July 13, 2005 at 06:36 AM So when I say self registration here I am referring to a cookie that is left on the client that contains merely a username. This cookie would only be left on the client if the end user chooses to do so (think of this as a "remember me next time checkbox"). This very common feature used in may web applications. For example, when you go to Yahoo or Amazon and it knows your username and in some cases the username might be used to direct you to special offers or customized content. This would by no means replace HTTP based authentication. HTTP authentication will still be required to access protected resources with the servlet API. We don't plan on changing that. As for Http servlets there aren't many other variations of the servlets out there. There are SIP Servlets which extend the Servlet API. Having a flexible API makes the Servlets versatile and capable of handling whatever the future may bring. Posted by: gmurray71 on July 13, 2005 at 06:51 AM #1 thing for me would be to allow a container-managed authentication model - ie [auth-method]CONTAINER[/auth-method]. Taking the login method out of the webapp allows container-level integration with (eg) CAS, Athens, and the like, instead of relying on servlet filters, without waiting for a new revision of the servlet spec to add each one. Posted by: ba22a on July 13, 2005 at 06:52 AM I'd like to see a mechanism for deploying non-HTTP servlets. While we see support for well defined protocols in things like the SipServlet spec, I'd like to be able to deploy a servlet that handles a custom protocol over TCP/IP into my servlet container. I understand that this has side effects (e.g. the container can probably not serve any other type of requests (e.g. HTTP requests) if it does not have a way of distinguishing between my custom protocol and other formal protocols. However, I'd be quite happy to have all incoming requests routed to this one servlet. The reason for this: there are still an awful lot of applications around that work with some kind of custom protocol by just opening a TCP/IP connection and dumping text or binary data. Being able to service such requests within a (servlet) container is much more convenient than having to write my own server application managing a ServerSocket for each of those. Depending on the container I select, I might get some of the management and monitoring support that I can get for HttpServlets today. Posted by: okamps on July 13, 2005 at 07:33 AM Greg, One small cosmetic change that I think would help a lot (specially when you are teaching servlets and JSP) is to create an interface for attribute containers (such as ServletContext, HttpSession, ServletRequest and PageRequest implement it): public interface AttributeContainer() { void setAttribute( String name, Object attribute ); Object getAttribute( String name ); Enumeration getAttributeNames(); void removeAttribute( String name ); } The cost of implementing it would be almost none - only PageContext doesn't already have getAttributeNames() and it would be easy to implement it as { return getAttributeNamesInScope( PAGE_SCOPE ) }; the only hard job would be defining a decent name for this interface, as container is already overused on J2EE (maybe AttributesHolder or AttributesManager would make more sense). -- Felipe PS: I had commented this suggestion with some web-tier folks last year at JavaOne, but I'm not sure if I mailed it to you. Posted by: felipeal on July 13, 2005 at 10:25 AM Something like: public class MyServlet .... { @EJB PersonManagement personMngt; @Inject DataSource myDb; @GetMethod public void myOwnDoGet(...) { } @PostMethod public void myOwnDoPost(...) { } } Also, regex in web.xml mappings, allow to do EXCLUDES servlet-mappings. So: ... /* Also, add generics to request.getParameter and request.set/getAttribute methods: public T getAttribute(Key key); So in my servlet I can write: Date d = request.getAttribute(Key.create("loginDate")); Or something like it... Cheers, Arik. Posted by: arikk on July 13, 2005 at 10:31 AM Posted by: arikk on July 13, 2005 at 10:34 AM The new servlet spec should work with NIO. Let's change it from a pull model to a push model. For instance, instead of a getHeaders() method, there should be a HeadersListener interface. Those components that are interested in the headers can simply register for those events. A goal of the new servlet spec should be to get rid of thread pools in a servlet container. Use NIO and a push/event model. Posted by: sethladd on July 13, 2005 at 12:50 PM Oh, and definitely +1 to regex's used for servlet and filter mapping. BTW I believe the Jetty servlet container has done some excellent work on exploring how NIO will fit into a new servlet spec. Posted by: sethladd on July 13, 2005 at 12:51 PM In reference to Anotations Injection @Resource DataSource myDb; @GetMethod public void myOwnDoGet(...) { } @PostMethod public void myOwnDoPost(...) { } } So just a note on your example. We are considering supporting a few annotations defined in JSR 250 (Common Annotations) in the Servlet 2.5 Maintenance Release. In Java EE 5.0 web containers (Servlet 2.5) we are considering an @Resource annotation that provide dependency injection in the same way the @Inject tag you showed in your code snippet. This will allow you to inject DataSources, access to JMS queues, and Environment entries into container managed objects such as servlets and listeners. @EJB will also provide easy definitions on Java EE 5.0 enabled web containers. Stay tuned for more details as the maintenance release progresses. As for the @GetMethod and @PostMethod we haven't gone as far as to define this level yet. The goal of course would be to make the API easier to get jump started with and reduce the need to use deployment descriptors. The web.xml is not going away anytime soon but it would be nice to investigate what can be done to reduce the need for it. Regarding NIO. We hope to investigate this as well but there will be some issues as can be seen in the blog NIO and the Servlet API by one of the Servlet Expert Group members and creator of the Jetty Servlet Server. This blog a good read. The Glassfish Web Container is NIO underneath of the Servlet APIs. Jean-Francois talks about this in his blog Grizzly: An HTTP Listener Using Java Technology NIO. Moving forward it will be good to investigate what APIs make sense to expose to the Servlet API and how they may or may not work with the current model. Posted by: gmurray71 on July 13, 2005 at 05:42 PM JSPs loaded from JARs. One of the things that drives me nuts about JSPs is that there is no way to break them down into modules and ship them with the code. If I want to include a new module in my WAR file, I also have to copy over the JSPs as well which I find sloppy. One module, one JAR, JSPs and code inclusive. Posted by: chicagokarl on July 14, 2005 at 02:11 AM I thought servlets are the assembly language of Java web programming. I just want them to be invisible--e.g. no boilerplate in web.xml. Ask the JSF implementors what enhancements, if any, they need. Posted by: cayhorstmann on July 14, 2005 at 08:09 AM Current httpsession support in spec defines different session for each wedmodule. If application has multiple web modules there will be multiple session objects for a given client and there is no easy way for application to correlate sessions together. For example, if a session in one module timesout and application wants to invalidate sessions in other modules for that client, they cannot achieve that today. Servlet API should provide a notion of ApplicationSession that will have referece to all sessions for a given client. From HttpSession we should be able to get to ApplicationSession and viceversa. SIP Servlet spec already has notion of ApplicationSession(javax.servlet.sip.SipApplicationSession) . Similar programming model can be used in ServletSpec to support httpsessions,sipsessions and other types of sessions. This will help supporting converged applications. Posted by: srinivas_h on July 14, 2005 at 08:28... My 2Cent: full regex support for mappings, including e.g. "/*/*.suffix" (!) get rid of Enumeration in the API, or at least deprecate those methods using Enumeration. THE TIME HAS COME TO DO IT! I like the "JSP from .jar" idea too. Posted by: vict0r on July 14, 2005 at 05:27 PM I have Servlets outlines some of my initial thoughts (sorry, I was going to TrackBack but TrackBacks are still switched off, I think). Posted by: simongbrown on July 15, 2005 at 01:59 AM First on my list is more powerful mappings. It's been awhile since I've worked with servlets, but I seem to remember hitting limitations with mappings more than once. If memory serves correctly, it is sometimes a problem that you need to specify a default mapping for servlets, but still want the ability to reference static files without the default servlet being invoked. Second would be more options for configuring properties. Right now you often embed property name/value pairs in the WAR file somewhere. If your customer has a different configuration, they have to expand the WAR, change the values, and then their stuff gets trampled the next time they deploy. An easy way to package configuration settings outside of the WAR file would be nice. So then I could just get in there and edit a properties file and those props would be hot-deployed right away, or I could deploy a new version of my WAR file and my properties file wouldn't be erased. Posted by: burke_e on July 15, 2005 at 04:39... I'm not asking for the full DNS host name, just the IP address would be fine. We can do getServerName and getServerPort from within a servlet request, why not within a start up listener or servlet context? Surely the servlet should be able to ask the container what its ip address is? Posted by: rsanheim on July 15, 2005 at 09:01 AM Wow I wish I could edit comments here now... Servlet spec should not require to commit and close the response writer, if request was forwarded from another location (SRV version 2.4, section 8.4) The current spec prevents using good MVC practices with directive, because if included resource forwards to another location to obtain a view, a writer is closed and master page is not rendered fully. See details in JSP spec mailing list. I already sent this request to servlets spec group directly, and I got an answer that it will be taken into account. But I thought that it would not hurt to repeat it one more time :) Posted by: michael_jouravlev on July 16, 2005 at 11:14 AM A poster on the Struts user list was having problems posting comments to this blog, so she asked me to post a link to her blog entry on the subject. Posted by: craig_mcc on July 16, 2005 at 05:35 PM Here's my Servlet API wishlist for authentication: Standard support for custom authenticatorsTo integrate with SiteMinder, currently we use Tomcat's custom authenticator support which is a bit of a "hack" (applying the nicest possible term). Standard way of accessing permission groups beyond "Roles":We have a custom JAAS login module to load account and access information from various sources. Currently to access data beyond the "Roles" group we have to make a separate call after the user logs in because there is no standard way of accessing other permission groups. +1 on self-registration and "remember me" Beyond authentication: Async NIO support Standard FTPServlet Apache-style rewrite rules Posted by: ctrawick on July 18, 2005 at 12:08 PM Better HTML support on java.net would be nice too. ;) My post below got pretty mangled, but it's still readable. To clarify, the first item asks for standard support for custom authenticators, not SiteMinder specifically. Posted by: ctrawick on July 18, 2005 at 12:13 PM It would be nice to have some sort of session timeout notification mechanism so that requests to a timed out session could be automatically forwarded to a timeout page or a timeout handler which could be specified either declaratively in web.xml or programatically in the application code. The HttpServlet service() method could transparently capture the timeout event and forward it to an application defined handler. This of course should only occur only when a request to a timed out session is detected, and not when a new session is created. Posted by: branko_juric on July 21, 2005 at 02:28 AM My improvement ideas come from my work on the Java version of ModSecurity (still work in progress): Server-wide filters/plugins. Servlet filters are a pretty capable technology but they are still an application-level feature. I'd like to see a Java standard for web server-wide plug-ins. There is so much to learn from the Apache web server here. on August 08, 2005 at 03:55 AM My vote is for more choice in login methods. BASIC and FORM are need to be supplemented with a mechanism that allows more flexibility, e.g. for the login form to be positioned as an HTML snippet on an unprotected page for instance a home page. It should also be possible to set SSL encryption for just the login form, to avoid sending clear text passwords, but without enforcing SSL for all protected pages after login. Clear text passwords are an egregious security loophole. Session hijacking is also a bad (but not as bad) issue, which all non-SSL security level sessions are open to, which leads to a requirement for sensitive data on authenticated users to be handled differently to insensitive data such as the user's first name used in salutations (insensitive) compared to user's credit card info (sensitive). Currently in any webapp even when on different pages under different security-constraints it is very difficult to handle these 2 seperately without jumping through hoops. The developer must either encrypt everything, just to see a first name salutation, in order to protect the credit card info, or use such mechanisms as an unencrypted first login and an encrypted second login. I hope that makes sense - it's not an obvious problem but it causes many people to ditch CMS. Posted by: ahardy66 on August 08, 2005 at 04:45 PM Here is an import suggestion that will save hundred of hours to Developers worldwide based on the recommended HTML (W3C) standards: Updating the Java Specification to allow the request object to follow a first in first out behavior with "names/values" pairs when retrieving the Request Object, the same way W3C standards recommend: snips from: application/x-www-form-urlencoded ... 2. The control names/values are listed in the order they appear in the document. Otherwise application following the Java standards such as the Jakarta Project (Apache) are not forced to organized their request objects and limit developers to utilize random name/value pair controls. This is a huge limitation when writing dynamic web applications. Developers should be expecting a sorted list to come out *in the order they appear in the document* as recommended. Thank you for your interest in that matter, Jeff Grangier Posted by: jefou on August 12, 2005 at 07:49 PM Updating the Java Specification to allow the request object to follow a first in first out behavior with "names/values" when retrieving the Request Object, the same way W3C standards recommend: Posted by: jefou on August 12, 2005 at 07:51 PM Another security feature. At present servlet containers cannot regulate how many times a user is allowed to attempt to login. Nice-to-have enhancements would be: configurable number of login attempts before lock-out lock-out period length configurability Posted by: ahardy66 on August 25, 2005 at 06:10 AM forgot to mention, the previous suggestion would be to foil scripted attacks attempting to guess the password by brute force means. Posted by: ahardy66 on August 25, 2005 at 06:14 AM The servlet spec is considered low level in these days of web application frameworks. It would be a waste to compete with the frameworks by adopting higher level functionality like self registration. IMHO, the focus should be making improvements that can not be achieved by the frameworks because of the servlet spec. Some of these are: Applicaiton wide session. Someone already mentioned this. A web flow scope, which is wider than a request scope but narrower than session scope. In most frameworks we put the command object or form object in the session. All hell breaks lose when the user opens a form in two browser windows. For single forms this can be handled with hiddens, but when we have a "flows", where we have to carry large session data between screens, things become very complicated. A web flow scope could be the perfect solution. Dynamic reloading of classes without requiring a restart of the full web application. Theoretically, this should be possible unless a class is referred from the session. In practice, all containers restart the application when reloading a class. Hotswapping helps somewhat, but it's limited. Facility for modular development of web applications. Currently, we either make a war for each module, or the full application is developed as a single war. Making a war for each module has many limitations, number one is a lack of application scope (a shared session scope between the wars). On the other hand, modular development in a single war is quite difficult when the development team is large. Someone already mentioned the lack of modularization support in JSPs. Posted by: masum on January 07, 2006 at 07:34 AM I'm using SipServlets, which is a perfect example of non-HTTP servlets. For more info on SIP and SipServlets check out this cool developer community site: Posted by: emmanuelproulx on May 30, 2006 at 11:42 AM Don't know what the cons are, but regex for servlet mapping would be nice. Posted by: cornichon on May 31, 2006 at 12:08 AM First of all thank your for starting this initiative. It is highly needed and I think it is right time to start thinking about "re-inventing" the Servlets API. It is one of the nicest, the most successful and the easiest to work with but it can be improved. Before listing my specific suggestions let me say that among other things we should look at some features of the Ruby language to get some ideas on how to simplify the web components. Now to be specific. Lets introduce the new concept called Web Aware object. Web aware object is any java object that satisifes the method level contract. It just needs to have one of the methods that match the HTTP methods: public void onPost( HttpRequest request, HttpResponse response ); public onGet( HttpRequest request, HttpResponse response ); ... Then, in order to configure this component to respond to particular URL (e.g. ) it would have to be annotated with something like this: @UrlMapping ProcessOrder public void onGet( ... ) or as previosuly suggested bind that with @GetMethod Absence of annotation would mean that component is not mapped for processing of the URL based requests (like not being mapped in web.xml) and it would be treated as a regular java bean. There would be no mandatory web.xml file. Web.xml would be an option for some more complicated scenarios. For the basic scenarios annotations would be sufficient Why I am proposing this? Because of the practical experience. Once we define and map the servlets in web.xml we never touch that definition again. Plus, web.xml is not configurtable on the fly. So why have the external xml for it. We could have smarter application server tools that tell us which components we have configured for web access instead of having it in an external xml. Thank you, Edmon Begoli Posted by: ebegoli on May 31, 2006 at 05:49 AM Hi Greg....Your first item - File Upload - gets my vote. The absence of this item is painful....it would be useful to about 20-30% of my web apps. Posted by: johanley on June 22, 2006 at 05:36 PM
http://weblogs.java.net/blog/gmurray71/archive/2005/07/got_servlets.html
crawl-002
refinedweb
3,740
61.46
Can't create pull request from hg bookmark (BB-11438) On "compare view" I can select a bookmark from the dropdown on a fork, but I can't create a pull request from that bookmark. Going to the pull request UI, I can create a pull request from a changeset that happens to be a bookmark, but there's no bookmark section in the dropdown -- only named branches. It would be great to have bookmarks in the Pull Request dropdown and to be able to create a Pull Request from a bookmark in the compare view. Since these are somewhat analogous to "feature branches" it would also be nice to be able to close/delete them on PR, like branches. +1, as well as all other ways of creating feature parity with hg branches. +1 for all features with hg branches as well +1 (if this is how to vote, if not apologies) @Floris Bruynooghe Just add yourself as a watcher on the issue using the link in the top-right box. I just tried this out again and noticed that it's a bit more annoying that I thought: I cannot even create a pull request after manually selecting the head (bookmark) I want to merge into default. The create pull request button simply doesn't do anything. There is no error message either. In short, trying to merge two heads on default with each other doesn't seem to work. Neither head is an ancestor of the other, so there is something to merge. It would have been a good start if I could just select the revisions to merge from and to freely and manually, but there seems to be too much logic in the form :-) I just created a small test repository to demonstrate this. The compare view works great, but will also not allow me to create a pull request: Yeah we've dropped the ball on that one. We have an internal issue for it but it hasn't been worked on yet. Hi Erik, thanks for the feedback! I'm sure you'll get around to updating/redesigning the logic behind the form one day. i'm curious about one thing: as far as i understand it, the workflow endorsed by bitbucket (named branch per pull request) goes straight against the mercurial documentation: "don't treat branch names as disposable", so let's say the mercurial authors know their code, and creating a branch name for every pull request is "using it wrong". where will i get support if mercurial hits some performance or correctness limits thanks to a few thousand closed branches? Having many (closed or not) named branches wont cause any correctness problems. It's mostly a UI problem: programs often put all named branches into a drop-down which then becomes very, very, big if you have a couple of thousand branches. You can try cloning my 10k test repository and play around. It has 10,000 named branches so it should be a good example of how a repository can look after many years of intensive use. (I notice that there are 22 watchers for this issue, but only 4 votes for it — it should be the other way around! So please vote for it if you haven't already.) That might be because ppl are still trying to figure out how the issue affects their workflow. :) Anyway, I cast my vote now. I'd really like to see this fixed. So, I went back and re-tested this after @Matt Turk wrote me that he can create pull requests between different clones and that he can have multiple pending pull requests between two repositories. What I found is: Pull requests inside a single repository is still broken like described above. Pull requests between repositories work: The "Create pull request" view doesn't know about bookmarks, but you can select a head by its changeset hash. No matter what head you select, the Commits tab will show a preview as if you're selected the branch tip (most recent commit on the branch). Looking at the AJAX request being made explains it: no matter what head you select, the request being made is /user/fork/compare/branch..user/repo:default, that is, it is based on branch names instead of the actual head selected. Clicking "Create pull request" works despite the broken preview! The compare view between repositories mostly works: It knows about bookmarks. The preview of in the Commits tab is correct. When selecting a bookmark, the "Create pull request" button becomes inactive and you cannot create a pull request. Selecting the same head by changeset hash allows you to create a pull request. The pull request has the wrong preview in the Commits tab. So it seems that there is two small problems here: the Commits tab in the pull request view only uses the branch name when fetching the preview and the compare view doesn't allow one to create a pull request after selecting a bookmark. Let's hope the good people at Bitbucket can track those bugs down! +1, following. I feel like creating requests based on branches or bookmarks should simply be an abstraction over doing it from the actual changeset hash itself. By default, I should be able to click on any commit hash in the log, go to the diff and create a pull request from there. Using bookmarks or branches is only abstraction on top of that. @Martin Geisler wrote: How exactly can you select a head by its changeset hash? In bitbucket.org/<username>/<repo>/pull-request/new I can put hashes in the branch field, but they are not accepted. Meaning the selection still stays on the branch, the search tooltip doesn't close (saying No results match ...) and I am still on the branch (selecting the latest head/tip, mostly another bookmark). Okay, so now I could at least reproduce how one can compare a bookmark to something: You have to go to the commits tab and then select the bookmark you want. This shows up in the url then as .../commits/branch/test1with test1being a bookmark. When you go to "compare" up in the toolbar now (the link didn't actually change, according to my FF status bar), it will lead you to the standard compare ui but forward to .../compare/test1..almost immediately and automatically. (which is a wtf in itself). You can then change the target repository to view the difference. Like @Matt Turk said, you can't click on "pull request" right there. You can try and change the pull request url to force a specific commit in the branch, but that also doesn't work (except when the commit/bookmark is also the tip of the branch!) Details: A pull request url looks like this: bitbucket.org/<user>/<repo>/pull-request/new?source=<user>/<repo>:<hash>:<branch>&dest=<user>/<repo>::<branch> When you do create a pull request from your default to the default branch of another repo, the <hash> is set to the tip of your default branch. Changing that hash to the bookmark (part of the default branch) you want does not seem to help. Not only the preview still shows the differences between your tip and the tip of the other default, but also the final pull request. Sorry, but what I got from lots of testing today is that using bookmarks in pull requests doesn't work at all. Not with inserting hashes in the UI and not with inserting hashes in the URL. This might seem to work when the bookmark you want is currently the tip of the default branch, but then you are not actually working with the bookmark, but with the tip of the default branch. If my observations are incorrect, please do tell me. @Johannes Dewender They changed this! I noticed today that the dropdown in the pull request view no longer has entries for the different heads of a named branch... It used to list each head as separate entries. The heads were listed by their changeset ID, but I could live with that. When you selected a head, the preview of the commits was wrong since it always used the branch tip instead of the selected head. The pull request itself was created correctly, though, so I could live with that too. Now I can only choose the branch tip (head with highest revision number). That means that the only way to create multiple pull requests is to make them right after pushing each head: push first head, create first pull request, push second head, create second pull request, etc. @Brodie Rao and @Erik van Zijst : I guess you are working in this area after all? Great! Please try not to regress this further :-) @Martin Geisler Could be a regression. We're having a look! That regression should be fixed now. Sorry about that. Also, if it's any consolation, hopefully sometime next week we'll be putting out support for choosing different destination branch heads. It's not proper bookmark support, but it's one step closer. @Brodie Rao you mean source branch heads, right? Ideally both. I should be able to choose any changeset that isn't in the source repository and create a pull request from it, not just heads. The receiver should then be able to choose which changeset it get's merged into (destitination). @Brodie Rao thanks for the quick response, much appreciated! Thx @Brodie Rao. I can test this just fine now. Choose a head for a pull request (listed as default (<hash>)), create pull request. When I update that head, I can even update the pull request (popup telling me there is a new commit, update) like with "normal branches". This breaks when the commit I chose for the pull request is again included in two heads, since the pull request saves the hash, not the (name of the) bookmark. Saving the hash also means: Having pull requests for bookmarks that currently are not on (the tip of) a head is not supported. Example: I fork and get a default branch. Then I bookmark the head as "main" and commit stuff (moving the main bookmark along). Now I actually branch off a "feature1" bookmark and do some commits there. I still got 1 head only, but two "branches"/bookmarks. I would like to be able to open a pull request for "main", which currently isn't a head, but can be after updates. These two things are still missing in order to get a usable workflow for projects that chose mercurial as their SCM. I am always told "just use bookmarks, they are like git branches" and then I have to tell them that this just isn't supported on bitbucket in any way similar to how git branches are supported. Which is weird, since bitbucket started out with mercurial-only. You're totally right, Johannes. Right now when you one-click update a PR, we choose an arbitrary descendant of the current source commit that's on the same named branch. That can cause you to update to the wrong head if you've branched off from that source commit. You can work around this by updating the pull request by clicking "edit" and manually choosing the right head. Note that the support I'm adding for choosing destination branch heads will work the same way and have the same limitations. To give you some back story on this: We launched pull requests in June of 2011. At the time, Mercurial only very recently made bookmarks a built-in feature, and we (the Bitbucket team) weren't using them internally. We designed pull requests around making forks and doing PRs between them. You could pick any head as the source commit, and you could choose a destination branch the parent repo to merge it into. After we launched Git support, we updated pull requests so they tracked the source by branch and added support for intra-repo PRs. Since then, we haven't made any substantial changes to how PRs work. I think if bookmarks were more popular at the time we started the feature, we would've added support for them. But, at least for now, revisiting pull requests isn't on our immediate development road map. Also, I should mention that one technical aspect that's held this up (and made it a bigger undertaking than it probably should be) is that everywhere in our pull requests code we only look at the branches namespace. If we start looking at bookmarks as well, we'll need to have proper namespacing between the two. As a compromise, we could make it work in a way that if you have a bookmark that shadows a named branch, you can't use that named branch in a pull request. Either way, it's a significant undertaking. I can't make any promises as to when we'll add bookmark support, but I can say this: there's a Mercurial developer sprint coming up soon. I've been known to do a little Bitbucket development in between hacking on Hg when I'm at those. I might look into implementing it myself when I'm there (in addition to upgrading us to the latest version of Hg and enabling proper changeset evolution support). @Brodie Rao That's awesome news, thanks for the update! I'll probably not make it to the November 15th sprint, but I'll be happy to help out with beta testing when you have something to show the world. Great to hear. Absolutely 100% +1 on this! Seems like HG bookmarks are gaining popularity. I can only say for myself, that FUD around HG named branches gave it a bad reputation. The explanation that the only problem with them is the huge list of names in drop-down lists should be on the top page of Mercurial docs somewhere. Now it seems, that some how it is possible to use bookmarks for pull requests, but bookmark name is not always show, bookmarks are listed as branches in overview page, but not in branches page. You can'd create pull request from branch page, but it is possible to create pull request from bookmark from pull request form page (only bookmark name is not shown). Overall, actually I managed to create pull requests from bookmarks, but bookmark support looks like half done. Thanks to @sirex explanation (which I guess is a result from all contributors to this thread) I summarized the current practice in - feel free to improve if things get better. Issue #9209was marked as a duplicate of this issue. Any update on this? These things seem to have a horrible habit of going dead. I'm not too convinced that Mercurial workflow support is a big priority these days. @ruarc i don't think the lack of commitment from atlassian is mercurial-specific. they seem to have thrown the towel in re github competition, bitbucket.org has basic, easy to solve issues in the UI, and they haven't addressed those in many months at least. Bump It's been two years since this issue was opened... surely making such a change shouldn't be that much of a difficult change? Worth mentioning that @Sean Farley has added some support for opening pull requests from PR heads. It was always possible to do this, of course, but for a long time the bookmark name did not show up in the pull request dropdown menu. As of a few months ago, if a head in your repository has a bookmark on it, the bookmark name will show up in the pull request dropdown menu: In this case, I'm making a pull request from the "py3-notebooks" bookmark in my fork. @Nathan Goldbaum feel free to add this answer to I have 2 heads in the default branch, and they're both bookmarked. I get the impression from this thread that it's possible to create a pull request between the two, but it gives me the error Is it still not possible to implement this (simple and realistic) workflow with bitbucket? Issue #13090was marked as a duplicate of this issue. +1 It's not possible yet?... You have to create at least two bookmarks before it starts showing it in the pull request UI. I guess it works, but it would kind of be nice if it worked when there was only one too… I haven’t actually tried to finish making this PR, though… This also isn't working for me. I tried pushing up two bookmarks like Nathan said, but it doesn't show up in the drop down on the pull request page. yep, still not working. I've got two bookmarks in my fork, but nothing bookmark-y is showing up in the pull request creation UI. any chance of getting this working in time for the ticket's 4-year anniversary? Any chance Bitbucket will be turned into an open source product? This would be a pragmatic and expedient strategy for generating a fix for this issue. In fact, it's already is That is Bitbucket server (formally called stash) not Bitbucket cloud. I'm having the same issue as @Peter Hvidgaard. When I tried to create a pull request between 2 bookmarked branch heads on the same named branch it responds with "There are no changes to be pulled" even though the Diff says otherwise. It does work between a bookmarked branch head and a different named branch. So the only way I see of working around the problem is to create a named branch specifically to handle pull requests from bookmarked branch heads in another named branch...
https://bitbucket.org/site/master/issues/6705/cant-create-pull-request-from-hg-bookmark
CC-MAIN-2017-51
refinedweb
2,974
70.13
Details - Type: Bug - Status: Resolved - Priority: Major - Resolution: Won't Fix - Affects Version/s: None - Fix Version/s: None - Component/s: None - Labels:None Description The compareTo() method of org.apache.pig.data.DataByteArray does not compare items in lexicographic order. Actually, it takes into account the signum of the bytes that compose the DataByteArray. So, for example, 0xff compares to less than 0x00 Activity - All - Work Log - History - Activity - Transitions The test failures seem related to hudson, I have no failure locally. I think the patch is ready for review. The problem is we do not have unsigned byte in Java. Although DataByteArray is for semantic unknown type and the actual order does not matter, it is more natural to see 0xff > 0x00. I have two comments: 1. Can we measure if there is any noticeable performance downgrade due to two additional "and" operation? 2. Do we have somewhere else use this logic? It is important to keep them consistent. 1) I will write a simple program to measure the performance impact. 2) I think this has no correlation to other places, but I will check. Furthermore, this patch makes the ordering consistent with Hadoop's WritableComparator.compareBytes() (lexicographic order of binary data). I ran some tests. I see a ~1% decrease in performance overall. I looked around the codebase for references to the method, and it does not seem there is any place that relies on the specific ordering. Here is the code I used: import java.util.Random; public class TestSpeed { private static final int TIMES = (int) 10e6; private static final int NUM_ARRAYS = (int) 10e5; private static final int ARRAY_LENGTH = 50; private static int compareSigned(byte[] b1, byte[] b2) { int i; for (i = 0; i < b1.length; i++) { if (i >= b2.length) return 1; int a = b1[i]; int b = b2[i]; if (a < b) return -1; else if (a > b) return 1; } if (i < b2.length) return -1; return 0; } private static int compareUnsisgned(byte[] b1, byte[] b2) { int i; for (i = 0; i < b1.length; i++) { if (i >= b2.length) return 1; int a = b1[i] & 0xff; int b = b2[i] & 0xff; if (a < b) return -1; else if (a > b) return 1; } if (i < b2.length) return -1; return 0; } public static void main(String[] args) { long before, after; Random rand = new Random(123456789); byte[][] batch1 = new byte[NUM_ARRAYS][]; byte[][] batch2 = new byte[NUM_ARRAYS][]; for (int i = 0; i < NUM_ARRAYS; i++) { batch1[i] = new byte[ARRAY_LENGTH]; batch2[i] = new byte[ARRAY_LENGTH]; rand.nextBytes(batch1[i]); rand.nextBytes(batch2[i]); } before = System.currentTimeMillis(); for (int i = 0; i < TIMES; i++) for (int j = 0; j < ARRAY_LENGTH; j++) compareSigned(batch1[j], batch2[j]); after = System.currentTimeMillis(); System.out.println("Time for signed comparison (ms): " + (after - before)); before = System.currentTimeMillis(); for (int i = 0; i < TIMES; i++) for (int j = 0; j < ARRAY_LENGTH; j++) compareUnsisgned(batch1[j], batch2[j]); after = System.currentTimeMillis(); System.out.println("Time for UNsigned comparison (ms): " + (after - before)); } } The other concern is we only change DataByteArray not byte. So comparator for DataType.BYTEARRAY and DataType.BYTE is different. This will cause confusion. It is quite easy to fix DataType.compare() to keep into account the unsigned logic. But I am starting to feel that all of this is probably not worth the trouble. This would make DataType.compare() for Bytes different from Byte.compareTo(). We want to keep the comparators consistent. -1 overall. Here are the results of testing the latest attachment against trunk revision 958053. : Console output: This message is automatically generated.
https://issues.apache.org/jira/browse/PIG-1468
CC-MAIN-2017-09
refinedweb
590
58.99
The StyleInterface class provides an interface for Qtopia widget styles. More... #include <qtopia/styleinterface.h> List of all member functions. Styles may be added to Qtopia via plug-ins. In order to write a style plug-in you must create an interface to your QStyle derived class by deriving from the StyleInterface class and implementing the pure virtual functions. The name() function returns the name of the style. This will be displayed in the appearance settings dialog. Returns an instance of your style. You should always return the same style instance if this function is called multiple times. This file is part of the Qtopia platform, copyright © 1995-2005 Trolltech, all rights reserved.
http://doc.trolltech.com/qtopia2.2/html/styleinterface.html
crawl-001
refinedweb
113
67.76
.]]>.]]> Some of the recent developments in Hudson:. Jeff Black wrote a Google Desktop gadest for Hudson, which lets you see the status of builds in your desktop. This is neat, and the same idea should be useful for other gadget technologies..]]>: The optional bonus credit would be to support the remote container mode of Cargo. I'm sure it's not too hard to do that. This could be an excellent candidate for the GlassFish Award Program. See more about this issue in JIRA at CARGO-491. ]]> She just turned three, and she ... Hmm... where did I make a mistake?]]> When, ]]> First, apologies for a shameless plug. Ed Burns interviewed me when we were at Sun's internal conference (this was a rather nice place near Santa Cruz), and that interview became a part of his book "Secrets of the Rock Star Programmers: Riding the IT Crest." We talked about many different things, but I enjoyed the process. What's interesting is that sometimes I learn myself by what I'm saying to others, and this was no exception. He just gave me a copy when I met him at the server-side Java symposium, so I haven't read the whole thing yet, but I find the book enjoyable, partly because I recognize many names in the book as they are mainly from the Java community.]]> As Hudson improves its presence in Japan, I decided to resurrect my old blog in Japanese that I haven't touched for a long time. Many of the postings are the translation of the posts I made here, but there are some additional posts in there as replies to the reactions that my posting caused among Japanese bloggers.]]>. First the disclaimers: - I'm not a performance expert. - Don't try to take this too far, like optimizing your code against what you see here. The option in question is only available in debug builds of JDKs. You can download one from here. The binary I tested is JDK6 u10 b14. $ java -fullversion java full version "1.6.0_10-beta-fastdebug-b14" First, let's try something trivial: public class Main { public static void main(String[] args) { for(int i=0; i<100; i++) foo(); } private static void foo() { for(int i=0; i<100; i++) bar(); } private static void bar() { } } I run this like "java -XX:+PrintOptoAssembly -server -cp . Main". The -XX:+PrintOptoAssembly is the magic option, and with this option I get the following, which shows the code of the "foo" method: 000 B1: # N1 <- BLOCK HEAD IS JUNK Freq: 100 000 pushq rbp subq rsp, #16 # Create frame nop # nop for patch_verified_entry 006 addq rsp, 16 # Destroy frame popq rbp testl rax, [rip + #offset_to_poll_page] # Safepoint: poll for GC 011 ret <- BLOCK HEAD IS JUNK Freq: 78 000 # stack bang pushq rbp subq rsp, #80 # Create frame 00c # TLS is in R15 00c movq R8, [R15 + #120 (8-bit)] # ptr 010 movq R10, R8 # spill 013 addq R10, #280 # ptr 01a cmpq R10, [R15 + #136 (32-bit)] # raw ptr 021 jge,u B15 P=0.000100 C=-1.000000 021 027 B2: # B3 <- B1 Freq: 77.9922 027 movq [R15 + #120 (8-bit)], R10 # ptr 02b PREFETCHNTA [R10 + #256 (32-bit)] # Prefetch to non-temporal cache for write 033 movq [R8], 0x0000000000000001 # ptr 03a PREFETCHNTA [R10 + #320 (32-bit)] # Prefetch to non-temporal cache for write 042 movq RDI, R8 # spill 045 addq RDI, #24 # ptr 049 PREFETCHNTA [R10 + #384 (32-bit)] # Prefetch to non-temporal cache for write 051 movl RCX, #32 # long (unsigned 32-bit) 056 movq R10, precise klass [B: 0x00002aaaab076708:Constant:exact * # ptr 060 movq [R8 + #8 (8-bit)], R10 # ptr 064 movl [R8 + #16 (8-bit)], #256 # int 06c xorl rax, rax # ClearArray: rep stosq # Store rax to *rdi++ while rcx-- 071 071 B3: # B4 <- B16 B2 Freq: 78 071 071 # checkcastPP of R8 071 xorl R10, R10 # int 074 movl R9, #256 # int nop # 2 bytes pad for loops and calls 07c B4: # B17 B5 <- B3 B5 Loop: B4-B5 inner stride: not constant pre of N153 Freq: 19850.2 07c cmpl R10, #256 # unsigned 083 jge,u B17 P=0.000001 C=-1.000000 083 089 B5: # B4 B6 <- B4 Freq: 19850.2 089 movslq R11, R10 # i2l 08c movb [R8 + #24 + R11], #0 # byte 092 incl R10 # int 095 cmpl R10, #8 099 jlt,s B4 P=0.996072 C=22313.000000 099 09b B6: # B11 B7 <- B5 Freq: 77.9799 09b subl R9, R10 # int 09e andl R9, #-16 # int 0a2 addl R9, R10 # int 0a5 cmpl R10, R9 0a8 jge,s B11 P=0.500000 C=-1.000000 0a8 0aa B7: # B8 <- B6 Freq: 38.9899 0aa PXOR XMM0,XMM0 ! replicate8B nop # 2 bytes pad for loops and calls 0b0 B8: # B10 B9 <- B7 B9 Loop: B8-B9 inner stride: not constant main of N85 Freq: 9925.09 0b0 movslq R11, R10 # i2l 0b3 MOVQ [R8 + #24 + R11],XMM0 ! packed8B 0ba movl R11, R10 # spill 0bd addl R11, #16 # int 0c1 movslq R10, R10 # i2l 0c4 MOVQ [R8 + #32 + R10],XMM0 ! packed8B 0cb cmpl R11, R9 0ce jge,s B10 P=0.003928 C=22313.000000 0ce 0d0 B9: # B8 <- B8 Freq: 9886.1 0d0 movl R10, R11 # spill 0d3 jmp,s B8 0d3 0d5 B10: # B11 <- B8 Freq: 38.9899 0d5 movl R10, R11 # spill 0d5 0d8 B11: # B14 B12 <- B6 B10 Freq: 77.9799 0d8 cmpl R10, #256 0df jge,s B14 P=0.500000 C=-1.000000 nop # 3 bytes pad for loops and calls 0e4 B12: # B17 B13 <- B11 B13 Loop: B12-B13 inner stride: not constant post of N153 Freq: 9922.54 0e4 cmpl R10, #256 # unsigned 0eb jge,us B17 P=0.000001 C=-1.000000 0eb 0ed B13: # B12 B14 <- B12 Freq: 9922.53 0ed movslq R11, R10 # i2l 0f0 movb [R8 + #24 + R11], #0 # byte 0f6 incl R10 # int 0f9 cmpl R10, #256 100 jlt,s B12 P=0.996072 C=22313.000000 100 102 B14: # N1 <- B13 B11 Freq: 77.9698 102 movq RAX, R8 # spill 105 addq rsp, 80 # Destroy frame popq rbp testl rax, [rip + #offset_to_poll_page] # Safepoint: poll for GC 110 ret 110 111 B15: # B18 B16 <- B1 Freq: 0.00780129 111 movq RSI, precise klass [B: 0x00002aaaab076708:Constant:exact * # ptr 11b movl RDX, #256 # int 120 nop # 3 bytes pad for loops and calls 123 call,static wrapper for: _new_array_Java # Main::foo @ bci:3 L[0]=_ L[1]=_ # 128 128 B16: # B3 <- B15 Freq: 0.00780114 # Block is sole successor of call 128 movq R8, RAX # spill 12b jmp B3 12b 130 B17: # N1 <- B12 B4 Freq: 1e-06 130 movl RSI, #-28 # int 135 movq RBP, R8 # spill 138 movl [rsp + #0], R10 # spill 13c nop # 3 bytes pad for loops and calls 13f call,static wrapper for: uncommon_trap(reason='range_check' action='make_not_entrant') # Main::foo @ bci:17 L[0]=RBP L[1]=rsp + #0 STK[0]=RBP STK[1]=rsp + #0 STK[2]=#0 # AllocatedObj(0x0000000040c31880) 144 int3 # ShouldNotReachHere 144 151 B18: # N1 <- B15 Freq: 7.80129e-08 151 # exception oop is in rax; no code emitted 151 movq RSI, RAX # spill 154 addq rsp, 80 # Destroy frame popq rbp 159 jmp rethrow_stub zero computation. <- BLOCK HEAD IS JUNK Freq: 20168 000 # stack bang pushq rbp subq rsp, #80 # Create frame 00c # TLS is in R15 00c movq RAX, [R15 + #120 (8-bit)] # ptr 010 movq R10, RAX # spill 013 addq R10, #40 # ptr 017 # TLS is in R15 017 cmpq R10, [R15 + #136 (32-bit)] # raw ptr 01e jge,u B10 P=0.000100 C=-1.000000 01e 024 B2: # B3 <- B1 Freq: 20166 024 # TLS is in R15 024 movq [R15 + #120 (8-bit)], R10 # ptr 028 PREFETCHNTA [R10 + #256 (32-bit)] # Prefetch to non-temporal cache for write 030 movq R10, precise klass java/util/Vector: 0x00002aaaf2649f38:Constant:exact * # ptr 03a movq R11, [R10 + #176 (32-bit)] # ptr 041 movq [RAX], R11 # ptr 044 movq [RAX + #8 (8-bit)], R10 # ptr 048 movq [RAX + #16 (8-bit)], #0 # long 050 movq [RAX + #24 (8-bit)], #0 # long 058 movq [RAX + #32 (8-bit)], #0 # long 058 060 B3: # B12 B4 <- B11 B2 Freq: 20168 060 060 movq RBP, RAX # spill 063 # checkcastPP of RBP 063 # TLS is in R15 063 movq R11, [R15 + #120 (8-bit)] # ptr 067 movq R10, R11 # spill 06a addq R10, #104 # ptr 06e # TLS is in R15 06e cmpq R10, [R15 + #136 (32-bit)] # raw ptr 075 jge,u B12 P=0.000100 C=-1.000000 075 07b B4: # B5 <- B3 Freq: 20166 07b # TLS is in R15 07b movq [R15 + #120 (8-bit)], R10 # ptr 07f PREFETCHNTA [R10 + #256 (32-bit)] # Prefetch to non-temporal cache for write 087 movq [R11], 0x0000000000000001 # ptr 08e PREFETCHNTA [R10 + #320 (32-bit)] # Prefetch to non-temporal cache for write 096 movq RDI, R11 # spill 099 addq RDI, #24 # ptr 09d PREFETCHNTA [R10 + #384 (32-bit)] # Prefetch to non-temporal cache for write 0a5 movq R10, precise klass [Ljava/lang/Object;: 0x00002aaaf264e928:Constant:exact * # ptr 0af movq [R11 + #8 (8-bit)], R10 # ptr 0b3 movl [R11 + #16 (8-bit)], #10 # int 0bb movl RCX, #10 # long (unsigned 32-bit) 0c0 xorl rax, rax # ClearArray: rep stosq # Store rax to *rdi++ while rcx-- 0c5 0c5 B5: # B16 B6 <- B13 B4 Freq: 20168 0c5 0c5 # checkcastPP of R11 0c5 movq [RBP + #32 (8-bit)], R11 # ptr ! Field java/util/Vector.elementData 0c9 movq R10, RBP # ptr -> <- B5 Freq: 20167.6 # Block is sole successor of call 0f4 movq RDX, java/lang/String:exact * # ptr 0fe movq RSI, RBP # spill 101 nop # 2 bytes pad for loops and calls 103 call,static java.util.Vector::add # Main::foo @ bci:18 L[0]=RBP # AllocatedObj(0x0000000040b30680) 108 108 B7: # B14 B8 <- B6 Freq: 20167.2 # Block is sole successor of call 108 movq RDX, java/lang/String:exact * # ptr 112 movq RSI, RBP # spill 115 nop # 2 bytes pad for loops and calls 117 call,static java.util.Vector::add # Main::foo @ bci:25 L[0]=_ # 11c 11c B8: # N1 <- B7 Freq: 20166.8 # Block is sole successor of call 11c addq rsp, 80 # Destroy frame popq rbp testl rax, [rip + #offset_to_poll_page] # Safepoint: poll for GC 127 ret (slow path omitted) The allocation of a Vector object (00c-058) is almost identical to the array allocation code we've seen before (except the additional field initializations at 048-058.) The array allocation for Vector.elementData follows (060-0C0.) Note that the Vector construct object never escapes the stack. I thought perhaps that's because Vector.add is too complex to be inlined, so I tried the following code, in the hope of seeing the lock elision: This produced the following code:This produced the following code: private static void foo() { Foo foo = new Foo(); foo.inc(); foo.inc(); foo.inc(); } private static final class Foo { int i=0; public synchronized void inc() { i++; } } 000 B1: # B6 B2 <- BLOCK HEAD IS JUNK Freq: 19972 000 # stack bang pushq rbp subq rsp, #80 # Create frame 00c # TLS is in R15 00c movq RBP, [R15 + #120 (8-bit)] # ptr 010 movq R10, RBP # spill 013 addq R10, #24 # ptr 017 cmpq R10, [R15 + #136 (32-bit)] # raw ptr 01e jge,u B6 P=0.000100 C=-1.000000 01e 024 B2: # B3 <- B1 Freq: 19970 024 movq [R15 + #120 (8-bit)], R10 # ptr 028 PREFETCHNTA [R10 + #256 (32-bit)] # Prefetch to non-temporal cache for write 030 movq R10, precise klass Main$Foo: 0x00002aaaf2646e58:Constant:exact * # ptr 03a movq R11, [R10 + #176 (32-bit)] # ptr 041 movq [RBP], R11 # ptr 045 movq [RBP + #8 (8-bit)], R10 # ptr 049 movq [RBP + #16 (8-bit)], #0 # long 049 051 B3: # B8 B4 <- B7 B2 Freq: 19972 051 051 # checkcastPP of RBP 051 leaq R11, [rsp + #64] # box lock 056 fastlock RBP,R11,RAX,R10 135 jne B8 P=0.000001 C=-1.000000 135 13b B4: # B9 B5 <- B8 B3 Freq: 19972 13b MEMBAR-acquire (prior CMPXCHG in FastLock so empty encoding) 13b movl R11, [RBP + #16 (8-bit)] # int ! Field Main$Foo.i 13f incl R11 # int 142 movl [RBP + #16 (8-bit)], R11 # int ! Field Main$Foo.i 146 MEMBAR-release 146 MEMBAR-acquire 146 movl R11, [RBP + #16 (8-bit)] # int ! Field Main$Foo.i 14a incl R11 # int 14d movl [RBP + #16 (8-bit)], R11 # int ! Field Main$Foo.i 151 MEMBAR-release 151 MEMBAR-acquire 151 movl R11, [RBP + #16 (8-bit)] # int ! Field Main$Foo.i 155 incl R11 # int 158 movl [RBP + #16 (8-bit)], R11 # int ! Field Main$Foo.i 15c MEMBAR-release (a FastUnlock follows so empty encoding) 15c leaq RAX, [rsp + #64] # box lock 161 fastunlock RBP, RAX, R10 218 jne,s B9 P=0.000001 C=-1.000000 218 21a B5: # N1 <- B9 B4 Freq: 19972 21a addq rsp, 80 # Destroy frame popq rbp testl rax, [rip + #offset_to_poll_page] # Safepoint: poll for GC 225 ret (slow path omitted) <- BLOCK HEAD IS JUNK Freq: 27066 000 # stack bang pushq rbp subq rsp, #16 # Create frame 00c # TLS is in R15 00c movq RAX, [R15 + #120 (8-bit)] # ptr 010 movq R10, RAX # spill 013 addq R10, #24 # ptr 017 cmpq R10, [R15 + #136 (32-bit)] # raw ptr 01e jge,us B4 P=0.000100 C=-1.000000 01e 020 B2: # B3 <- B1 Freq: 27063.3 020 movq [R15 + #120 (8-bit)], R10 # ptr 024 PREFETCHNTA [R10 + #256 (32-bit)] # Prefetch to non-temporal cache for write 02c movq R10, precise klass Main$Foo: 0x00002aaaf25dfbc8:Constant:exact * # ptr 036 movq R11, [R10 + #176 (32-bit)] # ptr 03d movq [RAX], R11 # ptr 040 movq [RAX + #8 (8-bit)], R10 # ptr 040 044 B3: # N1 <- B5 B2 Freq: 27066 044 movq [RAX + #16 (8-bit)], #3 # long 04c 04c addq rsp, 16 # Destroy frame popq rbp testl rax, [rip + #offset_to_poll_page] # Safepoint: poll for GC 057 ret (slow path omitted).]]>! ]]> This...)]]> A.
http://weblogs.java.net/blog/kohsuke/atom.xml
crawl-001
refinedweb
2,328
78.01
10 April 2012 23:09 [Source: ICIS news] HOUSTON (ICIS)--US April methyl ethyl ketone (MEK) contract values settled flat from the previous month amid expectations of increased competition from ?xml:namespace> The rollover holds MEK contract values at $1.02-1.06/lb ($2,249-2,337/tonne, €1,709-1,776/tonne), as assessed by ICIS. Buyers suggested no April contract price increases were proposed because although demand is “holding its own,” supply is ample. “There’s plenty of demand, and there’s plenty of supply,” a buyer said. Although producers did not comment on the rollovers, buyers suggested that with domestic supply continuing to improve, “no one wants to heighten interest in imports”. Sources primarily cited the imminent restart of Contract values for March gained 9 cents/lb on higher production costs amid snug supply, but business has slowed and supply is accessible - especially cheaper imports, most sources said. Feedstock butane at Mont Belvieu, US March ethylene contracts for March were settling initially at 55.75 cents/lb during the week, rising by 1.75 cents/lb from February as a result of higher spot prices last month. US MEK suppliers include ExxonMobil, Shell Chemical and Sas
http://www.icis.com/Articles/2012/04/10/9548906/us-april-mek-contracts-roll-over-as-sellers-anticipate-more.html
CC-MAIN-2015-11
refinedweb
200
55.03
Alex Chiang wrote: > A recent patch titled: > > CRED: Separate task security context from task_struct > > removed task security context from task_struct, but did not > update all locations to use the new struct cred that was > introduced. > > The change to task_struct broke perfmon and ia32 syscalls on > ia64. This patch fixes the build. I've submitted a patch to fix this. > All things considered, I'd prefer to see this patch folded into > 7931c65268777ed10cab22486de149d742a1f269 so we can keep > bisectability. Would that be possible, given that these changes > are "only" in linux-next and haven't hit Linus's tree yet? Probably. I'll have to talk to Stephen about how to do this. I can't maintain my patches on top of linux-next now:-/ > Also, I'm not exactly sure why wrappers were provided for > task_gid, but then later removed. Additionally, I wasn't sure why > no wrapper was provided for task_suid and friends. But I admit > that I didn't read the patch series in depth; only enough to fix > the build. Generally, accesses to task->gid are accompanied by accesses to task->uid and/or task->groups, in which case using multiple wrappers in series introduces excess locking and superfluous memory barriers. To access task->gid, one must take the RCU read lock and then use rcu_dereference(). However, I can't use the cred struct until the patch in which it is introduced. The wrappers, however, allow me to grep for things I've missed, and thus make it easier to do things in stages. Your patch also has a couple of issues: > + get_group_info(current->cred->group_info); The call to get_group_info() is not necessary. Only current may change its own groups. > + || (uid != task->cred->suid) > + || (gid != task->cred->egid) > + || (gid != task->cred->sgid) > + || (gid != task->cred->gid)) This is incorrect. You must hold the RCU read lock whilst you make this access, and you must pass task->cred through rcu_dereference(), or better still, use __task_cred(task) to get at it. My patch is below. Note that there is a problem with it, presumably something to do with GIT's merging (the ad1848 files being deleted). David --- Fix the IA64 arch's use of COW credentials. Signed-off-by: David Howells --- arch/ia64/ia32/sys_ia32.c | 7 +++---- arch/ia64/kernel/perfmon.c | 32 ++++++++++++++++++++------------ include/sound/ad1848.h | 0 sound/isa/ad1848/ad1848_lib.c | 0 4 files changed, 23 insertions(+), 16 deletions(-) delete mode 100644 include/sound/ad1848.h delete mode 100644 sound/isa/ad1848/ad1848_lib.c diff --git a/arch/ia64/ia32/sys_ia32.c b/arch/ia64/ia32/sys_ia32.c index 465116a..7f0704f 100644 --- a/arch/ia64/ia32/sys_ia32.c +++ b/arch/ia64/ia32/sys_ia32.c @@ -2084,25 +2084,24 @@ groups16_from_user(struct group_info *group_info, short __user *grouplist) asmlinkage long sys32_getgroups16 (int gidsetsize, short __user *grouplist) { + const struct cred *cred = current_cred(); int i; if (gidsetsize < 0) return -EINVAL; - get_group_info(current->group_info); - i = current->group_info->ngroups; + i = cred->group_info->ngroups; if (gidsetsize) { if (i > gidsetsize) { i = -EINVAL; goto out; } - if (groups16_to_user(grouplist, current->group_info)) { + if (groups16_to_user(grouplist, cred->group_info)) { i = -EFAULT; goto out; } } out: - put_group_info(current->group_info); return i; } diff --git a/arch/ia64/kernel/perfmon.c b/arch/ia64/kernel/perfmon.c index ffe6de0..a1aead7 100644 --- a/arch/ia64/kernel/perfmon.c +++ b/arch/ia64/kernel/perfmon.c @@ -2403,25 +2403,33 @@ error_kmem: static int pfm_bad_permissions(struct task_struct *task) { + const struct cred *tcred; uid_t uid = current_uid(); gid_t gid = current_gid(); + int ret; + + rcu_read_lock(); + tcred = __task_cred(task); /* inspired by ptrace_attach() */ DPRINT(("cur: uid=%d gid=%d task: euid=%d suid=%d uid=%d egid=%d sgid=%d\n", uid, gid, - task->euid, - task->suid, - task->uid, - task->egid, - task->sgid)); - - return (uid != task->euid) - || (uid != task->suid) - || (uid != task->uid) - || (gid != task->egid) - || (gid != task->sgid) - || (gid != task->gid)) && !capable(CAP_SYS_PTRACE); + tcred->euid, + tcred->suid, + tcred->uid, + tcred->egid, + tcred->sgid)); + + ret = ((uid != tcred->euid) + || (uid != tcred->suid) + || (uid != tcred->uid) + || (gid != tcred->egid) + || (gid != tcred->sgid) + || (gid != tcred->gid)) && !capable(CAP_SYS_PTRACE); + + rcu_read_unlock(); + return ret; } static int diff --git a/include/sound/ad1848.h b/include/sound/ad1848.h deleted file mode 100644 index e69de29..0000000 diff --git a/sound/isa/ad1848/ad1848_lib.c b/sound/isa/ad1848/ad1848_lib.c deleted file mode 100644 index e69de29..0000000 -- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.kernel.org More majordomo info at Please read the FAQ at
http://fixunix.com/kernel/521009-%5Bpatch%5D-cred-fixup-credentials-build-breakage.html
CC-MAIN-2015-06
refinedweb
735
57.57
User talk:ColbertFan "Anonymous User" (you can't even post in your own real name), your incoherent comments are getting tiresome. I looked at your contributions and I think several of your postings are an example of liberal deceit, so it's painfully obvious that you're against Conservapedia. And you persist in denying the obvious truth that classroom prayer reduces autism. The answer to your silly question is this: the photo of a pompous Obama standing in front of teleprompters in an elementary school classroom is priceless, and Jay Leno's criticism is right on target. Wikipedia may be a better place for you to deny that fact, or to persist in ignoring the truth. Read my posting below and contribute to this encyclopedia, or go rant somewhere else.--Andy Schlafly 02:01, 27 November 2021 (UTC) ТyTalk. 19:44, 4 March 2011 (UTC) Namespaces[edit] There is no "vote" namespace, so pages prefixed "vote" will appear in the mainspace. Cheers! Blue Talk 22:09, 4 March 2011 (UTC) - Okay, knowing is half the battle. GI-JOE®! Colbert|FanThis sig is so outdated 22:12, 4 March 2011 (UTC) Sir![edit] It is my great pleasure to inform you that you have been demoted to the lowly rank of sysop. Here's your guide, feel free to ask about anything! Blue Talk - Thanks, I lost it via the Block War of 2011. I will only ask for it back AFTER the Block War of 2011, Thanks :) DickTurpis (talk) 00:01, 11 March 2011 (UTC) - Okay, I want my sysop status back! Also, great video. I think who ever made it was a pacifist, but still it was funny. Colbert|FanThis sig is so outdated 03:18, 11 March 2011 (UTC) - And the problem with being a pacifist is? Totnesmartin (talk) 18:13, 14 March 2011 (UTC) - Nothing, I just don't agree with them. However, one of my friends is a pacifist. I think, however, that the only excuse for violence to stop other peoples violence. Colbert|FanThis sig is so outdated 02:41, 15 March 2011 (UTC) - EXTERMINATE PACIFISTS. EXTERMINATE 02:43, 15 March 2011 (UTC) - HUG A DALEK TODAY Totnesmartin (talk) 10:06, 15 March 2011 (UTC) - I hugged a dalek and I died. Hey, Dalek want to join the Dead Club(aka heaven)? You are pacifist and thus you want to kill yourself(because a pacifist is someone who wants to kill him or herself for being a pacifist, right?). Colbert|FanThis sig is so outdated 18:22, 15 March 2011 (UTC) - [Edit↑] - [Fossil record↑] Contents Vandalism. Colors Now I don't have to always have to google something like "red color hex". Thanks, I will bookmark it. No offence... No offence... but an organised block war just seems a bit lame :\ Also, the Confederate States of America were racist. If you'd like to argue otherwise, please begin by refuting Alexander H. Stephens' length speech at the founding of the Confederation: I were taking part in the founding of a new state, which I believed not to be racist, and the new Vice President spoke these words, not only would I be disgusted, but I'd probably have heckled him. In fact, the enormous non-racist crowd, from the population of this non-racist state, would probably have all heckled him. I never said the PEOPLE weren't racist, also an organised block war is better than organised religion. So: - You accept that the Vice President of the CSA said that the state was founded on the principle that one race is superior to another. - You do not deny racism among the population of the CSA? - You accept that the CSA would rather fight a bloody war than give up slavery; but claim that they were not racist? By these standards, what possibly could be a racist state? Could a racist state exist, if this were not one? Surely, Apartheid South Africa was racist, with whites legally seen as superior to blacks? Well what if the whites OWNED the blacks? Would that be racist? How is that a nation state (the CSA) the founding documents of which entrench the right of members of one racial group to own members of another (and not vice versa) can be viewed as anything other than racist? Our friend here appears to be under the delusion that the CSA was founded on the noble philosophical principle of states' rights, which was of course completely separate from slavery and racism. "which was of course completely separate from slavery and racism." --Blue Talk I didn't say it was SEPERATE from slavery and racism, what I mean by "Nor do I believe the Confederacy was racist" means that I don't believe that is mainly founded on slavery. I know that it WAS a racist state, however, so was the US when it was founded(most of the founding fathers owned slaves) and we don't say the US was founded on slavery. Putting people to high standards and then saying to supporters of a view "SEE!" is a bad arguing method. Well if you know the Confederacy was a racist state, why do you have Nor do I think the Confederacy was racist. on your userpage? Updated to say, don't you think you should qualify Nor do I think the Confederacy was racist. to represent what you really think? Please, since you've spent so much effort describing what you don't think, tell us clearly what you do think. - The Confederacy was founded mainly on states' rights - Abe didn't care about slavery as much as people think he did - The Union at that time could be easily compared to the Great Britain under King George III with regards to secession movements. Category:You Categories affect the rest of the wiki. Nonetheless, it is good to have a spare CUR. I challenge you to debate me on the subject of cats. You mean categories. I just want to have a category for my userpage and subpages of my userpage. Colbert|FanWhat is a sig. 20:30, 13 March 2011 (UTC) I meant cats. It was a reference to CUR. He and I debated cats. It was a golden age. Okay, cats are better than dogs. Dogs bark a lot, trust me I know. Kitties are cute and cuddly and don't bark! Colbert|FanI know what I don't know 20:34, 13 March 2011 (UTC) Dogs are better than cats. Dogs never bark. Kitties are incredibly dangerous (like sharks). I hate you. This is just like the old days. I "hate" you too, isn't hating people fun and moral and has NO problems. PROVE ME WRONG! Colbert|FanBritons are people too! 01:12, 14 March 2011 (UTC) this is who CUR was Totnesmartin (talk) 20:19, 13 March 2011 (UTC) Trying too hard For what, what goal how am I doing it? Why are you talking to be about it without good information? You are trying too hard to fit in, and this irritates people. Take it slow, let the community grow on you. And for the record, block wars are haphazard, spur of the moment things. I am not trying, I am just trying to have a chat maybe drink a root beers along the way. Whatever, just remember that the stuff in the glass bottles is way better that the stuff in a can. Cheers. It is possible to fit in? Thorvelden (talk) Lots of things. I need help NOT going to college(I am in my early teens, by the way). That you were in your early teens was readily apparent. As to not going to college, my best advice would be to not apply to college, or draw penises all over the applications or something. "That you were in your early teens was readily apparent."-Blue What about me gave that away, my newbieness. That has nothing to do with my age. The way you write. You could have been an octogenarian or a tween, and statistically it was probably the latter. First, I researched tween and found out I was wrong. I thought I was an early teen, but I am tween! Sorry about that :) Now, tween powers activate! Oh, come now; when today's octogenarians were in school the academic standards were still such that students were taught some semblance of good grammar. We are on RW 3.0. Rule of thumb, don't edit debates that haven't been active for a while. Cheers. Also, you can edit pages if you feel like it. This is a wiki, if your edits are crap I have teh magic rollback button.
https://rationalwiki.org/wiki/User_talk:ColbertFan
CC-MAIN-2021-49
refinedweb
1,450
74.08
Please confirm that you want to add Windows Service Programming in C# .Net For Coders & Students to your Wishlist. This course teaches you how to create Windows Service which are a key component of Windows operating system. The the final section we are going to create an admin application for a Windows Service. This application will have the ability to start/stop a service and get service status as well.. Sign up and I will see you inside! Hello and welcome to my course... creating Windows Services using C# .Net. In this course... you will learn a very useful skill that is creating and debugging Windows Service applications. I am Naeem Akram, I have done Windows Service programming as a full time job for several years. My.exe section 5 we are going to create an admin application for a Windows Service. This application will have the ability to start/stop a service and change the configuration file of the service. Section 6 was added by popular demand. In this section I will show you how to create a setup installer for your Windows Service. I am going to use Inno Setup for this purpose.. So now I am going to explain some very important concepts about Windows services. First, open the services control manager SCM.(+pan into Run and show hint on screen but don’t go on with narration). First of all, the columns name and description are self explanatory. The column status shows the current status of the service, which might be any of the those shown on the screen. Stopped Started Paused Pending Start Pending Stop Pending Pause The column Startup Type tells whether a service is started automatically by Windows or it is stopped, it is possible to disable a service as well and in that case this column will contain the word “Disabled”. In short the four possible values of a service start up type are shown on screen. That is Manual Automatic Disabled Automatic(Delayed Start) The last column “Log On As” shows the username of the Windows account a particular service is going to use. Possible values of this field are: Local System Network Service Local Service Specific User More information can be found on the link mentioned in the description of this lecture. Having a specific set of credentials to logon makes it possible for Windows Services to start before a human user logs-in and stay operational even when a human user is gone. Among these types of login credentials, LocalService is the one with the fewest powers. It’s a non-privileged user on the local machine. LocalSystem on the other hand is the most powerful type of user and it can do almost anything you want the the machine. Third type NetworkService is slightly more powerful than LocalService, and it can interact with various network services. Details are not relevant from the perspective of this course so I would prefer not to stress too much on the definition. We can perform various service operations by clicking on a service entry in SCM and going to the Action menu. There are some shortcuts on the top left as well. It is also possible to right click a service and select ‘Properties’ from the dropdown. The properties dialog not only allows you to start/stop/pause/resume a service, it also shows you the file path from where a specific service is running. In this video, I will show you some major differences between Windows Service executables and simple exe files. Let’s open a console application project First of all I will press ‘Control+F5’. IMPORTANT: The source code for section 1 can be downloaded here. In this video, I will show you some major differences between Windows Service executable and simple exe files. Let’s open a console application project First of all I will press ‘Control + F5’ You. This quiz is aimed at fortifying the basics of Windows Service programming which you have learned in general. It’s time! it’s time to create your first Windows Service project cadet and fire up Visual Studio Hah ha ha ha… OK… <Launch Visual Studio, show splash for split second> Visual Studio twenty fifteen Enterprise is up, I’ll click ‘File’ menu and select ‘New’, and then ‘Project’ Expand Visual C sharp Expand Windows Click ‘Classic Desktop’ Look for Windows Service and select it Name of solution will be ‘Udemy Windows Service’ When we create a new Windows Service project, Service1.cs file is opened by default We can see that this file is opened in design view The code of our Windows Service is going to reside inside this file First of all, I will like to change the name of this file In solution explorer, right click the file ‘Service1.cs’ Select menu option ‘Rename’ I will change the name to UdemyWindowsService.cs VS will ask if you want to rename all references of this service, click Yes There is another file ‘Program.cs’ in the solution explorer files hierarchy, don’t worry about it. Double click on UdemyWindowsService.cs Now click inside the designer area On the properties panel, change property ‘ServiceName’ to ‘Udemy Windows Service’ Build the project Ctrl+Shift+B I hope you remember that we can’t run a Windows Service without installing it In the next video, I will tell you how to solve this problem. I’ve opened the Windows Service project which we created in the last lecture The file UdemyWindowsService.cs is opened in design view If you have moved to code view somehow, just goto ‘View’ menu and select ‘Designer’ Now right click in the designer area Select the menu item ‘Add Installer’ The file ‘ProjectInstaller.cs’ will open in designer view Your Windows Service is almost ready for the action We need to change a few properties First of all, right click click ‘serviceProcessInstaller1’ and select menu item ‘Properties’. Change the property ‘User’ to LocalSystemAccount Now right click ‘serviceInstaller1’ and select menu item ‘Properties’. Set the property ‘Display Name’ to ‘Udemy Demo Service’ Set the property ‘Description’ to something like ‘My hello world Windows Service’ Now go back to ‘UdemyWindowsService.cs’ file in design view Right click designer area and select ‘Properties’ I am about to tell you a very small but important thing. The property ‘Service Name’ of your service must have the same value as the serviceInstaller.ServiceName If this value is different, your service will not work. Now let’s go to the next lecture and prepare to run our service IMPORTANT: Download source code here. I’ve opened the Windows Service project I am repeating this step on the start of every video intentionally, to help people who are not watching the course in one go The file ‘UdemyWindowsService.cs’ is opened in designer view Right click and select ‘View Code’ from the options We can see a partial class which is derived from ServiceBase After the constructor, this class contains overrided methods ‘OnStart’ and ‘OnStop’ The method OnStart is called by the system when the service is started, either by Windows automatically or by a user clicking Start in Service Control Manager The other method OnStop is called by the system before stopping the service. Click inside the method OnStart and write following code EventLog dot WriteEntry. “Udemy Windows Service by naeem is starting.” Comma, EventLogEntryType dot Information. Copy the same line of code over to OnStop method. By default, every Windows Service is capable of writing events to the event log given that it is being run with appropriate permissions. Now build the service In the next lecture, we will build your service and run it. I have opened the Windows Service solution which we have created and configured in this section so far Build the project Open Solution Explorer Select project ‘UdemyWindowsService’ Click ‘Show All Files’ icon Expand the ‘bin’ folder Right click the ‘Debug’ folder Select option ‘Open Folder in File Explorer’ Look at the contents of the folder You see an application exe file ‘UdemyWindowsService’ Now click ‘Start Menu’ and type ‘Developer Command Prompt’ For older versions of Visual Studio you can use ‘Visual Studio Command Prompt’ Open the developer command prompt Now type installutil dot exe space minus i space Go back to file explorer Press shift key and right click the UdemyWindowsService.exe file Click menu option ‘Copy as path’ Now go back to the developer command prompt Right click the top of the window and from drop down menu select option ‘Paste’ Press enter key. The command prompt says ‘The transacted install has completed’ this means our service is installed! (keep command line on screen)Now let’s open service control manager Look for ‘Udemy Demo Service’ in the list of services Click the service And now click ‘Start’ button The status of the service will change to ‘Started’ The operations buttons on top left will also change from ‘Start’ to ‘Stop this service’ and ‘Restart the service’ Click ‘Stop’ link. The service will stop. The status and operation buttons will change accordingly. (close everything else but SCM)Let us take a quick look into Windows Event Log I will click start button and type Event Viewer and open it The event viewer can take a few minutes to load the data Let’s Expand the node ‘Windows Logs’ I’ll Click the sub-item ‘Application’ I will Look for ‘Udemy Windows Service’ in the ‘Source’ column When I click on an item in the list, the lower half of the window shows some stuff in ‘General’ and ‘Details’ tab The General tab will have the message your application would’ve written to the Windows event logs. Now click on the ‘System’ node under ‘Windows Logs’ If you didn’t install this service a long long while ago, you will be able to find an event related to service install near the top of list view. In our case, I’ve found the event related to service installation. It says ‘A service was installed in the system.‘ Removing or Uninstalling a Windows Service is a simple operation which can be performed using the same .Net framework utility which we used to install a service. This short document shows you how do just that using InstallUtil -u command. How well do you know your Windows Service code? I will open the Windows Service project which we created in last section The source files can be downloaded from the downloads section of all videos of section two, three, four, or five The sources are available on GitHub too, a link is present in the course & video description. Before we start debugging Let us add a few lines of code in the ‘OnStart’ method. I’ve added an integer variable i with initial value zero and a do while loop after it. The loop is simply printing the integer to debug console and incrementing it. In order to start debugging, we need to add some code which will launch the debugger on run time. Let’s do it right on top of the OnStart method. System dot Diagnostics dot Debugger dot Launch Before starting the build, make sure that debug configuration is selected on top Now let’s build the service If you have already installed the service during previous videos, go to service control manager and make sure it is stopped. Otherwise, the build process will fail. Also, you don’t need to do run InstallUtil again if it’s already there. The reason is that we installed the service straight from the debug folder and building the project again will simply replace the old files. If you haven’t installed the service already, take a look at video four of section two and install the service. Open service control manager, click ‘Udemy Windows Service’ and click the ‘Start’ link Service start progress dialog shows up Another dialog with a list of visual studio versions and your open Windows service project has shown up Click your already opened Windows Service project from the list and click Yes You see that the control is transferred to the point in your code where you had launched the debugger. Now you can continue debugging normally, let’s press F ten. Let’s switch back to Service Control Manager for a second You see the start service dialog is still up on screen Let’s switch back to your service code Make sure that the output console is visible on the bottom of screen, if it is not there already go to ‘Debug’ menu, ‘Window’, and then select ‘Output’. Let’s pin it permanently and clear it as well. By pressing F ten key a few times you will hit Write Line statement inside the loop. in the Output window below, you can see that the string “Value of i is colon zero” Similarly, we can add a watch to see the value of variable i Right click i and select ‘Add a watch’ from the drop down The value of variable i can be seen in the Watch window below The value can be seen by hovering over the variable i I will press F five a few more times to see what’s going on Now press F five Stop debugger by clicking the stop button on top, you may press Shift + F5 Switch back to ‘Service Control Manager’, most probably a dialog will be on screen already screaming that the service startup failed. Don’t bother it and press OK Click your Windows Service and press F five to refresh SCM The service is now showing as started. Once you’ve gone through the video, you may remove the Debugger dot launch call In the next video, I will introduce you to Log 4 Net library. Log 4 Net is used to generate rolling log files that help immensely in diagnosing problems in production environments. In order to use this technique, we need to run as administrator both Visual Studio and Service Control Manager. Let me do it [Action – Click Start, right click VS, select “Run as Admin”] [Action – Minimize “VS”] [Action – Click Start, type “Services”, right click, select “Run as Admin”] [Action – Go back to “VS”] I am going to place a break point in service “Stop” method. Now I will go to the service control manager and start our Udemy Windows Service The service has started, now go back to Visual Studio Click “Debug” menu and select “Attach to Process” On the dialog box, click a list item in the column “Available Process” and press U “UdemyWindowsService.exe” will be highlighted I have expanded the “Process” column so that full process name will be visible You can see there’s a process “UdemyWindowsService.vshost.exe” right underneath our service process Don’t let that one confuse you So, I’ve selected “UdemyWindowsService.exe” I will click the button “Attach” [PAUSE] Once the debugger is attached, you’ll see that Visual Studio UI will change to debug mode Now I will go back to the service control manager and stop the service, the break-point in “Stop” method should be hit. There you go It is possible to use this technique in a variety of scenarios. I suggest you keep this technique in mind when watching the videos in “practical usages” section which comes next This slightly lengthy lecture shows you how to add Log4Net library in your Windows service project, how to configure it, and how to use it in code. In just seven minutes, we are going to cover a lot of very useful stuff commonly used in enterprise application software. Contents of the Log4Net config file are given below FYI. <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" allowExeDefinition="MachineToRoamingUser"/> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="UdemyWindowsService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> </configSections> <log4net debug="true"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file type="log4net.Util.PatternString" value=".\ServiceLog.txt"/> <appendToFile value="true"/> <rollingStyle value="Size"/> <maxSizeRollBackups value="10"/> <maximumFileSize value="10MB"/> <staticLogFileName value="true"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%p %d %r %m %newline"/> </layout> <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/> </appender> <logger name="servicelog"> <level value="DEBUG"/> <appender-ref </logger> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration> Yet another exciting demo! In this you are going to see your rolling text log file functionality in action. I am also going to show you BareTail which is a cool utility used to watch log files in real time, its very popular among professional programmers. Welcome to section 4 In this section I am going to show you some real world usages of Windows Services. In this lecture, we will create a skeleton of a Windows Service which will be capable of reading data in a periodic fashion A few common examples are, reading data from a website and storing it to a database, reading data from a database and sending an alert if need be etc. First of all, We are going to use the service project which we’ve created until section three. The source code is already available in download section of this video We are going to use a system dot threading dot timer for periodic data updates This timer will be started upon service start and keep firing at set intervals. First of all, open UdemyWindowsService.cs file and double click in the designer area Inside the code, I’m going to define a System dot Threading dot Timer member variable on class level System.Threading.Timer mRepeatingTimer; Let’s define a class level variable which will be updated by our thread. double mCounter; now set the value of this counter to zero on startup We also need to define a callback method which will be invoked by this timer public void myTimerCallback(object objParam) Let’s write some text to the log file mLogger. Debug “Value of counter is mCounter plus plus Now let us go back to OnStart method Inside this method we will start our thread. mTimer equals new System dot Threading dot Timer(myTimerCallback comma mTimer comma 1000 comma 1000); These numbers are in millisecond. First number tells after how many milliseconds the timer will be fired first time Second number tells after how many milliseconds the timer will be fired subsequently We can increase or decrease the duration of the timer by changing these numbers Now let’s build and see if all is well We will run this service in next lecture Let’s open the service debug folder I have got the serviceLog.txt file open in BareTail Its a free software that hot updates the text file as soon as it is changed by your windows service Let’s start the service Now I’m going to open the service log file using baretail. How to generate rolling text log files is explained in section three of this course. You can see that the log file is updated by the timer again and again Now you know how to create a periodic data update service, you may use the skeleton shown here in production as well. Important: Source code is available in download section Dear student, now I am going to show you how to make your Windows Service watch for changes on the file system. We will create a new folder and provide its path to your Windows Service. Once we write appropriate code, Windows operating system will notify your service every time a file changes in this directory. The service will get events when a file is created, deleted, changed, or renamed. First of all, open the Udemy Windows Service project. Expand solution explorer, expand bin and right click debug folder, select “Open in file explorer”. Right click in the file explorer and select “New” “Folder”. I will call this folder “Watch Me”. Now switch back to our service project and open UdemyWindowsService.cs Go to code view add namespace System.IO. using system.io. We need this namespace for file system watcher. Next, let’s define a class level member of type FileSystemWatcher. FileSystemWatcher mFSW; Go to the end of OnStart method of the service. If you have the line of code which starts the timer, the one we created in a previous video of this section. Change the thread parameters to 100000. You can comment the line of code as well. Otherwise, the timer will keep ticking and log file will keep growing which won’t let you see the events related to file system watcher. Now, back to real work. Instantiate the file system watcher. mFSW = new FileSystemWatcher(); We’ll supply the path of the folder which we want to monitor as parameter. We will also enable raising events by setting a flag like mFSW.EnableRaisingEvents = true; Lets set another flag to enable monitoring of sub-directories. mFSW.IncludeSubdirectories = true; Now let’s add a callback delegate to handle file system events. mFSW.Created += Visual Studio 2015 says “Press TAB to insert”. I’m cool with that. I’ll press tab. The VS has automatically created appropriate callback method. It shows a rename dialog as well, we haven’t used this method anywhere else so I’ll just click ‘Apply’. Let’s rename the delegate to “MFSW_somethingHappenedToTheFolder” Click the like bulb and allow VS to rename all references. At this stage, we can use the same delegate to handle multiple types of events. For example mFSW.Changed += MFSW_somethingHappenedToTheFolder; mFSW.Deleted += MFSW_somethingHappenedToTheFolder; and mFSW.Renamed += MFSW_somethingHappenedToTheFolder; There’s a “NotImplementedException” inside the newly generated method. Let’s delete it and add some code. mLogger.Debug(string.Format("{0} - \r\nnFile event for: {1}", e.ChangeType, e.FullPath)); We’re writing the same line to the output console as well. Let’s build the service to see if everything is okay or not. Build succeeded, we’re in good shape. In the next video, we will run this service and see a demo. To start with, we need to open the installation folder of our service. We’ve been doing this through visual studio. Let’s do it another way this time. Run the service control manager by press windows R and typing services.msc and pressing enter Find udemy windows service in list of services Right click and select “Properties” Look for “Path to executeable”, copy this value. Launch Run dialog by pressing Windows + R Paste the file path value Remove the double quotes from start and end of the path From the end of path, remove UdemyWindowsService.exe Now press “Enter” The debug folder has opened You can see that the folder “Watch Me” is there Our service is going to monitor any changes made to this folder. Next, launch BareTail If the serviceLog.txt file is already there, drag it over to bare tail Now I’ll delete the log file from disk Let's go back to service control manager and close the service properties dialog which we opened earlier Start Udemy Windows Service Tuck file explorer on one side and bare tail on the other You can see a new ServiceLog.txt file has been created by the service Right click and copy this file Double click to open the folder “Watch Me” Right click and paste the file which you copied earlier You can see that a “Changed” event has shown up in the log file. The event also contains path of the file Similarly, launch “Notepad” and type some text. Now save the file in the folder which is being watched by our service. I will copy the folder path from explorer window and paste it in file save dialog FIle name is first.txt Now you see that three events were fired against new file creation, one “Created” event and two “Changed”. Let’s go back to the explorer and delete one of the files. An event “Deleted” is shown in the log file by the service. Your service can take any action on the files when these events happen. For example, I once created a password synchronization application. It had a Windows Password Filter which was invoked on system password change, wrote the new password in encrypted form to the disk, and then a separate file system watcher service would pick it up and send the user name/password over to a cloud based system. In this video I will show you how to add a config file to your project and how to use it to pass parameters over to your service upon service startup. Please note that this technique can be used to affect service behavior and it is helpful in many situations where you can make the service behave differently without a recompile and redeploy. You are going to dig deep into the config file and see what are its various components and how you can take advantage in deployments by changing various values. It is possible to control a service using a desktop application or an ASP.Net website using System.ServiceProcess.ServiceController class. I will show you how to use this class. Let’s open the UdemyWindowsService solution. Right click the solution and select “Add” and “New Project” Go to Visual C# and click “Windows” and then click “Windows Forms Application”. Let’s name it “USAdmin” I’m going to rename the file “Form1.cs” to “USAdmin.cs” Now double click to open the form in design view. I’ll click the form and then go to properties and change the “Text” to “Udemy Service Admin”. Next I’ll add a label to the service, rename it to “lblServiceStatus” and change its text property to “Service Status”. We need to add the assembly reference of System.ServiceProcess here. Go to the “References” node under the “USAdmin” project. Right click the “References” node and click “Add Reference” Expand “Assemblies” and then “Framework” Click the search text box and type “System.ServiceProcess”. The relevant assembly will show up. Click the checkbox behind it and click button “OK”. Now right click the USAdmin form and select “View Code” Go to the top of the file and add a using statement. using System.ServiceProcess. Now go back to the design view and double click the form body. VS will automatically add an OnLoad method delegate for you. Let’s get outside this delegate’s body and define a new method, it will be used to retrieve the status of our running service. We’ll use a local variable of type ServiceController here, let’s define it. ServiceController sc = new ServiceController("Udemy Windows Service"); We’ve used the constructor which takes only the service name and assumes it is running on the local machine. I’m sure you have memorized the name of our Windows service that is “Udemy Windows Service”, I’m passing that to the constructor. Next let’s get the status of the service by calling sc.Status.ToString(). I’m keeping the value in a local variable which will be returned in the end of the method. I’ve also created a Try/Catch safety net around the property read operation, it will help if you mistakenly supply the wrong service name. Now let’s go the USAdminMain_Load method, call getServiceStatus, and assign the return value to the status label. Build the project to see if everything is okay. After successful build I will go back to the designer view and add a new button “Get Status” as well. Double click the “btnGetStatus”, a new OnClick method will be generated for you. I will copy over the status line of code which from the OnLoad method. lblServiceStatus.Text = string.Format("Service Status: {0}", getServiceStatus()); Now let’s build again. Right click “USAdmin” and select “Start New Instance”. The form will show up, you can see that the service status is “Stopped” at present. Let’s go to service control manager and start the service. Back on the form, I will click the button “Get Status”, the value will be updated to “Running”. In the next video I will show you how to start/stop a service from your forms application. I am a professional programmer, I will be happy to answer your questions and help you in case of a problem. Feel free to reach out. Happy learning and stay tuned for more. :) Starting or stopping a service is a very simple step. In this video I’m going to show you how to do it in asynchronous fashion. First of all, let’s create new methods in our form to start and stop service. public bool startService() public bool stopService() For the purpose of this demo I’m going to define service name as a constant. Otherwise, you might put the service name in config file and read the value on runtime. Let’s go to the top of the form and define the constant like this const string CONST_SERVICE_NAME = "Udemy Windows Service"; Back in the startService method, I will define a service controller like we did earlier and call its method “StartService”. try { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); }catch(Exception excp) { MessageBox.Show (excp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); bRetVal = false; } The boilerplate like try/catch safety net is in place. Let me do the same in stopService as well. The difference is the method call Stop in the later method and the parameter of waitForServiceStatus method which is changed to stopped.. Please note that if an exception occurs while starting or stopping the service, both of these methods are going to return false. If the operation goes successful, the methods will return true. We will use this value in a while. Next, I’m going to add a couple of buttons to start/stops the service. I’ve added two buttons, start and stop. Both buttons are disabled by default, the OnLoad method of the form will decide which one should be enabled on the startup. I’ve done it through the value of lblServiceStatus instead of calling the getServiceStatus method again. Here’s the code if (lblServiceStatus.Text.EndsWith("Stopped")) { btnStart.Enabled = true; } else { btnStop.Enabled = true; } I’ll also add the logic to enable/disable start/stop buttons to the method getServiceStatus. if (lblServiceStatus.Text.EndsWith("Stopped")) { btnStart.Enabled = true; } else { btnStop.Enabled = true; } Now I am going to go to the form design view and double click the button “Start”. In the onClick callback, let’s call the method which we wrote earlier to start the service. if (startService()) { btnStop.Enabled = true; btnStart.Enabled = false; } lblServiceStatus.Text = "Service Status: " + getServiceStatus(); This piece of code will attempt to start the service and if it succeeds, it will update the button state. The last line will update the status label. Let’s do the logical equivalent in serviceStop as well. if (stopService()) { btnStart.Enabled = true; btnStop.Enabled = false; } lblServiceStatus.Text = "Service Status: " + getServiceStatus(); Now let’s build everything. And run the form application. It says that the service is stopped. The start button you can see is enabled and the stop button is disabled. I’ll click “Start” button. The system shows an error message :( It says “Cannot open service Udemy Windows Service on the system” Well, that’s because we’re not running VS with admin privileges. You can do two things. Either close the VS, and start it as administrator again. Or go to the debug directory of the solution, right click and run the application as administrator. Let’s do the former. Now I’ll run the application And I’m going to click “Start” button. You see it will take a short while, and then the button statuses will change. Let’ check the service status in SCM. It looks correct Now click the stop button and refresh the SCM. This is the end of this video. I hope you found it useful. SC.exe is a command line utility built into Windows operating system. You don’t need to install it separately. That’s why we can use it to install/uninstall a Windows service. Most probably you would’ve installed the UdemyWindowsService on your machine In that case, un-install the service using technique shown in lecture 10 “Uninstall a Windows Service”. We’re going to run command prompt as administrator Open the debug folder of the service and copy the path of the service exe file Now go to the command prompt and key-in command sc.exe create Name="Udemy Windows Service" binPath="C:\Users\Naeem Akram\Documents\Visual Studio 2015\Projects\UdemyWindowsService\UdemyWindowsService\UdemyWindowsService\bin\Debug\UdemyWindowsService.exe" In order to see the detailed help about sc.exe, just type the command sc on command prompt. Now go to service control manager, our service will show as installed. Let’s run our service Everything looks fine In order to uninstall a service, we are going to use the command given below Sc.exe delete “Udemy Windows Service” The parameter in double quotes is the name of the service Let’s try it Now refresh the SCM The service is gone! We are going to use these commands in next videos of this section, to install and uninstall a Windows Service. I’ve chosen to use Inno setup to create an installer for our Windows Service. There are various reasons for this. First of all Microsoft has pulled the plug on the installer projects which came with Visual Studio by default. They are supporting WiX toolkit, I’ve used it a for a project and I … found it complicated. So, I’ll show you how to use Inno Setup which is a free installation system. The download link is given in course description and shown on the screen as well Download and install the latest stable release of Inno Setup. In the next video we will create an installer setup which will use Inno Setup and SC.exe to install our service on a non-developer PC. Before we start creating installer for our service, let us build our project in release mode. We must build our projects in “Release” mode before sending them to deployment So now let’s go to our service project and select “Release” from the build toolbar Go to “Build” menu and select “Build” Next… I am going to launch the “Inno Setup Compiler”. [Click start, click “Inno Setup Compiler”] Click check box “Create a new script file using the Script Wizard”, click “OK” button Click Next Supply Application parameters like Application name would be “Udemy Windows Service” Version 1.0, Publisher can be your name or my name etc. Cilck “Next” Application folder name will be again “Udemy Windows Service”, click “Next” For “Application main executable file” we will click “Browse” button I will browse to the “Release” folder of our project and pick “Udemy Windows Service.exe” Uncheck the check-box “Allow user to start the application after setup has completed” Click button “Other Application files and select “Log4Net.dll” and service config file as well Click the button again and pick the files of US Admin as well Click “Open” button Click “Next” button Start Menu folder name will be “I Love You”, or maybe “Udemy Windows Service” is okay. Click Next three times I will call “Compiler Output base file name” … “SetupUWS” Click “Next” button twice And click “Finish” button Don’t compile the script, we need to make some important changes Firstly, “My App Name” will become “Udemy Windows Service” We will add a [Run] section This section will run when setup has finished copying files to destination program files directory It will contain the “sc” command in a slightly twisted fashion I am about to bring in the command, hold your breath and don’t freak out. I will explain. This syntax means that we are going to launch the command prompt and pass it the sc command The /c will make the command run and close the command prompt afterwards You can see the words sc and create which were explained in first video of this section The next parameter {#MyAppname} is defined on top of this script file [Scroll Up] It will be resolved to “Udemy Windows Service” on run time. On the command prompt we need to put the name in double quotes, the extra double quote is used as an escape sequence. Same is true for binPath Which will be ultimately resolved to the path of our main service file on target machine. I must mention a very small error which can give you a head-ache. See this space between binPath= and the double quotes, miss it and you will regret. Don’t miss this space, the sc command will fail. Similarly, we can add a section UninstallRun which will run when we will run the uninstall utility Let me put the script here In this case we are running the “sc” with “delete” command I would love to make things even sweeter by making a small change to the [icons] section In the first line, I will change {#MyAppExeName} to “USAdmin.exe” I will make the same change in the line below, which lets us create an icon on the desktop Now let compile the script I will click “Build” menu and select “Compile” The system didn’t show any error You can either click the play button on the toolbar Right here[emphasis on button] Or, you can go to the output folder of your installer project and run the SetupUWS.exe In the next video, you are going to see this very installer in action! I will browse to the “Output” directory of our setup project SetupUWS.exe is present there. I will double click the file and launch the installer Just keep clicking the next button, I will like to create a desktop icon though. Click Install button Now click “Finish” button You can see an icon is created on the desktop, I will right click it and select “Run as Administrator” Now click the button “Start Service” The service has started. We can check in the service control manager. [Click windows button and click Service Control manager] You see, Udemy Windows Service is present and installed Let me show you the application installation folder as well [Open using explorer] Here you can see all files related to your service The service log file is also in place That’s all for this video I believe the course is pretty much complete now after the addition of the installer section. Thanks very much for watching, feel free to ask questions and get in touch. A brief introduction about my first online course titled "TCP/IP socket programming in C# .Net for coders & students". The course URL is:.
https://www.udemy.com/windows-service-programming/?couponCode=HALF
CC-MAIN-2017-22
refinedweb
6,512
61.16
T). Example 13-1. benchmarks/registry.pl use strict; print "Content-type: text/plain\n\n"; print "Hello"; And we will use the equivalent content-generation handler, shown in Example 13-2. Example 13-2. Benchmark/Handler.pm scripts,. Example 13-3. processing_with_apache_args.pl use strict; my $r = shift; $r->send_http_header('text/plain'); my %args = $r->args; print join "\n", map {"$_ => $args{$_}" } keys %args; Example 13-4. processing_with_apache_request.pl use strict; use Apache::Request ( ); my $r = shift; my $q = Apache::Request->new($r); $r->send_http_header('text/plain'); my %args = map {$_ => $q->param($_) } $q->param; print join "\n", map {"$_ => $args{$_}" } keys %args; Example 13-5. processing_with_cgi_pm.pl. As you probably know, this statement: local $|=1; disables buffering of the currently select( )ed file handle (the default is STDOUT). Under mod_perl, the STDOUT file handle is automatically tied to the output socket. If STDOUT buffering is disabled, each print( ) call also calls ap_rflush( ) to flush Apache’s output buffer. When multiple print( ) calls are used (bad style in generating output), or if there are just too many of them, you will experience a degradation in performance. The severity depends on the number of print( ) calls that are made. Many old CGI scripts were written like this: print "<body bgcolor=\"black\" text=\"white\">"; print "<h1>Hello</h1>"; print "<a href=\"foo.html\">foo</a>"; print "</body>"; This example has multiple print( ) calls, which will cause performance degradation with $|=1. It also uses too many backslashes. This makes the code less readable, and it is more difficult to format the HTML so that it is easily readable as the script’s output. The code below solves the problems: print qq{ <body bgcolor="black" text="white"> <h1>Hello</h1> <a href="foo.html">foo</a> </body> }; You can easily see the difference. Be careful, though, when printing an <html> tag. The correct way is: print qq{<html> <head></head> }; You can also try the following: print qq{ <html> <head></head> }; but note that some older browsers expect the first characters after the headers and empty line to be <html> with no spaces before the opening left angle bracket. If there are any other characters, they might not accept the output as HTML might and print it as plain text. Even if this approach works with your browser, it might not work with others. Another approach is to use the here document style: print <<EOT; <html> <head></head> EOT Performance-wise, the qq{ } and here document styles compile down to exactly the same code, so there should not be any real difference between them. Remember that the closing tag of the here document style ( EOT in our example) must be aligned to the left side of the line, with no spaces or other characters before it and nothing but a newline after it. Yet another technique is to pass the arguments to print( ) as a list: print "<body bgcolor=\"black\" text=\"white\">", "<h1>Hello</h1>", "<a href=\"foo.html\">foo</a>", "</body>"; This technique makes fewer print( ) calls but still suffers from so-called backslashitis (quotation marks used in HTML need to be prefixed with a backslash). Single quotes can be used instead: '<a href="foo.html">foo</a>' but then how do we insert a variable? The string will need to be split again: '<a href="',$foo,'.html">', $foo, '</a>' This is ugly, but it’s a matter of taste. We tend to use the print qq{<a href="$foo.html">$foo</a> Some text <img src="bar.png" alt="bar" width="1" height="1"> }; What if you want to make fewer print( ) calls, but you don’t have the output ready all at once? One approach is to buffer the output in the array and then print it all at once: my @buffer = ( ); push @buffer, "<body bgcolor=\"black\" text=\"white\">"; push @buffer, "<h1>Hello</h1>"; push @buffer, "<a href=\"foo.html\">foo</a>"; push @buffer, "</body>"; print @buffer; An even better technique is to pass print( ) a reference to the string. The print( ) used under Apache overloads the default CORE::print( ) and knows that it should automatically dereference any reference passed to it. Therefore, it’s more efficient to pass strings by reference, as it avoids the overhead of copying. my $"; $buffer .= "<h1>Hello</h1>"; $buffer .= "<a href=\"foo.html\">foo</a>"; $buffer .= "</body>"; print \$buffer; If you print references in this way, your code will not be backward compatible with mod_cgi, which uses the CORE::print( ) function. Now to the benchmarks. Let’s compare the printing techniques we have just discussed. The benchmark that we are going to use is shown in Example 13-6. Example 13-6. benchmarks/print.pl use Benchmark; use Symbol; my $fh = gensym; open $fh, ">/dev/null" or die; my @text = ( "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">\n", "<HTML>\n", " <HEAD>\n", " <TITLE>\n", " Test page\n", " </TITLE>\n", " </HEAD>\n", " <BODY BGCOLOR=\"black\" TEXT=\"white\">\n", " <H1>\n", " Test page \n", " </H1>\n", " <A HREF=\"foo.html\">foo</A>\n", "text line that emulates some real output\n" x 100, " <HR>\n", " </BODY>\n", "</HTML>\n", ); my $text = join "", @text; sub multi { my @copy = @text; my_print($_) for @copy; } sub single { my $copy = $text; my_print($copy); } sub array { my @copy = @text; my_print(@copy); } sub ref_arr { my @refs = \(@text); my_print(@refs); } sub concat { my $buffer; $buffer .= $_ for @text; my_print($buffer); } sub my_join { my $buffer = join '', @text; my_print($buffer); } sub my_print { for (@_) { print $fh ref($_) ? $$_ : $_; } } timethese(100_000, { join => \&my_join, array => \&array, ref_arr => \&ref_arr, multi => \&multi, single => \&single, concat => \&concat, }); timethese(100_000, { 'array /b' => sub {my $ofh=select($fh);$|=0;select($ofh); array( ) }, 'array /u' => sub {my $ofh=select($fh);$|=1;select($ofh); array( ) }, 'ref_arr/b' => sub {my $ofh=select($fh);$|=0;select($ofh); ref_arr( )}, 'ref_arr/u' => sub {my $ofh=select($fh);$|=1;select($ofh); ref_arr( )}, 'multi /b' => sub {my $ofh=select($fh);$|=0;select($ofh); multi( ) }, 'multi /u' => sub {my $ofh=select($fh);$|=1;select($ofh); multi( ) }, 'single /b' => sub {my $ofh=select($fh);$|=0;select($ofh); single( ) }, 'single /u' => sub {my $ofh=select($fh);$|=1;select($ofh); single( ) }, 'concat /b' => sub {my $ofh=select($fh);$|=0;select($ofh); concat( ) }, 'concat /u' => sub {my $ofh=select($fh);$|=1;select($ofh); concat( ) }, 'join /b' => sub {my $ofh=select($fh);$|=0;select($ofh); my_join( )}, 'join /u' => sub {my $ofh=select($fh);$|=1;select($ofh); my_join( )}, }); Under Perl 5.6.0 on Linux, the first set of results, sorted by CPU clocks, is: Benchmark: timing 100000 iterations of array, concat, multi, ref_array... single: 6 wallclock secs ( 5.42 usr + 0.16 sys = 5.58 CPU) join: 8 wallclock secs ( 8.63 usr + 0.14 sys = 8.77 CPU) concat: 12 wallclock secs (10.57 usr + 0.31 sys = 10.88 CPU) ref_arr: 14 wallclock secs (11.92 usr + 0.13 sys = 12.05 CPU) array: 15 wallclock secs (12.95 usr + 0.26 sys = 13.21 CPU) multi: 38 wallclock secs (34.94 usr + 0.25 sys = 35.19 CPU) single string print is obviously the fastest; join, concatination of string, array of references to string, and array of strings are very close to each other (the results may vary according to the length of the strings); and print call per string is the slowest. Now let’s look at the same benchmark, where the printing was either buffered or not: Benchmark: timing 100000 iterations of ... single /b: 10 wallclock secs ( 8.34 usr + 0.23 sys = 8.57 CPU) single /u: 10 wallclock secs ( 8.57 usr + 0.25 sys = 8.82 CPU) join /b: 13 wallclock secs (11.49 usr + 0.27 sys = 11.76 CPU) join /u: 12 wallclock secs (11.80 usr + 0.18 sys = 11.98 CPU) concat /b: 14 wallclock secs (13.73 usr + 0.17 sys = 13.90 CPU) concat /u: 16 wallclock secs (13.98 usr + 0.15 sys = 14.13 CPU) ref_arr/b: 15 wallclock secs (14.95 usr + 0.20 sys = 15.15 CPU) array /b: 16 wallclock secs (16.06 usr + 0.23 sys = 16.29 CPU) ref_arr/u: 18 wallclock secs (16.85 usr + 0.98 sys = 17.83 CPU) array /u: 19 wallclock secs (17.65 usr + 1.06 sys = 18.71 CPU) multi /b: 41 wallclock secs (37.89 usr + 0.28 sys = 38.17 CPU) multi /u: 48 wallclock secs (43.24 usr + 1.67 sys = 44.91 CPU) First, we see the same picture among different printing techniques. Second, we can see that the buffered print is always faster, but only in the case where print( ) is called for each short string does it have a significant speed impact. Now let’s go back to the $|=1 topic. You might still decide to disable buffering, for two reasons: You use relatively few print( ) calls. You achieve this by arranging for print( ) statements to print multiline text, not one line per print( ) statement. You want your users to see output immediately. If you are about to produce the results of a database query that might take some time to complete, you might want users to get some feedback while they are waiting. Ask yourself whether you prefer getting the output a bit slower but steadily from the moment you press the Submit button, or having to watch the “falling stars” for a while and then getting the whole output at once, even if it’s a few milliseconds faster—assuming the browser didn’t time out during the wait. An even better solution is to keep buffering enabled and call $r->rflush( ) to flush the buffers when needed. This way you can place the first part of the page you are sending in the buffer and flush it a moment before you perform a lengthy operation such as a database query. This kills two birds with the same stone: you show some of the data to the user immediately so she will see that something is actually happening, and you don’t suffer from the performance hit caused by disabling buffering. Here is an example of such code: use CGI ( ); my $r = shift; my $q = new CGI; print $q->header('text/html'); print $q->start_html; print $q->p("Searching...Please wait"); $r->rflush; # imitate a lengthy operation for (1..5) { sleep 1; } print $q->p("Done!"); The script prints the beginning of the HTML document along with a nice request to wait by flushing the output buffer just before it starts the lengthy operation. Now let’s run the web benchmark and compare the performance of buffered versus unbuffered printing in the multi-printing code used in the last benchmark. We are going to use two identical handlers, the first handler having its STDOUT stream (tied to socket) unbuffered. The code appears in Example 13-7. Example 13-7. Book/UnBuffered.pm package Book::UnBuffered; use Apache::Constants qw(:common); local $|=1; # Switch off buffering. sub handler { my $r = shift; $r->send_http_header('text/html'); print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">\n"; print "<html>\n"; print " <head>\n"; print " <title>\n"; print " Test page\n"; print " </title>\n"; print " </head>\n"; print " <body bgcolor=\"black\" text=\"white\">\n"; print " <h1> \n"; print " Test page \n"; print " </h1>\n"; print " <a href=\"foo.html\">foo</a>\n" for 1..100; print " <hr>\n"; print " </body>\n"; print "</html>\n"; return OK; } 1; The following httpd.conf configuration is used: ################################# ### Buffered output ################################# <Location /buffering> SetHandler perl-script PerlHandler +Book::Buffered </Location> ################################# ### UnBuffered output ################################# <Location /unbuffering> SetHandler perl-script PerlHandler +Book::UnBuffered </Location> Now we run the benchmark, using ApacheBench, with concurrency set to 50, for a total of 5,000 requests. Here are the results: name | avtime completed failed RPS --------------------------------------------- unbuffering | 56 5000 0 855 buffering | 55 5000 0 865 As you can see, there is not much difference when the overhead of other processing is added. The difference was more significant when we benchmarked only the Perl code. In real web requests, a few percent difference will be felt only if you unbuffer the output and print thousands of strings one at a time. Let). Example 13-8. benchmarks/join.pl; }, }); strings. Example 13-9. benchmarks/join_long.pl; }, }); you use " string" or ' string‘.. Example 13-10. size_interp.pl . Example 13-11. size_nointerp.pl. Since.pm suffers. Example 13-12. perlbloat.pl #! scripts '. Which form of subroutine call is more efficient: object methods or function calls? Let’s look at the overhead. Let’s do some benchmarking. We will start by using empty methods, which will allow us to measure the real difference in the overhead each kind of call introduces. We will use the code in Example 13-15. Example 13-15. bench_call1.pl. The). Example 13-16. bench_call2.pl. Some. Example 13-17. bench_call3.pl. When _; If( ). To send a complete file from disk, without applying any modifications first, instead of: my $filename = "/tmp/foo"; my $fh = Apache::gensym( ); # generate a new filehandle open $fh, $filename or return NOT_FOUND; print <$fh>; close $fh; it’s better to write: my $filename = "/tmp/foo"; my $fh = Apache::gensym( ); # generate a new filehandle open $fh, $filename or return NOT_FOUND; $r->send_fd($fh); close $fh; The former implementation uses more memory and it’s slower, because it creates a temporary variable to read the data in and then print it out. The latter uses optimized C code to read the file and send it to the client. In some situations, you may have data that is expensive to generate but must be created on the fly. If the data can be reused, it may be more efficient to cache it. This will save the CPU cycles that regenerating the data would incur and will improve performance (at the expense of using more memory to cache the results). If the data set is final, it can be a good idea to generate this data set at server startup and then share it with all the child processes, thus saving both memory and time. We’ll create a calendar example similar to the ones many online services use to allow their users to choose dates for online forms or to navigate to pages specific to a particular date. Since we are talking about dynamic pages, we cannot allow the calendar to be static. To make our explanations easier, let’s assume that we are trying to build a nice navigation system for forums, but will implement only the temporal navigation. You can extend our code to add the actual forums and interface elements to change presentation modes (index, thread, nested) and to change forums (perl, mod_perl, apache). In Figure 13-1, you can see how the calendar looks if today is May 16, 2002 and the user has just entered the site. You can see that only day numbers before this date are linked to the data for those dates. The current month appears between the previous month, April, and the next to come, June. June dates aren’t linked at all, since they’re in the future. We click on April 16 and get a new calendar (see Figure 13-2), where April is shown in the middle of the two adjacent months. Again, we can see that in May not all dates are linked, since we are still in the middle of the month. In both figures you can see a title (which can be pretty much anything) that can be passed when some link in the calendar is clicked. When we go through the actual script that presents the calendar we will show this in detail. As you can see from the figures, you can move backward and forward in time by clicking on the righthand or lefthand month. If you currently have a calendar showing Mar-Apr-May, by clicking on some day in March, you will get a calendar of Feb-Mar-Apr, and if you click on some day in May you will see Apr-May-Jun. Most users will want to browse recent data from the forums—especially the current month and probably the previous month. Some users will want to browse older archives, but these users would be a minority. Since the generation of the calendar is quite an expensive operation, it makes sense to generate the current and previous months’ calendars at server startup and then reuse them in all the child processes. We also want to cache any other items generated during the requests. In order to appreciate the results of the benchmark presented at the end of this section, which show the benefits of caching for this application, it’s important to understand how the application works. Therefore, let’s explain the code first. First we create a new package and load Date::Calc: package Book::Calendar; use Date::Calc ( ); Date::Calc, while a quite bloated module, is very useful for working with dates. We have two caches, one for one-month text calendars ( %TXT_CAL_CACHE, where we will cache the output of Date::Calc::Calendar( )), and the other for caching the real three-month HTML calendar components: my %HTML_CAL_CACHE = ( ); my %TXT_CAL_CACHE = ( ); The following variable controls the last day the current month’s calendar was updated in the cache. We will explain this variable (which serves as a flag) in a moment. my $CURRENT_MONTH_LAST_CACHED_DAY = 0; The debug constant allows us to add some debug statements and keep them in the production code: use constant DEBUG => 1; All the code that is executed if DEBUG is true: warn "foo" if DEBUG; will be removed at compile time by Perl when DEBUG is made false (in production, for example). This code prebuilds each month’s calendar from three months back to one month forward. If this module is loaded at server startup, pre-caching will happen automatically and data will be shared between the children, so you save both memory and time. If you think that you need more months cached, just adjust this pre-caching code. my ($cyear,$cmonth) = Date::Calc::Today( ); for my $i (-3..1) { my($year, $month) = Date::Calc::Add_Delta_YMD($cyear, $cmonth, 1, 0, $i, 0); my $cal = ''; get_html_calendar(\$cal, $year, $month); } The get_text_calendar function wraps a retrieval of plain-text calendars generated by Date::Calc::Calendar( ), caches the generated months, and, if the month was already cached, immediately returns it, thus saving time and CPU cycles. sub get_text_calendar{ my($year, $month) = @_; unless ($TXT_CAL_CACHE{$year}{$month}) { $TXT_CAL_CACHE{$year}{$month} = Date::Calc::Calendar($year, $month); # remove extra new line at the end chomp $TXT_CAL_CACHE{$year}{$month}; } return $TXT_CAL_CACHE{$year}{$month}; } Now the main function starts. sub get_html_calendar{ my $r_calendar = shift; my $year = shift || 1; my $month = shift || 1; get_html_calendar( ) is called with a reference to a final calendar and the year/month of the middle month in the calendar. Remember that the whole widget includes three months. So you call it like this, as we saw in the pre-caching code: my $calendar = ''; get_html_calendar(\$calendar, $year, $month); After get_html_calendar( ) is called, $calendar contains all the HTML needed. Next we get the current year, month, and day, so we will know what days should be linked. In our design, only past days and today are linked. my($cur_year, $cur_month, $cur_day) = Date::Calc::Today( ); The following code decides whether the $must_update_current_month_cache flag should be set or not. It’s used to solve a problem with calendars that include the current month. We cannot simply cache the current month’s calendar, because on the next day it will be incorrect, since the new day will not be linked. So what we are going to do is cache this month’s day and remember this day in the $CURRENT_MONTH_LAST_CACHED_DAY variable, explained; } Now the decision logic is simple: we go through all three months in our calendar, and if any of them is the current month, we check the date when the cache was last updated for the current month (stored in the $CURRENT_MONTH_LAST_CACHED_DAY variable). If this date is less than today’s date, we have to rebuild this cache entry. unless (exists $HTML_CAL_CACHE{$year}{$month} and not $must_update_current_month_cache) { So we enter the main loop where the calendar is HTMLified and linked. We enter this loop if: There is no cached copy of the requested month. There is a cached copy of the requested month, but it includes the current month and the next date has arrived; we need to rebuild it again, since the new day should be linked as well. The following is the debug statement we mentioned earlier. This can help you check that the cache works and that you actually reuse it. If the constant DEBUG is set to a true value, the warning will be output every time this loop is entered. warn "creating a new calendar for $year $month\n" if DEBUG; When we load this module at server startup, the pre-caching code we described earlier gets executed, and we will see the following warnings (if DEBUG is true): creating a new calendar for 2000 9 creating a new calendar for 2000 10 creating a new calendar for 2000 11 creating a new calendar for 2000 12 creating a new calendar for 2001 1 my @cal = ( ); Now we create three calendars, which will be stored in @cal: for my $i (-1..1) { my $id = $i+1; As you can see, we make a loop (-1,0,1) so we can go one month back from the requested month and one month forward in a generic way. Now we call Date::Calc::Add_Delta_YMD( ) to retrieve the previous, current, or next month by providing the requested year and month, using the first date of the month. Then we add zero years, $i months, and zero days. Since $i loops through the values ( -1, 0, 1), we get the previous, current, and next months: my ($t_year, $t_month) = Date::Calc::Add_Delta_YMD($year, $month, 1, 0, $i, 0); Next, we get the text calendar for a single month. It will be cached internally by get_text_calendar( ) if it wasn’t cached already: $cal[$id] = get_text_calendar($t_year, $t_month); The following code determines whether the requested month is the current month (present), a month from the past, or the month in the future. That’s why the decision variable has three possible values: -1, 0, and 1 (past, present, and future, respectively). We will need this flag when we decide whether a day should be linked or not. my $yearmonth = sprintf("%0.4d%0.2d", $t_year, $t_month); my $cur_yearmonth = sprintf("%0.4d%0.2d", $cur_year, $cur_month); # tri-state: ppf (past/present/future) my $ppf = $yearmonth <=> $cur_yearmonth; # If $yearmonth = = $cur_yearmonth, $ppf = 0; # elsif $yearmonth < $cur_yearmonth, $ppf = -1; # elsif $yearmonth > $cur_yearmonth, $ppf = 1; This regex is used to substitute days in the textual calendar returned by Date::Calc::Calendar( ) with links: $cal[$id] =~ s{(\s\d|\b\d\d)\b} {link_days($1, $yearmonth, $ppf, $cur_day)}eg; It means: “Find a space followed by a digit, or find two digits (in either case with no adjoining digits), and replace what we’ve found with the result of the link_days( ) subroutine call.” The e option tells Perl to execute the substitution expression—i.e., to call link_days( )—and the g option tells Perl to perform the substitution for every match found in the source string. Note that word boundaries are zero-width assertions (they don’t match any text) and are needed to ensure that we don’t match the year digits. You can see them in the first line of the calendar: May 2002 Mon Tue Wed Thu Fri Sat Sun 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 The link_days( ) subroutine will add HTML links only to dates that aren’t in the future. This line closes the for loop: } This code constructs an HTML table with three calendars and stores it in the cache. We use <pre> ... </pre> blocks to preserve the textual layout of the calendar: #> }; If the $must_update_current_month_cache flag was turned on, the current month is re-processed, since a new day just started. Therefore, we update the $CURRENT_MONTH_LAST_CACHED_DAY with the current day, so that the next request in the same day will use the cached data: # update the last cached day in the current month if needed $CURRENT_MONTH_LAST_CACHED_DAY = $cur_day if $must_update_current_month_cache; This line signals that the conditional block where the calendar was created is over: } Regardless of whether the calendar is created afresh or was already cached, we provide the requested calendar component by assigning it to a variable in the caller namespace, via the reference. The goal is for just this last statement to be executed and for the cache to do the rest: $$r_calendar = $HTML_CAL_CACHE{$year}{$month}; } # end of sub calendar Note that we copy the whole calendar component and don’t just assign the reference to the cached value. The reason for doing this lies in the fact that this calendar component’s HTML text will be adjusted to the user’s environment and will render the cached entry unusable for future requests. In a moment we will get to customize_calendar( ), which adjusts the calendar for the user environment. This is the function that was called in the second part of the regular expression: sub link_days { my ($token, $yearmonth, $ppf, $cur_day) = @_; It accepts the matched space digit or two digits. We kept the space character for days 1 to 9 so that the calendar is nicely aligned. The function is called as: link_days($token, 200101, $ppf, $cur_day); where the arguments are the token (e.g., ' 2' or ' 31' or possibly something else), the year and the month concatenated together (to be used in a link), the past/present/future month flag, and finally the current date’s day, which is relevant only if we are working in the current month. We immediately return unmodified non-days tokens and break the token into two characters in one statement. Then we set the $fill variable to a single space character if the token included days below 10, or set it to an empty string. $day actually includes the date (1-31). return $token unless my($c1, $c2) = $token =~ /^(\s|\d)(\d)$/; my ($fill, $day) = ($c1 =~ /\d/) ? ('', $c1.$c2) : ($c1, $c2) ; The function is not supposed to link days in future months, or days in this month that are in the future. For days in the future the function returns the token unmodified, which renders these days as plain text with no link. # don't link days in the future return $token if $ppf = = 1 or ($ppf = = 0 and $day > $cur_day); Finally, those tokens that reach this point get linked. The link is constructed of the [URL] placeholder, the date arguments, and the [PARAMS] placeholder. The placeholders will be replaced with real data at runtime. return qq{$fill<a href="[URL]?date=$yearmonth}. sprintf("%0.2d", $day). qq{&[PARAMS]" class="nolink">$day</a>}; The a tag’s nolink class attribute will be used by the client code to render the links with no underlining, to make the calendar more visually appealing. The nolink class must be defined in a Cascading Style Sheet (CSS). Be careful, though—this might not be a very good usability technique, since many people are used to links that are blue and underlined. This line conludes the link_days( ) function: } # end of sub link_days The customize_calendar( ) subroutine takes a reference to a string of HTML (our calendar component, for example) and replaces the placeholders with the data we pass it. We do an efficient one-pass match and replace for both placeholders using the hash lookup trick. If you want to add more placeholders later, all that’s needed is to add a new placeholder name to the %map hash: # replace the placeholders with live data # customize_calendar(\$calendar,$url,$params); ####################### sub customize_calendar { my $r_calendar = shift; my $url = shift || ''; my $params = shift || ''; my %map = ( URL => $url, PARAMS => $params, ); $$r_calendar =~ s/\[(\w+)\]/$map{$1}/g; } # end of sub calendar The module ends with the usual true statement to make require( ) happy: 1; The whole Book::Calendar package is presented in Example 13-18. Example 13-18. Book/Calendar.pm package Book::Calendar; use Date::Calc ( ); my %HTML_CAL_CACHE = ( ); my %TXT_CAL_CACHE = ( ); my $CURRENT_MONTH_LAST_CACHED_DAY = 0; use constant DEBUG => 0; # prebuild this month's, 3 months back and 1 month forward calendars my($cyear, $cmonth) = Date::Calc::Today( ); for my $i (-3..1) { my($year, $month) = Date::Calc::Add_Delta_YMD($cyear, $cmonth, 1, 0, $i, 0); my $cal = ''; get_html_calendar(\$cal, $year, $month); # disregard the returned calendar } # $cal = create_text_calendar($year, $month); # the created calendar is cached ###################### sub get_text_calendar { my($year,$month) = @_; unless ($TXT_CAL_CACHE{$year}{$month}) { $TXT_CAL_CACHE{$year}{$month} = Date::Calc::Calendar($year, $month); # remove extra new line at the end chomp $TXT_CAL_CACHE{$year}{$month}; } return $TXT_CAL_CACHE{$year}{$month}; } # get_html_calendar(\$calendar,1999,7); ###################### sub get_html_calendar { my $r_calendar = shift; my $year = shift || 1; my $month = shift || 1; my($cur_year, $cur_month, $cur_day) = Date::Calc::Today( ); # should requested calendar be updated if it exists; } unless (exists $HTML_CAL_CACHE{$year}{$month} and not $must_update_current_month_cache) { warn "creating a new calendar for $year $month\n" if DEBUG; my @cal = ( ); for my $i (-1..1) { my $id = $i+1; my ($t_year, $t_month) = Date::Calc::Add_Delta_YMD($year, $month, 1, 0, $i, 0); # link the calendar from passed month $cal[$id] = get_text_calendar($t_year, $t_month); # get a copy my $yearmonth = sprintf("%0.4d%0.2d", $t_year, $t_month); my $cur_yearmonth = sprintf("%0.4d%0.2d", $cur_year, $cur_month); # tri-state: ppf (past/present/future) my $ppf = $yearmonth <=> $cur_yearmonth; $cal[$id] =~ s{(\s\d|\b\d\d)\b} {link_days($1, $yearmonth, $ppf, $cur_day)}eg; } #> }; $CURRENT_MONTH_LAST_CACHED_DAY = $cur_day if $must_update_current_month_cache; } $$r_calendar = $HTML_CAL_CACHE{$year}{$month}; } # end of sub calendar # # link_days($token,199901,1,10); ########### sub link_days { my($token, $yearmonth, $ppf, $cur_day) = @_; # $cur_day relevant only if $ppf = = 0 # skip non-days (non (\d or \d\d) ) return $token unless my ($c1, $c2) = $token =~ /(\s|\d)(\d)/; my($fill, $day) = ($c1 =~ /\d/) ? ('', $c1.$c2) : ($c1, $c2) ; # don't link days in the future return $token if $ppf = = 1 or ($ppf = = 0 and $day > $cur_day); # link the date with placeholders to be replaced later return qq{$fill<a href="[URL]?date=$yearmonth}. sprintf("%0.2d",$day). qq{&[PARAMS]" class="nolink">$day</a>}; } # end of sub link_days # replace the placeholders with live data # customize_calendar(\$calendar,$url,$params); ####################### sub customize_calendar { my $r_calendar = shift; my $url = shift || ''; my $params = shift || ''; my %map = ( URL => $url, PARAMS => $params, ); $$r_calendar =~ s/\[(\w+)\]/$map{$1}/g; } # end of sub calendar 1; Now let’s review the code that actually prints the page. The script starts by the usual strict mode, and adds the two packages that we are going to use: use strict; use Date::Calc ( ); use Book::Calendar ( ); We extract the arguments via $r->args and store them in a hash: my $r = shift; my %args = $r->args; Now we set the $year, $month, and $day variables by parsing the requested date (which comes from the day clicked by the user in the calendar). If the date isn’t provided we use today as a starting point. # extract the date or set it to be today my ($year, $month, $day) = ($args{date} and $args{date} =~ /(\d{4})(\d\d)(\d\d)/) ? ($1, $2, $3) : Date::Calc::Today( ); Then we retrieve or use defaults for the other arguments that one might use in a forum application: my $do = $args{do} || 'forums'; my $forum = $args{forum} || 'mod_perl'; my $mode = $args{mode} || 'index'; Next we start to generate the HTTP response, by setting the Content-Type header to text/html and sending all HTTP headers: $r->send_http_header("text/html"); The beginning of the HTML page is generated. It includes the previously mentioned CSS for the calendar link, whose class we have called nolink. Then we start the body of the page and print the title of the page constructed from the arguments that we received or their defaults, followed by the selected or current date:> }; Now we request the calendar component for $year and $month: my $calendar = ''; Book::Calendar::get_html_calendar(\$calendar, $year, $month); We adjust the links to the live data by replacing the placeholders, taking the script’s URI from $r->uri, and setting the paramaters that will be a part of the link: my $params = "do=forums&forum=mod_perl&mode=index"; Book::Calendar::customize_calendar(\$calendar, $r->uri, $params); At the end we print the calendar and finish the HTML: print $calendar; print qq{</body></html>}; The entire script is shown in Example 13-19. Example 13-19. calendar.pl use strict; use Date::Calc ( ); use Book::Calendar ( ); my $r = shift; my %args = $r->args; # extract the date or set it to be today my($year, $month, $day) = ($args{date} and $args{date} =~ /(\d{4})(\d\d)(\d\d)/) ? ($1, $2, $3) : Date::Calc::Today( ); my $do = $args{do} || 'forums'; my $forum = $args{forum} || 'mod_perl'; my $mode = $args{mode} || 'index'; $r->send_http_header("text/html");> }; my $calendar = ''; Book::Calendar::get_html_calendar(\$calendar, $year, $month); my $params = "do=forums&forum=mod_perl&mode=index"; Book::Calendar::customize_calendar(\$calendar, $r->uri, $params); print $calendar; print qq{</body></html>}; Now let’s analyze the importance of the caching that we used in the Book::Calendar module. We will use the simple benchmark in Example 13-20 to get the average runtime under different conditions. Example 13-20. bench_cal.pl use strict; use Benchmark; use Book::Calendar; my ($year, $month) = Date::Calc::Today( ); sub calendar_cached { ($year, $month) = Date::Calc::Add_Delta_YMD($year, $month, 1, 0, 0, 0); my $calendar = ''; Book::Calendar::get_html_calendar(\$calendar, $year, $month); } sub calendar_non_cached { ($year, $month) = Date::Calc::Add_Delta_YMD($year, $month, 1, 0, 1, 0); my $calendar = ''; Book::Calendar::get_html_calendar(\$calendar, $year, $month); } timethese(10_000, { cached => \&calendar_cached, non_cached => \&calendar_non_cached, }); We create two subroutines: calendar_cached( ) and calendar_non_cached( ). Note that we aren’t going to remove the caching code from Book::Calendar; instead, in the calendar_non_cached( ) function we will increment to the next month on each invocation, thus not allowing the data to be cached. In calendar_cached( ) we will request the same calendar all the time. When the benchmark is executed on an unloaded machine, we get the following results: panic% perl calendar_bench.pl Benchmark: timing 10000 iterations of cached, non_cached... cached: 0 wallclock secs ( 0.48 usr + 0.01 sys = 0.49 CPU) non_cached: 26 wallclock secs (24.93 usr + 0.56 sys = 25.49 CPU) The non-cached version is about 52 times slower. On the other hand, when a pretty heavy load is created, which is a common situation for web servers, we get these results: panic% perl calendar_bench.pl Benchmark: timing 10000 iterations of cached, non_cached... cached: 3 wallclock secs ( 0.52 usr + 0.00 sys = 0.52 CPU) non_cached: 146 wallclock secs (28.09 usr + 0.46 sys = 28.55 CPU) We can see that the results of running the same benchmark on machines with different loads are very similar, because the module in question mostly needed CPU. It took six times longer to complete the same benchmark, but CPU-wise the performance is not very different from that of the unloaded machine. You should nevertheless draw your conclusions with care: if your code is not CPU-bound but I/O-bound, for example, the same benchmark on the unloaded and loaded machines will be very different. If. Perl. Perl). Example 13-22. factorial.c). Example 13-23. Makefile.PL. Example 13-24. Book/Factorial.pm. Example 13-25. test.pl). Example 13-26. Factorial.xs sub). We are now ready to write the benchmark code. Take a look at Example 13-27. Example 13-27. factorial_benchmark.pl Using. Example 13-28. factorial_benchmark_inline.pl. Example 13-29. Apache/Factorial.pm.. XSI) No credit card required
https://www.oreilly.com/library/view/practical-mod_perl/0596002270/ch13.html
CC-MAIN-2019-51
refinedweb
5,944
60.24
I generate a few thousand object in my program based on the C++ rand() function. Keeping them in the memory would be exhaustive. Is there a way to copy the CURRENT seed of rand() at any given time? This would give me the opportunity to store ONLY the current seeds and not full objects. (thus I could regenerate those objects, by regenerating the exact same sub-sequences of random numbers) An exhaustive solution is storing the full sequence of random numbers given by rand() – doesn’t worth it. Another would be solution is to implement my own class for randomized numbers. Google gave me no positive clues. There are hundreds of articles teaching the basics of rand and srand, and I couldn’t find the specific ones. Does anyone know other random number generators with implemented seed-stealer? Thank you for your fast answers! There are more possible answers/solutions to this question, so I made a list of your answers here. SOLUTIONS: The short answer is: there is no standard way to get the seed The closest possible workaround is to save the INITIAL seed in the beginning, and count how many times you call the rand() function. I marked this as solution because it works on the current std::rand() function of every compiler (and this was the main question about). I’ve benchmarked my 2.0 GHz CPU, and found that I can call&count rand() 1,000,000,000 times in 35 seconds. This might sound good, but I have 80,000 calls to generate one object. This restricts the number of generations to 50,000 because the size of unsigned long. Anyway, here is my code: class rand2 { unsigned long n; public: rand2 () : n(0) {} unsigned long rnd() { n++; return rand(); } // get number of rand() calls inside this object unsigned long getno () { return n; } // fast forward to a saved position called rec void fast_forward (unsigned long rec) { while (n < rec) rnd(); } }; Another way is to implement your own Pseudo-random number generator, like the one Matteo Italia suggested. This is the fastest, and possibly the BEST solution. You’re not restricted to 4,294,967,295 rand() calls, and don’t need to use other libraries either. It’s worth mentioning that different compilers have different generators. I’ve compared Matteo’s LCG with rand() in Mingw/GCC 3.4.2 and G++ 4.3.2. All 3 of them were different (with seed = 0). Use generators from C++11 or other libraries as Cubbi, Jerry Coffin and Mike Seymour suggested. This is the best idea, if you’re already working with them. Link for C++11 generators: (there are some algorithm descriptions here too) C# – Get Seed from Sequence Is it possible to get the seed from a Random() sequence in c#? My goal is to create a kind of editor, where the player creates his character, like he’d be able to choose in a set of different eyes, p How to sample rows in MySQL using RAND(seed)? I need to fetch a repeatable random set of rows from a table using MySQL. I implemented this using the MySQL RAND function using the bigint primary key of the row as the seed. Interestingly this produ How do I seed the rand() function in Objective-C? Part of what I’m developing is a random company name generator. It draws from several arrays of name parts. I use the rand() function to draw the random name parts. However, the same random numbers What the equalivant code as SQL Server RAND ( [ seed ] )? What the equivalent code in C# as SQL Server T-SQL RAND ( [ seed ] )? python file object how to remove byte from current seed postion to end python file object how to remove byte from current seed postion to end f = open(filename, a+) truncate_pos = f.tell() f.truncate(truncate_pos) seems not work,how could i do? How to get the seed value from a random number generator in PHP I would like to get the seed value after the rand() or mt_rand() is used. Essentially I want to store the seed so that I can use this seed to continue generating random numbers next time php is execut How do you get the current seed of random in C#? In my game I’m going to use random values to pick the reward the player gets from a chest. The problem is that you can quick save and quick load and that means they can keep reloading to re-randomize How to get a larger random number from the c function rand() I am in a coding environment where I only have access to some most basic c functions. #include’ing other lib is not feasible. In this environment, I can call rand() which gives me a random number betw In C, how do I get a specific range of numbers from rand()? srand(time(null)); printf(%d, rand()); Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I’m not sure how to go about it. Any help? Can I get the current seed from a Mersenne Twister? I’m adapting a Mersenne Twister in my Application, specifically mt19937ar.c from – Code is mirrored on Answers Use srand() to set the seed. save the value you used as the seed. There’s no standard way to obtain the current seed (you can only set it via srand), but you can reimplement rand() (which is usually a linear congruential generator) by yourself in a few lines of code: class LCG { private: unsigned long next = 1; public: LCG(unsigned long seed) : next(seed) {} const unsigned long rand_max = 32767 int rand() { next = next * 1103515245 + 12345; return (unsigned int)(next/65536) % 32768; } void reseed(unsigned long seed) { next = seed; } unsigned long getseed() { return next; } }; Does anyone know other random number generators with implemented seed-stealer All standard C++11 random number generators (also available in TR1 and in Boost) offer this functionality. You can simply copy the generator objects or serialize/deserialize them. The random number generation classes in C++11 support operator<< to store their state (mostly the seed) and operator>> to read it back in. So, basically, before you create your objects, save the state, then when you need to re-generate same sequence, read the state back in, and off you go. rand() does not offer any way to extract or duplicate the seed. The best you can do is store the initial value of the seed when you set it with srand(), and then reconstruct the whole sequence from that. The Posix function rand_r() gives you control of the seed. The C++11 library includes a random number library based on sequence-generating “engines”; these engines are copyable, and allow their state to be extracted and restored with << and >> operators, so that you can capture the state of a sequence at any time. Very similar libraries are available in TR1 and Boost, if you can’t use C++11 yet. You could try saving the value that you used to seed right before (or after) the srand. So, for example: int seed = time(NULL); srand(time(NULL)); cout << seed << endl; cout << time(NULL); The two values should be the same. I would recommend you to use the Mersenne Twister Pseudo-Random Number Generator. It is fast and offer very good random numbers. You can seed the generator in the constructor of the class very simply by unsigned long rSeed = 10; MTRand myRandGen(rSeed); Then you just need to store somewhere the seeds you used to generate the sequences… Is there a way to copy the CURRENT seed of rand() at any given time? What follows is an implementation-specific way to save and restore the pseudo-random number generator (PRNG) state that works with the C library on Ubuntu Linux (tested on 14.04 and 16.04). #include <array> #include <cstdlib> #include <iostream> using namespace std; constexpr size_t StateSize = 128; using RandState = array<char, StateSize>; void save(RandState& state) { RandState tmpState; char* oldState = initstate(1, tmpState.data(), StateSize); copy(oldState, oldState + StateSize, state.data()); setstate(oldState); } void restore(RandState& state) { setstate(state.data()); } int main() { cout << "srand(1)/n"; srand(1); cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << "srand(1)/n"; srand(1); cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << "save()/n"; RandState state; save(state); cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << "restore()/n"; restore(state); cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; cout << " rand(): " << rand() << '/n'; } This relies on: - the same PRNG being used by the C library to expose both rand() and random() interfaces, and - some knowledge about the default initialization of this PRNG in the C library (128 bytes state). If run, this should output: srand(1) rand(): 1804289383 rand(): 846930886 rand(): 1681692777 rand(): 1714636915 rand(): 1957747793 rand(): 424238335 rand(): 719885386 rand(): 1649760492 srand(1) rand(): 1804289383 rand(): 846930886 rand(): 1681692777 rand(): 1714636915 save() rand(): 1957747793 rand(): 424238335 rand(): 719885386 rand(): 1649760492 restore() rand(): 1957747793 rand(): 424238335 rand(): 719885386 rand(): 1649760492 This solution can help in some cases (code that can’t be changed, reproducing execution for debugging purpose, etc…), but it is obviously not recommended as a general one (e.g. use C++11 PRNG which properly support this).
http://w3cgeek.com/how-to-get-current-seed-from-c-rand.html
CC-MAIN-2019-04
refinedweb
1,604
66.98
xandra alternatives and similar packages Based on the "ORM and Datamapping" category ecto10.0 9.0 xandra VS ectoA database wrapper and language integrated query for Elixir. eredis9.8 0.0 xandra VS eredisErlang Redis client. postgrex9.6 6.1 xandra VS postgrexPostgreSQL driver for Elixir. redix9.5 7.0 xandra VS redixSuperfast, pipelined, resilient Redis driver for Elixir. eventstore9.4 7.6 xandra VS eventstoreA CQRS EventStore using Postgres for persistence, written in Elixir. amnesia9.3 0.4 xandra VS amnesiaMnesia wrapper for Elixir. ecto_enum9.2 2.2 xandra VS ecto_enumEcto extension to support enums in models. mongodb9.2 5.2 xandra VS mongodbMongoDB driver for Elixir. rethinkdb9.1 0.0 xandra VS rethinkdbRethinkdb client in pure Elixir using JSON protocol. moebius9.1 0.0 xandra VS moebiusA functional query tool for Elixir and PostgreSQL. mongodb_ecto9.0 0.0 xandra VS mongodb_ectoMongoDB adapter for Ecto. mysql9.0 4.7 xandra VS mysqlMySQL/OTP memento9.0 2.4 xandra VS mementoSimple Mnesia Interface in Elixir. arc_ecto8.9 0.3 xandra VS arc_ectoArc.Ecto provides an integration with Arc and Ecto. mariaex8.8 0.0 xandra VS mariaexMariaDB/MySQL driver for Elixir. exredis8.8 0.0 xandra VS exredisRedis client for Elixir. paper_trail8.7 6.8 xandra VS paper_trailEcto plugin for tracking and recording all the changes in your database. ecto_mnesia8.3 2.3 xandra VS ecto_mnesiaEcto adapter for Mnesia Erlang term database. shards8.3 2.9 xandra VS shardsTransparent and out-of-box Sharding support for Erlang/Elixir ETS tables. triplex8.2 0.0 xandra VS triplexDatabase multitenancy with postgres schemas for Elixir applications! riak8.2 0.0 xandra VS riakA Riak client written in Elixir. timex_ecto8.1 0.0 xandra VS timex_ectoAn adapter for using Timex DateTimes with Ecto. ExAudit8.0 4.7 xandra VS ExAuditEcto auditing library that transparently tracks changes and can revert them. Bolt.Sips7.9 5.3 xandra VS Bolt.SipsNeo4j driver for Elixir using the Bolt protocol. kst7.9 6.3 xandra VS kstErlang Abstract Term Database. atlas7.9 0.0 xandra VS atlasObject Relational Mapper for Elixir. redo7.7 0.0 xandra VS redoHeroku's pipelining redis client for erlang. esqlite7.7 2.2 L3 xandra VS esqliteErlang NIF for sqlite. tds7.6 6.8 xandra VS tdsMSSQL / TDS Database driver for Elixir. instream7.6 8.0 xandra VS instreamInfluxDB driver for Elixir. inquisitor7.5 0.0 xandra VS inquisitorComposable query builder for Ecto. arbor7.5 1.3 xandra VS arborEcto adjacency list and tree traversal. extreme7.5 0.0 xandra VS extremeAn Elixir library using Eventstore for persistance of events generated by aggregates (CQRS). ecto_fixtures7.4 1.0 xandra VS ecto_fixturesFixtures for Elixir apps using Ecto. mongo7.3 0.0 xandra VS mongoMongoDB driver for Elixir. kalecto7.3 0.0 xandra VS kalectoGlue between Kalends and Ecto for saving dates, times and datetimes. tds_ecto7.1 0.0 xandra VS tds_ectoMSSQL / TDS Adapter for Ecto. couchdb_connector7.1 0.0 xandra VS couchdb_connectorA connector for CouchDB, the Erlang-based, JSON document database. sqlitex7.1 4.5 xandra VS sqlitexAn Elixir wrapper around esqlite. Allows access to sqlite3 databases. boltun7.0 0.0 xandra VS boltunTransforms notifications from the Postgres LISTEN/NOTIFY mechanism into callback execution. sqlite_ecto7.0 0.0 xandra VS sqlite_ectoSQLite3 adapter for Ecto. github_ecto6.9 0.0 xandra VS github_ectoEcto adapter for GitHub API. gremlex6.8 0.0 xandra VS gremlexApache Tinkerpop Gremlin Elixir Client. sql_dust6.8 0.0 xandra VS sql_dustGenerate (complex) SQL queries using magical Elixir SQL dust. craterl6.8 0.0 xandra VS craterlErlang client for crate. neo4j_sips6.8 0.0 xandra VS neo4j_sipsNeo4j driver for Elixir. ecto_cassandra6.7 0.0 xandra VS ecto_cassandraCassandra DB Adapter for Ecto. ecto_psql_extras6.5 5.6 xandra VS ecto_psql_extrasEcto PostgreSQL database performance insights. ecto_rut6.5 0.0 xandra VS ecto_rutEcto Model shortcuts to make your life easier! triton6.4 0.7 xandra VS tritonPure Elixir Cassandra ORM built on top of Xandra. xandra or a related project? Popular Comparisons README Xandra Fast, simple, and robust Cassandra driver for Elixir. Xandra is a Cassandra driver built natively in Elixir and focused on speed, simplicity, and robustness. This driver works exclusively with the Cassandra Query Language v3 (CQL3) and the native protocol versions 3 and 4. Features This library is in its early stages when it comes to features, but we're already successfully using it in production at Forza Football. Currently, the supported features are: - connection pooling with reconnections in case of connection loss - prepared queries (with local cache of prepared queries on a per-connection basis) and batch queries - page streaming - compression - clustering (random and priority load balancing for now) with support for autodiscovery of nodes in the cluster (same datacenter only for now) - customizable retry strategies for failed queries - user-defined types - authentication - SSL encryption See the documentation for detailed explanation of how the supported features work. Installation Add the :xandra dependency to your mix.exs file: def deps() do [{:xandra, "~> 0.11"}] end Then, run mix deps.get in your shell to fetch the new dependency. Overview The documentation is available on HexDocs. Connections or pool of connections can be started with Xandra.start_link/1: {:ok, conn} = Xandra.start_link(nodes: ["127.0.0.1:9042"]) This connection can be used to perform all operations against the Cassandra server. Executing simple queries looks like this: statement = "INSERT INTO users (name, postcode) VALUES ('Priam', 67100)" {:ok, %Xandra.Void{}} = Xandra.execute(conn, statement, _params = []) Preparing and executing a query: with {:ok, prepared} <- Xandra.prepare(conn, "SELECT * FROM users WHERE name = ?"), {:ok, %Xandra.Page{}} <- Xandra.execute(conn, prepared, [_name = "Priam"]), do: Enum.to_list(page) Xandra supports streaming pages: prepared = Xandra.prepare!(conn, "SELECT * FROM subscriptions WHERE topic = :topic") page_stream = Xandra.stream_pages!(conn, prepared, _params = [], page_size: 1_000) # This is going to execute the prepared query every time a new page is needed: page_stream |> Enum.take(10) |> Enum.each(fn page -> IO.puts("Got a bunch of rows: #{inspect(Enum.to_list(page))}") end) Scylla support Xandra supports Scylla (version 2.x) without the need to do anything in particular. Contributing To run tests, you will need Docker installed on your machine. This repository uses docker-compose to run multiple Cassandra instances in parallel on different ports to test different features (such as authentication or SSL encryption). To run normal tests, do this from the root of the project: docker-compose up -d mix test The -d flags runs the instances as daemons in the background. Give it a minute between starting the services and running mix test since Cassandra takes a while to start. To stop the services, run docker-compose stop. To run tests for Scylla, you'll need a different set of services and a different test task: docker-compose --file docker-compose.scylladb.yml up -d mix test.scylladb Use docker-compose --file docker-compose.scylladb.yml stop to stop Scylla when done. By default, tests run for native protocol v3 except for a few specific tests that run on native protocol v4. If you want to test the whole suite on native protocol v4, use: CASSANDRA_NATIVE_PROTOCOL=v4 mix test License Xandra is released under the ISC license, see the [LICENSE](LICENSE) file. *Note that all licence references and agreements mentioned in the xandra README section above are relevant to that project's source code only.
https://elixir.libhunt.com/xandra-alternatives
CC-MAIN-2020-45
refinedweb
1,212
51.34
Hello,<?xml:namespace prefix = o I need to create a pdf with form fields, automatically generated, and that users can edit and save. The problem is that if I create the entire document with the class Aspose.Pdf.Pdf, I have “modify” access to the document after the document is opened with Acrobat reader, but I cannot save the data I filled in fields. I could see in forum that I have to activate “Enable Reader users to save form data » parameters, but I have not seen any property for that parameter in the namespace Aspose.Pdf.Kit or Aspose.Pdf. I wonder if we should not first create a PDF with Acrobat software such as to enable this setting, like a template, to modify the document later with Aspose. My question is: is it possible to create a pdf form with Aspose, in which the data can be edited and recorded by a user and if not, what software do you recommend to create a template of pdf ? Thanks for all. Yannick
https://forum.aspose.com/t/save-data-in-pdf-form/107577
CC-MAIN-2021-21
refinedweb
173
58.82
54 I've written a new service advertisement driver (for mdns). See <? func=detail&aid=977153&group_id=42445&atid=433166> patch includes the driver, documentation, and changes to the autoconf script (m4.d/drivertests.m4). reed -- Reed Hedges reed@... AIM: ReedHedges VOS/Interreality Project - Hi, we are trying to install librtk so that we could install player in SUSE 9.1, kernel 2.6, gcc 3.3.3, however we are having this error and we have no idea how to solve it. We had player already installed in SUSE 9.0, but we upgraded to the new one which has a better kernel and more features but we are not able to install player again. make[2]: Entering directory `/home/jose/librtk-src-2.3.0/test' gcc -DHAVE_CONFIG_H -I. -I. -I.. -I../librtk -I/opt/gnome/include/glib-2.0 -I/opt/gnome/lib/glib-2.0/include -I/opt/gnome/include/pango-1.0 -I/usr/X11R6/include -I/usr/include/freetype2 -I/usr/include/freetype2/config -I/opt/gnome/include/gtk-2.0 -I/opt/gnome/include/atk-1.0 -I/opt/gnome/lib/gtk-2.0/include -g -O2 -c test.c gcc -g -O2 -o test test.o -L../librtk -lrtk -lm -ljpeg -L/opt/gnome/lib -lpango-1.0 -lglib-2.0 -lgmodule-2.0 -ldl -lgobject-2.0 -lpangox-1.0 -lpangoxft-1.0 -lgdk_pixbuf-2.0 -lm -latk-1.0 -lgdk-x11-2.0 -lgtk-x11-2.0 -lpthread ../librtk/librtk.a(motion_est_mmx.o)(.text+0x943): In function `pix_abs8x8_xy2_mmx2': i386/motion_est_mmx.c:118: undefined reference to `bone' ../librtk/librtk.a(motion_est_mmx.o)(.text+0xc63): In function `pix_abs16x16_xy2_mmx2': i386/motion_est_mmx.c:118: undefined reference to `bone' ../librtk/librtk.a(motion_est_mmx.o)(.text+0xce3):i386/motion_est_mmx.c:118: undefined reference to `bone' ../librtk/librtk.a(simple_idct_mmx.o)(.text+0x24): In function `ff_simple_idct_mmx': i386/simple_idct_mmx.c:209: undefined reference to `wm1010' ../librtk/librtk.a(simple_idct_mmx.o)(.text+0x120):i386/simple_idct_mmx.c:209: undefined reference to `d40000' ../librtk/librtk.a(simple_idct_mmx.o)(.text+0x1de6): In function `ff_simple_idct_put_mmx': i386/simple_idct_mmx.c:209: undefined reference to `wm1010' ../librtk/librtk.a(simple_idct_mmx.o)(.text+0x1ee2):i386/simple_idct_mmx.c:209: undefined reference to `d40000' ../librtk/librtk.a(simple_idct_mmx.o)(.text+0x3bb6): In function `ff_simple_idct_add_mmx': i386/simple_idct_mmx.c:209: undefined reference to `wm1010' ../librtk/librtk.a(simple_idct_mmx.o)(.text+0x3cb2):i386/simple_idct_mmx.c:209: undefined reference to `d40000' collect2: ld returned 1 exit status make[2]: *** [test] Error 1 make[2]: Leaving directory `/home/jose/librtk-src-2.3.0/test' make[1]: *** [all-recursive] Error 1 make[1]: Leaving directory `/home/jose/librtk-src-2.3.0' make: *** [all-recursive-am] Error 2 jose@...:~/librtk-src-2.3.0> I hope someone could help us thanks Jose attached is a patch to bring player joy up to date with the unit changes in player. Toby -- Toby Collett University of Auckland Robotics Group hi, You can no longer specify the robot's size for the 'vfh' or 'wavefront' drivers in the configuration file. Each driver now gets the robot's size from the underlying position device; 'robot_radius' in the .cfg file will be ignored. This is a Good Thing, because now the robot's size only needs to specified in one place, usually either in the simulation model or hardware driver (*). If you want to pretend your robot is bigger (e.g., if it runs into things), use the 'safety_dist' option in the .cfg file to give you some wiggle room (both drivers accept this option). You might also be able to use a negative safety distance to pretend your robot is smaller, but I don't know whether that will work. I had to re-architect 'vfh' a bit, so let me know if anything's broken. brian. (*) Not all hardware drivers will necessarily return the correct robot size. In particular, the 'p2os' driver is currently always reporting the dimensions of a Pioneer 2, no matter what kind of robot is actually in use. I'll fix that. -- Brian P. Gerkey gerkey@... Stanford AI Lab hi, I've added a new driver, 'mapcspace', which support the 'map' interface. This driver takes a map (from another map device) and produces the configuration space map for a given robot shape and size. The only robot shape currently supported is "circle", for a round robot. Feel free to add support for other shapes. For example: map:0 (driver "mapfile" filename "mymap.ppm" resolution 0.1) map:1 (driver "mapcspace" map_index 0 robot_shape "circle" robot_radius 0.2) There are probably other drivers like this to be written, which perform useful operations on maps... brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab hi, (A heads-up for people using 'wavefront' and working from CVS. Hmm, this set might contain exactly one element.) I've created a new interface, 'planner', which can control a 2D motion planner. I've updated the 'wavefront' driver to support this new interface, instead of the 'position' interface (into which it had been shoe-horned). The 'planner' interface is not yet stable, as I'm figuring out what should go where. Client-side support for 'planner' is currently only done in libplayerc. brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab Player/Stage developers, Looking to use Player for a language for which there is no client yet? You might consider using SWIG, the Simplified Wrapper Interface Generator, to wrap the Player C++ library. SWIG can autogenerate Ruby, Python, Scheme, Perl, Java, Tcl/Tk, OCAML, and C# interfaces. I've created a basic Python wrap, and you can get it from: The .tgz file contains a directory, python, that is meant to be placed in player/client_libs/. See the enclosed README file for more details. Some additional work (maybe just adding a few methods) will have to be done on the C++ code to make all of the Player functions useful. But, if someone worked on this, all of the other language clients could be auto-generated any time there was a change in the base Player code. I may come back to this someday, but I thought I'd point it out to anyone considering such a port. If you are, let me know. Currently I'm bringing Boyoon's pure-Python version up to speed for Player 1.5. Wed, 16 Jun 2004, Nate Koenig wrote: > I'm trying out the new mapfile driver along with AMC Localization, and I'm > running into some problems. If I specify "enable_gui 1" and/or "alwayson 1" for > the localization interface, I get a SIGSEGV. Looks like heap corruption (pthread_create() doesn't usually segfault). Give it another try; I just fixed an off-by-one array indexing bug in the mapfile driver. To my credit, I had the following comment in the code: // TODO: debug off-by-one error(s) in this loop brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab Hi Brian, I'm trying out the new mapfile driver along with AMC Localization, and I'm running into some problems. If I specify "enable_gui 1" and/or "alwayson 1" for the localization interface, I get a SIGSEGV. I can get along without the gui, but if I create a localization proxy or include the wavefront driver then I get the same seg fault. Basically, once something tries to subscribe to the localization interface player dies. That is only my best guess. I've included a backtrace and a player config. I'll keep looking at it, but hopefully you have a bit more insight into this. Ohh, I'm running off of CVS head. Thanks, -nate Backtrace: (gdb) Player got a SIGSEGV! (that ain't good...) bt #0 0x408199f4 in pthread_getconcurrency () from /lib/libpthread.so.0 #1 0x40819838 in pthread_getconcurrency () from /lib/libpthread.so.0 #2 0x40818ef2 in pthread_create () from /lib/libpthread.so.0 #3 0x080704d7 in CDevice::StartThread (this=0xfffffffc) at device.cc:411 #4 0x080c081e in AdaptiveMCL::Setup (this=0x824c6f8) at amcl.cc:245 #5 0x0807043e in CDevice::Subscribe (this=0x824c6f8, client=0x8260ac8) at device.cc:370 #6 0x0806e5e7 in ClientData::Subscribe (this=0xfffffffc, id= {code = 25, index = 0, port = 6665}) at clientdata.cc:942 #7 0x0806e06b in ClientData::UpdateRequested (this=0x8260ac8, req= {subtype = 57920, code = 25, index = 0, access = 114 'r'}) at clientdata.cc:759 #8 0x08073e23 in parse_config_file (fname=0x8168f7d "", ports=0xbfffe320, num_ports=0xbfffe324, alwayson_devices=0xbfffe328, num_alwayson_devices=0xbfffe32c) at main.cc:860 #9 0x08074268 in main (argc=4, argv=0xbffff3d4) at main.cc:1164 Player Config: map:0 ( driver "mapfile" filename "map1.ppm" resolution 0.1 ) laser:0 ( driver "gz_laser" gz_id "laser1" ) position:0 ( driver "gz_position" gz_id "robot1" ) localize:0 ( driver "amcl" laser_index 0 odom_index 0 laser_map_index 0 enable_gui 1 alwayson 1 ) Guys, =20 Player now compiles and run under Cygwin in Windows. The only small change was the attached patch. Quick Fix and Run like a charm. Bernard Guillot Patch made with diff -up to patch "patch -p1 < cygwin.patch" from your player-src-1.5 directory diff -r -up player-src-1.5_orig/replace/replace.h player-src-1.5/replace/replace.h --- player-src-1.5_orig/replace/replace.h 2003-04-29 08:32:50.000000000 +0800 +++ player-src-1.5/replace/replace.h 2004-06-16 17:16:17.584580800 +0800 @@ -95,7 +95,11 @@ int scandir(const char *dir, struct dire #else #include <sys/types.h> #include <dirent.h> - #include <sys/dir.h> + #ifdef __CYGWIN__ + #include <mingw/dir.h> + #else + #include <sys/dir.h> + #endif #endif #ifdef __cplusplus diff -r -up player-src-1.5_orig/server/drivers/mixed/rflex/rflex-io.cc player-src-1.5/server/drivers/mixed/rflex/rflex-io.cc --- player-src-1.5_orig/server/drivers/mixed/rflex/rflex-io.cc 2003-07-17 06:44:58.000000000 +0800 +++ player-src-1.5/server/drivers/mixed/rflex/rflex-io.cc 2004-06-16 17:15:07.503809600 +0800 @@ -19,6 +19,10 @@ #include <sys/time.h> #include <sys/ioctl.h> +#ifdef __CYGWIN__ + #include <sys/socket.h> +#endif + #include "rflex-info.h" #include "rflex-io.h" Outsourced IT Management Bernard Guillot Technical Director InCore Technology Ltd #4402, Blk 44, 2/f, Baguio Villa 550 Victoria Road Pokfulam Hong Kong SAR=20 bguillot@... tel: +852 2887 2254=20 Signature powered by PlaxoWant a signature like this? Add me to your address book... hi, We've just released Stage 1.3.4. Get it from the usual place: Nothing much new here; this release is just for compatibility reasons. Stage 1.3.4 works with: Player 1.5 librtk 2.3.0 A list of compatible software bundles is forthcoming. brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab In the same way that drivers needing a map should instantiate a map device and read from there, drivers needing camera frames should instantiate a camera device, and read from there. Since Nate has recently added V4L and 1394 drivers that support the 'camera' interface, I've removed direct framegrabbing support from the 'cmvision' driver. This driver now requires an underlying camera device. For example, after creating a camera, say camera:0, you would do: blobfinder:0 (driver "cmvision" camera_index 0 colorile "colors.txt") This is untested; bug reports are welcome. brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab One more thing. If you're using a Stage-style image as a map (white obstacles on black freespace) you'll want to use the negate option, e.g.: map:0 (driver "mapfile" filename "inverted-map.ppm" resolution 0.1 negate 1) brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab hi, This is mainly a heads-up for people working from CVS. I've just added a 'map' interface. This interface allows access to an occupancy grid map. The goal is to put all the image-loading code in one place, and provide one source for map(s), reducing the likelihood of, for example, accidentally using different maps for localization and planning. A nice side-effect is that clients can also get maps, in the same way (client-side support for the 'map' interface is forthcoming). Because of the limit on Player packets, the map is not delivered as data; rather it is retrieved in successive tiles via configuration requests. I've added a driver, 'mapfile', which supports the 'map' interface, and supports loading a map from an image file, e.g.: map:0 (driver "mapfile" filename "my-map.ppm" resolution 0.1) The gdk-pixbuf-2.0 package is required to build 'mapfile'. All drivers needing occupancy grid maps should now use this interface, rather than loading image files themselves. I've updated the 'wavefront' driver, and the laser portion of the 'amcl' driver. Look at Wavefront::SetupMap() in server/drivers/position/wavefront/wavefront.cc for an example of how to use the internal Request() mechanism to retrieve and assemble a map. For example, instead of this: localize:0 ( driver "amcl" odom_index 2 laser_index 0 laser_map "my-map.ppm" laser_map_scale 0.1 ) you would now do this: map:0 (driver "mapfile" filename "my-map.ppm" resolution 0.1) localize:0 ( driver "amcl" odom_index 2 laser_index 0 laser_map_index 0 ) This setup will be in a state of flux for a while, but it should work. Let me know if you have trouble. brian. p.s. The client can no longer get the map via the 'localize' interface. -- Brian P. Gerkey gerkey@... Stanford AI Lab [I'm CCing this to the list, as I include an example, and attach some questions on method-naming philosophy. -Doug] ahoward <ahoward@...> said privately: > On Thu, 10 Jun 2004, Douglas S. Blank wrote: > > > (which would be much nicer than using the string representation of lists > > that the Player C-based pyplayer code uses). > > I'm curious: what do you mean by "string representation"? pyplayerc uses > plain Python lists. Thanks for questioning that statement! I was used to exploring Python objects via the "dir(object)" function, which lists out an object's methods and attributes. However, this doesn't show the functions that are coded in the __getattr__ C function in playerc, and I could only figure out how to get laser data by forcing a laser object into a string (I didn't think that you would have us get data that way!). Looking at the source code shows the proper way: import playerc client = playerc.client(None, "localhost", 6665) client.connect() laser = playerc.laser(client, 0) laser.subscribe("a") client.read() data = laser.scan When I'm done, I hope to also have an player/examples/python directory for the project. If there are already Python examples, please point me to them. On a different note, I know that a goal of the Player/Stage project is to create a Unix file system-like interface for robots and their devices, and that many of the devices have low-level Read/Write methods. But, it seems that each device has its own method names in the higher-level interfaces (ie, GetSonarGeom and SetLaserState in the C++ interface). Has any thought been given to trying to standardize to a smaller set of method names there as well? Like: set, get, setPose, getPose, print, config, etc. It seems that even laser and sonar devices in the C++ interface have very differently named methods. In using Player/Stage for teaching robotics, it would be nice if those objects that share many attributes (range sensors) shared method names. I think I'd rather see methods like: object.get("capacity") and object.get("state") rather than having each device have different method names like object.getLaserState(). These could be added in addition to the current methods, as to not break existing code. Or maybe I'm just not seeing such an interface? Thanks again, -Doug > > >>> -- Douglas S. Blank, Assistant Professor dblank@..., (610)526-6501 Bryn Mawr College, Computer Science Program 101 North Merion Ave, Park Science Building Bryn Mawr, PA 19010 dangermouse.brynmawr.edu... Thanks, Thu, 3 Jun 2004, Kratochvil, Bradley Eugene wrote: >. Thanks for noticing and tracking that down. The best fix is to add the following line to server/Makefile.am: player_LDFLAGS = -rdynamic Then 'rm server/player' (assuming that you've already built it), and 'make'. I've made this change in CVS; it will appear in the next bugfix release, which probably won't be too far off (has noone found bugs in the C++ client lib yet?). brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab Hello, I've been working on the changes/additions to the position interfaces that I mentioned last week, and I think I've come up with a fairly good solution. I tried to strike a balance between getting the correct functionality and having the least amount of code to be rewritten. I have come up with the following idea: In all the following interfaces, I have switched the internal player angle measurements (formerly degrees and arc-seconds) to the standard radians. To keep things straightforward on the server side, the data kept in the driver is in milliradians (similar to the way mm are stored for distance). This means they'll stay as int32_t and be easy to pass around on the wire. If they are stored in mrad then the maximum resolution we can achieve is roughly .06 degrees, which should be sufficient in most applications. If anyone had another idea on how to best store the angle measurements, I'm all ears. This just seemed to fit best with what we currently have. It's also nice on the client side because all the data (both distance & angular) is now multiplied by 1000. I've come up with 2 new interfaces, "motor" and "position2d," and propose slight changes to "position3d." In order to control simple rotational devices (like a turret for a sensor), I've created a new interface called "motor." This interface is very similar to the position interface except that it only has one position and velocity parameter, theta. You'll be able to set PID, position control, velocity control etc... Position2d was conceived as a way to make an interface change while keeping the amount of current code that needed to be changed to a minimum. It's basically just a copy of the "position" interface with the internal angle measurement kept as radians (mrad). The new naming seems to make sense (Position2d/Position3d). I thought this would be a good way to help motivate people migrate their existing clients and drivers to a more unit friendly interface without breaking all the code and forcing people to. Eventually, the old position interface could then be deprecated. I would like to make some changes to Position3d, which include switching the angular units, as mentioned above, along with adding some of the other configuration options of the "position" interface such as setting ramp parameters, odometry set, odometry reset, etc. The only change that would require change to existing drivers would be the change of angular units from arc-seconds to mrad. If you're curious for some actual code, I've got a copy of my new player.h at I was working on this today, and I have the c libraries/tests for all of these finished, and have yet to do the c++ ones which shouldn't take that long tomorrow. I will hopefully be able to submit a patch in the next few days with all the working code. Any suggestions are more than Best regards, Brad Hello all, This is because when the library is loaded using dlopen:. I looked through the old makefiles of Player 1.4 and it seems that RTK_LDADD was including the -rdynamic flag in the linking stage, and now it isn. Best regards, Brad hi, I saw this note in the latest update from SF.net, regarding CVS access: Developer CVS check-in/check-out is getting a major speed increase in the next 5 weeks. Anonymous check-out has been performing great and soon SSH check-ins/check-outs will have similar speeds. With this upgrade are also eliminating the 5 to 8 hour delay that currently exists between developer check-in and anonymous check-outs. Everything will be in real-time. This means as soon as you make a code change, your users can grab the latest code. This will mark the completion of our long-term CVS infrastructure improvement project. I wasn't aware of this delay until now, and it's a good thing to keep in mind when debugging on HEAD. The issue should be resolved some time relatively soon, but I've seen SF.net miss such self-imposed deadlines before... brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab On Tue, 1 Jun 2004, Kratochvil, Bradley Eugene wrote: > As I've previously mentioned in the users list, I'm hoping to work on > the position & position3d interfaces to standardize/extend them a bit. > The main portion of the work will be adding similar configuration > options to the position3d interface as the position interface. > > First off, I was wondering if anyone else is actively working on these > interfaces. No sense in duplicating work. Not me. > Second, has there been any major changes to these interfaces since > 1.4rc2? I'm having a problem with the cvs server right now and can't > get at the current code. You can now start working with 1.5. > Finally, I plan on making these changes in the server side as well as > the C & C++ clients. I'm going to do my best not to break any of the > other client libraries. I was planning on writing a changelog that > listed the exact changes made. > > If anyone has suggestions on extensions/standardizations they would like > on the position or position3d interfaces, please let me know. We really > need these changes for our application, but I figured as long as I'm > going to the work I might as well make it as useful to everyone else as > possible. I don't have a particular wish list. In general, new functionality and/or standardization/normalization in an interface is good, as long as it doesn't come at the expense of "normal use." For example, the reason to have separate 2D and 3D position interfaces is that almost everyone only need (X,Y,yaw) info for their planar robots, and sending (X,Y,Z,roll,pitch,yaw) back and forth all the time is waste of bandwidth. Send in your patches, and I'll consider for inclusion in the tree. brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab On Wed, 2 Jun 2004, Kratochvil, Bradley Eugene wrote: > >SourceForge CVS access has been extremely flaky of late. Assuming you > are > >following the instructions on the web page, I can only suggest that you > >keep at it. For non-anonymous access, I generally have to try 3 or 4 > >times in a row. > > I cut and paste the login cvs line from the web. If I try the same > command line, but log into the gaim cvs root, I have no problems. I've > tried back at several different times during the day with no luck. Has > anyone else run into this problem (or better yet a work around)? Sorry, don't know what to tell you. We don't have any control over that kind of thing. We just kind of pray that SF.net works. Your best bet is to troll through the existing support requests (aka bug reports) at SF.net, and post your own if they don't already have a "Master Bug Report" that covers this problem. brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab *************************************************** * What happened: *************************************************** I said this in the release announcement, but I want to be sure that people are listening: units in the C++ client library have been normalized to MKS. This means that positions, angles, and their time derivatives are specified in meters and radians. If you use the C++ client library, you will need to change your code. The compiler may tell you about some of the changes, but it won't catch all of them, even with all warnings turned on. PLEASE go through your code and change it, before you send your robot off at 200 meters/sec! I have likely introduced some bugs in making these changes; help me by making bug reports (preferably with patches to fix them) to our bug tracker at SF.net. *************************************************** * Rationale: *************************************************** Up until now, different proxies have used different units, which is a big source of bugs. And some proxies have been very thin wrappers around the Player protocol, exposing Player's own strange units, like 1/3600 of a degree to measure angles. Units like this are chosen for convenience and efficiency over the network; there's no reason to make programmers work with them. *************************************************** * Examples: *************************************************** So, to make your robot go 200 mm/sec, you used to do this: pp.SetSpeed(200,0); You now do this: pp.SetSpeed(0.200,0); Similarly, to make your robot turn at 45 deg/sec, you used to do this: pp.SetSpeed(0,45); You now do this: pp.SetSpeed(0,M_PI/4.0); Actually, I usually employ the RTOD() and DTOR() macros, which convert between radians and degrees: pp.SetSpeed(0,DTOR(45)); These macros are defined in <playercommon.h>, which is included for you by <playerclient.h>. brian. -- Brian P. Gerkey gerkey@... Stanford AI Lab Player 1.5 has been released. You can get it in the usual place: Please read the release notes: They are also appended below, for better readability (SF.net's HTML-rendering seems to broken at the moment; yar). PLEASE NOTE THE NORMALIZATION OF UNITS IN THE C++ CLIENT LIBRARY: YOU WILL HAVE TO CHANGE YOUR CODE. Sorry, and please don't complain. brian. ------------------------------------------------------------------------------- Compatibility: * Player 1.5 is compatible with librtk 2.3.0 (it's really compatible with librtk 2.2.0, but Player now relies on pkg-config metadata to find librtk, and this metadata is only included in librtk 2.3.0) * Player 1.5 is compatible with Gazebo 0.4.0 * Player 1.5 is mostly compatible with Stage 1.3.3. The only problem is that the position set odometry configuration will not work in Stage. Client lib changes: * C++: All units are now MKS: distances are in meters, time in seconds, and angles in radians. Note that almost everybody will have to change existing C++ code. Sorry, but it's worth it! * C++: Added AIOProxy, to handle 'aio' (analog I/O) data, and made DIOProxy::Print() look nicer. Thanks to Brad Kratochvil. * libplayerc: added support for 'ir' and 'bumper' interfaces, and support to playerv for visualizing them. Thanks to Toby Collett. * C++: fixed several signed/unsigned bugs in TruthProxy. Thanks to Cameron Morland. * C++: fixed cast to get full precision in angles. Thanks to Toby Collett. * C++: enhancements to IRProxy::Print(). Thanks to Toby Collett. * C++: Initialize SonarProxy::range_count to 0. Thanks to Cameron Morland. New drivers: * 'sickpls', which controls a SICK PLS laser range-finder, via the 'laser' interface. This driver will soon be merged with the existing 'sicklms200' driver. Thanks to Yannick Brosseau. * 'ptu46', which controls a Directed Perceptions ptu46 pan-tilt unit, via the 'ptz' interface. Thanks to Toby Collett. * 'khepera_position' and 'khepera_ir', which control the K-Team Khepera mobile robot, via the 'position' and 'ir' interfaces (experimental). Thanks to Toby Collett. * 'flockofbirds', which controls an Ascension Flock of Birds 6-DOF tracking system, via the 'position3d' interface. Thanks to Toby Collett. * 'er1_position', which controls an Evolution Robotics ER1 mobile robot, via the 'position' interface. Thanks to David Feil-Seifer. * 'rflex_ir' and 'rflex_bumper', which control the IR and bumper arrays on a RWI B21 mobile robot, via the 'ir' and 'bumper' interfaces. Thanks to Toby Collett. * 'p2os_gyro', which controls the gyro that accompanies some ActivMedia Pioneer 3 mobile robots, via the 'position' interface (highly experimental). * 'camerav4l', which supports image acquisition from Video4Linux; the images are made available through the new 'camera' interface. * 'clodbuster', which controls the UPenn Clodbuster mobile robot, via the 'position' interface. Thanks to the UPenn crew. * 'upcbarcode', which find UPC-style barcodes in camera images, and reports them via the 'blobfinder' interface. * 'cmucam2', which controls a CMUCam2, reporting the data via the 'blobfinder' interface. Thanks to Pouya Bastani. * 'nomad', 'nomad_position', and 'nomad_sonar', which control a Nomadics 200 mobile robot. Thanks to Pawel Zebrowski. * 'laservisualbw', which finds black and white combined laser-visual fiducials. New interfaces: * 'camera', which provides raw images as data. Really only meant for internal use among drivers within a server. Though it can be used by the client, if Player is configured with the --enable-bigmess option. * 'nomad', which provides access to Nomad-specific info, and is mostly used by the nomad_position and nomad_sonar drivers. Interface changes: * position: The 'theta' field of the set-odometry request is now a signed int, rather than an unsigned short. Note that this makes this request NOT work with Stage 1.3.3. * sonar: maximum number of sonars is now 64, rather than 32. * ir: maximum number of IRs is now 32, rather than 8.
https://sourceforge.net/p/playerstage/mailman/playerstage-developers/?viewmonth=200406&page=1
CC-MAIN-2017-47
refinedweb
4,839
58.89
[ Jeremie writes: ] "Welcome! This message is from the Jabber.org project, and is intended to provide a current overview, for both technical and non-technical users, of the many related technologies, projects, and plans for Jabber. "What is Jabber?" Many think of Jabber as just an instant messaging client/server, but in fact it's much more. At the core, Jabber is an extensible architecture to flexibly route XML data instantly between any two points. The primary use of Jabber is as a platform for communicating instant messages and broadcasting presence. But the set of tools and technologies being continually developed at Jabber.org also have the flexibility to do much more than a simple buddy list application. The Jabber project has made incredible and substantial progress over the last year. It started as a few prototypes in 1998 and was announced to the world at the start of 1999 on Slashdot.org. Since then we have had three major revisions and the architecture has matured significantly. Commercial interest in Jabber has also grown significantly. The first company to step forward and support the project is Webb Interactive Services, with an interest in helping advance XML as an open messaging platform. There's also been interest in using Jabber as a platform for instant messaging for ISPs and portals, which we welcome all involvement in. If you represent commercial interest, we are developing a special site for you at to answer some of your questions and list others involved. The following sections represent the general categories of Jabber development. The basic network connection in Jabber is an "XML Stream," a simple and powerful concept of unifying an XML document and simple TCP/IP socket. On top of XML Streams, any application can layer their own XML data in a namespace to be streamed between the two points. In Jabber, we use a basic protocol consisting of messages, presence, and queries. Within each basic Jabber protocol type, any application can further embed it's own XML data protected in a namespace. The server side of Jabber has been the focus of the core development team, and includes jserver (the application Jabber clients connect to), etherx (an XML Stream 'router' of sorts), and modules (used within jserver to extend functionality). Version 0.8 of the server side tools, which was released in the first week of December, bundled full functionality for deploying instant messaging, presence, and buddy lists. The current plan is to get a 0.9 version, which has a better build system and will work on more platforms, out shortly and release a 1.0 server in January. The long-time clients include zABBER (Tcl/Tk) and Cabbar (GTK+), and the new clients are WinJab and Jabba, both for Windows. Clients are also being developed to accompany many of the libraries described below. A "transport" within the Jabber architecture is a server-side, special purpose engine that can interact with the rest of Jabber and has its own namespace. This is used to gateway transparently to other instant messaging networks or information sources. Development is progressing on an AIM and Yahoo! transport, which both have working versions available, with ICQ and MSN not far behind. An IRC transport has been discussed that can participate as a server within an IRC network, and allow Jabber and IRC users to communicate transparently (any experienced individuals that want to take the lead on this, join us in #jabber on the OpenProjects network - try irc.linux.com). There are numerous other transports planned including SMTP, RSS, talk/finger, news/stock tickers, and more. There is always a need for more help in every aspect of any open development project, but a few key areas we could use some talented help on include: Administrative: team@jabber.org General: info@jabber.org irc.openprojects.net #jabber Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
http://www.linuxtoday.com/developer/1999123000904OS
CC-MAIN-2014-23
refinedweb
655
54.63
Political Hopes Laura K. Field Rhodes College ‘‘generalizable’’ to all political endeavors. In studying Cyrus’ case, we deepen our thinking about civic education, justice, rule, freedom, and the law—matters that Cyrus neglected—and are led to prudential insights that are vital to the cultivation and support of healthy politics. 1 See Nadon (2001, 1–25) for a thorough account of the history of Xenophon scholarship (an account which informs my comments here). Nadon’s introduction also includes a helpful treatment of contemporary pieces on the Cyropaedia, and a rich discussion of ‘‘Machiavelli’s Cyrus.’’ See also Whidden (2008, 32–36), Johnson (2005, 181), and Howland (2000, 875–76). 2 Unless otherwise noted, all subsequent citations are to book, chapter, and (when appropriate) section numbers of the 2001 Wayne Ambler translation of the Cyropaedia (The Education of Cyrus). The Journal of Politics, Vol. 74, No. 3, July 2012, Pp. 723–738 doi:10.1017/S0022381612000424 Ó Southern Political Science Association, 2012 ISSN 0022-3816 723 724 laura k. field of Cyrus’ posthumous empire (8.8).3 For the most The answers offered by the Cyropaedia seem to enthusiastic supporters of Cyrus, the conclusion of hinge upon the narrative structure of the book. In his the book is bound to seem tragic. At the very least, it 1996 article and 2001 book, Nadon suggests that the is a genuine letdown. Over the course of the last disheartening closing chapter of the Cyropaedia is not century, some interpreters have been tempted to an anomaly, but is well-foreshadowed by Xenophon suggest that the book is ultimately incoherent, or if one attends to the rest of the text. A careful that the last chapter is in some ways spurious, since study—which he goes very far in providing—reveals Xenophon’s intention could not have been to ques- Cyrus’ many troubling characteristics. But Nadon tion Cyrus’ standard-setting role. I join several other goes further. To him, the disappointing conclusion to more recent commentators in defending the coher- the work not only casts Cyrus’ accomplishments into ence of Xenophon’s book, but the grounds for my doubt, but also encapsulates Xenophon’s thorough reading, and its implications, differ in significant disenchantment with political life as such; in light of ways from theirs. I disagree with the suggestion made the closing chapter, the book as a whole can be read by Due (1989, 19 and 237) and Sage (1994, 161–74) as ‘‘a critique of politics, tout court’’ (Nadon, 1996, that the austere ending of the Cyropaedia highlights 373; 2001, 164 and 178). Though Nadon concedes the justice and excellence of Cyrus’ life by contrasting that the Cyropaedia remains outside the range of it with the chaos that ensued after his death. Nor do I tragedy strictly speaking (since Cyrus is too wily and believe that Xenophon’s Cyrus represents an idealized Odyssean to be a tragic hero; 2001, 100), towards the political type, whose image is subtly challenged by end of his commentary, he nevertheless employs the Xenophon’s historical realism only retrospectively in language of tragedy to explain Xenophon’s main the final chapter (see Tatum 1989, 238), or that Cyrus intention: represents an ambiguous Machiavellian ideal of be- Xenophon may tempt us with the charms of an nevolence and despotism that makes his legacy entirely austere and virtuous republic devoted to producing fitting (see Gera 1993, 297–98; see also Danzig 2009 good men, or with the portrait of a perfect prince for a similar outlook on Cyrus). Rather, I argue that capable of governing the entire world; he may engage the bleak finale casts a shadow back over the rest of our deepest passions for justice, glory and unlimited the text, somewhat like a Platonic aporia, and acts as wealth; but he then purges them by demonstrating a deliberate invitation to consider the book and its the impossibility, and even the undesirability, of their complete fulfillment (1.6.19). (2001, 179) protagonist anew. This interpretation is more in line with that of Christopher Nadon. In important re- To Nadon, the book has the effect of purging our spects, however, I disagree with Nadon and others deepest political passions, just as, according to about where such a reconsideration leads us. The dis- Aristotle’s Poetics, tragedy purges our hopes and agreement concerns two questions that are of funda- fears. In a similar vein, W. R. Newell suggests that mental importance to us as political theorists, citizens, ‘‘neither republic nor empire—the two archetypal and human beings: how legitimate are our hopes for possibilities presented by the Cyropaedia—can pro- real improvement in politics? And, can philosophy mote the fullest human satisfaction. . . . Within the help us to understand how healthy political life might realm of politics simply speaking, it appears that the be cultivated and preserved? longing for the noble can have no issue’’ (1983, 904– 905). Historian Robin Waterfield suggests in his 2006 book on the Anabasis that Xenophon became de- spondent about politics and turned to the scholarly 3 It is important here as elsewhere to distinguish Xenophon’s life as a response (see 2006, 192). Christopher Whidden Cyrus from the historical figure. Historically, the empire lasted comes to a similar conclusion, stating that ‘‘if at the long after Cyrus’ death, since it still existed during Xenophon’s beginning of his intellectual odyssey Xenophon was time and posed an enduring threat to Greek stability. In his final chapter, however, Xenophon relates that, when Cyrus died, ‘‘his optimistic that wisdom can provide salvation for sons immediately fell into dissension, cities and nations imme- political life, throughout the Cyropaedia he shows the diately revolted, and everything took a turn for the worse’’ reasons for rejecting his opening hypothesis. He con- (8.8.1). The chapter is a careful delineation of the character of this decline and emphasizes not only the moral decline of the cludes that wisdom is no match for and thus cannot Persian rulers and their subjects, but also the pervasive sense of tame politics’’ (2007, 567). Whidden looks at Xeno- instability brought about by the moral disorder. This exagger- phon’s Cyrus through an Aristotelian lens and finds ation highlights Cyrus’ ultimate failure in a way that a more still further evidence for the ‘‘ancients’ sober resigna- accurate portrait could not have matched. For an alternative interpretation of Xenophon’s account of Persian corruption, see tion’’ with regards to political life’’ (2008, 62). Accord- Reisert (2009, 306–12). ing to these commentators, Cyrus represents the very xenophon’s cyropaedia 725 best one can expect from politics, and the best none- education (see 1.1.6). I then turn to consider some theless proves deeply problematic.4 episodes that demonstrate the extent of Cyrus’ psy- Though recent studies on the book have much to chological insight into others, and how this serves him offer, there is a growing consensus that Xenophon’s as a ruler, before turning in the third part to consider perspective on politics was, or at least became, wholly elements of Xenophon’s account that reveal the limits negative. According to these interpreters, Xenophon of Cyrus’ psyche. In light of insights gained in the early wishes to purge our passion for politics, because wisdom sections regarding Cyrus’ education, reign, and char- is incapable of taming the political world; he rejects acter, I finally turn to present my own interpretation optimism and instead promotes realistic disenchantment of the work’s meaning and purpose. and sober resignation; he encourages a full retreat to the private, contemplative life. While my reading agrees with the body of work that defends the Cyropaedia as a subtle Education or Corruption? and coherent whole, it challenges these reigning inter- pretive conclusions. This article aims to demonstrate First, then, let us turn to Xenophon’s opening that a negative assessment of Cyrus hardly need translate description of Cyrus’ ‘‘birth, nature, and upbringing’’ into tragic resignation regarding political life in general. (1.1.6), which spans the first Book of the Cyropaedia. The meaning of the Cyropaedia clearly depends From the outset, the portrait of Cyrus contains subtle on what Cyrus represents: if he represents the best ambiguities that raise questions, and also provide possible ruler, who nevertheless proves inadequate, early clues, about how we should interpret his then the failure and demise of his empire represents character. First, Cyrus’ parentage is called into ques- the tragic, inevitable, and predictable result of all tion when we are told that ‘‘Cyrus’ father is said to political endeavors. But if Cyrus is a man with great have been Cambyses [the King of Persia]’’ whereas potential, who nevertheless misses the mark for detect- ‘‘his mother is agreed to have been Mandane’’ (1.2.1). able reasons, the outcome of the Cyropaedia can be seen A tension is hereby acknowledged between the as far less inevitable. Cyrus’ ‘‘education’’ takes place reputed austerity of Old Persia and some, at least, against a dramatic background that is sufficiently of its mores. Second, by switching to the third coherent psychologically so as to guide our judgment person, Xenophon introduces an element of hearsay of the book’s principal figure quite narrowly. In a into his account of Cyrus’ nature. And third, while manner comparable to other ancient authors in the for the most part it is a very elevated portrait—Cyrus Socratic tradition, Xenophon concerns himself with is said to have earned a remarkable reputation among the wide spectrum of human longings, hopes, and the Persians and is remembered for his beauty, fears. In the Cyropaedia, these themes are discussed by benevolence, curiosity, and ambition—Xenophon also Xenophon as narrator (in rare but important pas- notes that Cyrus was willing to risk anything for the sages), as well as by the characters Xenophon depicts; sake of praise and honor (1.2.1). Even from a they are also illuminated by Cyrus’ unfolding story and preliminary perspective it is questionable whether this its adjoining dramas. By drawing on all three dimen- kind of risk taking is praiseworthy in itself. In the sions of the work, it is possible to give an accurate opening passage of the work, then, Xenophon inti- characterization of Cyrus’ strengths and limitations. mates that there is a streak of corruption in the Persian My argument is that Xenophon’s work is at regime and that there is some tension between the bottom so seriously critical of Cyrus’ rule that the myths about Cyrus’ nature and his own view. ending of the book must be considered a wholly In the very next section, Xenophon turns to Cyrus’ fitting one, and further that the question of whether a formal Persian education, and here further questions wiser man, or a Cyrus under different circumstances, emerge. Cyrus’ early education in Persia is an education could have succeeded where Xenophon’s Cyrus failed in austerity and basic law-abidingness. The account of must be considered open. To make my case for such this education is contained in three pages (1.2.2–12), a openness, I begin by exploring the brief but revealing brevity that replicates the austere simplicity of the account of Cyrus’ childhood and youth, which serves Persian way of life, which seems to involve a long chain to illuminate Cyrus’ lineage, ‘‘nature,’’ and early of personal hardship and strict obedience to the law. Citizens spend almost all of their time, from a very young age, engaged in common, public activity char- 4 Even Robert Faulkner—whose recent book, The Case for Greatness, acterized by extreme continence and an economy of contains a nuanced interpretation of the Cyropaedia and a powerful critique of Cyrus—insists that Cyrus’s political quest proceeded honors. There is training in the punishment of injustice ‘‘without failures or mistakes, strategic or otherwise’’ (2007, 127). and ingratitude (1.2.6–7), and training in hunting, 726 laura k. field which is seen as preparation for war (1.2.10). The aim Cyrus claims that the episode taught him all about of the education seems to be respect for the laws, in justice. Once, acting as judge among his peers, he was conjunction with a submission of the self. Xenophon beaten for ruling in favor of distributing goods describes a life devoted exclusively to bodily preserva- according to need, but contrary to the laws of owner- tion and justice understood as obedience to the laws. ship; the beating taught him that justice requires strict Cyrus himself is undaunted by the many basic adherence to the law, even against what is fitting, for, challenges presented by the Persian way of life. It is according to the Persians, the fitting often proves clear that Cyrus has extraordinary natural capacities unlawful and violent (1.3.17). When Mandane points that emerge early on (see 1.3.1); that he has ambitions out to Cyrus that the laws in Media are different—that, and talents beyond those supported in Old Persia is in contrast to the equitable laws of Old Persia, every- clear upon his arrival in the more urbane nation of his thing in Media is oriented towards the gratification of mother’s family. Cyrus’ natural gregariousness com- the tyrannical king—Cyrus’ clever reply betrays the bined with his cultivated Persian continence are soon shallowness of his commitment to the lawful (see put to use to make him a great favourite with his 1.3.18). Not for the last time, Cyrus’ prudent charm grandfather Astyages, King of Media, as well as with the allows him to dodge serious questions about justice. people of Media. Cyrus is impressed with the riches Over the course of his stay in Media, as Cyrus he sees in Media, but does not seem to be desirous of repeatedly encounters the community’s demand for the material benefits that he encounters there, and as discipline and restraint, his internal development takes such is able to display a great deal of warmth and the form of an ongoing struggle between his unruly generosity towards others (see 1.3.2, 1.4.1). Media also desires, his growing self-consciousness in relation to presents Cyrus, who is called a lover of learning by others, and his prudence. He learns to get past his own Xenophon in this context, with many new opportu- self-consciousness and vulnerability by developing nities to educate himself (see 1.3.15, 1.4.3; compare prudent shame and humility (see 1.4.4, 1.4.15) and 1.2.6). In Media, there is ample room for Cyrus to becoming ‘‘a Sakas to himself’’ (1.4.15). He also escape the deep-seated rigidity of the Persian laws and develops a surprising mercenary streak—learning to tradition—his sense of personal strength and his use men like Sakas and the King to his own ultimate natural benevolence can be exercised there in a way advantage (1.4.6, 1.4.12–13). Though this does not that was not possible in Persia—however, Cyrus also diminish his actual dependence on others, as he is finds himself newly confined with regards to what he more at the mercy of public opinion than ever (see can accomplish with impunity. Cyrus’ animosity to- 1.4.13), it does perhaps serve to obscure it. His self- wards his grandfather’s servant Sakas is the most control and prudence continue to develop during this obvious example of such a limit. It infuriates Cyrus to period and serve to check some of his more impetuous discover that his grandfather’s love is finite (contra and ambitious instincts. Reisert 2009, 301), and he soon seeks to take Sakas’ We learn in the course of Book 1, Chapter 4, place in his grandfather’s affections (1.3.11). Ultimately, however, that Cyrus’ natural exuberance is never fully of course, Cyrus will seek to supersede Astyages. quelled in Media: the naturally exuberant Cyrus The danger that Media poses to Cyrus’ Old Persian repeatedly faces external constraints and conventions, virtue does not go unnoticed. Before leaving him in and, through growing prudence and an irresistible Media ‘‘to be raised’’ (1.4.1), Cyrus’ mother Mandane charm, he manages to break through unbowed (see, registers a major reservation: how will Cyrus learn justice for example, 1.4.8–10). Such experiences culminate in in Media when his teachers are in Persia? This question, an incredible act of military boldness when Median which Mandane poses to Cyrus directly, leads to Cyrus’ lands are invaded by the Assyrian Prince (1.4.16–24). famous recollection of an incident from his youth At the time in youth that ‘‘seems especially in need of involving the just distribution of tunics (1.3.16–18).5 care’’ (1.2.9), ‘‘just as a well-bred but inexperienced dog rushes without forethought against a boar’’ (1.4.21) and ‘‘mad with daring’’ (1.4.24), Cyrus 5 For alternative accounts of this incident, see Nadon (2001, successfully leads the Median cavalry against the 47–48), Newell (1983, 896–97), Gera (1993, 75) and Danzig (2009). Most commentators take Cyrus’ youthful understanding Assyrians. The ultimate implications of this act of justice—as that which is fitting—to be correct and to represent (which humiliates the young Assyrian Prince on the a natural standard against which conventional laws come to light threshold of his marriage and likely contributes to his as harsh and injurious to the individual. In my mind this becoming a particularly vicious despot) emerge only formulation pits natural justice too starkly against convention and fails to appreciate the extent to which conventional agree- gradually over the course of the book, but it is ment contributes to our living well, and indeed justly, together. immediately clear that Cyrus’ risk taking on this xenophon’s cyropaedia 727 occasion is more than even his doting Median family Reisert 2009, 311–15). There is no mention of him in will tolerate. He is sent home. the description of Cyrus’ early childhood, and he In the dense first book of the Cyropaedia, we can makes no objections to Cyrus’ being raised in Media see the general character of the dynamics at play in (1.4.1) despite its being contrary to tradition (see Cyrus’ soul. He is well-born and is shown to have a 1.2.15; compare also Mandane’s claim that Cambyses very impressive nature; he is called a lover of learning, always obeys the laws, 1.3.18). Furthermore, he is under certain circumstances is capable of great pleased upon learning of Cyrus’ rash behavior there, degrees of self-control, but is also bold and spirited though ultimately he recognizes some need for Cyrus to the point of recklessness. Cyrus is driven by a to return home to fulfill what was ‘‘customary among powerful desire to be seen as best and most benev- the Persians’’ (1.4.25). Cyrus’ education does con- olent in all things and thus to be the most beloved of tinue in Persia, but not according to custom (see all human beings. As Xenophon’s Socrates argues, it 1.6.12–14, compare 1.2.9–14). When Cyrus is chosen is precisely those who are the most gifted who are in as the ruler of the expedition to defend Media against danger of becoming the most harmful through lack of Assyria, Cambyses is apparently supportive, as evi- education and learning (Memorabilia, 4.1.3–4, see denced by the long strategic, or ‘‘calculative,’’ discus- also Plato’s Republic, 491d–492e). Because of his great sion between them that closes Book 1, and includes nature, Cyrus arguably needs a good education more references to similar prior conversations at 1.6.3, than most, and it is far from clear that he gets it in 1.6.5–8, 1.6.12–15, and 1.6.43 (compare Republic, Persia or Media. The education in Old Persia is 550b). Whidden argues that this is ‘‘the capstone in excessively negative, focused narrowly on obedience a long series of rather philosophic conversations and the body, and even tinged with brutality (see 1.2, between father and son’’ and ‘‘it is not as though on entire). In Media, Cyrus’ development proceeds largely a single occasion Cambyses tried to moderate his son unchecked for several years, and here our questions and failed’’ (2007, 560). But it is not entirely clear that about his education grow more acute. Cyrus receives Cambyses is trying to moderate Cyrus. While Camb- no guidance or admonishment while there. Instead, he yses has Cyrus agree that taking good care of oneself is builds favor with his grandfather the king, and gains ‘‘sufficient and noble work for man,’’ the next agree- influence over all with his natural gifts and charms. He ment he gains concerns the wondrous character of alleviates his dependence on others primarily by caring for others (1.6.7). Furthermore, Cambyses’ long making them beholden to him. Indeed, Cyrus’ form speech at 1.6 begins: ‘‘That the gods send you forth of benevolence, to the extent that it is not informed by propitiously and favorably is clear son, both in the real wisdom, may be of the most harmful variety, since sacrifices and from the heavenly signs’’ (1.6.2). This it directly threatens others’ freedom. There is no hint powerful endorsement is followed by the reiteration of from Xenophon that Cyrus ever recognizes the tension a fatherly lesson on taking care of the divinations between his benevolent goals and his lawless manner oneself. of accomplishing them. In this, Cyrus manages to Though Cambyses does go some way towards avoid thinking through the tensions between his own discussing the ends of politics with his son (1.6.7), he political aspirations and the needs of those whose falls short of having Cyrus question the coherence of affection he seeks. The same is true upon his return his own actions and ends, and does not shy away home to Persia. from supportive lessons in political ambition. For the If there is one person who seems capable of most part Cambyses ratifies previous advice about the bringing a greater degree of self-awareness to Cyrus practical business of campaigning and adds new upon his return to Persia, it is Cambyses, the Persian Machiavellian insights about gaining the advantage king and Cyrus’ father. Cambyses is interesting over enemies through deception and manipulation. because he is one of several figures who call to mind He concludes with a message about the limits of hu- Xenophon’s Socrates. Christopher Whidden goes so man knowledge and the many failures of men (1.6.46, far as to suggest not only that Cambyses is meant to see Memorabilia 1.1.8). This may have been intended as represent a philosophic type, but that any failure on a message of moderation, but it might also be read as at his part to transform Cyrus indicates the incorrigi- least partly ironic given the character of the speech’s bility of Cyrus’ nature (2007, 560). Christopher beginning. Cambyses’ influence, therefore, is rather Nadon suggests that the limits pertain to rational mixed. He is largely absent throughout Cyrus’ child- discourse itself (2001, 178). But the extent and nature hood and never tries to dampen Cyrus’ ambitions to of Cambyses’ involvement with his son’s education dominion in any obvious way, nor does he turn him are in fact both difficult to discern (on this point, see towards other kinds of pursuits and interests, including 728 laura k. field the pursuit of self-knowledge.6 Thus, by the end of his psychological machinations. I will consider some of Persian education, Cyrus is well-prepared to fulfill his the passages that best reveal Cyrus’ capacities in this youthful pledge to return to Media (1.4.26–28). The regard, before turning to consider Xenophon’s com- final departure from Persia highlights the inability of plex exploration of the limits of Cyrus’ outlook. the Old Persian regime to deal with powerful individ- Ten years pass between Cyrus’ departure from ual ambition internally. Media and his being appointed general of the Persian At the end of the first chapter of the Cyropaedia, army. As his first speech to his two hundred men and in keeping with the book’s title, Xenophon shows, by the time his own political ‘‘opportunity’’ suggests that Cyrus’ ‘‘birth, nature, and education’’ arises, Cyrus has had much time to formulate his will be the main themes of the whole book (1.1.6).7 It aspirations and to plan accordingly. These ambitions is perhaps surprising, then, that by the end of Book 1, are extraordinary and, once brought into play, irrever- Cyrus is leading the Persian army as general and that sible. The speech takes aim at the core of the ancient the remaining seven books tell the story of his con- Persian establishment. Cyrus argues that all their quests. Of course, Cyrus will continue to learn over the practice of virtue has had no proper purpose until course of his campaigning career, but through the now: ‘‘I do not think human beings practice virtue in brevity and sparse content of the account of his formal order that those who become good have no more than upbringing, Xenophon raises questions early on about do the worthless. Rather those who abstain from the the adequacy of Cyrus’ ‘‘education.’’ pleasures at hand do so not in order that they may never have enjoyment, but through their present continence they prepare themselves to have much more enjoyment Cyrus’ Psychological Prowess in the future’’ (1.5.9). The enjoyments Cyrus then lists as Unleashed possible ends include ‘‘many and great goods,’’ such as wealth, happiness, and great honors both for themselves and their city (1.5.9). That attaining such pleasures will For all the lurking uncertainties, Xenophon makes it not occur without great sacrifice and pain is quietly clear that Cyrus is a capable psychologist when it acknowledged by Cyrus at the end of his speech, where comes to those over whom he rules.8 While his own he explains that ‘‘lovers of praise must of necessity take goals remain static, Cyrus is portrayed as a diligent on with pleasure every labor and every risk’’ (1.5.12). learner with regards to the ambitions, hopes, and With these comments Cyrus points to one of the fears of others. This is perhaps best illustrated by problems presented by a community devoted exclu- considering Cyrus’ growing practical ability to help, sively to basic civic virtue and well-being: the entice- gratify, and otherwise manipulate people towards his ments Cyrus offers are all the more alluring because they ultimate purpose of maintaining his dominance and are novel to the Persians, who have spent their lives receiving their love and praise. Cyrus’ manner of suppressing their unruly passions. influencing the hopes and fears of those he conquers Cyrus’ undermining of the traditional Persian is subtle and often impressive; it does not seem to be education starts very early on and seems to be based dependent upon his sharing their sentiments. He on an insight into the problematic character of the rules using sophisticated, and often well-meaning, common good (stability and ‘‘justice’’) that is achieved in Old Persia. Because it is intangible and incomplete, 6 In the Memorabilia, Socrates does not discourage political the common good in Persia proves fragile. The strength involvement, but he does encourage psychological self-analysis. See 3.7.9, 4.2.25, and Plato’s Alcibiades I. of Cyrus’ psychological understanding is evident in the 7 momentum of Book 2, where he is able to cultivate For a discussion of several other interpretations of the signifi- cance of Xenophon’s title, see Due (1989, 15). great hope among his troops, as well as to sustain it 8 through the difficult parts of the campaign. One of the This is not to say that Cyrus is able to conquer everyone. There are some suggestive silences in Xenophon’s list of the people over most vivid examples of Cyrus’ psychological skill takes whom Cyrus rules in Book 1, Chapter 1 (1.2.4–5). These include place in Book 2, Chapter 2. Having been recently the Armenians, Chaldeans, and the Caducians. The philosophically reminded by his father that there are ways to rule educated Armenian Tigranes and Gadatas the Caducian are probably the closest Cyrus comes to having friends, and the besides fear (1.6.21–24), this chapter demonstrates how suggestion seems to be that they preserve their rule in some form. Cyrus used humour to his advantage, in stark contrast The roaming troop of plundering Chaldeans are the only group to the austere Persian traditions. Having orchestrated a that seem to achieve lasting freedom (Cyrus never gives them up to major shift in the hierarchy of the Persian army by a Satrap, even upon his death). Their mode of life (see 3.2.7, 7.2.2–8) warrants comparison with the discussion of the ‘‘foreign policy’’ of promoting all the mercenary and common soldiers, the city in speech in Plato’s Republic (422a–423e and 468–471e). Cyrus needs some way in which to mitigate the fears of xenophon’s cyropaedia 729 the elite peers (see 2.2.18). The jesting he encourages in the brutality perpetrated by the campaign, and con- Chapter 2, though divisive, also serves to alleviate the doned by Cyrus, are in some tension with his seeming- fears of his leading men and (by fostering hopes) to spirit of justice and benevolence. ‘‘motivate toward the good’’ (2.2.1); we should note Cyrus does not restrict his soul-machinations to that the lone dissenter to the jesting (Aglaitadas at the realm of material desires and ‘‘base’’ erotic mo- 2.2.14–2.2.16) is never heard from again. tives, for he is also keenly aware of the power that Cyrus is able to manipulate the general hopes of individual loves can have over men and women. He his men for progress and change, and we soon learn willingly uses this sophisticated awareness wherever that he is also a careful calculator with respect to the it proves expedient, against enemies and so-called particular types of goods that will satisfy them. In his friends alike. We see him use the Armenian’s love for first speech to his men, the goods to which Cyrus his family, for example, to his humiliation (3.1.9), directs his troops’ hopes are generally of the material and time and time again Cyrus manages to make variety, though he also speaks of honor and praise. As himself look generous through his continence with the plot unfolds it becomes clear that Cyrus also respect to women (3.1.35–37, 4.4.9, 5.1.1, 5.1, 6.1.45). maneuvers his men’s erotic desires quite capably. He also doubtless gains some knowledge of love by Xenophon does not dwell on Cyrus’ reliance on this witnessing the effect that he has on those around him. aspect of the campaign’s progression, but the full Perhaps the most vivid case is that of his ‘‘noble and story of the plunder that so motivates his armies is good’’ ‘‘relative’’ Artabazus, who is struck by Cyrus’ gradually brought to the surface in the course of the beauty during his youth in Media, and evidently telling. Xenophon often speaks only euphemistically never recovers; he follows and serves Cyrus to the about the fate of vanquished women (see 4.1.9, 4.2.32, end, only to be treated with general indifference (see 4.4.4, 4.5.3, 4.4.7, 4.5.39; not so euphemistically at 1.4.28, 7.5.55). Cyrus has a similar effect on his old 3.3.67), but the juxtaposition of Cyrus’ injunction friend Tigranes, though Tigranes’ affection for Cyrus against plunder of this kind (4.2.25–26), and the appears more lighthearted than that of Artabazus (see subsequent description of all the women captured by 3.1.42–43). The extent to which Cyrus understands the Medes and Hyrcanians (4.3.2) brings the ugly truth the phenomenon of love emerges in his conversation to the surface. That the defiance does not come as a with his old friend Araspas, where Cyrus mounts an surprise to Cyrus is made clear by Xenophon, who, eloquent attack on Araspas’ claim that love is strictly right after explaining the reasons for which the Asians voluntary (5.1.12). Cyrus understands the power of take women on campaign, and relating the capture of beauty and love to enslave men and has made a the women by the Medes, tells us: ‘‘When he saw the conscious decision not to take such risks with his deeds of the Medes and the Hyrcanians, it was as if own soul.10 Xenophon alerts us to the reflexive Cyrus blamed both himself and those with him, since implications of this understanding of love with the the others seemed at this time both to be flourishing inclusion of two brief speeches in loving support of more than they themselves, and to be acquiring things, Cyrus’ coup against his uncle (one by Artabazas, the while [the Persians] themselves seemed to be waiting other by Tigranes), in the very same chapter. That in a place of relative inactivity’’ (4.3.3). For just a Cyrus’ understanding of love’s force hardly impels moment Xenophon allows his reader to think (hope?) that Cyrus’ moral scruples are causing him some 10 regret . . . before he reveals that in fact Cyrus’ feelings, As has often been noted, this discussion merits comparison to if they are sincere at all, pertain to the Persians’ relative Socrates’ encounter with the beautiful courtesan Theodote in Memorabilia 3.11; see also his advice to Xenophon in 1.3. In the poverty in plunder.9 Not to put too fine a point on it, former, Socrates seems to endorse encounters with the beautiful, whereas in Xenophon’s case he playfully encourages the kind of conscious avoidance taken on by Cyrus. There are numerous 9 The full truth of the situation may be even more sinister than possible explanations for Cyrus’ ability to make the choice he does this. Upon further consideration it seems that Cyrus is in fact regarding the beautiful: it may signal weak eros, a lack of experience only pretending to feel even the sinister regret about his failure to of beauty as a youth, strong powers of self-control and/or reason, satisfy his troops. The order of Cyrus’ tale may suggest that Cyrus powerful alternate drives, or some combination of these. What has orchestrated the entire drama—including the feeling of envy seems most important in Cyrus’ case is the fact that his self-control, that would be born in the Persians upon the return of the however impressive, is in the service of shallow ends. Howland triumphant plunderers (see Cambyses’ advice in such matters, (2000) provides a very helpful discussion of this aspect of Cyrus’ 1.6.42). This is suggested by the cunning timing of both his psychology. There, he suggests that ‘‘Cyrus renders himself imper- saccharine speech to the Persians about moderation before the vious to the educative power of music, which has everything to return of the plunderers (4.2.45), and his and Chrysantas’ poetic do with ‘‘love matters [erotika] that concern the fair’’ (Republic speeches about the Persians’ desperate need for horses immedi- 403c6–7)’’ (2000, 877). See Newell (1983, 901ff.) for another view ately on the heels of their return (4.3.4–23). of the significance of eros in the Cyropaedia. 730 laura k. field him to protect his friends against it is evident in the quered. While he hopes to be the greatest of benefac- fate of Araspas, who is made pliable to Cyrus’ whim tors, he willingly steals some of the greatest goods, as a result of his unrequited love (see 6.1.31–44). namely self-sufficiency and freedom, from friends as Cyrus’ psychological understanding of eros is not well as enemies. limited to an appreciation of the magnetic force that The problem of the value of Cyrus’ ends is never ‘‘the beautiful’’ exerts over human beings. He is also overcome. Rather, much of Xenophon’s text seems attentive to the hopes that are fostered through designed to demonstrate the proportions to which familial love and to the vulnerability effected by all such dynamics can be magnified when they originate love. Cyrus recognizes and manipulates the fears in so capable an individual. Cyrus’ rule becomes fostered in most people by the prospects of a loveless increasingly tyrannical and cruel, and Cyrus becomes life, as well as the spirit of vengeance that is born more isolated and dependent on others for his safety. from the ruining of such attachments. Over the length Perhaps the most concise evidence of Cyrus’ growing of the campaign, Cyrus increasingly depends on the brutality is Xenophon’s admission at 5.4.51 that, spirit of revenge rather than love, as he takes advantage whereas Gobryas and Gadatas use violence and per- of the particular vulnerabilities of the kings Gobryas suasion in their respective conquests, Cyrus uses (who is left without an heir after the murder of his son terror.11 He also comes to look the part of the tyrant, by the Assyrian Prince), and Gadatas (who is made a with rising reliance on the adornment which he had eunuch by the same Assyrian in a fit of rage). With his previously scorned in others (compare, for example, ever-growing power, Cyrus promises to help both men 2.4.5 with 8.3.1–5). Cyrus’ growing preoccupation with achieve vengeance and is hereby able to bring them personal security is clearly in view when he has to under his authority almost effortlessly. Each of them consider the possibility of treachery upon seating his admits his vulnerability to Cyrus and is grateful for the best friends to a feast (8.4.3). At one point, Xen- protection he offers (see 4.6.2, 5.2.7, 5.3.18, 5.4.29–32, ophon explicitly articulates what we have suspected and 6.1.1). Cyrus’ treatment of them is not always about Cyrus’ dependence on others’ vulnerability, magnanimous (see 5.3.56–5.4.9, 6.1.1), but they are when he explains Cyrus’ reliance on eunuchs at length loyal to him and become important allies because of (7.5.61–65); the eunuch Gadatas obtains a role of this reliability. honor that only highlights Cyrus’ isolation (8.4.2). Cyrus’ prudential ability to see what is required These tyrannical traits are presented lucidly to the to accomplish his ambitious military objectives is reader. In the next section I hope to show that the lack impressive. He is an able learner of these strategic of redeeming ends in Cyrus’ empire mirrors Cyrus’ kinds of truths, and this practical knowledge of how general lack of self-reflection and thoughtfulness. to use peoples’ hopes and fears becomes his most impressive possession. However, in light of the obvious unscrupulousness of Cyrus’ method, a pressing ques- The Limits of Cyrus’ Rule and the tion emerges: that of the ultimate ends served by his Limits of Cyrus’ Psyche campaign. As a youth in Media it was clear that Cyrus was ambitious for praise and honors, but whether While Xenophon continues to hint at misgivings Cyrus’ rule is truly advantageous, either to him or to about our protagonist’s character, it is clear that those over whom he rules, remains unclear. Many of Cyrus continues to think of himself as the greatest of his men are satisfied with the material gains they have benefactors. The incoherence of Cyrus’ youth is made and show gratitude for the good Cyrus has done perpetuated and enlarged through his whole lifetime them (consider Artabazus’ declaration at 6.1.10 that, of martial triumphs, and Cyrus never seems to gain ‘‘since what is at home is a campaign, but this is a much awareness of the difficulties attending his holiday, I do not think that we should disband this notion of a good life. Several episodes in the text festive gathering’’). Cyrus is able to bring peace to some attest to Cyrus’ lack of self-reflection, and Xenophon nations and a better life to some individuals (most enhances our attentiveness to Cyrus’ faults through notable in this regard is Pheraulas, but see 8.3.40). He the inclusion of several characters who provide certainly gains brute power and a certain degree of compelling points of psychological comparison. freedom for himself; his ability to provide help to Gobryas and Gadatas, in the form of retribution, makes 11 him appear god-like to them and others (including Other straightforward examples of Cyrus’ growing harshness include the use of women in battle (6.3.30), and his changing himself, see 5.3.56–5.4.9, 7.1.16–18, 7.5.9, and 7.5.16). standards of warfare (compare 4.4 and 5.4.25–27 with 7.5.31 and But in general Cyrus’ victories are bad for the con- 7.5.69). See also 1.1.5. xenophon’s cyropaedia 731 An early example arises when Cyrus is trying to dubiousness of his ends. In Book 5, as his campaign sort out a pressing situation with the Armenian king. gains momentum, Cyrus goes out of his way to help The king, caught red-handed in defiance of his Gadatas, and in response Gadatas comes bearing a obligations to Cyrus’ uncle Cyaxares, and in the wealth of gifts. Cyrus justifies his unwillingness to midst of an attempted flight from Cyrus’ approach, accept this gesture of gratitude as follows: is in a terribly vulnerable position (3.1.10). We see I accept the horses, for I will benefit you by giving Cyrus torn between, on the one hand, belief in them to troops better disposed toward you than were retributive justice and the idea that the Armenian those troops of yours who just had them, as it seems, king ought to suffer the harshest of punishments for and for my part, I will more quickly increase the his crimes (3.1.12), and, on the other, his desire to be Persian cavalry up to ten thousand knights, some- a just benefactor. Cyrus is uncertain whether it is just thing I have long desired to do. As for the other valuables, take them away and guard them until you to let the king live, especially since the king frankly see me having enough that I will not be outdone in admits that in Cyrus’ position he would opt for reciprocating with gifts to you. If you go away after execution. To his credit, Cyrus appeals to his old giving to me more than you receive from me, by the (and, it would seem, Socratically educated) playmate gods I do not know how I could possibly avoid being Tigranes for help, and it is only through the latter’s ashamed. (5.4.32) careful reasoning that the dilemma is resolved Of course, as is evident in this passage, Cyrus has no (3.1.23–31). Tigranes is able to convince Cyrus that difficulty making others—even his next of kin— he can have his retributive cake and give his benefac- experience the shame of inferiority. His Median uncle tion too. Only once Cyrus is persuaded that the Cyaxares articulates some of the psychological effects Armenian has suffered considerably, and that in being of Cyrus’ brand of generosity with candor: merciful he is proving himself to be the better man, is he willing to overcome his indignation and produce the And as for the valuables and the way you are now giving them to me, I think it would be more pleasant outcome favored by his more benevolent self. In this to bestow them upon you than to receive them from case the outcome is good from every perspective: the you like this, for being enriched in them by you, I private interests of Cyrus, the king, and Tigranes are perceive even more those things in which I am achieved, and so too is the common good of continued becoming impoverished . . . Be assured that if you harmonious relations. That Cyrus is persuaded by cared for me at all, you would guard against depriv- Tigranes, however, is not to say that he has learned ing me of nothing so much as my dignity and honor. (5.5.27–34) from him. This is one of those rare incidents early in the book where a clear common good is achieved (see Cyrus is not willing to linger on this thought for long. also 3.2); more typically, at key moments when his rule He interrupts his uncle, who has no choice but to might have become genuinely political—when it might submit to Cyrus’ sheer power. When confronted with have taken on a shared good as its end—Cyrus retreats the contradiction he is perpetuating, Cyrus responds into isolation.12 The example of the Armenian king also with nothing but vague unease. Despite his uncanny demonstrates Cyrus’ persistent failure to consider his ability to wield authority through complex psycho- own conflicting opinions about justice. logical maneuvering, Cyrus demonstrates that there Another later series of conversations confirms are real limits to his self-understanding, and a dogged our suspicion that Cyrus fails to understand the unwillingness to confront the question of the ulti- moral intricacies of his own actions and the moral mate worthiness of the ends he pursues (though he is able to articulate these ends; see 7.1.13 and 7.1.18). The narrative thread that best demonstrates 12 In his most recent article, Whidden persuasively argues that Cyrus’ lack of self-knowledge is the tragic love story Cyrus’ rule is not ‘‘political’’ at all, since, at least according to the of Panthea and Abradatas. The stories of Panthea and Aristotelian sense of the word, genuine political rule involves political deliberation and helps to fulfill man’s rational nature Abradatas, like those of Gobryas and Gadatas, take (2008, 38; see Aristotle Politics 1253a2–18). Political rule in its place over the course of Books V through VII and are fullest sense ‘‘involves a relationship between free and equal woven together with the continuing tale of Cyrus’ persons, one in which ‘‘there is an alternation of ruler and ruled’’ between those who ‘‘tend by their nature to be on an equal growing empire. Xenophon’s intermittent descrip- footing and to differ in nothing’’’ (57; see Aristotle Politics tions of Cyrus’ diverse and impressive innovations, 1255b20, 1259b1–6). In his 2007 article, by contrast, Whidden and of the magnificent armaments and well-ordering argues that Cyrus represents the ‘‘most virtuous and knowledge- of his troops, help to remind the reader of the able of leaders’’ (540), and in both pieces holds the ancients to be deeply skeptical about the possibility of political improvement excitement and expectation that can be generated in (see 2007, 563–67 and 2008, 62). times of war and imperial expansion. Along with the 732 laura k. field hints about the increasingly despotic tenor of Cyrus’ seized by their love, they forget the fact that they rule, the story of Abradatas and Panthea dampens themselves are what matters to the other, and that, this tale of enthusiasm with a rising sense of tragic therefore, proper attention to themselves is a prereq- fear and foreboding. Abradatas and Panthea each uisite for sustaining their love. In this they provide a seem to be models of human virtue and nobility; they mirror-image to Cyrus. While their moral purity and have no difficulty gaining the reader’s affections. Both devotion to one another leads them to risk everything, are renowned for their beauty, and this quality seems such that the ends they seek are thwarted, Cyrus’ to be reflected in their actions, which are solidly unwillingness to compromise himself for anything grounded in love for one another, despite being mixed ensures honor and a kind of political success, but his with excessive credulity.13 Abradatas and Panthea come situation is isolated and ethically compromised. Ulti- to represent the model of romantic love (complete with mately Xenophon discloses that his deeper sympathies a human-all-too-human crescendo of delusions). lie with the noble pair. Blinded, it would seem, by their love of one As we have already seen, Cyrus is aware of another, Panthea and Abradatas become ensnared in Panthea’s beauty, but suppresses any desires he may Cyrus’ operations, only to come to a terrible end. Out have to be with her out of skepticism about love and of misbegotten gratitude to the ‘‘pious, moderate and deference to his other ambitions; he is so keenly pitying’’ Cyrus (who has only shown restraint to- aware of the devastating effects of love on others that wards Panthea out of fear of excessive entanglement he avoids it at all costs. Nevertheless, Cyrus does not with ‘‘the beautiful’’ and his hopes that she might go unaffected by the presence of Panthea and prove otherwise useful, see 5.1.12–17), Panthea feels Abradatas. They are some of the few people Cyrus obliged to send for her husband (6.1.47, see 6.4.6–7); feels admiration for—Abradatas for his goodness and out of similarly deluded gratitude (also rooted in his faith and Panthea for her beauty and moderation (see love for his wife), and perhaps the slightest hint of 6.3.36, 7.3.8–16), and perhaps this is an indication on envy (reciprocated by Cyrus, see 6.1.50 and 6.1.52), Xenophon’s part that they surpass Cyrus in some Abradatas comes eagerly to Cyrus and gallantly ways. It speaks to Cyrus’ character that, while he does volunteers to take the most dangerous position in seem willing to make use of the two of them, he in no battle (6.3.35). Panthea, in turn, sacrifices her own way bears them actual ill will. Though he misses the riches to make beautiful armaments for her husband, poignant departure scene between Panthea and Abra- and, losing sight of her husband’s actual well-being, datas because he is busy attending to the sacrifices she passionately promotes Abradatas’ actions (6.4.4–8). (6.4.1), he gives Abradatas pious words of encourage- The noble Abradatas fights courageously alongside ment prior to the battle that seem sincere (7.1.15–18). loyal friends (7.1.30); his death takes place at the Perhaps in part because Cyrus believed the reassuring work’s height of violence and confusion (7.1.30–32, message he had spoken, he is quite affected by see also 7.3.8). True to her word (6.4.6), Panthea Abradatas’ death (7.3.6). When he hears of Panthea’s joins her husband in death (7.4.14). taking her own life despite his reassuring words to her Abradatas and Panthea have our sympathies, (7.3.12–15), he is similarly stunned, even though her even while Xenophon shows us that their expectations final words to him were ominous (see 7.3.13). Cyrus’ are unattainable. Abradatas and Panthea are linked lack of foresight and general perplexity regarding these with the idea of nobility in Xenophon’s text, and this is tragic events betray his lack of experience and reflec- reflected in their appearances, their speeches, and their tion upon at least two seminal dimensions of human actions. Insofar as they each represent so much that is life as they are presented in ancient thought: eros and good, it is not surprising that Abradatas and Panthea mortality. are very much in love with one another and care about Xenophon makes it clear to his reader that neither the other so much that they lose sight of themselves; Abradatas nor Panthea have a perfect understanding of their love for one another, or of their mortal natures. 13 Panthea is modest and faithful, as evidenced by her horror at Just as Cyrus’ perspective contains an escalating tension the thought of conjugal betrayal (5.1.4–6). She is also mindful of between his capacity to provide great benefactions and her husband’s safety, not sending for him until she has come to trust Cyrus (6.2.45). Abradatas is a powerful and trusted his desire to obtain the good for himself, theirs contains representative of the (old) Assyrian King (5.1.3) and is said by an escalating misunderstanding about the meaning of Xenophon to have a nature ‘‘most handsome and most free.’’ He their love for one another and their capacity to sustain is moderate even in his eventual disloyalty—awaiting Panthea’s that love through martyr-like devotion. There is, how- faithful word before he comes over to Cyrus’ side. When he does so (6.2.48), it is in a noble, restrained fashion that is in marked ever, one remarkable difference between Cyrus’ per- contrast to the capitulations of earlier rulers. spective and theirs, which is indicated by Xenophon in xenophon’s cyropaedia 733 his customarily quiet way: Panthea, upon the death of hero and dies a most wretched and violent death her husband, attains a degree of self-reflexive clarity. We (1452a20); she ‘‘discovers’’ her hamartia, or missing of witness this moment in the following striking scene: the mark, too late (but at the same time as she finds out about the reversal, which is said by Aristotle to be When he [Cyrus] saw the woman seated on the ground and the corpse lying there, he wept at the the most beautiful possibility in a story, 1452a30–33); sorrowful event and said, ‘‘Alas! You good and as a result she suffers terribly (1452b1); the reader feels faithful soul, are you going away and leaving us?’’ both fear and pity for her and is left in a state of And at the same time he grasped Abradatas’ right catharsis and wonder about the events (1449b29, hand, but the hand of the corpse stayed with his, for 1452b2, 1452b30, 1453b).15 Cyrus’ story lacks this it had been cut off with a sword by the Egyptians. On seeing this, he was still more grieved by far. And the tragic structure. He is a gifted individual, but he never woman wailed, and taking the hand back from encounters a terrible turn of events in his own lifetime. Cyrus, kissed it and attached it again as best she Though his own actions do help us to understand the could, and said, ‘‘The rest is also like this, Cyrus. But ‘‘reversal’’ that happens after his death, and we are left why must you see? I know that he suffered this not in a state of curiosity, Cyrus himself is always portrayed least because of me, and perhaps also no less because as happy, even at the time of his passing. Unlike of you, Cyrus. For I, foolish I, frequently encouraged him to act in such a way that he might show himself Panthea, he never makes any ‘‘discovery’’ about the to be a noteworthy friend for you. I myself know that implications of his actions, nor about the many ways in he did not have in mind what he would suffer but which he ‘‘misses the mark’’ concerning the common what he could do in gratitude to you. Accordingly, he good and justice; the reader does not feel fear or pity himself died a blameless death, but I who exhorted for Cyrus, either before or after his death, and him sit beside him alive. (7.3.8–10) experiences no ‘‘purge’’ or catharsis of the emotions. Though Panthea’s thoughts, as well as her subsequent The story of Cyrus lacks the most important elements actions, may still contain some problematic elements, of tragedy as they are outlined by Aristotle in the it is nonetheless true that she reaches a degree of self- Poetics, and this raises problems for the reigning awareness that is never matched by Cyrus, who proves interpretation which sees Cyropaedia as representing a unable to confront the contradictory elements in his thorough-going critique of politics. That reading is life. Panthea comes to realize the folly of her earlier predicated on the idea that the book’s ending contains exhortations to Abradatas and provides a clear articu- the purgative elements of tragedy, by which our lation of her motives; she also acknowledges the com- political hopes are effaced; such pessimism has to be plicated role of Cyrus. Upon hearing Panthea’s tentative challenged given our discovery of the Cyropaedia’s accusation, Cyrus weeps in silence before offering her singularly nontragic character. further consolation (7.3.11), but there is no indication that he recognizes any connection between his own ambitions and the ugly death of Abradatas.14 Xenophon’s Counter-Paedia This difference is significant, since it points to a core difference between the narrative constitution of In the Cyropaedia, Xenophon provides a provocative Panthea’s story and Cyrus’. The story of Panthea portrayal of the opportunities available to an ambi- follows the characteristic pattern of tragedy very much tious and talented political ruler who obtains an as it is outlined in Aristotle’s Poetics: an excellent impressive degree of psychological insight. But Cyrus individual (see Poetics 1453a15, 1454b9) encounters a is not in fact the perfect political man, nor should his terrible turn of events that follow ‘‘as if by design’’ story be interpreted as a lesson about the tragic and from her very own actions (1452a7, 1453b); there is a irremediable character of political life, as it has been ‘‘reversal’’ of fortune by which Panthea’s husband, at by several otherwise impressive interpreters of the her own convincing, heads off to battle like a shining Cyropaedia. Instead, he is Xenophon’s preeminent 14 representative of a recurring and significant political Cyrus is portrayed as genuinely stunned (from ekplesso—to be astonished, stricken with terror) and aggrieved at the sight of problem: the extremely talented and ambitious Abradatas and Panthea dead, as well as disturbed by the youth who, however well-meaning, is insufficiently mutilated state of Abradatas’ corpse. This bespeaks a certain naivety in Cyrus’ outlook—he is genuinely surprised that 15 Abradatas proved mortal—more than any morbid eros for killing See Sach’s introduction to his translation of Aristotle’s Poetics and the dead (for the latter suggestion, see Nadon 2001: 159–160 (2006) for a most helpful analysis of Aristotle and tragedy. For and 1.4.24). The scene also provides a counterpoint to the other discussions of tragedy in Xenophon, see Gera (1993, romantic outlook of Panthea and Abradatas; perhaps it also 221–45), Kingsbury (1956), Sage (1994, 171–72), and Nadon provides some hint of Xenophon’s macabre sense of humor. (2001, 146). 734 laura k. field thoughtful about the most important human con- Media and providing him with a better understand- cerns. This failure points to characteristic, but not ing of the relative merits and virtues of the traditional inevitable, limitations of extraordinary political Persian regime. For example, if Cyrus had been in men, and close study of the text suggests that it Persia rather than Media during his early youth, has at least three obvious political dimensions. First perhaps he would have come to understand the and foremost is the fact that Cyrus receives an benefits of laws—something that is beaten into him inadequate education from his political community. when he is very young, but which is ultimately a Second, and partly as a result of his faulty education, lesson that Cyrus never learns. Stated simply, Cyrus is Cyrus governs only by means of increasingly brutal never taught how justice and the law (or other personal command and manipulation, failing to people) at times compromise short-term interests enact any good laws. Finally, Cyrus fails to question for the sake of more important goals, like the peace, the coherence of his own motives and therefore stability, and flourishing of one’s homeland. Having neglects the essential question of the proper ends of only ever experienced the law as something that politics. The recognition of Cyrus’ defects, rather interferes with his desires, he learns to work around than leading to resignation about politics, allows us it. With greater vigilance, informed by a surer under- to begin to articulate avenues which Xenophon leaves standing of the merits of Old Persia, Cyrus’ revolu- open for contemplation and prospective action. In tionary activity might have been prevented. what follows, I outline the main course of reflection It is not altogether clear, however, that Old Persia that Xenophon seems to me to recommend in light of was truly flourishing, or that Cyrus’ natural ambition his condemnation of Cyrus’ empire. could have been satisfied without some change in In Plato’s Laws, the Athenian Stranger criticizes conditions there. The regime had troubling dimen- Cyrus for not educating his own sons, saying that he sions worthy of criticism, and possibly of reform. In ‘‘failed completely to grasp what is a correct educa- his description of Cyrus’ early education, as well as of tion’’ (694c). The failure Plato ascribes to Cyrus with the life that it preconditions, Xenophon encourages respect to his own sons, Xenophon also quietly us to question the premises of a life singularly devoted ascribes to the Persians with respect to Cyrus. While to basic forms of the common good such as security it is true that Cyrus receives training from Old Persia, and order. The fleeting description of the Persian the Medes, and his father Cambyses, and that this education illustrates the problem of having concern combination provides him with many of his most for physical sustenance and stability dominate so impressive qualities (such as discipline, charm, and a overwhelmingly, and Cyrus’ life confirms that this sharp strategic mind), Xenophon also indicates several exclusive focus on the most basic elements of com- ways in which Cyrus’ education was haphazard and munity ultimately makes the old regime vulnerable. faulty. As far as the reader is shown, he is offered little The monotony of this life and the apparent absence of opportunity to learn that politics consists of more than many higher order goods (such as family life, music, prudent dominion, and he never undertook a serious literature, sciences, and even friendship) prove prob- consideration of the character of genuine political life. lematic. While we might not notice such deficiencies By portraying Cyrus’ education as such, Xenophon at in the course of a preliminary reading, Xenophon once indicates how Cyrus became what he was, and would surely have us note that there are no ‘‘arts and reveals some of the basic parameters of genuine letters’’ or ‘‘musical arts’’ in Old. Indeed, when poets political education. or poems are mentioned in the book, it is usually in It is hard to deny that Old Persia was more just reference to war strategy (see the references to war and ultimately more impressive than the new empire, paeans at 3.3.55 and 3.3.59, the ‘‘poet of stratagems’’ at in spite of its various inadequacies (see Whidden 1.6.38, and the ‘‘tragic stage’’ at 6.1.54; see also 2008, 56). First in comparison to Media, and sub- Strauss1939, 510). sequently in contrast with Cyrus’ empire, Old Persia Although sweeping political change like Cyrus’ is especially impressive in its respect for law and the can be dangerously single-minded, Xenophon’s book longstanding stability which this brings to the regime, demonstrates how the stultification of a traditional as well as for the character of its citizens (see system can make it vulnerable. The laws of Old Persia Whidden 2007, 554–63). The political question that are obeyed without being understood and are dis- lurks here is whether Cyrus’ ambitions might some- obeyed by the rulers without any real sense of how have been channeled within the regime without foreboding. The old system is defenseless against undermining its stable character. This would have Cyrus’ bold initiatives, whereas its vitality might have involved preventing Cyrus’ morally corrosive trip to been sustained and improved through more careful, xenophon’s cyropaedia 735 incremental changes. Cyrus would have benefited from however, our author lifts the veil on Cyrus’ system, long conversations, perhaps with a more thoughtful informing us that instead of fostering justice it fueled Cambyses, about how Persian political life might have envy and hatred (and probably corruption and bribery been improved (rather than just maintained), the too; see 8.8.13).17 Xenophon even holds out the relative merits of other types of regimes (such as promise of leisure to his readers (8.1.13), but in Cyrus’ monarchy, and the more commercial Athenian de- empire life at the top is devoted mostly to wealth and mocracy), and even the possibilities pertaining to pageantry (8.2.20, 8.3); even the leisurely symposium various kinds of empire. Xenophon indicates that such at 8.4.1–27 involves its share of sycophantic banter, alternative forms of education are a real possibility by and when finally we arrive at the question of Cyrus’ having Cambyses mention how for a time there was a happiness, Xenophon punts (8.7.6). By showing us more sophisticated form of education in Old Persia, what is missing in Cyrus’ empire, and in such a but that it threatened civic virtue and was therefore tantalizing way, Xenophon reminds us of what is put to a stop (1.6.31–33). The deep question this short essential to genuine political life as understood and interlude raises is whether the political stability prized practiced by the ancient Hellenes. by the Old Persians, and in the new Persian empire, is Unlike Plato or Aristotle, Xenophon does not, in worth everything that might be gained through more the Cyropaedia or elsewhere, articulate a definite ‘‘best cosmopolitan forms of education. If the pseudo- regime,’’ or set of ends. But as Cyrus’ own empire enlightenment of 1.6.31–33 inadequately taught young grows, what becomes most obvious is that Cyrus citizens the merits of the law, it does not follow that would have benefited from a thorough consideration a return to simplicity was the optimal pedagogical of the final ends of politics—that great theme of response. The Cyropaedia shows us the pitfalls of this ancient political philosophy. Cyrus has little personal choice writ large. understanding of the kinds of goods that are most Xenophon further indicates some of the partic- important to human beings, nor of the kind of ular advantages of a more cosmopolitan, or Hellenic, architectonic prudence that would work to arrange education in Book 8 of the Cyropaedia. He does this such goods within a shared political order (see through his graduated revelation of the dissatisfying Aristotle, Ethics 1141b25, 1152b2–3). In Book 8, some character of Cyrus’ despotism. Chapter by chapter, of these goods, like freedom, virtue, justice, leisure, Xenophon raises his readers’ hopes about the ultimate and happiness, are grasped at by Cyrus, with thor- state of affairs under Cyrus’ rule, only to disappoint. In oughly dissatisfying results. Genuine prudence surely 8.1, for example, Xenophon holds out the promise of involves the rare ability to rank such goods, and to freedom, when, in an early speech by Chrysantas, a order one’s life accordingly with a view to living well distinction is made between those who obey freely and (in light of one’s own particular character); genuine willingly and those who do so under compulsion political prudence, in the ancient view, involves the (8.1.1–5). The initial suggestion seems to be that rarer ability to make such judgments on others’ behalf Cyrus’ subjects are free in their willing obedience, (see Aristotle, Ethics 1140a25–1140b14, 1141b7–34, but by 8.2, Cyrus’ servants are likened to dogs (8.2.4) 1129b31–1130a15). and his friends to sheep (8.2.14); everyone is kept in Which leads us back to the question of the mean- check through an elaborate surveillance system ing of the law—a question raised early on in Old (known as the king’s Eyes and Ears, and especially Persia, but set aside by a youthful Cyrus convinced of punitive of the free thinking; see 8.2.10–12, 8.3.22, and his exact understanding of justice (1.3.16). Though 8.6.16–18). Next, Xenophon holds out the promise of Cyrus can offer some explanation of the merits of law virtue (8.1.17), but soon we are shown how Cyrus (3.3.49–54), he himself lives only by the ‘‘law’’ of abides by the Old Persian methods of petty honors, conquest, which he believes to be eternal (7.5.73). competition, animal appetites, and fear.16 The hope Cyrus’ failure to legislate adequately at home (i.e., the for justice is also enlivened in Book 8 when Xenophon inadequacy of his petty tribunals) points to an enor- mentions Cyrus’ establishment of a system of legal mous area of political activity that remains virtually judgments (8.2.27–28). In the course of the telling, untouched, and doubtless contributes to the demise of the empire upon his death. His failure at legislation 16 See 8.1.42, 8.1.18, 8.2.12, 8.2.25–27, 8.3.22, and 8.1.39; on food see 8.1.38, 8.2.6–7, and 8.4.6. These echoes of Old Persia indicate 17 the extent to which Cyrus’ empire relies on traditional virtue. For a helpful discussion of the contrast between Cyrus’ rule and This may also be Xenophon’s way of indicating the latent the rule of law in the Cyropaedia, see Whidden (2007); for an instability of the empire, since, absent a better legislator than analysis of Cyrus’ other main piece of legislation (4.3.22; see also Cyrus, the Old Persian ways will not be sustainable there. 8.4.5), see Johnson (2005). 736 laura k. field does more than this, however. It also ensures that while a different education remains an open question, but he is alive it is nearly impossible for anyone else to be he is called a lover of learning by Xenophon, and free. In displaying for us the shallow austerity of Old there are several instances when Cyrus’ rule was made Persia, Xenophon teaches that the law must exist for more just by the advice of thoughtful characters like the sake of something more than Persian self-control; Tigranes. This suggests that under different circum- in illuminating the dreadful proportions of Cyrus’ stances he might have learned the lessons discussed empire, he shows us what can happen in law’s absence. above. Xenophon tells us that ‘‘When the person in If the meaning or purpose of the law has been forgotten control is better, the lawful things are observed with among the Old Persians (who have lawfulness beaten greater purity,’’ and that ‘‘when he is worse, they are into them sans the accompaniment of understanding), observed in an inferior way’’ (8.1.8), which indicates by the end of the book it is not lost upon the reader. that there is ample room in Xenophon’s outlook for And it would not be lost on the ancient Greeks, either, political improvement, and furthermore that it is who were so manifestly concerned with the laws’ role connected to the virtue of the ruler. As we gain this in establishing and preserving the conditions of genu- understanding, and trace out the difficulties with ine freedom.18 The ancients too teach that laws can Cyrus’ rule—the limitations of his education and be a powerful expression of political moderation and self-understanding, the lack of redemptive final ends are a necessary condition of virtue and freedom; while to his dominion, and his failure to legislate—any it is easy to delineate the differences between ancient lingering tragic dimensions of the story fall away. forms of rule and contemporary notions of personal My reading does not produce a singular positive autonomy enshrined in rights-based constitutions, it is teaching about the proper direction of political important not to overstate them.19 Cyrus’ tyranny life. This, I think, is in keeping with the spirit of reminds us of the import of such Hellenic norms, as Xenophon and of ancient thought more generally, well as of their fragility in the absence of institutional but it is also especially appropriate to the Cyropaedia, and cultural supports. which as a pedagogical text operates primarily by way of Cyrus’ negative example. Indeed, if there is a clear message that does emerge from the Cyropaedia, it is Conclusion to be especially on guard against single-minded political solutions. While Cyrus’ conquests are excit- ing and impressive, the system he ultimately estab- In studying Xenophon’s Cyropaedia, we learn that lishes is brutal and hollow (see Faulkner 2007, Cyrus’ empire reflects the unexamined contradictions 170–76). Like so many regimes throughout history, of its founder’s life. The book attunes us to the rare it suppresses the human potential of its subjects for and unique qualities of a good education, as well as to the sake of singular dominion. While Cyrus dramat- the dangers of a faulty one. Whether Cyrus’ nature ically proves that knowledge of how this may be done was such that he ever could have been transformed by is attainable (see 1.1.3), such know-how falls short of the kind of wisdom that would enable one to live a fulfilling and benevolent life within a stable political community, let alone to establish one. This does not mean that genuine political wisdom is an illusion. 18 A straightforward proof of the Ancients’ deep regard for legal While the ancients are careful to avoid universal forms can be found in Aeschylus’ Eumenides, which celebrates political solutions that are bound in time to falter, Athena’s establishment of the court of the Areopagus in Athens. their political works seek above all to cultivate genuine Athena’s speeches in the play highlight several legal principles that are essential even today. These include equality before the prudence and wisdom, especially in their most ambi- law and the presumption of innocence (407–13), the restraint tious readers. Though this targeted educative project is demanded of individuals (and even gods like Athena) in the a far cry from universal enlightenment, it does promise establishment of courts of justice (see 470–89), the role of courts in achieving a genuinely political order, as opposed to anarchy something—namely prudential wisdom—that is ap- and despotism (681–710), and their role in countering individual propriate to all times and places. The Cyropaedia is ambition (864–65). thus best seen as a work that illuminates questions that 19 Ruderman’s concise suggestion about the difference between are explored more fully in other ancient texts, like ancient and modern understandings of political judgment also Plato’s Republic and Aristotle’s Politics; it is written to pertains to the respective notions of political freedom: ‘‘A key attract and inspire ambitious young people, as well as difference between the [contemporary] advocates of political judgment and Aristotle is that they, but not he, insist that all to introduce them to some of the abiding concerns citizens exercise it’’ (1997, 412; see also 419n23). of politics. xenophon’s cyropaedia 737 Cyrus’ failure, then, is not inevitable, and a major the University of Texas at Austin. I am grateful to purpose of Xenophon’s work is to cultivate in his Lorraine Pangle for many helpful comments and reader that which Cyrus lacked.20 Indeed, my ultimate suggestions on this manuscript. Thank you as well reservation about the suggestion that Xenophon’s goal to Stephen Lange, Devin Stauffer, Eduardo Dargent, in the Cyropaedia is to undermine political hopes rests and Austin Hart for valuable support and advice and in this literary experience of the work. The gripping to the editors at JOP and anonymous reviewers for power of Xenophon’s narrative defies an apolitical their thorough and thoughtful comments. All linger- reading. The excitement of the book, achieved through ing errors remain my own. its inviting novel form and terrific tempo, was surely meant to attract young politically minded readers (who might be inclined to confuse successful conquest References with political virtue) and has succeeded throughout history in doing so. And while the finale to the book Aeschylus. 1953. Oresteia. Trans. Richmond Lattimore. Chicago: is deflating, it is not structured so as to purge the very University of Chicago Press. political hopes that the whole at the same time Ambler, Wayne. 2001. ‘‘Introduction’’ to Cyropaedia. Trans. cultivates—political hopes for justice, for example, Wayne Ambler. Ithaca, NY: Cornell University Press, 1–18. and for a common good which is good for the rulers Aristotle. 2006. Poetics. Ed. and Trans. Joe Sachs. Newburyport, as well as for the ruled. The ending acts as an in- MA: Focus Publishing. vitation for reconsideration, but instead of delivering Aristotle. 1984. Politics. Ed. and Trans. Carnes Lord. Chicago: University of Chicago Press. any absolute message on the limits of politics, Xen- Aristotle. 2002. Nichomachean Ethics. Ed. and Trans. Joe Sachs. ophon guides his reader in the political and philo- Newburyport, MA: Focus Publishing. sophical reflections that Cyrus never undertook. Danzig, Gabriel. 2009. ‘‘Big Boys and Little Boys: Justice and Law Principal among these are reflections on the meaning in Xenophon’s Cyropaedia and Memorabilia.’’ Polis: The and value of education itself, the meaning and value of Journal of the Society for Greek Political Thought 26 (2): 271–95. justice, the true ends of politics, freedom, and the law. Due, Bodil. 1989. The Cyropaedia: Xenophon’s Aims and Methods. Aarhus: Aarhus University Press. Xenophon would have his reader carefully consider Faulkner, Robert. 2007. The Case for Greatness. New Haven, CT how and when they can and should contribute to and London: Yale University Press. politics, and to what ends. Insofar as these questions Gera, Deborah Levine. 1993. Xenophon’s Cyropaedia: Style, continue to perplex us, and insofar as there is no Genre, and Literary Technique. Oxford, UK: Clarendon Press. substitute for this experience of education, there is a Howland, Jacob. 2000. ‘‘Xenophon’s Philosophic Odyssey: On great deal of continuity between his ancient concerns the Anabasis and Plato’s Republic.’’ American Political Science Review 94 (4): 875–89. and our own. What is more, the introspective reader Johnson, David M. 2005. ‘‘Persians as Centaurs in Xenophon’s of the Cyropaedia experiences the kind of liberating Cyropaedia.’’ Transactions of the American Philological Associ- human transformations that, among other things, ation 135: 177–207. make better politics a perpetual possibility. Kingsbury, A. 1956. ‘‘The Dramatic Techniques of Xenophon’s Anabasis.’’ Classical Weekly 49 (12): 161–64. Machiavelli, Niccolo. 1985. The Prince. Ed. and Trans. Harvey C. Acknowledgments Mansfield. Chicago: University of Chicago Press. Machiavelli, Niccolo. 1996. The Discourses on Livy. Ed. and Trans. Harvey C. Mansfield and Nathan Tarcov. Chicago: University An earlier version of this article was presented at the of Chicago Press. 2008 Midwest Political Science Association confer- Nadon, Christopher. 1996. ‘‘From Republic to Empire: Political ence, and support for this research was provided by Revolution and the Common Good in Xenophon’s Cyropae- The Social Sciences and Humanities Research Coun- dia.’’ American Political Science Review 90 (2): 361–74. cil of Canada and the Department of Government at Nadon, Christopher. 2001. Xenophon’s Prince: Republic and Empire in the Cyropaedia. Berkeley and Los Angeles: Univer- sity of California Press. 20 Newell, W. R. 1983. ‘‘Tyranny and the Science of Ruling in Reisert, in his recent article, comes close to acknowledging that Xenophon’s ‘‘Education of Cyrus.’’ The Journal of Politics 45: Xenophon’s purpose is to provide the reader with a moral and 889–906. political education that Cyrus never received (and helpfully suggest that the novel form of the Cyropaedia contributes to its Plato. 1968. Republic. Ed. and Trans. Allan Bloom. New York: persuasive power; 2009, 315). But he does not consider the ways Basic Books. in which Cyrus’ own education was faulty (see especially 311–12), Plato. 1987. Alcibiades I. Trans. Carnes Lord. In The Roots of or the extent to which Xenophon’s pedagogical approach differs Political Philosophy: Then Forgotten Socratic Dialogues, ed. both from the nonphilosophic traditions of Old Persia and from Thomas Pangle. Ithaca, NY: Cornell University Press, 175– the lessons of Cambyses. 221. 738 laura k. field Plato. 1987. Laws. Ed. and Trans. Thomas Pangle. Chicago: Whidden, Christopher. 2007. ‘‘The Account of Persia and Cyrus’ University of Chicago Press. Persian Education in Xenophon’s Cyropaedia.’’ The Review of Plato. 2004. Protagoras and Meno. Trans. Robert Bartlett. Ithaca, Politics 69: 539–67. NY: Cornell University Press. Whidden, Christopher. 2008. ‘‘Cyrus’ Imperial Household: An Reisert, Joseph. 2009. ‘‘Ambition and Corruption in Xenophon’s Aristotelian Reading of Xenophon’s Cyropaedia.’’ Polis 25 (1): Cyropaedia.’’ Polis: The Journal of the Society for Greek Political 31–62. Thought 26 (2): 296–315. Waterfield, Robin. 2006. Xenophon’s Retreat: Greece, Persia, and Ruderman, Richard. 1997. ‘‘Aristotle and the Recovery of the End of the Golden Age. Cambridge, MA: The Belknap Press Political Judgment.’’ American Political Science Review 91 of Harvard University Press. (2): 409–19. Xenophon. 1994. Memorabilia. Trans. Amy L. Bonnette. Ithaca, Sachs, Joe. 2006. ‘‘Introduction.’’ In Aristotle’s Poetics. New- NY: Cornell University Press. buryport, MA: Focus Publishing, 1–18. Xenophon. 2001. Cyropaedia. Trans. Wayne Ambler. Ithaca, NY: Sage, Paula Winsor. 1994. ‘‘Dying in Style: Xenophon’s Ideal Cornell University Press. Leader and the End of the Cyropaedia.’’ Classical Journal 90: Xenophon. 2007. The Anabasis of Cyrus, Trans. Wayne Ambler. 161–74. Ithaca, NY: Cornell University Press. Strauss, Leo. 1939. The Spirit of Sparta or the Taste of Xenophon. Social Research 6 (1/4): 502–36. Tatum, James. 1989. Xenophon’s Imperial Fiction: On the Education of Cyrus. Princeton, NJ: Princeton University Laura K. Field is a postdoctoral Fellow at Rhodes Press. College in Memphis, TN 38112. Copyright of Journal of Politics is the property of Cambridge University Press and its content may not be copied or emailed to multiple sites or posted to a listserv without the copyright holder's express written permission. However, users may print, download, or email articles for individual use.
https://www.scribd.com/document/402722027/Xenophon-s-Cyropaedia-Educating-Our-Political-Hopes
CC-MAIN-2019-30
refinedweb
13,747
57.3
Small, fast and scaleable bearbones state-management solution. Has a comfy api based on hooks, that isn’t boilerplatey or opinionated, but still just enough to be explicit and flux-like. import create from 'zustand' const [useStore] = create(set => ({ count: 1, inc: () => set(state => ({ count: state.count + 1 })), dec: () => set(state => ({ count: state.count - 1 })), })) function Counter() { const { count, inc, dec } = useStore() return ( <> <h1>{count}</h1> <button onClick={inc}>up</button> <button onClick={dec}>down</button> </> ) } Here’s where things get interesting: To use parts of the store in child components, call the useStore hook, selecting the piece you need from it — no providers needed: function Counter() { const count = useStore(state => state.count) return <h1>{count}</h1> } Installation per NPM/Yarn: npm install zustand Zustand – Bear necessities for state management in React → 🌐 In case you don’t get the name: Zustand is German for State.
https://www.bram.us/2019/12/02/manage-react-state-with-zustand/
CC-MAIN-2021-04
refinedweb
145
50.87
by Bob Nota bene: this instalment in the Ports and Adapters with Command Handlers series is code-heavy, and isn’t going to make much sense unless you’ve read the previous parts: Okay, so we have a basic skeleton for an application and we can add new issues into the database, then fetch them from a Flask API. So far, though, we don’t have any domain logic at all. All we have is a whole bunch of complicated crap where we could just have a tiny Django app. Let’s work through some more use-cases and start to flesh things out. Back to our domain expert: So when we’ve added a reported issue to the issue log, what happens next? Well we need to triage the problem and decide how urgent it is. Then we might assign it to a particular engineer, or we might leave it on the queue to be picked up by anyone. Wait, the queue? I thought you had an issue log, are they the same thing, or is there a difference? Oh, yes. The issue log is just a record of all the issues we have received, but we work from the queue. I see, and how do things get into the queue? We triage the new items in the issue log to decide how urgent they are, and what categories they should be in. When we know how to categorise them, and how urgent they are, we treat the issues as a queue, and work through them in priority order. This is because users always set things to “Extremely urgent”? Yeah, it’s just easier for us to triage the issues ourselves. And what does that actually mean, like, do you just read the ticket and say “oh, this is 5 important, and it’s in the broken mouse category”? Mmmm… more or less, sometimes we need to ask more questions from the user so we’ll email them, or call them. Most things are first-come, first-served, but occasionally someone needs a fix before they can go to a meeting or something. So you email the user to get more information, or you call them up, and then you use that information to assess the priority of the issue - sorry triage the issue, and work out what category it should go in… what do the categories achieve? Why categorise? Partly for reporting, so we can see what stuff is taking up the most time, or if there are clusters of similar problems on a particular batch of laptops for example. Mostly because different engineers have different skills, like if you have a problem with the Active Directory domain, then you should send that to Barry, or if it’s an Exchange problem, then George can sort it out, and Mike has the equipment log so he can give you a temporary laptop and so on, and so on. Okay, and where do I find this “queue”? Your customer grins and gestures at the wall where a large whiteboard is covered in post-its and stickers of different colours. Mapping our requirements to our domain How can we map these requirements back to our system? Looking back over our notes with the domain expert, there’s a few obvious verbs that we should use to model our use cases. We can triage an issue, which means we prioritise and categorise it; we can assign a triaged issue to an engineer, or an engineer can pick up an unassigned issue. There’s also a whole piece about asking questions, which we might do synchronously by making a phone call and filling out some more details, or asynchronously by sending an email. The Queue, with all of its stickers and sigils and swimlanes looks too complicated to handle today, so we’ll dig deeper into that separately. Let’s quickly flesh out the triage use cases. We’ll start by updating the existing unit test for reporting an issue: class When_reporting_an_issue: def given_an_empty_unit_of_work(self): self.uow = FakeUnitOfWork() def because_we_report_a_new_issue(self): handler = ReportIssueHandler(self.uow) cmd = ReportIssueCommand(id, name, email, desc) handler.handle(cmd) @property def issue(self): return self.uow.issues[0] def it_should_be_awaiting_triage(self): expect(self.issue.state).to(equal(IssueState.AwaitingTriage)) We’re introducing a new concept - Issues now have a state, and a newly reported issue begins in the AwaitingTriage state. We can quickly add a command and handler that allows us to triage an issue. class TriageIssueHandler: def __init__(self, uowm: UnitOfWorkManager): self.uowm = uowm def handle(self, cmd): with self.uowm.start() as uow: issue = uow.issues.get(cmd.issue_id) issue.triage(cmd.priority, cmd.category) uow.commit() Triaging an issue, for now, is a matter of selecting a category and priority. We’ll use a free string for category, and an enumeration for Priority. Once an issue is triaged, it enters the AwaitingAssignment state. At some point we’ll need to add some view builders to list issues that are waiting for triage or assignment, but for now let’s quickly add a handler so that an engineer can Pick an issue from the queue. class PickIssueHandler: def __init__(self, uowm: UnitOfWorkManager): self.uowm = uowm def handle(self, cmd): with self.uowm.start() as uow: issue = uow.issues.get(cmd.issue_id) issue.assign_to(cmd.picked_by) uow.commit() At this point, the handlers are becoming a little boring. As I said way back in the first part [], commands handlers are supposed to be boring glue-code, and every command handler has the same basic structure: So far, though, we’ve only seen steps 1, 2, and 3. Let’s introduce a new requirement. When an issue is assigned to an engineer, can we send them an email to let them know? A brief discourse on SRP Let’s try and implement this new requirement. Here’s a first attempt: class AssignIssueHandler: def __init__(self, uowm: UnitOfWorkManager, email_builder: EmailBuilder, email_sender: EmailSender): self.uowm = uowm self.email_builder = email_builder self.email_sender = email_sender def handle(self, cmd): # Assign Issue with self.uowm.start() as uow: issue = uow.issues.get(cmd.issue_id) issue.assign_to( cmd.assigned_to, assigned_by=cmd.assigned_by ) uow.commit() # Send Email email = self.email_builder.build( cmd.assigned_to, cmd.assigned_by, issue.problem_description) self.email_sender.send(email) Something here feels wrong, right? Our command-handler now has two very distinct responsibilities. Back at the beginning of this series we said we would stick with three principles: The latter two are being maintained here, but the first principle feels a little more strained. At the very least we’re violating the Single Responsibility Principle []; my rule of thumb for the SRP is “describe the behaviour of your class. If you use the word ‘and’ or ‘then’ you may be breaking the SRP”. What does this class do? It assigns an issue to an engineer, AND THEN sends them an email. That’s enough to get my refactoring senses tingling, but there’s another, less theoretical, reason to split this method up, and it’s to do with error handling. If I click a button marked “Assign to engineer”, and I can’t assign the issue to that engineer, then I expect an error. The system can’t execute the command I’ve given to it, so I should retry, or choose a different engineer. If I click a button marked “Assign to engineer”, and the system succeeds, but then can’t send a notification email, do I care? What action should I take in response? Should I assign the issue again? Should I assign it to someone else? What state will the system be in if I do? Looking at the problem in this way, it’s clear that “assigning the issue” is the real boundary of our use case, and we should either do that successfully, or fail completely. “Send the email” is a secondary side effect. If that part fails I don’t want to see an error - let the sysadmins clear it up later. What if we split out the notification to another class? class AssignIssueHandler: def __init__(self, uowm: UnitOfWorkManager): self.uowm = uowm def handle(self, cmd): with self.uowm.start() as uow: issue = uow.issues.get(cmd.issue_id) issue.assign_to( cmd.assignee_address, assigned_by=cmd.assigner_address ) uow.commit() class SendAssignmentEmailHandler def init(self, uowm: UnitOfWorkManager, email_builder: EmailBuilder, email_sender: EmailSender): self.uowm = uowm self.email_builder = email_builder self.email_sender = email_sender def handle(self, cmd): with self.uowm.start() as uow: issue = uow.issues.get(cmd.issue_id) email = self.email_builder.build( cmd.assignee_address, cmd.assigner_address, issue.problem_description) self.email_sender.send(email) We don’t really need a unit of work here, because we’re not making any persistent changes to the Issue state, so what if we use a view builder instead? class SendAssignmentEmailHandler def init(self, view: IssueViewBuilder, email_builder: EmailBuilder, email_sender: EmailSender): self.view = view self.email_builder = email_builder self.email_sender = email_sender def handle(self, cmd): issue = self.view.fetch(cmd.issue_id) email = self.email_builder.build( cmd.assignee_address, cmd.assigner_address, issue['problem_description']) self.email_sender.send(email) That seems better, but how should we invoke our new handler? Building a new command and handler from inside our AssignIssueHandler also sounds like a violation of SRP. Worse still, if we start calling handlers from handlers, we’ll end up with our use cases coupled together again - and that’s definitely a violation of Principle #1. What we need is a way to signal between handlers - a way of saying “I did my job, can you go do yours?” All Aboard the Message Bus In this kind of system, we use Domain Events [] to fill that need. Events are closely related to Commands, in that both commands and events are types of message [] We will often use domain events to signal that a command has been processed and to do any additional book-keeping. When should we use a domain event? Going back to our principle #1, we should use events to trigger workflows that fall outside of our immediate use-case boundary. In this instance, our use-case boundary is “assign the issue”, and there is a second requirement “notify the assignee” that should happen as a secondary result. Notifications, to humans or other systems, are one of the most common reasons to trigger events in this way, but they might also be used to clear a cache, or regenerate a view model, or execute some logic to make the system eventually consistent. Armed with this knowledge, we know what to do - we need to raise a domain event when we assign an issue to an engineer. We don’t want to know about the subscribers to our event, though, or we’ll remain coupled; what we need is a mediator, a piece of infrastructure that can route messages to the correct places. What we need is a message bus. A message bus is a simple piece of middleware that’s responsible for getting messages to the right listeners. In our application we have two kinds of message, commands and events. These two types of message are in some sense symmetrical, so we’ll use a single message bus for both. How do we start off writing a message bus? Well, it needs to look up subscribers based on the name of an event. That sounds like a dict to me: class MessageBus: def __init__(self): """Our message bus is just a mapping from message type to a list of handlers""" self.subscribers = defaultdict(list) def handle(self, msg): """The handle method invokes each handler in turn with our event""" msg_name = type(msg).__name__ subscribers = self.subscribers[msg_name] for subscriber in subscribers: subscriber.handle(cmd) def subscribe_to(self, msg, handler): """Subscribe sets up a new mapping, we make sure not to allow more than one handler for a command""" subscribers = [msg.__name__] if msg.is_cmd and len(subscribers) > 0: raise CommandAlreadySubscribedException(msg.__name__) subscribers.append(handler) bus = MessageBus() bus.subscribe_to(ReportIssueCommand, ReportIssueHandler(db.unit_of_work_manager)) bus.handle(cmd) Here we have a bare-bones implementation of a message bus. It doesn’t do anything fancy, but it will do the job for now. In a production system, the message bus is an excellent place to put cross-cutting concerns; for example, we might want to validate our commands before passing them to handlers, or we may want to perform some basic logging, or performance monitoring. I want to talk more about that in the next part, when we’ll tackle the controversial subject of dependency injection and Inversion of Control containers. For now, let’s look at how to hook this up. Firstly, we want to use it from our API handlers. @api.route(‘/issues’, methods=[‘POST’]) def create_issue(self): issue_id = uuid.uuid4() cmd = ReportIssueCommand(issue_id=issue_id, **request.get_json()) bus.handle(cmd) return “”, 201, {“Location”: “/issues/” + str(issue_id) } Not much has changed here - we’re still building our command in the Flask adapter, but now we’re passing it into a bus instead of directly constructing a handler for ourselves. What about when we need to raise an event? We’ve got several options for doing this. Usually I raise events from my command handlers, like this: class AssignIssueHandler: def handle(self, cmd): with self.uowm.start() as uow: issue = uow.issues.get(cmd.id) issue.assign_to(cmd.assigned_to, cmd.assigned_by) uow.commit() # This is step 4: notify other parts of the system self.bus.raise(IssueAssignedToEngineer( cmd.issue_id, cmd.assigned_to, cmd.assigned_by)) I usually think of this event-raising as a kind of glue - it’s orchestration code. Raising events from your handlers this way makes the flow of messages explicit - you don’t have to look anywhere else in the system to understand which events will flow from a command. It’s also very simple in terms of plumbing. The counter argument is that this feels like we’re violating SRP in exactly the same way as before - we’re sending a notification about our workflow. Is this really any different to sending the email directly from the handler? Another option is to send events directly from our model objects, and treat them as part our domain model proper. class Issue: def assign_to(self, assigned_to, assigned_by): self.assigned_to = assigned_to self.assigned_by = assigned_by # Add our new event to a list self.events.add(IssueAssignedToEngineer(self.id, self.assigned_to, self.assigned_by)) There’s a couple of benefits of doing this: firstly, it keeps our command handler simpler, but secondly it pushes the logic for deciding when to send an event into the model. For example, maybe we don’t always need to raise the event. class Issue: def assign_to(self, assigned_to, assigned_by): self.assigned_to = assigned_to self.assigned_by = assigned_by # don't raise the event if I picked the issue myself if self.assigned_to != self.assigned_by: self.events.add(IssueAssignedToEngineer(self.id, self.assigned_to, self.assigned_by)) Now we’ll only raise our event if the issue was assigned by another engineer. Cases like this are more like business logic than glue code, so today I’m choosing to put them in my domain model. Updating our unit tests is trivial, because we’re just exposing the events as a list on our model objects: class When_assigning_an_issue: issue_id = uuid.uuid4() assigned_to = 'ashley@example.org' assigned_by = 'laura@example.org' def given_a_new_issue(self): self.issue = Issue(self.issue_id, 'reporter@example.org', 'how do I even?') def because_we_assign_the_issue(self): self.issue.assign(self.assigned_to, self.assigned_by) def we_should_raise_issue_assigned(self): expect(self.issue).to(have_raised( IssueAssignedToEngineer(self.issue_id, self.assigned_to, self.assigned_by))) The have_raised function is a custom matcher I wrote that checks the events attribute of our object to see if we raised the correct event. It’s easy to test for the presence of events, because they’re namedtuples, and have value equality. All that remains is to get the events off our model objects and into our message bus. What we need is a way to detect that we’ve finished one use-case and are ready to flush our changes. Fortunately, we have a name for this already - it’s a unit of work. In this system I’m using SQLAlchemy’s event hooks [] to work out which objects have changed, and queue up their events. When the unit of work exits, we raise the events. class SqlAlchemyUnitOfWork(UnitOfWork): def __init__(self, sessionfactory, bus): self.sessionfactory = sessionfactory self.bus = bus # We want to listen to flush events so that we can get events # from our model objects event.listen(self.sessionfactory, "after_flush", self.gather_events) def __enter__(self): self.session = self.sessionfactory() # When we first start a unit of work, create a list of events self.flushed_events = [] return self def commit(self): self.session.flush() self.session.commit() def rollback(self): self.session.rollback() # If we roll back our changes we should drop all the events self.events = [] def gather_events(self, session, ctx): # When we flush changes, add all the events from our new and # updated entities into the events list flushed_objects = ([e for e in session.new] + [e for e in session.dirty]) for e in flushed_objects: self.flushed_events += e.events def publish_events(self): # When the unit of work completes # raise any events that are in the list for e in self.flushed_events: self.bus.handle(e) def __exit__(self, type, value, traceback): self.session.close() self.publish_events() Okay, we’ve covered a lot of ground here. We’ve discussed why you might want to use domain events, how a message bus actually works in practice, and how we can get events out of our domain and into our subscribers. The newest code sample [] demonstrates these ideas, please do check it out, run it, open pull requests, open Github issues etc. Some people get nervous about the design of the message bus, or the unit of work, but this is just infrastructure - it can be ugly, so long as it works. We’re unlikely to ever change this code after the first few user-stories. It’s okay to have some crufty code here, so long as it’s in our glue layers, safely away from our domain model. Remember, we’re doing all of this so that our domain model can stay pure and be flexible when we need to refactor. Not all layers of the system are equal, glue code is just glue. Next time I want to talk about Dependency Injection, why it’s great, and why it’s nothing to be afraid of.tags: python - architecture
https://io.made.com/blog/2017-09-19-why-use-domain-events.html
CC-MAIN-2021-49
refinedweb
3,073
65.01
Vanilla JavaScript string endsWith Yesterday we had a look at the startsWith() function, and today we are looking at its brother the endsWith() function! As the name suggests, this one looks if a string ends with a specific substring. Using endsWith function in JavaScript permalink To use the function, we need to have a string then we can call the string.endsWith('substring') function and we will get a boolean value in return (true/false) var string = "Life is what happens when you're busy making other plans."; // Check if it ends with `plans.` console.log(string.endsWith('plans.')); // true As we saw in the startsWith() function this one is also case sensitive. var string = "Life is what happens when you're busy making other plans."; // Check if it ends with `Plans.` console.log(string.endsWith('Plans.')); // false Using an offset search position on endsWith permalink The endsWith() also has the option to offset, but from the end, so let's say we know the string always ends with "plans". We can then offset by six characters using the position attribute. var string = "Life is what happens when you're busy making other plans."; // Check if it ends with `other` console.log(string.endsWith('Life', 4)); // true With this position, keep in mind it will cap the string after four characters from the starting point! Feel free to play with this Codepen: See the Pen Vanilla JavaScript string endsWith by Chris Bongers (@rebelchris) on CodePen. Browser Support permalink This function works in all browsers but not in IE 😢. We can use this polyfill to help IE. Thank you for reading, and let's connect! permalink Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
https://daily-dev-tips.com/posts/vanilla-javascript-string-endswith/
CC-MAIN-2020-29
refinedweb
295
82.14
, write: React.useState or to import it, write: import React, { useState } from 'react'; A state object declared in a class allows you to declare more than one state variable. import React from 'react'; class Knoldus extends React.Component { constructor(props) { super(props); this.state = { name: '', count: 0, isModalOpen: false }; } } But useState hook allows you to declare only one state variable at a time. import React, { useState } from 'react'; const Knoldus = () => { const [name, setName] = useState(''); const [count, setCount] = useState(0); const [isModalOpen, setIsModalOpen] = useState(false); } Let’s discuss the above example in detail: - useState declares a state variable. It is a new way to use the exact same capabilities that this.state in class-based components. - The only argument to the useState is the initial value for the state variable. We can keep a number, string, or any value that we need as the initial value. Using useState alone won’t work because its arguments are used the first time only – not every time the property changes. In our example, we just want the initial value of - name as an empty string - count to be 0 - isModalOpen to false. - useState returns an array, where the first element is the state variable and the second element is a function to update the value of that variable. Usually, we will use the array destructuring to simplify the state variable declaration. This is why we write const [name, setName] = useState(”) . This is is similar to this.state.name and this.setState in a class-based component. Reading State Variable In class-based component, we can use state variable: <p>Name: {this.state.name}</p> <p>Total Count: {this.state.count}</p> <p>Is modal open: {this.state.isModalOpen}</p> In a functional component, we can use state variable directly: <p>Name: {name}</p> <p>Total Count: {count}</p> <p>Is modal open: {isModalOpen}</p> Updating State Variable In class-based component, we need to call this.setState to update the state: <button onClick={() => this.setState({ ...state, isModalOpen: false })}> Close Modal </button> But in functional component, we already have a setIsModalOpen function to close the modal: <button onClick={() => setIsModalOpen(false)}> Close Modal </button> Similiarly, setName and setCount are used to update the values of their respective state variables. Rules for using the useState Hook useState follows the same rules that all hooks follow: - Only call useState at the top level. - Only call useState in functional components. The first rule means you should not call useState in loops, conditions, or nested functions, even inside functional components, because React relies on the order in which useState functions are called to get the correct value. if (condition) { const [name, setName] = useState( '' ); setName( 'Rudar' ); } The second rule is easy to follow. Don’t use useState in a class based components. import React, { Component, useState } from 'react'; class App extends Component { render() { const [name, setName] = useState( '' ); return ( <p>Name: {name}</p> ) } } If you are violating this rule you will get an error. Further in the series, we will discuss various hooks in detail. For more details, visit React Docs.
https://blog.knoldus.com/react-hooks-usestate-part-2/?shared=email&msg=fail
CC-MAIN-2021-31
refinedweb
509
56.15
File operations - The JVM is missing some file operations needed by File and friends in Ruby. Some JSRs exist which may fix some of these and we could perhaps call external scripts to perform the rest. This is an area we have not spent any time looking at. Java Limitations - Java consumers cannot see what we are extending (see next item on list) This feature will work once we have a compiler - Extended Java Classes in Ruby will not be visible to Java consumers Consider the following code: include_class 'java.util.ArrayList' class MyList < ArrayList def toString "MYLIST" end end If we send an instance of MyList to a java object which calls toString on it; it will NOT call the toString we defined on it. This will be fixed once we have a compiler.
http://docs.codehaus.org/pages/viewpage.action?pageId=25296916
CC-MAIN-2015-18
refinedweb
135
65.86
I understand the issues and recommendations being made. But, possibly a little more detail in the app is needed. The web pages provided with the app are static and created in English. Upon starting the web app new pages are created that are language based. When deployed the war is always exploded so that access to the scripts, styles, pages, etc. is available to the web app to make new ones and or modify existing ones. Data for the web pages is provided by means of web services where the client browser IE/Firefox makes calls to web services for data (loading/saving) and business logic. Currently the same WAR produced by Ant build script is used in Websphere 7 and WebLogic 11g without issue or modifications needed. We have a customer that has asked me to support Tomcat (assume the cost of Webshere/Weblogic is an issue). Having provide a brief description of system. I have tried the following. I have modified the InitServlet class (removed everything). The following is the complete code of InitServlet package com.surecomp.allMATCH.client; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InitServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public void destroy() { } public void init() throws ServletException { System.out.println("Loaded"); } } I have compiled it and placed the class file into C:\Downloads\tomcat-7\apache-tomcat-7.0.6\webapps\allMATCHWeb\WEB-INF\classes\com\surecomp\allMATCH\client and I expected to see the System.out.println either on the screen or in some log file. I do not see it anywhere. Sincerely, Robert Jenkin Surecomp Services, Inc. 2 Hudson Place, 4th Floor Hoboken, NJ 07030 Skype: robert.jenkin Office: 201 217 1437 | Direct: 201 716 1219 | Mobile: 908 251 0537 -----Original Message----- From: Mark Thomas [mailto:markt@apache.org] Sent: Friday, January 28, 2011 4:00 PM To: Tomcat Users List Subject: Re: deploying a war file and starting the application This mail was sent via Mail-SeCure System.
http://mail-archives.apache.org/mod_mbox/tomcat-users/201101.mbox/%3CDB844CED5F7681439DAE7C35173D899F0E6A713F13@s1mail07%3E
CC-MAIN-2015-48
refinedweb
343
60.82
Giving searchhi a bit of a makeover A user of one of the scripts I wrote a while back, searchhi, dropped me a mail to say: it would be handy if I could take some action if no hits are found. After a bit of probing, it turned out that they were using it for an in-page search — what searchhi actually does is look at the referrer to see if you came here from a Google/Yahoo search and highlight the stuff you searched for — so you could fill in a search form and then search the words in the page and highlight them. I’m at a bit of a loss as to how the built-in browser search (which is Ctrl-F for everyone, I think, although Macs might be different, and I use / on Firefox) doesn’t satisfy this need, but needs must and all that. Hacking both of those things in (have a <form class="searchhi"> in the page and its first textbox will automatically be used as the search entry) was relatively quick. The nice thing about this is that I took the opportunity to tidy the script up a bit; it was written some time ago, and created its functions in the global namespace, was careless about var, that sort of thing. I’m now a bit happier with it — it passes JSLint for a start, modulo that I disagree with Douglas about single-line if — by which I mean that I don’t cringe when I look at it. (I haven’t documented the changes on the searchhi page itself, because the in-page search stuff is obviously JavaScript-dependent and that’s not how you should do it, so I don’t want to encourage people to use it.)
http://www.kryogenix.org/days/2008/12
crawl-002
refinedweb
298
55.85
keyctl_clear - Clear a keyring #include <keyutils.h> long keyctl_clear(key_serial_t keyring); keyctl_clear() clears the contents of a keyring. The caller must have write permission on a keyring to be able clear it. On success keyctl_clear() returns 0. On error, the value -1 will be returned and errno will have been set to an appropriate error. ENOKEY The keyring specified is invalid. EKEYEXPIRED The keyring specified has expired. EKEYREVOKED The keyring specified had been revoked. EACCES The keyring exists, but is not writable by the calling process. This is a library function that can be found in libkeyutils. When linking, -lkeyutils should be specified to the linker. keyctl(1), add_key(2), keyctl(2), request_key(2), keyctl(3), request-key(8)
http://huge-man-linux.net/man3/keyctl_clear.html
CC-MAIN-2018-05
refinedweb
119
79.06
Using the Effect Hook Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. The Effect Hook lets you perform side effects in function components:> ); } This snippet is based on the counter example from the previous page, but we added a new feature to it: we set the document title to a custom message including the number of clicks. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before. Tip If you’re familiar with React class lifecycle methods, you can think of useEffectHook as componentDidMount, componentDidUpdate, and componentWillUnmountcombined. There are two common kinds of side effects in React components: those that don’t require cleanup, and those that do. Let’s look at this distinction in more detail. Effects Without Cleanup Sometimes, we want to run some additional code after React has updated the DOM. Network requests, manual DOM mutations, and logging are common examples of effects that don’t require a cleanup. We say that because we can run them and immediately forget about them. Let’s compare how classes and Hooks let us express such side effects. Example Using Classes In React class components, the render method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM. This is why in React classes, we put side effects into componentDidMount and componentDidUpdate. Coming back to our example, here is a React counter class component that updates the document title right after React makes changes to the DOM:> ); } } Note how we have to duplicate the code between these two lifecycle methods in class. This is because in many cases we want to perform the same side effect regardless of whether the component just mounted, or if it has been updated. Conceptually, we want it to happen after every render — but React class components don’t have a method like this. We could extract a separate method but we would still have to call it in two places. Now let’s see how we can do the same with the useEffect Hook. Example Using Hooks We’ve already seen this example at the top of this page, but let’s take a closer look at it: import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API. Why is useEffect called inside a component? Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect. We don’t need a special API to read it — it’s already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution. Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects. Detailed Explanation Now that we know more about effects, these lines should make sense: function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); } We declare the count state variable, and then we tell React we need to use an effect. We pass a function to the useEffect Hook. This function we pass is our effect. Inside our effect, we set the document title using the document.title browser API. We can read the latest count inside the effect because it’s in the scope of our function. When React renders our component, it will remember the effect we used, and then run our effect after updating the DOM. This happens for every render, including the first one. Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render. This is intentional. In fact, this is what lets us read the count value from inside the effect without worrying about it getting stale. Every time we re-render, we schedule a different effect, replacing the previous one. In a way, this makes the effects behave more like a part of the render result — each effect “belongs” to a particular render. We will see more clearly why this is useful later on this page. Tip. Effects with Cleanup Earlier, we looked at how to express side effects that don’t require any cleanup. However, some effects do. For example, we might want to set up a subscription to some external data source. In that case, it is important to clean up so that we don’t introduce a memory leak! Let’s compare how we can do it with classes and with Hooks. Example Using Classes In a React class, you would typically set up a subscription in componentDidMount, and clean it up in componentWillUnmount. For example, let’s say we have a ChatAPI module that lets us subscribe to a friend’s online status. Here’s how we might subscribe and display that status using a class: class FriendStatus extends React.Component { constructor(props) { super(props); this.state = { isOnline: null }; this.handleStatusChange = this.handleStatusChange.bind(this); } componentDidMount() { ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentWillUnmount() { ChatAPI.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ); } handleStatusChange(status) { this.setState({ isOnline: status.isOnline }); } render() { if (this.state.isOnline === null) { return 'Loading...'; } return this.state.isOnline ? 'Online' : 'Offline'; } } Notice how componentDidMount and componentWillUnmount need to mirror each other. Lifecycle methods force us to split this logic even though conceptually code in both of them is related to the same effect. Note Eagle-eyed readers may notice that this example also needs a componentDidUpdatemethod to be fully correct. We’ll ignore this for now but will come back to it in a later section of this page. Example Using Hooks Let’s see how we could write this component with Hooks. You might be thinking that we’d need a separate effect to perform the cleanup. But code for adding and removing a subscription is so tightly related that useEffect is designed to keep it together. If your effect returns a function, React will run it when it is time to clean up: import React, { useState, useEffect } from 'react'; function FriendStatus(props) { const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); // Specify how to clean up after this effect: return function cleanup() { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; }! When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time. We’ll discuss why this helps avoid bugs and how to opt out of this behavior in case it creates performance issues later below. Note We don’t have to return a named function from the effect. We called it cleanuphere to clarify its purpose, but you could return an arrow function or call it something different. Recap We’ve learned that useEffect lets us express different kinds of side effects after a component renders. Some effects might require cleanup so they return a function: useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); Other effects might not have a cleanup phase, and don’t return anything. useEffect(() => { document.title = `You clicked ${count} times`; }); The Effect Hook unifies both use cases with a single API. If you feel like you have a decent grasp on how the Effect Hook works, or if you feel overwhelmed, you can jump to the next page about Rules of Hooks now. Tips for Using Effects We’ll continue this page with an in-depth look at some aspects of useEffect that experienced React users will likely be curious about. Don’t feel obligated to dig into them now. You can always come back to this page to learn more details about the Effect Hook. Tip: Use Multiple Effects to Separate Concerns One of the problems we outlined in the Motivation for Hooks is that class lifecycle methods often contain unrelated logic, but related logic gets broken up into several methods. Here is a component that combines the counter and the friend status indicator logic from the previous examples: }); } // ... Note how the logic that sets document.title is split between componentDidMount and componentDidUpdate. The subscription logic is also spread between componentDidMount and componentWillUnmount. And componentDidMount contains code for both tasks. So, how can Hooks solve this problem? Just like you can use the State Hook more than once, you can also use several effects. This lets us separate unrelated logic into different effects: function FriendStatusWithCounter(props) { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; });); }; }); // ... } Hooks let us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified. Explanation: Why Effects Run on Each Update If you’re used to classes, you might be wondering why the effect cleanup phase happens after every re-render, and not just once during unmounting. Let’s look at a practical example to see why this design helps us create components with fewer bugs. Earlier on this page, we introduced an example FriendStatus component that displays whether a friend is online or not. Our class reads friend.id from this.props, subscribes to the friend status after the component mounts, and unsubscribes during unmounting: componentDidMount() { ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentWillUnmount() { ChatAPI.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ); } But what happens if the friend prop changes while the component is on the screen? Our component would continue displaying the online status of a different friend. This is a bug. We would also cause a memory leak or crash when unmounting since the unsubscribe call would use the wrong friend ID. In a class component, we would need to add componentDidUpdate to handle this case: ); } Forgetting to handle componentDidUpdate properly is a common source of bugs in React applications. Now consider the version of this component that uses Hooks: function FriendStatus(props) { // ... useEffect(() => { // ... ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); It doesn’t suffer from this bug. (But we also didn’t make any changes to it.) There is no special code for handling updates because useEffect handles them by default. It cleans up the previous effects before applying the next effects. To illustrate this, here is a sequence of subscribe and unsubscribe calls that this component could produce over time: // This behavior ensures consistency by default and prevents bugs that are common in class components due to missing update logic. Tip: Optimizing Performance by Skipping Effects In some cases, cleaning up or applying the effect after every render might create a performance problem. In class components, we can solve this by writing an extra comparison with prevProps or prevState inside componentDidUpdate: componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { document.title = `You clicked ${this.state.count} times`; } } This requirement is common enough that it is built into the useEffect Hook API. You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect: useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only re-run the effect if count changes In the example above, we pass [count] as the second argument. What does this mean? If the count is 5, and then our component re-renders with count still equal to 5, React will compare [5] from the previous render and [5] from the next render. Because all items in the array are the same ( 5 === 5), React would skip the effect. That’s our optimization. When we render with count updated to 6, React will compare the items in the [5] array from the previous render to items in the [6] array from the next render. This time, React will re-apply the effect because 5 !== 6. If there are multiple items in the array, React will re-run the effect even if just one of them is different. This also works for effects that have a cleanup phase: In the future, the second argument might get added automatically by a build-time transformation. changes. Next Steps Congratulations! This was a long page, but hopefully by the end most of your questions about effects were answered. You’ve learned both the State Hook and the Effect Hook, and there is a lot you can do with both of them combined. They cover most of the use cases for classes — and where they don’t, you might find the additional Hooks helpful. We’re also starting to see how Hooks solve problems outlined in Motivation. We’ve seen how effect cleanup avoids duplication in componentDidUpdate and componentWillUnmount, brings related code closer together, and helps us avoid bugs. We’ve also seen how we can separate effects by their purpose, which is something we couldn’t do in classes at all. At this point you might be questioning how Hooks work. How can React know which useState call corresponds to which state variable between re-renders? How does React “match up” previous and next effects on every update? On the next page we will learn about the Rules of Hooks — they’re essential to making Hooks work.
https://ml.reactjs.org/docs/hooks-effect.html
CC-MAIN-2021-04
refinedweb
2,413
55.95
!ATTLIST div activerev CDATA #IMPLIED> <!ATTLIST div nodeid CDATA #IMPLIED> <!ATTLIST a command CDATA #IMPLIED> I would like to create my own file format, which is text based, which is imported by the editor and then made available to the runtime player as an prefab object. I other words, I would like to mimic what happens with fbx. The editor reads it, shows any editable properties in the project window, it becomes part of the build, and then the player can instantiate a copy of it at runtime. Is it reasonable to think I can do this with the current C# API? I know I can load a txt extension as a TextAsset, and then process it at runtime. But I'm burning cycles at runtime and I would rather the importer did most of the processing. asked May 21 '10 at 09:48 PM Brian 4 215 ● 7 ● 9 ● 15 I know this is kind of old, but it really bugs me that the only answers here are to use TextAssets which you then parse at runtime. The correct answer is to create an AssetPostprocessor and override the OnPostprocessAllAssets method. Like so: using UnityEngine; using UnityEditor; public class CustomPostprocessor : AssetPostprocessor { /// <summary> /// Handles when ANY asset is imported, deleted, or moved. Each parameter is the full path of the asset, including filename and extension. /// </summary> /// <param name="importedAssets">The array of assets that were imported.</param> /// <param name="deletedAssets">The array of assets that were deleted.</param> /// <param name="movedAssets">The array of assets that were moved. These are the new file paths.</param> /// <param name="movedFromPath">The array of assets that were moved. These are the old file paths.</param> private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) { foreach(string asset in importedAssets) { Debug.Log("Imported: " + asset); } foreach (string asset in deletedAssets) { Debug.Log("Deleted: " + asset); } for (int i = 0; i < movedAssets.Length; i++ ) { Debug.Log("Moved: from " + movedFromPath[i] + " to " + movedAssets[i]); } } } Then you can use the standard Mono libraries to parse the files and do whatever you want in Unity. answered Dec 06 '10 at 06:48 PM GlitchEnzo2 288 ● 3 ● 4 ● 14 Do you have an example of the code that actually imports something in OnPostprocessAllAssets()? I'm trying to create a GameObject and save it as asset with AssetDatabase.CreateAsset(go,path+".asset"); but the result seems broken somehow (unity crashes eventually). Also, the GameObject immediately appears in the current scene, which is not my intention... AssetDatabase.CreateAsset(go,path+".asset"); After some more research: is is possible to process custom files in OnPostprocessAllAssets() and create assets but impossible to create prefabs with hierarchy of game objects. That's because it's impossible to create a GameObject suitable for storing in a prefab (like OnPostprocessModel() receives) on your own. OnPostprocessAllAssets() OnPostprocessModel() I have never tried this, but you could give this a shot: Make your file be imported as a textfile. Write an AssetPostProcessor, and in that do the parsing of the text, create a bunch of new objects (texture2d, material, custom scriptableobjects, AnimationClips, whatever), and use AssetDatabase.AddObjectToAsset() to add it to the just imported file. Again, I'm not 100% sure this will work, but it's a good first shot. Please be aware that Unity2.6.1 has a bug that makes a textasset being read as binary be garbled, so use an actual textformat, and not a binary one. I fixed this for Unity3. answered May 22 '10 at 10:31 PM Lucas Meijer 1 ♦♦ 7.9k ● 19 ● 43 ● 85 Thanks for the suggestion. It gave me an error that the asset is not persistent. OnPostprocessModel is almost working. When I get this event for the FBX import, I load the associated text file. I can then create additional GameObjects... GameObject newgo = new GameObject( name ); newgo.transform.parent = go.transform; I then create a mesh based on the text file... Mesh mesh = new Mesh(); ...populate mesh... newgo.AddComponent< MeshFilter >().sharedMesh = mesh; At runtime, I see the new GameObject with a MeshFilter, but the mesh is missing. Any ideas what is wrong? Hi! I would like to import my own formats, too. These are to then emerge also in the Project folder and also the characteristics them have to point out. For example Xpresso tags or simply only dependence of each other. I have already tried with the function AssetDatabase.AddObjectToAsset () to get ahead. however unsuccessfully. Can someone help me? Thanks a lot. answered Jun 01 '11 at 12:31 PM hunn3s 1 ● 1 ● 1 ● 1 You can't create your own file formats that Unity imports, as far as I know. Sure, you can stick whatever files you want inside your Assets folder, and you could MAYBE write an editor script to have a custom Inspector for those files, but that's unreasonable. Here's what you can do that should be relatively easy: public TextAsset myTextFile; Now, in that script, you'll have your text file with all its data in it. You can read how to get the data of the text file by checking out the TextAsset documentation. answered May 21 '10 at 10:15 PM qJake 11.6k ● 43 ● 78 ● 161 Yeah, right now I'm basically doing that. But it means that all the parsing is happening at runtime, which is slow. I would rather have the editor parse the file during import and create an object that I can then include with the build and instantiate as needed. The documentation seems to elude to having classes that will do this, but it isn't very clear. Parsing a file shouldn't take that long. Try timing it to see how fast it actually goes. You could also just parse it in Start() or Awake(), which is where most of your "slow code" should go anyway. You can then store references to your created objects and just pass them around as needed (which is extremely fast and efficient). Would it be possible to run the script to parse the text file once, and save the resulting GameObjects while the editor is running the game? That way, once you stop the editor running the engine you still have your generated GameObjects that you can include with the build, and remove your TextAsset and generator x417 custom x199 importer x26 asked: May 21 '10 at 09:48 PM Seen: 4827 times Last Updated: Apr 13 at 10:34 PM Custom Asset Files Editor Window with settings and Asset Creation Custom Asset Icons? Creating an asset from script? Custom Inspector when Selecting from Project Tree? Dynamic Asset loading? How to encrypt Asset Bundles Extending support for other file formats. How I can get an instace of a material, created in a project panel How do I load the assets from a tutorial? EnterpriseSocial Q&A
http://answers.unity3d.com/questions/17831/how-can-i-create-a-custom-import-object.html
CC-MAIN-2013-20
refinedweb
1,140
65.12
I have my values in a two dimensional list. a = [[5,2],[7,4],[0,3]] from operator import itemgetter b = [((i, j), v) for i, t in enumerate(a) for j, v in enumerate(t)] b.sort(key=itemgetter(-1), reverse=True) print(b) coords, vals = zip(*b) print(vals) print(coords) [((1, 0), 7), ((0, 0), 5), ((1, 1), 4), ((2, 1), 3), ((0, 1), 2), ((2, 0), 0)] (7, 5, 4, 3, 2, 0) ((1, 0), (0, 0), (1, 1), (2, 1), (0, 1), (2, 0)) cumulative_sum = np.cumsum(a) cumulative_sum a (1,0) (0,0) This is easily done using a simple for loop to iterate over the (coordinate, value) pairs in b. The trick is to test if the sum would overflow the desired limit before we add the coordinate tuple t to the list of coordinates in selected. from operator import itemgetter a = [[5,2],[7,4],[0,3]] b = [((i, j), v) for i, t in enumerate(a) for j, v in enumerate(t)] b.sort(key=itemgetter(-1), reverse=True) coords, vals = zip(*b) total = sum(vals) lim = int(0.68 * total) selected = [] s = 0 for t, v in b: if s + v <= lim: s += v selected.append(t) else: break print(s, selected) output 12 [(1, 0), (0, 0)] The limit calculation could be written as lim = 0.68 * total but if your data is guaranteed to be integers then it's neater to have lim as an integer too, because comparing 2 integers is slightly more efficient than comparing an integer to a float. When you do an operation combining an int with a float (and that includes comparisons) they have to be converted to a common type to perform the operation.
https://codedump.io/share/uMYO9DpuXQ2E/1/python---selecting-elements-that-sum-up-to-the-68-of-the-cumulative-sum-in-a-2d-list
CC-MAIN-2017-34
refinedweb
292
56.79
Due: , 11:59 pm The main purpose of this project. For this assignment you will implement classes to represent a card, a hand, a deck, and the game Blackjack. The result will be a text-based version of the game that runs in the terminal. You are free to make the game more complex as an extension. The purpose of the assignment is not to create a Blackjack game for people to play, however, but to study the properties of Blackjack, given a particular rule set, when played over many hands. You are using CS to study the properties of a system defined by a set of rules. More information about Blackjack. Create a java class called Card, which should hold all information unique to the card. For this assignment, it needs only to hold the value of the card, which must be in the range 1-10. The Card class should have the following methods. In addition, make a main method that uses each of the class methods. public Card()a constructor with no arguments. public Card(int v)a constructor with the value of the card, possibly doing range checking. public int getValue()return the numeric value of the card. Create a java class called Hand, which should hold a set of cards. You can use an ArrayList ( import java.util.ArrayList) to hold the Card objects. The class should have at least the following methods. public Hand()initialize the ArrayList. public void reset()reset the hand to empty. public void add( Card card )add the card object to the hand. public int size()returns the number of cards in the hand. public Card getCard( int i )returns the card with index i. Cast as appropriate. public int getTotalValue()returns the sum of the values of the cards in the hand. public String toString()returns a String that has the contents of the hand "written" in a nice format. Create a java class called Deck, which should hold a set of cards and be able to shuffle and deal the cards. You should use an ArrayList to hold the cards. The class should support the following methods. public Deck()builds a deck of 52 cards, 4 each of cards with values 1-9 and 16 cards with the value 10. Note, you probably want the constructor to call the build() method, below. public void build()builds a deck of 52 cards, 4 each of cards with values 1-9 and 16 cards with the value 10. public Card deal()returns the top card (position zero) and removes it from the deck. public Card pick( int i)(optional) returns the card at position i and removes it from the deck. public void shuffle()shuffles the deck. This method should put the deck in random order. One way to do it is to build a fresh second deck and then make n random picks from it, where n is the size of the deck at the time of the shuffle. Note that the first pick should be in the range [0, n-1], the second pick should be in the range [0, n-2] and so on. You may want to generate a seed for the Random object by using the function System.currentTimeMillis()so that each run of a game is different. You are expected to implement the shuffle method. Please do not use Collection.shuffle(). public String toString()returns a String that has the contents of the deck "written" in a nice format (so that you can see the ordering of the card values). Create a class called Blackjack that implements a simple version of the card game. The class will need to have a Deck, a Hand for the player, a Hand for the dealer, and scores for both the dealer and player. The main function for the Blackjack class should implement one complete game. public Blackjack()should set up and reset the game (call reset(), below). public void reset( boolean newDeck )should set up and reset the game. If newDeck is true, then the function should create a fresh deck. The deck should be shuffled before the game starts. public void deal()should deal out two cards to both players. public String toString()returns a String that has describes the state of the game, including player scores. public boolean playerTurn()have the player draw cards until the total value of the player's hand is equal to or above 16. The function should return false if the player goes over 21 (bust). public boolean dealerTurn()have the dealer draw cards until the total of the dealer's hand is equal to or above 17. The function should return false if the dealer goes over 21. public static class called Simulation. This class should have only a main function that executes 1000 games of Blackjack. It should keep track of how many games the player wins, how many the dealer wins, and many are pushes. Print out the total in the end both as raw numbers and as percentages. Have the dealer take only one card to start, then make the game interactive so that you can decide whether the player takes another card or not. Add betting. [Obviously, this makes simulating many games impossible, so the point is to make a real interactive game.] totaling 21) when evaluating the winning hand. A Blackjack beats a 21 with more than 2 cards. See how these rules affect the simulation results. Make your game use 6 decks, and reshuffle if only 1 deck left. Play the game 1000 times, and observe how many games the player wins, how many the dealer wins, and many are pushes. Run the simulation with different decision rules for the player and see how it affects the outcome percentages over many games (>= 1000). Add a type of betting strategy to the simulation and see if the player can win money even while losing more games than winning. Try running the simulation with different numbers of games and see how variable the results are. For example, run the simulation using M games (e.g. M = 100) and do this N times (e.g. N = 10). Then calculate the standard deviation of the results. Then you can plot the standard deviation versus the number of games (M) in the simulation to see how the results stabilize as you use a larger number of games. For any assignment, a good extension will be to implement a Java class yourself and demonstrate that it has the same functionality as the Java class. For example, you could implement your own ArrayList class for this assignment. Another good extension for any assignment is to identify in comments when memory is being "lost." (Indicate the line of code in which the last reference to an object in memory is removed.) Your writeup should have a simple format. Make your writeup for the project a wiki page in your personal space. If you have questions about making a wiki page, stop by my office or ask in lab. Once you have written up your assignment, give the page the label: cs231f17project.
http://cs.colby.edu/courses/F17/cs231-labs/proj01.php
CC-MAIN-2018-47
refinedweb
1,190
74.08
Annual appeal: Please make a donation to keep the OEIS running! Over 6000 articles have referenced us, often saying "we discovered this result with the help of the OEIS". Other ways to donate 0,2 To show for example that C(2n+1, n+1) is the number of monotone maps from 1..n + 1 to 1..n + 1, notice that we can describe such a map by a nondecreasing sequence of length n + 1 with entries from 1 to n + 1. The number k of increases in this sequence is anywhere from 0 to n. We can specify these increases by throwing k balls into n+1 boxes, so the total is Sum_{k = 0..n} C((n+1) + k - 1, k) = C(2n+1, n+1). Also number of ordered partitions (or compositions) of n + 1 into n + 1 parts. E.g., a(2) = 10: 003 030 300 012 021 102 120 210 201 111. - Mambetov Bektur (bektur1987(AT)mail.ru), Apr 17 2003 Also number of walks of length n on square lattice, starting at origin, staying in first and second quadrants. - David W. Wilson, May 05 2001. (E.g., for n = 2 there are 10 walks, all starting at 0, 0: 0, 1 -> 0, 0; 0, 1 -> 1, 1; 0, 1 -> 0, 2; 1, 0 -> 0, 0; 1, 0 -> 1, 1; 1, 0 -> 2, 0; 1, 0 -> 1, -1; -1, 0 -> 0, 0; -1, 0 -> -1, 1; -1, 0-> -2, 0) Also total number of leaves in all ordered trees with n + 1 edges. Also number of digitally balanced numbers [A031443] from 2^(2n+1) to 2^(2n+2). - Naohiro Nomoto, Apr 07 2001 Also number of ordered trees with 2n + 2 edges having root of even degree and nonroot nodes of outdegree 0 or 2. - Emeric Deutsch, Aug 02 2002 Also number of paths of length 2*d(G) connecting two neighboring nodes in optimal chordal graph of degree 4, G(2*d(G)^2 + 2*d(G) + 1, 2d(G) + 1), where d(G) = diameter of graph G. - S. Bujnowski (slawb(AT)atr.bydgoszcz.pl), Feb 11 2002 Define an array by m(1, j) = 1, m(i, 1) = i, m(i, j) = m(i, j-1) + m(i-1, j); then a(n) = m(n, n). - Benoit Cloitre, May 07 2002 Also the numerator of the constant term in the expansion of cos^2n(x) or sin^2n(x) when the denominator is 2^(2n-1). - Robert G. Wilson v Consider the expansion of cos^n(x) as a linear combination of cosines of multiple angles. If n is odd, then the expansion is a combination of a*cos((2k-1)*x)/2^(n-1) for all 2k - 1 <= n. If n is even, then the expansion is a combination of a*cos(2k*x)/2^(n-1) terms plus a constant. "The constant term, [a(n)/2^(2n-1)], is due to the fact that [cos^2n(x)] is never negative, i.e., electrical engineers would say the average or 'dc value' of [cos^2n(x)] is [a(n)/2^(2n-1)]. The dc value of [cos^(2n-1)(x)] on the other hand, is zero because it is symmetrical about the horizontal axis, i.e., it is negative and positive equally." Nahin[62] - Robert G. Wilson v, Aug 01 2002 Also number of times a fixed Dyck word of length 2k occurs in all Dyck words of length 2n + 2k. Example: if the fixed Dyck word is xyxy (k = 2), then it occurs a(1) = 3 times in the 5 Dyck words of length 6 (n = 1): (xy[xy)xy], xyxxyy, xxyyxy, x(xyxy)y, xxxyyy (placed between parentheses). - Emeric Deutsch, Jan 02 2003 a(n+1) is the determinant of the n X n matrix m(i, j) = binomial(2n-i, j). - Benoit Cloitre, Aug 26 2003 a(n-1) = (2n)!/(2*n!*n!), formula in [Davenport] used by Gauss for the special case prime p = 4*n + 1: x = a(n-1) mod p and y = x*(2n)! mod p are solutions of p = x^2 + y^2. - Frank Ellermann. Example: For prime 29 = 4*7 + 1 use a(7-1) = 1716 = (2*7)!/(2*7!*7!), 5 = 1716 mod 29 and 2 = 5*(2*7)! mod 29, then 29 = 5*5 + 2*2. a(n) = sum{k = 0..n+1, binomial(2n+2, k)*cos((n - k + 1)*Pi)}. - Paul Barry, Nov 02 2004 The number of compositions of 2n, say c_1 + c_2 + ... + c_k = 2n, satisfy that Sum_(i = 1..j)c_i < 2j for all j = 1..k, or equivalently, the number of subsets, say S, of [2n-1] = {1, 2, ..., 2n-1} with at least n elements such that if 2k is in S, then there must be at least k elements in S smaller than 2k. E.g., a(2) = 3 because we can write 4 = 1 + 1 + 1 + 1 = 1 + 1 + 2 = 1 + 2 + 1. - Ricky X. F. Chen (ricky_chen(AT)mail.nankai.edu.cn), Jul 30 2006 a(n) = A122366(n,n). - Reinhard Zumkeller, Aug 30 2006 The number of walks of length 2n + 1 on an infinite linear lattice that begin at the origin and end at node (1). Also the number of paths on a square lattice from the origin to (n+1,n) that use steps (1,0) and (0,1). Also number of binary numbers of length 2n + 1 with n + 1 ones and n zeros. - Stefan Hollos (stefan(AT)exstrom.com), Dec 10 2007 If Y is a 3-subset of an 2n-set X then, for n>=3, a(n-1) is the number of n-subsets of X having at least two elements in common with Y. - Milan Janjic, Dec 16 2007 Also the number of rankings (preferential arrangements) of n unlabeled elements onto n levels when empty levels are allowed. - Thomas Wieder, May 24 2008 Also the Catalan transform of A000225 shifted one index, i.e., dropping A000225(0). - R. J. Mathar, Nov 11 2008 With offset 1. The number of solutions in nonnegative integers to X1 + X2 + ... + Xn = n. The number of terms in the expansion of (X1 + X2 + ... + Xn)^n. The coefficient of x^n in the expansion of (1 + x + x^2 + ...)^n. The number of distinct image sets of all functions taking [n] into [n]. - Geoffrey Critzer, Feb 22 2009 The Hankel transform of the aerated sequence 1, 0, 3, 0, 10, 0, ... is 1, 3, 3, 5, 5, 7, 7, ... (A109613(n+1)). - Paul Barry, Apr 21 2009 Also the number of distinct network topologies for a network of n items with 1 to n - 1 unidirectional connections to other objects in the network. - Anthony Bachler, May 05 2010 Equals INVERT transform of the Catalan numbers starting with offset 1. E.g.: a(3) = 35 = (1, 2, 5) dot (10, 3, 1) + 14 = 21 + 14 = 35. - Gary W. Adamson, May 15 2009 a(n) = 2*A000984(n) - A000108(n), that is, a(n) = 2*c(2n,n) - n-th Catalan number. - Joseph Abate, Jun 11 2010 The integral of 1/(1+x^2)^(n+1) is given by a(n)/2^(2n-1) * (x/(1+x^2)^n*P(x) + arctan(x)), where P(x) is a monic polynomial of degree 2n-2 with rational coefficients. - Christiaan van de Woestijne, Jan 25 2011 a(n) is the number of Schroder paths of semilength n in which the (2,0)-steps at level 0 come in 2 colors and there are no (2,0)-steps at a higher level. Example: a(2) = 10 because, denoting U = (1,1), H = (1,0), and D = (1,-1), we have 2^2 = 4 paths of shape HH, 2 paths of shape HUD, 2 paths of shape UDH, and 1 path of each of the shapes UDUD and UUDD. - Emeric Deutsch, May 02 2011 a(n) is the number of Motzkin paths of length n in which the (1,0)-steps at level 0 come in 3 colors and those at a higher level come in 2 colors. Example: a(3)=35 because, denoting U=(1,1), H=(1,0), and D=(1,-1), we have 3^3 = 27 paths of shape HHH, 3 paths of shape HUD, 3 paths of shape UDH, and 2 paths of shape UHD. - Emeric Deutsch, May 02 2011 Also number of digitally balanced numbers having length 2*(n+1) in binary representation: a(n) = #{m: A070939(A031443(m)) = 2*(n+1)}. - Reinhard Zumkeller, Jun 08 2011 a(n) equals 2^(2n+3) times the coefficient of Pi in 2F1(1/2, n+2, 3/2, -1). - John M. Campbell, Jul 17 2011 For positive n, a(n) equals 4^(n+2) times the coefficient of Pi^2 in integral_{x = 0..Pi/2} x sin^(2n+2)x. - John M. Campbell, Jul 19 2011 a(n-1) = C(2n, n)/2 is the number of ways to assign 2n people into 2 (unlabeled) groups of size n. - Dennis P. Walsh, Nov 09 2011 Equals row sums of triangle A205945. - Gary W. Adamson, Feb 01 2012 a(n-1) gives the number of n-regular sequences defined by Erdős and Gallai in 1960 in connection with the degree sequences of simple graphs. - Matuszka Tamás, Mar 06 2013 a(n) is the sum of falling diagonals of squares in the comment in A085812 (equivalent to the Cloitre formula of Aug 2002). - John Molokach, Sep 26 2013 For n > 0: largest terms of Zigzag matrices as defined in A088961. - Reinhard Zumkeller, Oct 25 2013 Also the number of different possible win/loss round sequences (from the perspective of the eventual winner) in a "best of 2n + 1" two-player game. For example, a(2) = 10 means there are 10 different win/loss sequences in a "best of 5" game (like a tennis match in which the first player to win 3 sets, out of a maximum of 5, wins the match); the 10 sequences are WWW, WWLW, WWLLW, WLWW, WLWLW, WLLWW, LWWW, LWWLW, LWLWW, LLWWW. See also A072600. - Philippe Beaudoin, May 14 2014; corrected by Jon E. Schoenfield, Nov 23 2014 When adding 1 to the beginning of the sequence: Convolving a(n)/2^n with itself equals 2^(n+1). For example, when n = 4: convolving {1, 1/1, 3/2, 10/4, 35/8, 126/16} with itself is 32 = 2^5. - Bob Selcoe, Jul 16 2014 From Tom Copeland, Nov 09 2014: (Start) The shifted array belongs to a family of arrays associated to the Catalan A000108 (t = 1), and Riordan, or Motzkin sums A005043 (t = 0), with the o.g.f. [1 - sqrt(1 - 4x/(1 + (1 - t)x))]/2 and inverse x(1 - x)/[1 + (t - 1)x(1 - x)]. See A091867 for more info on this family. Here is t = -3 (mod signs in the results). Let C(x) = [1 - sqrt(1-4x)]/2, an o.g.f. for the Catalan numbers A000108, with inverse Cinv(x) = x*(1-x) and P(x,t) = x/(1 + t*x) with inverse P(x, -t). O.g.f: G(x) = [-1 + sqrt(1 + 4*x/(1-4x))]/2 = -C[P(-x, 4)]. Inverse o.g.f: Ginv(x) = x*(1+x)/[1 + 4x*(1+x)] = -P(Cinv(-x),-4) (shifted signed A001792). A088218 = 1+ G(x). Equals A001813/2 omitting the leading 1 there. (End) For n > 1: a(n-1) = A166454(2*n,n), central terms in A166454. - Reinhard Zumkeller, Mar 04 2015 Placing n distinguishable balls into n indistinguishable boxes gives A000110(n) (the number of set partitions). - N. J. A. Sloane, Jun 19 2015 The sequence is the INVERTi transform of A049027: (1, 4, 17, 74, 326, ...). - Gary W. Adamson, Jun 23 2015 a(n) is the number of compositions of 2*n + 2 such that the sum of the elements at odd positions is equal to the sum of the elements at even positions. a(2) = 10 because there are 10 such compositions of 6: (3, 3), (1, 3, 2), (2, 3, 1), (1, 1, 2, 2), (1, 2, 2, 1), (2, 2, 1, 1), (2, 1, 1, 2), (1, 2, 1, 1, 1), (1, 1, 1, 2, 1), (1, 1, 1, 1, 1, 1). - Ran Pan, Oct 08 2015 a(n-1) is also the Schur function of the partition (n) of n evaluated at x_1 = x_2 = ... = x_n = 1, i.e., the number of semistandard Young tableaux of shape (n) (weakly increasing rows with n boxes with numbers from {1, 2, ..., n}). - Wolfdieter Lang, Oct 11 2015 Also the number of ordered (rooted planar) forests with a total of n+1 edges and no trivial trees. - Nachum Dershowitz, Mar 30 2016 a(n) is the number of sets (i1,...in) of length n so that n>=i1>=i2>=...in>=1 For instance, n=3 as there are only 10 such sets (3,3,3) (3,3,2) (3,3,1) (3,2,2) (3,2,1) (3,1,1) (2,2,2) (2,2,1) (2,1,1) (1,1,1,) 3,2,1 is each used 10 times respectively. - Anton Zakharov, Jul 04 2016 H. Davenport, The Higher Arithmetic. Cambridge Univ. Press, 7th ed., 1999, ch. V.3 (p. 122). A. Frosini, R. Pinzani and S. Rinaldi, About half the middle binomial coefficient, Pure Math. Appl., 11 (2000), 497-508. Charles Jordan, Calculus of Finite Differences, Chelsea 1965, p. 449. J. C. P. Miller, editor, Table of Binomial Coefficients. Royal Society Mathematical Tables, Vol. 3, Cambridge Univ. Press, 1954. Paul J. Nahin, "An Imaginary Tale, The Story of [Sqrt(-1)]," Princeton University Press, Princeton, NJ 1998, p. 62. L. W. Shapiro and C. J. Wang, Generating identities via 2 X 2 matrices, Congressus Numerantium, 205 (2010), 33-46. N. J. A. Sloane, A Handbook of Integer Sequences, Academic Press, 1973 (includes this sequence). N. J. A. Sloane and Simon Plouffe, The Encyclopedia of Integer Sequences, Academic Press, 1995 (includes this sequence). T. D. Noe and Matuszka Tamás, Table of n, a(n) for n = 0..1200 (first 100 terms from T. D. Noe) J. Abate, W. Whitt, Brownian Motion and the Generalized Catalan Numbers, J. Int. Seq. 14 (2011) # 11.2.6, theorem 4. José Agapito, Ângela Mestre, Maria M. Torres, and Pasquale Petrullo, On One-Parameter Catalan Arrays, Journal of Integer Sequences, Vol. 18 (2015), Article 15.5.1. Martin Aigner, Enumeration via ballot numbers, Discrete Math., 308 (2008), 2544-2563. Elena Barcucci, Andrea Frosini and Simone Rinaldi, On directed-convex polyominoes in a rectangle, Discr. Math., 298 (2005). 62-78. Paul Barry, On Integer-Sequence-Based Constructions of Generalized Pascal Triangles, Journal of Integer Sequences, Vol. 9 (2006), Article 06.2.4. Antonio Bernini, Filippo Disanto, Renzo Pinzani and Simone Rinaldi, Permutations defining convex permutominoes, J. Int. Seq. 10 (2007) # 07.9.7 Ciprian Borcea and Ileana Streinu, On the number of embeddings of minimally rigid graphs, arXiv:math/0207126 [math.MG], 2002. Mireille Bousquet-Mélou, New enumerative results on two-dimensional directed animals, Discr. Math., 180 (1998), 73-106. See Eq. (1). - From N. J. A. Sloane, Jun 03 2012 Jean-Paul Bultel, Samuele Giraudo, Combinatorial Hopf algebras from PROs, arXiv preprint arXiv:1406.6903 [math.CO], 2014. David Callan, A Combinatorial Interpretation for a Super-Catalan Recurrence, Journal of Integer Sequences, Vol. 8 (2005), Article 05.1.8. Peter J. Cameron, Sequences realized by oligomorphic permutation groups, J. Integ. Seqs. Vol. 3 (2000), #00.1.5. Gi-Sang Cheon, Hana Kim, Louis W. Shapiro, Mutation effects in ordered trees, arXiv preprint arXiv:1410.1249 [math.CO], 2014. Dennis E. Davenport, Lara K. Pudwell, Louis W. Shapiro, Leon C. Woodson, The Boundary of Ordered Trees, Journal of Integer Sequences, Vol. 18 (2015), Article 15.5.8. Nachum Dershowitz, 1700 Forests, arXiv preprint arXiv:1608.08740 [cs.DM], 2016. N. Gromov and P. Vieira, Tailoring Three-Point Functions and Integrability IV. Theta-morphism, arXiv preprint arXiv:1205.5288 [hep-th], 2012. - From N. J. A. Sloane, Oct 23 2012 R. K. Guy, Catwalks, sandsteps and Pascal pyramids, J. Integer Sequences, Vol. 3 (2000), Article #00.1.6 Guo-Niu Han, Enumeration of Standard Puzzles Guo-Niu Han, Enumeration of Standard Puzzles [Cached copy] INRIA Algorithms Project, Encyclopedia of Combinatorial Structures 145 A. Ivanyi, L. Lucz, T. Matuszka, and S. Pirzada, Parallel enumeration of degree sequences of simple graphs, Acta Univ. Sapientiae, Informatica, 4, 2 (2012) 260-288. Milan Janjic, Two Enumerative Functions Dmitry Kruchinin, Superposition's properties of logarithmic generating functions, arXiv:1109.1683 [math.CO], 2011-2015. W. Lang, On generalizations of Stirling number triangles, J. Integer Seqs., Vol. 3 (2000), #00.2.4. J. W. Layman, The Hankel Transform and Some of its Properties, J. Integer Sequences, 4 (2001), #01.1.5. H. Li, T. MacHenry, Permanents and Determinants, Weighted Isobaric Polynomials, and Integer Sequences, J. Int. Seq. 16 (2013) #13.3.5, example 40. T. Mansour, M. Shattuck, A statistic on n-color compositions and related sequences, Proc. Indian Acad. Sci. (Math. Sci.) Vol. 124, No. 2, May 2014, pp. 127-140. M. D. McIlroy, Letter to N. J. A. Sloane (no date). Y. Puri and T. Ward, Arithmetic and growth of periodic orbits, J. Integer Seqs., Vol. 4 (2001), #01.2.1. Louis Shapiro, Problem 10753 Amer. Math. Monthly, Vol. 106, No. 8 (Oct., 1999), p. 777. Louis Shapiro et al., Leaves of Ordered Trees: 10753, Amer. Math. Monthly, Vol. 108, No. 9 (Nov., 2001), pp. 873-874 Eric Weisstein's World of Mathematics, Binomial Coefficient Eric Weisstein's World of Mathematics, Odd Graph Index entries for "core" sequences a(n-1) = binomial(2*n, n)/2 = (2*n)!/(2*n!*n!). a(0) = 1, a(n) = 2*(2*n+1)*a(n-1)/(n+1) for n > 0. G.f.: (1/sqrt(1-4*x)-1)/(2*x). L.g.f. log((1-sqrt(1-4*x))/(2*x)) = sum(n>0, a(n)/n*x^n). - Vladimir Kruchinin, Aug 10 2010 G.f.: 2F1(1,3/2;2;4*x). - Paul Barry, Jan 23 2009 G.f.: 1/(1-2x-x/(1-x/(1-x/(1-x/(1-... (continued fraction). - Paul Barry, May 06 2009 G.f.: c(x)^2/(1-x*c(x)^2), c(x) the g.f. of A000108. - Paul Barry, Sep 07 2009 O.g.f.: c(x)/sqrt(1-4*x) = (2 - c(x))/(1-4*x), with c(x) the o.g.f. of A000108. Added second formula. - Wolfdieter Lang, Sep 02 2012 Convolution of A000108 (Catalan) and A000984 (central binomial): Sum(C(k)*binomial(2*(n-k), n-k), k=0..n), C(k) Catalan. - Wolfdieter Lang, Dec 11 1999 a(n) = sum(k=0..n, C(n+k, k)). - Benoit Cloitre, Aug 20 2002 a(n) = sum(k=0..n, C(n, k)*C(n+1, k+1)). - Benoit Cloitre, Oct 19 2002 a(n) = 4^n*binomial(n+1/2, n)/(n+1). - Paul Barry, May 10 2005 E.g.f.: sum(n>=0, a(n)*x^(2*n+1)/(2*n+1)!) = BesselI(1, 2*x). - Michael Somos, Jun 22 2005 E.g.f. in Maple notation: exp(2*x)*(BesselI(0, 2*x)+BesselI(1, 2*x)). Integral representation as n-th moment of a positive function on [0, 4]: a(n)=int(x^n*((x/(4-x))^(1/2)), x=0..4)/(2*Pi), n=0,1... This representation is unique. - Karol A. Penson, Oct 11 2001 Narayana transform of [1, 2, 3,...]. Let M = the Narayana triangle of A001263 as an infinite lower triangular matrix and V = the Vector [1, 2, 3,...]. Then A001700 = M * V. - Gary W. Adamson, Apr 25 2006 a(n) = C(2*n, n) + C(2*n, n-1) = A000984(n) + A001791(n). - Zerinvary Lajos, Jan 23 2007 a(n) = n*(n+1)*(n+2)*...*(2*n-1)/n! (product of n consecutive integers, divided by n!). - Jonathan Vos Post, Apr 09 2007 a(n-1) = (2*n-1)!/(n!*(n-1)!). - William A. Tedeschi, Feb 27 2008 a(n) = (2*n+1)*A000108(n). - Paul Barry, Aug 21 2007 Binomial transform of A005773 starting (1, 2, 5, 13, 35, 96,...) and double binomial transform of A001405. - Gary W. Adamson, Sep 01 2007 Row sums of triangle A132813. - Gary W. Adamson, Sep 01 2007 Row sums of triangle A134285. - Gary W. Adamson, Nov 19 2007 Conjectured: 4^n GaussHypergeometric(1/2,-n;2;1) --Solution for the path which stays in the first and second quadrant. - Benjamin Phillabaum, Feb 20 2011 a(n)= sum(0<=k<=n, A038231(n,k)*(-1)^k*A000108(k)). - Philippe Deléham, Nov 27 2009 Let A be the Toeplitz matrix of order n defined by: A[i,i-1]=-1, A[i,j]=Catalan(j-i), (i<=j), and A[i,j]=0, otherwise. Then, for n>=1, a(n)=(-1)^n*charpoly(A,-2). - Milan Janjic, Jul 08 2010 a(n) is the upper left term of M^(n+1), where M is the infinite matrix in which a column of (1,2,3,...) is prepended to an infinite lower triangular matrix of all 1's and the rest zeros, as follows: 1, 1, 0, 0, 0, ... 2, 1, 1, 0, 0, ... 3, 1, 1, 1, 0, ... 4, 1, 1, 1, 1, ... ... Alternatively, a(n) is the upper left term of M^n where M is the infinite matrix: 3, 1, 0, 0, 0, ... 1, 1, 1, 0, 0, ... 1, 1, 1, 1, 0, ... 1, 1, 1, 1, 1, ... - Gary W. Adamson, Jul 14 2011 a(n) = (n+1)*hypergeom([-n, -n], [2], 1). - Peter Luschny, Oct 24 2011 a(n) = pochhammer(n+1,n+1)/(n+1)!. - Peter Luschny, Nov 07 2011 E.g.f.: 1+6*x/(U(0)-6*x); U(k)=k^2+(4*x+3)*k+6*x+2-2*x*(k+1)*(k+2)*(2*k+5)/U(k+1); (continued fraction). - Sergei N. Gladkovskii, Nov 18 2011 a(n) = 2*A000984(n) - A000108(n). [Abate & Whitt] a(n) = 2^(2*n+1)*binomial(n+1/2, -1/2). - Peter Luschny, May 06 2014 a(n) = 2*4^n*Gamma(3/2+n)/(sqrt(Pi)*Gamma(2+n)). - Peter Luschny, Dec 14 2015 a(n) ~ 2*4^n*(1-(5/8)/n+(73/128)/n^2-(575/1024)/n^3+(18459/32768)/n^4)/sqrt(n*Pi). - Peter Luschny, Dec 16 2015 a(n) = (-1)^(n)*B(n,n+1,-n-1)/n!, where B(n,a,x) is a generalized Bernoulli polynomial. - Vladimir Kruchinin, Apr 06 2016. a(n) = Gamma(2 + 2*n)/(n!*Gamma(2 + n)). Andres Cicuttin, Apr 06 2016 a(n) = (n + (n + 1))!/(Gamma(n)*Gamma(1 + n)*A002378(n)), for n>0. Andres Cicuttin, Apr 07 2016 From Ilya Gutkovskiy, Jul 04 2016: (Start) Sum_{n>=0} 1/a(n) = 2*(9 + 2*sqrt(3)*Pi)/27 = A248179. Sum_{n>=0} (-1)^n/a(n) = 2*(5 + 4*sqrt(5)*arcsinh(1/2))/25 = 2*(5*A145433 - 1). Sum_{n>=0} (-1)^n*a(n)/n! = BesselI(2,2)*exp(-2) = A229020*A092553. (End) There are a(2)=10 ways to put 3 indistinguishable balls into 3 distinguishable boxes, namely, (OOO)()(), ()(OOO)(), ()()(OOO), (OO)(O)(), (OO)()(O), (O)(OO)(), ()(OO)(O), (O)()(OO), ()(O)(OO), and (O)(O)(O). - Dennis P. Walsh, Apr 11 2012 a(2) = 10: Semistandard Young tableaux for partition (3) of 3 (the indeterminates x_i, i = 1, 2, 3 are omitted and only their indices are given): 111, 112, 113, 122, 123, 133, 222, 223, 233, 333. - Wolfdieter Lang, Oct 11 2015 A001700 := n -> binomial(2*n+1, n+1); seq(A001700(n), n=0..20); Table[ Binomial[2n + 1, n + 1], {n, 0, 23}] CoefficientList[ Series[2/((Sqrt[1 - 4 x] + 1)*Sqrt[1 - 4 x]), {x, 0, 22}], x] (* Robert G. Wilson v, Aug 08 2011 *) (Sage) [rising_factorial(n+1, n+1)/factorial(n+1) for n in (0..22)] # Peter Luschny, Nov 07 2011 (PARI) a(n)=binomial(2*n+1, n+1) (Haskell) a001700 n = a007318 (2*n+1) (n+1) -- Reinhard Zumkeller, Oct 25 2013 (MAGMA) [Binomial(2*n, n)/2: n in [1..40]]; // Vincenzo Librandi, Nov 10 2014 (PARI) z='z+O('z^50); Vec((1/sqrt(1-4*z)-1)/(2*z)) \\ Altug Alkan, Oct 11 2015 (Python) from __future__ import division A001700_list, b = [], 1 for n in range(10**3): A001700_list.append(b) b = b*(4*n+6)//(n+2) # Chai Wah Wu, Jan 26 2016 (Maxima) B(n, a, x):=coeff(taylor(exp(x*t)*(t/(exp(t)-1))^a, t, 0, 20), t, n)*n!; makelist((-1)^(n)*B(n, n+1, -n-1)/n!, n, 0, 10); /* Vladimir Kruchinin, Apr 06 2016 */ Cf. A000110, A007318, A030662, A046097, A060897-A060900, A049027, A076025, A076026, A060150, A028364, A050166, A039598, A001263, A005773, A001405, A132813, A134285. Equals A000984(n+1)/2. Cf. A030662, A046097. a(n) = (2n+1)*Catalan(n) [A000108] = A035324(n+1, 1) (first column of triangle). Row sums of triangles A028364, A050166, A039598. Bisections: a(2*k)= A002458(k), a(2*k+1)= A001448(k+1)/2, k>=0. Other versions of the same sequence: A088218, A110556, A138364. Diagonals 1 and 2 of triangle A100257. Second row of array A102539. Column of array A073165. Row sums of A103371. - Susanne Wienand, Oct 22 2011 Cf. A002054: C(2n+1,n-1). - Bruno Berselli, Jan 20 2014 Cf. A005043, A091867, A001792, A001813. Cf. A166454. Sequence in context: A167403 A088218 A110556 * A072266 A085282 A149036 Adjacent sequences: A001697 A001698 A001699 * A001701 A001702 A001703 easy,nonn,nice,core,changed N. J. A. Sloane, Apr 30 1991 Name corrected by Paul S. Coombes, Jan 11 2012 Name corrected by Robert Tanniru, Feb 01 2014 approved
https://oeis.org/A001700
CC-MAIN-2017-47
refinedweb
4,303
75.61
Hi, I need to make an application to recognize pt-BR, i've tryed to use System.Speech but this namespace don't have support for pt-BR, after that i've found Microsoft.Speech that have support for pt-BR, what I want to know is if have some way of doing the recognition without having to create the entire dictionary in a .GRXML file? I'm making this question because the System.Speech has the class DictationGrammar that have already the whole words recognition, but in English (en-US). Thank you for your attention. Hi Raphael, currently Microsoft only provides the following speech recognition engines in Win7: English (U.S. and British), Spanish, German, French, Japanese and Chinese (traditional and simplified). To install one of these languages you just need to install the correspondent language pack for the choosen language. For server side there´re a lot of other speech engines for other languages available, including pt-br. If you to develop server side app in Brazilian-Portuguese you need to have a Windows Server + Speech Server installed. Regards Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site. Would you like to participate?
http://social.msdn.microsoft.com/Forums/en-US/4aa94871-3c06-4a65-bc46-c4834a8e025d/speech-recognition-for-portuguese-brazil?forum=windowsgeneraldevelopmentissues
CC-MAIN-2014-35
refinedweb
221
65.01
We. Measuring real-world performance of websites is difficult and error prone today. Developers are forced to use hacks, such as injecting low resolution JavaScript timestamps throughout their code, which slows down the pages for end users, introduces an observer effect, and provides inaccurate results which can drive the wrong behavior. The browser knows exactly how long it takes to load and execute a webpage, so we believe the right solution is for the browser to provide developers an API to access these performance results. Web developers shouldn’t have to think about how to measure performance – it should just be available for them. It’s important for this API to be interoperable across all browsers and platforms so that developers can consistently rely on these results. The Web Timing specification at the W3C is a good foundation for solving this problem in an interoperable manner. The implementation that you’ll find in the latest IE9 platform preview is based off the navigation section of Web Timings and we’ve started conversations with the W3C and other browser manufacturers about working together to get Web Timing chartered and broadly supported. Let’s take a closer look at how developers are forced to measure performance today and what the new API’s enable. How Developers Measure Performance Today Today, in order to collect performance metrics a web developer has to instrument their code with specific timing markers at strategic places on their web page. This can result in code that opposes performance best practices. Developers write something like this: <html> <head> <script type=”text/javascript”> var start = (new Date).getTime(); </script> </head> <body> <script type=”text/javascript”> /* do work here */ var pageLoad = (new Date).getTime() - start; </script> </body> </html> This approach has several problems. It forces the JavaScript engine to load earlier than normal. It forces the HTML and JavaScript parsers to switch contexts. It may block parallel requests to load the remaining resources. Something else to mention is that this JavaScript approach does not capture network latency timings, which is the time associated from when the document is initially requested from the server to the time it arrives and is displayed to the end-user. Additionally, while the Date function is available across all browsers, the results vary in precision. John Resig has a nice blog post in which he goes to some lengths to determine that the time from (new Date).getTime(); is as precise as 7.5ms on average across browsers, half the interval for the Windows system timer at 15ms. Many operations can execute in under 1ms which means that some measurements can have an error range of 750%! How Developers can Measure Performance with Internet Explorer 9 The third Internet Explorer 9 platform preview contains a prototype implementation of the Web Timings NavigationTiming interface called window.msPerformance.timing. Following convention, we use a vendor prefix (ms) on the namespace because the spec is under development. There are no other implementations yet, and therefore no interoperability with other browsers. This interface captures key timing information about the load of the root document with sub-millisecond accuracy, which is immediately available from the DOM once the page had loaded. window.msPerformance.timing interface MSPerformanceTiming{ readonly attribute unsigned longlong navigationStart; readonly attribute unsigned longlong fetchStart; readonly attribute unsigned longlong unloadStart; readonly attribute unsigned longlong unloadEnd; readonly attribute unsigned longlong domainLookupStart; readonly attribute unsigned longlong domainLookupEnd; readonly attribute unsigned longlong connectStart; readonly attribute unsigned longlong connectEnd; readonly attribute unsigned longlong requestStart; readonly attribute unsigned longlong requestEnd; readonly attribute unsigned longlong responseStart; readonly attribute unsigned longlong responseEnd; readonly attribute unsigned longlong domLoading; readonly attribute unsigned longlong domInteractive; readonly attribute unsigned longlong domContentLoaded; readonly attribute unsigned longlong domComplete; readonly attribute unsigned longlong loadStart; readonly attribute unsigned longlong loadEnd; readonly attribute unsigned longlong firstPaint; readonly attribute unsigned longlong fullyLoaded; } For the first time, web developers can accurately understand how long it takes to load their page on their customer’s machines. They have access to when the end-user starts navigation ( navigationStart), the network latency related to loading the page ( responseEnd - fetchStart), and the elapsed time to load the page within the browser. Developers can use this information to adapt their applications at runtime for maximum performance, and they can use their favorite serialization interface to package these timings and store them on the server to establish performance trends. With JSON, this would look something like this: JSON.Stringify(window.msPerformance); Another useful feature of window.msPerformance is the ability to only query for the elapsed time taken in important time phases of loading the document called timingMeasures. window.msPerformance.timingMeasures interface MSPerformanceTimingMeasures{ readonly attribute unsigned longlong navigation; readonly attribute unsigned longlong fetch; readonly attribute unsigned longlong unload; readonly attribute unsigned longlong domainLookup; readonly attribute unsigned longlong connect; readonly attribute unsigned longlong request; readonly attribute unsigned longlong response; readonly attribute unsigned longlong domLoading; readonly attribute unsigned longlong domInteractive; readonly attribute unsigned longlong domContentLoaded; readonly attribute unsigned longlong domComplete; readonly attribute unsigned longlong load; readonly attribute unsigned longlong firstPaint; readonly attribute unsigned longlong fullyLoaded; } Simply access window.msPerformance.timingMeasures.navigation after the page has been loaded and you have the time taken to perform the navigation to the loaded document. Finally, the window.msPerformance.navigation interface contains information such as the type of navigation and additional network activity that occurred on the page to help describe the overall navigation experience. window.msPerformance.navigation interface MSPerformanceNavigation{ const unsigned short NAVIGATION = 0; const unsigned short RELOAD_BACK_FORWARD = 1; readonly attribute unsigned longlong type; readonly attribute unsigned longlong redirectedCount; readonly attribute unsigned longlong uniqueDomains; readonly attribute unsigned longlong requestCount; readonly attribute unsigned longlong startTime; } Let’s look at it in action On the IE9 Test Drive site, you can try the window.msPerformance Test Drive demo. There you see a visualization of the time to load the demo page as shown below. In this example, the overall navigation took 111ms to go from when the link is clicked to the time the contents are loaded within the platform preview. Check it out! Everything described here is available now in the third platform preview. Check it out at and try out the window.msPerformance Test Drive demo. This interface is a prototype of a working draft. The API may change, but we want to release this early so that developers can begin to use the API and provide feedback. Please give window.msPerformance interface a try and let us know what you think by providing feedback through the Connect. Anderson Quach Program Manager Edit 6/29 – correction in sentence describing demo page load time. Overall navigation took 111ms, not 72ms. If you're interested in setting good examples for other developers, that timing code should really be (new Date()).getTime() Very nice! This is something we the devlopers have needed for a loooong time! I'm really looking forward to IE9. Can you say something about when you think IE9 will be ready? 🙂 What does the firstPaint process stand for? hAI: Maybe when the render starts. IETeam: This is a very usefull feature! Are you planing to standardize this in BOM? Hope other browsers will implement this feature as well with same(!) interface. It is a great idea. How about a memory and processor profiler too? Performance is good, but despite what IE touts, it's HTML5 support in the previews is still rather pathetic in comparison to Webkit or Gecko. Last I checked, the Firefox nightly got 199/300, and Webkit got 220/300. IE is still not to 100, last I checked. Maybe my morning coffee hasn't kicked in yet, but where does that 72ms come from? Shouldn't it be 111ms? This system is absolutely fantastic. I don't expect it to come from Microsoft, but I would absolutely love to see someone explain what all of the timings mean and provide recommendations on how to improve times for various configurations (classic LAMP stack, IIS, etc.) Additionally, none of my comments seem to be showing up in Firefox. Do they need to be approved? Can the system at least acknowledge that somehting was sent and that it needs that or something? I keep thinking the system failed. What is up with that? @Timothy J Warren html5test page has several issues. For instance it portraits WebGL as part of HTML5 which is it isn't. It isn'tr even a W3C spec but a private initiative. Great! Can this be submitted as a standard that other browser would support? I would be great to compare timings from browser to browser. I wonder what Steve Souders would have to say… @Jean-Philippe– As mentioned in the post itself, the Web Timing spec is in the W3C. And as he said at Velocity, Steve is very happy to see this in IE9. These measurements are an excellent development. Now, I'm not sure where to log this (does this belong in IE bugs?) but if I log out of MSDN, I get a message telling me that to finish signing out, I must "try clearing all of your browser cookies, and then close all browser windows"! Now that is absolutely ludicrous: why I should I have to lose all my cookies and close all my browser windows, just to log out of MSDN? Similarly, if I log out of my bank, I get a message telling me to close all my browser windows (which, obviously, is a hugely inconvenient thing for me to have to do – especially if this era of multi-tabbed windows). Shouldn't IE have a feature that allows you to close the session(s) belonging to a particular website without having to close all browser windows (and definitely without having to clear all sites' cookies)? With all the speed improvements in IE9 and other competing browsers, the performance range is going to vary wildly depending on the browser, the OS and/or the device. If we are to abide to your commendable "same markup" drive, and renounce any sort of browser detection, it's hard to risk exploiting all the capabilities of IE9 if this might expose some of our users to a bad experience (like some 1FPS animation we get from some examples on the test drive page). It would be useful to have some kind of performance index (à la Windows) so we can either tone down animations and effects to a usable level or, as a last resort, warn the user that the page might be unusable on their browser/platform/hardware. Is there any work or standard being made on that front? If not, what approach would you recommend? @MarioCossi: Don't forget that performance might suddenly decline because of background tasks or energy-saving throttling. The best way to go is to build scalable applications. @Brian LePore: Yes, that was an editing mistake based on an earlier version of this post. The proper value is 111ms not 72ms. Excellent work! And great to see Internet Explorer take the lead in a specific area instead of lagging behind! 🙂 This will result in more accurate <a href="stevesouders.com/…/a> measurements and also more <em>extensive</em> <a href="wimleers.com/…/master-thesis-proposal-web-performance-optimization-analytics">my master thesis: 'Web Performance Optimization: Analytics'</a>. Those who are interested, feel free to <a href="wimleers.com/contact">contact me</a>! And thanks again for this tremendous step forward, IE team! 🙂 Ok, so apparently this blog doesn't work very well. No instructions on commenting imply that simple HTML is allowed most of the time. But not here. Here's my comment again: Excellent work! And great to see Internet Explorer take the lead in a specific area instead of lagging behind! 🙂 This will result in more accurate Episodes [1] measurements and also more *extensive* my master thesis, which is titled "Web Performance Optimization: Analytics" [2]. Those who are interested, feel free to contact me [3]! And thanks again for this tremendous step forward, IE team! 🙂 [1] stevesouders.com/episodes [2] wimleers.com/…/master-thesis-proposal-web-performance-optimization-analytics [3] In IE9 will it remove flash support? And what about VP8 codec? Is IE 9 having a homepage protection or will it alerts on the default homepage change, by different programs/viruses/worms??? One important thing is that the toolbars are creating huge problems for the browser and to the system. There should be security system in installing the toolbars. The security may be like the driver signing and security certificates. Please the remove the setting to "remembering the username and passwords on forms". This setting is harmful to common user. Remembering form data may be useful but it is not safe to remember the password. OK, thanks for the new development. Hoping better security and a speedy browser (IE9). bcdalai @bcdalai: No, IE9 will not remove support for browser add-ons like Flash. IE9 will not ship with a VP8/WebM codec but if one is installed the VIDEO tag can use it. If your computer is compromised by a "virus/worm" then having homepage protection won't help you (if you're running malicious code on your computer, it's not your computer anymore). Non-virus programs which violate your preferences by changing your homepage will typically be blocked by Windows Defender and/or IE's "Bad add-on" blocker. Any user who wants to disable saving of passwords can easily do so using the appropriate checkbox; administrators can do so using Group Policy. For most users, the convenience outweighs the risk. EricLaw[MSFT] I was wondering if you guys will link to a VP8/WebM codec once you guys show off IE9 beta. The VP8 codec is terribly inefficient and is not a standard. Please support the WMV-HD/VC-1 standard codec which is at least as efficient and has the best decoding footprint so that it can be easily played on mobile devices. Also I request you support the WMA-Pro 10.x audio codec as it is an highly efficient codec. Supporting Microsofts own codecs would respect your customers that invested in your technologie. VP8 as released by Google requires 50% more data for the same quality video compared to h.264 main profile and the codec perfoemcnace is even slower. That mean the VP8 is a terrible waste of bandwith and storage. Microsoft should not support putting some inferior and non standardized codec over it's own formats. hAl, as much sense as your post may make, Microsoft has explained what they're going to do in the codec space (h264, WebM only if installed), and they're not going to change that plan now. They're only "supporting WebM if installed" in the hope that somebody (aka Google) would be stupid enough to ship that codec and subsequently get sued for billions. @Not-A-Democracy That still leaves a big question why Microsoft is not supporting the formats tehy devloped and that they are using in a lot of their existing software and for which a lot of their customers would like support in the browser as well a lot more than they would some fairly inferior non standardized codec like VP8. @hAl Well, since Windows has built-in codecs for those formats, IE9 will be able to play them…or am I wrong ? Please post a memory consumption graph for each of the page events in your test. Browsers memory consumption affects performance from URL request to viewing the page especially when you have multiple tabs open. @Aethec De IE team has not indicated that would be the case. @hAl: the IE team has been touting "Same Markup" left and right (which, for them, includes code in general: markup, script…), interoperability and so on, and you're proposing that they support codecs that other browsers or OSes won't be able to support? Awesome idea! To get very bad press, that is. Something IE can't afford anymore. @Stifu Many companies already publish their video in WMV/VC-1 (an official standard) and would like to continue doing so. They might use them for internal use or for target groups that have no problem with WMV video. HTML 5 test (300 Full Test): Chrome 6.0.447.0 -> 219 / 300 (+ 10 bonus points) Chrome 5.0.375.86.Final -> 197 / 300 (+ 7 bonus points) Safari 5.0 -> 165 / 300 Opera 10.60 -> 159 / 300 (+ 7 bonus points) Firefox 3.6.6 -> 139 / 300 (+ 4 bonus points) IE 9 P.3 -> 84 / 300 (+ 1 bonus points) IE 8.0 -> 37 / 300 @Ali That was already discussed before. The "HTML5 Test" is not testing any kind of standard compliance. (e.g. WebGL is not a standard, but included in the test…) @Aethec: To be fair, WebGL is under the heading "Related Specifications". @Wurst Several W3C specifications are related to HTML5 and state so in the introduction of the W3C specifications but WebGL is not one of them Please, Form validator:…/common-input-element-attributes.html Input element type:…/the-input-element.html Section elements:…/semantics.html Geolocation: dev.w3.org/…/spec-source.html Web SQL Database:…/webdatabase Geolocation API is only really usefull for mobile browsers on devices with gps capabilities is it not? A mobile browser which IE9 is not planned to be. But if Windows phone in the future gets based on an IE9 version than geolocation API might be usefull. Geolocation is also potentially useful on netbooks/laptops, and GPS capability is only needed if you need a very accurate position. A lot of the potential uses for geolocation work fine with the less accurate location worked out by services like Google Location Service.
https://blogs.msdn.microsoft.com/ie/2010/06/28/measuring-web-page-performance/
CC-MAIN-2017-09
refinedweb
2,944
54.73
Going SOA with Symfony2: A year and a half down the road This Case Study is a guest post written by Alessandro Nadalin, VP Technology at Namshi. Want your company featured on the official Symfony blog? Send a proposal or case study to [email protected] When I first started working on Symfony2 to renew parts of our architecture at Namshi, I was genuinely excited because I was sure that Symfony was the best choice for our business. As time went by, I felt pretty confident about the choice, but I would like to give an honest and clear overview of which elements worked and which ones didn't, so that others can benefit from what we all learned from our experience. Before we began First, let me introduce our architecture, or, at least, how it looks nowadays: at Namshi, we run a fashion e-commerce portal that is growing rapidly in the Middle East (7 countries, 2 languages). In order to achieve desired growth, we tackled complexity by relying on microservices in a Service-Oriented Architecture. We also diversified the development platforms, as our frontends are either "native" (mobile apps) or written in JavaScript, whether on NodeJS (desktop website) or on the client-side with AngularJS (mobile website). As you might have already guessed, we use Symfony2 to develop the backend APIs used by those frontends. In this article, we'll focus solely on the backend part of the application. To FOSRest or not to FOSRest? If you are building APIs, you must use FOSRestBundle, right? Not so fast! I'm not saying this isn't a good piece of software, but in highly customized, long-term projects you might want to look into something simpler, with less configuration and with your own constraints and domain rules. We do use FOSRestBundle but have been slowly migrating away from it for all the new services that don't require too much abstraction: we determined that a simpler solution (i.e. JMS serializer + JsonResponse) is probably all we need. When supporting additional formats, you might argue that using FOSRestBundle can save you a lot of work. That's why I think it´s important to evaluate your concrete needs and then opt for using it or not. In our case, we've seen that a simple method in the controllers was all we required: class ApiController { public function createApiResponse($data, $whatever, ...) { return new JsonResponse($this->getSerializer()->serialize($data, 'json'), ...); } } Again, I think FOSRest is a very nice piece of software. However, I would like to highlight the fact that you might be able to avoid additional complexity or abstraction if you don't need all the features. Authentication In order to authenticate API requests we decided to go for something that Google was promoting in some of its SDKs, Json Web Tokens. We ended up writing a small library for using JWTs in PHP and, guess what, someone wrote a bundle for this. We're actually quite happy with the simplicity of JWTs so far and, compared with other more complex solutions, this simplicity has worked pretty well. The idea behind JWS (Json Web Signatures, which are the signed version of JWTs) is very simple, as the client first logs in with credentials, then you issue a standard, signed JWT that contains client-related information and then the client sends that token for each API request. Another important thing to note, all our APIs run on HTTPS and I would definitely recommend moving in that direction. With a faster and faster web, and things like SPDY and LTE connections, the perceived overhead is very small. Multiple bundles or multiple apps? Another thing that we discussed to great extent was whether to develop N Symfony apps or simply keep all our different APIs in isolated bundles, i.e. in one app. We started with the latter since it was the fastest way to get stuff in production, but are currently moving towards splitting all of the services into their own apps. This strategy avoids getting trapped in dependency conflicts (one bundle needs version X of dependency Y that isn't supported in another bundle, for whatever reason, etc.) to keep the development process of these components separate. This means that we can dedicate a small team of developers to work on one API without depending on any other API. In addition, the team can achieve fast, lean deployments without the need to deploy the whole API infrastructure at once. Lastly, this approach also helps in case we want to rewrite one of our services with another platform (NodeJS, for example). Of course, these are problems that you start facing once you scale the team and scope of the software, so I would still recommend to start with multiple bundles and then simply split them in N apps only when necessary. We also have some code / bundles that are common to basically every API and store it in separate repositories that will be included through Composer. What about performance? To be honest, nothing very specific here: we serve most of our content through Redis and have Varnish on top of Nginx, so that our API can relax once in a while. Although we didn't attain crazy performance throughput, we are thrilled to see our APIs taking around 75ms, which is decent enough to not worry about performances for a while and focus on other aspects of the architecture. Unit testing gotcha Truth: we've been very remiss on this one. We´ve added functional tests without focusing too much on unit test; a trend that we've started to change recently. In any case, there are a couple things I would like to mention: - Instead of using PHPUnit, which is fully integrated out-of-the-box with Symfony, we decided to go for PHPSpec because we feel it's a more modern solution for unit tests and to let the software design emerge. - Travis-CI is almost a no brainer: we've been using it for months now and are very happy not having to manage our own Jenkins instances to trigger tests every time someone pushes to GitHub. CORS & friends For those interested in knowing how we solved CORS issues, we started with the NelmioCorsBundle but, since we needed to support older versions of IE anyway and solutions like xDomain aren't as straightforward as you might think, we decided to implement an API proxy so that we would avoid cross-origin requests altogether. Instead of requesting api.example.com/users, the frontend at example.com will hit example.com/api/users and a rule on the webserver will send that request to the API on the api. subdomain. Versioning In an effort to break as little as possible, we embraced versioning and implemented it through the webserver and Symfony itself. The approach we took is actually quite simple. We let clients hit our APIs through URLs like api.example.com/checkout/v3/.... The trick being that the nginx server takes the first two segments of the URL and sets two HTTP headers accordingly: Api-Service: checkout Api-Version: 3 Then, we have a routing listener that boots controllers accordingly to the version: it checks if a controller is available under the \Namshi\CheckoutBundle\Controller\V3 namespace. If not, it fallbacks until it reaches version zero ( \Namshi\CheckoutBundle\Controller) or throws a 404 error. On top of this, before sending the response back to the client, we have response transformers taking the stage: we look at the API version that was requested, find the transformers that match that version and apply them to the response. The transformer is a simple POPO (Plain Old PHP Object) that accepts a Response and applies transformations when necessary. For example, we use a transformer to camelCase values in the API responses, to add some caching rules or to trim content that we don't need on specific versions. Here´s how transformers look: class CamelCaseTransformer implements ApiResponseTransformer { protected $inflector; public function __construct(SomeInflector $inflector) { $this->inflector = $inflector; } public function transform(Response $response) { $content = $this->inflector->camelize($response->getContent()); $response->setContent($content); } } All in all The Tech team at Namshi is far from being perfect and I truly believe there's still much to do and many improvements to make. Still, some very simple choices, like the ones we described, helped us get ahead of many of our competitors due to the flexibility that comes from reducing the complexity of our Symfony-powered APIs. We are very happy to be using Symfony2 for our APIs and are certain that, if we had to start again from scratch, we wouldn't go for anything else offered by the PHP ecosystem. Please send us your feedback about the decisions we made, because we truly believe we can and should learn as much as possible from the smart brains in the Symfony community. Last, but not least, in the process of writing our SOA we had the chance to develop some open source components (both in JavaScript and PHP) that are available on GitHub: feel free to drop by and help us make them even more awesome! As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities. Going SOA with Symfony2: A year and a half down the road symfony.com/index.php/blog/going-soa-with-symfony2-a-year-and-a-half-down-the-roadTweet this __CERTIFICATION_MESSAGE__ Become a certified developer! Exams are online and available in all countries.Register Now We use JWT as well for our APIs thanks to the LexikJWTAuthenticationBundle and its dependencies (yours among them) and we are very happy with it, it's a really simple authentication system to implement. And it was a perfect fit with the NelmioCorsBundle as our APIs are only used by a mobile app or from other server-side apps (no legacy browsers to take into account then). There's two things I would say about bundles vs micro services. First I think user applications don't need to use bundles in symfony at all because... well, there's no real reason to use it, it makes your code coupled to symfony, it adds two unneeded directories in hierarchy (vendor and bundle names), there's some other reasons which I'll not remember right now. And what about micro services - it's a very good way to distribute programmers work, to write decoupled code and it's basically isolation of components which usually good for testing and simplicity. But there's two problems you should always keep your eye on: complexity of dependencies between services - the more you divide everything the more complex it becomes for developers to grasp the architecture because everything is divided into small pieces and lies in different places, and the second thing is latencies between services that can add up and make your response time worse, they will often have a nature of sequential requests which you cannot "speedup" by asynchronicity. To ensure that comments stay relevant, they are closed for old posts. Lukas Kahwe Smith said on Dec 16, 2014 at 11:09 #1
https://symfony.com/index.php/blog/going-soa-with-symfony2-a-year-and-a-half-down-the-road
CC-MAIN-2021-49
refinedweb
1,868
56.29
There is no class or function called vil3d_property. More... Go to the source code of this file. There is no class or function called vil3d_property. The image class vil3d_image_resource has the method : bool get_property(char const *label, void *property_value = 0) const; which allow format extensions to be added without cluttering the interface to vil_image_resource. The idea is that properties can be identified by a "label" labels is a namespace in the general sense of the word. We only have one namespace, so try not to clutter it. All property labels described in this file should begin with "vil3d_property_" and that chunk of the namespace is reserved. An example float vs[3]; vcl_cout << "Volume of image is "; if (image.get_property(vil3d_property_voxel_size, &voxel_size)) vcl_cout << vs[0]*vs[1]*vs[2]*im.ni()*im.nj()*im.nk() << vcl_endl; else vcl_cout << "unknown\n"; Definition in file vil3d 50 of file vil3d_property.h. Original image origin in pixels. Measured from vil3d origin in standard direction. Type is float[3]. Definition at line 69 of file vil3d 57 of file vil3d_property.h. voxel size in metres. Type is float[3]. If this property exists you may get and set the values through the size_i(), and set_pixel_size() members of vil3d_image_resource. Definition at line 64 of file vil3d_property.h.
http://public.kitware.com/vxl/doc/release/contrib/mul/vil3d/html/vil3d__property_8h.html
crawl-003
refinedweb
211
60.72
Yes I know to use srand() But does anyone have anything more random? Thnx in advance Yes I know to use srand() But does anyone have anything more random? Thnx in advance Thanks. I don't have I compiler on this computer so I can't try it out. Would this work: That should give an integer between 1 and 100, right?That should give an integer between 1 and 100, right?Code: #include<iostream.h> #include<stdlib.h> #include<time.h> int main() { srand(time(NULL)); cout<<"A random number: "<<(int)((double)rand()/((double)RAND_MAX+1)*100)<<endl; cin.get(); return 0; } I tried it, it's giving me 79 every time. 80 Now, so it's not random, it's 100% based on the time in which it's seeded. I'll check in a minute to see what's wrong. Thanks. I would do it myself, but as I said before I don't have a compiler on this comp and I can't download one This is working for me.. Although i'm sure you don't want the windows header in there... I can't figure out what's wrong with the regular time() implementation.Although i'm sure you don't want the windows header in there... I can't figure out what's wrong with the regular time() implementation.Code: #include <iostream.h> #include <stdlib.h> #include <time.h> #include <windows.h> int main(int argc, char* argv[]) { srand(GetTickCount()); cout<<"A random number: " << rand() / (RAND_MAX / 100 + 1) << endl; cin.get(); return 0; } I would prefer not to have the windows header in my program. I'm trying to make this thing non platform specific. Anybody write their own random function? I dont know what the problem with your system is but the ocde you posted works just fine on VC60. maybe you had the srand(time(NULL)) in the loop so you kept re-seeding rand with the same value; make sure you only seed once Yes, that would be a problem if you seeded everytime you were going to use rand();
http://cboard.cprogramming.com/cplusplus-programming/25065-rand-printable-thread.html
CC-MAIN-2016-07
refinedweb
350
76.22
0 replies on 1 page. As Anil Hemrajani noted, Rails configuration files are actually ruby files. They even end with a .rb extension. So they can include any code you need to handle dynamic configuration. That's pretty cool. Ruby is nice because (as Anil also noted) the same language can be used either for a serious OO application or for a simple script. That makes one language to learn, with many possible applications. But that dual-use capability is rapidly becoming the only reason left for preferring Ruby over Scala. There was the ability to create DSLs, but Scala seems to be all over that one with functional composition. And the real killer app was Rails, but the Scala's Lift framework looks like serious competition on that front. (See the resources.) That leaves my favorite build language, Rake. And the ability to write simple scripts. And of course, there is the small matter of dynamic typing. But do I really need that, if the language is as flexible as Scala? The award for Loudest Applause at a non-keynote session goes to Todd Fast, from Sun. His talk centered on the long tail of user-constructed applications. But that summary doesn't do justice to the masterful way he deconstructed the space. The main points were: Platforms like FaceBook, MySpace, Ning, and Meebo provide high levels of abstraction in their application models, making it easy for non-programmers to do stuff. OpenSocial provides a common API people can use to write such applications Social networking applications grow virally. Your friends use it. They tell their friends... An application can take off very fast--to the tune of 250 thousand users a day. And they can drop off just as rapidly, as people turn their attention to other things. So maybe "disposable apps" are the wave of the future (eventually). 20% of earth's population is on the web today. Approximately a seventh of them are doing social networking. So the potential is huge. Clay Shirke identified the Cognitive surplus that will likely produce the long tail apps. That surplus is pretty huge, when you consider that approximately 100 million hours of human thought went in Wikipedia, but 200 billion hours are spent watching TV every year--that's the equivalent of 2,000 wikipedia projects per year. Given a proliferation of higher-level application models that anyone can use, there is the potential for explosive growth in the application domain. Another really good session was given by Dean Allemang, author of Semantic Web for the Working Ontologist. (See Resources.) It was the best explanation I've seen yet of RDF and its potential applications. The key points: RDF is basically subject/predicate/object -- like a basic sentence, where the predicate is the verb that links the subject and the object. In the semantic web, the subjects are URIs. In effect, each triplet identifies a cell in a gigantic table. The cells are joined by subject-URIs to create "rows". (They could conceivably be jointed by joined by predicates to create "columns", as well.) OWL equivalences can be used to map locally-desirable nomenclature into a common ontology. (The Dublin Core is a standard ontology that was created to catalog library contents. One of the 15 standard items it defines is "creator". The namespace is "dc", so "dc:creator" specifies that entry in their ontology. Using OWL equivalences it becomes possible to map book:author and play:playwright to dc:creator--so the common meaning is identified while separate terminology is maintained. That's a really big point. As Allemang pointed out, the idea is not to somehow get everyone to agree on one big giant vocabulary. (Good luck.) Instead, The idea is be able to identify the vocabulary someone is using, map terms that mean the same thing and distinguish terms that mean something different. Namespaces do the distinguishing, and equivalences allow for mapping. Once the mappings are defined, it becomes possible to do searches and interesting mashups--all of which help to enable "long tail" applications. The award for Best Service goes to the entire staff of the Moscone Convention Center, who were unfailingly as helpful as they could possibly be. The award for Best Swag goes to Oracle, who gave out tickets to see IronMan. (A fact I discovered only just too late!) They even included coupons for drinks and snacks. The award for Coldest Venue for a rock concert goes to Yerba Buena Gardens, where SmashMouth gave a show for a freezing conference crowd. (There should have been more dancing, so we could stay warm!) The award for Best New Technology may just have to go to Scala. Although it's not exactly new, it certainly provides the majority of features that are near and dear to a Rubyist's heart. Then there is its static typing, which does eliminate a whole class of runtime errors, while also making it easier to write a refactoring IDE. And mostly, I get the idea that things just seem to work. I'll have to join the Scala list to confirm that one. (You can get an amazing sense of things by lurking for a week or so.) If it's as solid as it appears to be, and Lift is as cool as it looks, it just may take home the award. Well, that's all for this year. See you again in 2009!
http://www.artima.com/forums/flat.jsp?forum=106&thread=230383
CC-MAIN-2015-22
refinedweb
907
65.83
table of contents NAME¶ lockf - apply, test or remove a POSIX lock on an open file SYNOPSIS¶ #include <unistd.h> int lockf(int fd, int cmd, off_t len); lockf(): || /* Glibc since 2.19: */ _DEFAULT_SOURCE || /* Glibc versions <= 2.19: */ _BSD_SOURCE || _SVID_SOURCE DESCRIPTION¶¶ On success, zero is returned. On error, -1 is returned, and errno is set appropriately. ERRORS¶ -. ATTRIBUTES¶ For an explanation of the terms used in this section, see attributes(7). CONFORMING TO¶ POSIX.1-2001, POSIX.1-2008, SVr4. SEE ALSO¶ locks.txt and mandatory-locking.txt in the Linux kernel source directory Documentation/filesystems (on older kernels, these files are directly under the Documentation directory, and mandatory-locking.txt is called mandatory.txt) COLOPHON¶ This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manpages.debian.org/bullseye/manpages-dev/lockf.3.en.html
CC-MAIN-2022-27
refinedweb
150
53.47
To find unique words in a string use Map utility of java because of its property that it does not contain duplicate keys.In order to find unique words first get all words in array so that compare each word,for this split string on the basis of space/s.If other characters such as comma(,) or fullstop (.) are present then using required regex first replace these characters from the string. Insert each word of string as key of Map and provide initial value corresponding to each key as 'is unique' if this word does not inserted in map before.Now when a word repeats during insertion as key in Map delete its entry from map.Continue this for each word untill all words of string get check for insertion. import java.util.LinkedHashMap; import java.util.Map; public class Tester { public static void main(String[] args) { String str = "Guitar is instrument and Piano is instrument"; String[] strArray = str.split("\\s+"); Map<String, String> hMap = new LinkedHashMap<String, String>(); for(int i = 0; i < strArray.length ; i++ ) { if(!hMap.containsKey(strArray[i])) { hMap.put(strArray[i],"Unique"); } } System.out.println(hMap); } } {Guitar=Unique, is=Unique, instrument=Unique, and=Unique, Piano=Unique}
https://www.tutorialspoint.com/java-program-to-print-all-unique-words-of-a-string
CC-MAIN-2021-43
refinedweb
201
65.73
CV_CREATE(3L) CV_CREATE(3L) NAME cv_create, cv_destroy, cv_wait, cv_notify, cv_broadcast, cv_send, cv_enumerate, cv_waiters, SAMECV - manage LWP condition variables SYNOPSIS #include <<lwp/lwp.h>> cv_t cv_create(cv, mid) cv_t *cv; mon_t mid; int cv_destroy(cv) cv_t cv; int cv_wait(cv) cv_t cv; int cv_notify(cv) cv_t cv; int cv_send(cv, tid) cv_t cv; lwp_t tid int cv_broadcast(cv) cv_t cv; int cv_enumerate(vec, maxsize) cv_t vec[]; /* will contain list of all conditions */ int maxsize; /* maximum size of vec */ int cv_waiters(cv, vec, maxsize) cv_t cv; /* condition variable being interrogated */ thread_t vec[]; /* which threads are blocked on cv */ int maxsize; /* maximum size of vec */ SAMECV(c1, c2) DESCRIPTION Condition variables are useful for synchronization within monitors. By waiting on a condition variable, the currently-held monitor (a condi- tion variable must always be used within a monitor) is released atomi- cally and the invoking thread is suspended. When monitors are nested, monitor locks other than the current one are retained by the thread. At some later point, a different thread may awaken the waiting thread by issuing a notification on the condition variable. When the notifi- cation occurs, the waiting thread will queue to reacquire the monitor it gave up. It is possible to have different condition variables oper- ating within the same monitor to allow selectivity in waking up threads. cv_create() creates a new condition variable (returned in cv) which is bound to the monitor specified by mid. It is illegal to access (using cv_wait(), cv_notify(), cv_send() or cv_broadcast()) a condition vari- able from a monitor other than the one it is bound to. cv_destroy() removes a condition variable. cv_wait() blocks the current thread and releases the monitor lock asso- ciated with the condition (which must also be the monitor lock most recently acquired by the thread). Other monitor locks held by the thread are not affected. The blocked thread is enqueued by its sched- uling priority on the condition. cv_notify() awakens at most one thread blocked on the condition vari- able and causes the awakened thread to queue for access to the monitor released at the time it waited on the condition. It can be dangerous to use cv_notify() if there is a possibility that the thread being awakened is one of several threads that are waiting on a condition variable and the awakened thread may not be the one intended. In this case, use of cv_broadcast() is recommended. cv_broadcast() is the same as cv_notify() except that all threads blocked on the condition variable are awakened. cv_notify() and cv_broadcast() do nothing if no thread is waiting on the condition. For both cv_notify() and cv_broadcast(), the currently held monitor must agree with the one bound to the condition by cv_create(). cv_send() is like cv_notify() except that the particular thread tid is awakened. If this thread is not currently blocked on the condition, cv_send() reports an error. cv_enumerate() lists the ID of all of the condition variables. The value returned is the total number of condition variables. The vector supplied is filled in with the ID's of condition variables. cv_wait- ers() lists the ID's of the threads blocked on the condition variable cv and returns the number of threads blocked on cv. For both cv_enu- merate() and cv_waiters(), maxsize is used to avoid exceeding the capacity of the list vec. If the number of entries to be filled is greater than maxsize, only maxsize entries are filled in vec. It is legal in both of these primitives to specify a maxsize of 0. SAMECV is a convenient predicate used to compare two condition vari- ables for equality. RETURN VALUES cv_create(), cv_destroy(), cv_send(), cv_wait(), cv_notify() and cv_broadcast() return: 0 on success. -1 on failure and set errno to indicate the error. cv_enumerate() returns the total number of condition variables. cv_waiters() returns the number of threads blocked on a condition vari- able. ERRORS cv_destroy() will fail if one or more of the following is true: LE_INUSE Attempt to destroy condition variable being waited on by a thread. LE_NONEXIST Attempt to destroy non-existent condition variable. cv_wait() will fail if one or more of the following is true: LE_NONEXIST Attempt to wait on non-existent condition variable. LE_NOTOWNED Attempt to wait on a condition without possessing the correct monitor lock. cv_notify() will fail if one or more of the following is true: LE_NONEXIST Attempt to notify non-existent condition variable. LE_NOTOWNED Attempt to notify condition variable without pos- sessing the correct monitor. cv_send() will fail if one or more of the following is true: LE_NONEXIST Attempt to awaken non-existent condition variable. LE_NOTOWNED Attempt to awaken condition variable without pos- sessing the correct monitor lock. LE_NOWAIT The specified thread is not currently blocked on the condition. cv_broadcast() will fail if one or more of the following is true: LE_NONEXIST Attempt to broadcast non-existent condition vari- able. LE_NOTOWNED Attempt to broadcast condition without possessing the correct monitor lock. SEE ALSO mon_create(3L) 21 January 1990 CV_CREATE(3L)
http://modman.unixdev.net/?sektion=3&page=cv_destroy&manpath=SunOS-4.1.3
CC-MAIN-2017-17
refinedweb
824
53.41
Module: Essential Tools Module Group: Generic Does not inherit #include <rw/gvector.h> declare(RWGVector,val) implement(RWGVector,val) RWGVector(val) a; // A Vector of val's. Class RWGVector(val) represents a group of ordered elements, accessible by an index. Duplicates are allowed. This class is implemented as an array. Objects of type RWGVector(val) are declared with macros defined in the standard C++ header file <generic.h>. NOTE -- RWGVector is deprecated. Please use RWTValVector or RWTPtrVector. Note that it is a value-based collection: items are copied in and out of the collection. The class val must have: a default constructor; well-defined copy semantics (val::val(const val&) or equivalent); well-defined assignment semantics (val::operator=(const val&) or equivalent). For each type of RWGVector, you must include one (and only one) call to the macro implement, somewhere in your code. None #include <rw/gvector.h> #include <rw/rwdate.h> #include <rw/rstream.h> declare(RWGVector, RWDate) /* Declare a vector of dates */ implement(RWGVector, RWDate) /* Implement a vector of dates */ int main() { RWGVector(RWDate) oneWeek(7); for (int i=1; i<7; i++) oneWeek(i) = oneWeek(0) + i; for (i=0; i<7; i++) std::cout << oneWeek(i) << std::endl; return 0; } Program output: 04/12/93 04/13/93 04/14/93 04/15/93 04/16/93 04/17/93 04/18/93 RWGVector(val)(); Construct an empty vector. RWGVector(val)(size_t n); Construct a vector with length n. The initial values of the elements can (and probably will) be garbage. RWGVector(val)(size_t n, val v); Construct a vector with length n. Each element is assigned the value v. RWGVector(val)(RWGVector(val)& s); Copy constructor. The entire vector is copied, including all embedded values. RWGVector(val)& operator=(RWGVector(val)& s); Assignment operator. The entire vector is copied. RWGVector(val)& operator=(val v); Sets all elements of self to the value v. val operator()(size_t i) const; val& operator()(size_t i); Return the ith element in the vector. The index i must be between zero and the length of the vector less one. No bounds checking is performed. The second variant can be used as an lvalue. val operator[](size_t i) const; val& operator[](size_t i); Return the ith element in the vector. The index i must be between zero and the length of the vector less one. Bounds checking is performed. const val* data() const; Returns a pointer to the raw data of self. Should be used with care. size_t length() const; Returns the length of the vector. void reshape(size_t n); Resize the vector. If the vector shrinks, it will be truncated. If the vector grows, then the value of the additional elements will be undefined. Rogue Wave and SourcePro are registered trademarks of Quovadx, Inc. in the United States and other countries. All other trademarks are the property of their respective owners. Contact Rogue Wave about documentation or support issues.
http://www.xvt.com/sites/default/files/docs/Pwr%2B%2B_Reference/rw/docs/html/toolsref/rwgvector.html
CC-MAIN-2017-51
refinedweb
488
52.66
A relatively little known fact about the rails routing helpers is that they use the ActiveRecord#to_param method for the id value. This means you can have the to_param method of a user object return the username, and access that resource as /users/georgebushlol. The problem is that you still have controller methods that look like this: def show @user = User.find_by_username(:id) end ...when what you'd really like is this: def show @user = User.find_by_username(:username) end We submitted a patch to Rails that adds the ability to change the name of the :id parameter in the RESTFull routes. It adds a parameter named :key to the options for map.resources, which specifies a name to be used instead of :id in all member urls. If the value doesn’t start with the singular name of the resource (such as :name), then '[resource]_' will be prepended to it when nested (more on that later). Here’s an example: map.resources :clients, :key => :client_name do |client| client.resources :sites, :key => :name do |site| site.resources :articles, :key => :title end end These routes create the following paths: /clients/:client_name /clients/:client_name/sites/:name /clients/:client_name/sites/:site_name/articles/:title Notice that because 'client_name' starts with 'client' (singular version of the controller), the nested path parameter remains 'client_name', and is not automatically set to 'client_client_name' (which would be dumb). The example above shows the full range of the :key option, but common usage would be more in line with this: map.resources :users, :key => :user_id do |user| user.resources :books, :key => :isbn do |book| book.resources :authors end end The path to parameterized path mappings for these routes are: /users/2 => /users/:user_id /users/2/books/0-12-345678-9 => /users/:user_id/books/:isbn /users/2/books/0-12-345678-9/authors/3 => /users/:user_id/books/:book_isbn/authors/:id In addition, we find that our code can be greatly simplified when the keys in the params hash are always referring to the same models. Normally :id can refer to any of your model classes, depending on which controller you’re in. If you specify a :key value of :XXX_id for each resource, however, then you can move a good deal of your code to helper methods which can be used globally: def get_user @user ||= User.find(params[:user_id]) end Consistent use of these helpers really helps the readability of you application. The patch includes pretty good tests, and we’ve been using it for the past few months in three of our production applications. If you’d like to see it in rails 1.3, please head on over and vote for it. UPDATE: Thanks to Jon for pointing out a typo in a code block above.
https://robots.thoughtbot.com/rails-patch-change-the-name-of-the-id-parameter-in
CC-MAIN-2016-18
refinedweb
457
62.27
Asked by: ListView Manipulation Question In my ContentGrid, there is a ListView which lists some items of a category. Then how to do this: by swiping the ListView horizontally and repeatly, the items of other categories will be list on the ListView one (category) by one? Thinking the data model as the following: public class Book { public int ID {get;set;} public string Name {get;set;} public int CategoryID {get;set;} ..... } Thanks Wednesday, January 21, 2015 3:02 AM All replies Hi imnbwd, To make the listview horizontally, you can set orientation of the itempanel like this: <ItemsPanelTemplate x: <ItemsStackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> CarouselPanel class is used to repeat the items but I don't think it works with ListView, I think you may use ObserverableCollection for help range the listview items. --James We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate the survey.Wednesday, January 21, 2015 7:38 AMModerator - Hi, Jamles, Thanks for your answer. While I think that you may misunderstand my mean of "horizontally", it is to describe the direction of the action (swipe or manipulation) on ListView.Wednesday, January 21, 2015 9:57 AM Thanks for your explanation, however I'm still confused about what is your scenario. I may understand you would like to implement something: ListView act as the main index page, by select the category (swipe the item), the detail things will list on the ListView. However I'm not able to know why its other category items will be shown one by one: "the items of other categories will be list on the ListView one (category) by one". Could you explain in more detail so that we can have a better understanding.- 6:32 AMModerator OK, so let us think about Pivot, when we swipe on it, pivot pages will be cyclically changing. Assume each PivotItem represents a category, its name is PivotItem.Header, and all items of this category are list on this PivotItem and as its Content (PivotItem.Content). By swiping, different pivot pages (PivotItem) will show us categories of data cyclically (or what I mean "one by one"), this effect is what I want. Based on the concept of Pivot, here I do not want to use Pivot, but use basic controls and layout like the following: <Grid x: <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <!--"be treated as pivotitem header"--> <TextBlock Text="{Binding CategoryName}" FontSize="28" /> <!-- "be treated as pivotitem content"--> <ListView Grid. </ListView> </Grid> So, this is my question, how can I swipe on this ListView to change the current category(include category name in TextBlock and its items in ListView) to next category? BTW, my difficulties are mainly about the Manipulation property setting for control and how to process the corresponding Manipulation event to achieve this effect. Thanks very much. Thursday, January 22, 2015 9:55 AM
https://social.msdn.microsoft.com/Forums/en-US/77ada452-5aef-4e62-a061-167849219a12/listview-manipulation?forum=winappswithcsharp
CC-MAIN-2020-40
refinedweb
505
51.89
You can subscribe to this list here. Showing 4 results of 4 In the current release I have added a somewhat experimental "strict java" mode. When activated with: setStrictJava(true) BeanShell will: 1) Require typed variable declarations, method arguments and return types (no loose types allowed) 2) Modify the scoping of variables to be consistent with the above - to look for the variable declaration first in the parent namespace, as would a java method inside a java class. (As opposed to assuming local scope and auto-allocation as in normal bsh.) e.g. you can write a method called incrementFoo() that will do the correct thing without referring to super.foo. Getting this to work required only tiny changes to the namespace class, etc. so I thought it might be useful to make it available. I anticipate that it might be useful for people teaching Java, who don't want to deal with explanations of differences in behavior between Java and BeanShell. Note that there are some limitations - the GUI desktop environment is not written to conform to "strict Java", so it probably won't run with that mode turned on... So for now you'll be stuck with running scripts from the command line. Pat With the 1.2b1 release I have added a new dynamically loadable extension - the ReflectManager. This allows us to add new reflection capabilities supported by later versions of Java without breaking backwards compatability. The current use for this is to allow use of the java.lang.reflect accessibility API to grant BeanShell access to private/protected fields, methods, and non-public classes. Since this is still somewhat experimental (and changes certain behavior in field and method lookup when activated), it is turned off by default. To activate accessibility do this: setAccessibility( true ); I'd appreciate feedback on this new feature... Thanks, Pat For those of you interested in using BeanShell as the scripting language for an application that supports IBM's Bean Scripting Framework - The necessary adapter is now included in the BeanShell 1.2b1 release. (You can also grab it separately if you want). Unfortunately we will have to wait for the BSF group to add us to the list of "known" scripting languages in order to be automatically detected. So in the mean time if you are writing an application that must be aware of BeanShell you must do something like: // register beanshell with the BSF framework BSFManager mgr = new BSFManager(); String [] extensions = { "bsh" }; mgr.registerScriptingEngine( "beanshell", "bsh.util.BeanShellBSFEngine", extensions ); Please let me know if you have any feedback on the adapter's behavior. It was pretty straightforward. We are even supporting some of the more interesting capabilities such as anonymous method invocation. Pat I've posted a 1.2 beta release... But I'd like to hold off making a big announcement until we get some feedback and make this a final version. This had a few bug fixes over the last release and some new features included (and available separately as optional packages for those who don't want them): - IBM Bean Scripting Framework (BSF) adapter. - Reflective accessibility control. i.e. the ability to access private methods, fields, and non-public classes (still alpha testing this). - An experimental "strict Java" mode that alters the way bsh behaves slightly to be more useful for those who are teaching Java. I'll follow up in separate email about the new features individually and, as always, I'm trying to make time to update the docs... Pat
http://sourceforge.net/p/beanshell/mailman/beanshell-developers/?viewmonth=200107&viewday=27
CC-MAIN-2015-32
refinedweb
585
54.32
On Tue, 16 Jul 2002, Peter Donald wrote: >. You're right. That means we can use SAX2 ( and even replace the SAX1 ProjectHelper ), but the problem remain on choosing the default for namespace support - which must be disabled if we want to support the 'not recomended' XML format, or can be enabled by default if we don't. Note that test:task is likely to fail in other tools - like IDEs, etc where a SAX2 parser is used. Most of the times the namespace processing is enabled in tools ( it is by default anyway ). Costin -- To unsubscribe, e-mail: <mailto:ant-dev-unsubscribe@jakarta.apache.org> For additional commands, e-mail: <mailto:ant-dev-help@jakarta.apache.org>
http://mail-archives.eu.apache.org/mod_mbox/ant-dev/200207.mbox/%3CPine.LNX.4.44.0207151617230.12657-100000@costinm.sfo.covalent.net%3E
CC-MAIN-2020-10
refinedweb
118
62.88
Part. Another part of the learning curve comes from the math you’ll need to deal with DirectX. I am going to point out some resources along the way that will help you brush up on, or learn, the math skills you’ll need to keep going in DirectX. In this series, we are going to build a simple game to illustrate the various components of a commercial game. We will cover how to create great looking graphics in 3D, how to handle user input, how to add sound to a game, how to create computer opponents using Artificial Intelligence, and how to model real-world physics. In addition we are going to cover how to make your game playable over the network and how to optimize your game for performance. Along the way, I will show you how to apply principles of object-oriented development and, as well, I will share some of my experience in creating well-organized and elegant code. Before we start writing our first game we need to talk about the tools we will use. The most important tool for any developer is the Integrated Development Environment (IDE). This is where you are going to spend the majority of your time writing and debugging code, so it needs be powerful and fast. Visual Studio 2005 (also known by the codename “Whidbey") is the third version of the standard Microsoft IDE for .NET Framework-based applications. Visual Studio 2005 introduces a number of Express versions that provide most of the functionality of their more advanced counterparts but are simplified for the novice, hobbyist, and student developer and cost much less (There are express versions available for VB, C#, C++, J# and for Web Developers using ASP.NET). For this series, I am going to use both Visual C# Express and Visual Basic Express. If you have not already done so, download the C# or Visual Basic Visual Studio Express IDE at:. The second important tool we need to create a great looking game is a graphics Application Programming Interface (API). Without such an API it would be extremely difficult to access the graphics capabilities of your PC. The API we are going use is the DirectX API. This API allows us to create powerful multimedia applications on the Windows platform. To work on the game, you will need to download the latest DirectX SDK at:. Make sure that you download the SDK and not just the runtime. The SDK includes samples and other utilities that are extremely useful when developing using DirectX. At some point in your game development experience you are going to have to create or modify graphics. Every copy of Microsoft Windows comes with Microsoft Paint, and while it is not the most powerful program, you already own it and it is good enough for most of our needs. As we dive deeper into DirectX and cover 3D models and sounds, you might find the need to use other programs to manipulate the image or sound files. As we cover these topics I will point you towards free or inexpensive programs and resources on the Web. Finally, you need to know where to go to get help. One of the best places is the public newsgroups. Here, you can ask questions and get answers from people with the same interests as you. Microsoft MVPs and employees also monitor these newsgroups and provide help for you along the way. The newsgroups that are going to be of most interest for game programming are: Other places to go for inspiration and help for gaming are: My first experience using a computer was in 1981. They rival large commercial enterprise application in their complexity and cost many millions of dollars to develop and market. The payback, however, can be enormous and rival Hollywood blockbuster movies in sales – Halo 2 grossed $100M in its first day of availability. All successful games have a couple of features in common that made them stand out. If you apply your design efforts in this order you, too, can create a great game. It may not be a refined first person shooter like Battlefield 1942, but Tetris is arguably one of the most popular games and has neither fancy 3D graphics nor Dolby digital sound. Even today, games like Gish () demonstrate what can come from creative independent developers. If you can write enough of a game to show your game idea, then maybe you can interest the large gaming companies in your game. The Independent Games Festival is the “Sundance” of the game community, runs concurrently with the professional Game Developers Conference and, believe me, is among the most closely-watched events at the show. Now that you know what features make a great game, the next step is to lay out the game proposal for our game. Idea: Since coming up with a unique and creative game idea is the core of any game, I am going to cheat and use the game idea from the first 3D game I ever saw: Atari’s Battlezone. (If I had that great idea why would I let of all you know anyway?) Battlezone is a basic first-person shooter game in which you are looking through the viewfinder of a tank into a 3D landscape. The goal is to destroy as many of the opponent’s tanks as possible before getting destroyed yourself. The landscape includes random objects behind which you can hide. The game screen includes a radar to show you the location of your opponents and the current score. Playability: The original game started out fairly slowly but kept adding more opponent tanks and other random enemies. The game also increased the speed and intelligence of the opponents. All of this kept the game challenging but playable. Graphics: The original game used graphics that proved just engaging enough to feel like you were in a 3D world, but because of the hardware available in 1980 (an 8-bit processor running at 1.5 megahertz) it rendered the 3D objects as wire frames. These graphics were advanced when the game first came out, but we are going to improve upon them using the magic of DirectX (and the magic of 25 years of Moore’s Law!). Screenshot of Atari’s Battlezone game – complete with wire frame mountains, tanks, and even a wire frame moon for added realism! Performance: This game pushed the limits of the hardware available at the time. This is evident in the use of the wire frame objects. If the game had been written to fill these objects then it would have been unplayable. With today’s advanced hardware we should not have any performance issues other than those introduced by us writing sloppy code. Now that we have decided on a game, the next step is to write down the goals of your game. This does not need to be anything formal but the simple act of writing things down has the tendency to make ideas clearer. At a minimum you need to determine the object of the game, what the player can and cannot do and how the player interacts with the game. We also should define what the scoring system is going to be like and what are the victory conditions. For our game these are the simple specification I came up with. Now we are ready to do some coding. In general, it is best to write down just the overall idea of the application. Spending a lot of effort upfront designing every little detail is just a waste of time. As we add more functionally to the game we will continuously do small design sessions to formulate our ideas. This iterative approach to developing software is the best way to create good software, and is more fun at the same time. Now we are ready to write some code. The first step is to create a new solution in Visual Studio 2005. Visual Studio now creates a new solution for us called BattleTank2005 that contains a single project with the same name. First, we need to rename the class to something more descriptive. Naming is one of the most efficient methods of keeping code well organized and understandable. Always choose names that clearly describe what the item is doing and avoid meaningless names like Class1 and Form1. Replacing Form1 text with GameEngine. You'll thank yourself later. Another trick to keeping things organized is to ensure that the files in the Solution Explorer are named exactly the same as the classes they contain and to always create a separate file for each distinct element such as each class or enumeration. Now we have a Windows application that we can run, but it doesn’t do anything. The form has no other controls on it such as buttons you can click or textboxes to display any information. In a regular Windows Forms application we would now add such controls to the forms to create our final application, but for our game we are going draw everything using the DirectX API rather than the Windows Forms API. We really only need the Form for its Windows Handle, which is basically its unique name among all the other windows on the screen. We will use this handle to set up our DirectX drawing surface. The other use of the Form is that it contains an event that we are going to use to create our render loop. A game is much different from a regular application, such as Microsoft Word. Word presents a screen to the user that mimics a page in a typewriter and then waits for the user to do something. This something could be pressing the keys on the keyboard or selecting a menu item from the menu with the mouse. While waiting for the user to interact with the application Word does nothing. (Actually I lie: it does do things like run spell checking and auto save in the background but nothing you as the user can see). Generally, programs written using the Windows Forms library generally have the same behavior – they don’t consume CPU time unless the user is doing something (of course, it’s possible to use the Timer control or the capabilities of the System.Threading namespace to do things independent of the user). Games are different. As you know, smooth movement in games requires the screen to be updated many times per second. The “flicker fusion threshold” at which static images begin to fuse is generally taken to be 1/16 of a second, although it actually varies depending on illumination (brighter lights like computer monitors require higher frame rates) and where on the retina the image falls (peripheral vision requires higher rates than foveal vision). Although movies are shown at 24 frames per second (FPS), 30 FPS is often considered the lowest-acceptable rate for video games, and most actiongame players tune their graphics for no less than 60 FPS. Because the render loop is called dozens of times per second and runs nonstop, game programming almost always uses the render loop as the “stopwatch” of the game, calculating everything inside the loop, not just graphics, but physics, AI, checking for user input, and scores. (Again, you could use the Timer class or threads to write a multithreaded game, but doing so would introduce significant complexity without any clear benefits and although multithreading in the .NET Framework’s Common Language Runtime is quite efficient, the slight overhead could knock a couple frames per second off your game.) So how do we get the computer to run this loop? The form we added earlier has an event called the Paint event. The Paint event for a Windows Form object is called whenever the form is redrawn. This normally occurs only when you maximize a form or when a form is covered by another form that is moved. As all Windows Forms programming, even game programming, is event-based, understanding the principles of events and event handlers is critical. Although the event is triggered automatically, we need to create a special method called an event handler to be able to intercept the event and do something in response to it.. Visual C# protected override void OnPaint(PaintEventArgs e){ } Visual Basic Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) End Sub This is our event handler. When is it called? “OnPaint” – when the Paint event occurs. One thing is still missing. Even though Windows and the Windows Forms library automatically raise the event, some actions that we might expect to trigger the Paint event don’t. Minimizing a window, for example, does not trigger the Paint event, since Windows does not see the need to repaint the entire form (Windows is just being efficient since we are actually displaying less when we are shrinking the form). So we cannot rely on these automatically-created events to manage the loop we need for our game. Luckily, we can programmatically trigger the Paint event by calling the Invalidate method of a form. This causes the Paint event to be triggered and Windows to enter back into our OnPaint event handler. Then we execute any code we want to run every frame and start all over again by calling the Invalidate method. You might ask, “Why can’t we just add a while(true) loop directly within OnPaint() and never leave it?” The answer is that even though we’re game programmers, we’re expected to play well with others. Creating a loop within OnPaint() would starve the rest of the programs running on the system. While our game might gain a few frames per second, the rest of the system would become, at best, ugly, and at worst, unstable. So, instead of directly looping, we essentially “ask” to be called again as soon as possible. Visual C# this.Invalidate(); Me.Invalidate() That’s it, we’ve created our render loop. But there is one more problem. It turns out that not all painting is done in the OnPaint method, Windows Forms triggers another event when the background is erased and by default performs some painting (well, erasing) in response. To force our application to truly only paint inside our method handler, we need to add one more line of code to our application. Since we need to ensure that this code is run when the application starts, we place it into the constructor of the form. This means that we are guaranteed that this code is run before we call any methods on that class. this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true); Me.SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.Opaque, True) Setting the ControlStyles to AllPaintingInWmPaint ensures that Windows only uses the OnPaint event handler to redraw the screen. The second parameter simply informs Windows that our window is not going to be transparent. Now we have the basic framework for our game. Everything we are going to create from now on out will be actions that occur inside the render loop. One issue with this type of loop is that fact that the speed in which the computer can accomplish the tasks in the render loop varies from computer to computer. It even varies on the same computer according to how much memory and CPU time is available for the game at any given moment. We need to have some way of accounting for these differences to make sure that we animate consistently. So instead of treating each frame the same, we are going to calculate the time elapsed between frames and apply that value to our calculations. There are a couple of different ways of keeping track of time in Windows: The last timer is kind of tricky to write since it requires calls to a low-level DLL (kernel32 if you need to know) in Windows. Luckily for us the need for a high-resolution timer is universal and a timer class is included with the DirectX SDK. You can find the timer class in the \Samples\Managed\Common directory underneath the install directory of the SDK. The file we are interested in is called dxmutmisc.cs, but we will use most of the other files in that directory as we add more functionality to our own project. Before we add dxmutmisc.cs we are going to create a separate folder. Organizing a solution by folders makes it easy to group related items together and keeps the project more organized. Now we are going to add the existing file to our project. This copies the file to our directory structure. If you want to, you can browse the contents of this file, it contains various other helper classes that save you from writing a lot of code yourself in addition to the FrameworkTimer class Since the timer class is contained in a different namespace we are going to add a using statement so we can use the FrameworkTimer without having to write “Microsoft.Samples.DirectX.UtilityToolkit.FrameworkTimer” every time. using Microsoft.Samples.DirectX.UtilityToolkit; Microsoft.Samples.DirectX.UtilityToolkit Next we need to have a way to store the value of the time elapsed. We are going to store this value in the deltaTime variable. Notice that we are declaring this variable as a double. If you declared it as an integer you would lose all of the resolution provided by our high-powered timer since everything would be rounded to an integer. private double deltaTime; Private deltaTime As Double We want to start the timer at the last possible moment in the render loop so we can get the most accurate time possible. FrameworkTimer.Start(); Microsoft.Samples.DirectX.UtilityToolkit.FrameworkTimer.Start() We need to calculate the elapsed (or delta) time at the start of each loop, because we are going to pass it to most of the subsequent calls we are going to make. deltaTime = FrameworkTimer.GetElapsedTime(); deltaTime = Microsoft.Samples.DirectX.UtilityToolkit.FrameworkTimer.GetElapsedTime(). We have accomplished a lot in this first article. First, we covered the tools needed to created managed DirectX games and then we discussed the features that make a great game. Next, we defined our game idea and created our game project. After that, we created the render loop we are going to use throughout the game, and finally we added a high resolution timer to our project. The next steps all require DirectX, which we will cover in the next article. I hope that this initial article has motivated you to begin that game you always thought about. Game development can be one of the most satisfying experiences in computer programming, and as we progress through this series, I am going to teach you all the fundamentals you need to accomplish that goal. If you would like to receive an email when updates are made to this post, please register here RSS dxmutmisc.cs is a c# file and there isn't a dxmutmisc.vb in C:\Program Files\Microsoft DirectX 9.0 SDK (February 2005)\Samples\Managed\Common. so how are you supposed to make this game in visual basic? hey thanks for this tutorial derek, it is really specific and even thought it gets technical, it is slow enough for me to learn. I can't wait to read the next one. When I tried to start the program after adding the timer, it gave me 133 error messages saying it couldn't find parts of the timer I have searched the internet up and down for starting a game from scratch and finalay I hit gold, This first section has been a huge help, Thx for putting your time into this! Cant wait to start the next section! [dxmutmisc.cs is a c# file and there isn't a dxmutmisc.vb] Because of the CLR with Visual C# and VB in the .NET Framework, (I believe that's what it is.) the C# file will work under the VB Code. I've done it before. Just wondering, does this tutorial still work with C# VBE and XNA in April 2007? I'm not sure if it's due to an IDE update or what, but something basic is breaking in the examples provided. The one I'm having difficulty with right now is using a constructor: one doesn't already exist. Creating one generates an error that there is already a member of that type. The code to be inserted into the constructor doesn't work either. Another issue is "PaintEventArgs" is an undefined type. My guess is that the default state of a WindowsApplication project has changed. Being a newb and all this stuff is completely confounding me. I had some problems with compiling after including the dxmutmisc.cs file. This helps: I am using Visual Basic.net and this is very hard for me to follow because of the references to all of the C# files and code. Also when I add the dxmutmisc.cs file and type in "Microsoft." Intelesense does not give me "Samples" I am using the newest SDK and I am not sure if that matters. This seems to be the only decent VB.net DirectX 9 tutorial so I hope someone knows the fix to this. Quote; "dxmutmisc.cs is a c# file and there isn't a dxmutmisc.vb in C:\Program Files\Microsoft DirectX 9.0 SDK (February 2005)\Samples\Managed\Common. so how are you supposed to make this game in visual basic?" You should still be able to reference the methods of a C# class because of the whole .NET thing. PingBack from The namespace code: protected override void OnPaint(PaintEventArgs e){ } could not be found, how do i fix this? As Joe said, I dont believe this works with vb.net. It may be possible, im no pro, but it doesnt work with the instructions you've given. :) Great guide though! I am new to this program, so I started with the BattleTank tutorial. I have tried to build the BattleTank project using C#, but every time I attempt to build it, it gives me an error reading: The type or namespace name 'device' could not be found (are you missing a using directive or an assembly reference?) Any help would be appreciated. Um... is there a post of what the finished form ought to look like at the end of this lesson? That'd be a fantastic help. thank you for this it has helped me impossible means form me I M Possible. i want to do somthing first nice tutorial i'm using vb.net but i can't do Microsoft.Samples and i did everything you said for VB can anyone help me please. I am using DirextX SDK 10, and When I tried to add the timer, the intelsence isn't giving me Samples as part of the Microsoft namespace. I am using VB. Can you be more detailed in how to get that working? [Selecting Add | New Folder. Name the new folder: DirectXSupport. This is where we are going to add the various support classes as we make use of them throughout this project. ] I got totally lost at this point. Where is the Add option within Visual Basic Express Edition which allows me to add a new folder. I can't find it. Can someone help me follow what he's talking about? Hardly coding for fun. Almost half of the instructions refer solely to C sharp and therefore confuse an intermediate Visual Basic user - towards whom this article is apparently aimed. Either add the VB counterparts to this article, or remove Visual Basic from the software category. if you are a begginer trying to learn, this gets very incoherant past part 1 and if you already know even a moderate amount of game development this is a complete waste of time. perhaps if the author started over from scratch he might get something worthwhile next time. I keep getting an error that the "Sample" name space does not exist in the "Microsoft" name space. Is there an additional reference that must be added or is it just not in the March '07 DirectX SDK? If anyone is having compilation problems, you need to do 2 things to fix them: 1 - Add references to the Microsoft.DirectX and Microsoft.DirectX.Direct3D components. 2 - Add all the files in "C:\Program Files\Microsoft DirectX 9.0 SDK (February 2005)\Samples\Managed\Common" to your project. This is a worthless tutorial for VB programmers. You can NOT compile C# code in a VB project, plain and simple. The CLR and .NET Framework are one thing, but that comes into play AFTER a file has been compiled, and so you cannot compile a .CS file in a VB project. This lack of basic understanding of how .NET works by the author is curious. Why include the VB code at all, knowing it asbolutely will not work? Well, the workaround is to add a C# library project to the solution and then link to that project. However, for a "beginner's" tutorial this seems hardly a good way to go about it. Quite simply, there is no reason why you would need QueryPerformanceCounter for a simple game anyways. Just use a regular 1-millisecond timer and ignore the C# file. For VB, ignore the part about including the dxmutmisc.cs. Get the VB code from chapter IV. That has the timer converted in Vb format, but it is renamed to HiResTimer instead of FrameworkTimer. In VB.NET you need to use Imports to reference another class; it still works, even if it's in C# I am quiet confused , i can't actually find this place , "At the top of the class in the using directives region add the following line of code" And also This place , "At the end of the class above the last two braces add the following line of code." It would be very helpful if you could show me a screenshot of where it is... Thanks Regards, Faizan Thanks for this guide, by the way what do you mean by " using directives region". "At the top of the class in the using directives region add the following line of code: " what do u mean by this i dont know were exactly it is [When I tried to start the program after adding the timer, it gave me 133 error messages saying it couldn't find parts of the timer] Me too, but I think it's because we didn't add the directx library for the linker, or something like this, I guess the next step will cover that. Just an idea could you have some srceen shots and smaple bits of code for a bit more help. PingBack from I believe the latest version of DirectX SDK does not contain dxmutmisc.cs file. Any other suggestions? I dont know where to put the "Microsoft.Samples.DirectX.UtilityToolkit;" thing. I get the error: "A namespace does not directly contain members such as fields or methods" when I put it in GameEngine.cs at the top or under the "using..." part. Hello, It would be awesome if these lessons were in Video because I have a lot of trouble learning reading through all the jargin and not knowing where exactly to place things. Video tutorial are an awesome avenue for me because I retain more stuff in a shorter period of time and it seems more hands on and the learning curve is so much faster. because lets face it theres a lot to learn. I just wish I could find more video tutorials? reading the and sifting through all this stuff its gonna take years. Im sure the other newbs would agree with me "PLEASE MSDN GIVE US MORE VIDEO TUTORAILS" they really help! I had the VB / C# problem discussed here. Solved it by instead of putting cs files in a folder, creating a new c# project, adding cs files, marking the Allow unsafe code property and adding a reference to this project in the Battle Tank project. I tried your tutorial, and I used the fix for 133 errors, but now i have 271 errors. any reason for this? PingBack from I getting the same error as many, have tried lots of what was suggested without any look. Can anyone help (email me at erdye@cebridge.net if you can) Error 1 The type or namespace name 'Samples' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) C:\Documents and Settings\eric\My Documents\Visual Studio 2005\Projects\EuchrePuker\EuchrePuker\GameEngine.cs 8 17 EuchrePuker Wow this is the best guide for noobs like me who dream of becoming a game developer one day.. Thanks alot Derek.. i really appreciete what you have done here :) Im 11 can some one tell me what the constructor I'm using visual c++ express and I can't seem to get the using namespace to work. Am I supposed to #include a file or something? I tried doing this in VB Express 2005, but, when I enter "Microsoft.", on the parameter list, only the things from before I installed the SDK are there. The SDK version is June 2007, and I followed the previous instructions. I'm using SharpDevelop to do this. I state it because i dont know if things works the same in VS. It's that i've found the way to use the .cs file in my solution by adding a new CS project for it that i referenced in the VB project. Of course this wont wont work if you only have VB, it require a full VS install. But it work like a charm in SharpD. See ya. I don't see how this is helping me learn anything. I hit a directX proplem right after adding the folder, and there is not a single explanation on what to do if this happens. Basically if I am copying you, I'm not learning anyway. But I am copying word for word right now, and its still not working right. Not to mention the fact that after the adding of the DirectX folder You become very vague about where the code your talking about even goes! :( This doesn't work for me, it's producing 'The tpe or namespace name DirectX does not exist in the namespace Microsoft. I am glad that you posted this set of tutorials, but this is really frustrating because when I go to compile them, in my I.D.E they don't compile correctly, can you please either update the code or recreate it, because it's not working. so can anyone shed some light on why the I keep getting errors in regards to this command: Microsoft.Samples.DirectX.UtilityToolkit.FrameworkTimer.Start() VB is telling me that it doesn't know what Samples is. I'm using the VB 2008 express, beta edition. -thx question 1. when adding " protected override void OnPaint(PaintEventArgs e){ } " after the constructors, where are the constructors exactly?? Also, Is this after the final brackets (i.e., }) or within "InitializeComponent();" ?? Question 2. Where do I place " this.Invalidate(); " exactly?? I've only had experience with visual basic and it has been a while. I'm viewing the GameEngine.cs (code view) and there is already code present, so the placement of the code is confusing for me. Some of the code is specific in referencing, but I'm lost on the other. Any clues? Does this method work for DirectX 10? [The latest SDK available from Microsoft.] Also, these codes are .NET C#/VB. Is there way to port some of this to C++, for native code? IMPO, C++ compiles/runs faster than the .NET languages. So how do you reference the .cs file in Visual Basic? the c# code doesn't work under VB if your using VB express edition. Sucks Im using C# on Windows Vista Home Premium, and i cant find the DirectX folder on my computer in order to get the dxmutmisc.cs file. Is it something to do with DirectX 10? Ok i had the same problem about dxmutmisc.cs but i fixed it (i think i havent finished the tutruiol) just rename the dxmutmisc.cs to dxmutmisc.vb it will give u the are u sure u wanna do this box click ok Thanks. This is what I'm looking for Hi I am new to visual c# I am having issues with the render loop and I am not sure if I made a mistake it keeps saying Error 1 The type or namespace name 'paintEventArgs' could not be found (are you missing a using directive or an assembly reference?) if you could get back to my and help it would be great thanks. I'm also finding this hard to follow using VB. It would be nice to be able to see some scren shots of how the classes should look. i have 3 errors when i put the timer code in to the visual basic game engine file. name delta time is not declared samples is not a member of microsoft twice So far this tutorial is great! Thank you for taking the time to be clear about why you are doing the things you are doing. I hope to use this as a learning tool to improve my programming skills. The renaming and adding folders type of ideas are certainly important to me and I hope you keep providing them throughout your remaining publications. The only thing that sucks is it takes too darn long to install DirectX. I'm ready to move on to the next tutorial but the SDK is still installing. :) i need help im a bit of a noob lol when i put the code that says protected override void in the void is underlined and their is a error saying expected class, delegate etc. i dont know how to fix this i have tried loads of things please help thanks "For this series, I am going to use both Visual C# Express and Visual Basic Express. If you have not already done so, download the C# or Visual Basic Visual Studio Express" So I download Visual Basic 2005 Express, Visual C# 2005 Express and Direct X SDK I start confuse when... "Now we are ready to write some code. The first step is to create a new solution in Visual Studio 2005..." I'm stuck at the Using statement. I understand that, in VB it translates to an Imports statement. However, I get an error message: Warning 1 Namespace or type specified in the Imports 'Microsoft.Samples.DirectX.UtilityToolkit' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Assuming the problem is that the Namespace can not be found, how do I add it? does the direct 3dx examples require a newer graphics card or can i use the 3d examples with my ibm thinkpad 600x or 600e video card ( made in 1998 or 1999 i think) i do have the direct x feb 2005 or close sdk but when i run the 3dk examples included in the sdk it says it needs a direct 3dk handle at runtime? Any help as how to use the d3dk examples in vb.net without a newer graphics card? HEY MAN IM HAVING A HARD TIME WITH THIS IM STUCK ON THE FIRST STEP IM USING .CS protected override void OnPaint(PaintEventArgs e){ Using the link here: I added the three references to my project. However, I still get the following error when attempting to build: Error 1 The type or namespace name 'Framework' could not be found (are you missing a using directive or an assembly reference?) C:\_devel\BattleTank2005\BattleTank2005\DirectXSupport\dxmutmisc.cs 2189 61 BattleTank2005 I am using VS2005 (with latest Feb 07 DirectX sdk) PingBack from PingBack from If you all read he explains that the program will no longer compile... The next article explains how to get things referenced. As pointed out in one of the above posts. Instead of using microsoft paint, use a free photoshop-like program called Paint.Net waaaayyy more fetures.. get it at getpaint.net PingBack from PingBack from Ok guys, for all you VB people out there having trouble, this may help. If you find that you don't have the Microsoft.Samples namespace, dont be alarmed. Here is a very steps that you can do to get it. Step One: Download this and extract it anywhere Step Two: Create a .dll project Step Three: Add all the files in the VBSamples2005/Common2005 folder (except the icon) Step Four: Have your .dll Project add the folowing references-- 1. Microsoft.DirectX 2. Microsoft.DirectX.Direct3D 3. Microsoft.DirectX.Direct3DX 4. System 5. System.Drawing 6. System.Windows.Forms Step Five: Solve all the other trivial errors. Visual Studio should provide the corrections for these errors. Step Six: Don't worry about the warnings Step Seven: Build the .dll project Step Eight: Add a reference to the .dll you created in your BattleTanks2005 project (the one being made here). The reference will probably be C:\Documents And Settings\(Current User)\My Documents\Visual Studio 2005 (or 2008)\Projects\(.dll project name)\(.dll project name again)\bin\Release\(.dll name).dll Note: Use the "Browse" tab in the Add Reference Window to add it Step Nine: Voila, you should now have the Microsoft.Samples namespace, albeit with only 1 sub-namespace, depending PingBack from PingBack from Hi there great instructions but im a bit lost got to here (At the top of the class in the using directives region add the following line of code: Microsoft.Samples.DirectX.UtilityToolkit;Visual Basic Microsoft.Samples.DirectX.UtilityToolkit) but i think where ive put my code is wrong i have 9 errors when debuged. i think the codes in the wrong place. any help would be Appreciated. wat?! I cant find the directX stuff. its not there bbut it says its installed how would i the thing from direct X folder if its not the same Direct X hey, im using the new directx sdk, and as far as i can tell, there is no dxmutmisc.cs file anywhere. is there anythin i can do? o.k. to fix the sdk issue i downloaded this file and extracted to the sdk directory. Then added the correct dxmutmisc.vb file to the directxsupport dir. this caused allot of errors. to correct this i created a new item in the directxSupport dir and copied the native method region and the timer region from the dxmutmisc to my new .vb. then remove the dxmutmisc.vb item this solved all errors and i was able to run. When I tried to compile, I got heaps of errors, saying it couldn't find bits of DirectX Ok, we obviously have a VB combatibility error here. I think that's proven when you download the SDK and it says it's only combatible with C, C++, and C#. Some people have mentioned that this is a source for VB versions of DirectX, and that it has worked well for them: The only problem is that getting those files installed properly is very tricky, and if anyone could elaborate (with lots of detail) how they installed those files, it would help the VB users of this tutorial. I really wish people would actually read the article. As Wayne said, the author very clearly states the result will NOT build and he'll sort that out next article. Now we have a thread packed out with comments saying it won't build (when he already warned that). If you cannot even read the article properly now AT THE START then you shouldn't even bother with the rest as it gets more involved than this and you'll just ruin the comment thread for the rest of us. Are you able to make text based games using this software? can i use a normal timer insted of that timer ? do i need the FPS rate timer at all ? whats the point and don't download latest directX, there is no needed samples there. The latest version, which include these, is SDK August 2007 I FIXED THE "POOL IS NOT DEFINED" AND ALL THAT FREAKING ERRORS IN VB!! Im using VB.net 2005, and I downloaded the DirectX SDK like here says.... Then I used the dxmutmisc.vb from The Z Buffer Web, and when I got all those errors, I: right click on BattleTank2005 in the solution explorer, add references.... and Added all Microsoft.DirectX References, (if you have more than 1 Direct3DX, just select the newest version). That solved the problem for me :D DIRECTX 9.0B SOFTWARE DEVELOPMENT KIT (SDK) FOR VISUAL BASIC .NET!!!!!!!!!!!! That took me about 5 seconds to find not even looking for it, I did a search for "Visual Basic DirectX" and that was the first result. i suck at this i got lost after: "Next right-click Form1 in the Solution Explorer and select Rename. Change Form1.cs to GameEngine.cs" thats how much i suck Make sure you download the correct version of the SDK (The article states you need the latest SDK, but to avoid issues download from the link below). Since this article was written Microsoft had removed the managed directx samples/documentation from its installation. You will no longer find the recommended dxmutmisc.cs file in it's latest installs. PingBack from To Shadow99117: Your problem is that you are trying to jump in over your head. This tutorial is intended to teach DirectX programming, but it assumes you already know the C# language and the Visual C# IDE very well. You need to find a tutorial on those things, and then come back to this. And you need to realize that learning a language well takes a few months, not a few hours. You know what, forget my last comment. Or at least the part about coming back to this after you've learned C# and the IDE. I wrote that just based on the questions, before I read the article carefully. When I did read it, I couldn't believe it. I read ahead, and looked at the whole series. What a mess. Simply put, I wouldn't tell my worst enemy to learn coding from this series. Part of the problem is that it's over two years old, and many of the resources have changed, but it's a mess even without that. He purports to give you a step by step guide on setting up the environment, but leaves out adding the needed references, which explains the 500 posts saying it won't compile. He tells you about the references in the second installment. Well, OK, maybe that was just a glitch in the first chapter. But no, almost every installment begins with how to make the last installment actually work. I guess even the author got sick of it, because the thing just stops dead after chapter 8. He says more is coming, but that was two years ago. I think more isn't coming. And I think that's fine. Why Microsoft even leaves this thing up is beyond me. Find one that uses the latest versions, and then skim through the chapters, and make sure it doesn't spend half the time correcting what it did wrong, and REALLY make sure it doesn't stop in the middle. Check out the comments, and if people who seem to know their way around the IDE say the code won't compile, keep looking for a tutorial that works. This tutorial is some of the worst i have ever seen. If you are still willing to learn how to write a game in VB try thsi great tutorial of Alan Phipps: @Burak Dobur: This was written multiple years ago before XNA was around. Creator's Club and other sites around the internet have XNA solutions. Thanks however for the XNA link! This is an excellent tutorial, and I am grateful, but it is relatively useless to me (and some others, I am sure). I currently use visual c# 2008, as well as DirectX 10 (November 2007). As such, some of the files and steps that would otherwise be essential are impossible to do. I was curious if anyone knew either if a tutorial for DirectX 10/Visual C# 2008 is in the works, or where I might find one, but covering the same subject matter (the basic process of creating a simple video game)? PingBack from I'm getting this error still: Error 1 The type or namespace name 'ShaderFlags' could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\mmaranao.CGYBMIR\My Documents\Visual Studio 2008\Projects\BattleTank1\BattleTank1\DirectXSupport\dxmutmisc.cs 524 16 BattleTank1 I made references to microsoft.directx and microsoft.directx.direct3d already and have also copied all the files for directxsupport. help? If you want to take a slow step into game programming, try This is my first time to really delve into game programming. Although in the past years I tried to focus on learning the basic programming in C++ so that in situation like this writing games as a hobby where I could use this knowledge would work at all. Probably I guess those times I just could not get the right link to keep myself up front but now with this C# language that I have started learning in weeks and the right programming environment using Visual Studio I am back to my interest. This tutorial fit exactly to people like and find it very useful the code are thorouhly explained. I would like to further improve myself professionally in game programming you as an online teacher in your on web site. Do you have? @Alex: You may want to try out XNA for further game programming. I just got back into programming again and I can't wait to try this out when I get home from work. I learned VB back when its was 4.0 and I was 14 and taught myself most of the basics for it to run chatroom programs on AOL 4.0-6.0. My friend and some of his friends have started programming a game of their own so hopefully I can get into helping them after I learn a bit more about Visual C#. Thanks for the great Tutorial!! I've been studying C# for 8 weeks, and I've taken coding classes before. Writing any tutorial like this is a tall task to ask for free.... and I have newer revisions of software, with that said, there are tons of comiple errors not explained here. I've worked through a bunch of them, but overall I feel like I've just wasted 2 hours and am left searching for another tutorial. Hey guys, part of the problem is this is an old tutorial where the updated APIs break the build. If someone would like to help update it, contact us and we'll update it. PingBack from I tried downloading multiple versions of DirectX 9.0 and 10.0 and i still cant find dxmutmisc.cs (I am using C# by the way). In the febuary 2005 version there are no .cs files at all! please help i would love to help update it but i dont know enough and you wont find alot of skilled help here (title says "beginning game developement" so most of use dont know what to do XD. It would be great if you could update this though. @jimi, this article is pretty old and I'm not sure if Managed DirectX is supported anymore. I'd suggest switching to XNA. I followed these tutorial by adapting a windows form program that I wrote myself in notepad and compiled it with the C# compiler in the .net SDK (I think it version 1.1) It all seems to work fine for me, although I haven't yet tried this with the IDE. For those people who are having problems with compiling the program after following all the instructions in the tutorial to the letter, I would be happy to refer you to the paragraph above the summary in which it states: "You will notice that the solution now will no longer build. This is because the classes in the file we added require DirectX to be referenced. We are going to cover which parts of DirectX we need in the next article." everyone make sure you download the sdk but for this tutorial you must not download any version later than august 2007. Any version later than that does not contain the managed components so you will not find them. Follow this link and not the one he gave you at the top of this page This is Part 2 of an introductory series on game programming using the Microsoft .NET Framework and managed This is Part 5 of an introductory series on game programming using the Microsoft .NET Framework and managed This is Part 3 of an introductory series on game programming using the Microsoft .NET Framework and managed PingBack from PingBack from PingBack from PingBack from PingBack from Hi Rob, Hope this may be useful to [] PingBack from Well I'm not an Intermediate I'm a beginner, so it turned a little difficult after some reading... :( (I couldn't find C:\Microsoft DirectX SDK\Samples\Common\ in my SDK direcory there are in ...\Samples\: -SampleBrowser -C++ -Media) Sorry I can't continue... @Ed, If you want to do managed code game development, I suggest using XNA instead. they have tons of examples too and you can put it on your 360 as well as your PC. I am trying to make a radar display for a research project with directx9 are there anyone help me? I think i have found the best tutorial for developing games in .net, very nicely explained by covering all the details. Hi, im just getting started with c# and all this directX stuff. Your tutorial seams to be what I need. But I have a 64 Bit Vista system and thought about using MS Visual Express 2008 which is free. On my journey through the internet I found some posts about c# and 64 bit issues. Whats about that? Does c# have problems with directX in Express 2008 on vista? I found a solution for x64 systems and Visual Express 2008 in the msdn help at :. You have to set up your project for x86 CPU (the default value "Any CPU" causes an error : "ist keine zulässige Win32-Anwendung. (Ausnahme von HRESULT: 0x800700C1)". In Visual Express 2008 this is a "hidden feature" which first have to be activated. @hhamm DirectX in managed languages is no longer supported. It is actually EOL'ed. To do this now we recommend XNA. XNA however does not support native x64 builds but since any 64bit version of Windows also supports 32bit versions of the application running, this isn’t an issue. I'm currently running x64 on Win7 and doing XNA development just fine. You can download DirectX versions when downloading DarkGDK in Express editions downloads. It will give you the link. I made it yesterday. This tutorial is not for Visual basic, isn't it? It does have VB examples however managed DirectX is no longer supported. I would check out for doing games with .Net
http://blogs.msdn.com/coding4fun/archive/2006/11/02/938703.aspx
crawl-002
refinedweb
8,633
71.95
0 I've been snooping around trying to figure whether or not this was completely safe. I've noticed that if you were to simply "delete this" you might have occurrences where the deleted pointer is still in use elsewhere in the program. To prevent this, you'd need to dereference it and perform a check to ensure that the pointer is valid. Now, the question: is using const_cast on the this pointer safe? I've whipped up a quick example below: #include "stdafx.h" class myclass { private: int *integer; public: myclass(int a, int b) { integer = new int[1]; *integer = a - b; if(!lessthannaught(*integer)) { delete this; const_cast<myclass *>(this) = 0; } } ~myclass() { delete integer; printf("Deconstructor\n"); } bool lessthannaught(int i) { return i < 0; } }; int main() { myclass *_class; _class = new myclass(3, 1); if(!_class) printf("Memory freed from within constructor\n"); else { printf("Freeing\n"); delete _class; } printf("----------\n"); _class = new myclass(2, 3); if(!_class) printf("Memory freed from within constructor\n"); else { printf("Freeing\n"); delete _class; } while(1); return 0; } I've tested it and it appears to work, but is such a method recommended (or better yet, are there alternate methods around it)? Thanks! Edited by Michael_Tanner: n/a
https://www.daniweb.com/programming/software-development/threads/353169/delete-this
CC-MAIN-2017-34
refinedweb
205
62.07
On Tue, Jun 2, 2015 at 10:20 AM, Arnd Bergmann <arnd@arndb.de> wrote:>> > --- a/arch/mn10300/include/asm/io.h>> > +++ b/arch/mn10300/include/asm/io.h>> > @@ -283,6 +283,7 @@ static inline void __iomem *ioremap_nocache(unsigned long offset, unsigned long>> >>> > #define ioremap_wc ioremap_nocache>> > #define ioremap_wt ioremap_nocache>> > +#define ioremap_cache ioremap_nocache>>>> From the comment in ioremap_nocache(), ioremap() may be cacheable in>> this arch.>> Right, and I guess that would be a bug. ;-)>> mn10300 decides caching on the address, so presumably all arguments passed intoAha, like MIPS...> ioremap here already have that bit set. I've checked all the resource> definitions for mn10300, and they are all between 0xA0000000 and 0xBFFFFFFF,> which is non-cacheable.But ioremap() clears that bit again:static inline void __iomem *ioremap(unsigned long offset, unsigned long size){ return (void __iomem *)(offset & ~0x20000000);
https://lkml.org/lkml/2015/6/2/139
CC-MAIN-2019-51
refinedweb
137
73.88
Model Validation in ASP.NET Web API by Mike Wasson This article shows how to annotate your models, use the annotations for data validation, and handle validation errors in your web API. When a client sends data to your web API, often you want to validate the data before doing any processing. Data Annotations In ASP.NET Web API, you can use attributes from the System.ComponentModel.DataAnnotations namespace to set validation rules for properties on your model. Consider the following model: using System.ComponentModel.DataAnnotations; namespace MyApi.Models { public class Product { public int Id { get; set; } [Required] public string Name { get; set; } public decimal Price { get; set; } [Range(0, 999)] public double Weight { get; set; } } } If you have used model validation in ASP.NET MVC, this should look familiar. The Required attribute says that the Name property must not be null. The Range attribute says that Weight must be between zero and 999. Suppose that a client sends a POST request with the following JSON representation: { "Id":4, "Price":2.99, "Weight":5 } You can see that the client did not include the Name property, which is marked as required. When Web API converts the JSON into a Product instance, it validates the Product against the validation attributes. In your controller action, you can check whether the model is valid: using MyApi.Models; using System.Net; using System.Net.Http; using System.Web.Http; namespace MyApi.Controllers { public class ProductsController : ApiController { public HttpResponseMessage Post(Product product) { if (ModelState.IsValid) { // Do something with the product (not shown). return new HttpResponseMessage(HttpStatusCode.OK); } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } } } } Model validation does not guarantee that client data is safe. Additional validation might be needed in other layers of the application. (For example, the data layer might enforce foreign key constraints.) The tutorial Using Web API with Entity Framework explores some of these issues. "Under-Posting": Under-posting happens when the client leaves out some properties. For example, suppose the client sends the following: {"Id":4, "Name":"Gizmo"} Here, the client did not specify values for Price or Weight. The JSON formatter assigns a default value of zero to the missing properties. The model state is valid, because zero is a valid value for these properties. Whether this is a problem depends on your scenario. For example, in an update operation, you might want to distinguish between "zero" and "not set." To force clients to set a value, make the property nullable and set the Required attribute: [Required] public decimal? Price { get; set; } "Over-Posting": A client can also send more data than you expected. For example: {"Id":4, "Name":"Gizmo", "Color":"Blue"} Here, the JSON includes a property ("Color") that does not exist in the Product model. In this case, the JSON formatter simply ignores this value. (The XML formatter does the same.) Over-posting causes problems if your model has properties that you intended to be read-only. For example: public class UserProfile { public string Name { get; set; } public Uri Blog { get; set; } public bool IsAdmin { get; set; } // uh-oh! } You don't want users to update the IsAdmin property and elevate themselves to administrators! The safest strategy is to use a model class that exactly matches what the client is allowed to send: public class UserProfileDTO { public string Name { get; set; } public Uri Blog { get; set; } // Leave out "IsAdmin" } Note Brad Wilson's blog post "Input Validation vs. Model Validation in ASP.NET MVC" has a good discussion of under-posting and over-posting. Although the post is about ASP.NET MVC 2, the issues are still relevant to Web API. Handling Validation Errors Web API does not automatically return an error to the client when validation fails. It is up to the controller action to check the model state and respond appropriately. You can also create an action filter to check the model state before the controller action is invoked. The following code shows an example:); } } } } If model validation fails, this filter returns an HTTP response that contains the validation errors. In that case, the controller action is not invoked. HTTP/1.1 400 Bad Request Content-Type: application/json; charset=utf-8 Date: Tue, 16 Jul 2013 21:02:29 GMT Content-Length: 331 { "Message": "The request is invalid.", "ModelState": { "product": [ "Required property 'Name' not found in JSON. Path '', line 1, position 17." ], "product.Name": [ "The Name field is required." ], "product.Weight": [ "The field Weight must be between 0 and 999." ] } } To apply this filter to all Web API controllers, add an instance of the filter to the HttpConfiguration.Filters collection during configuration: public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new ValidateModelAttribute()); // ... } } Another option is to set the filter as an attribute on individual controllers or controller actions: public class ProductsController : ApiController { [ValidateModel] public HttpResponseMessage Post(Product product) { // ... } }
https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
CC-MAIN-2020-10
refinedweb
808
50.33